source: src/SymTab/Validate.cc @ 44a81853

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 44a81853 was 9facf3b, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

update generation of return variables and the affected test outputs

  • Property mode set to 100644
File size: 30.2 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
12// Last Modified On : Tue Jul 12 17:49:21 2016
13// Update Count     : 298
[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
40#include <list>
41#include <iterator>
[e491159]42#include "Common/ScopedMap.h"
[630a82a]43#include "Common/utility.h"
44#include "Common/UniqueName.h"
[51b7345]45#include "Validate.h"
46#include "SynTree/Visitor.h"
47#include "SynTree/Mutator.h"
48#include "SynTree/Type.h"
[630a82a]49#include "SynTree/Expression.h"
[51b7345]50#include "SynTree/Statement.h"
51#include "SynTree/TypeSubstitution.h"
[68cd1ce]52#include "Indexer.h"
[51b7345]53#include "FixFunction.h"
[cc79d97]54// #include "ImplementationType.h"
[630a82a]55#include "GenPoly/DeclMutator.h"
[51b7345]56#include "AddVisit.h"
[f6d7e0f]57#include "MakeLibCfa.h"
[cc79d97]58#include "TypeEquality.h"
[620cb95]59#include "Autogen.h"
[1cbca6e]60#include "ResolvExpr/typeops.h"
[79970ed]61#include <algorithm>
[d1969a6]62#include "InitTweak/InitTweak.h"
[9facf3b]63#include "CodeGen/CodeGenerator.h"
[51b7345]64
[c8ffe20b]65#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
[51b7345]66
67namespace SymTab {
[9facf3b]68        class HoistStruct final : public Visitor {
[a08ba92]69          public:
[82dd287]70                /// Flattens nested struct types
[0dd3a2f]71                static void hoistStruct( std::list< Declaration * > &translationUnit );
[9cb8e88d]72
[0dd3a2f]73                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
[9cb8e88d]74
[0dd3a2f]75                virtual void visit( StructDecl *aggregateDecl );
76                virtual void visit( UnionDecl *aggregateDecl );
[c8ffe20b]77
[0dd3a2f]78                virtual void visit( CompoundStmt *compoundStmt );
79                virtual void visit( SwitchStmt *switchStmt );
[a08ba92]80          private:
[0dd3a2f]81                HoistStruct();
[c8ffe20b]82
[0dd3a2f]83                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
[c8ffe20b]84
[0dd3a2f]85                std::list< Declaration * > declsToAdd;
86                bool inStruct;
[a08ba92]87        };
[c8ffe20b]88
[cce9429]89        /// Fix return types so that every function returns exactly one value
[9facf3b]90        class ReturnTypeFixer final : public Visitor {
[cce9429]91          public:
[9facf3b]92
93                typedef Visitor Parent;
94                using Parent::visit;
95
[cce9429]96                static void fix( std::list< Declaration * > &translationUnit );
97
[9facf3b]98                virtual void visit( FunctionDecl * functionDecl );
99
[cce9429]100                virtual void visit( FunctionType * ftype );
101        };
102
[de91427b]103        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
[9facf3b]104        class EnumAndPointerDecayPass final : public Visitor {
[0dd3a2f]105                typedef Visitor Parent;
106                virtual void visit( EnumDecl *aggregateDecl );
107                virtual void visit( FunctionType *func );
[a08ba92]108        };
[82dd287]109
110        /// Associates forward declarations of aggregates with their definitions
[cce9429]111        class LinkReferenceToTypes final : public Indexer {
[0dd3a2f]112                typedef Indexer Parent;
[a08ba92]113          public:
[cce9429]114                LinkReferenceToTypes( bool doDebug, const Indexer *indexer );
[a08ba92]115          private:
[62e5546]116                using Indexer::visit;
117                void visit( StructInstType *structInst ) final;
118                void visit( UnionInstType *unionInst ) final;
119                void visit( TraitInstType *contextInst ) final;
120                void visit( StructDecl *structDecl ) final;
121                void visit( UnionDecl *unionDecl ) final;
122                void visit( TypeInstType *typeInst ) final;
[0dd3a2f]123
124                const Indexer *indexer;
[9cb8e88d]125
[0dd3a2f]126                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
127                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
128                ForwardStructsType forwardStructs;
129                ForwardUnionsType forwardUnions;
[a08ba92]130        };
[c8ffe20b]131
[82dd287]132        /// Replaces array and function types in forall lists by appropriate pointer type
[a08ba92]133        class Pass3 : public Indexer {
[0dd3a2f]134                typedef Indexer Parent;
[a08ba92]135          public:
[0dd3a2f]136                Pass3( const Indexer *indexer );
[a08ba92]137          private:
[0dd3a2f]138                virtual void visit( ObjectDecl *object );
139                virtual void visit( FunctionDecl *func );
[c8ffe20b]140
[0dd3a2f]141                const Indexer *indexer;
[a08ba92]142        };
[c8ffe20b]143
[de91427b]144        class ReturnChecker : public Visitor {
145          public:
146                /// Checks that return statements return nothing if their return type is void
147                /// and return something if the return type is non-void.
148                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
149          private:
150                virtual void visit( FunctionDecl * functionDecl );
151
152                virtual void visit( ReturnStmt * returnStmt );
153
154                std::list< DeclarationWithType * > returnVals;
155        };
156
[a08ba92]157        class EliminateTypedef : public Mutator {
158          public:
[de91427b]159                EliminateTypedef() : scopeLevel( 0 ) {}
160                /// Replaces typedefs by forward declarations
[0dd3a2f]161                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
[a08ba92]162          private:
[0dd3a2f]163                virtual Declaration *mutate( TypedefDecl *typeDecl );
164                virtual TypeDecl *mutate( TypeDecl *typeDecl );
165                virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
[1db21619]166                virtual DeclarationWithType *mutate( ObjectDecl *objDecl );
[0dd3a2f]167                virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
168                virtual Type *mutate( TypeInstType *aggregateUseType );
169                virtual Expression *mutate( CastExpr *castExpr );
[cc79d97]170
[85c4ef0]171                virtual Declaration *mutate( StructDecl * structDecl );
172                virtual Declaration *mutate( UnionDecl * unionDecl );
173                virtual Declaration *mutate( EnumDecl * enumDecl );
[4040425]174                virtual Declaration *mutate( TraitDecl * contextDecl );
[85c4ef0]175
176                template<typename AggDecl>
177                AggDecl *handleAggregate( AggDecl * aggDecl );
178
[45161b4d]179                template<typename AggDecl>
180                void addImplicitTypedef( AggDecl * aggDecl );
[70a06f6]181
[46f6134]182                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
[e491159]183                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
[679864e1]184                typedef std::map< std::string, TypeDecl * > TypeDeclMap;
[cc79d97]185                TypedefMap typedefNames;
[679864e1]186                TypeDeclMap typedeclNames;
[cc79d97]187                int scopeLevel;
[a08ba92]188        };
[c8ffe20b]189
[d1969a6]190        class VerifyCtorDtorAssign : public Visitor {
[9cb8e88d]191        public:
[d1969a6]192                /// ensure that constructors, destructors, and assignment have at least one
193                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
[9cb8e88d]194                /// return values.
195                static void verify( std::list< Declaration * > &translationUnit );
196
197                virtual void visit( FunctionDecl *funcDecl );
[5f98ce5]198        };
[70a06f6]199
[62e5546]200        class CompoundLiteral final : public GenPoly::DeclMutator {
[630a82a]201                DeclarationNode::StorageClass storageclass = DeclarationNode::NoStorageClass;
202
[62e5546]203                using GenPoly::DeclMutator::mutate;
204                DeclarationWithType * mutate( ObjectDecl *objectDecl ) final;
205                Expression *mutate( CompoundLiteralExpr *compLitExpr ) final;
[9cb8e88d]206        };
207
[a08ba92]208        void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
[bda58ad]209                EnumAndPointerDecayPass epc;
[cce9429]210                LinkReferenceToTypes lrt( doDebug, 0 );
[0dd3a2f]211                Pass3 pass3( 0 );
[630a82a]212                CompoundLiteral compoundliteral;
213
[0dd3a2f]214                EliminateTypedef::eliminateTypedef( translationUnit );
215                HoistStruct::hoistStruct( translationUnit );
[cce9429]216                ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
[bda58ad]217                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecayPass
218                acceptAll( translationUnit, epc );
[cce9429]219                acceptAll( translationUnit, lrt );
[de91427b]220                ReturnChecker::checkFunctionReturns( translationUnit );
[40e636a]221                compoundliteral.mutateDeclarationList( translationUnit );
[0dd3a2f]222                acceptAll( translationUnit, pass3 );
[d1969a6]223                VerifyCtorDtorAssign::verify( translationUnit );
[a08ba92]224        }
[9cb8e88d]225
[a08ba92]226        void validateType( Type *type, const Indexer *indexer ) {
[bda58ad]227                EnumAndPointerDecayPass epc;
[cce9429]228                LinkReferenceToTypes lrt( false, indexer );
[0dd3a2f]229                Pass3 pass3( indexer );
[bda58ad]230                type->accept( epc );
[cce9429]231                type->accept( lrt );
[0dd3a2f]232                type->accept( pass3 );
[a08ba92]233        }
[c8ffe20b]234
[a08ba92]235        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
[0dd3a2f]236                HoistStruct hoister;
237                acceptAndAdd( translationUnit, hoister, true );
[a08ba92]238        }
[c8ffe20b]239
[a08ba92]240        HoistStruct::HoistStruct() : inStruct( false ) {
241        }
[c8ffe20b]242
[a08ba92]243        void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
[0dd3a2f]244                std::list< Declaration * >::iterator i = declList.begin();
245                while ( i != declList.end() ) {
246                        std::list< Declaration * >::iterator next = i;
247                        ++next;
248                        if ( pred( *i ) ) {
249                                if ( doDelete ) {
250                                        delete *i;
251                                } // if
252                                declList.erase( i );
253                        } // if
254                        i = next;
255                } // while
[a08ba92]256        }
[c8ffe20b]257
[a08ba92]258        bool isStructOrUnion( Declaration *decl ) {
[0dd3a2f]259                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
[a08ba92]260        }
[b3b2077]261        // xxx - shouldn't this be declsToAddBefore?
[a08ba92]262        template< typename AggDecl >
263        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
[0dd3a2f]264                if ( inStruct ) {
265                        // Add elements in stack order corresponding to nesting structure.
266                        declsToAdd.push_front( aggregateDecl );
267                        Visitor::visit( aggregateDecl );
268                } else {
269                        inStruct = true;
270                        Visitor::visit( aggregateDecl );
271                        inStruct = false;
272                } // if
273                // Always remove the hoisted aggregate from the inner structure.
274                filter( aggregateDecl->get_members(), isStructOrUnion, false );
[a08ba92]275        }
[c8ffe20b]276
[a08ba92]277        void HoistStruct::visit( StructDecl *aggregateDecl ) {
[0dd3a2f]278                handleAggregate( aggregateDecl );
[a08ba92]279        }
[c8ffe20b]280
[a08ba92]281        void HoistStruct::visit( UnionDecl *aggregateDecl ) {
[0dd3a2f]282                handleAggregate( aggregateDecl );
[a08ba92]283        }
[c8ffe20b]284
[a08ba92]285        void HoistStruct::visit( CompoundStmt *compoundStmt ) {
[0dd3a2f]286                addVisit( compoundStmt, *this );
[a08ba92]287        }
[c8ffe20b]288
[a08ba92]289        void HoistStruct::visit( SwitchStmt *switchStmt ) {
[0dd3a2f]290                addVisit( switchStmt, *this );
[a08ba92]291        }
[c8ffe20b]292
[bda58ad]293        void EnumAndPointerDecayPass::visit( EnumDecl *enumDecl ) {
[0dd3a2f]294                // Set the type of each member of the enumeration to be EnumConstant
295                for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
[f6d7e0f]296                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
[0dd3a2f]297                        assert( obj );
[a436947]298                        obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false, false, false ), enumDecl->get_name() ) );
[0dd3a2f]299                } // for
300                Parent::visit( enumDecl );
[a08ba92]301        }
[51b7345]302
[a08ba92]303        namespace {
[83de11e]304                template< typename DWTList >
305                void fixFunctionList( DWTList & dwts, FunctionType * func ) {
[0dd3a2f]306                        // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
307                        // entirely other fix ups are handled by the FixFunction class
[83de11e]308                        typedef typename DWTList::iterator DWTIterator;
309                        DWTIterator begin( dwts.begin() ), end( dwts.end() );
[0dd3a2f]310                        if ( begin == end ) return;
311                        FixFunction fixer;
312                        DWTIterator i = begin;
[83de11e]313                        *i = (*i)->acceptMutator( fixer );
[0dd3a2f]314                        if ( fixer.get_isVoid() ) {
315                                DWTIterator j = i;
316                                ++i;
[bda58ad]317                                delete *j;
[83de11e]318                                dwts.erase( j );
[9cb8e88d]319                                if ( i != end ) {
[0dd3a2f]320                                        throw SemanticError( "invalid type void in function type ", func );
321                                } // if
322                        } else {
323                                ++i;
324                                for ( ; i != end; ++i ) {
325                                        FixFunction fixer;
326                                        *i = (*i )->acceptMutator( fixer );
327                                        if ( fixer.get_isVoid() ) {
328                                                throw SemanticError( "invalid type void in function type ", func );
329                                        } // if
330                                } // for
331                        } // if
332                }
[a08ba92]333        }
[c8ffe20b]334
[bda58ad]335        void EnumAndPointerDecayPass::visit( FunctionType *func ) {
[0dd3a2f]336                // Fix up parameters and return types
[83de11e]337                fixFunctionList( func->get_parameters(), func );
338                fixFunctionList( func->get_returnVals(), func );
[0dd3a2f]339                Visitor::visit( func );
[a08ba92]340        }
[c8ffe20b]341
[cce9429]342        LinkReferenceToTypes::LinkReferenceToTypes( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
[0dd3a2f]343                if ( other_indexer ) {
344                        indexer = other_indexer;
345                } else {
346                        indexer = this;
347                } // if
[a08ba92]348        }
[c8ffe20b]349
[cce9429]350        void LinkReferenceToTypes::visit( StructInstType *structInst ) {
[0dd3a2f]351                Parent::visit( structInst );
352                StructDecl *st = indexer->lookupStruct( structInst->get_name() );
353                // it's not a semantic error if the struct is not found, just an implicit forward declaration
354                if ( st ) {
[98735ef]355                        //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
[0dd3a2f]356                        structInst->set_baseStruct( st );
357                } // if
358                if ( ! st || st->get_members().empty() ) {
359                        // use of forward declaration
360                        forwardStructs[ structInst->get_name() ].push_back( structInst );
361                } // if
[a08ba92]362        }
[c8ffe20b]363
[cce9429]364        void LinkReferenceToTypes::visit( UnionInstType *unionInst ) {
[0dd3a2f]365                Parent::visit( unionInst );
366                UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
367                // it's not a semantic error if the union is not found, just an implicit forward declaration
368                if ( un ) {
369                        unionInst->set_baseUnion( un );
370                } // if
371                if ( ! un || un->get_members().empty() ) {
372                        // use of forward declaration
373                        forwardUnions[ unionInst->get_name() ].push_back( unionInst );
374                } // if
[a08ba92]375        }
[c8ffe20b]376
[cce9429]377        void LinkReferenceToTypes::visit( TraitInstType *contextInst ) {
[0dd3a2f]378                Parent::visit( contextInst );
[2c57025]379                if ( contextInst->get_name() == "sized" ) {
380                        // "sized" is a special trait with no members - just flick the sized status on for the type variable
381                        if ( contextInst->get_parameters().size() != 1 ) {
382                                throw SemanticError( "incorrect number of context parameters: ", contextInst );
383                        }
384                        TypeExpr * param = safe_dynamic_cast< TypeExpr * > ( contextInst->get_parameters().front() );
385                        TypeInstType * inst = safe_dynamic_cast< TypeInstType * > ( param->get_type() );
386                        TypeDecl * decl = inst->get_baseType();
387                        decl->set_sized( true );
388                        // since "sized" is special, the next few steps don't apply
389                        return;
390                }
[4040425]391                TraitDecl *ctx = indexer->lookupTrait( contextInst->get_name() );
[0dd3a2f]392                if ( ! ctx ) {
393                        throw SemanticError( "use of undeclared context " + contextInst->get_name() );
[17cd4eb]394                } // if
[0dd3a2f]395                for ( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) {
396                        for ( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) {
[4040425]397                                if ( TraitInstType *otherCtx = dynamic_cast< TraitInstType * >(*assert ) ) {
[0dd3a2f]398                                        cloneAll( otherCtx->get_members(), contextInst->get_members() );
399                                } else {
400                                        contextInst->get_members().push_back( (*assert )->clone() );
401                                } // if
402                        } // for
403                } // for
[51b986f]404
405                if ( ctx->get_parameters().size() != contextInst->get_parameters().size() ) {
406                        throw SemanticError( "incorrect number of context parameters: ", contextInst );
407                } // if
408
[79970ed]409                // need to clone members of the context for ownership purposes
410                std::list< Declaration * > members;
411                std::transform( ctx->get_members().begin(), ctx->get_members().end(), back_inserter( members ), [](Declaration * dwt) { return dwt->clone(); } );
412
413                applySubstitution( ctx->get_parameters().begin(), ctx->get_parameters().end(), contextInst->get_parameters().begin(), members.begin(), members.end(), back_inserter( contextInst->get_members() ) );
[a08ba92]414        }
[c8ffe20b]415
[cce9429]416        void LinkReferenceToTypes::visit( StructDecl *structDecl ) {
[677c1be]417                // visit struct members first so that the types of self-referencing members are updated properly
418                Parent::visit( structDecl );
[0dd3a2f]419                if ( ! structDecl->get_members().empty() ) {
420                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
421                        if ( fwds != forwardStructs.end() ) {
422                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
423                                        (*inst )->set_baseStruct( structDecl );
424                                } // for
425                                forwardStructs.erase( fwds );
426                        } // if
427                } // if
[a08ba92]428        }
[c8ffe20b]429
[cce9429]430        void LinkReferenceToTypes::visit( UnionDecl *unionDecl ) {
[677c1be]431                Parent::visit( unionDecl );
[0dd3a2f]432                if ( ! unionDecl->get_members().empty() ) {
433                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
434                        if ( fwds != forwardUnions.end() ) {
435                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
436                                        (*inst )->set_baseUnion( unionDecl );
437                                } // for
438                                forwardUnions.erase( fwds );
439                        } // if
440                } // if
[a08ba92]441        }
[c8ffe20b]442
[cce9429]443        void LinkReferenceToTypes::visit( TypeInstType *typeInst ) {
[0dd3a2f]444                if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
445                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
446                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
447                        } // if
448                } // if
[a08ba92]449        }
[c8ffe20b]450
[a08ba92]451        Pass3::Pass3( const Indexer *other_indexer ) :  Indexer( false ) {
[0dd3a2f]452                if ( other_indexer ) {
453                        indexer = other_indexer;
454                } else {
455                        indexer = this;
456                } // if
[a08ba92]457        }
[c8ffe20b]458
[82dd287]459        /// Fix up assertions
[a08ba92]460        void forallFixer( Type *func ) {
[8c49c0e]461                for ( Type::ForallList::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) {
[0dd3a2f]462                        std::list< DeclarationWithType * > toBeDone, nextRound;
463                        toBeDone.splice( toBeDone.end(), (*type )->get_assertions() );
464                        while ( ! toBeDone.empty() ) {
465                                for ( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) {
[4040425]466                                        if ( TraitInstType *ctx = dynamic_cast< TraitInstType * >( (*assertion )->get_type() ) ) {
[0dd3a2f]467                                                for ( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) {
468                                                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i );
469                                                        assert( dwt );
470                                                        nextRound.push_back( dwt->clone() );
471                                                }
472                                                delete ctx;
473                                        } else {
474                                                FixFunction fixer;
475                                                *assertion = (*assertion )->acceptMutator( fixer );
476                                                if ( fixer.get_isVoid() ) {
477                                                        throw SemanticError( "invalid type void in assertion of function ", func );
478                                                }
479                                                (*type )->get_assertions().push_back( *assertion );
480                                        } // if
481                                } // for
482                                toBeDone.clear();
483                                toBeDone.splice( toBeDone.end(), nextRound );
484                        } // while
485                } // for
[a08ba92]486        }
[c8ffe20b]487
[a08ba92]488        void Pass3::visit( ObjectDecl *object ) {
[0dd3a2f]489                forallFixer( object->get_type() );
490                if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
491                        forallFixer( pointer->get_base() );
492                } // if
493                Parent::visit( object );
494                object->fixUniqueId();
[a08ba92]495        }
[c8ffe20b]496
[a08ba92]497        void Pass3::visit( FunctionDecl *func ) {
[0dd3a2f]498                forallFixer( func->get_type() );
499                Parent::visit( func );
500                func->fixUniqueId();
[a08ba92]501        }
[c8ffe20b]502
[de91427b]503        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
504                ReturnChecker checker;
505                acceptAll( translationUnit, checker );
506        }
507
508        void ReturnChecker::visit( FunctionDecl * functionDecl ) {
509                std::list< DeclarationWithType * > oldReturnVals = returnVals;
510                returnVals = functionDecl->get_functionType()->get_returnVals();
511                Visitor::visit( functionDecl );
512                returnVals = oldReturnVals;
513        }
514
515        void ReturnChecker::visit( ReturnStmt * returnStmt ) {
[74d1804]516                // Previously this also checked for the existence of an expr paired with no return values on
517                // the  function return type. This is incorrect, since you can have an expression attached to
518                // a return statement in a void-returning function in C. The expression is treated as if it
519                // were cast to void.
[de91427b]520                if ( returnStmt->get_expr() == NULL && returnVals.size() != 0 ) {
521                        throw SemanticError( "Non-void function returns no values: " , returnStmt );
522                }
523        }
524
525
[a08ba92]526        bool isTypedef( Declaration *decl ) {
[0dd3a2f]527                return dynamic_cast< TypedefDecl * >( decl );
[a08ba92]528        }
[c8ffe20b]529
[a08ba92]530        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
[0dd3a2f]531                EliminateTypedef eliminator;
532                mutateAll( translationUnit, eliminator );
[5f98ce5]533                if ( eliminator.typedefNames.count( "size_t" ) ) {
534                        // grab and remember declaration of size_t
535                        SizeType = eliminator.typedefNames["size_t"].first->get_base()->clone();
536                } else {
[40e636a]537                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
538                        // eventually should have a warning for this case.
539                        SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
[5f98ce5]540                }
[0dd3a2f]541                filter( translationUnit, isTypedef, true );
[5f98ce5]542
[a08ba92]543        }
[c8ffe20b]544
[85c4ef0]545        Type *EliminateTypedef::mutate( TypeInstType * typeInst ) {
[9cb8e88d]546                // instances of typedef types will come here. If it is an instance
[cc79d97]547                // of a typdef type, link the instance to its actual type.
548                TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
[0dd3a2f]549                if ( def != typedefNames.end() ) {
[cc79d97]550                        Type *ret = def->second.first->get_base()->clone();
[0dd3a2f]551                        ret->get_qualifiers() += typeInst->get_qualifiers();
[0215a76f]552                        // place instance parameters on the typedef'd type
553                        if ( ! typeInst->get_parameters().empty() ) {
554                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
555                                if ( ! rtt ) {
556                                        throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
557                                }
558                                rtt->get_parameters().clear();
[b644d6f]559                                cloneAll( typeInst->get_parameters(), rtt->get_parameters() );
560                                mutateAll( rtt->get_parameters(), *this );  // recursively fix typedefs on parameters
[1db21619]561                        } // if
[0dd3a2f]562                        delete typeInst;
563                        return ret;
[679864e1]564                } else {
565                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
566                        assert( base != typedeclNames.end() );
[1e8b02f5]567                        typeInst->set_baseType( base->second );
[0dd3a2f]568                } // if
569                return typeInst;
[a08ba92]570        }
[c8ffe20b]571
[85c4ef0]572        Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) {
[0dd3a2f]573                Declaration *ret = Mutator::mutate( tyDecl );
[5f98ce5]574
[cc79d97]575                if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
[9cb8e88d]576                        // typedef to the same name from the same scope
[cc79d97]577                        // must be from the same type
578
579                        Type * t1 = tyDecl->get_base();
580                        Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
[1cbca6e]581                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
[cc79d97]582                                throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
[85c4ef0]583                        }
[cc79d97]584                } else {
[46f6134]585                        typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
[cc79d97]586                } // if
587
[0dd3a2f]588                // When a typedef is a forward declaration:
589                //    typedef struct screen SCREEN;
590                // the declaration portion must be retained:
591                //    struct screen;
592                // because the expansion of the typedef is:
593                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
594                // hence the type-name "screen" must be defined.
595                // Note, qualifiers on the typedef are superfluous for the forward declaration.
596                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( tyDecl->get_base() ) ) {
597                        return new StructDecl( aggDecl->get_name() );
598                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( tyDecl->get_base() ) ) {
599                        return new UnionDecl( aggDecl->get_name() );
[956a9c7]600                } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( tyDecl->get_base() ) ) {
601                        return new EnumDecl( enumDecl->get_name() );
[0dd3a2f]602                } else {
[46f6134]603                        return ret->clone();
[0dd3a2f]604                } // if
[a08ba92]605        }
[c8ffe20b]606
[85c4ef0]607        TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) {
[cc79d97]608                TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
[0dd3a2f]609                if ( i != typedefNames.end() ) {
610                        typedefNames.erase( i ) ;
611                } // if
[679864e1]612
613                typedeclNames[ typeDecl->get_name() ] = typeDecl;
[2c57025]614                return Mutator::mutate( typeDecl );
[a08ba92]615        }
[c8ffe20b]616
[85c4ef0]617        DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) {
[46f6134]618                typedefNames.beginScope();
[0dd3a2f]619                DeclarationWithType *ret = Mutator::mutate( funcDecl );
[46f6134]620                typedefNames.endScope();
[0dd3a2f]621                return ret;
[a08ba92]622        }
[c8ffe20b]623
[1db21619]624        DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) {
[46f6134]625                typedefNames.beginScope();
[1db21619]626                DeclarationWithType *ret = Mutator::mutate( objDecl );
[46f6134]627                typedefNames.endScope();
[02e5ab6]628                // is the type a function?
[1db21619]629                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( ret->get_type() ) ) {
[02e5ab6]630                        // replace the current object declaration with a function declaration
[1db21619]631                        return new FunctionDecl( ret->get_name(), ret->get_storageClass(), ret->get_linkage(), funtype, 0, ret->get_isInline(), ret->get_isNoreturn() );
632                } else if ( objDecl->get_isInline() || objDecl->get_isNoreturn() ) {
633                        throw SemanticError( "invalid inline or _Noreturn specification in declaration of ", objDecl );
634                } // if
[0dd3a2f]635                return ret;
[a08ba92]636        }
[c8ffe20b]637
[85c4ef0]638        Expression *EliminateTypedef::mutate( CastExpr * castExpr ) {
[46f6134]639                typedefNames.beginScope();
[0dd3a2f]640                Expression *ret = Mutator::mutate( castExpr );
[46f6134]641                typedefNames.endScope();
[0dd3a2f]642                return ret;
[a08ba92]643        }
[c8ffe20b]644
[85c4ef0]645        CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) {
[46f6134]646                typedefNames.beginScope();
[cc79d97]647                scopeLevel += 1;
[0dd3a2f]648                CompoundStmt *ret = Mutator::mutate( compoundStmt );
[cc79d97]649                scopeLevel -= 1;
[0dd3a2f]650                std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
651                while ( i != compoundStmt->get_kids().end() ) {
[85c4ef0]652                        std::list< Statement * >::iterator next = i+1;
[0dd3a2f]653                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
654                                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
655                                        delete *i;
656                                        compoundStmt->get_kids().erase( i );
657                                } // if
658                        } // if
659                        i = next;
660                } // while
[46f6134]661                typedefNames.endScope();
[0dd3a2f]662                return ret;
[a08ba92]663        }
[85c4ef0]664
[45161b4d]665        // there may be typedefs nested within aggregates in order for everything to work properly, these should be removed
666        // as well
[85c4ef0]667        template<typename AggDecl>
668        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
669                std::list<Declaration *>::iterator it = aggDecl->get_members().begin();
670                for ( ; it != aggDecl->get_members().end(); ) {
671                        std::list< Declaration * >::iterator next = it+1;
672                        if ( dynamic_cast< TypedefDecl * >( *it ) ) {
673                                delete *it;
674                                aggDecl->get_members().erase( it );
675                        } // if
676                        it = next;
677                }
678                return aggDecl;
679        }
680
[45161b4d]681        template<typename AggDecl>
682        void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
683                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
[62e5546]684                        Type *type = nullptr;
[45161b4d]685                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
686                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
687                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
688                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
689                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
690                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
691                        } // if
[46f6134]692                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), DeclarationNode::NoStorageClass, type ) );
693                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
[45161b4d]694                } // if
695        }
[4e06c1e]696
[85c4ef0]697        Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) {
[45161b4d]698                addImplicitTypedef( structDecl );
[85c4ef0]699                Mutator::mutate( structDecl );
700                return handleAggregate( structDecl );
701        }
702
703        Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) {
[45161b4d]704                addImplicitTypedef( unionDecl );
[85c4ef0]705                Mutator::mutate( unionDecl );
706                return handleAggregate( unionDecl );
707        }
708
709        Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) {
[45161b4d]710                addImplicitTypedef( enumDecl );
[85c4ef0]711                Mutator::mutate( enumDecl );
712                return handleAggregate( enumDecl );
713        }
714
[45161b4d]715        Declaration *EliminateTypedef::mutate( TraitDecl * contextDecl ) {
[85c4ef0]716                Mutator::mutate( contextDecl );
717                return handleAggregate( contextDecl );
718        }
719
[d1969a6]720        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
721                VerifyCtorDtorAssign verifier;
[9cb8e88d]722                acceptAll( translationUnit, verifier );
723        }
724
[d1969a6]725        void VerifyCtorDtorAssign::visit( FunctionDecl * funcDecl ) {
[9cb8e88d]726                FunctionType * funcType = funcDecl->get_functionType();
727                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
728                std::list< DeclarationWithType * > &params = funcType->get_parameters();
729
[d1969a6]730                if ( InitTweak::isCtorDtorAssign( funcDecl->get_name() ) ) {
[9cb8e88d]731                        if ( params.size() == 0 ) {
[d1969a6]732                                throw SemanticError( "Constructors, destructors, and assignment functions require at least one parameter ", funcDecl );
[9cb8e88d]733                        }
734                        if ( ! dynamic_cast< PointerType * >( params.front()->get_type() ) ) {
[d1969a6]735                                throw SemanticError( "First parameter of a constructor, destructor, or assignment function must be a pointer ", funcDecl );
[9cb8e88d]736                        }
[d1969a6]737                        if ( InitTweak::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
[9cb8e88d]738                                throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
739                        }
740                }
741
742                Visitor::visit( funcDecl );
743        }
[70a06f6]744
[630a82a]745        DeclarationWithType * CompoundLiteral::mutate( ObjectDecl *objectDecl ) {
746                storageclass = objectDecl->get_storageClass();
747                DeclarationWithType * temp = Mutator::mutate( objectDecl );
748                storageclass = DeclarationNode::NoStorageClass;
749                return temp;
750        }
751
752        Expression *CompoundLiteral::mutate( CompoundLiteralExpr *compLitExpr ) {
753                // transform [storage_class] ... (struct S){ 3, ... };
754                // into [storage_class] struct S temp =  { 3, ... };
755                static UniqueName indexName( "_compLit" );
756
757                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageclass, LinkageSpec::C, 0, compLitExpr->get_type(), compLitExpr->get_initializer() );
758                compLitExpr->set_type( 0 );
759                compLitExpr->set_initializer( 0 );
760                delete compLitExpr;
761                DeclarationWithType * newtempvar = mutate( tempvar );
762                addDeclaration( newtempvar );                                   // add modified temporary to current block
763                return new VariableExpr( newtempvar );
764        }
[cce9429]765
766        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
767                ReturnTypeFixer fixer;
768                acceptAll( translationUnit, fixer );
769        }
770
[9facf3b]771        void ReturnTypeFixer::visit( FunctionDecl * functionDecl ) {
772                Parent::visit( functionDecl );
773                FunctionType * ftype = functionDecl->get_functionType();
774                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
775                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %d", functionDecl->get_name().c_str(), retVals.size() );
776                if ( retVals.size() == 1 ) {
777                        // 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)
778                        // ensure other return values have a name
779                        DeclarationWithType * ret = retVals.front();
780                        if ( ret->get_name() == "" ) {
781                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
782                        }
783                }
784        }
[cce9429]785
[9facf3b]786        void ReturnTypeFixer::visit( FunctionType * ftype ) {
[cce9429]787                // xxx - need to handle named return values - this information needs to be saved somehow
788                // so that resolution has access to the names.
789                // Note that this pass needs to happen early so that other passes which look for tuple types
790                // find them in all of the right places, including function return types.
791                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
792                if ( retVals.size() > 1 ) {
793                        // generate a single return parameter which is the tuple of all of the return values
794                        TupleType * tupleType = safe_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
795                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
[9facf3b]796                        ObjectDecl * newRet = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
[cce9429]797                        deleteAll( retVals );
798                        retVals.clear();
799                        retVals.push_back( newRet );
800                }
801        }
[51b7345]802} // namespace SymTab
[0dd3a2f]803
804// Local Variables: //
805// tab-width: 4 //
806// mode: c++ //
807// compile-command: "make install" //
808// End: //
Note: See TracBrowser for help on using the repository browser.