source: src/SymTab/Validate.cc @ 395fc37

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 395fc37 was 395fc37, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

Merge branch 'master' of plg2:software/cfa/cfa-cc

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