source: src/SymTab/Validate.cc @ 69918cea

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

Add new EliminateTypedef? pass that just removes typedefs from AST

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