source: src/SymTab/Validate.cc @ a506df4

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since a506df4 was a506df4, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Convert EliminateTypedef? to PassVisitor?

  • Property mode set to 100644
File size: 40.2 KB
RevLine 
[0dd3a2f]1//
2// Cforall Version 1.0.0 Copyright (C) 2015 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//
[9cb8e88d]7// Validate.cc --
[0dd3a2f]8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
[b128d3e]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Aug 28 13:47:23 2017
13// Update Count     : 359
[0dd3a2f]14//
15
16// The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
17// as regular in structure as possible.  Some assumptions can be made regarding the state of the tree after this pass is
18// complete, including:
19//
20// - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
21//   union.
22//
23// - All enumeration constants have type EnumInstType.
24//
[3c13c03]25// - The type "void" never occurs in lists of function parameter or return types.  A function
26//   taking no arguments has no argument types.
[0dd3a2f]27//
28// - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
29//   by the particular set of type arguments.
30//
31// - Every declaration is assigned a unique id.
32//
33// - No typedef declarations or instances exist; the actual type is substituted for each instance.
34//
35// - Each type, struct, and union definition is followed by an appropriate assignment operator.
36//
37// - Each use of a struct or union is connected to a complete definition of that struct or union, even if that
38//   definition occurs later in the input.
[51b7345]39
[0db6fc0]40#include "Validate.h"
41
[d180746]42#include <cassert>                     // for assertf, assert
[30f9072]43#include <cstddef>                     // for size_t
[d180746]44#include <list>                        // for list
45#include <string>                      // for string
46#include <utility>                     // for pair
[30f9072]47
48#include "CodeGen/CodeGenerator.h"     // for genName
[9236060]49#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
[30f9072]50#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
[d180746]51#include "Common/ScopedMap.h"          // for ScopedMap
[30f9072]52#include "Common/SemanticError.h"      // for SemanticError
53#include "Common/UniqueName.h"         // for UniqueName
54#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
[be9288a]55#include "Concurrency/Keywords.h"      // for applyKeywords
[30f9072]56#include "FixFunction.h"               // for FixFunction
57#include "Indexer.h"                   // for Indexer
[d180746]58#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
59#include "Parser/LinkageSpec.h"        // for C
60#include "ResolvExpr/typeops.h"        // for typesCompatible
[be9288a]61#include "SymTab/AddVisit.h"           // for addVisit
62#include "SymTab/Autogen.h"            // for SizeType
63#include "SynTree/Attribute.h"         // for noAttributes, Attribute
[30f9072]64#include "SynTree/Constant.h"          // for Constant
[d180746]65#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
66#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
67#include "SynTree/Initializer.h"       // for ListInit, Initializer
68#include "SynTree/Label.h"             // for operator==, Label
69#include "SynTree/Mutator.h"           // for Mutator
70#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
71#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
72#include "SynTree/Visitor.h"           // for Visitor
73
74class CompoundStmt;
75class ReturnStmt;
76class SwitchStmt;
[51b7345]77
78
[c8ffe20b]79#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
[51b7345]80
81namespace SymTab {
[9facf3b]82        class HoistStruct final : public Visitor {
[c0aa336]83                template< typename Visitor >
84                friend void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor );
85            template< typename Visitor >
86            friend void addVisitStatementList( std::list< Statement* > &stmts, Visitor &visitor );
[a08ba92]87          public:
[82dd287]88                /// Flattens nested struct types
[0dd3a2f]89                static void hoistStruct( std::list< Declaration * > &translationUnit );
[9cb8e88d]90
[0dd3a2f]91                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
[9cb8e88d]92
[c0aa336]93                virtual void visit( EnumInstType *enumInstType );
94                virtual void visit( StructInstType *structInstType );
95                virtual void visit( UnionInstType *unionInstType );
[0dd3a2f]96                virtual void visit( StructDecl *aggregateDecl );
97                virtual void visit( UnionDecl *aggregateDecl );
[c8ffe20b]98
[0dd3a2f]99                virtual void visit( CompoundStmt *compoundStmt );
100                virtual void visit( SwitchStmt *switchStmt );
[a08ba92]101          private:
[0dd3a2f]102                HoistStruct();
[c8ffe20b]103
[0dd3a2f]104                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
[c8ffe20b]105
[c0aa336]106                std::list< Declaration * > declsToAdd, declsToAddAfter;
[0dd3a2f]107                bool inStruct;
[a08ba92]108        };
[c8ffe20b]109
[cce9429]110        /// Fix return types so that every function returns exactly one value
[d24d4e1]111        struct ReturnTypeFixer {
[cce9429]112                static void fix( std::list< Declaration * > &translationUnit );
113
[0db6fc0]114                void postvisit( FunctionDecl * functionDecl );
115                void postvisit( FunctionType * ftype );
[cce9429]116        };
117
[de91427b]118        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
[d24d4e1]119        struct EnumAndPointerDecay {
[06edda0]120                void previsit( EnumDecl *aggregateDecl );
121                void previsit( FunctionType *func );
[a08ba92]122        };
[82dd287]123
124        /// Associates forward declarations of aggregates with their definitions
[cce9429]125        class LinkReferenceToTypes final : public Indexer {
[0dd3a2f]126                typedef Indexer Parent;
[a08ba92]127          public:
[cce9429]128                LinkReferenceToTypes( bool doDebug, const Indexer *indexer );
[be9036d]129                using Parent::visit;
130                void visit( TypeInstType *typeInst ) final;
131
[c0aa336]132                void visit( EnumInstType *enumInst ) final;
[62e5546]133                void visit( StructInstType *structInst ) final;
134                void visit( UnionInstType *unionInst ) final;
[be9036d]135                void visit( TraitInstType *traitInst ) final;
136
[c0aa336]137                void visit( EnumDecl *enumDecl ) final;
[62e5546]138                void visit( StructDecl *structDecl ) final;
139                void visit( UnionDecl *unionDecl ) final;
[be9036d]140                void visit( TraitDecl * traitDecl ) final;
141
[06edda0]142          private:
[0dd3a2f]143                const Indexer *indexer;
[9cb8e88d]144
[c0aa336]145                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
[0dd3a2f]146                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
147                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
[c0aa336]148                ForwardEnumsType forwardEnums;
[0dd3a2f]149                ForwardStructsType forwardStructs;
150                ForwardUnionsType forwardUnions;
[a08ba92]151        };
[c8ffe20b]152
[06edda0]153        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
154        class ForallPointerDecay final : public Indexer {
[0dd3a2f]155                typedef Indexer Parent;
[a08ba92]156          public:
[4a9ccc3]157                using Parent::visit;
[06edda0]158                ForallPointerDecay( const Indexer *indexer );
159
[4a9ccc3]160                virtual void visit( ObjectDecl *object ) override;
161                virtual void visit( FunctionDecl *func ) override;
[c8ffe20b]162
[0dd3a2f]163                const Indexer *indexer;
[a08ba92]164        };
[c8ffe20b]165
[d24d4e1]166        struct ReturnChecker : public WithGuards {
[de91427b]167                /// Checks that return statements return nothing if their return type is void
168                /// and return something if the return type is non-void.
169                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
170
[0db6fc0]171                void previsit( FunctionDecl * functionDecl );
172                void previsit( ReturnStmt * returnStmt );
[de91427b]173
[0db6fc0]174                typedef std::list< DeclarationWithType * > ReturnVals;
175                ReturnVals returnVals;
[de91427b]176        };
177
[a506df4]178        struct EliminateTypedef final : public WithVisitorRef<EliminateTypedef>, public WithGuards {
[de91427b]179                EliminateTypedef() : scopeLevel( 0 ) {}
180                /// Replaces typedefs by forward declarations
[0dd3a2f]181                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
[85c4ef0]182
[a506df4]183                Type * postmutate( TypeInstType * aggregateUseType );
184                Declaration * postmutate( TypedefDecl * typeDecl );
185                void premutate( TypeDecl * typeDecl );
186                void premutate( FunctionDecl * funcDecl );
187                void premutate( ObjectDecl * objDecl );
188                DeclarationWithType * postmutate( ObjectDecl * objDecl );
189
190                void premutate( CastExpr * castExpr );
191
192                void premutate( CompoundStmt * compoundStmt );
193                CompoundStmt * postmutate( CompoundStmt * compoundStmt );
194
195                void premutate( StructDecl * structDecl );
196                Declaration * postmutate( StructDecl * structDecl );
197                void premutate( UnionDecl * unionDecl );
198                Declaration * postmutate( UnionDecl * unionDecl );
199                void premutate( EnumDecl * enumDecl );
200                Declaration * postmutate( EnumDecl * enumDecl );
201                Declaration * postmutate( TraitDecl * contextDecl );
202
203          private:
[85c4ef0]204                template<typename AggDecl>
205                AggDecl *handleAggregate( AggDecl * aggDecl );
206
[45161b4d]207                template<typename AggDecl>
208                void addImplicitTypedef( AggDecl * aggDecl );
[70a06f6]209
[46f6134]210                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
[e491159]211                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
[679864e1]212                typedef std::map< std::string, TypeDecl * > TypeDeclMap;
[cc79d97]213                TypedefMap typedefNames;
[679864e1]214                TypeDeclMap typedeclNames;
[cc79d97]215                int scopeLevel;
[a08ba92]216        };
[c8ffe20b]217
[d24d4e1]218        struct VerifyCtorDtorAssign {
[d1969a6]219                /// ensure that constructors, destructors, and assignment have at least one
220                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
[9cb8e88d]221                /// return values.
222                static void verify( std::list< Declaration * > &translationUnit );
223
[0db6fc0]224                void previsit( FunctionDecl *funcDecl );
[5f98ce5]225        };
[70a06f6]226
[11ab8ea8]227        /// ensure that generic types have the correct number of type arguments
[d24d4e1]228        struct ValidateGenericParameters {
[0db6fc0]229                void previsit( StructInstType * inst );
230                void previsit( UnionInstType * inst );
[5f98ce5]231        };
[70a06f6]232
[d24d4e1]233        struct ArrayLength {
[fbd7ad6]234                /// for array types without an explicit length, compute the length and store it so that it
235                /// is known to the rest of the phases. For example,
236                ///   int x[] = { 1, 2, 3 };
237                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
238                /// here x and y are known at compile-time to have length 3, so change this into
239                ///   int x[3] = { 1, 2, 3 };
240                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
241                static void computeLength( std::list< Declaration * > & translationUnit );
242
[0db6fc0]243                void previsit( ObjectDecl * objDecl );
[fbd7ad6]244        };
245
[d24d4e1]246        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
[68fe077a]247                Type::StorageClasses storageClasses;
[630a82a]248
[d24d4e1]249                void premutate( ObjectDecl *objectDecl );
250                Expression * postmutate( CompoundLiteralExpr *compLitExpr );
[9cb8e88d]251        };
252
[5809461]253        struct LabelAddressFixer final : public WithGuards {
254                std::set< Label > labels;
255
256                void premutate( FunctionDecl * funcDecl );
257                Expression * postmutate( AddressExpr * addrExpr );
258        };
[4fbdfae0]259
260        FunctionDecl * dereferenceOperator = nullptr;
261        struct FindSpecialDeclarations final {
262                void previsit( FunctionDecl * funcDecl );
263        };
264
[a08ba92]265        void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
[06edda0]266                PassVisitor<EnumAndPointerDecay> epc;
[cce9429]267                LinkReferenceToTypes lrt( doDebug, 0 );
[06edda0]268                ForallPointerDecay fpd( 0 );
[d24d4e1]269                PassVisitor<CompoundLiteral> compoundliteral;
[0db6fc0]270                PassVisitor<ValidateGenericParameters> genericParams;
[4fbdfae0]271                PassVisitor<FindSpecialDeclarations> finder;
[5809461]272                PassVisitor<LabelAddressFixer> labelAddrFixer;
[630a82a]273
[fbcde64]274                EliminateTypedef::eliminateTypedef( translationUnit );
[11ab8ea8]275                HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
[cce9429]276                ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
[861799c]277                acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
[11ab8ea8]278                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes
[ed8a0d2]279                acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist
280                VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
[bcda04c]281                Concurrency::applyKeywords( translationUnit );
[06edda0]282                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
[bcda04c]283                Concurrency::implementMutexFuncs( translationUnit );
284                Concurrency::implementThreadStarter( translationUnit );
[de91427b]285                ReturnChecker::checkFunctionReturns( translationUnit );
[d24d4e1]286                mutateAll( translationUnit, compoundliteral );
[06edda0]287                acceptAll( translationUnit, fpd );
[fbd7ad6]288                ArrayLength::computeLength( translationUnit );
[4fbdfae0]289                acceptAll( translationUnit, finder );
[5809461]290                mutateAll( translationUnit, labelAddrFixer );
[a08ba92]291        }
[9cb8e88d]292
[a08ba92]293        void validateType( Type *type, const Indexer *indexer ) {
[06edda0]294                PassVisitor<EnumAndPointerDecay> epc;
[cce9429]295                LinkReferenceToTypes lrt( false, indexer );
[06edda0]296                ForallPointerDecay fpd( indexer );
[bda58ad]297                type->accept( epc );
[cce9429]298                type->accept( lrt );
[06edda0]299                type->accept( fpd );
[a08ba92]300        }
[c8ffe20b]301
[a08ba92]302        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
[0dd3a2f]303                HoistStruct hoister;
[c0aa336]304                acceptAndAdd( translationUnit, hoister );
[a08ba92]305        }
[c8ffe20b]306
[a08ba92]307        HoistStruct::HoistStruct() : inStruct( false ) {
308        }
[c8ffe20b]309
[a08ba92]310        bool isStructOrUnion( Declaration *decl ) {
[0dd3a2f]311                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
[a08ba92]312        }
[c0aa336]313
[a08ba92]314        template< typename AggDecl >
315        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
[0dd3a2f]316                if ( inStruct ) {
317                        // Add elements in stack order corresponding to nesting structure.
318                        declsToAdd.push_front( aggregateDecl );
319                        Visitor::visit( aggregateDecl );
320                } else {
321                        inStruct = true;
322                        Visitor::visit( aggregateDecl );
323                        inStruct = false;
324                } // if
325                // Always remove the hoisted aggregate from the inner structure.
326                filter( aggregateDecl->get_members(), isStructOrUnion, false );
[a08ba92]327        }
[c8ffe20b]328
[c0aa336]329        void HoistStruct::visit( EnumInstType *structInstType ) {
330                if ( structInstType->get_baseEnum() ) {
331                        declsToAdd.push_front( structInstType->get_baseEnum() );
332                }
333        }
334
335        void HoistStruct::visit( StructInstType *structInstType ) {
336                if ( structInstType->get_baseStruct() ) {
337                        declsToAdd.push_front( structInstType->get_baseStruct() );
338                }
339        }
340
341        void HoistStruct::visit( UnionInstType *structInstType ) {
342                if ( structInstType->get_baseUnion() ) {
343                        declsToAdd.push_front( structInstType->get_baseUnion() );
344                }
345        }
346
[a08ba92]347        void HoistStruct::visit( StructDecl *aggregateDecl ) {
[0dd3a2f]348                handleAggregate( aggregateDecl );
[a08ba92]349        }
[c8ffe20b]350
[a08ba92]351        void HoistStruct::visit( UnionDecl *aggregateDecl ) {
[0dd3a2f]352                handleAggregate( aggregateDecl );
[a08ba92]353        }
[c8ffe20b]354
[a08ba92]355        void HoistStruct::visit( CompoundStmt *compoundStmt ) {
[0dd3a2f]356                addVisit( compoundStmt, *this );
[a08ba92]357        }
[c8ffe20b]358
[a08ba92]359        void HoistStruct::visit( SwitchStmt *switchStmt ) {
[0dd3a2f]360                addVisit( switchStmt, *this );
[a08ba92]361        }
[c8ffe20b]362
[06edda0]363        void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
[0dd3a2f]364                // Set the type of each member of the enumeration to be EnumConstant
365                for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
[f6d7e0f]366                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
[0dd3a2f]367                        assert( obj );
[f2e40a9f]368                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->get_name() ) );
[0dd3a2f]369                } // for
[a08ba92]370        }
[51b7345]371
[a08ba92]372        namespace {
[83de11e]373                template< typename DWTList >
374                void fixFunctionList( DWTList & dwts, FunctionType * func ) {
[0dd3a2f]375                        // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
[06edda0]376                        // entirely. other fix ups are handled by the FixFunction class
[83de11e]377                        typedef typename DWTList::iterator DWTIterator;
378                        DWTIterator begin( dwts.begin() ), end( dwts.end() );
[0dd3a2f]379                        if ( begin == end ) return;
380                        FixFunction fixer;
381                        DWTIterator i = begin;
[83de11e]382                        *i = (*i)->acceptMutator( fixer );
[0dd3a2f]383                        if ( fixer.get_isVoid() ) {
384                                DWTIterator j = i;
385                                ++i;
[bda58ad]386                                delete *j;
[83de11e]387                                dwts.erase( j );
[9cb8e88d]388                                if ( i != end ) {
[0dd3a2f]389                                        throw SemanticError( "invalid type void in function type ", func );
390                                } // if
391                        } else {
392                                ++i;
393                                for ( ; i != end; ++i ) {
394                                        FixFunction fixer;
[06edda0]395                                        *i = (*i)->acceptMutator( fixer );
[0dd3a2f]396                                        if ( fixer.get_isVoid() ) {
397                                                throw SemanticError( "invalid type void in function type ", func );
398                                        } // if
399                                } // for
400                        } // if
401                }
[a08ba92]402        }
[c8ffe20b]403
[06edda0]404        void EnumAndPointerDecay::previsit( FunctionType *func ) {
[0dd3a2f]405                // Fix up parameters and return types
[83de11e]406                fixFunctionList( func->get_parameters(), func );
407                fixFunctionList( func->get_returnVals(), func );
[a08ba92]408        }
[c8ffe20b]409
[cce9429]410        LinkReferenceToTypes::LinkReferenceToTypes( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
[0dd3a2f]411                if ( other_indexer ) {
412                        indexer = other_indexer;
413                } else {
414                        indexer = this;
415                } // if
[a08ba92]416        }
[c8ffe20b]417
[c0aa336]418        void LinkReferenceToTypes::visit( EnumInstType *enumInst ) {
419                Parent::visit( enumInst );
420                EnumDecl *st = indexer->lookupEnum( enumInst->get_name() );
421                // it's not a semantic error if the enum is not found, just an implicit forward declaration
422                if ( st ) {
423                        //assert( ! enumInst->get_baseEnum() || enumInst->get_baseEnum()->get_members().empty() || ! st->get_members().empty() );
424                        enumInst->set_baseEnum( st );
425                } // if
426                if ( ! st || st->get_members().empty() ) {
427                        // use of forward declaration
428                        forwardEnums[ enumInst->get_name() ].push_back( enumInst );
429                } // if
430        }
431
[cce9429]432        void LinkReferenceToTypes::visit( StructInstType *structInst ) {
[0dd3a2f]433                Parent::visit( structInst );
434                StructDecl *st = indexer->lookupStruct( structInst->get_name() );
435                // it's not a semantic error if the struct is not found, just an implicit forward declaration
436                if ( st ) {
[98735ef]437                        //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
[0dd3a2f]438                        structInst->set_baseStruct( st );
439                } // if
440                if ( ! st || st->get_members().empty() ) {
441                        // use of forward declaration
442                        forwardStructs[ structInst->get_name() ].push_back( structInst );
443                } // if
[a08ba92]444        }
[c8ffe20b]445
[cce9429]446        void LinkReferenceToTypes::visit( UnionInstType *unionInst ) {
[0dd3a2f]447                Parent::visit( unionInst );
448                UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
449                // it's not a semantic error if the union is not found, just an implicit forward declaration
450                if ( un ) {
451                        unionInst->set_baseUnion( un );
452                } // if
453                if ( ! un || un->get_members().empty() ) {
454                        // use of forward declaration
455                        forwardUnions[ unionInst->get_name() ].push_back( unionInst );
456                } // if
[a08ba92]457        }
[c8ffe20b]458
[be9036d]459        template< typename Decl >
460        void normalizeAssertions( std::list< Decl * > & assertions ) {
461                // ensure no duplicate trait members after the clone
462                auto pred = [](Decl * d1, Decl * d2) {
463                        // only care if they're equal
464                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
465                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
466                        if ( dwt1 && dwt2 ) {
467                                if ( dwt1->get_name() == dwt2->get_name() && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
468                                        // std::cerr << "=========== equal:" << std::endl;
469                                        // std::cerr << "d1: " << d1 << std::endl;
470                                        // std::cerr << "d2: " << d2 << std::endl;
471                                        return false;
472                                }
[2c57025]473                        }
[be9036d]474                        return d1 < d2;
475                };
476                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
477                // if ( unique_members.size() != assertions.size() ) {
478                //      std::cerr << "============different" << std::endl;
479                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
480                // }
481
482                std::list< Decl * > order;
483                order.splice( order.end(), assertions );
484                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
485                        return unique_members.count( decl );
486                });
487        }
488
489        // expand assertions from trait instance, performing the appropriate type variable substitutions
490        template< typename Iterator >
491        void expandAssertions( TraitInstType * inst, Iterator out ) {
492                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toString( inst ).c_str() );
493                std::list< DeclarationWithType * > asserts;
494                for ( Declaration * decl : inst->baseTrait->members ) {
495                        asserts.push_back( safe_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
[2c57025]496                }
[be9036d]497                // substitute trait decl parameters for instance parameters
498                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
499        }
500
501        void LinkReferenceToTypes::visit( TraitDecl * traitDecl ) {
502                Parent::visit( traitDecl );
503
504                if ( traitDecl->name == "sized" ) {
505                        // "sized" is a special trait - flick the sized status on for the type variable
506                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
507                        TypeDecl * td = traitDecl->parameters.front();
508                        td->set_sized( true );
509                }
510
511                // move assertions from type parameters into the body of the trait
512                for ( TypeDecl * td : traitDecl->parameters ) {
513                        for ( DeclarationWithType * assert : td->assertions ) {
514                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
515                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
516                                } else {
517                                        traitDecl->members.push_back( assert->clone() );
518                                }
519                        }
520                        deleteAll( td->assertions );
521                        td->assertions.clear();
522                } // for
523        }
[2ae171d8]524
[be9036d]525        void LinkReferenceToTypes::visit( TraitInstType * traitInst ) {
526                Parent::visit( traitInst );
[2ae171d8]527                // handle other traits
[be9036d]528                TraitDecl *traitDecl = indexer->lookupTrait( traitInst->name );
[4a9ccc3]529                if ( ! traitDecl ) {
[be9036d]530                        throw SemanticError( "use of undeclared trait " + traitInst->name );
[17cd4eb]531                } // if
[4a9ccc3]532                if ( traitDecl->get_parameters().size() != traitInst->get_parameters().size() ) {
533                        throw SemanticError( "incorrect number of trait parameters: ", traitInst );
534                } // if
[be9036d]535                traitInst->baseTrait = traitDecl;
[79970ed]536
[4a9ccc3]537                // need to carry over the 'sized' status of each decl in the instance
538                for ( auto p : group_iterate( traitDecl->get_parameters(), traitInst->get_parameters() ) ) {
539                        TypeExpr * expr = safe_dynamic_cast< TypeExpr * >( std::get<1>(p) );
540                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
541                                TypeDecl * formalDecl = std::get<0>(p);
542                                TypeDecl * instDecl = inst->get_baseType();
543                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
544                        }
545                }
[be9036d]546                // normalizeAssertions( traitInst->members );
[a08ba92]547        }
[c8ffe20b]548
[c0aa336]549        void LinkReferenceToTypes::visit( EnumDecl *enumDecl ) {
550                // visit enum members first so that the types of self-referencing members are updated properly
551                Parent::visit( enumDecl );
552                if ( ! enumDecl->get_members().empty() ) {
553                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->get_name() );
554                        if ( fwds != forwardEnums.end() ) {
555                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
556                                        (*inst )->set_baseEnum( enumDecl );
557                                } // for
558                                forwardEnums.erase( fwds );
559                        } // if
560                } // if
561        }
562
[cce9429]563        void LinkReferenceToTypes::visit( StructDecl *structDecl ) {
[677c1be]564                // visit struct members first so that the types of self-referencing members are updated properly
[67cf18c]565                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and and their defaults)
[677c1be]566                Parent::visit( structDecl );
[0dd3a2f]567                if ( ! structDecl->get_members().empty() ) {
568                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
569                        if ( fwds != forwardStructs.end() ) {
570                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
571                                        (*inst )->set_baseStruct( structDecl );
572                                } // for
573                                forwardStructs.erase( fwds );
574                        } // if
575                } // if
[a08ba92]576        }
[c8ffe20b]577
[cce9429]578        void LinkReferenceToTypes::visit( UnionDecl *unionDecl ) {
[677c1be]579                Parent::visit( unionDecl );
[0dd3a2f]580                if ( ! unionDecl->get_members().empty() ) {
581                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
582                        if ( fwds != forwardUnions.end() ) {
583                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
584                                        (*inst )->set_baseUnion( unionDecl );
585                                } // for
586                                forwardUnions.erase( fwds );
587                        } // if
588                } // if
[a08ba92]589        }
[c8ffe20b]590
[cce9429]591        void LinkReferenceToTypes::visit( TypeInstType *typeInst ) {
[0dd3a2f]592                if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
593                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
594                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
595                        } // if
596                } // if
[a08ba92]597        }
[c8ffe20b]598
[06edda0]599        ForallPointerDecay::ForallPointerDecay( const Indexer *other_indexer ) :  Indexer( false ) {
[0dd3a2f]600                if ( other_indexer ) {
601                        indexer = other_indexer;
602                } else {
603                        indexer = this;
604                } // if
[a08ba92]605        }
[c8ffe20b]606
[4a9ccc3]607        /// Fix up assertions - flattens assertion lists, removing all trait instances
608        void forallFixer( Type * func ) {
609                for ( TypeDecl * type : func->get_forall() ) {
[be9036d]610                        std::list< DeclarationWithType * > asserts;
611                        asserts.splice( asserts.end(), type->assertions );
612                        // expand trait instances into their members
613                        for ( DeclarationWithType * assertion : asserts ) {
614                                if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
615                                        // expand trait instance into all of its members
616                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
617                                        delete traitInst;
618                                } else {
619                                        // pass other assertions through
620                                        type->assertions.push_back( assertion );
621                                } // if
622                        } // for
623                        // apply FixFunction to every assertion to check for invalid void type
624                        for ( DeclarationWithType *& assertion : type->assertions ) {
625                                FixFunction fixer;
626                                assertion = assertion->acceptMutator( fixer );
627                                if ( fixer.get_isVoid() ) {
628                                        throw SemanticError( "invalid type void in assertion of function ", func );
629                                } // if
630                        } // for
631                        // normalizeAssertions( type->assertions );
[0dd3a2f]632                } // for
[a08ba92]633        }
[c8ffe20b]634
[06edda0]635        void ForallPointerDecay::visit( ObjectDecl *object ) {
[0dd3a2f]636                forallFixer( object->get_type() );
637                if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
638                        forallFixer( pointer->get_base() );
639                } // if
640                Parent::visit( object );
641                object->fixUniqueId();
[a08ba92]642        }
[c8ffe20b]643
[06edda0]644        void ForallPointerDecay::visit( FunctionDecl *func ) {
[0dd3a2f]645                forallFixer( func->get_type() );
646                Parent::visit( func );
647                func->fixUniqueId();
[a08ba92]648        }
[c8ffe20b]649
[de91427b]650        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
[0db6fc0]651                PassVisitor<ReturnChecker> checker;
[de91427b]652                acceptAll( translationUnit, checker );
653        }
654
[0db6fc0]655        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
[0508ab3]656                GuardValue( returnVals );
[de91427b]657                returnVals = functionDecl->get_functionType()->get_returnVals();
658        }
659
[0db6fc0]660        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
[74d1804]661                // Previously this also checked for the existence of an expr paired with no return values on
662                // the  function return type. This is incorrect, since you can have an expression attached to
663                // a return statement in a void-returning function in C. The expression is treated as if it
664                // were cast to void.
[30f9072]665                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
[de91427b]666                        throw SemanticError( "Non-void function returns no values: " , returnStmt );
667                }
668        }
669
670
[a08ba92]671        bool isTypedef( Declaration *decl ) {
[0dd3a2f]672                return dynamic_cast< TypedefDecl * >( decl );
[a08ba92]673        }
[c8ffe20b]674
[a08ba92]675        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
[a506df4]676                PassVisitor<EliminateTypedef> eliminator;
[0dd3a2f]677                mutateAll( translationUnit, eliminator );
[a506df4]678                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
[5f98ce5]679                        // grab and remember declaration of size_t
[a506df4]680                        SizeType = eliminator.pass.typedefNames["size_t"].first->get_base()->clone();
[5f98ce5]681                } else {
[40e636a]682                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
683                        // eventually should have a warning for this case.
684                        SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
[5f98ce5]685                }
[0dd3a2f]686                filter( translationUnit, isTypedef, true );
[5f98ce5]687
[a08ba92]688        }
[c8ffe20b]689
[a506df4]690        Type * EliminateTypedef::postmutate( TypeInstType * typeInst ) {
[9cb8e88d]691                // instances of typedef types will come here. If it is an instance
[cc79d97]692                // of a typdef type, link the instance to its actual type.
693                TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
[0dd3a2f]694                if ( def != typedefNames.end() ) {
[cc79d97]695                        Type *ret = def->second.first->get_base()->clone();
[6f95000]696                        ret->get_qualifiers() |= typeInst->get_qualifiers();
[0215a76f]697                        // place instance parameters on the typedef'd type
698                        if ( ! typeInst->get_parameters().empty() ) {
699                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
700                                if ( ! rtt ) {
701                                        throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
702                                }
703                                rtt->get_parameters().clear();
[b644d6f]704                                cloneAll( typeInst->get_parameters(), rtt->get_parameters() );
[a506df4]705                                mutateAll( rtt->get_parameters(), *visitor );  // recursively fix typedefs on parameters
[1db21619]706                        } // if
[0dd3a2f]707                        delete typeInst;
708                        return ret;
[679864e1]709                } else {
710                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
[b128d3e]711                        assertf( base != typedeclNames.end(), "Cannot find typedecl name %s", typeInst->get_name().c_str() );
[1e8b02f5]712                        typeInst->set_baseType( base->second );
[0dd3a2f]713                } // if
714                return typeInst;
[a08ba92]715        }
[c8ffe20b]716
[a506df4]717        Declaration *EliminateTypedef::postmutate( TypedefDecl * tyDecl ) {
[cc79d97]718                if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
[9cb8e88d]719                        // typedef to the same name from the same scope
[cc79d97]720                        // must be from the same type
721
722                        Type * t1 = tyDecl->get_base();
723                        Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
[1cbca6e]724                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
[cc79d97]725                                throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
[85c4ef0]726                        }
[cc79d97]727                } else {
[46f6134]728                        typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
[cc79d97]729                } // if
730
[0dd3a2f]731                // When a typedef is a forward declaration:
732                //    typedef struct screen SCREEN;
733                // the declaration portion must be retained:
734                //    struct screen;
735                // because the expansion of the typedef is:
736                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
737                // hence the type-name "screen" must be defined.
738                // Note, qualifiers on the typedef are superfluous for the forward declaration.
[6f95000]739
740                Type *designatorType = tyDecl->get_base()->stripDeclarator();
741                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
[cbce272]742                        return new StructDecl( aggDecl->get_name(), DeclarationNode::Struct, noAttributes, tyDecl->get_linkage() );
[6f95000]743                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
[cbce272]744                        return new UnionDecl( aggDecl->get_name(), noAttributes, tyDecl->get_linkage() );
[6f95000]745                } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
[cbce272]746                        return new EnumDecl( enumDecl->get_name(), noAttributes, tyDecl->get_linkage() );
[0dd3a2f]747                } else {
[a506df4]748                        return tyDecl->clone();
[0dd3a2f]749                } // if
[a08ba92]750        }
[c8ffe20b]751
[a506df4]752        void EliminateTypedef::premutate( TypeDecl * typeDecl ) {
[cc79d97]753                TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
[0dd3a2f]754                if ( i != typedefNames.end() ) {
755                        typedefNames.erase( i ) ;
756                } // if
[679864e1]757
758                typedeclNames[ typeDecl->get_name() ] = typeDecl;
[a08ba92]759        }
[c8ffe20b]760
[a506df4]761        void EliminateTypedef::premutate( FunctionDecl * ) {
762                GuardScope( typedefNames );
[a08ba92]763        }
[c8ffe20b]764
[a506df4]765        void EliminateTypedef::premutate( ObjectDecl * ) {
766                GuardScope( typedefNames );
767        }
[dd020c0]768
[a506df4]769        DeclarationWithType *EliminateTypedef::postmutate( ObjectDecl * objDecl ) {
770                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->get_type() ) ) { // function type?
[02e5ab6]771                        // replace the current object declaration with a function declaration
[a506df4]772                        FunctionDecl * newDecl = new FunctionDecl( objDecl->get_name(), objDecl->get_storageClasses(), objDecl->get_linkage(), funtype, 0, objDecl->get_attributes(), objDecl->get_funcSpec() );
[0a86a30]773                        objDecl->get_attributes().clear();
[dbe8f244]774                        objDecl->set_type( nullptr );
[0a86a30]775                        delete objDecl;
776                        return newDecl;
[1db21619]777                } // if
[a506df4]778                return objDecl;
[a08ba92]779        }
[c8ffe20b]780
[a506df4]781        void EliminateTypedef::premutate( CastExpr * ) {
782                GuardScope( typedefNames );
[a08ba92]783        }
[c8ffe20b]784
[a506df4]785        void EliminateTypedef::premutate( CompoundStmt * ) {
786                GuardScope( typedefNames );
[cc79d97]787                scopeLevel += 1;
[a506df4]788                GuardAction( [this](){ scopeLevel -= 1; } );
789        }
790
791        CompoundStmt *EliminateTypedef::postmutate( CompoundStmt * compoundStmt ) {
[2bf9c37]792                // remove and delete decl stmts
793                filter( compoundStmt->kids, [](Statement * stmt) {
794                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
[0dd3a2f]795                                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
[2bf9c37]796                                        return true;
[0dd3a2f]797                                } // if
798                        } // if
[2bf9c37]799                        return false;
800                }, true);
[a506df4]801                return compoundStmt;
[a08ba92]802        }
[85c4ef0]803
[43c89a7]804        // there may be typedefs nested within aggregates. in order for everything to work properly, these should be removed
[45161b4d]805        // as well
[85c4ef0]806        template<typename AggDecl>
807        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
[2bf9c37]808                filter( aggDecl->members, isTypedef, true );
[85c4ef0]809                return aggDecl;
810        }
811
[45161b4d]812        template<typename AggDecl>
813        void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
814                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
[62e5546]815                        Type *type = nullptr;
[45161b4d]816                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
817                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
818                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
819                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
820                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
821                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
822                        } // if
[cbce272]823                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), Type::StorageClasses(), type, aggDecl->get_linkage() ) );
[46f6134]824                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
[45161b4d]825                } // if
826        }
[4e06c1e]827
[a506df4]828        void EliminateTypedef::premutate( StructDecl * structDecl ) {
[45161b4d]829                addImplicitTypedef( structDecl );
[a506df4]830        }
831
832
833        Declaration *EliminateTypedef::postmutate( StructDecl * structDecl ) {
[85c4ef0]834                return handleAggregate( structDecl );
835        }
836
[a506df4]837        void EliminateTypedef::premutate( UnionDecl * unionDecl ) {
[45161b4d]838                addImplicitTypedef( unionDecl );
[a506df4]839        }
840
841        Declaration *EliminateTypedef::postmutate( UnionDecl * unionDecl ) {
[85c4ef0]842                return handleAggregate( unionDecl );
843        }
844
[a506df4]845        void EliminateTypedef::premutate( EnumDecl * enumDecl ) {
[45161b4d]846                addImplicitTypedef( enumDecl );
[a506df4]847        }
848
849        Declaration *EliminateTypedef::postmutate( EnumDecl * enumDecl ) {
[85c4ef0]850                return handleAggregate( enumDecl );
851        }
852
[a506df4]853        Declaration *EliminateTypedef::postmutate( TraitDecl * traitDecl ) {
854                return handleAggregate( traitDecl );
[85c4ef0]855        }
856
[d1969a6]857        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
[0db6fc0]858                PassVisitor<VerifyCtorDtorAssign> verifier;
[9cb8e88d]859                acceptAll( translationUnit, verifier );
860        }
861
[0db6fc0]862        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
[9cb8e88d]863                FunctionType * funcType = funcDecl->get_functionType();
864                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
865                std::list< DeclarationWithType * > &params = funcType->get_parameters();
866
[bff227f]867                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
[9cb8e88d]868                        if ( params.size() == 0 ) {
[d1969a6]869                                throw SemanticError( "Constructors, destructors, and assignment functions require at least one parameter ", funcDecl );
[9cb8e88d]870                        }
[ce8c12f]871                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
[084fecc]872                        if ( ! refType ) {
873                                throw SemanticError( "First parameter of a constructor, destructor, or assignment function must be a reference ", funcDecl );
[9cb8e88d]874                        }
[bff227f]875                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
[9cb8e88d]876                                throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
877                        }
878                }
879        }
[70a06f6]880
[11ab8ea8]881        template< typename Aggr >
882        void validateGeneric( Aggr * inst ) {
883                std::list< TypeDecl * > * params = inst->get_baseParameters();
[30f9072]884                if ( params ) {
[11ab8ea8]885                        std::list< Expression * > & args = inst->get_parameters();
[67cf18c]886
887                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
888                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
889                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
890                        //   vector(int) v;
891                        // after insertion of default values becomes
892                        //   vector(int, heap_allocator(T))
893                        // and the substitution is built with T=int so that after substitution, the result is
894                        //   vector(int, heap_allocator(int))
895                        TypeSubstitution sub;
896                        auto paramIter = params->begin();
897                        for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
898                                if ( i < args.size() ) {
899                                        TypeExpr * expr = safe_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
900                                        sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
901                                } else if ( i == args.size() ) {
902                                        Type * defaultType = (*paramIter)->get_init();
903                                        if ( defaultType ) {
904                                                args.push_back( new TypeExpr( defaultType->clone() ) );
905                                                sub.add( (*paramIter)->get_name(), defaultType->clone() );
906                                        }
907                                }
908                        }
909
910                        sub.apply( inst );
[11ab8ea8]911                        if ( args.size() < params->size() ) throw SemanticError( "Too few type arguments in generic type ", inst );
912                        if ( args.size() > params->size() ) throw SemanticError( "Too many type arguments in generic type ", inst );
913                }
914        }
915
[0db6fc0]916        void ValidateGenericParameters::previsit( StructInstType * inst ) {
[11ab8ea8]917                validateGeneric( inst );
918        }
[9cb8e88d]919
[0db6fc0]920        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
[11ab8ea8]921                validateGeneric( inst );
[9cb8e88d]922        }
[70a06f6]923
[d24d4e1]924        void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
[a7c90d4]925                storageClasses = objectDecl->get_storageClasses();
[630a82a]926        }
927
[d24d4e1]928        Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
[630a82a]929                // transform [storage_class] ... (struct S){ 3, ... };
930                // into [storage_class] struct S temp =  { 3, ... };
931                static UniqueName indexName( "_compLit" );
932
[d24d4e1]933                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
934                compLitExpr->set_result( nullptr );
935                compLitExpr->set_initializer( nullptr );
[630a82a]936                delete compLitExpr;
[d24d4e1]937                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
938                return new VariableExpr( tempvar );
[630a82a]939        }
[cce9429]940
941        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
[0db6fc0]942                PassVisitor<ReturnTypeFixer> fixer;
[cce9429]943                acceptAll( translationUnit, fixer );
944        }
945
[0db6fc0]946        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
[9facf3b]947                FunctionType * ftype = functionDecl->get_functionType();
948                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
[56e49b0]949                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
[9facf3b]950                if ( retVals.size() == 1 ) {
[861799c]951                        // ensure all function return values have a name - use the name of the function to disambiguate (this also provides a nice bit of help for debugging).
952                        // ensure other return values have a name.
[9facf3b]953                        DeclarationWithType * ret = retVals.front();
954                        if ( ret->get_name() == "" ) {
955                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
956                        }
[c6d2e93]957                        ret->get_attributes().push_back( new Attribute( "unused" ) );
[9facf3b]958                }
959        }
[cce9429]960
[0db6fc0]961        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
[cce9429]962                // xxx - need to handle named return values - this information needs to be saved somehow
963                // so that resolution has access to the names.
964                // Note that this pass needs to happen early so that other passes which look for tuple types
965                // find them in all of the right places, including function return types.
966                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
967                if ( retVals.size() > 1 ) {
968                        // generate a single return parameter which is the tuple of all of the return values
969                        TupleType * tupleType = safe_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
970                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
[68fe077a]971                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
[cce9429]972                        deleteAll( retVals );
973                        retVals.clear();
974                        retVals.push_back( newRet );
975                }
976        }
[fbd7ad6]977
978        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
[0db6fc0]979                PassVisitor<ArrayLength> len;
[fbd7ad6]980                acceptAll( translationUnit, len );
981        }
982
[0db6fc0]983        void ArrayLength::previsit( ObjectDecl * objDecl ) {
[fbd7ad6]984                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
[30f9072]985                        if ( at->get_dimension() ) return;
[fbd7ad6]986                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->get_init() ) ) {
987                                at->set_dimension( new ConstantExpr( Constant::from_ulong( init->get_initializers().size() ) ) );
988                        }
989                }
990        }
[4fbdfae0]991
[5809461]992        struct LabelFinder {
993                std::set< Label > & labels;
994                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
995                void previsit( Statement * stmt ) {
996                        for ( Label & l : stmt->labels ) {
997                                labels.insert( l );
998                        }
999                }
1000        };
1001
1002        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1003                GuardValue( labels );
1004                PassVisitor<LabelFinder> finder( labels );
1005                funcDecl->accept( finder );
1006        }
1007
1008        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1009                // convert &&label into label address
1010                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1011                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1012                                if ( labels.count( nameExpr->name ) ) {
1013                                        Label name = nameExpr->name;
1014                                        delete addrExpr;
1015                                        return new LabelAddressExpr( name );
1016                                }
1017                        }
1018                }
1019                return addrExpr;
1020        }
1021
[4fbdfae0]1022        void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) {
1023                if ( ! dereferenceOperator ) {
1024                        if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) {
1025                                FunctionType * ftype = funcDecl->get_functionType();
1026                                if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) {
1027                                        dereferenceOperator = funcDecl;
1028                                }
1029                        }
1030                }
1031        }
[51b7345]1032} // namespace SymTab
[0dd3a2f]1033
1034// Local Variables: //
1035// tab-width: 4 //
1036// mode: c++ //
1037// compile-command: "make install" //
1038// End: //
Note: See TracBrowser for help on using the repository browser.