source: src/SymTab/Validate.cc @ 636e1b9

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 636e1b9 was ac3362c, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Resolve enumerator initializers early to allow other passes to determine if expression is constexpr and to evaluate constexprs

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