source: src/SymTab/Validate.cc @ 0508ab3

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

fix passes using PassVisitor? to use inheritance rather than explicit members

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