source: src/Concurrency/Keywords.cc@ 6840e7c

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 6840e7c was 549c006, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Implemented out of order waitfor for destructors

  • Property mode set to 100644
File size: 19.8 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Keywords.cc --
8//
9// Author : Thierry Delisle
10// Created On : Mon Mar 13 12:41:22 2017
11// Last Modified By :
12// Last Modified On :
13// Update Count : 5
14//
15
16#include "Concurrency/Keywords.h"
17
18#include <cassert> // for assert
19#include <string> // for string, operator==
20
21#include "Common/PassVisitor.h" // for PassVisitor
22#include "Common/SemanticError.h" // for SemanticError
23#include "Common/utility.h" // for deleteAll, map_range
24#include "CodeGen/OperatorTable.h" // for isConstructor
25#include "InitTweak/InitTweak.h" // for getPointerBase
26#include "Parser/LinkageSpec.h" // for Cforall
27#include "SymTab/AddVisit.h" // for acceptAndAdd
28#include "SynTree/Constant.h" // for Constant
29#include "SynTree/Declaration.h" // for StructDecl, FunctionDecl, ObjectDecl
30#include "SynTree/Expression.h" // for VariableExpr, ConstantExpr, Untype...
31#include "SynTree/Initializer.h" // for SingleInit, ListInit, Initializer ...
32#include "SynTree/Label.h" // for Label
33#include "SynTree/Statement.h" // for CompoundStmt, DeclStmt, ExprStmt
34#include "SynTree/Type.h" // for StructInstType, Type, PointerType
35#include "SynTree/Visitor.h" // for Visitor, acceptAll
36
37class Attribute;
38
39namespace Concurrency {
40
41 namespace {
42 const std::list<Label> noLabels;
43 const std::list< Attribute * > noAttributes;
44 Type::StorageClasses noStorage;
45 Type::Qualifiers noQualifiers;
46 }
47
48 //=============================================================================================
49 // Pass declarations
50 //=============================================================================================
51
52 //-----------------------------------------------------------------------------
53 //Handles sue type declarations :
54 // sue MyType { struct MyType {
55 // int data; int data;
56 // a_struct_t more_data; a_struct_t more_data;
57 // => NewField_t newField;
58 // }; };
59 // static inline NewField_t * getter_name( MyType * this ) { return &this->newField; }
60 //
61 class ConcurrentSueKeyword : public WithDeclsToAdd {
62 public:
63
64 ConcurrentSueKeyword( std::string&& type_name, std::string&& field_name, std::string&& getter_name, std::string&& context_error, bool needs_main ) :
65 type_name( type_name ), field_name( field_name ), getter_name( getter_name ), context_error( context_error ), needs_main( needs_main ) {}
66
67 virtual ~ConcurrentSueKeyword() {}
68
69 void postvisit( StructDecl * decl );
70
71 void handle( StructDecl * );
72 FunctionDecl * forwardDeclare( StructDecl * );
73 ObjectDecl * addField( StructDecl * );
74 void addRoutines( ObjectDecl *, FunctionDecl * );
75
76 virtual bool is_target( StructDecl * decl ) = 0;
77
78 private:
79 const std::string type_name;
80 const std::string field_name;
81 const std::string getter_name;
82 const std::string context_error;
83 bool needs_main;
84
85 StructDecl* type_decl = nullptr;
86 };
87
88
89 //-----------------------------------------------------------------------------
90 //Handles thread type declarations :
91 // thread Mythread { struct MyThread {
92 // int data; int data;
93 // a_struct_t more_data; a_struct_t more_data;
94 // => thread_desc __thrd_d;
95 // }; };
96 // static inline thread_desc * get_thread( MyThread * this ) { return &this->__thrd_d; }
97 //
98 class ThreadKeyword final : public ConcurrentSueKeyword {
99 public:
100
101 ThreadKeyword() : ConcurrentSueKeyword(
102 "thread_desc",
103 "__thrd",
104 "get_thread",
105 "thread keyword requires threads to be in scope, add #include <thread>",
106 true
107 )
108 {}
109
110 virtual ~ThreadKeyword() {}
111
112 virtual bool is_target( StructDecl * decl ) override final { return decl->is_thread(); }
113
114 static void implement( std::list< Declaration * > & translationUnit ) {
115 PassVisitor< ThreadKeyword > impl;
116 acceptAll( translationUnit, impl );
117 }
118 };
119
120 //-----------------------------------------------------------------------------
121 //Handles coroutine type declarations :
122 // coroutine MyCoroutine { struct MyCoroutine {
123 // int data; int data;
124 // a_struct_t more_data; a_struct_t more_data;
125 // => coroutine_desc __cor_d;
126 // }; };
127 // static inline coroutine_desc * get_coroutine( MyCoroutine * this ) { return &this->__cor_d; }
128 //
129 class CoroutineKeyword final : public ConcurrentSueKeyword {
130 public:
131
132 CoroutineKeyword() : ConcurrentSueKeyword(
133 "coroutine_desc",
134 "__cor",
135 "get_coroutine",
136 "coroutine keyword requires coroutines to be in scope, add #include <coroutine>",
137 true
138 )
139 {}
140
141 virtual ~CoroutineKeyword() {}
142
143 virtual bool is_target( StructDecl * decl ) override final { return decl->is_coroutine(); }
144
145 static void implement( std::list< Declaration * > & translationUnit ) {
146 PassVisitor< CoroutineKeyword > impl;
147 acceptAll( translationUnit, impl );
148 }
149 };
150
151 //-----------------------------------------------------------------------------
152 //Handles monitor type declarations :
153 // monitor MyMonitor { struct MyMonitor {
154 // int data; int data;
155 // a_struct_t more_data; a_struct_t more_data;
156 // => monitor_desc __mon_d;
157 // }; };
158 // static inline monitor_desc * get_coroutine( MyMonitor * this ) { return &this->__cor_d; }
159 //
160 class MonitorKeyword final : public ConcurrentSueKeyword {
161 public:
162
163 MonitorKeyword() : ConcurrentSueKeyword(
164 "monitor_desc",
165 "__mon",
166 "get_monitor",
167 "monitor keyword requires monitors to be in scope, add #include <monitor>",
168 false
169 )
170 {}
171
172 virtual ~MonitorKeyword() {}
173
174 virtual bool is_target( StructDecl * decl ) override final { return decl->is_monitor(); }
175
176 static void implement( std::list< Declaration * > & translationUnit ) {
177 PassVisitor< MonitorKeyword > impl;
178 acceptAll( translationUnit, impl );
179 }
180 };
181
182 //-----------------------------------------------------------------------------
183 //Handles mutex routines definitions :
184 // void foo( A * mutex a, B * mutex b, int i ) { void foo( A * a, B * b, int i ) {
185 // monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
186 // monitor_guard_t __guard = { __monitors, 2 };
187 // /*Some code*/ => /*Some code*/
188 // } }
189 //
190 class MutexKeyword final {
191 public:
192
193 void postvisit( FunctionDecl * decl );
194 void postvisit( StructDecl * decl );
195
196 std::list<DeclarationWithType*> findMutexArgs( FunctionDecl* );
197 void validate( DeclarationWithType * );
198 void addDtorStatments( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
199 void addStatments( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
200
201 static void implement( std::list< Declaration * > & translationUnit ) {
202 PassVisitor< MutexKeyword > impl;
203 acceptAll( translationUnit, impl );
204 }
205
206 private:
207 StructDecl* monitor_decl = nullptr;
208 StructDecl* guard_decl = nullptr;
209 StructDecl* dtor_guard_decl = nullptr;
210
211 static std::unique_ptr< Type > generic_func;
212 };
213
214 std::unique_ptr< Type > MutexKeyword::generic_func = std::unique_ptr< Type >(
215 new FunctionType(
216 noQualifiers,
217 true
218 )
219 );
220
221 //-----------------------------------------------------------------------------
222 //Handles mutex routines definitions :
223 // void foo( A * mutex a, B * mutex b, int i ) { void foo( A * a, B * b, int i ) {
224 // monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
225 // monitor_guard_t __guard = { __monitors, 2 };
226 // /*Some code*/ => /*Some code*/
227 // } }
228 //
229 class ThreadStarter final {
230 public:
231
232 void postvisit( FunctionDecl * decl );
233 void previsit ( StructDecl * decl );
234
235 void addStartStatement( FunctionDecl * decl, DeclarationWithType * param );
236
237 static void implement( std::list< Declaration * > & translationUnit ) {
238 PassVisitor< ThreadStarter > impl;
239 acceptAll( translationUnit, impl );
240 }
241
242 private :
243 bool thread_ctor_seen = false;
244 StructDecl * thread_decl = nullptr;
245 };
246
247 //=============================================================================================
248 // General entry routine
249 //=============================================================================================
250 void applyKeywords( std::list< Declaration * > & translationUnit ) {
251 ThreadKeyword ::implement( translationUnit );
252 CoroutineKeyword ::implement( translationUnit );
253 MonitorKeyword ::implement( translationUnit );
254 }
255
256 void implementMutexFuncs( std::list< Declaration * > & translationUnit ) {
257 MutexKeyword ::implement( translationUnit );
258 }
259
260 void implementThreadStarter( std::list< Declaration * > & translationUnit ) {
261 ThreadStarter ::implement( translationUnit );
262 }
263
264 //=============================================================================================
265 // Generic keyword implementation
266 //=============================================================================================
267 void ConcurrentSueKeyword::postvisit(StructDecl * decl) {
268 if( decl->name == type_name && decl->body ) {
269 assert( !type_decl );
270 type_decl = decl;
271 }
272 else if ( is_target(decl) ) {
273 handle( decl );
274 }
275
276 }
277
278 void ConcurrentSueKeyword::handle( StructDecl * decl ) {
279 if( ! decl->body ) return;
280
281 if( !type_decl ) throw SemanticError( context_error, decl );
282
283 FunctionDecl * func = forwardDeclare( decl );
284 ObjectDecl * field = addField( decl );
285 addRoutines( field, func );
286 }
287
288 FunctionDecl * ConcurrentSueKeyword::forwardDeclare( StructDecl * decl ) {
289
290 StructDecl * forward = decl->clone();
291 forward->set_body( false );
292 deleteAll( forward->get_members() );
293 forward->get_members().clear();
294
295 FunctionType * get_type = new FunctionType( noQualifiers, false );
296 ObjectDecl * this_decl = new ObjectDecl(
297 "this",
298 noStorage,
299 LinkageSpec::Cforall,
300 nullptr,
301 new ReferenceType(
302 noQualifiers,
303 new StructInstType(
304 noQualifiers,
305 decl
306 )
307 ),
308 nullptr
309 );
310
311 get_type->get_parameters().push_back( this_decl );
312 get_type->get_returnVals().push_back(
313 new ObjectDecl(
314 "ret",
315 noStorage,
316 LinkageSpec::Cforall,
317 nullptr,
318 new PointerType(
319 noQualifiers,
320 new StructInstType(
321 noQualifiers,
322 type_decl
323 )
324 ),
325 nullptr
326 )
327 );
328
329 FunctionDecl * get_decl = new FunctionDecl(
330 getter_name,
331 Type::Static,
332 LinkageSpec::Cforall,
333 get_type,
334 nullptr,
335 noAttributes,
336 Type::Inline
337 );
338
339 FunctionDecl * main_decl = nullptr;
340
341 if( needs_main ) {
342 FunctionType * main_type = new FunctionType( noQualifiers, false );
343
344 main_type->get_parameters().push_back( this_decl->clone() );
345
346 main_decl = new FunctionDecl(
347 "main",
348 noStorage,
349 LinkageSpec::Cforall,
350 main_type,
351 nullptr
352 );
353 }
354
355 declsToAddBefore.push_back( forward );
356 if( needs_main ) declsToAddBefore.push_back( main_decl );
357 declsToAddBefore.push_back( get_decl );
358
359 return get_decl;
360 }
361
362 ObjectDecl * ConcurrentSueKeyword::addField( StructDecl * decl ) {
363 ObjectDecl * field = new ObjectDecl(
364 field_name,
365 noStorage,
366 LinkageSpec::Cforall,
367 nullptr,
368 new StructInstType(
369 noQualifiers,
370 type_decl
371 ),
372 nullptr
373 );
374
375 decl->get_members().push_back( field );
376
377 return field;
378 }
379
380 void ConcurrentSueKeyword::addRoutines( ObjectDecl * field, FunctionDecl * func ) {
381 CompoundStmt * statement = new CompoundStmt( noLabels );
382 statement->push_back(
383 new ReturnStmt(
384 noLabels,
385 new AddressExpr(
386 new MemberExpr(
387 field,
388 UntypedExpr::createDeref( new VariableExpr( func->get_functionType()->get_parameters().front() ) )
389 )
390 )
391 )
392 );
393
394 FunctionDecl * get_decl = func->clone();
395
396 get_decl->set_statements( statement );
397
398 declsToAddAfter.push_back( get_decl );
399
400 // get_decl->fixUniqueId();
401 }
402
403 //=============================================================================================
404 // Mutex keyword implementation
405 //=============================================================================================
406
407 void MutexKeyword::postvisit(FunctionDecl* decl) {
408
409 std::list<DeclarationWithType*> mutexArgs = findMutexArgs( decl );
410 if( mutexArgs.empty() ) return;
411
412 if( CodeGen::isConstructor(decl->name) ) throw SemanticError( "constructors cannot have mutex parameters", decl );
413
414 bool isDtor = CodeGen::isDestructor( decl->name );
415
416 if( isDtor && mutexArgs.size() != 1 ) throw SemanticError( "destructors can only have 1 mutex argument", decl );
417
418 for(auto arg : mutexArgs) {
419 validate( arg );
420 }
421
422 CompoundStmt* body = decl->get_statements();
423 if( ! body ) return;
424
425 if( !monitor_decl ) throw SemanticError( "mutex keyword requires monitors to be in scope, add #include <monitor>", decl );
426 if( !guard_decl ) throw SemanticError( "mutex keyword requires monitors to be in scope, add #include <monitor>", decl );
427 if( !dtor_guard_decl ) throw SemanticError( "mutex keyword requires monitors to be in scope, add #include <monitor>", decl );
428
429 if( isDtor ) {
430 addDtorStatments( decl, body, mutexArgs );
431 }
432 else {
433 addStatments( decl, body, mutexArgs );
434 }
435 }
436
437 void MutexKeyword::postvisit(StructDecl* decl) {
438
439 if( decl->name == "monitor_desc" ) {
440 assert( !monitor_decl );
441 monitor_decl = decl;
442 }
443 else if( decl->name == "monitor_guard_t" ) {
444 assert( !guard_decl );
445 guard_decl = decl;
446 }
447 else if( decl->name == "monitor_dtor_guard_t" ) {
448 assert( !dtor_guard_decl );
449 dtor_guard_decl = decl;
450 }
451 }
452
453 std::list<DeclarationWithType*> MutexKeyword::findMutexArgs( FunctionDecl* decl ) {
454 std::list<DeclarationWithType*> mutexArgs;
455
456 for( auto arg : decl->get_functionType()->get_parameters()) {
457 //Find mutex arguments
458 Type* ty = arg->get_type();
459 if( ! ty->get_mutex() ) continue;
460
461 //Append it to the list
462 mutexArgs.push_back( arg );
463 }
464
465 return mutexArgs;
466 }
467
468 void MutexKeyword::validate( DeclarationWithType * arg ) {
469 Type* ty = arg->get_type();
470
471 //Makes sure it's not a copy
472 ReferenceType* rty = dynamic_cast< ReferenceType * >( ty );
473 if( ! rty ) throw SemanticError( "Mutex argument must be of reference type ", arg );
474
475 //Make sure the we are pointing directly to a type
476 Type* base = rty->get_base();
477 if( dynamic_cast< ReferenceType * >( base ) ) throw SemanticError( "Mutex argument have exactly one level of indirection ", arg );
478 if( dynamic_cast< PointerType * >( base ) ) throw SemanticError( "Mutex argument have exactly one level of indirection ", arg );
479
480 //Make sure that typed isn't mutex
481 if( base->get_mutex() ) throw SemanticError( "mutex keyword may only appear once per argument ", arg );
482 }
483
484 void MutexKeyword::addDtorStatments( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
485 Type * arg_type = args.front()->get_type()->clone();
486 arg_type->set_mutex( false );
487
488 ObjectDecl * monitors = new ObjectDecl(
489 "__monitor",
490 noStorage,
491 LinkageSpec::Cforall,
492 nullptr,
493 new PointerType(
494 noQualifiers,
495 new StructInstType(
496 noQualifiers,
497 monitor_decl
498 )
499 ),
500 new SingleInit( new UntypedExpr(
501 new NameExpr( "get_monitor" ),
502 { new CastExpr( new VariableExpr( args.front() ), arg_type ) }
503 ))
504 );
505
506 assert(generic_func);
507
508 //in reverse order :
509 // monitor_guard_t __guard = { __monitors, #, func };
510 body->push_front(
511 new DeclStmt( noLabels, new ObjectDecl(
512 "__guard",
513 noStorage,
514 LinkageSpec::Cforall,
515 nullptr,
516 new StructInstType(
517 noQualifiers,
518 dtor_guard_decl
519 ),
520 new ListInit(
521 {
522 new SingleInit( new AddressExpr( new VariableExpr( monitors ) ) ),
523 new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone() ) )
524 },
525 noDesignators,
526 true
527 )
528 ))
529 );
530
531 //monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
532 body->push_front( new DeclStmt( noLabels, monitors) );
533 }
534
535 void MutexKeyword::addStatments( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
536 ObjectDecl * monitors = new ObjectDecl(
537 "__monitors",
538 noStorage,
539 LinkageSpec::Cforall,
540 nullptr,
541 new ArrayType(
542 noQualifiers,
543 new PointerType(
544 noQualifiers,
545 new StructInstType(
546 noQualifiers,
547 monitor_decl
548 )
549 ),
550 new ConstantExpr( Constant::from_ulong( args.size() ) ),
551 false,
552 false
553 ),
554 new ListInit(
555 map_range < std::list<Initializer*> > ( args, [this](DeclarationWithType * var ){
556 Type * type = var->get_type()->clone();
557 type->set_mutex( false );
558 return new SingleInit( new UntypedExpr(
559 new NameExpr( "get_monitor" ),
560 { new CastExpr( new VariableExpr( var ), type ) }
561 ) );
562 })
563 )
564 );
565
566 assert(generic_func);
567
568 //in reverse order :
569 // monitor_guard_t __guard = { __monitors, #, func };
570 body->push_front(
571 new DeclStmt( noLabels, new ObjectDecl(
572 "__guard",
573 noStorage,
574 LinkageSpec::Cforall,
575 nullptr,
576 new StructInstType(
577 noQualifiers,
578 guard_decl
579 ),
580 new ListInit(
581 {
582 new SingleInit( new VariableExpr( monitors ) ),
583 new SingleInit( new ConstantExpr( Constant::from_ulong( args.size() ) ) ),
584 new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone() ) )
585 },
586 noDesignators,
587 true
588 )
589 ))
590 );
591
592 //monitor_desc * __monitors[] = { get_monitor(a), get_monitor(b) };
593 body->push_front( new DeclStmt( noLabels, monitors) );
594 }
595
596 //=============================================================================================
597 // General entry routine
598 //=============================================================================================
599 void ThreadStarter::previsit( StructDecl * decl ) {
600 if( decl->name == "thread_desc" && decl->body ) {
601 assert( !thread_decl );
602 thread_decl = decl;
603 }
604 }
605
606 void ThreadStarter::postvisit(FunctionDecl * decl) {
607 if( ! CodeGen::isConstructor(decl->name) ) return;
608
609 Type * typeof_this = InitTweak::getTypeofThis(decl->type);
610 StructInstType * ctored_type = dynamic_cast< StructInstType * >( typeof_this );
611 if( ctored_type && ctored_type->baseStruct == thread_decl ) {
612 thread_ctor_seen = true;
613 }
614
615 DeclarationWithType * param = decl->get_functionType()->get_parameters().front();
616 auto type = dynamic_cast< StructInstType * >( InitTweak::getPointerBase( param->get_type() ) );
617 if( type && type->get_baseStruct()->is_thread() ) {
618 if( !thread_decl || !thread_ctor_seen ) {
619 throw SemanticError("thread keyword requires threads to be in scope, add #include <thread>");
620 }
621
622 addStartStatement( decl, param );
623 }
624 }
625
626 void ThreadStarter::addStartStatement( FunctionDecl * decl, DeclarationWithType * param ) {
627 CompoundStmt * stmt = decl->get_statements();
628
629 if( ! stmt ) return;
630
631 stmt->push_back(
632 new ExprStmt(
633 noLabels,
634 new UntypedExpr(
635 new NameExpr( "__thrd_start" ),
636 { new VariableExpr( param ) }
637 )
638 )
639 );
640 }
641};
642
643// Local Variables: //
644// mode: c //
645// tab-width: 4 //
646// End: //
Note: See TracBrowser for help on using the repository browser.