source: src/SymTab/Validate.cc @ 7c782af

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

Merge branch 'master' of plg.uwaterloo.ca:/u/cforall/software/cfa/cfa-cc

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