source: src/SymTab/Validate.cc @ e5ea867

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since e5ea867 was 2a6292d, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Resolve with expressions earlier to ensure new local variables are present before other user-code is resolved

  • Property mode set to 100644
File size: 52.6 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
[25fcb84]50#include "ControlStruct/Mutate.h"      // for ForExprMutator
[30f9072]51#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
[d180746]52#include "Common/ScopedMap.h"          // for ScopedMap
[30f9072]53#include "Common/SemanticError.h"      // for SemanticError
54#include "Common/UniqueName.h"         // for UniqueName
55#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
[be9288a]56#include "Concurrency/Keywords.h"      // for applyKeywords
[30f9072]57#include "FixFunction.h"               // for FixFunction
58#include "Indexer.h"                   // for Indexer
[8b11840]59#include "InitTweak/GenInit.h"         // for fixReturnStatements
[d180746]60#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
61#include "Parser/LinkageSpec.h"        // for C
62#include "ResolvExpr/typeops.h"        // for typesCompatible
[4934ea3]63#include "ResolvExpr/Resolver.h"       // for findSingleExpression
[2b79a70]64#include "ResolvExpr/ResolveTypeof.h"  // for resolveTypeof
[be9288a]65#include "SymTab/Autogen.h"            // for SizeType
66#include "SynTree/Attribute.h"         // for noAttributes, Attribute
[30f9072]67#include "SynTree/Constant.h"          // for Constant
[d180746]68#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
69#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
70#include "SynTree/Initializer.h"       // for ListInit, Initializer
71#include "SynTree/Label.h"             // for operator==, Label
72#include "SynTree/Mutator.h"           // for Mutator
73#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
74#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
75#include "SynTree/Visitor.h"           // for Visitor
[fd2debf]76#include "Validate/HandleAttributes.h" // for handleAttributes
[d180746]77
78class CompoundStmt;
79class ReturnStmt;
80class SwitchStmt;
[51b7345]81
[b16923d]82#define debugPrint( x ) if ( doDebug ) x
[51b7345]83
84namespace SymTab {
[15f5c5e]85        /// hoists declarations that are difficult to hoist while parsing
86        struct HoistTypeDecls final : public WithDeclsToAdd {
[29f9e20]87                void previsit( SizeofExpr * );
88                void previsit( AlignofExpr * );
89                void previsit( UntypedOffsetofExpr * );
[95d09bdb]90                void previsit( CompoundLiteralExpr * );
[29f9e20]91                void handleType( Type * );
92        };
93
[a12c81f3]94        struct FixQualifiedTypes final : public WithIndexer {
95                Type * postmutate( QualifiedType * );
96        };
97
[a09e45b]98        struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
[82dd287]99                /// Flattens nested struct types
[0dd3a2f]100                static void hoistStruct( std::list< Declaration * > &translationUnit );
[9cb8e88d]101
[a09e45b]102                void previsit( StructDecl * aggregateDecl );
103                void previsit( UnionDecl * aggregateDecl );
[0f40912]104                void previsit( StaticAssertDecl * assertDecl );
[d419d8e]105                void previsit( StructInstType * type );
106                void previsit( UnionInstType * type );
107                void previsit( EnumInstType * type );
[9cb8e88d]108
[a08ba92]109          private:
[0dd3a2f]110                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
[c8ffe20b]111
[bdad6eb7]112                AggregateDecl * parentAggr = nullptr;
[a08ba92]113        };
[c8ffe20b]114
[cce9429]115        /// Fix return types so that every function returns exactly one value
[d24d4e1]116        struct ReturnTypeFixer {
[cce9429]117                static void fix( std::list< Declaration * > &translationUnit );
118
[0db6fc0]119                void postvisit( FunctionDecl * functionDecl );
120                void postvisit( FunctionType * ftype );
[cce9429]121        };
122
[de91427b]123        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
[d24d4e1]124        struct EnumAndPointerDecay {
[06edda0]125                void previsit( EnumDecl *aggregateDecl );
126                void previsit( FunctionType *func );
[a08ba92]127        };
[82dd287]128
129        /// Associates forward declarations of aggregates with their definitions
[afcb0a3]130        struct LinkReferenceToTypes final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes>, public WithShortCircuiting {
[522363e]131                LinkReferenceToTypes( const Indexer *indexer );
132                void postvisit( TypeInstType *typeInst );
[be9036d]133
[522363e]134                void postvisit( EnumInstType *enumInst );
135                void postvisit( StructInstType *structInst );
136                void postvisit( UnionInstType *unionInst );
137                void postvisit( TraitInstType *traitInst );
[afcb0a3]138                void previsit( QualifiedType * qualType );
139                void postvisit( QualifiedType * qualType );
[be9036d]140
[522363e]141                void postvisit( EnumDecl *enumDecl );
142                void postvisit( StructDecl *structDecl );
143                void postvisit( UnionDecl *unionDecl );
144                void postvisit( TraitDecl * traitDecl );
[be9036d]145
[b95fe40]146                void previsit( StructDecl *structDecl );
147                void previsit( UnionDecl *unionDecl );
148
149                void renameGenericParams( std::list< TypeDecl * > & params );
150
[06edda0]151          private:
[522363e]152                const Indexer *local_indexer;
[9cb8e88d]153
[c0aa336]154                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
[0dd3a2f]155                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
156                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
[c0aa336]157                ForwardEnumsType forwardEnums;
[0dd3a2f]158                ForwardStructsType forwardStructs;
159                ForwardUnionsType forwardUnions;
[b95fe40]160                /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
161                bool inGeneric = false;
[a08ba92]162        };
[c8ffe20b]163
[06edda0]164        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
[522363e]165        struct ForallPointerDecay final {
[8b11840]166                void previsit( ObjectDecl * object );
167                void previsit( FunctionDecl * func );
[bbf3fda]168                void previsit( FunctionType * ftype );
[bd7e609]169                void previsit( StructDecl * aggrDecl );
170                void previsit( UnionDecl * aggrDecl );
[a08ba92]171        };
[c8ffe20b]172
[d24d4e1]173        struct ReturnChecker : public WithGuards {
[de91427b]174                /// Checks that return statements return nothing if their return type is void
175                /// and return something if the return type is non-void.
176                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
177
[0db6fc0]178                void previsit( FunctionDecl * functionDecl );
179                void previsit( ReturnStmt * returnStmt );
[de91427b]180
[0db6fc0]181                typedef std::list< DeclarationWithType * > ReturnVals;
182                ReturnVals returnVals;
[de91427b]183        };
184
[48ed81c]185        struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
186                ReplaceTypedef() : scopeLevel( 0 ) {}
[de91427b]187                /// Replaces typedefs by forward declarations
[48ed81c]188                static void replaceTypedef( std::list< Declaration * > &translationUnit );
[85c4ef0]189
[48ed81c]190                void premutate( QualifiedType * );
191                Type * postmutate( QualifiedType * qualType );
[a506df4]192                Type * postmutate( TypeInstType * aggregateUseType );
193                Declaration * postmutate( TypedefDecl * typeDecl );
194                void premutate( TypeDecl * typeDecl );
195                void premutate( FunctionDecl * funcDecl );
196                void premutate( ObjectDecl * objDecl );
197                DeclarationWithType * postmutate( ObjectDecl * objDecl );
198
199                void premutate( CastExpr * castExpr );
200
201                void premutate( CompoundStmt * compoundStmt );
202
203                void premutate( StructDecl * structDecl );
204                void premutate( UnionDecl * unionDecl );
205                void premutate( EnumDecl * enumDecl );
[0bcc2b7]206                void premutate( TraitDecl * );
[a506df4]207
[1f370451]208                void premutate( FunctionType * ftype );
209
[a506df4]210          private:
[45161b4d]211                template<typename AggDecl>
212                void addImplicitTypedef( AggDecl * aggDecl );
[48ed81c]213                template< typename AggDecl >
214                void handleAggregate( AggDecl * aggr );
[70a06f6]215
[46f6134]216                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
[e491159]217                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
[0bcc2b7]218                typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
[cc79d97]219                TypedefMap typedefNames;
[679864e1]220                TypeDeclMap typedeclNames;
[cc79d97]221                int scopeLevel;
[1f370451]222                bool inFunctionType = false;
[a08ba92]223        };
[c8ffe20b]224
[69918cea]225        struct EliminateTypedef {
226                /// removes TypedefDecls from the AST
227                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
228
229                template<typename AggDecl>
230                void handleAggregate( AggDecl *aggregateDecl );
231
232                void previsit( StructDecl * aggregateDecl );
233                void previsit( UnionDecl * aggregateDecl );
234                void previsit( CompoundStmt * compoundStmt );
235        };
236
[d24d4e1]237        struct VerifyCtorDtorAssign {
[d1969a6]238                /// ensure that constructors, destructors, and assignment have at least one
239                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
[9cb8e88d]240                /// return values.
241                static void verify( std::list< Declaration * > &translationUnit );
242
[0db6fc0]243                void previsit( FunctionDecl *funcDecl );
[5f98ce5]244        };
[70a06f6]245
[11ab8ea8]246        /// ensure that generic types have the correct number of type arguments
[d24d4e1]247        struct ValidateGenericParameters {
[0db6fc0]248                void previsit( StructInstType * inst );
249                void previsit( UnionInstType * inst );
[5f98ce5]250        };
[70a06f6]251
[2b79a70]252        struct FixObjectType : public WithIndexer {
253                /// resolves typeof type in object, function, and type declarations
254                static void fix( std::list< Declaration * > & translationUnit );
255
256                void previsit( ObjectDecl * );
257                void previsit( FunctionDecl * );
258                void previsit( TypeDecl * );
259        };
260
[4934ea3]261        struct ArrayLength : public WithIndexer {
[fbd7ad6]262                /// for array types without an explicit length, compute the length and store it so that it
263                /// is known to the rest of the phases. For example,
264                ///   int x[] = { 1, 2, 3 };
265                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
266                /// here x and y are known at compile-time to have length 3, so change this into
267                ///   int x[3] = { 1, 2, 3 };
268                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
269                static void computeLength( std::list< Declaration * > & translationUnit );
270
[0db6fc0]271                void previsit( ObjectDecl * objDecl );
[4934ea3]272                void previsit( ArrayType * arrayType );
[fbd7ad6]273        };
274
[d24d4e1]275        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
[68fe077a]276                Type::StorageClasses storageClasses;
[630a82a]277
[d24d4e1]278                void premutate( ObjectDecl *objectDecl );
279                Expression * postmutate( CompoundLiteralExpr *compLitExpr );
[9cb8e88d]280        };
281
[5809461]282        struct LabelAddressFixer final : public WithGuards {
283                std::set< Label > labels;
284
285                void premutate( FunctionDecl * funcDecl );
286                Expression * postmutate( AddressExpr * addrExpr );
287        };
[4fbdfae0]288
289        FunctionDecl * dereferenceOperator = nullptr;
290        struct FindSpecialDeclarations final {
291                void previsit( FunctionDecl * funcDecl );
292        };
293
[522363e]294        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
[06edda0]295                PassVisitor<EnumAndPointerDecay> epc;
[522363e]296                PassVisitor<LinkReferenceToTypes> lrt( nullptr );
297                PassVisitor<ForallPointerDecay> fpd;
[d24d4e1]298                PassVisitor<CompoundLiteral> compoundliteral;
[0db6fc0]299                PassVisitor<ValidateGenericParameters> genericParams;
[4fbdfae0]300                PassVisitor<FindSpecialDeclarations> finder;
[5809461]301                PassVisitor<LabelAddressFixer> labelAddrFixer;
[15f5c5e]302                PassVisitor<HoistTypeDecls> hoistDecls;
[a12c81f3]303                PassVisitor<FixQualifiedTypes> fixQual;
[630a82a]304
[15f5c5e]305                acceptAll( translationUnit, hoistDecls );
[48ed81c]306                ReplaceTypedef::replaceTypedef( translationUnit );
[cce9429]307                ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
[8e0147a]308                acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes because it is an indexer and needs correct types for mangling
[861799c]309                acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
[a12c81f3]310                mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes, because aggregate members are accessed
[29f9e20]311                HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
[69918cea]312                EliminateTypedef::eliminateTypedef( translationUnit ); //
[11ab8ea8]313                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes
[ed8a0d2]314                VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
[bd7e609]315                ReturnChecker::checkFunctionReturns( translationUnit );
316                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
[bcda04c]317                Concurrency::applyKeywords( translationUnit );
[bd7e609]318                acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
[25fcb84]319                ControlStruct::hoistControlDecls( translationUnit );  // hoist initialization out of for statements; must happen before autogenerateRoutines
[06edda0]320                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
[bcda04c]321                Concurrency::implementMutexFuncs( translationUnit );
322                Concurrency::implementThreadStarter( translationUnit );
[d24d4e1]323                mutateAll( translationUnit, compoundliteral );
[2a6292d]324                ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables
[2b79a70]325                FixObjectType::fix( translationUnit );
[fbd7ad6]326                ArrayLength::computeLength( translationUnit );
[bd7e609]327                acceptAll( translationUnit, finder ); // xxx - remove this pass soon
[5809461]328                mutateAll( translationUnit, labelAddrFixer );
[fd2debf]329                Validate::handleAttributes( translationUnit );
[a08ba92]330        }
[9cb8e88d]331
[a08ba92]332        void validateType( Type *type, const Indexer *indexer ) {
[06edda0]333                PassVisitor<EnumAndPointerDecay> epc;
[522363e]334                PassVisitor<LinkReferenceToTypes> lrt( indexer );
335                PassVisitor<ForallPointerDecay> fpd;
[bda58ad]336                type->accept( epc );
[cce9429]337                type->accept( lrt );
[06edda0]338                type->accept( fpd );
[a08ba92]339        }
[c8ffe20b]340
[29f9e20]341
[15f5c5e]342        void HoistTypeDecls::handleType( Type * type ) {
[29f9e20]343                // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
344                AggregateDecl * aggr = nullptr;
345                if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
346                        aggr = inst->baseStruct;
347                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
348                        aggr = inst->baseUnion;
349                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
350                        aggr = inst->baseEnum;
351                }
352                if ( aggr && aggr->body ) {
353                        declsToAddBefore.push_front( aggr );
354                }
355        }
356
[15f5c5e]357        void HoistTypeDecls::previsit( SizeofExpr * expr ) {
[29f9e20]358                handleType( expr->type );
359        }
360
[15f5c5e]361        void HoistTypeDecls::previsit( AlignofExpr * expr ) {
[29f9e20]362                handleType( expr->type );
363        }
364
[15f5c5e]365        void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
[29f9e20]366                handleType( expr->type );
367        }
368
[95d09bdb]369        void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
370                handleType( expr->result );
371        }
372
[29f9e20]373
[a12c81f3]374        Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
375                Type * parent = qualType->parent;
376                Type * child = qualType->child;
377                if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
378                        // .T => lookup T at global scope
[062e8df]379                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
[a12c81f3]380                                auto td = indexer.globalLookupType( inst->name );
[062e8df]381                                if ( ! td ) {
382                                        SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
383                                }
[a12c81f3]384                                auto base = td->base;
[062e8df]385                                assert( base );
[8a3ecb9]386                                Type * ret = base->clone();
387                                ret->get_qualifiers() = qualType->get_qualifiers();
388                                return ret;
[a12c81f3]389                        } else {
[062e8df]390                                // .T => T is not a type name
391                                assertf( false, "unhandled global qualified child type: %s", toCString(child) );
[a12c81f3]392                        }
393                } else {
394                        // S.T => S must be an aggregate type, find the declaration for T in S.
395                        AggregateDecl * aggr = nullptr;
396                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
397                                aggr = inst->baseStruct;
398                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
399                                aggr = inst->baseUnion;
400                        } else {
[062e8df]401                                SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
[a12c81f3]402                        }
403                        assert( aggr ); // TODO: need to handle forward declarations
404                        for ( Declaration * member : aggr->members ) {
405                                if ( StructInstType * inst = dynamic_cast< StructInstType * >( child ) ) {
406                                        if ( StructDecl * aggr = dynamic_cast< StructDecl * >( member ) ) {
407                                                if ( aggr->name == inst->name ) {
[8a3ecb9]408                                                        // TODO: is this case, and other non-TypeInstType cases, necessary?
[a12c81f3]409                                                        return new StructInstType( qualType->get_qualifiers(), aggr );
410                                                }
411                                        }
412                                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( child ) ) {
413                                        if ( UnionDecl * aggr = dynamic_cast< UnionDecl * > ( member ) ) {
414                                                if ( aggr->name == inst->name ) {
415                                                        return new UnionInstType( qualType->get_qualifiers(), aggr );
416                                                }
417                                        }
418                                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( child ) ) {
419                                        if ( EnumDecl * aggr = dynamic_cast< EnumDecl * > ( member ) ) {
420                                                if ( aggr->name == inst->name ) {
421                                                        return new EnumInstType( qualType->get_qualifiers(), aggr );
422                                                }
423                                        }
424                                } else if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
[8a3ecb9]425                                        // name on the right is a typedef
[a12c81f3]426                                        if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
427                                                if ( aggr->name == inst->name ) {
[062e8df]428                                                        assert( aggr->base );
[8a3ecb9]429                                                        Type * ret = aggr->base->clone();
430                                                        ret->get_qualifiers() = qualType->get_qualifiers();
431                                                        return ret;
[a12c81f3]432                                                }
433                                        }
434                                } else {
435                                        // S.T - S is not an aggregate => error
436                                        assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
437                                }
438                        }
439                        // failed to find a satisfying definition of type
[062e8df]440                        SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
[a12c81f3]441                }
442
443                // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
444        }
445
446
[a08ba92]447        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
[a09e45b]448                PassVisitor<HoistStruct> hoister;
449                acceptAll( translationUnit, hoister );
[a08ba92]450        }
[c8ffe20b]451
[0f40912]452        bool shouldHoist( Declaration *decl ) {
453                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
[a08ba92]454        }
[c0aa336]455
[d419d8e]456        namespace {
457                void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
458                        if ( aggr->parent ) qualifiedName( aggr->parent, ss );
459                        ss << "__" << aggr->name;
460                }
461
462                // mangle nested type names using entire parent chain
463                std::string qualifiedName( AggregateDecl * aggr ) {
464                        std::ostringstream ss;
465                        qualifiedName( aggr, ss );
466                        return ss.str();
467                }
468        }
469
[a08ba92]470        template< typename AggDecl >
471        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
[bdad6eb7]472                if ( parentAggr ) {
[d419d8e]473                        aggregateDecl->parent = parentAggr;
474                        aggregateDecl->name = qualifiedName( aggregateDecl );
[0dd3a2f]475                        // Add elements in stack order corresponding to nesting structure.
[a09e45b]476                        declsToAddBefore.push_front( aggregateDecl );
[0dd3a2f]477                } else {
[bdad6eb7]478                        GuardValue( parentAggr );
479                        parentAggr = aggregateDecl;
[0dd3a2f]480                } // if
481                // Always remove the hoisted aggregate from the inner structure.
[0f40912]482                GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
[a08ba92]483        }
[c8ffe20b]484
[0f40912]485        void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
486                if ( parentAggr ) {
487                        declsToAddBefore.push_back( assertDecl );
488                }
489        }
490
[a09e45b]491        void HoistStruct::previsit( StructDecl * aggregateDecl ) {
[0dd3a2f]492                handleAggregate( aggregateDecl );
[a08ba92]493        }
[c8ffe20b]494
[a09e45b]495        void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
[0dd3a2f]496                handleAggregate( aggregateDecl );
[a08ba92]497        }
[c8ffe20b]498
[d419d8e]499        void HoistStruct::previsit( StructInstType * type ) {
500                // need to reset type name after expanding to qualified name
501                assert( type->baseStruct );
502                type->name = type->baseStruct->name;
503        }
504
505        void HoistStruct::previsit( UnionInstType * type ) {
506                assert( type->baseUnion );
507                type->name = type->baseUnion->name;
508        }
509
510        void HoistStruct::previsit( EnumInstType * type ) {
511                assert( type->baseEnum );
512                type->name = type->baseEnum->name;
513        }
514
515
[69918cea]516        bool isTypedef( Declaration *decl ) {
517                return dynamic_cast< TypedefDecl * >( decl );
518        }
519
520        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
521                PassVisitor<EliminateTypedef> eliminator;
522                acceptAll( translationUnit, eliminator );
523                filter( translationUnit, isTypedef, true );
524        }
525
526        template< typename AggDecl >
527        void EliminateTypedef::handleAggregate( AggDecl *aggregateDecl ) {
528                filter( aggregateDecl->members, isTypedef, true );
529        }
530
531        void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
532                handleAggregate( aggregateDecl );
533        }
534
535        void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
536                handleAggregate( aggregateDecl );
537        }
538
539        void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
540                // remove and delete decl stmts
541                filter( compoundStmt->kids, [](Statement * stmt) {
542                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
543                                if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
544                                        return true;
545                                } // if
546                        } // if
547                        return false;
548                }, true);
549        }
550
[06edda0]551        void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
[0dd3a2f]552                // Set the type of each member of the enumeration to be EnumConstant
[0b3b2ae]553                for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
[f6d7e0f]554                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
[0dd3a2f]555                        assert( obj );
[0b3b2ae]556                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
[0dd3a2f]557                } // for
[a08ba92]558        }
[51b7345]559
[a08ba92]560        namespace {
[83de11e]561                template< typename DWTList >
[4bda2cf]562                void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
563                        auto nvals = dwts.size();
564                        bool containsVoid = false;
565                        for ( auto & dwt : dwts ) {
566                                // fix each DWT and record whether a void was found
567                                containsVoid |= fixFunction( dwt );
568                        }
569
570                        // the only case in which "void" is valid is where it is the only one in the list
571                        if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
[a16764a6]572                                SemanticError( func, "invalid type void in function type " );
[4bda2cf]573                        }
574
575                        // one void is the only thing in the list; remove it.
576                        if ( containsVoid ) {
577                                delete dwts.front();
578                                dwts.clear();
579                        }
[0dd3a2f]580                }
[a08ba92]581        }
[c8ffe20b]582
[06edda0]583        void EnumAndPointerDecay::previsit( FunctionType *func ) {
[0dd3a2f]584                // Fix up parameters and return types
[4bda2cf]585                fixFunctionList( func->parameters, func->isVarArgs, func );
586                fixFunctionList( func->returnVals, false, func );
[a08ba92]587        }
[c8ffe20b]588
[522363e]589        LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) {
[0dd3a2f]590                if ( other_indexer ) {
[522363e]591                        local_indexer = other_indexer;
[0dd3a2f]592                } else {
[522363e]593                        local_indexer = &indexer;
[0dd3a2f]594                } // if
[a08ba92]595        }
[c8ffe20b]596
[522363e]597        void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) {
[eaa6430]598                EnumDecl *st = local_indexer->lookupEnum( enumInst->name );
[c0aa336]599                // it's not a semantic error if the enum is not found, just an implicit forward declaration
600                if ( st ) {
[eaa6430]601                        enumInst->baseEnum = st;
[c0aa336]602                } // if
[29f9e20]603                if ( ! st || ! st->body ) {
[c0aa336]604                        // use of forward declaration
[eaa6430]605                        forwardEnums[ enumInst->name ].push_back( enumInst );
[c0aa336]606                } // if
607        }
608
[48fa824]609        void checkGenericParameters( ReferenceToType * inst ) {
610                for ( Expression * param : inst->parameters ) {
611                        if ( ! dynamic_cast< TypeExpr * >( param ) ) {
[a16764a6]612                                SemanticError( inst, "Expression parameters for generic types are currently unsupported: " );
[48fa824]613                        }
614                }
615        }
616
[522363e]617        void LinkReferenceToTypes::postvisit( StructInstType *structInst ) {
[eaa6430]618                StructDecl *st = local_indexer->lookupStruct( structInst->name );
[0dd3a2f]619                // it's not a semantic error if the struct is not found, just an implicit forward declaration
620                if ( st ) {
[eaa6430]621                        structInst->baseStruct = st;
[0dd3a2f]622                } // if
[29f9e20]623                if ( ! st || ! st->body ) {
[0dd3a2f]624                        // use of forward declaration
[eaa6430]625                        forwardStructs[ structInst->name ].push_back( structInst );
[0dd3a2f]626                } // if
[48fa824]627                checkGenericParameters( structInst );
[a08ba92]628        }
[c8ffe20b]629
[522363e]630        void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) {
[eaa6430]631                UnionDecl *un = local_indexer->lookupUnion( unionInst->name );
[0dd3a2f]632                // it's not a semantic error if the union is not found, just an implicit forward declaration
633                if ( un ) {
[eaa6430]634                        unionInst->baseUnion = un;
[0dd3a2f]635                } // if
[29f9e20]636                if ( ! un || ! un->body ) {
[0dd3a2f]637                        // use of forward declaration
[eaa6430]638                        forwardUnions[ unionInst->name ].push_back( unionInst );
[0dd3a2f]639                } // if
[48fa824]640                checkGenericParameters( unionInst );
[a08ba92]641        }
[c8ffe20b]642
[afcb0a3]643        void LinkReferenceToTypes::previsit( QualifiedType * ) {
644                visit_children = false;
645        }
646
647        void LinkReferenceToTypes::postvisit( QualifiedType * qualType ) {
648                // linking only makes sense for the 'oldest ancestor' of the qualified type
649                qualType->parent->accept( *visitor );
650        }
651
[be9036d]652        template< typename Decl >
653        void normalizeAssertions( std::list< Decl * > & assertions ) {
654                // ensure no duplicate trait members after the clone
655                auto pred = [](Decl * d1, Decl * d2) {
656                        // only care if they're equal
657                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
658                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
659                        if ( dwt1 && dwt2 ) {
[eaa6430]660                                if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
[be9036d]661                                        // std::cerr << "=========== equal:" << std::endl;
662                                        // std::cerr << "d1: " << d1 << std::endl;
663                                        // std::cerr << "d2: " << d2 << std::endl;
664                                        return false;
665                                }
[2c57025]666                        }
[be9036d]667                        return d1 < d2;
668                };
669                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
670                // if ( unique_members.size() != assertions.size() ) {
671                //      std::cerr << "============different" << std::endl;
672                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
673                // }
674
675                std::list< Decl * > order;
676                order.splice( order.end(), assertions );
677                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
678                        return unique_members.count( decl );
679                });
680        }
681
682        // expand assertions from trait instance, performing the appropriate type variable substitutions
683        template< typename Iterator >
684        void expandAssertions( TraitInstType * inst, Iterator out ) {
[eaa6430]685                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
[be9036d]686                std::list< DeclarationWithType * > asserts;
687                for ( Declaration * decl : inst->baseTrait->members ) {
[e3e16bc]688                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
[2c57025]689                }
[be9036d]690                // substitute trait decl parameters for instance parameters
691                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
692        }
693
[522363e]694        void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) {
[be9036d]695                if ( traitDecl->name == "sized" ) {
696                        // "sized" is a special trait - flick the sized status on for the type variable
697                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
698                        TypeDecl * td = traitDecl->parameters.front();
699                        td->set_sized( true );
700                }
701
702                // move assertions from type parameters into the body of the trait
703                for ( TypeDecl * td : traitDecl->parameters ) {
704                        for ( DeclarationWithType * assert : td->assertions ) {
705                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
706                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
707                                } else {
708                                        traitDecl->members.push_back( assert->clone() );
709                                }
710                        }
711                        deleteAll( td->assertions );
712                        td->assertions.clear();
713                } // for
714        }
[2ae171d8]715
[522363e]716        void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) {
[2ae171d8]717                // handle other traits
[522363e]718                TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name );
[4a9ccc3]719                if ( ! traitDecl ) {
[a16764a6]720                        SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
[17cd4eb]721                } // if
[0b3b2ae]722                if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
[a16764a6]723                        SemanticError( traitInst, "incorrect number of trait parameters: " );
[4a9ccc3]724                } // if
[be9036d]725                traitInst->baseTrait = traitDecl;
[79970ed]726
[4a9ccc3]727                // need to carry over the 'sized' status of each decl in the instance
[eaa6430]728                for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
[5c4d27f]729                        TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
730                        if ( ! expr ) {
[a16764a6]731                                SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
[5c4d27f]732                        }
[4a9ccc3]733                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
734                                TypeDecl * formalDecl = std::get<0>(p);
[eaa6430]735                                TypeDecl * instDecl = inst->baseType;
[4a9ccc3]736                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
737                        }
738                }
[be9036d]739                // normalizeAssertions( traitInst->members );
[a08ba92]740        }
[c8ffe20b]741
[522363e]742        void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) {
[c0aa336]743                // visit enum members first so that the types of self-referencing members are updated properly
[b16923d]744                if ( enumDecl->body ) {
[eaa6430]745                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
[c0aa336]746                        if ( fwds != forwardEnums.end() ) {
747                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
[eaa6430]748                                        (*inst)->baseEnum = enumDecl;
[c0aa336]749                                } // for
750                                forwardEnums.erase( fwds );
751                        } // if
[ac3362c]752
753                        for ( Declaration * member : enumDecl->members ) {
754                                ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member );
755                                if ( field->init ) {
756                                        // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information.
757                                        SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init );
758                                        ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
759                                }
760                        }
[c0aa336]761                } // if
762        }
763
[b95fe40]764        void LinkReferenceToTypes::renameGenericParams( std::list< TypeDecl * > & params ) {
765                // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
766                //   forall(otype T)
767                //   struct Box {
768                //     T x;
769                //   };
770                //   forall(otype T)
771                //   void f(Box(T) b) {
772                //     ...
773                //   }
774                // The T in Box and the T in f are different, so internally the naming must reflect that.
775                GuardValue( inGeneric );
776                inGeneric = ! params.empty();
777                for ( TypeDecl * td : params ) {
778                        td->name = "__" + td->name + "_generic_";
779                }
780        }
781
782        void LinkReferenceToTypes::previsit( StructDecl * structDecl ) {
783                renameGenericParams( structDecl->parameters );
784        }
785
786        void LinkReferenceToTypes::previsit( UnionDecl * unionDecl ) {
787                renameGenericParams( unionDecl->parameters );
788        }
789
[522363e]790        void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) {
[677c1be]791                // visit struct members first so that the types of self-referencing members are updated properly
[522363e]792                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
[b16923d]793                if ( structDecl->body ) {
[eaa6430]794                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
[0dd3a2f]795                        if ( fwds != forwardStructs.end() ) {
796                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
[eaa6430]797                                        (*inst)->baseStruct = structDecl;
[0dd3a2f]798                                } // for
799                                forwardStructs.erase( fwds );
800                        } // if
801                } // if
[a08ba92]802        }
[c8ffe20b]803
[522363e]804        void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) {
[b16923d]805                if ( unionDecl->body ) {
[eaa6430]806                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
[0dd3a2f]807                        if ( fwds != forwardUnions.end() ) {
808                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
[eaa6430]809                                        (*inst)->baseUnion = unionDecl;
[0dd3a2f]810                                } // for
811                                forwardUnions.erase( fwds );
812                        } // if
813                } // if
[a08ba92]814        }
[c8ffe20b]815
[522363e]816        void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) {
[b95fe40]817                // ensure generic parameter instances are renamed like the base type
818                if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
[eaa6430]819                if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
[0dd3a2f]820                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
821                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
822                        } // if
823                } // if
[a08ba92]824        }
[c8ffe20b]825
[4a9ccc3]826        /// Fix up assertions - flattens assertion lists, removing all trait instances
[8b11840]827        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
828                for ( TypeDecl * type : forall ) {
[be9036d]829                        std::list< DeclarationWithType * > asserts;
830                        asserts.splice( asserts.end(), type->assertions );
831                        // expand trait instances into their members
832                        for ( DeclarationWithType * assertion : asserts ) {
833                                if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
834                                        // expand trait instance into all of its members
835                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
836                                        delete traitInst;
837                                } else {
838                                        // pass other assertions through
839                                        type->assertions.push_back( assertion );
840                                } // if
841                        } // for
842                        // apply FixFunction to every assertion to check for invalid void type
843                        for ( DeclarationWithType *& assertion : type->assertions ) {
[4bda2cf]844                                bool isVoid = fixFunction( assertion );
845                                if ( isVoid ) {
[a16764a6]846                                        SemanticError( node, "invalid type void in assertion of function " );
[be9036d]847                                } // if
848                        } // for
849                        // normalizeAssertions( type->assertions );
[0dd3a2f]850                } // for
[a08ba92]851        }
[c8ffe20b]852
[522363e]853        void ForallPointerDecay::previsit( ObjectDecl *object ) {
[3d2b7bc]854                // ensure that operator names only apply to functions or function pointers
855                if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
856                        SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
857                }
[0dd3a2f]858                object->fixUniqueId();
[a08ba92]859        }
[c8ffe20b]860
[522363e]861        void ForallPointerDecay::previsit( FunctionDecl *func ) {
[0dd3a2f]862                func->fixUniqueId();
[a08ba92]863        }
[c8ffe20b]864
[bbf3fda]865        void ForallPointerDecay::previsit( FunctionType * ftype ) {
866                forallFixer( ftype->forall, ftype );
867        }
868
[bd7e609]869        void ForallPointerDecay::previsit( StructDecl * aggrDecl ) {
870                forallFixer( aggrDecl->parameters, aggrDecl );
871        }
872
873        void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) {
874                forallFixer( aggrDecl->parameters, aggrDecl );
875        }
876
[de91427b]877        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
[0db6fc0]878                PassVisitor<ReturnChecker> checker;
[de91427b]879                acceptAll( translationUnit, checker );
880        }
881
[0db6fc0]882        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
[0508ab3]883                GuardValue( returnVals );
[de91427b]884                returnVals = functionDecl->get_functionType()->get_returnVals();
885        }
886
[0db6fc0]887        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
[74d1804]888                // Previously this also checked for the existence of an expr paired with no return values on
889                // the  function return type. This is incorrect, since you can have an expression attached to
890                // a return statement in a void-returning function in C. The expression is treated as if it
891                // were cast to void.
[30f9072]892                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
[a16764a6]893                        SemanticError( returnStmt, "Non-void function returns no values: " );
[de91427b]894                }
895        }
896
897
[48ed81c]898        void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
899                PassVisitor<ReplaceTypedef> eliminator;
[0dd3a2f]900                mutateAll( translationUnit, eliminator );
[a506df4]901                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
[5f98ce5]902                        // grab and remember declaration of size_t
[0b3b2ae]903                        SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
[5f98ce5]904                } else {
[40e636a]905                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
906                        // eventually should have a warning for this case.
907                        SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
[5f98ce5]908                }
[a08ba92]909        }
[c8ffe20b]910
[48ed81c]911        void ReplaceTypedef::premutate( QualifiedType * ) {
912                visit_children = false;
913        }
914
915        Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
916                // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
917                qualType->parent = qualType->parent->acceptMutator( *visitor );
918                return qualType;
919        }
920
921        Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
[9cb8e88d]922                // instances of typedef types will come here. If it is an instance
[cc79d97]923                // of a typdef type, link the instance to its actual type.
[0b3b2ae]924                TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
[0dd3a2f]925                if ( def != typedefNames.end() ) {
[f53836b]926                        Type *ret = def->second.first->base->clone();
[e82ef13]927                        ret->location = typeInst->location;
[6f95000]928                        ret->get_qualifiers() |= typeInst->get_qualifiers();
[1f370451]929                        // attributes are not carried over from typedef to function parameters/return values
930                        if ( ! inFunctionType ) {
931                                ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
932                        } else {
933                                deleteAll( ret->attributes );
934                                ret->attributes.clear();
935                        }
[0215a76f]936                        // place instance parameters on the typedef'd type
[f53836b]937                        if ( ! typeInst->parameters.empty() ) {
[0215a76f]938                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
939                                if ( ! rtt ) {
[a16764a6]940                                        SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
[0215a76f]941                                }
[0b3b2ae]942                                rtt->parameters.clear();
[f53836b]943                                cloneAll( typeInst->parameters, rtt->parameters );
944                                mutateAll( rtt->parameters, *visitor );  // recursively fix typedefs on parameters
[1db21619]945                        } // if
[0dd3a2f]946                        delete typeInst;
947                        return ret;
[679864e1]948                } else {
[0b3b2ae]949                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
[062e8df]950                        if ( base == typedeclNames.end() ) {
951                                SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
952                        }
[1e8b02f5]953                        typeInst->set_baseType( base->second );
[062e8df]954                        return typeInst;
[0dd3a2f]955                } // if
[062e8df]956                assert( false );
[a08ba92]957        }
[c8ffe20b]958
[f53836b]959        struct VarLenChecker : WithShortCircuiting {
960                void previsit( FunctionType * ) { visit_children = false; }
961                void previsit( ArrayType * at ) {
962                        isVarLen |= at->isVarLen;
963                }
964                bool isVarLen = false;
965        };
966
967        bool isVariableLength( Type * t ) {
968                PassVisitor<VarLenChecker> varLenChecker;
969                maybeAccept( t, varLenChecker );
970                return varLenChecker.pass.isVarLen;
971        }
972
[48ed81c]973        Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
[0b3b2ae]974                if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
[9cb8e88d]975                        // typedef to the same name from the same scope
[cc79d97]976                        // must be from the same type
977
[0b3b2ae]978                        Type * t1 = tyDecl->base;
979                        Type * t2 = typedefNames[ tyDecl->name ].first->base;
[1cbca6e]980                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
[a16764a6]981                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
[f53836b]982                        }
[4b97770]983                        // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
984                        // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
985                        // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
986                        // to fix this corner case likely outweighs the utility of allowing it.
[f53836b]987                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
[a16764a6]988                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
[85c4ef0]989                        }
[cc79d97]990                } else {
[0b3b2ae]991                        typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
[cc79d97]992                } // if
993
[0dd3a2f]994                // When a typedef is a forward declaration:
995                //    typedef struct screen SCREEN;
996                // the declaration portion must be retained:
997                //    struct screen;
998                // because the expansion of the typedef is:
999                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
1000                // hence the type-name "screen" must be defined.
1001                // Note, qualifiers on the typedef are superfluous for the forward declaration.
[6f95000]1002
[0b3b2ae]1003                Type *designatorType = tyDecl->base->stripDeclarator();
[6f95000]1004                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
[48ed81c]1005                        declsToAddBefore.push_back( new StructDecl( aggDecl->name, DeclarationNode::Struct, noAttributes, tyDecl->linkage ) );
[6f95000]1006                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
[48ed81c]1007                        declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
[6f95000]1008                } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
[48ed81c]1009                        declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage ) );
[0dd3a2f]1010                } // if
[48ed81c]1011                return tyDecl->clone();
[a08ba92]1012        }
[c8ffe20b]1013
[48ed81c]1014        void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
[0b3b2ae]1015                TypedefMap::iterator i = typedefNames.find( typeDecl->name );
[0dd3a2f]1016                if ( i != typedefNames.end() ) {
1017                        typedefNames.erase( i ) ;
1018                } // if
[679864e1]1019
[0bcc2b7]1020                typedeclNames.insert( typeDecl->name, typeDecl );
[a08ba92]1021        }
[c8ffe20b]1022
[48ed81c]1023        void ReplaceTypedef::premutate( FunctionDecl * ) {
[a506df4]1024                GuardScope( typedefNames );
[0bcc2b7]1025                GuardScope( typedeclNames );
[a08ba92]1026        }
[c8ffe20b]1027
[48ed81c]1028        void ReplaceTypedef::premutate( ObjectDecl * ) {
[a506df4]1029                GuardScope( typedefNames );
[0bcc2b7]1030                GuardScope( typedeclNames );
[a506df4]1031        }
[dd020c0]1032
[48ed81c]1033        DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
[0b3b2ae]1034                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
[02e5ab6]1035                        // replace the current object declaration with a function declaration
[0b3b2ae]1036                        FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
1037                        objDecl->attributes.clear();
[dbe8f244]1038                        objDecl->set_type( nullptr );
[0a86a30]1039                        delete objDecl;
1040                        return newDecl;
[1db21619]1041                } // if
[a506df4]1042                return objDecl;
[a08ba92]1043        }
[c8ffe20b]1044
[48ed81c]1045        void ReplaceTypedef::premutate( CastExpr * ) {
[a506df4]1046                GuardScope( typedefNames );
[0bcc2b7]1047                GuardScope( typedeclNames );
[a08ba92]1048        }
[c8ffe20b]1049
[48ed81c]1050        void ReplaceTypedef::premutate( CompoundStmt * ) {
[a506df4]1051                GuardScope( typedefNames );
[0bcc2b7]1052                GuardScope( typedeclNames );
[cc79d97]1053                scopeLevel += 1;
[a506df4]1054                GuardAction( [this](){ scopeLevel -= 1; } );
1055        }
1056
[45161b4d]1057        template<typename AggDecl>
[48ed81c]1058        void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
[45161b4d]1059                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
[62e5546]1060                        Type *type = nullptr;
[45161b4d]1061                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
1062                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
1063                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
1064                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
1065                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
1066                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
1067                        } // if
[0b0f1dd]1068                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
[46f6134]1069                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
[48ed81c]1070                        // add the implicit typedef to the AST
1071                        declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
[45161b4d]1072                } // if
1073        }
[4e06c1e]1074
[48ed81c]1075        template< typename AggDecl >
1076        void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
1077                SemanticErrorException errors;
[a506df4]1078
[48ed81c]1079                ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
1080                ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter  );
1081                declsToAddBefore.clear();
1082                declsToAddAfter.clear();
[a506df4]1083
[48ed81c]1084                GuardScope( typedefNames );
[0bcc2b7]1085                GuardScope( typedeclNames );
[48ed81c]1086                mutateAll( aggr->parameters, *visitor );
[85c4ef0]1087
[48ed81c]1088                // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
1089                for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
1090                        if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
[a506df4]1091
[48ed81c]1092                        try {
1093                                *i = maybeMutate( *i, *visitor );
1094                        } catch ( SemanticErrorException &e ) {
1095                                errors.append( e );
1096                        }
1097
1098                        if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
1099                }
1100
1101                if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
1102                if ( !errors.isEmpty() ) { throw errors; }
[85c4ef0]1103        }
1104
[48ed81c]1105        void ReplaceTypedef::premutate( StructDecl * structDecl ) {
1106                visit_children = false;
1107                addImplicitTypedef( structDecl );
1108                handleAggregate( structDecl );
[a506df4]1109        }
1110
[48ed81c]1111        void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
1112                visit_children = false;
1113                addImplicitTypedef( unionDecl );
1114                handleAggregate( unionDecl );
[85c4ef0]1115        }
1116
[48ed81c]1117        void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
1118                addImplicitTypedef( enumDecl );
[85c4ef0]1119        }
1120
[48ed81c]1121        void ReplaceTypedef::premutate( FunctionType * ) {
[1f370451]1122                GuardValue( inFunctionType );
1123                inFunctionType = true;
1124        }
1125
[0bcc2b7]1126        void ReplaceTypedef::premutate( TraitDecl * ) {
1127                GuardScope( typedefNames );
1128                GuardScope( typedeclNames);
1129        }
1130
[d1969a6]1131        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
[0db6fc0]1132                PassVisitor<VerifyCtorDtorAssign> verifier;
[9cb8e88d]1133                acceptAll( translationUnit, verifier );
1134        }
1135
[0db6fc0]1136        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
[9cb8e88d]1137                FunctionType * funcType = funcDecl->get_functionType();
1138                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1139                std::list< DeclarationWithType * > &params = funcType->get_parameters();
1140
[bff227f]1141                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
[9cb8e88d]1142                        if ( params.size() == 0 ) {
[a16764a6]1143                                SemanticError( funcDecl, "Constructors, destructors, and assignment functions require at least one parameter " );
[9cb8e88d]1144                        }
[ce8c12f]1145                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
[084fecc]1146                        if ( ! refType ) {
[a16764a6]1147                                SemanticError( funcDecl, "First parameter of a constructor, destructor, or assignment function must be a reference " );
[9cb8e88d]1148                        }
[bff227f]1149                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
[a16764a6]1150                                SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " );
[9cb8e88d]1151                        }
1152                }
1153        }
[70a06f6]1154
[11ab8ea8]1155        template< typename Aggr >
1156        void validateGeneric( Aggr * inst ) {
1157                std::list< TypeDecl * > * params = inst->get_baseParameters();
[30f9072]1158                if ( params ) {
[11ab8ea8]1159                        std::list< Expression * > & args = inst->get_parameters();
[67cf18c]1160
1161                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1162                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1163                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1164                        //   vector(int) v;
1165                        // after insertion of default values becomes
1166                        //   vector(int, heap_allocator(T))
1167                        // and the substitution is built with T=int so that after substitution, the result is
1168                        //   vector(int, heap_allocator(int))
1169                        TypeSubstitution sub;
1170                        auto paramIter = params->begin();
1171                        for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
1172                                if ( i < args.size() ) {
[e3e16bc]1173                                        TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
[67cf18c]1174                                        sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
1175                                } else if ( i == args.size() ) {
1176                                        Type * defaultType = (*paramIter)->get_init();
1177                                        if ( defaultType ) {
1178                                                args.push_back( new TypeExpr( defaultType->clone() ) );
1179                                                sub.add( (*paramIter)->get_name(), defaultType->clone() );
1180                                        }
1181                                }
1182                        }
1183
1184                        sub.apply( inst );
[a16764a6]1185                        if ( args.size() < params->size() ) SemanticError( inst, "Too few type arguments in generic type " );
1186                        if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
[11ab8ea8]1187                }
1188        }
1189
[0db6fc0]1190        void ValidateGenericParameters::previsit( StructInstType * inst ) {
[11ab8ea8]1191                validateGeneric( inst );
1192        }
[9cb8e88d]1193
[0db6fc0]1194        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
[11ab8ea8]1195                validateGeneric( inst );
[9cb8e88d]1196        }
[70a06f6]1197
[d24d4e1]1198        void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
[a7c90d4]1199                storageClasses = objectDecl->get_storageClasses();
[630a82a]1200        }
1201
[d24d4e1]1202        Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
[630a82a]1203                // transform [storage_class] ... (struct S){ 3, ... };
1204                // into [storage_class] struct S temp =  { 3, ... };
1205                static UniqueName indexName( "_compLit" );
1206
[d24d4e1]1207                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1208                compLitExpr->set_result( nullptr );
1209                compLitExpr->set_initializer( nullptr );
[630a82a]1210                delete compLitExpr;
[d24d4e1]1211                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1212                return new VariableExpr( tempvar );
[630a82a]1213        }
[cce9429]1214
1215        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
[0db6fc0]1216                PassVisitor<ReturnTypeFixer> fixer;
[cce9429]1217                acceptAll( translationUnit, fixer );
1218        }
1219
[0db6fc0]1220        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
[9facf3b]1221                FunctionType * ftype = functionDecl->get_functionType();
1222                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
[56e49b0]1223                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
[9facf3b]1224                if ( retVals.size() == 1 ) {
[861799c]1225                        // 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).
1226                        // ensure other return values have a name.
[9facf3b]1227                        DeclarationWithType * ret = retVals.front();
1228                        if ( ret->get_name() == "" ) {
1229                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1230                        }
[c6d2e93]1231                        ret->get_attributes().push_back( new Attribute( "unused" ) );
[9facf3b]1232                }
1233        }
[cce9429]1234
[0db6fc0]1235        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
[cce9429]1236                // xxx - need to handle named return values - this information needs to be saved somehow
1237                // so that resolution has access to the names.
1238                // Note that this pass needs to happen early so that other passes which look for tuple types
1239                // find them in all of the right places, including function return types.
1240                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1241                if ( retVals.size() > 1 ) {
1242                        // generate a single return parameter which is the tuple of all of the return values
[e3e16bc]1243                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
[cce9429]1244                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
[68fe077a]1245                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
[cce9429]1246                        deleteAll( retVals );
1247                        retVals.clear();
1248                        retVals.push_back( newRet );
1249                }
1250        }
[fbd7ad6]1251
[2b79a70]1252        void FixObjectType::fix( std::list< Declaration * > & translationUnit ) {
1253                PassVisitor<FixObjectType> fixer;
1254                acceptAll( translationUnit, fixer );
1255        }
1256
1257        void FixObjectType::previsit( ObjectDecl * objDecl ) {
1258                Type *new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer );
1259                new_type->get_qualifiers() -= Type::Lvalue; // even if typeof is lvalue, variable can never have lvalue-qualified type
1260                objDecl->set_type( new_type );
1261        }
1262
1263        void FixObjectType::previsit( FunctionDecl * funcDecl ) {
1264                Type *new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer );
1265                new_type->get_qualifiers() -= Type::Lvalue; // even if typeof is lvalue, variable can never have lvalue-qualified type
1266                funcDecl->set_type( new_type );
1267        }
1268
1269        void FixObjectType::previsit( TypeDecl *typeDecl ) {
1270                if ( typeDecl->get_base() ) {
1271                        Type *new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer );
1272                        new_type->get_qualifiers() -= Type::Lvalue; // even if typeof is lvalue, variable can never have lvalue-qualified type
1273                        typeDecl->set_base( new_type );
1274                } // if
1275        }
1276
[fbd7ad6]1277        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
[0db6fc0]1278                PassVisitor<ArrayLength> len;
[fbd7ad6]1279                acceptAll( translationUnit, len );
1280        }
1281
[0db6fc0]1282        void ArrayLength::previsit( ObjectDecl * objDecl ) {
[0b3b2ae]1283                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
[f072892]1284                        if ( at->dimension ) return;
[0b3b2ae]1285                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
[f072892]1286                                at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
[fbd7ad6]1287                        }
1288                }
1289        }
[4fbdfae0]1290
[4934ea3]1291        void ArrayLength::previsit( ArrayType * type ) {
1292                if ( type->dimension ) {
1293                        // need to resolve array dimensions early so that constructor code can correctly determine
1294                        // if a type is a VLA (and hence whether its elements need to be constructed)
1295                        ResolvExpr::findSingleExpression( type->dimension, SymTab::SizeType->clone(), indexer );
1296
1297                        // must re-evaluate whether a type is a VLA, now that more information is available
1298                        // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1299                        type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
1300                }
1301        }
1302
[5809461]1303        struct LabelFinder {
1304                std::set< Label > & labels;
1305                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1306                void previsit( Statement * stmt ) {
1307                        for ( Label & l : stmt->labels ) {
1308                                labels.insert( l );
1309                        }
1310                }
1311        };
1312
1313        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1314                GuardValue( labels );
1315                PassVisitor<LabelFinder> finder( labels );
1316                funcDecl->accept( finder );
1317        }
1318
1319        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1320                // convert &&label into label address
1321                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1322                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1323                                if ( labels.count( nameExpr->name ) ) {
1324                                        Label name = nameExpr->name;
1325                                        delete addrExpr;
1326                                        return new LabelAddressExpr( name );
1327                                }
1328                        }
1329                }
1330                return addrExpr;
1331        }
1332
[4fbdfae0]1333        void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) {
1334                if ( ! dereferenceOperator ) {
1335                        if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) {
1336                                FunctionType * ftype = funcDecl->get_functionType();
1337                                if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) {
1338                                        dereferenceOperator = funcDecl;
1339                                }
1340                        }
1341                }
1342        }
[51b7345]1343} // namespace SymTab
[0dd3a2f]1344
1345// Local Variables: //
1346// tab-width: 4 //
1347// mode: c++ //
1348// compile-command: "make install" //
1349// End: //
Note: See TracBrowser for help on using the repository browser.