source: src/SymTab/Validate.cc @ fc56cdbf

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

Merge branch 'master' into references

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