source: src/Concurrency/Keywords.cc @ 1cdfa82

new-envwith_gc
Last change on this file since 1cdfa82 was 1cdfa82, checked in by Aaron Moss <a3moss@…>, 6 years ago

Merge remote-tracking branch 'origin/master' into with_gc

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