source: src/SymTab/Validate.cc @ ada0eb06

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

Fix handling of GCC label address and computed goto

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