source: src/SymTab/Validate.cc @ 5af7306

new-envwith_gc
Last change on this file since 5af7306 was 5af7306, checked in by Aaron Moss <a3moss@…>, 6 years ago

Assorted bug fixes

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