source: src/SymTab/Validate.cc @ 1744e6d

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

Refactor operator predicates into OperatorTable?.cc

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