source: src/Concurrency/Keywords.cc@ f229fc2

new-env with_gc
Last change on this file since f229fc2 was bd06384, checked in by Aaron Moss <a3moss@…>, 8 years ago

Add static roots to GC; fix some static GC_Objects

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