source: src/Concurrency/Keywords.cc @ 9cc3a18

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 9cc3a18 was ecfd758, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Major exception update, seperating type-ids from virtual tables. The major interface changes are done. There is a regression of ?Cancelled(T) to Some?Cancelled. There is some bits of code for the new verion of the ?Cancelled(T) interface already there. Not connected yet but I just reached the limit of what I wanted to do in one commit and then spent over a day cleaning up, so it will replace Some?Cancelled in a future commit.

  • Property mode set to 100644
File size: 35.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     : 10
14//
15
16#include "Concurrency/Keywords.h"
17
18#include <cassert>                        // for assert
19#include <string>                         // for string, operator==
20
21#include <iostream>
22
23#include "Common/Examine.h"               // for isMainFor
24#include "Common/PassVisitor.h"           // for PassVisitor
25#include "Common/SemanticError.h"         // for SemanticError
26#include "Common/utility.h"               // for deleteAll, map_range
27#include "CodeGen/OperatorTable.h"        // for isConstructor
28#include "ControlStruct/LabelGenerator.h" // for LebelGenerator
29#include "InitTweak/InitTweak.h"          // for getPointerBase
30#include "SynTree/LinkageSpec.h"          // for Cforall
31#include "SynTree/Constant.h"             // for Constant
32#include "SynTree/Declaration.h"          // for StructDecl, FunctionDecl, ObjectDecl
33#include "SynTree/Expression.h"           // for VariableExpr, ConstantExpr, Untype...
34#include "SynTree/Initializer.h"          // for SingleInit, ListInit, Initializer ...
35#include "SynTree/Label.h"                // for Label
36#include "SynTree/Statement.h"            // for CompoundStmt, DeclStmt, ExprStmt
37#include "SynTree/Type.h"                 // for StructInstType, Type, PointerType
38#include "SynTree/Visitor.h"              // for Visitor, acceptAll
39#include "Virtual/Tables.h"
40
41class Attribute;
42
43namespace Concurrency {
44        inline static std::string getTypeIdName( std::string const & exception_name ) {
45                return exception_name.empty() ? std::string() : Virtual::typeIdType( exception_name );
46        }
47        inline static std::string getVTableName( std::string const & exception_name ) {
48                return exception_name.empty() ? std::string() : Virtual::vtableTypeName( exception_name );
49        }
50
51        // Only detects threads constructed with the keyword thread.
52        inline static bool isThread( DeclarationWithType * decl ) {
53                Type * baseType = decl->get_type()->stripDeclarator();
54                StructInstType * instType = dynamic_cast<StructInstType *>( baseType );
55                if ( nullptr == instType ) { return false; }
56                return instType->baseStruct->is_thread();
57        }
58
59        //=============================================================================================
60        // Pass declarations
61        //=============================================================================================
62
63        //-----------------------------------------------------------------------------
64        //Handles sue type declarations :
65        // sue MyType {                             struct MyType {
66        //      int data;                                  int data;
67        //      a_struct_t more_data;                      a_struct_t more_data;
68        //                                =>             NewField_t newField;
69        // };                                        };
70        //                                           static inline NewField_t * getter_name( MyType * this ) { return &this->newField; }
71        //
72        class ConcurrentSueKeyword : public WithDeclsToAdd {
73          public:
74
75                ConcurrentSueKeyword( std::string&& type_name, std::string&& field_name,
76                        std::string&& getter_name, std::string&& context_error, std::string&& exception_name,
77                        bool needs_main, AggregateDecl::Aggregate cast_target ) :
78                  type_name( type_name ), field_name( field_name ), getter_name( getter_name ),
79                  context_error( context_error ), exception_name( exception_name ),
80                  typeid_name( getTypeIdName( exception_name ) ),
81                  vtable_name( getVTableName( exception_name ) ),
82                  needs_main( needs_main ), cast_target( cast_target ) {}
83
84                virtual ~ConcurrentSueKeyword() {}
85
86                Declaration * postmutate( StructDecl * decl );
87                DeclarationWithType * postmutate( FunctionDecl * decl );
88
89                void handle( StructDecl * );
90                void addTypeId( StructDecl * );
91                void addVtableForward( StructDecl * );
92                FunctionDecl * forwardDeclare( StructDecl * );
93                ObjectDecl * addField( StructDecl * );
94                void addRoutines( ObjectDecl *, FunctionDecl * );
95
96                virtual bool is_target( StructDecl * decl ) = 0;
97
98                Expression * postmutate( KeywordCastExpr * cast );
99
100          private:
101                const std::string type_name;
102                const std::string field_name;
103                const std::string getter_name;
104                const std::string context_error;
105                const std::string exception_name;
106                const std::string typeid_name;
107                const std::string vtable_name;
108                bool needs_main;
109                AggregateDecl::Aggregate cast_target;
110
111                StructDecl   * type_decl = nullptr;
112                FunctionDecl * dtor_decl = nullptr;
113                StructDecl * except_decl = nullptr;
114                StructDecl * typeid_decl = nullptr;
115                StructDecl * vtable_decl = nullptr;
116        };
117
118
119        //-----------------------------------------------------------------------------
120        //Handles thread type declarations :
121        // thread Mythread {                         struct MyThread {
122        //      int data;                                  int data;
123        //      a_struct_t more_data;                      a_struct_t more_data;
124        //                                =>             $thread __thrd_d;
125        // };                                        };
126        //                                           static inline $thread * get_thread( MyThread * this ) { return &this->__thrd_d; }
127        //
128        class ThreadKeyword final : public ConcurrentSueKeyword {
129          public:
130
131                ThreadKeyword() : ConcurrentSueKeyword(
132                        "$thread",
133                        "__thrd",
134                        "get_thread",
135                        "thread keyword requires threads to be in scope, add #include <thread.hfa>\n",
136                        "ThreadCancelled",
137                        true,
138                        AggregateDecl::Thread
139                )
140                {}
141
142                virtual ~ThreadKeyword() {}
143
144                virtual bool is_target( StructDecl * decl ) override final { return decl->is_thread(); }
145
146                static void implement( std::list< Declaration * > & translationUnit ) {
147                        PassVisitor< ThreadKeyword > impl;
148                        mutateAll( translationUnit, impl );
149                }
150        };
151
152        //-----------------------------------------------------------------------------
153        //Handles coroutine type declarations :
154        // coroutine MyCoroutine {                   struct MyCoroutine {
155        //      int data;                                  int data;
156        //      a_struct_t more_data;                      a_struct_t more_data;
157        //                                =>             $coroutine __cor_d;
158        // };                                        };
159        //                                           static inline $coroutine * get_coroutine( MyCoroutine * this ) { return &this->__cor_d; }
160        //
161        class CoroutineKeyword final : public ConcurrentSueKeyword {
162          public:
163
164                CoroutineKeyword() : ConcurrentSueKeyword(
165                        "$coroutine",
166                        "__cor",
167                        "get_coroutine",
168                        "coroutine keyword requires coroutines to be in scope, add #include <coroutine.hfa>\n",
169                        "CoroutineCancelled",
170                        true,
171                        AggregateDecl::Coroutine
172                )
173                {}
174
175                virtual ~CoroutineKeyword() {}
176
177                virtual bool is_target( StructDecl * decl ) override final { return decl->is_coroutine(); }
178
179                static void implement( std::list< Declaration * > & translationUnit ) {
180                        PassVisitor< CoroutineKeyword > impl;
181                        mutateAll( translationUnit, impl );
182                }
183        };
184
185
186
187        //-----------------------------------------------------------------------------
188        //Handles monitor type declarations :
189        // monitor MyMonitor {                       struct MyMonitor {
190        //      int data;                                  int data;
191        //      a_struct_t more_data;                      a_struct_t more_data;
192        //                                =>             $monitor __mon_d;
193        // };                                        };
194        //                                           static inline $monitor * get_coroutine( MyMonitor * this ) { return &this->__cor_d; }
195        //
196        class MonitorKeyword final : public ConcurrentSueKeyword {
197          public:
198
199                MonitorKeyword() : ConcurrentSueKeyword(
200                        "$monitor",
201                        "__mon",
202                        "get_monitor",
203                        "monitor keyword requires monitors to be in scope, add #include <monitor.hfa>\n",
204                        "",
205                        false,
206                        AggregateDecl::Monitor
207                )
208                {}
209
210                virtual ~MonitorKeyword() {}
211
212                virtual bool is_target( StructDecl * decl ) override final { return decl->is_monitor(); }
213
214                static void implement( std::list< Declaration * > & translationUnit ) {
215                        PassVisitor< MonitorKeyword > impl;
216                        mutateAll( translationUnit, impl );
217                }
218        };
219
220        //-----------------------------------------------------------------------------
221        //Handles generator type declarations :
222        // generator MyGenerator {                   struct MyGenerator {
223        //      int data;                                  int data;
224        //      a_struct_t more_data;                      a_struct_t more_data;
225        //                                =>             int __gen_next;
226        // };                                        };
227        //
228        class GeneratorKeyword final : public ConcurrentSueKeyword {
229          public:
230
231                GeneratorKeyword() : ConcurrentSueKeyword(
232                        "$generator",
233                        "__generator_state",
234                        "get_generator",
235                        "Unable to find builtin type $generator\n",
236                        "",
237                        true,
238                        AggregateDecl::Generator
239                )
240                {}
241
242                virtual ~GeneratorKeyword() {}
243
244                virtual bool is_target( StructDecl * decl ) override final { return decl->is_generator(); }
245
246                static void implement( std::list< Declaration * > & translationUnit ) {
247                        PassVisitor< GeneratorKeyword > impl;
248                        mutateAll( translationUnit, impl );
249                }
250        };
251
252
253        //-----------------------------------------------------------------------------
254        class SuspendKeyword final : public WithStmtsToAdd, public WithGuards {
255        public:
256                SuspendKeyword() = default;
257                virtual ~SuspendKeyword() = default;
258
259                void  premutate( FunctionDecl * );
260                DeclarationWithType * postmutate( FunctionDecl * );
261
262                Statement * postmutate( SuspendStmt * );
263
264                static void implement( std::list< Declaration * > & translationUnit ) {
265                        PassVisitor< SuspendKeyword > impl;
266                        mutateAll( translationUnit, impl );
267                }
268
269        private:
270                bool is_real_suspend( FunctionDecl * );
271
272                Statement * make_generator_suspend( SuspendStmt * );
273                Statement * make_coroutine_suspend( SuspendStmt * );
274
275                struct LabelPair {
276                        Label obj;
277                        int   idx;
278                };
279
280                LabelPair make_label() {
281                        labels.push_back( gen.newLabel("generator") );
282                        return { labels.back(), int(labels.size()) };
283                }
284
285                DeclarationWithType * in_generator = nullptr;
286                FunctionDecl * decl_suspend = nullptr;
287                std::vector<Label> labels;
288                ControlStruct::LabelGenerator & gen = *ControlStruct::LabelGenerator::getGenerator();
289        };
290
291        //-----------------------------------------------------------------------------
292        //Handles mutex routines definitions :
293        // void foo( A * mutex a, B * mutex b,  int i ) {                  void foo( A * a, B * b,  int i ) {
294        //                                                                       $monitor * __monitors[] = { get_monitor(a), get_monitor(b) };
295        //                                                                       monitor_guard_t __guard = { __monitors, 2 };
296        //    /*Some code*/                                       =>           /*Some code*/
297        // }                                                               }
298        //
299        class MutexKeyword final {
300          public:
301
302                void postvisit( FunctionDecl * decl );
303                void postvisit(   StructDecl * decl );
304
305                std::list<DeclarationWithType*> findMutexArgs( FunctionDecl*, bool & first );
306                void validate( DeclarationWithType * );
307                void addDtorStatements( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
308                void addStatements( FunctionDecl* func, CompoundStmt *, const std::list<DeclarationWithType * > &);
309                void addThreadDtorStatements( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args );
310
311                static void implement( std::list< Declaration * > & translationUnit ) {
312                        PassVisitor< MutexKeyword > impl;
313                        acceptAll( translationUnit, impl );
314                }
315
316          private:
317                StructDecl* monitor_decl = nullptr;
318                StructDecl* guard_decl = nullptr;
319                StructDecl* dtor_guard_decl = nullptr;
320                StructDecl* thread_guard_decl = nullptr;
321
322                static std::unique_ptr< Type > generic_func;
323        };
324
325        std::unique_ptr< Type > MutexKeyword::generic_func = std::unique_ptr< Type >(
326                new FunctionType(
327                        noQualifiers,
328                        true
329                )
330        );
331
332        //-----------------------------------------------------------------------------
333        //Handles mutex routines definitions :
334        // void foo( A * mutex a, B * mutex b,  int i ) {                  void foo( A * a, B * b,  int i ) {
335        //                                                                       $monitor * __monitors[] = { get_monitor(a), get_monitor(b) };
336        //                                                                       monitor_guard_t __guard = { __monitors, 2 };
337        //    /*Some code*/                                       =>           /*Some code*/
338        // }                                                               }
339        //
340        class ThreadStarter final {
341          public:
342
343                void postvisit( FunctionDecl * decl );
344                void previsit ( StructDecl   * decl );
345
346                void addStartStatement( FunctionDecl * decl, DeclarationWithType * param );
347
348                static void implement( std::list< Declaration * > & translationUnit ) {
349                        PassVisitor< ThreadStarter > impl;
350                        acceptAll( translationUnit, impl );
351                }
352
353          private :
354                bool thread_ctor_seen = false;
355                StructDecl * thread_decl = nullptr;
356        };
357
358        //=============================================================================================
359        // General entry routine
360        //=============================================================================================
361        void applyKeywords( std::list< Declaration * > & translationUnit ) {
362                ThreadKeyword   ::implement( translationUnit );
363                CoroutineKeyword        ::implement( translationUnit );
364                MonitorKeyword  ::implement( translationUnit );
365                GeneratorKeyword  ::implement( translationUnit );
366                SuspendKeyword    ::implement( translationUnit );
367        }
368
369        void implementMutexFuncs( std::list< Declaration * > & translationUnit ) {
370                MutexKeyword    ::implement( translationUnit );
371        }
372
373        void implementThreadStarter( std::list< Declaration * > & translationUnit ) {
374                ThreadStarter   ::implement( translationUnit );
375        }
376
377        //=============================================================================================
378        // Generic keyword implementation
379        //=============================================================================================
380        void fixupGenerics(FunctionType * func, StructDecl * decl) {
381                cloneAll(decl->parameters, func->forall);
382                for ( TypeDecl * td : func->forall ) {
383                        strict_dynamic_cast<StructInstType*>(
384                                func->parameters.front()->get_type()->stripReferences()
385                        )->parameters.push_back(
386                                new TypeExpr( new TypeInstType( noQualifiers, td->name, td ) )
387                        );
388                }
389        }
390
391        Declaration * ConcurrentSueKeyword::postmutate(StructDecl * decl) {
392                if( decl->name == type_name && decl->body ) {
393                        assert( !type_decl );
394                        type_decl = decl;
395                }
396                else if ( is_target(decl) ) {
397                        handle( decl );
398                }
399                else if ( !except_decl && exception_name == decl->name && decl->body ) {
400                        except_decl = decl;
401                }
402                else if ( !typeid_decl && typeid_name == decl->name && decl->body ) {
403                        typeid_decl = decl;
404                }
405                else if ( !vtable_decl && vtable_name == decl->name && decl->body ) {
406                        vtable_decl = decl;
407                }
408                // Might be able to get ride of is target.
409                assert( is_target(decl) == (cast_target == decl->kind) );
410                return decl;
411        }
412
413        DeclarationWithType * ConcurrentSueKeyword::postmutate( FunctionDecl * decl ) {
414                if ( type_decl && isDestructorFor( decl, type_decl ) )
415                        dtor_decl = decl;
416                else if ( vtable_name.empty() )
417                        ;
418                else if( !decl->has_body() )
419                        ;
420                else if ( auto param = isMainFor( decl, cast_target ) ) {
421                        // This should never trigger.
422                        assert( vtable_decl );
423                        // Should be safe because of isMainFor.
424                        StructInstType * struct_type = static_cast<StructInstType *>(
425                                static_cast<ReferenceType *>( param->get_type() )->base );
426                        assert( struct_type );
427
428                        std::list< Expression * > poly_args = { new TypeExpr( struct_type->clone() ) };
429                        ObjectDecl * vtable_object = Virtual::makeVtableInstance(
430                                vtable_decl->makeInst( poly_args ), struct_type, nullptr );
431                        declsToAddAfter.push_back( vtable_object );
432                        declsToAddAfter.push_back( Virtual::makeGetExceptionFunction(
433                                vtable_object, except_decl->makeInst( std::move( poly_args ) )
434                        ) );
435                }
436
437                return decl;
438        }
439
440        Expression * ConcurrentSueKeyword::postmutate( KeywordCastExpr * cast ) {
441                if ( cast_target == cast->target ) {
442                        // convert (thread &)t to ($thread &)*get_thread(t), etc.
443                        if( !type_decl ) SemanticError( cast, context_error );
444                        if( !dtor_decl ) SemanticError( cast, context_error );
445                        assert( cast->result == nullptr );
446                        cast->set_result( new ReferenceType( noQualifiers, new StructInstType( noQualifiers, type_decl ) ) );
447                        cast->concrete_target.field  = field_name;
448                        cast->concrete_target.getter = getter_name;
449                }
450                return cast;
451        }
452
453
454        void ConcurrentSueKeyword::handle( StructDecl * decl ) {
455                if( ! decl->body ) return;
456
457                if( !type_decl ) SemanticError( decl, context_error );
458                if( !dtor_decl ) SemanticError( decl, context_error );
459
460                if ( !exception_name.empty() ) {
461                        if( !typeid_decl ) SemanticError( decl, context_error );
462                        if( !vtable_decl ) SemanticError( decl, context_error );
463
464                        addTypeId( decl );
465                        addVtableForward( decl );
466                }
467                FunctionDecl * func = forwardDeclare( decl );
468                ObjectDecl * field = addField( decl );
469                addRoutines( field, func );
470        }
471
472        void ConcurrentSueKeyword::addTypeId( StructDecl * decl ) {
473                assert( typeid_decl );
474                StructInstType typeid_type( Type::Const, typeid_decl );
475                typeid_type.parameters.push_back( new TypeExpr(
476                        new StructInstType( noQualifiers, decl )
477                        ) );
478                declsToAddBefore.push_back( Virtual::makeTypeIdInstance( &typeid_type ) );
479        }
480
481        void ConcurrentSueKeyword::addVtableForward( StructDecl * decl ) {
482                assert( vtable_decl );
483                std::list< Expression * > poly_args = {
484                        new TypeExpr( new StructInstType( noQualifiers, decl ) ),
485                };
486                declsToAddBefore.push_back( Virtual::makeGetExceptionForward(
487                        vtable_decl->makeInst( poly_args ),
488                        except_decl->makeInst( poly_args )
489                ) );
490                declsToAddBefore.push_back( Virtual::makeVtableForward(
491                        vtable_decl->makeInst( move( poly_args ) ) ) );
492        }
493
494        FunctionDecl * ConcurrentSueKeyword::forwardDeclare( StructDecl * decl ) {
495
496                StructDecl * forward = decl->clone();
497                forward->set_body( false );
498                deleteAll( forward->get_members() );
499                forward->get_members().clear();
500
501                FunctionType * get_type = new FunctionType( noQualifiers, false );
502                ObjectDecl * this_decl = new ObjectDecl(
503                        "this",
504                        noStorageClasses,
505                        LinkageSpec::Cforall,
506                        nullptr,
507                        new ReferenceType(
508                                noQualifiers,
509                                new StructInstType(
510                                        noQualifiers,
511                                        decl
512                                )
513                        ),
514                        nullptr
515                );
516
517                get_type->get_parameters().push_back( this_decl->clone() );
518                get_type->get_returnVals().push_back(
519                        new ObjectDecl(
520                                "ret",
521                                noStorageClasses,
522                                LinkageSpec::Cforall,
523                                nullptr,
524                                new PointerType(
525                                        noQualifiers,
526                                        new StructInstType(
527                                                noQualifiers,
528                                                type_decl
529                                        )
530                                ),
531                                nullptr
532                        )
533                );
534                fixupGenerics(get_type, decl);
535
536                FunctionDecl * get_decl = new FunctionDecl(
537                        getter_name,
538                        Type::Static,
539                        LinkageSpec::Cforall,
540                        get_type,
541                        nullptr,
542                        { new Attribute("const") },
543                        Type::Inline
544                );
545
546                FunctionDecl * main_decl = nullptr;
547
548                if( needs_main ) {
549                        FunctionType * main_type = new FunctionType( noQualifiers, false );
550
551                        main_type->get_parameters().push_back( this_decl->clone() );
552
553                        main_decl = new FunctionDecl(
554                                "main",
555                                noStorageClasses,
556                                LinkageSpec::Cforall,
557                                main_type,
558                                nullptr
559                        );
560                        fixupGenerics(main_type, decl);
561                }
562
563                delete this_decl;
564
565                declsToAddBefore.push_back( forward );
566                if( needs_main ) declsToAddBefore.push_back( main_decl );
567                declsToAddBefore.push_back( get_decl );
568
569                return get_decl;
570        }
571
572        ObjectDecl * ConcurrentSueKeyword::addField( StructDecl * decl ) {
573                ObjectDecl * field = new ObjectDecl(
574                        field_name,
575                        noStorageClasses,
576                        LinkageSpec::Cforall,
577                        nullptr,
578                        new StructInstType(
579                                noQualifiers,
580                                type_decl
581                        ),
582                        nullptr
583                );
584
585                decl->get_members().push_back( field );
586
587                return field;
588        }
589
590        void ConcurrentSueKeyword::addRoutines( ObjectDecl * field, FunctionDecl * func ) {
591                CompoundStmt * statement = new CompoundStmt();
592                statement->push_back(
593                        new ReturnStmt(
594                                new AddressExpr(
595                                        new MemberExpr(
596                                                field,
597                                                new CastExpr(
598                                                        new VariableExpr( func->get_functionType()->get_parameters().front() ),
599                                                        func->get_functionType()->get_parameters().front()->get_type()->stripReferences()->clone(),
600                                                        false
601                                                )
602                                        )
603                                )
604                        )
605                );
606
607                FunctionDecl * get_decl = func->clone();
608
609                get_decl->set_statements( statement );
610
611                declsToAddAfter.push_back( get_decl );
612        }
613
614        //=============================================================================================
615        // Suspend keyword implementation
616        //=============================================================================================
617        bool SuspendKeyword::is_real_suspend( FunctionDecl * func ) {
618                if(isMangled(func->linkage)) return false; // the real suspend isn't mangled
619                if(func->name != "__cfactx_suspend") return false; // the real suspend has a specific name
620                if(func->type->parameters.size() != 0) return false; // Too many parameters
621                if(func->type->returnVals.size() != 0) return false; // Too many return values
622
623                return true;
624        }
625
626        void SuspendKeyword::premutate( FunctionDecl * func ) {
627                GuardValue(in_generator);
628                in_generator = nullptr;
629
630                // Is this the real suspend?
631                if(is_real_suspend(func)) {
632                        decl_suspend = decl_suspend ? decl_suspend : func;
633                        return;
634                }
635
636                // Is this the main of a generator?
637                auto param = isMainFor( func, AggregateDecl::Aggregate::Generator );
638                if(!param) return;
639
640                if(func->type->returnVals.size() != 0) SemanticError(func->location, "Generator main must return void");
641
642                in_generator = param;
643                GuardValue(labels);
644                labels.clear();
645        }
646
647        DeclarationWithType * SuspendKeyword::postmutate( FunctionDecl * func ) {
648                if( !func->statements ) return func; // Not the actual definition, don't do anything
649                if( !in_generator     ) return func; // Not in a generator, don't do anything
650                if( labels.empty()    ) return func; // Generator has no states, nothing to do, could throw a warning
651
652                // This is a generator main, we need to add the following code to the top
653                // static void * __generator_labels[] = {&&s0, &&s1, ...};
654                // goto * __generator_labels[gen.__generator_state];
655                const auto & loc = func->location;
656
657                const auto first_label = gen.newLabel("generator");
658
659                // for each label add to declaration
660                std::list<Initializer*> inits = { new SingleInit( new LabelAddressExpr( first_label ) ) };
661                for(const auto & label : labels) {
662                        inits.push_back(
663                                new SingleInit(
664                                        new LabelAddressExpr( label )
665                                )
666                        );
667                }
668                auto init = new ListInit(std::move(inits), noDesignators, true);
669                labels.clear();
670
671                // create decl
672                auto decl = new ObjectDecl(
673                        "__generator_labels",
674                        Type::StorageClasses( Type::Static ),
675                        LinkageSpec::AutoGen,
676                        nullptr,
677                        new ArrayType(
678                                Type::Qualifiers(),
679                                new PointerType(
680                                        Type::Qualifiers(),
681                                        new VoidType( Type::Qualifiers() )
682                                ),
683                                nullptr,
684                                false, false
685                        ),
686                        init
687                );
688
689                // create the goto
690                assert(in_generator);
691
692                auto go_decl = new ObjectDecl(
693                        "__generator_label",
694                        noStorageClasses,
695                        LinkageSpec::AutoGen,
696                        nullptr,
697                        new PointerType(
698                                Type::Qualifiers(),
699                                new VoidType( Type::Qualifiers() )
700                        ),
701                        new SingleInit(
702                                new UntypedExpr(
703                                        new NameExpr("?[?]"),
704                                        {
705                                                new NameExpr("__generator_labels"),
706                                                new UntypedMemberExpr(
707                                                        new NameExpr("__generator_state"),
708                                                        new VariableExpr( in_generator )
709                                                )
710                                        }
711                                )
712                        )
713                );
714                go_decl->location = loc;
715
716                auto go = new BranchStmt(
717                        new VariableExpr( go_decl ),
718                        BranchStmt::Goto
719                );
720                go->location = loc;
721                go->computedTarget->location = loc;
722
723                auto noop = new NullStmt({ first_label });
724                noop->location = loc;
725
726                // wrap everything in a nice compound
727                auto body = new CompoundStmt({
728                        new DeclStmt( decl ),
729                        new DeclStmt( go_decl ),
730                        go,
731                        noop,
732                        func->statements
733                });
734                body->location   = loc;
735                func->statements = body;
736
737                return func;
738        }
739
740        Statement * SuspendKeyword::postmutate( SuspendStmt * stmt ) {
741                SuspendStmt::Type type = stmt->type;
742                if(type == SuspendStmt::None) {
743                        // This suspend has a implicit target, find it
744                        type = in_generator ? SuspendStmt::Generator : SuspendStmt::Coroutine;
745                }
746
747                // Check that the target makes sense
748                if(!in_generator && type == SuspendStmt::Generator) SemanticError( stmt->location, "'suspend generator' must be used inside main of generator type.");
749
750                // Act appropriately
751                switch(type) {
752                        case SuspendStmt::Generator: return make_generator_suspend(stmt);
753                        case SuspendStmt::Coroutine: return make_coroutine_suspend(stmt);
754                        default: abort();
755                }
756        }
757
758        Statement * SuspendKeyword::make_generator_suspend( SuspendStmt * stmt ) {
759                assert(in_generator);
760                // Target code is :
761                //   gen.__generator_state = X;
762                //   { THEN }
763                //   return;
764                //   __gen_X:;
765
766                // Save the location and delete the old statement, we only need the location from this point on
767                auto loc = stmt->location;
768
769                // Build the label and get its index
770                auto label = make_label();
771
772                // Create the context saving statement
773                auto save = new ExprStmt( new UntypedExpr(
774                        new NameExpr( "?=?" ),
775                        {
776                                new UntypedMemberExpr(
777                                        new NameExpr("__generator_state"),
778                                        new VariableExpr( in_generator )
779                                ),
780                                new ConstantExpr(
781                                        Constant::from_int( label.idx )
782                                )
783                        }
784                ));
785                assert(save->expr);
786                save->location = loc;
787                stmtsToAddBefore.push_back( save );
788
789                // if we have a then add it here
790                auto then = stmt->then;
791                stmt->then = nullptr;
792                delete stmt;
793                if(then) stmtsToAddBefore.push_back( then );
794
795                // Create the return statement
796                auto ret = new ReturnStmt( nullptr );
797                ret->location = loc;
798                stmtsToAddBefore.push_back( ret );
799
800                // Create the null statement with the created label
801                auto noop = new NullStmt({ label.obj });
802                noop->location = loc;
803
804                // Return the null statement to take the place of the previous statement
805                return noop;
806        }
807
808        Statement * SuspendKeyword::make_coroutine_suspend( SuspendStmt * stmt ) {
809                if(stmt->then) SemanticError( stmt->location, "Compound statement following coroutines is not implemented.");
810
811                // Save the location and delete the old statement, we only need the location from this point on
812                auto loc = stmt->location;
813                delete stmt;
814
815                // Create the call expression
816                if(!decl_suspend) SemanticError( loc, "suspend keyword applied to coroutines requires coroutines to be in scope, add #include <coroutine.hfa>\n");
817                auto expr = new UntypedExpr( VariableExpr::functionPointer( decl_suspend ) );
818                expr->location = loc;
819
820                // Change this statement into a regular expr
821                assert(expr);
822                auto nstmt = new ExprStmt( expr );
823                nstmt->location = loc;
824                return nstmt;
825        }
826
827
828        //=============================================================================================
829        // Mutex keyword implementation
830        //=============================================================================================
831
832        void MutexKeyword::postvisit(FunctionDecl* decl) {
833
834                bool first = false;
835                std::list<DeclarationWithType*> mutexArgs = findMutexArgs( decl, first );
836                bool const isDtor = CodeGen::isDestructor( decl->name );
837
838                // Is this function relevant to monitors
839                if( mutexArgs.empty() ) {
840                        // If this is the destructor for a monitor it must be mutex
841                        if(isDtor) {
842                                Type* ty = decl->get_functionType()->get_parameters().front()->get_type();
843
844                                // If it's a copy, it's not a mutex
845                                ReferenceType* rty = dynamic_cast< ReferenceType * >( ty );
846                                if( ! rty ) return;
847
848                                // If we are not pointing directly to a type, it's not a mutex
849                                Type* base = rty->get_base();
850                                if( dynamic_cast< ReferenceType * >( base ) ) return;
851                                if( dynamic_cast< PointerType * >( base ) ) return;
852
853                                // Check if its a struct
854                                StructInstType * baseStruct = dynamic_cast< StructInstType * >( base );
855                                if( !baseStruct ) return;
856
857                                // Check if its a monitor
858                                if(baseStruct->baseStruct->is_monitor() || baseStruct->baseStruct->is_thread())
859                                        SemanticError( decl, "destructors for structures declared as \"monitor\" must use mutex parameters\n" );
860                        }
861                        return;
862                }
863
864                // Monitors can't be constructed with mutual exclusion
865                if( CodeGen::isConstructor(decl->name) && !first ) SemanticError( decl, "constructors cannot have mutex parameters" );
866
867                // It makes no sense to have multiple mutex parameters for the destructor
868                if( isDtor && mutexArgs.size() != 1 ) SemanticError( decl, "destructors can only have 1 mutex argument" );
869
870                // Make sure all the mutex arguments are monitors
871                for(auto arg : mutexArgs) {
872                        validate( arg );
873                }
874
875                // Check if we need to instrument the body
876                CompoundStmt* body = decl->get_statements();
877                if( ! body ) return;
878
879                // Do we have the required headers
880                if( !monitor_decl || !guard_decl || !dtor_guard_decl )
881                        SemanticError( decl, "mutex keyword requires monitors to be in scope, add #include <monitor.hfa>\n" );
882
883                // Instrument the body
884                if ( isDtor && isThread( mutexArgs.front() ) ) {
885                        if( !thread_guard_decl ) {
886                                SemanticError( decl, "thread destructor requires threads to be in scope, add #include <thread.hfa>\n" );
887                        }
888                        addThreadDtorStatements( decl, body, mutexArgs );
889                }
890                else if ( isDtor ) {
891                        addDtorStatements( decl, body, mutexArgs );
892                }
893                else {
894                        addStatements( decl, body, mutexArgs );
895                }
896        }
897
898        void MutexKeyword::postvisit(StructDecl* decl) {
899
900                if( decl->name == "$monitor" && decl->body ) {
901                        assert( !monitor_decl );
902                        monitor_decl = decl;
903                }
904                else if( decl->name == "monitor_guard_t" && decl->body ) {
905                        assert( !guard_decl );
906                        guard_decl = decl;
907                }
908                else if( decl->name == "monitor_dtor_guard_t" && decl->body ) {
909                        assert( !dtor_guard_decl );
910                        dtor_guard_decl = decl;
911                }
912                else if( decl->name == "thread_dtor_guard_t" && decl->body ) {
913                        assert( !thread_guard_decl );
914                        thread_guard_decl = decl;
915                }
916        }
917
918        std::list<DeclarationWithType*> MutexKeyword::findMutexArgs( FunctionDecl* decl, bool & first ) {
919                std::list<DeclarationWithType*> mutexArgs;
920
921                bool once = true;
922                for( auto arg : decl->get_functionType()->get_parameters()) {
923                        //Find mutex arguments
924                        Type* ty = arg->get_type();
925                        if( ! ty->get_mutex() ) continue;
926
927                        if(once) {first = true;}
928                        once = false;
929
930                        //Append it to the list
931                        mutexArgs.push_back( arg );
932                }
933
934                return mutexArgs;
935        }
936
937        void MutexKeyword::validate( DeclarationWithType * arg ) {
938                Type* ty = arg->get_type();
939
940                //Makes sure it's not a copy
941                ReferenceType* rty = dynamic_cast< ReferenceType * >( ty );
942                if( ! rty ) SemanticError( arg, "Mutex argument must be of reference type " );
943
944                //Make sure the we are pointing directly to a type
945                Type* base = rty->get_base();
946                if( dynamic_cast< ReferenceType * >( base ) ) SemanticError( arg, "Mutex argument have exactly one level of indirection " );
947                if( dynamic_cast< PointerType * >( base ) ) SemanticError( arg, "Mutex argument have exactly one level of indirection " );
948
949                //Make sure that typed isn't mutex
950                if( base->get_mutex() ) SemanticError( arg, "mutex keyword may only appear once per argument " );
951        }
952
953        void MutexKeyword::addDtorStatements( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
954                Type * arg_type = args.front()->get_type()->clone();
955                arg_type->set_mutex( false );
956
957                ObjectDecl * monitors = new ObjectDecl(
958                        "__monitor",
959                        noStorageClasses,
960                        LinkageSpec::Cforall,
961                        nullptr,
962                        new PointerType(
963                                noQualifiers,
964                                new StructInstType(
965                                        noQualifiers,
966                                        monitor_decl
967                                )
968                        ),
969                        new SingleInit( new UntypedExpr(
970                                new NameExpr( "get_monitor" ),
971                                {  new CastExpr( new VariableExpr( args.front() ), arg_type, false ) }
972                        ))
973                );
974
975                assert(generic_func);
976
977                //in reverse order :
978                // monitor_dtor_guard_t __guard = { __monitors, func };
979                body->push_front(
980                        new DeclStmt( new ObjectDecl(
981                                "__guard",
982                                noStorageClasses,
983                                LinkageSpec::Cforall,
984                                nullptr,
985                                new StructInstType(
986                                        noQualifiers,
987                                        dtor_guard_decl
988                                ),
989                                new ListInit(
990                                        {
991                                                new SingleInit( new AddressExpr( new VariableExpr( monitors ) ) ),
992                                                new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone(), false ) ),
993                                                new SingleInit( new ConstantExpr( Constant::from_bool( false ) ) )
994                                        },
995                                        noDesignators,
996                                        true
997                                )
998                        ))
999                );
1000
1001                //$monitor * __monitors[] = { get_monitor(a), get_monitor(b) };
1002                body->push_front( new DeclStmt( monitors ) );
1003        }
1004
1005        void MutexKeyword::addThreadDtorStatements(
1006                        FunctionDecl*, CompoundStmt * body,
1007                        const std::list<DeclarationWithType * > & args ) {
1008                assert( args.size() == 1 );
1009                DeclarationWithType * arg = args.front();
1010                Type * arg_type = arg->get_type()->clone();
1011                assert( arg_type->get_mutex() );
1012                arg_type->set_mutex( false );
1013
1014                // thread_dtor_guard_t __guard = { this, intptr( 0 ) };
1015                body->push_front(
1016                        new DeclStmt( new ObjectDecl(
1017                                "__guard",
1018                                noStorageClasses,
1019                                LinkageSpec::Cforall,
1020                                nullptr,
1021                                new StructInstType(
1022                                        noQualifiers,
1023                                        thread_guard_decl
1024                                ),
1025                                new ListInit(
1026                                        {
1027                                                new SingleInit( new CastExpr( new VariableExpr( arg ), arg_type ) ),
1028                                                new SingleInit( new UntypedExpr(
1029                                                        new NameExpr( "intptr" ), {
1030                                                                new ConstantExpr( Constant::from_int( 0 ) ),
1031                                                        }
1032                                                ) ),
1033                                        },
1034                                        noDesignators,
1035                                        true
1036                                )
1037                        ))
1038                );
1039        }
1040
1041        void MutexKeyword::addStatements( FunctionDecl* func, CompoundStmt * body, const std::list<DeclarationWithType * > & args ) {
1042                ObjectDecl * monitors = new ObjectDecl(
1043                        "__monitors",
1044                        noStorageClasses,
1045                        LinkageSpec::Cforall,
1046                        nullptr,
1047                        new ArrayType(
1048                                noQualifiers,
1049                                new PointerType(
1050                                        noQualifiers,
1051                                        new StructInstType(
1052                                                noQualifiers,
1053                                                monitor_decl
1054                                        )
1055                                ),
1056                                new ConstantExpr( Constant::from_ulong( args.size() ) ),
1057                                false,
1058                                false
1059                        ),
1060                        new ListInit(
1061                                map_range < std::list<Initializer*> > ( args, [](DeclarationWithType * var ){
1062                                        Type * type = var->get_type()->clone();
1063                                        type->set_mutex( false );
1064                                        return new SingleInit( new UntypedExpr(
1065                                                new NameExpr( "get_monitor" ),
1066                                                {  new CastExpr( new VariableExpr( var ), type, false ) }
1067                                        ) );
1068                                })
1069                        )
1070                );
1071
1072                assert(generic_func);
1073
1074                // in reverse order :
1075                // monitor_guard_t __guard = { __monitors, #, func };
1076                body->push_front(
1077                        new DeclStmt( new ObjectDecl(
1078                                "__guard",
1079                                noStorageClasses,
1080                                LinkageSpec::Cforall,
1081                                nullptr,
1082                                new StructInstType(
1083                                        noQualifiers,
1084                                        guard_decl
1085                                ),
1086                                new ListInit(
1087                                        {
1088                                                new SingleInit( new VariableExpr( monitors ) ),
1089                                                new SingleInit( new ConstantExpr( Constant::from_ulong( args.size() ) ) ),
1090                                                new SingleInit( new CastExpr( new VariableExpr( func ), generic_func->clone(), false ) )
1091                                        },
1092                                        noDesignators,
1093                                        true
1094                                )
1095                        ))
1096                );
1097
1098                //$monitor * __monitors[] = { get_monitor(a), get_monitor(b) };
1099                body->push_front( new DeclStmt( monitors) );
1100        }
1101
1102        //=============================================================================================
1103        // General entry routine
1104        //=============================================================================================
1105        void ThreadStarter::previsit( StructDecl * decl ) {
1106                if( decl->name == "$thread" && decl->body ) {
1107                        assert( !thread_decl );
1108                        thread_decl = decl;
1109                }
1110        }
1111
1112        void ThreadStarter::postvisit(FunctionDecl * decl) {
1113                if( ! CodeGen::isConstructor(decl->name) ) return;
1114
1115                Type * typeof_this = InitTweak::getTypeofThis(decl->type);
1116                StructInstType * ctored_type = dynamic_cast< StructInstType * >( typeof_this );
1117                if( ctored_type && ctored_type->baseStruct == thread_decl ) {
1118                        thread_ctor_seen = true;
1119                }
1120
1121                DeclarationWithType * param = decl->get_functionType()->get_parameters().front();
1122                auto type  = dynamic_cast< StructInstType * >( InitTweak::getPointerBase( param->get_type() ) );
1123                if( type && type->get_baseStruct()->is_thread() ) {
1124                        if( !thread_decl || !thread_ctor_seen ) {
1125                                SemanticError( type->get_baseStruct()->location, "thread keyword requires threads to be in scope, add #include <thread.hfa>");
1126                        }
1127
1128                        addStartStatement( decl, param );
1129                }
1130        }
1131
1132        void ThreadStarter::addStartStatement( FunctionDecl * decl, DeclarationWithType * param ) {
1133                CompoundStmt * stmt = decl->get_statements();
1134
1135                if( ! stmt ) return;
1136
1137                stmt->push_back(
1138                        new ExprStmt(
1139                                new UntypedExpr(
1140                                        new NameExpr( "__thrd_start" ),
1141                                        { new VariableExpr( param ), new NameExpr("main") }
1142                                )
1143                        )
1144                );
1145        }
1146};
1147
1148// Local Variables: //
1149// mode: c //
1150// tab-width: 4 //
1151// End: //
1152
Note: See TracBrowser for help on using the repository browser.