source: src/SymTab/Validate.cc @ 00a8e19

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since 00a8e19 was a488783, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Translated the first half of validate-D. HoistControlStruct? is pretty much the same, Autogen has changed a lot due to the changes in the AST.

  • Property mode set to 100644
File size: 78.9 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Validate.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Fri Nov 12 11:00:00 2021
13// Update Count     : 364
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 <unordered_map>               // for unordered_map
47#include <utility>                     // for pair
48
49#include "AST/Chain.hpp"
50#include "AST/Decl.hpp"
51#include "AST/Node.hpp"
52#include "AST/Pass.hpp"
53#include "AST/SymbolTable.hpp"
54#include "AST/Type.hpp"
55#include "AST/TypeSubstitution.hpp"
56#include "CodeGen/CodeGenerator.h"     // for genName
57#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
58#include "ControlStruct/Mutate.h"      // for ForExprMutator
59#include "Common/CodeLocation.h"       // for CodeLocation
60#include "Common/Stats.h"              // for Stats::Heap
61#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
62#include "Common/ScopedMap.h"          // for ScopedMap
63#include "Common/SemanticError.h"      // for SemanticError
64#include "Common/UniqueName.h"         // for UniqueName
65#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
66#include "CompilationState.h"          // skip some passes in new-ast build
67#include "Concurrency/Keywords.h"      // for applyKeywords
68#include "FixFunction.h"               // for FixFunction
69#include "Indexer.h"                   // for Indexer
70#include "InitTweak/GenInit.h"         // for fixReturnStatements
71#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
72#include "ResolvExpr/typeops.h"        // for typesCompatible
73#include "ResolvExpr/Resolver.h"       // for findSingleExpression
74#include "ResolvExpr/ResolveTypeof.h"  // for resolveTypeof
75#include "SymTab/Autogen.h"            // for SizeType
76#include "SynTree/LinkageSpec.h"       // for C
77#include "SynTree/Attribute.h"         // for noAttributes, Attribute
78#include "SynTree/Constant.h"          // for Constant
79#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
80#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
81#include "SynTree/Initializer.h"       // for ListInit, Initializer
82#include "SynTree/Label.h"             // for operator==, Label
83#include "SynTree/Mutator.h"           // for Mutator
84#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
85#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
86#include "SynTree/Visitor.h"           // for Visitor
87#include "Validate/HandleAttributes.h" // for handleAttributes
88#include "Validate/FindSpecialDecls.h" // for FindSpecialDecls
89
90class CompoundStmt;
91class ReturnStmt;
92class SwitchStmt;
93
94#define debugPrint( x ) if ( doDebug ) x
95
96namespace SymTab {
97        /// hoists declarations that are difficult to hoist while parsing
98        struct HoistTypeDecls final : public WithDeclsToAdd {
99                void previsit( SizeofExpr * );
100                void previsit( AlignofExpr * );
101                void previsit( UntypedOffsetofExpr * );
102                void previsit( CompoundLiteralExpr * );
103                void handleType( Type * );
104        };
105
106        struct FixQualifiedTypes final : public WithIndexer {
107                FixQualifiedTypes() : WithIndexer(false) {}
108                Type * postmutate( QualifiedType * );
109        };
110
111        struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
112                /// Flattens nested struct types
113                static void hoistStruct( std::list< Declaration * > &translationUnit );
114
115                void previsit( StructDecl * aggregateDecl );
116                void previsit( UnionDecl * aggregateDecl );
117                void previsit( StaticAssertDecl * assertDecl );
118                void previsit( StructInstType * type );
119                void previsit( UnionInstType * type );
120                void previsit( EnumInstType * type );
121
122          private:
123                template< typename AggDecl > void handleAggregate( AggDecl * aggregateDecl );
124
125                AggregateDecl * parentAggr = nullptr;
126        };
127
128        /// Fix return types so that every function returns exactly one value
129        struct ReturnTypeFixer {
130                static void fix( std::list< Declaration * > &translationUnit );
131
132                void postvisit( FunctionDecl * functionDecl );
133                void postvisit( FunctionType * ftype );
134        };
135
136        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
137        struct EnumAndPointerDecay_old {
138                void previsit( EnumDecl * aggregateDecl );
139                void previsit( FunctionType * func );
140        };
141
142        /// Associates forward declarations of aggregates with their definitions
143        struct LinkReferenceToTypes_old final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes_old>, public WithShortCircuiting {
144                LinkReferenceToTypes_old( const Indexer * indexer );
145                void postvisit( TypeInstType * typeInst );
146
147                void postvisit( EnumInstType * enumInst );
148                void postvisit( StructInstType * structInst );
149                void postvisit( UnionInstType * unionInst );
150                void postvisit( TraitInstType * traitInst );
151                void previsit( QualifiedType * qualType );
152                void postvisit( QualifiedType * qualType );
153
154                void postvisit( EnumDecl * enumDecl );
155                void postvisit( StructDecl * structDecl );
156                void postvisit( UnionDecl * unionDecl );
157                void postvisit( TraitDecl * traitDecl );
158
159                void previsit( StructDecl * structDecl );
160                void previsit( UnionDecl * unionDecl );
161
162                void renameGenericParams( std::list< TypeDecl * > & params );
163
164          private:
165                const Indexer * local_indexer;
166
167                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
168                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
169                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
170                ForwardEnumsType forwardEnums;
171                ForwardStructsType forwardStructs;
172                ForwardUnionsType forwardUnions;
173                /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
174                bool inGeneric = false;
175        };
176
177        /// Does early resolution on the expressions that give enumeration constants their values
178        struct ResolveEnumInitializers final : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveEnumInitializers>, public WithShortCircuiting {
179                ResolveEnumInitializers( const Indexer * indexer );
180                void postvisit( EnumDecl * enumDecl );
181
182          private:
183                const Indexer * local_indexer;
184
185        };
186
187        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
188        struct ForallPointerDecay_old final {
189                void previsit( ObjectDecl * object );
190                void previsit( FunctionDecl * func );
191                void previsit( FunctionType * ftype );
192                void previsit( StructDecl * aggrDecl );
193                void previsit( UnionDecl * aggrDecl );
194        };
195
196        struct ReturnChecker : public WithGuards {
197                /// Checks that return statements return nothing if their return type is void
198                /// and return something if the return type is non-void.
199                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
200
201                void previsit( FunctionDecl * functionDecl );
202                void previsit( ReturnStmt * returnStmt );
203
204                typedef std::list< DeclarationWithType * > ReturnVals;
205                ReturnVals returnVals;
206        };
207
208        struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
209                ReplaceTypedef() : scopeLevel( 0 ) {}
210                /// Replaces typedefs by forward declarations
211                static void replaceTypedef( std::list< Declaration * > &translationUnit );
212
213                void premutate( QualifiedType * );
214                Type * postmutate( QualifiedType * qualType );
215                Type * postmutate( TypeInstType * aggregateUseType );
216                Declaration * postmutate( TypedefDecl * typeDecl );
217                void premutate( TypeDecl * typeDecl );
218                void premutate( FunctionDecl * funcDecl );
219                void premutate( ObjectDecl * objDecl );
220                DeclarationWithType * postmutate( ObjectDecl * objDecl );
221
222                void premutate( CastExpr * castExpr );
223
224                void premutate( CompoundStmt * compoundStmt );
225
226                void premutate( StructDecl * structDecl );
227                void premutate( UnionDecl * unionDecl );
228                void premutate( EnumDecl * enumDecl );
229                void premutate( TraitDecl * );
230
231                void premutate( FunctionType * ftype );
232
233          private:
234                template<typename AggDecl>
235                void addImplicitTypedef( AggDecl * aggDecl );
236                template< typename AggDecl >
237                void handleAggregate( AggDecl * aggr );
238
239                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
240                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
241                typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
242                TypedefMap typedefNames;
243                TypeDeclMap typedeclNames;
244                int scopeLevel;
245                bool inFunctionType = false;
246        };
247
248        struct EliminateTypedef {
249                /// removes TypedefDecls from the AST
250                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
251
252                template<typename AggDecl>
253                void handleAggregate( AggDecl * aggregateDecl );
254
255                void previsit( StructDecl * aggregateDecl );
256                void previsit( UnionDecl * aggregateDecl );
257                void previsit( CompoundStmt * compoundStmt );
258        };
259
260        struct VerifyCtorDtorAssign {
261                /// ensure that constructors, destructors, and assignment have at least one
262                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
263                /// return values.
264                static void verify( std::list< Declaration * > &translationUnit );
265
266                void previsit( FunctionDecl * funcDecl );
267        };
268
269        /// ensure that generic types have the correct number of type arguments
270        struct ValidateGenericParameters {
271                void previsit( StructInstType * inst );
272                void previsit( UnionInstType * inst );
273        };
274
275        /// desugar declarations and uses of dimension paramaters like [N],
276        /// from type-system managed values, to tunnneling via ordinary types,
277        /// as char[-] in and sizeof(-) out
278        struct TranslateDimensionGenericParameters : public WithIndexer, public WithGuards {
279                static void translateDimensions( std::list< Declaration * > &translationUnit );
280                TranslateDimensionGenericParameters();
281
282                bool nextVisitedNodeIsChildOfSUIT = false; // SUIT = Struct or Union -Inst Type
283                bool visitingChildOfSUIT = false;
284                void changeState_ChildOfSUIT( bool newVal );
285                void premutate( StructInstType * sit );
286                void premutate( UnionInstType * uit );
287                void premutate( BaseSyntaxNode * node );
288
289                TypeDecl * postmutate( TypeDecl * td );
290                Expression * postmutate( DimensionExpr * de );
291                Expression * postmutate( Expression * e );
292        };
293
294        struct FixObjectType : public WithIndexer {
295                /// resolves typeof type in object, function, and type declarations
296                static void fix( std::list< Declaration * > & translationUnit );
297
298                void previsit( ObjectDecl * );
299                void previsit( FunctionDecl * );
300                void previsit( TypeDecl * );
301        };
302
303        struct InitializerLength {
304                /// for array types without an explicit length, compute the length and store it so that it
305                /// is known to the rest of the phases. For example,
306                ///   int x[] = { 1, 2, 3 };
307                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
308                /// here x and y are known at compile-time to have length 3, so change this into
309                ///   int x[3] = { 1, 2, 3 };
310                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
311                static void computeLength( std::list< Declaration * > & translationUnit );
312
313                void previsit( ObjectDecl * objDecl );
314        };
315
316        struct ArrayLength : public WithIndexer {
317                static void computeLength( std::list< Declaration * > & translationUnit );
318
319                void previsit( ArrayType * arrayType );
320        };
321
322        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
323                Type::StorageClasses storageClasses;
324
325                void premutate( ObjectDecl * objectDecl );
326                Expression * postmutate( CompoundLiteralExpr * compLitExpr );
327        };
328
329        struct LabelAddressFixer final : public WithGuards {
330                std::set< Label > labels;
331
332                void premutate( FunctionDecl * funcDecl );
333                Expression * postmutate( AddressExpr * addrExpr );
334        };
335
336        void validate_A( std::list< Declaration * > & translationUnit ) {
337                PassVisitor<EnumAndPointerDecay_old> epc;
338                PassVisitor<HoistTypeDecls> hoistDecls;
339                {
340                        Stats::Heap::newPass("validate-A");
341                        Stats::Time::BlockGuard guard("validate-A");
342                        VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
343                        acceptAll( translationUnit, hoistDecls );
344                        ReplaceTypedef::replaceTypedef( translationUnit );
345                        ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
346                        acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes_old because it is an indexer and needs correct types for mangling
347                }
348        }
349
350        void validate_B( std::list< Declaration * > & translationUnit ) {
351                PassVisitor<LinkReferenceToTypes_old> lrt( nullptr );
352                PassVisitor<FixQualifiedTypes> fixQual;
353                {
354                        Stats::Heap::newPass("validate-B");
355                        Stats::Time::BlockGuard guard("validate-B");
356                        acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
357                        mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes_old, because aggregate members are accessed
358                        HoistStruct::hoistStruct( translationUnit );
359                        EliminateTypedef::eliminateTypedef( translationUnit );
360                }
361        }
362
363        void validate_C( std::list< Declaration * > & translationUnit ) {
364                PassVisitor<ValidateGenericParameters> genericParams;
365                PassVisitor<ResolveEnumInitializers> rei( nullptr );
366                {
367                        Stats::Heap::newPass("validate-C");
368                        Stats::Time::BlockGuard guard("validate-C");
369                        Stats::Time::TimeBlock("Validate Generic Parameters", [&]() {
370                                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes_old; observed failing when attempted before eliminateTypedef
371                        });
372                        Stats::Time::TimeBlock("Translate Dimensions", [&]() {
373                                TranslateDimensionGenericParameters::translateDimensions( translationUnit );
374                        });
375                        Stats::Time::TimeBlock("Resolve Enum Initializers", [&]() {
376                                acceptAll( translationUnit, rei ); // must happen after translateDimensions because rei needs identifier lookup, which needs name mangling
377                        });
378                        Stats::Time::TimeBlock("Check Function Returns", [&]() {
379                                ReturnChecker::checkFunctionReturns( translationUnit );
380                        });
381                        Stats::Time::TimeBlock("Fix Return Statements", [&]() {
382                                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
383                        });
384                }
385        }
386
387        void validate_D( std::list< Declaration * > & translationUnit ) {
388                PassVisitor<ForallPointerDecay_old> fpd;
389                {
390                        Stats::Heap::newPass("validate-D");
391                        Stats::Time::BlockGuard guard("validate-D");
392                        Stats::Time::TimeBlock("Apply Concurrent Keywords", [&]() {
393                                Concurrency::applyKeywords( translationUnit );
394                        });
395                        Stats::Time::TimeBlock("Forall Pointer Decay", [&]() {
396                                acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
397                        });
398                        Stats::Time::TimeBlock("Hoist Control Declarations", [&]() {
399                                ControlStruct::hoistControlDecls( translationUnit );  // hoist initialization out of for statements; must happen before autogenerateRoutines
400                        });
401                        Stats::Time::TimeBlock("Generate Autogen routines", [&]() {
402                                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay_old
403                        });
404                }
405        }
406
407        void validate_E( std::list< Declaration * > & translationUnit ) {
408                PassVisitor<CompoundLiteral> compoundliteral;
409                {
410                        Stats::Heap::newPass("validate-E");
411                        Stats::Time::BlockGuard guard("validate-E");
412                        Stats::Time::TimeBlock("Implement Mutex Func", [&]() {
413                                Concurrency::implementMutexFuncs( translationUnit );
414                        });
415                        Stats::Time::TimeBlock("Implement Thread Start", [&]() {
416                                Concurrency::implementThreadStarter( translationUnit );
417                        });
418                        Stats::Time::TimeBlock("Compound Literal", [&]() {
419                                mutateAll( translationUnit, compoundliteral );
420                        });
421                        if (!useNewAST) {
422                                Stats::Time::TimeBlock("Resolve With Expressions", [&]() {
423                                        ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables
424                                });
425                        }
426                }
427        }
428
429        void validate_F( std::list< Declaration * > & translationUnit ) {
430                PassVisitor<LabelAddressFixer> labelAddrFixer;
431                {
432                        Stats::Heap::newPass("validate-F");
433                        Stats::Time::BlockGuard guard("validate-F");
434                        if (!useNewAST) {
435                                Stats::Time::TimeCall("Fix Object Type",
436                                        FixObjectType::fix, translationUnit);
437                        }
438                        Stats::Time::TimeCall("Initializer Length",
439                                InitializerLength::computeLength, translationUnit);
440                        if (!useNewAST) {
441                                Stats::Time::TimeCall("Array Length",
442                                        ArrayLength::computeLength, translationUnit);
443                        }
444                        Stats::Time::TimeCall("Find Special Declarations",
445                                Validate::findSpecialDecls, translationUnit);
446                        Stats::Time::TimeCall("Fix Label Address",
447                                mutateAll<LabelAddressFixer>, translationUnit, labelAddrFixer);
448                        if (!useNewAST) {
449                                Stats::Time::TimeCall("Handle Attributes",
450                                        Validate::handleAttributes, translationUnit);
451                        }
452                }
453        }
454
455        void decayForallPointers( std::list< Declaration * > & translationUnit ) {
456                PassVisitor<ForallPointerDecay_old> fpd;
457                acceptAll( translationUnit, fpd );
458        }
459
460        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
461                validate_A( translationUnit );
462                validate_B( translationUnit );
463                validate_C( translationUnit );
464                validate_D( translationUnit );
465                validate_E( translationUnit );
466                validate_F( translationUnit );
467        }
468
469        void validateType( Type * type, const Indexer * indexer ) {
470                PassVisitor<EnumAndPointerDecay_old> epc;
471                PassVisitor<LinkReferenceToTypes_old> lrt( indexer );
472                PassVisitor<ForallPointerDecay_old> fpd;
473                type->accept( epc );
474                type->accept( lrt );
475                type->accept( fpd );
476        }
477
478        void HoistTypeDecls::handleType( Type * type ) {
479                // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
480                AggregateDecl * aggr = nullptr;
481                if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
482                        aggr = inst->baseStruct;
483                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
484                        aggr = inst->baseUnion;
485                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
486                        aggr = inst->baseEnum;
487                }
488                if ( aggr && aggr->body ) {
489                        declsToAddBefore.push_front( aggr );
490                }
491        }
492
493        void HoistTypeDecls::previsit( SizeofExpr * expr ) {
494                handleType( expr->type );
495        }
496
497        void HoistTypeDecls::previsit( AlignofExpr * expr ) {
498                handleType( expr->type );
499        }
500
501        void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
502                handleType( expr->type );
503        }
504
505        void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
506                handleType( expr->result );
507        }
508
509
510        Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
511                Type * parent = qualType->parent;
512                Type * child = qualType->child;
513                if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
514                        // .T => lookup T at global scope
515                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
516                                auto td = indexer.globalLookupType( inst->name );
517                                if ( ! td ) {
518                                        SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
519                                }
520                                auto base = td->base;
521                                assert( base );
522                                Type * ret = base->clone();
523                                ret->get_qualifiers() = qualType->get_qualifiers();
524                                return ret;
525                        } else {
526                                // .T => T is not a type name
527                                assertf( false, "unhandled global qualified child type: %s", toCString(child) );
528                        }
529                } else {
530                        // S.T => S must be an aggregate type, find the declaration for T in S.
531                        AggregateDecl * aggr = nullptr;
532                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
533                                aggr = inst->baseStruct;
534                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
535                                aggr = inst->baseUnion;
536                        } else {
537                                SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
538                        }
539                        assert( aggr ); // TODO: need to handle forward declarations
540                        for ( Declaration * member : aggr->members ) {
541                                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
542                                        // name on the right is a typedef
543                                        if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
544                                                if ( aggr->name == inst->name ) {
545                                                        assert( aggr->base );
546                                                        Type * ret = aggr->base->clone();
547                                                        ret->get_qualifiers() = qualType->get_qualifiers();
548                                                        TypeSubstitution sub = parent->genericSubstitution();
549                                                        sub.apply(ret);
550                                                        return ret;
551                                                }
552                                        }
553                                } else {
554                                        // S.T - S is not an aggregate => error
555                                        assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
556                                }
557                        }
558                        // failed to find a satisfying definition of type
559                        SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
560                }
561
562                // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
563        }
564
565
566        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
567                PassVisitor<HoistStruct> hoister;
568                acceptAll( translationUnit, hoister );
569        }
570
571        bool shouldHoist( Declaration * decl ) {
572                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
573        }
574
575        namespace {
576                void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
577                        if ( aggr->parent ) qualifiedName( aggr->parent, ss );
578                        ss << "__" << aggr->name;
579                }
580
581                // mangle nested type names using entire parent chain
582                std::string qualifiedName( AggregateDecl * aggr ) {
583                        std::ostringstream ss;
584                        qualifiedName( aggr, ss );
585                        return ss.str();
586                }
587        }
588
589        template< typename AggDecl >
590        void HoistStruct::handleAggregate( AggDecl * aggregateDecl ) {
591                if ( parentAggr ) {
592                        aggregateDecl->parent = parentAggr;
593                        aggregateDecl->name = qualifiedName( aggregateDecl );
594                        // Add elements in stack order corresponding to nesting structure.
595                        declsToAddBefore.push_front( aggregateDecl );
596                } else {
597                        GuardValue( parentAggr );
598                        parentAggr = aggregateDecl;
599                } // if
600                // Always remove the hoisted aggregate from the inner structure.
601                GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
602        }
603
604        void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
605                if ( parentAggr ) {
606                        declsToAddBefore.push_back( assertDecl );
607                }
608        }
609
610        void HoistStruct::previsit( StructDecl * aggregateDecl ) {
611                handleAggregate( aggregateDecl );
612        }
613
614        void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
615                handleAggregate( aggregateDecl );
616        }
617
618        void HoistStruct::previsit( StructInstType * type ) {
619                // need to reset type name after expanding to qualified name
620                assert( type->baseStruct );
621                type->name = type->baseStruct->name;
622        }
623
624        void HoistStruct::previsit( UnionInstType * type ) {
625                assert( type->baseUnion );
626                type->name = type->baseUnion->name;
627        }
628
629        void HoistStruct::previsit( EnumInstType * type ) {
630                assert( type->baseEnum );
631                type->name = type->baseEnum->name;
632        }
633
634
635        bool isTypedef( Declaration * decl ) {
636                return dynamic_cast< TypedefDecl * >( decl );
637        }
638
639        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
640                PassVisitor<EliminateTypedef> eliminator;
641                acceptAll( translationUnit, eliminator );
642                filter( translationUnit, isTypedef, true );
643        }
644
645        template< typename AggDecl >
646        void EliminateTypedef::handleAggregate( AggDecl * aggregateDecl ) {
647                filter( aggregateDecl->members, isTypedef, true );
648        }
649
650        void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
651                handleAggregate( aggregateDecl );
652        }
653
654        void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
655                handleAggregate( aggregateDecl );
656        }
657
658        void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
659                // remove and delete decl stmts
660                filter( compoundStmt->kids, [](Statement * stmt) {
661                        if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
662                                if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
663                                        return true;
664                                } // if
665                        } // if
666                        return false;
667                }, true);
668        }
669
670        void EnumAndPointerDecay_old::previsit( EnumDecl * enumDecl ) {
671                // Set the type of each member of the enumeration to be EnumConstant
672                for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
673                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( * i );
674                        assert( obj );
675                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
676                } // for
677        }
678
679        namespace {
680                template< typename DWTList >
681                void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
682                        auto nvals = dwts.size();
683                        bool containsVoid = false;
684                        for ( auto & dwt : dwts ) {
685                                // fix each DWT and record whether a void was found
686                                containsVoid |= fixFunction( dwt );
687                        }
688
689                        // the only case in which "void" is valid is where it is the only one in the list
690                        if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
691                                SemanticError( func, "invalid type void in function type " );
692                        }
693
694                        // one void is the only thing in the list; remove it.
695                        if ( containsVoid ) {
696                                delete dwts.front();
697                                dwts.clear();
698                        }
699                }
700        }
701
702        void EnumAndPointerDecay_old::previsit( FunctionType * func ) {
703                // Fix up parameters and return types
704                fixFunctionList( func->parameters, func->isVarArgs, func );
705                fixFunctionList( func->returnVals, false, func );
706        }
707
708        LinkReferenceToTypes_old::LinkReferenceToTypes_old( const Indexer * other_indexer ) : WithIndexer( false ) {
709                if ( other_indexer ) {
710                        local_indexer = other_indexer;
711                } else {
712                        local_indexer = &indexer;
713                } // if
714        }
715
716        void LinkReferenceToTypes_old::postvisit( EnumInstType * enumInst ) {
717                const EnumDecl * st = local_indexer->lookupEnum( enumInst->name );
718                // it's not a semantic error if the enum is not found, just an implicit forward declaration
719                if ( st ) {
720                        enumInst->baseEnum = const_cast<EnumDecl *>(st); // Just linking in the node
721                } // if
722                if ( ! st || ! st->body ) {
723                        // use of forward declaration
724                        forwardEnums[ enumInst->name ].push_back( enumInst );
725                } // if
726        }
727
728        void LinkReferenceToTypes_old::postvisit( StructInstType * structInst ) {
729                const StructDecl * st = local_indexer->lookupStruct( structInst->name );
730                // it's not a semantic error if the struct is not found, just an implicit forward declaration
731                if ( st ) {
732                        structInst->baseStruct = const_cast<StructDecl *>(st); // Just linking in the node
733                } // if
734                if ( ! st || ! st->body ) {
735                        // use of forward declaration
736                        forwardStructs[ structInst->name ].push_back( structInst );
737                } // if
738        }
739
740        void LinkReferenceToTypes_old::postvisit( UnionInstType * unionInst ) {
741                const UnionDecl * un = local_indexer->lookupUnion( unionInst->name );
742                // it's not a semantic error if the union is not found, just an implicit forward declaration
743                if ( un ) {
744                        unionInst->baseUnion = const_cast<UnionDecl *>(un); // Just linking in the node
745                } // if
746                if ( ! un || ! un->body ) {
747                        // use of forward declaration
748                        forwardUnions[ unionInst->name ].push_back( unionInst );
749                } // if
750        }
751
752        void LinkReferenceToTypes_old::previsit( QualifiedType * ) {
753                visit_children = false;
754        }
755
756        void LinkReferenceToTypes_old::postvisit( QualifiedType * qualType ) {
757                // linking only makes sense for the 'oldest ancestor' of the qualified type
758                qualType->parent->accept( * visitor );
759        }
760
761        template< typename Decl >
762        void normalizeAssertions( std::list< Decl * > & assertions ) {
763                // ensure no duplicate trait members after the clone
764                auto pred = [](Decl * d1, Decl * d2) {
765                        // only care if they're equal
766                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
767                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
768                        if ( dwt1 && dwt2 ) {
769                                if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
770                                        // std::cerr << "=========== equal:" << std::endl;
771                                        // std::cerr << "d1: " << d1 << std::endl;
772                                        // std::cerr << "d2: " << d2 << std::endl;
773                                        return false;
774                                }
775                        }
776                        return d1 < d2;
777                };
778                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
779                // if ( unique_members.size() != assertions.size() ) {
780                //      std::cerr << "============different" << std::endl;
781                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
782                // }
783
784                std::list< Decl * > order;
785                order.splice( order.end(), assertions );
786                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
787                        return unique_members.count( decl );
788                });
789        }
790
791        // expand assertions from trait instance, performing the appropriate type variable substitutions
792        template< typename Iterator >
793        void expandAssertions( TraitInstType * inst, Iterator out ) {
794                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
795                std::list< DeclarationWithType * > asserts;
796                for ( Declaration * decl : inst->baseTrait->members ) {
797                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
798                }
799                // substitute trait decl parameters for instance parameters
800                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
801        }
802
803        void LinkReferenceToTypes_old::postvisit( TraitDecl * traitDecl ) {
804                if ( traitDecl->name == "sized" ) {
805                        // "sized" is a special trait - flick the sized status on for the type variable
806                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
807                        TypeDecl * td = traitDecl->parameters.front();
808                        td->set_sized( true );
809                }
810
811                // move assertions from type parameters into the body of the trait
812                for ( TypeDecl * td : traitDecl->parameters ) {
813                        for ( DeclarationWithType * assert : td->assertions ) {
814                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
815                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
816                                } else {
817                                        traitDecl->members.push_back( assert->clone() );
818                                }
819                        }
820                        deleteAll( td->assertions );
821                        td->assertions.clear();
822                } // for
823        }
824
825        void LinkReferenceToTypes_old::postvisit( TraitInstType * traitInst ) {
826                // handle other traits
827                const TraitDecl * traitDecl = local_indexer->lookupTrait( traitInst->name );
828                if ( ! traitDecl ) {
829                        SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
830                } // if
831                if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
832                        SemanticError( traitInst, "incorrect number of trait parameters: " );
833                } // if
834                traitInst->baseTrait = const_cast<TraitDecl *>(traitDecl); // Just linking in the node
835
836                // need to carry over the 'sized' status of each decl in the instance
837                for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
838                        TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
839                        if ( ! expr ) {
840                                SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
841                        }
842                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
843                                TypeDecl * formalDecl = std::get<0>(p);
844                                TypeDecl * instDecl = inst->baseType;
845                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
846                        }
847                }
848                // normalizeAssertions( traitInst->members );
849        }
850
851        void LinkReferenceToTypes_old::postvisit( EnumDecl * enumDecl ) {
852                // visit enum members first so that the types of self-referencing members are updated properly
853                if ( enumDecl->body ) {
854                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
855                        if ( fwds != forwardEnums.end() ) {
856                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
857                                        (* inst)->baseEnum = enumDecl;
858                                } // for
859                                forwardEnums.erase( fwds );
860                        } // if
861                } // if
862        }
863
864        void LinkReferenceToTypes_old::renameGenericParams( std::list< TypeDecl * > & params ) {
865                // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
866                //   forall(otype T)
867                //   struct Box {
868                //     T x;
869                //   };
870                //   forall(otype T)
871                //   void f(Box(T) b) {
872                //     ...
873                //   }
874                // The T in Box and the T in f are different, so internally the naming must reflect that.
875                GuardValue( inGeneric );
876                inGeneric = ! params.empty();
877                for ( TypeDecl * td : params ) {
878                        td->name = "__" + td->name + "_generic_";
879                }
880        }
881
882        void LinkReferenceToTypes_old::previsit( StructDecl * structDecl ) {
883                renameGenericParams( structDecl->parameters );
884        }
885
886        void LinkReferenceToTypes_old::previsit( UnionDecl * unionDecl ) {
887                renameGenericParams( unionDecl->parameters );
888        }
889
890        void LinkReferenceToTypes_old::postvisit( StructDecl * structDecl ) {
891                // visit struct members first so that the types of self-referencing members are updated properly
892                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
893                if ( structDecl->body ) {
894                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
895                        if ( fwds != forwardStructs.end() ) {
896                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
897                                        (* inst)->baseStruct = structDecl;
898                                } // for
899                                forwardStructs.erase( fwds );
900                        } // if
901                } // if
902        }
903
904        void LinkReferenceToTypes_old::postvisit( UnionDecl * unionDecl ) {
905                if ( unionDecl->body ) {
906                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
907                        if ( fwds != forwardUnions.end() ) {
908                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
909                                        (* inst)->baseUnion = unionDecl;
910                                } // for
911                                forwardUnions.erase( fwds );
912                        } // if
913                } // if
914        }
915
916        void LinkReferenceToTypes_old::postvisit( TypeInstType * typeInst ) {
917                // ensure generic parameter instances are renamed like the base type
918                if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
919                if ( const NamedTypeDecl * namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
920                        if ( const TypeDecl * typeDecl = dynamic_cast< const TypeDecl * >( namedTypeDecl ) ) {
921                                typeInst->set_isFtype( typeDecl->kind == TypeDecl::Ftype );
922                        } // if
923                } // if
924        }
925
926        ResolveEnumInitializers::ResolveEnumInitializers( const Indexer * other_indexer ) : WithIndexer( true ) {
927                if ( other_indexer ) {
928                        local_indexer = other_indexer;
929                } else {
930                        local_indexer = &indexer;
931                } // if
932        }
933
934        void ResolveEnumInitializers::postvisit( EnumDecl * enumDecl ) {
935                if ( enumDecl->body ) {
936                        for ( Declaration * member : enumDecl->members ) {
937                                ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member );
938                                if ( field->init ) {
939                                        // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information.
940                                        SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init );
941                                        ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
942                                }
943                        }
944                } // if
945        }
946
947        /// Fix up assertions - flattens assertion lists, removing all trait instances
948        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
949                for ( TypeDecl * type : forall ) {
950                        std::list< DeclarationWithType * > asserts;
951                        asserts.splice( asserts.end(), type->assertions );
952                        // expand trait instances into their members
953                        for ( DeclarationWithType * assertion : asserts ) {
954                                if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
955                                        // expand trait instance into all of its members
956                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
957                                        delete traitInst;
958                                } else {
959                                        // pass other assertions through
960                                        type->assertions.push_back( assertion );
961                                } // if
962                        } // for
963                        // apply FixFunction to every assertion to check for invalid void type
964                        for ( DeclarationWithType *& assertion : type->assertions ) {
965                                bool isVoid = fixFunction( assertion );
966                                if ( isVoid ) {
967                                        SemanticError( node, "invalid type void in assertion of function " );
968                                } // if
969                        } // for
970                        // normalizeAssertions( type->assertions );
971                } // for
972        }
973
974        void ForallPointerDecay_old::previsit( ObjectDecl * object ) {
975                // ensure that operator names only apply to functions or function pointers
976                if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
977                        SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
978                }
979                object->fixUniqueId();
980        }
981
982        void ForallPointerDecay_old::previsit( FunctionDecl * func ) {
983                func->fixUniqueId();
984        }
985
986        void ForallPointerDecay_old::previsit( FunctionType * ftype ) {
987                forallFixer( ftype->forall, ftype );
988        }
989
990        void ForallPointerDecay_old::previsit( StructDecl * aggrDecl ) {
991                forallFixer( aggrDecl->parameters, aggrDecl );
992        }
993
994        void ForallPointerDecay_old::previsit( UnionDecl * aggrDecl ) {
995                forallFixer( aggrDecl->parameters, aggrDecl );
996        }
997
998        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
999                PassVisitor<ReturnChecker> checker;
1000                acceptAll( translationUnit, checker );
1001        }
1002
1003        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
1004                GuardValue( returnVals );
1005                returnVals = functionDecl->get_functionType()->get_returnVals();
1006        }
1007
1008        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
1009                // Previously this also checked for the existence of an expr paired with no return values on
1010                // the  function return type. This is incorrect, since you can have an expression attached to
1011                // a return statement in a void-returning function in C. The expression is treated as if it
1012                // were cast to void.
1013                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
1014                        SemanticError( returnStmt, "Non-void function returns no values: " );
1015                }
1016        }
1017
1018
1019        void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
1020                PassVisitor<ReplaceTypedef> eliminator;
1021                mutateAll( translationUnit, eliminator );
1022                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
1023                        // grab and remember declaration of size_t
1024                        Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
1025                } else {
1026                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
1027                        // eventually should have a warning for this case.
1028                        Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1029                }
1030        }
1031
1032        void ReplaceTypedef::premutate( QualifiedType * ) {
1033                visit_children = false;
1034        }
1035
1036        Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
1037                // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
1038                qualType->parent = qualType->parent->acceptMutator( * visitor );
1039                return qualType;
1040        }
1041
1042        static bool isNonParameterAttribute( Attribute * attr ) {
1043                static const std::vector<std::string> bad_names = {
1044                        "aligned", "__aligned__",
1045                };
1046                for ( auto name : bad_names ) {
1047                        if ( name == attr->name ) {
1048                                return true;
1049                        }
1050                }
1051                return false;
1052        }
1053
1054        Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
1055                // instances of typedef types will come here. If it is an instance
1056                // of a typdef type, link the instance to its actual type.
1057                TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
1058                if ( def != typedefNames.end() ) {
1059                        Type * ret = def->second.first->base->clone();
1060                        ret->location = typeInst->location;
1061                        ret->get_qualifiers() |= typeInst->get_qualifiers();
1062                        // GCC ignores certain attributes if they arrive by typedef, this mimics that.
1063                        if ( inFunctionType ) {
1064                                ret->attributes.remove_if( isNonParameterAttribute );
1065                        }
1066                        ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
1067                        // place instance parameters on the typedef'd type
1068                        if ( ! typeInst->parameters.empty() ) {
1069                                ReferenceToType * rtt = dynamic_cast<ReferenceToType *>(ret);
1070                                if ( ! rtt ) {
1071                                        SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
1072                                }
1073                                rtt->parameters.clear();
1074                                cloneAll( typeInst->parameters, rtt->parameters );
1075                                mutateAll( rtt->parameters, * visitor );  // recursively fix typedefs on parameters
1076                        } // if
1077                        delete typeInst;
1078                        return ret;
1079                } else {
1080                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
1081                        if ( base == typedeclNames.end() ) {
1082                                SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
1083                        }
1084                        typeInst->set_baseType( base->second );
1085                        return typeInst;
1086                } // if
1087                assert( false );
1088        }
1089
1090        struct VarLenChecker : WithShortCircuiting {
1091                void previsit( FunctionType * ) { visit_children = false; }
1092                void previsit( ArrayType * at ) {
1093                        isVarLen |= at->isVarLen;
1094                }
1095                bool isVarLen = false;
1096        };
1097
1098        bool isVariableLength( Type * t ) {
1099                PassVisitor<VarLenChecker> varLenChecker;
1100                maybeAccept( t, varLenChecker );
1101                return varLenChecker.pass.isVarLen;
1102        }
1103
1104        Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
1105                if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
1106                        // typedef to the same name from the same scope
1107                        // must be from the same type
1108
1109                        Type * t1 = tyDecl->base;
1110                        Type * t2 = typedefNames[ tyDecl->name ].first->base;
1111                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
1112                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1113                        }
1114                        // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
1115                        // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
1116                        // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
1117                        // to fix this corner case likely outweighs the utility of allowing it.
1118                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
1119                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1120                        }
1121                } else {
1122                        typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
1123                } // if
1124
1125                // When a typedef is a forward declaration:
1126                //    typedef struct screen SCREEN;
1127                // the declaration portion must be retained:
1128                //    struct screen;
1129                // because the expansion of the typedef is:
1130                //    void rtn( SCREEN * p ) => void rtn( struct screen * p )
1131                // hence the type-name "screen" must be defined.
1132                // Note, qualifiers on the typedef are superfluous for the forward declaration.
1133
1134                Type * designatorType = tyDecl->base->stripDeclarator();
1135                if ( StructInstType * aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
1136                        declsToAddBefore.push_back( new StructDecl( aggDecl->name, AggregateDecl::Struct, noAttributes, tyDecl->linkage ) );
1137                } else if ( UnionInstType * aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
1138                        declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
1139                } else if ( EnumInstType * enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
1140                        declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage ) );
1141                } // if
1142                return tyDecl->clone();
1143        }
1144
1145        void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
1146                TypedefMap::iterator i = typedefNames.find( typeDecl->name );
1147                if ( i != typedefNames.end() ) {
1148                        typedefNames.erase( i ) ;
1149                } // if
1150
1151                typedeclNames.insert( typeDecl->name, typeDecl );
1152        }
1153
1154        void ReplaceTypedef::premutate( FunctionDecl * ) {
1155                GuardScope( typedefNames );
1156                GuardScope( typedeclNames );
1157        }
1158
1159        void ReplaceTypedef::premutate( ObjectDecl * ) {
1160                GuardScope( typedefNames );
1161                GuardScope( typedeclNames );
1162        }
1163
1164        DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
1165                if ( FunctionType * funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
1166                        // replace the current object declaration with a function declaration
1167                        FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
1168                        objDecl->attributes.clear();
1169                        objDecl->set_type( nullptr );
1170                        delete objDecl;
1171                        return newDecl;
1172                } // if
1173                return objDecl;
1174        }
1175
1176        void ReplaceTypedef::premutate( CastExpr * ) {
1177                GuardScope( typedefNames );
1178                GuardScope( typedeclNames );
1179        }
1180
1181        void ReplaceTypedef::premutate( CompoundStmt * ) {
1182                GuardScope( typedefNames );
1183                GuardScope( typedeclNames );
1184                scopeLevel += 1;
1185                GuardAction( [this](){ scopeLevel -= 1; } );
1186        }
1187
1188        template<typename AggDecl>
1189        void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
1190                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
1191                        Type * type = nullptr;
1192                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
1193                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
1194                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
1195                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
1196                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
1197                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
1198                        } // if
1199                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
1200                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
1201                        // add the implicit typedef to the AST
1202                        declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
1203                } // if
1204        }
1205
1206        template< typename AggDecl >
1207        void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
1208                SemanticErrorException errors;
1209
1210                ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
1211                ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter  );
1212                declsToAddBefore.clear();
1213                declsToAddAfter.clear();
1214
1215                GuardScope( typedefNames );
1216                GuardScope( typedeclNames );
1217                mutateAll( aggr->parameters, * visitor );
1218                mutateAll( aggr->attributes, * visitor );
1219
1220                // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
1221                for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
1222                        if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
1223
1224                        try {
1225                                * i = maybeMutate( * i, * visitor );
1226                        } catch ( SemanticErrorException &e ) {
1227                                errors.append( e );
1228                        }
1229
1230                        if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
1231                }
1232
1233                if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
1234                if ( !errors.isEmpty() ) { throw errors; }
1235        }
1236
1237        void ReplaceTypedef::premutate( StructDecl * structDecl ) {
1238                visit_children = false;
1239                addImplicitTypedef( structDecl );
1240                handleAggregate( structDecl );
1241        }
1242
1243        void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
1244                visit_children = false;
1245                addImplicitTypedef( unionDecl );
1246                handleAggregate( unionDecl );
1247        }
1248
1249        void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
1250                addImplicitTypedef( enumDecl );
1251        }
1252
1253        void ReplaceTypedef::premutate( FunctionType * ) {
1254                GuardValue( inFunctionType );
1255                inFunctionType = true;
1256        }
1257
1258        void ReplaceTypedef::premutate( TraitDecl * ) {
1259                GuardScope( typedefNames );
1260                GuardScope( typedeclNames);
1261        }
1262
1263        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
1264                PassVisitor<VerifyCtorDtorAssign> verifier;
1265                acceptAll( translationUnit, verifier );
1266        }
1267
1268        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
1269                FunctionType * funcType = funcDecl->get_functionType();
1270                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1271                std::list< DeclarationWithType * > &params = funcType->get_parameters();
1272
1273                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
1274                        if ( params.size() == 0 ) {
1275                                SemanticError( funcDecl->location, "Constructors, destructors, and assignment functions require at least one parameter." );
1276                        }
1277                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
1278                        if ( ! refType ) {
1279                                SemanticError( funcDecl->location, "First parameter of a constructor, destructor, or assignment function must be a reference." );
1280                        }
1281                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
1282                                if(!returnVals.front()->get_type()->isVoid()) {
1283                                        SemanticError( funcDecl->location, "Constructors and destructors cannot have explicit return values." );
1284                                }
1285                        }
1286                }
1287        }
1288
1289        // Test for special name on a generic parameter.  Special treatment for the
1290        // special name is a bootstrapping hack.  In most cases, the worlds of T's
1291        // and of N's don't overlap (normal treamtemt).  The foundations in
1292        // array.hfa use tagging for both types and dimensions.  Tagging treats
1293        // its subject parameter even more opaquely than T&, which assumes it is
1294        // possible to have a pointer/reference to such an object.  Tagging only
1295        // seeks to identify the type-system resident at compile time.  Both N's
1296        // and T's can make tags.  The tag definition uses the special name, which
1297        // is treated as "an N or a T."  This feature is not inteded to be used
1298        // outside of the definition and immediate uses of a tag.
1299        static inline bool isReservedTysysIdOnlyName( const std::string & name ) {
1300                // name's prefix was __CFA_tysys_id_only, before it got wrapped in __..._generic
1301                int foundAt = name.find("__CFA_tysys_id_only");
1302                if (foundAt == 0) return true;
1303                if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true;
1304                return false;
1305        }
1306
1307        template< typename Aggr >
1308        void validateGeneric( Aggr * inst ) {
1309                std::list< TypeDecl * > * params = inst->get_baseParameters();
1310                if ( params ) {
1311                        std::list< Expression * > & args = inst->get_parameters();
1312
1313                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1314                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1315                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1316                        //   vector(int) v;
1317                        // after insertion of default values becomes
1318                        //   vector(int, heap_allocator(T))
1319                        // and the substitution is built with T=int so that after substitution, the result is
1320                        //   vector(int, heap_allocator(int))
1321                        TypeSubstitution sub;
1322                        auto paramIter = params->begin();
1323                        auto argIter = args.begin();
1324                        for ( ; paramIter != params->end(); ++paramIter, ++argIter ) {
1325                                if ( argIter != args.end() ) {
1326                                        TypeExpr * expr = dynamic_cast< TypeExpr * >( * argIter );
1327                                        if ( expr ) {
1328                                                sub.add( (* paramIter)->get_name(), expr->get_type()->clone() );
1329                                        }
1330                                } else {
1331                                        Type * defaultType = (* paramIter)->get_init();
1332                                        if ( defaultType ) {
1333                                                args.push_back( new TypeExpr( defaultType->clone() ) );
1334                                                sub.add( (* paramIter)->get_name(), defaultType->clone() );
1335                                                argIter = std::prev(args.end());
1336                                        } else {
1337                                                SemanticError( inst, "Too few type arguments in generic type " );
1338                                        }
1339                                }
1340                                assert( argIter != args.end() );
1341                                bool typeParamDeclared = (*paramIter)->kind != TypeDecl::Kind::Dimension;
1342                                bool typeArgGiven;
1343                                if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) {
1344                                        // coerce a match when declaration is reserved name, which means "either"
1345                                        typeArgGiven = typeParamDeclared;
1346                                } else {
1347                                        typeArgGiven = dynamic_cast< TypeExpr * >( * argIter );
1348                                }
1349                                if ( ! typeParamDeclared &&   typeArgGiven ) SemanticError( inst, "Type argument given for value parameter: " );
1350                                if (   typeParamDeclared && ! typeArgGiven ) SemanticError( inst, "Expression argument given for type parameter: " );
1351                        }
1352
1353                        sub.apply( inst );
1354                        if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1355                }
1356        }
1357
1358        void ValidateGenericParameters::previsit( StructInstType * inst ) {
1359                validateGeneric( inst );
1360        }
1361
1362        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1363                validateGeneric( inst );
1364        }
1365
1366        void TranslateDimensionGenericParameters::translateDimensions( std::list< Declaration * > &translationUnit ) {
1367                PassVisitor<TranslateDimensionGenericParameters> translator;
1368                mutateAll( translationUnit, translator );
1369        }
1370
1371        TranslateDimensionGenericParameters::TranslateDimensionGenericParameters() : WithIndexer( false ) {}
1372
1373        // Declaration of type variable:           forall( [N] )          ->  forall( N & | sized( N ) )
1374        TypeDecl * TranslateDimensionGenericParameters::postmutate( TypeDecl * td ) {
1375                if ( td->kind == TypeDecl::Dimension ) {
1376                        td->kind = TypeDecl::Dtype;
1377                        if ( ! isReservedTysysIdOnlyName( td->name ) ) {
1378                                td->sized = true;
1379                        }
1380                }
1381                return td;
1382        }
1383
1384        // Situational awareness:
1385        // array( float, [[currentExpr]]     )  has  visitingChildOfSUIT == true
1386        // array( float, [[currentExpr]] - 1 )  has  visitingChildOfSUIT == false
1387        // size_t x =    [[currentExpr]]        has  visitingChildOfSUIT == false
1388        void TranslateDimensionGenericParameters::changeState_ChildOfSUIT( bool newVal ) {
1389                GuardValue( nextVisitedNodeIsChildOfSUIT );
1390                GuardValue( visitingChildOfSUIT );
1391                visitingChildOfSUIT = nextVisitedNodeIsChildOfSUIT;
1392                nextVisitedNodeIsChildOfSUIT = newVal;
1393        }
1394        void TranslateDimensionGenericParameters::premutate( StructInstType * sit ) {
1395                (void) sit;
1396                changeState_ChildOfSUIT(true);
1397        }
1398        void TranslateDimensionGenericParameters::premutate( UnionInstType * uit ) {
1399                (void) uit;
1400                changeState_ChildOfSUIT(true);
1401        }
1402        void TranslateDimensionGenericParameters::premutate( BaseSyntaxNode * node ) {
1403                (void) node;
1404                changeState_ChildOfSUIT(false);
1405        }
1406
1407        // Passing values as dimension arguments:  array( float,     7 )  -> array( float, char[             7 ] )
1408        // Consuming dimension parameters:         size_t x =    N - 1 ;  -> size_t x =          sizeof(N) - 1   ;
1409        // Intertwined reality:                    array( float, N     )  -> array( float,              N        )
1410        //                                         array( float, N - 1 )  -> array( float, char[ sizeof(N) - 1 ] )
1411        // Intertwined case 1 is not just an optimization.
1412        // Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
1413        //   forall([N]) void f( array(float, N) & );
1414        //   array(float, 7) a;
1415        //   f(a);
1416
1417        Expression * TranslateDimensionGenericParameters::postmutate( DimensionExpr * de ) {
1418                // Expression de is an occurrence of N in LHS of above examples.
1419                // Look up the name that de references.
1420                // If we are in a struct body, then this reference can be to an entry of the stuct's forall list.
1421                // Whether or not we are in a struct body, this reference can be to an entry of a containing function's forall list.
1422                // If we are in a struct body, then the stuct's forall declarations are innermost (functions don't occur in structs).
1423                // Thus, a potential struct's declaration is highest priority.
1424                // A struct's forall declarations are already renamed with _generic_ suffix.  Try that name variant first.
1425
1426                std::string useName = "__" + de->name + "_generic_";
1427                TypeDecl * namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1428
1429                if ( ! namedParamDecl ) {
1430                        useName = de->name;
1431                        namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1432                }
1433
1434                // Expect to find it always.  A misspelled name would have been parsed as an identifier.
1435                assert( namedParamDecl && "Type-system-managed value name not found in symbol table" );
1436
1437                delete de;
1438
1439                TypeInstType * refToDecl = new TypeInstType( 0, useName, namedParamDecl );
1440
1441                if ( visitingChildOfSUIT ) {
1442                        // As in postmutate( Expression * ), topmost expression needs a TypeExpr wrapper
1443                        // But avoid ArrayType-Sizeof
1444                        return new TypeExpr( refToDecl );
1445                } else {
1446                        // the N occurrence is being used directly as a runtime value,
1447                        // if we are in a type instantiation, then the N is within a bigger value computation
1448                        return new SizeofExpr( refToDecl );
1449                }
1450        }
1451
1452        Expression * TranslateDimensionGenericParameters::postmutate( Expression * e ) {
1453                if ( visitingChildOfSUIT ) {
1454                        // e is an expression used as an argument to instantiate a type
1455                        if (! dynamic_cast< TypeExpr * >( e ) ) {
1456                                // e is a value expression
1457                                // but not a DimensionExpr, which has a distinct postmutate
1458                                Type * typeExprContent = new ArrayType( 0, new BasicType( 0, BasicType::Char ), e, true, false );
1459                                TypeExpr * result = new TypeExpr( typeExprContent );
1460                                return result;
1461                        }
1462                }
1463                return e;
1464        }
1465
1466        void CompoundLiteral::premutate( ObjectDecl * objectDecl ) {
1467                storageClasses = objectDecl->get_storageClasses();
1468        }
1469
1470        Expression * CompoundLiteral::postmutate( CompoundLiteralExpr * compLitExpr ) {
1471                // transform [storage_class] ... (struct S){ 3, ... };
1472                // into [storage_class] struct S temp =  { 3, ... };
1473                static UniqueName indexName( "_compLit" );
1474
1475                ObjectDecl * tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1476                compLitExpr->set_result( nullptr );
1477                compLitExpr->set_initializer( nullptr );
1478                delete compLitExpr;
1479                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1480                return new VariableExpr( tempvar );
1481        }
1482
1483        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1484                PassVisitor<ReturnTypeFixer> fixer;
1485                acceptAll( translationUnit, fixer );
1486        }
1487
1488        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1489                FunctionType * ftype = functionDecl->get_functionType();
1490                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1491                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1492                if ( retVals.size() == 1 ) {
1493                        // 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).
1494                        // ensure other return values have a name.
1495                        DeclarationWithType * ret = retVals.front();
1496                        if ( ret->get_name() == "" ) {
1497                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1498                        }
1499                        ret->get_attributes().push_back( new Attribute( "unused" ) );
1500                }
1501        }
1502
1503        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1504                // xxx - need to handle named return values - this information needs to be saved somehow
1505                // so that resolution has access to the names.
1506                // Note that this pass needs to happen early so that other passes which look for tuple types
1507                // find them in all of the right places, including function return types.
1508                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1509                if ( retVals.size() > 1 ) {
1510                        // generate a single return parameter which is the tuple of all of the return values
1511                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1512                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1513                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer *>(), noDesignators, false ) );
1514                        deleteAll( retVals );
1515                        retVals.clear();
1516                        retVals.push_back( newRet );
1517                }
1518        }
1519
1520        void FixObjectType::fix( std::list< Declaration * > & translationUnit ) {
1521                PassVisitor<FixObjectType> fixer;
1522                acceptAll( translationUnit, fixer );
1523        }
1524
1525        void FixObjectType::previsit( ObjectDecl * objDecl ) {
1526                Type * new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer );
1527                objDecl->set_type( new_type );
1528        }
1529
1530        void FixObjectType::previsit( FunctionDecl * funcDecl ) {
1531                Type * new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer );
1532                funcDecl->set_type( new_type );
1533        }
1534
1535        void FixObjectType::previsit( TypeDecl * typeDecl ) {
1536                if ( typeDecl->get_base() ) {
1537                        Type * new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer );
1538                        typeDecl->set_base( new_type );
1539                } // if
1540        }
1541
1542        void InitializerLength::computeLength( std::list< Declaration * > & translationUnit ) {
1543                PassVisitor<InitializerLength> len;
1544                acceptAll( translationUnit, len );
1545        }
1546
1547        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1548                PassVisitor<ArrayLength> len;
1549                acceptAll( translationUnit, len );
1550        }
1551
1552        void InitializerLength::previsit( ObjectDecl * objDecl ) {
1553                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1554                        if ( at->dimension ) return;
1555                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1556                                at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
1557                        }
1558                }
1559        }
1560
1561        void ArrayLength::previsit( ArrayType * type ) {
1562                if ( type->dimension ) {
1563                        // need to resolve array dimensions early so that constructor code can correctly determine
1564                        // if a type is a VLA (and hence whether its elements need to be constructed)
1565                        ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
1566
1567                        // must re-evaluate whether a type is a VLA, now that more information is available
1568                        // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1569                        type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
1570                }
1571        }
1572
1573        struct LabelFinder {
1574                std::set< Label > & labels;
1575                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1576                void previsit( Statement * stmt ) {
1577                        for ( Label & l : stmt->labels ) {
1578                                labels.insert( l );
1579                        }
1580                }
1581        };
1582
1583        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1584                GuardValue( labels );
1585                PassVisitor<LabelFinder> finder( labels );
1586                funcDecl->accept( finder );
1587        }
1588
1589        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1590                // convert &&label into label address
1591                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1592                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1593                                if ( labels.count( nameExpr->name ) ) {
1594                                        Label name = nameExpr->name;
1595                                        delete addrExpr;
1596                                        return new LabelAddressExpr( name );
1597                                }
1598                        }
1599                }
1600                return addrExpr;
1601        }
1602
1603namespace {
1604        /// Replaces enum types by int, and function/array types in function parameter and return
1605        /// lists by appropriate pointers
1606        /*
1607        struct EnumAndPointerDecay_new {
1608                const ast::EnumDecl * previsit( const ast::EnumDecl * enumDecl ) {
1609                        // set the type of each member of the enumeration to be EnumConstant
1610                        for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1611                                // build new version of object with EnumConstant
1612                                ast::ptr< ast::ObjectDecl > obj =
1613                                        enumDecl->members[i].strict_as< ast::ObjectDecl >();
1614                                obj.get_and_mutate()->type =
1615                                        new ast::EnumInstType{ enumDecl->name, ast::CV::Const };
1616
1617                                // set into decl
1618                                ast::EnumDecl * mut = mutate( enumDecl );
1619                                mut->members[i] = obj.get();
1620                                enumDecl = mut;
1621                        }
1622                        return enumDecl;
1623                }
1624
1625                static const ast::FunctionType * fixFunctionList(
1626                        const ast::FunctionType * func,
1627                        std::vector< ast::ptr< ast::DeclWithType > > ast::FunctionType::* field,
1628                        ast::ArgumentFlag isVarArgs = ast::FixedArgs
1629                ) {
1630                        const auto & dwts = func->* field;
1631                        unsigned nvals = dwts.size();
1632                        bool hasVoid = false;
1633                        for ( unsigned i = 0; i < nvals; ++i ) {
1634                                func = ast::mutate_field_index( func, field, i, fixFunction( dwts[i], hasVoid ) );
1635                        }
1636
1637                        // the only case in which "void" is valid is where it is the only one in the list
1638                        if ( hasVoid && ( nvals > 1 || isVarArgs ) ) {
1639                                SemanticError(
1640                                        dwts.front()->location, func, "invalid type void in function type" );
1641                        }
1642
1643                        // one void is the only thing in the list, remove it
1644                        if ( hasVoid ) {
1645                                func = ast::mutate_field(
1646                                        func, field, std::vector< ast::ptr< ast::DeclWithType > >{} );
1647                        }
1648
1649                        return func;
1650                }
1651
1652                const ast::FunctionType * previsit( const ast::FunctionType * func ) {
1653                        func = fixFunctionList( func, &ast::FunctionType::params, func->isVarArgs );
1654                        return fixFunctionList( func, &ast::FunctionType::returns );
1655                }
1656        };
1657
1658        /// expand assertions from a trait instance, performing appropriate type variable substitutions
1659        void expandAssertions(
1660                const ast::TraitInstType * inst, std::vector< ast::ptr< ast::DeclWithType > > & out
1661        ) {
1662                assertf( inst->base, "Trait instance not linked to base trait: %s", toCString( inst ) );
1663
1664                // build list of trait members, substituting trait decl parameters for instance parameters
1665                ast::TypeSubstitution sub{
1666                        inst->base->params.begin(), inst->base->params.end(), inst->params.begin() };
1667                // deliberately take ast::ptr by-value to ensure this does not mutate inst->base
1668                for ( ast::ptr< ast::Decl > decl : inst->base->members ) {
1669                        auto member = decl.strict_as< ast::DeclWithType >();
1670                        sub.apply( member );
1671                        out.emplace_back( member );
1672                }
1673        }
1674
1675        /// Associates forward declarations of aggregates with their definitions
1676        class LinkReferenceToTypes_new final
1677        : public ast::WithSymbolTable, public ast::WithGuards, public
1678          ast::WithVisitorRef<LinkReferenceToTypes_new>, public ast::WithShortCircuiting {
1679
1680                // these maps of uses of forward declarations of types need to have the actual type
1681                // declaration switched in * after * they have been traversed. To enable this in the
1682                // ast::Pass framework, any node that needs to be so mutated has mutate() called on it
1683                // before it is placed in the map, properly updating its parents in the usual traversal,
1684                // then can have the actual mutation applied later
1685                using ForwardEnumsType = std::unordered_multimap< std::string, ast::EnumInstType * >;
1686                using ForwardStructsType = std::unordered_multimap< std::string, ast::StructInstType * >;
1687                using ForwardUnionsType = std::unordered_multimap< std::string, ast::UnionInstType * >;
1688
1689                const CodeLocation & location;
1690                const ast::SymbolTable * localSymtab;
1691
1692                ForwardEnumsType forwardEnums;
1693                ForwardStructsType forwardStructs;
1694                ForwardUnionsType forwardUnions;
1695
1696                /// true if currently in a generic type body, so that type parameter instances can be
1697                /// renamed appropriately
1698                bool inGeneric = false;
1699
1700        public:
1701                /// contstruct using running symbol table
1702                LinkReferenceToTypes_new( const CodeLocation & loc )
1703                : location( loc ), localSymtab( &symtab ) {}
1704
1705                /// construct using provided symbol table
1706                LinkReferenceToTypes_new( const CodeLocation & loc, const ast::SymbolTable & syms )
1707                : location( loc ), localSymtab( &syms ) {}
1708
1709                const ast::Type * postvisit( const ast::TypeInstType * typeInst ) {
1710                        // ensure generic parameter instances are renamed like the base type
1711                        if ( inGeneric && typeInst->base ) {
1712                                typeInst = ast::mutate_field(
1713                                        typeInst, &ast::TypeInstType::name, typeInst->base->name );
1714                        }
1715
1716                        if (
1717                                auto typeDecl = dynamic_cast< const ast::TypeDecl * >(
1718                                        localSymtab->lookupType( typeInst->name ) )
1719                        ) {
1720                                typeInst = ast::mutate_field( typeInst, &ast::TypeInstType::kind, typeDecl->kind );
1721                        }
1722
1723                        return typeInst;
1724                }
1725
1726                const ast::Type * postvisit( const ast::EnumInstType * inst ) {
1727                        const ast::EnumDecl * decl = localSymtab->lookupEnum( inst->name );
1728                        // not a semantic error if the enum is not found, just an implicit forward declaration
1729                        if ( decl ) {
1730                                inst = ast::mutate_field( inst, &ast::EnumInstType::base, decl );
1731                        }
1732                        if ( ! decl || ! decl->body ) {
1733                                // forward declaration
1734                                auto mut = mutate( inst );
1735                                forwardEnums.emplace( inst->name, mut );
1736                                inst = mut;
1737                        }
1738                        return inst;
1739                }
1740
1741                void checkGenericParameters( const ast::BaseInstType * inst ) {
1742                        for ( const ast::Expr * param : inst->params ) {
1743                                if ( ! dynamic_cast< const ast::TypeExpr * >( param ) ) {
1744                                        SemanticError(
1745                                                location, inst, "Expression parameters for generic types are currently "
1746                                                "unsupported: " );
1747                                }
1748                        }
1749                }
1750
1751                const ast::StructInstType * postvisit( const ast::StructInstType * inst ) {
1752                        const ast::StructDecl * decl = localSymtab->lookupStruct( inst->name );
1753                        // not a semantic error if the struct is not found, just an implicit forward declaration
1754                        if ( decl ) {
1755                                inst = ast::mutate_field( inst, &ast::StructInstType::base, decl );
1756                        }
1757                        if ( ! decl || ! decl->body ) {
1758                                // forward declaration
1759                                auto mut = mutate( inst );
1760                                forwardStructs.emplace( inst->name, mut );
1761                                inst = mut;
1762                        }
1763                        checkGenericParameters( inst );
1764                        return inst;
1765                }
1766
1767                const ast::UnionInstType * postvisit( const ast::UnionInstType * inst ) {
1768                        const ast::UnionDecl * decl = localSymtab->lookupUnion( inst->name );
1769                        // not a semantic error if the struct is not found, just an implicit forward declaration
1770                        if ( decl ) {
1771                                inst = ast::mutate_field( inst, &ast::UnionInstType::base, decl );
1772                        }
1773                        if ( ! decl || ! decl->body ) {
1774                                // forward declaration
1775                                auto mut = mutate( inst );
1776                                forwardUnions.emplace( inst->name, mut );
1777                                inst = mut;
1778                        }
1779                        checkGenericParameters( inst );
1780                        return inst;
1781                }
1782
1783                const ast::Type * postvisit( const ast::TraitInstType * traitInst ) {
1784                        // handle other traits
1785                        const ast::TraitDecl * traitDecl = localSymtab->lookupTrait( traitInst->name );
1786                        if ( ! traitDecl )       {
1787                                SemanticError( location, "use of undeclared trait " + traitInst->name );
1788                        }
1789                        if ( traitDecl->params.size() != traitInst->params.size() ) {
1790                                SemanticError( location, traitInst, "incorrect number of trait parameters: " );
1791                        }
1792                        traitInst = ast::mutate_field( traitInst, &ast::TraitInstType::base, traitDecl );
1793
1794                        // need to carry over the "sized" status of each decl in the instance
1795                        for ( unsigned i = 0; i < traitDecl->params.size(); ++i ) {
1796                                auto expr = traitInst->params[i].as< ast::TypeExpr >();
1797                                if ( ! expr ) {
1798                                        SemanticError(
1799                                                traitInst->params[i].get(), "Expression parameters for trait instances "
1800                                                "are currently unsupported: " );
1801                                }
1802
1803                                if ( auto inst = expr->type.as< ast::TypeInstType >() ) {
1804                                        if ( traitDecl->params[i]->sized && ! inst->base->sized ) {
1805                                                // traitInst = ast::mutate_field_index(
1806                                                //      traitInst, &ast::TraitInstType::params, i,
1807                                                //      ...
1808                                                // );
1809                                                ast::TraitInstType * mut = ast::mutate( traitInst );
1810                                                ast::chain_mutate( mut->params[i] )
1811                                                        ( &ast::TypeExpr::type )
1812                                                                ( &ast::TypeInstType::base )->sized = true;
1813                                                traitInst = mut;
1814                                        }
1815                                }
1816                        }
1817
1818                        return traitInst;
1819                }
1820
1821                void previsit( const ast::QualifiedType * ) { visit_children = false; }
1822
1823                const ast::Type * postvisit( const ast::QualifiedType * qualType ) {
1824                        // linking only makes sense for the "oldest ancestor" of the qualified type
1825                        return ast::mutate_field(
1826                                qualType, &ast::QualifiedType::parent, qualType->parent->accept( * visitor ) );
1827                }
1828
1829                const ast::Decl * postvisit( const ast::EnumDecl * enumDecl ) {
1830                        // visit enum members first so that the types of self-referencing members are updated
1831                        // properly
1832                        if ( ! enumDecl->body ) return enumDecl;
1833
1834                        // update forward declarations to point here
1835                        auto fwds = forwardEnums.equal_range( enumDecl->name );
1836                        if ( fwds.first != fwds.second ) {
1837                                auto inst = fwds.first;
1838                                do {
1839                                        // forward decl is stored * mutably * in map, can thus be updated
1840                                        inst->second->base = enumDecl;
1841                                } while ( ++inst != fwds.second );
1842                                forwardEnums.erase( fwds.first, fwds.second );
1843                        }
1844
1845                        // ensure that enumerator initializers are properly set
1846                        for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1847                                auto field = enumDecl->members[i].strict_as< ast::ObjectDecl >();
1848                                if ( field->init ) {
1849                                        // need to resolve enumerator initializers early so that other passes that
1850                                        // determine if an expression is constexpr have appropriate information
1851                                        auto init = field->init.strict_as< ast::SingleInit >();
1852
1853                                        enumDecl = ast::mutate_field_index(
1854                                                enumDecl, &ast::EnumDecl::members, i,
1855                                                ast::mutate_field( field, &ast::ObjectDecl::init,
1856                                                        ast::mutate_field( init, &ast::SingleInit::value,
1857                                                                ResolvExpr::findSingleExpression(
1858                                                                        init->value, new ast::BasicType{ ast::BasicType::SignedInt },
1859                                                                        symtab ) ) ) );
1860                                }
1861                        }
1862
1863                        return enumDecl;
1864                }
1865
1866                /// rename generic type parameters uniquely so that they do not conflict with user defined
1867                /// function forall parameters, e.g. the T in Box and the T in f, below
1868                ///   forall(otype T)
1869                ///   struct Box {
1870                ///     T x;
1871                ///   };
1872                ///   forall(otype T)
1873                ///   void f(Box(T) b) {
1874                ///     ...
1875                ///   }
1876                template< typename AggrDecl >
1877                const AggrDecl * renameGenericParams( const AggrDecl * aggr ) {
1878                        GuardValue( inGeneric );
1879                        inGeneric = ! aggr->params.empty();
1880
1881                        for ( unsigned i = 0; i < aggr->params.size(); ++i ) {
1882                                const ast::TypeDecl * td = aggr->params[i];
1883
1884                                aggr = ast::mutate_field_index(
1885                                        aggr, &AggrDecl::params, i,
1886                                        ast::mutate_field( td, &ast::TypeDecl::name, "__" + td->name + "_generic_" ) );
1887                        }
1888                        return aggr;
1889                }
1890
1891                const ast::StructDecl * previsit( const ast::StructDecl * structDecl ) {
1892                        return renameGenericParams( structDecl );
1893                }
1894
1895                void postvisit( const ast::StructDecl * structDecl ) {
1896                        // visit struct members first so that the types of self-referencing members are
1897                        // updated properly
1898                        if ( ! structDecl->body ) return;
1899
1900                        // update forward declarations to point here
1901                        auto fwds = forwardStructs.equal_range( structDecl->name );
1902                        if ( fwds.first != fwds.second ) {
1903                                auto inst = fwds.first;
1904                                do {
1905                                        // forward decl is stored * mutably * in map, can thus be updated
1906                                        inst->second->base = structDecl;
1907                                } while ( ++inst != fwds.second );
1908                                forwardStructs.erase( fwds.first, fwds.second );
1909                        }
1910                }
1911
1912                const ast::UnionDecl * previsit( const ast::UnionDecl * unionDecl ) {
1913                        return renameGenericParams( unionDecl );
1914                }
1915
1916                void postvisit( const ast::UnionDecl * unionDecl ) {
1917                        // visit union members first so that the types of self-referencing members are updated
1918                        // properly
1919                        if ( ! unionDecl->body ) return;
1920
1921                        // update forward declarations to point here
1922                        auto fwds = forwardUnions.equal_range( unionDecl->name );
1923                        if ( fwds.first != fwds.second ) {
1924                                auto inst = fwds.first;
1925                                do {
1926                                        // forward decl is stored * mutably * in map, can thus be updated
1927                                        inst->second->base = unionDecl;
1928                                } while ( ++inst != fwds.second );
1929                                forwardUnions.erase( fwds.first, fwds.second );
1930                        }
1931                }
1932
1933                const ast::Decl * postvisit( const ast::TraitDecl * traitDecl ) {
1934                        // set the "sized" status for the special "sized" trait
1935                        if ( traitDecl->name == "sized" ) {
1936                                assertf( traitDecl->params.size() == 1, "Built-in trait 'sized' has incorrect "
1937                                        "number of parameters: %zd", traitDecl->params.size() );
1938
1939                                traitDecl = ast::mutate_field_index(
1940                                        traitDecl, &ast::TraitDecl::params, 0,
1941                                        ast::mutate_field(
1942                                                traitDecl->params.front().get(), &ast::TypeDecl::sized, true ) );
1943                        }
1944
1945                        // move assertions from type parameters into the body of the trait
1946                        std::vector< ast::ptr< ast::DeclWithType > > added;
1947                        for ( const ast::TypeDecl * td : traitDecl->params ) {
1948                                for ( const ast::DeclWithType * assn : td->assertions ) {
1949                                        auto inst = dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
1950                                        if ( inst ) {
1951                                                expandAssertions( inst, added );
1952                                        } else {
1953                                                added.emplace_back( assn );
1954                                        }
1955                                }
1956                        }
1957                        if ( ! added.empty() ) {
1958                                auto mut = mutate( traitDecl );
1959                                for ( const ast::DeclWithType * decl : added ) {
1960                                        mut->members.emplace_back( decl );
1961                                }
1962                                traitDecl = mut;
1963                        }
1964
1965                        return traitDecl;
1966                }
1967        };
1968
1969        /// Replaces array and function types in forall lists by appropriate pointer type and assigns
1970        /// each object and function declaration a unique ID
1971        class ForallPointerDecay_new {
1972                const CodeLocation & location;
1973        public:
1974                ForallPointerDecay_new( const CodeLocation & loc ) : location( loc ) {}
1975
1976                const ast::ObjectDecl * previsit( const ast::ObjectDecl * obj ) {
1977                        // ensure that operator names only apply to functions or function pointers
1978                        if (
1979                                CodeGen::isOperator( obj->name )
1980                                && ! dynamic_cast< const ast::FunctionType * >( obj->type->stripDeclarator() )
1981                        ) {
1982                                SemanticError( obj->location, toCString( "operator ", obj->name.c_str(), " is not "
1983                                        "a function or function pointer." )  );
1984                        }
1985
1986                        // ensure object has unique ID
1987                        if ( obj->uniqueId ) return obj;
1988                        auto mut = mutate( obj );
1989                        mut->fixUniqueId();
1990                        return mut;
1991                }
1992
1993                const ast::FunctionDecl * previsit( const ast::FunctionDecl * func ) {
1994                        // ensure function has unique ID
1995                        if ( func->uniqueId ) return func;
1996                        auto mut = mutate( func );
1997                        mut->fixUniqueId();
1998                        return mut;
1999                }
2000
2001                /// Fix up assertions -- flattens assertion lists, removing all trait instances
2002                template< typename node_t, typename parent_t >
2003                static const node_t * forallFixer(
2004                        const CodeLocation & loc, const node_t * node,
2005                        ast::FunctionType::ForallList parent_t::* forallField
2006                ) {
2007                        for ( unsigned i = 0; i < (node->* forallField).size(); ++i ) {
2008                                const ast::TypeDecl * type = (node->* forallField)[i];
2009                                if ( type->assertions.empty() ) continue;
2010
2011                                std::vector< ast::ptr< ast::DeclWithType > > asserts;
2012                                asserts.reserve( type->assertions.size() );
2013
2014                                // expand trait instances into their members
2015                                for ( const ast::DeclWithType * assn : type->assertions ) {
2016                                        auto traitInst =
2017                                                dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
2018                                        if ( traitInst ) {
2019                                                // expand trait instance to all its members
2020                                                expandAssertions( traitInst, asserts );
2021                                        } else {
2022                                                // pass other assertions through
2023                                                asserts.emplace_back( assn );
2024                                        }
2025                                }
2026
2027                                // apply FixFunction to every assertion to check for invalid void type
2028                                for ( ast::ptr< ast::DeclWithType > & assn : asserts ) {
2029                                        bool isVoid = false;
2030                                        assn = fixFunction( assn, isVoid );
2031                                        if ( isVoid ) {
2032                                                SemanticError( loc, node, "invalid type void in assertion of function " );
2033                                        }
2034                                }
2035
2036                                // place mutated assertion list in node
2037                                auto mut = mutate( type );
2038                                mut->assertions = move( asserts );
2039                                node = ast::mutate_field_index( node, forallField, i, mut );
2040                        }
2041                        return node;
2042                }
2043
2044                const ast::FunctionType * previsit( const ast::FunctionType * ftype ) {
2045                        return forallFixer( location, ftype, &ast::FunctionType::forall );
2046                }
2047
2048                const ast::StructDecl * previsit( const ast::StructDecl * aggrDecl ) {
2049                        return forallFixer( aggrDecl->location, aggrDecl, &ast::StructDecl::params );
2050                }
2051
2052                const ast::UnionDecl * previsit( const ast::UnionDecl * aggrDecl ) {
2053                        return forallFixer( aggrDecl->location, aggrDecl, &ast::UnionDecl::params );
2054                }
2055        };
2056        */
2057} // anonymous namespace
2058
2059/*
2060const ast::Type * validateType(
2061                const CodeLocation & loc, const ast::Type * type, const ast::SymbolTable & symtab ) {
2062        // ast::Pass< EnumAndPointerDecay_new > epc;
2063        ast::Pass< LinkReferenceToTypes_new > lrt{ loc, symtab };
2064        ast::Pass< ForallPointerDecay_new > fpd{ loc };
2065
2066        return type->accept( lrt )->accept( fpd );
2067}
2068*/
2069
2070} // namespace SymTab
2071
2072// Local Variables: //
2073// tab-width: 4 //
2074// mode: c++ //
2075// compile-command: "make install" //
2076// End: //
Note: See TracBrowser for help on using the repository browser.