source: src/SymTab/Validate.cc @ 2bf9c37

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 2bf9c37 was 2bf9c37, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Refactor Validate filter into utility

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