source: src/SymTab/Validate.cc @ fa2c005

ADT
Last change on this file since fa2c005 was fa2c005, checked in by JiadaL <j82liang@…>, 12 months ago

Finish Adt POC

  • Property mode set to 100644
File size: 52.3 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 : Tue Jul 12 15:00:00 2022
13// Update Count     : 367
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 "CodeGen/CodeGenerator.h"     // for genName
50#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
51#include "ControlStruct/Mutate.h"      // for ForExprMutator
52#include "Common/CodeLocation.h"       // for CodeLocation
53#include "Common/Stats.h"              // for Stats::Heap
54#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
55#include "Common/ScopedMap.h"          // for ScopedMap
56#include "Common/SemanticError.h"      // for SemanticError
57#include "Common/ToString.hpp"         // for toCString
58#include "Common/UniqueName.h"         // for UniqueName
59#include "Common/utility.h"            // for cloneAll, deleteAll
60#include "CompilationState.h"          // skip some passes in new-ast build
61#include "Concurrency/Keywords.h"      // for applyKeywords
62#include "FixFunction.h"               // for FixFunction
63#include "Indexer.h"                   // for Indexer
64#include "InitTweak/GenInit.h"         // for fixReturnStatements
65#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
66#include "ResolvExpr/typeops.h"        // for extractResultType
67#include "ResolvExpr/Unify.h"          // for typesCompatible
68#include "ResolvExpr/Resolver.h"       // for findSingleExpression
69#include "ResolvExpr/ResolveTypeof.h"  // for resolveTypeof
70#include "SymTab/Autogen.h"            // for SizeType
71#include "SymTab/ValidateType.h"       // for decayEnumsAndPointers, decayFo...
72#include "SynTree/LinkageSpec.h"       // for C
73#include "SynTree/Attribute.h"         // for noAttributes, Attribute
74#include "SynTree/Constant.h"          // for Constant
75#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
76#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
77#include "SynTree/Initializer.h"       // for ListInit, Initializer
78#include "SynTree/Label.h"             // for operator==, Label
79#include "SynTree/Mutator.h"           // for Mutator
80#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
81#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
82#include "SynTree/Visitor.h"           // for Visitor
83#include "Validate/HandleAttributes.h" // for handleAttributes
84#include "Validate/FindSpecialDecls.h" // for FindSpecialDecls
85
86class CompoundStmt;
87class ReturnStmt;
88class SwitchStmt;
89
90#define debugPrint( x ) if ( doDebug ) x
91
92namespace SymTab {
93        /// hoists declarations that are difficult to hoist while parsing
94        struct HoistTypeDecls final : public WithDeclsToAdd {
95                void previsit( SizeofExpr * );
96                void previsit( AlignofExpr * );
97                void previsit( UntypedOffsetofExpr * );
98                void previsit( CompoundLiteralExpr * );
99                void handleType( Type * );
100        };
101
102        struct FixQualifiedTypes final : public WithIndexer {
103                FixQualifiedTypes() : WithIndexer(false) {}
104                Type * postmutate( QualifiedType * );
105        };
106
107        struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
108                /// Flattens nested struct types
109                static void hoistStruct( std::list< Declaration * > &translationUnit );
110
111                void previsit( StructDecl * aggregateDecl );
112                void previsit( UnionDecl * aggregateDecl );
113                void previsit( StaticAssertDecl * assertDecl );
114                void previsit( StructInstType * type );
115                void previsit( UnionInstType * type );
116                void previsit( EnumInstType * type );
117
118          private:
119                template< typename AggDecl > void handleAggregate( AggDecl * aggregateDecl );
120
121                AggregateDecl * parentAggr = nullptr;
122        };
123
124        /// Fix return types so that every function returns exactly one value
125        struct ReturnTypeFixer {
126                static void fix( std::list< Declaration * > &translationUnit );
127
128                void postvisit( FunctionDecl * functionDecl );
129                void postvisit( FunctionType * ftype );
130        };
131
132        /// Does early resolution on the expressions that give enumeration constants their values
133        struct ResolveEnumInitializers final : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveEnumInitializers>, public WithShortCircuiting {
134                ResolveEnumInitializers( const Indexer * indexer );
135                void postvisit( EnumDecl * enumDecl );
136
137          private:
138                const Indexer * local_indexer;
139
140        };
141
142        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
143        struct ForallPointerDecay_old final {
144                void previsit( ObjectDecl * object );
145                void previsit( FunctionDecl * func );
146                void previsit( FunctionType * ftype );
147                void previsit( StructDecl * aggrDecl );
148                void previsit( UnionDecl * aggrDecl );
149        };
150
151        struct ReturnChecker : public WithGuards {
152                /// Checks that return statements return nothing if their return type is void
153                /// and return something if the return type is non-void.
154                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
155
156                void previsit( FunctionDecl * functionDecl );
157                void previsit( ReturnStmt * returnStmt );
158
159                typedef std::list< DeclarationWithType * > ReturnVals;
160                ReturnVals returnVals;
161        };
162
163        struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
164                ReplaceTypedef() : scopeLevel( 0 ) {}
165                /// Replaces typedefs by forward declarations
166                static void replaceTypedef( std::list< Declaration * > &translationUnit );
167
168                void premutate( QualifiedType * );
169                Type * postmutate( QualifiedType * qualType );
170                Type * postmutate( TypeInstType * aggregateUseType );
171                Declaration * postmutate( TypedefDecl * typeDecl );
172                void premutate( TypeDecl * typeDecl );
173                void premutate( FunctionDecl * funcDecl );
174                void premutate( ObjectDecl * objDecl );
175                DeclarationWithType * postmutate( ObjectDecl * objDecl );
176
177                void premutate( CastExpr * castExpr );
178
179                void premutate( CompoundStmt * compoundStmt );
180
181                void premutate( StructDecl * structDecl );
182                void premutate( UnionDecl * unionDecl );
183                void premutate( EnumDecl * enumDecl );
184                void premutate( TraitDecl * );
185
186                void premutate( FunctionType * ftype );
187
188          private:
189                template<typename AggDecl>
190                void addImplicitTypedef( AggDecl * aggDecl );
191                template< typename AggDecl >
192                void handleAggregate( AggDecl * aggr );
193
194                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
195                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
196                typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
197                TypedefMap typedefNames;
198                TypeDeclMap typedeclNames;
199                int scopeLevel;
200                bool inFunctionType = false;
201        };
202
203        struct EliminateTypedef {
204                /// removes TypedefDecls from the AST
205                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
206
207                template<typename AggDecl>
208                void handleAggregate( AggDecl * aggregateDecl );
209
210                void previsit( StructDecl * aggregateDecl );
211                void previsit( UnionDecl * aggregateDecl );
212                void previsit( AdtDecl * AggregateDecl );
213                void previsit( CompoundStmt * compoundStmt );
214        };
215
216        struct VerifyCtorDtorAssign {
217                /// ensure that constructors, destructors, and assignment have at least one
218                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
219                /// return values.
220                static void verify( std::list< Declaration * > &translationUnit );
221
222                void previsit( FunctionDecl * funcDecl );
223        };
224
225        /// ensure that generic types have the correct number of type arguments
226        struct ValidateGenericParameters {
227                void previsit( StructInstType * inst );
228                void previsit( UnionInstType * inst );
229        };
230
231        /// desugar declarations and uses of dimension paramaters like [N],
232        /// from type-system managed values, to tunnneling via ordinary types,
233        /// as char[-] in and sizeof(-) out
234        struct TranslateDimensionGenericParameters : public WithIndexer, public WithGuards {
235                static void translateDimensions( std::list< Declaration * > &translationUnit );
236                TranslateDimensionGenericParameters();
237
238                bool nextVisitedNodeIsChildOfSUIT = false; // SUIT = Struct or Union -Inst Type
239                bool visitingChildOfSUIT = false;
240                void changeState_ChildOfSUIT( bool newVal );
241                void premutate( StructInstType * sit );
242                void premutate( UnionInstType * uit );
243                void premutate( BaseSyntaxNode * node );
244
245                TypeDecl * postmutate( TypeDecl * td );
246                Expression * postmutate( DimensionExpr * de );
247                Expression * postmutate( Expression * e );
248        };
249
250        struct FixObjectType : public WithIndexer {
251                /// resolves typeof type in object, function, and type declarations
252                static void fix( std::list< Declaration * > & translationUnit );
253
254                void previsit( ObjectDecl * );
255                void previsit( FunctionDecl * );
256                void previsit( TypeDecl * );
257        };
258
259        struct InitializerLength {
260                /// for array types without an explicit length, compute the length and store it so that it
261                /// is known to the rest of the phases. For example,
262                ///   int x[] = { 1, 2, 3 };
263                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
264                /// here x and y are known at compile-time to have length 3, so change this into
265                ///   int x[3] = { 1, 2, 3 };
266                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
267                static void computeLength( std::list< Declaration * > & translationUnit );
268
269                void previsit( ObjectDecl * objDecl );
270        };
271
272        struct ArrayLength : public WithIndexer {
273                static void computeLength( std::list< Declaration * > & translationUnit );
274
275                void previsit( ArrayType * arrayType );
276        };
277
278        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
279                Type::StorageClasses storageClasses;
280
281                void premutate( ObjectDecl * objectDecl );
282                Expression * postmutate( CompoundLiteralExpr * compLitExpr );
283        };
284
285        struct LabelAddressFixer final : public WithGuards {
286                std::set< Label > labels;
287
288                void premutate( FunctionDecl * funcDecl );
289                Expression * postmutate( AddressExpr * addrExpr );
290        };
291
292        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
293                PassVisitor<HoistTypeDecls> hoistDecls;
294                {
295                        Stats::Heap::newPass("validate-A");
296                        Stats::Time::BlockGuard guard("validate-A");
297                        VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
298                        acceptAll( translationUnit, hoistDecls );
299                        ReplaceTypedef::replaceTypedef( translationUnit );
300                        ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
301                        decayEnumsAndPointers( translationUnit ); // 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
302                }
303                PassVisitor<FixQualifiedTypes> fixQual;
304                {
305                        Stats::Heap::newPass("validate-B");
306                        Stats::Time::BlockGuard guard("validate-B");
307                        linkReferenceToTypes( translationUnit ); // Must happen before auto-gen, because it uses the sized flag.
308                        mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes_old, because aggregate members are accessed
309                        HoistStruct::hoistStruct( translationUnit );
310                        EliminateTypedef::eliminateTypedef( translationUnit );
311                }
312                PassVisitor<ValidateGenericParameters> genericParams;
313                PassVisitor<ResolveEnumInitializers> rei( nullptr );
314                {
315                        Stats::Heap::newPass("validate-C");
316                        Stats::Time::BlockGuard guard("validate-C");
317                        Stats::Time::TimeBlock("Validate Generic Parameters", [&]() {
318                                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes_old; observed failing when attempted before eliminateTypedef
319                        });
320                        Stats::Time::TimeBlock("Translate Dimensions", [&]() {
321                                TranslateDimensionGenericParameters::translateDimensions( translationUnit );
322                        });
323                        if (!useNewAST) {
324                        Stats::Time::TimeBlock("Resolve Enum Initializers", [&]() {
325                                acceptAll( translationUnit, rei ); // must happen after translateDimensions because rei needs identifier lookup, which needs name mangling
326                        });
327                        }
328                        Stats::Time::TimeBlock("Check Function Returns", [&]() {
329                                ReturnChecker::checkFunctionReturns( translationUnit );
330                        });
331                        Stats::Time::TimeBlock("Fix Return Statements", [&]() {
332                                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
333                        });
334                }
335                {
336                        Stats::Heap::newPass("validate-D");
337                        Stats::Time::BlockGuard guard("validate-D");
338                        Stats::Time::TimeBlock("Apply Concurrent Keywords", [&]() {
339                                Concurrency::applyKeywords( translationUnit );
340                        });
341                        Stats::Time::TimeBlock("Forall Pointer Decay", [&]() {
342                                decayForallPointers( translationUnit ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
343                        });
344                        Stats::Time::TimeBlock("Hoist Control Declarations", [&]() {
345                                ControlStruct::hoistControlDecls( translationUnit );  // hoist initialization out of for statements; must happen before autogenerateRoutines
346                        });
347                        Stats::Time::TimeBlock("Generate Autogen routines", [&]() {
348                                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay_old
349                        });
350                }
351                PassVisitor<CompoundLiteral> compoundliteral;
352                {
353                        Stats::Heap::newPass("validate-E");
354                        Stats::Time::BlockGuard guard("validate-E");
355                        Stats::Time::TimeBlock("Implement Mutex Func", [&]() {
356                                Concurrency::implementMutexFuncs( translationUnit );
357                        });
358                        Stats::Time::TimeBlock("Implement Thread Start", [&]() {
359                                Concurrency::implementThreadStarter( translationUnit );
360                        });
361                        Stats::Time::TimeBlock("Compound Literal", [&]() {
362                                mutateAll( translationUnit, compoundliteral );
363                        });
364                        if (!useNewAST) {
365                                Stats::Time::TimeBlock("Resolve With Expressions", [&]() {
366                                        ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables
367                                });
368                        }
369                }
370                PassVisitor<LabelAddressFixer> labelAddrFixer;
371                {
372                        Stats::Heap::newPass("validate-F");
373                        Stats::Time::BlockGuard guard("validate-F");
374                        if (!useNewAST) {
375                                Stats::Time::TimeCall("Fix Object Type",
376                                        FixObjectType::fix, translationUnit);
377                        }
378                        Stats::Time::TimeCall("Initializer Length",
379                                InitializerLength::computeLength, translationUnit);
380                        if (!useNewAST) {
381                                Stats::Time::TimeCall("Array Length",
382                                        ArrayLength::computeLength, translationUnit);
383                        }
384                        Stats::Time::TimeCall("Find Special Declarations",
385                                Validate::findSpecialDecls, translationUnit);
386                        Stats::Time::TimeCall("Fix Label Address",
387                                mutateAll<LabelAddressFixer>, translationUnit, labelAddrFixer);
388                        if (!useNewAST) {
389                                Stats::Time::TimeCall("Handle Attributes",
390                                        Validate::handleAttributes, translationUnit);
391                        }
392                }
393        }
394
395        void HoistTypeDecls::handleType( Type * type ) {
396                // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
397                AggregateDecl * aggr = nullptr;
398                if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
399                        aggr = inst->baseStruct;
400                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
401                        aggr = inst->baseUnion;
402                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
403                        aggr = inst->baseEnum;
404                }
405                if ( aggr && aggr->body ) {
406                        declsToAddBefore.push_front( aggr );
407                }
408        }
409
410        void HoistTypeDecls::previsit( SizeofExpr * expr ) {
411                handleType( expr->type );
412        }
413
414        void HoistTypeDecls::previsit( AlignofExpr * expr ) {
415                handleType( expr->type );
416        }
417
418        void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
419                handleType( expr->type );
420        }
421
422        void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
423                handleType( expr->result );
424        }
425
426
427        Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
428                Type * parent = qualType->parent;
429                Type * child = qualType->child;
430                if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
431                        // .T => lookup T at global scope
432                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
433                                auto td = indexer.globalLookupType( inst->name );
434                                if ( ! td ) {
435                                        SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
436                                }
437                                auto base = td->base;
438                                assert( base );
439                                Type * ret = base->clone();
440                                ret->get_qualifiers() = qualType->get_qualifiers();
441                                return ret;
442                        } else {
443                                // .T => T is not a type name
444                                assertf( false, "unhandled global qualified child type: %s", toCString(child) );
445                        }
446                } else {
447                        // S.T => S must be an aggregate type, find the declaration for T in S.
448                        AggregateDecl * aggr = nullptr;
449                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
450                                aggr = inst->baseStruct;
451                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
452                                aggr = inst->baseUnion;
453                        } else {
454                                SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
455                        }
456                        assert( aggr ); // TODO: need to handle forward declarations
457                        for ( Declaration * member : aggr->members ) {
458                                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
459                                        // name on the right is a typedef
460                                        if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
461                                                if ( aggr->name == inst->name ) {
462                                                        assert( aggr->base );
463                                                        Type * ret = aggr->base->clone();
464                                                        ret->get_qualifiers() = qualType->get_qualifiers();
465                                                        TypeSubstitution sub = parent->genericSubstitution();
466                                                        sub.apply(ret);
467                                                        return ret;
468                                                }
469                                        }
470                                } else {
471                                        // S.T - S is not an aggregate => error
472                                        assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
473                                }
474                        }
475                        // failed to find a satisfying definition of type
476                        SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
477                }
478
479                // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
480        }
481
482
483        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
484                PassVisitor<HoistStruct> hoister;
485                acceptAll( translationUnit, hoister );
486        }
487
488        bool shouldHoist( Declaration * decl ) {
489                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
490        }
491
492        namespace {
493                void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
494                        if ( aggr->parent ) qualifiedName( aggr->parent, ss );
495                        ss << "__" << aggr->name;
496                }
497
498                // mangle nested type names using entire parent chain
499                std::string qualifiedName( AggregateDecl * aggr ) {
500                        std::ostringstream ss;
501                        qualifiedName( aggr, ss );
502                        return ss.str();
503                }
504        }
505
506        template< typename AggDecl >
507        void HoistStruct::handleAggregate( AggDecl * aggregateDecl ) {
508                if ( parentAggr ) {
509                        aggregateDecl->parent = parentAggr;
510                        aggregateDecl->name = qualifiedName( aggregateDecl );
511                        // Add elements in stack order corresponding to nesting structure.
512                        declsToAddBefore.push_front( aggregateDecl );
513                } else {
514                        GuardValue( parentAggr );
515                        parentAggr = aggregateDecl;
516                } // if
517                // Always remove the hoisted aggregate from the inner structure.
518                GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
519        }
520
521        void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
522                if ( parentAggr ) {
523                        declsToAddBefore.push_back( assertDecl );
524                }
525        }
526
527        void HoistStruct::previsit( StructDecl * aggregateDecl ) {
528                handleAggregate( aggregateDecl );
529        }
530
531        void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
532                handleAggregate( aggregateDecl );
533        }
534
535        void HoistStruct::previsit( StructInstType * type ) {
536                // need to reset type name after expanding to qualified name
537                assert( type->baseStruct );
538                type->name = type->baseStruct->name;
539        }
540
541        void HoistStruct::previsit( UnionInstType * type ) {
542                assert( type->baseUnion );
543                type->name = type->baseUnion->name;
544        }
545
546        void HoistStruct::previsit( EnumInstType * type ) {
547                assert( type->baseEnum );
548                type->name = type->baseEnum->name;
549        }
550
551
552        bool isTypedef( Declaration * decl ) {
553                return dynamic_cast< TypedefDecl * >( decl );
554        }
555
556        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
557                PassVisitor<EliminateTypedef> eliminator;
558                acceptAll( translationUnit, eliminator );
559                filter( translationUnit, isTypedef, true );
560        }
561
562        template< typename AggDecl >
563        void EliminateTypedef::handleAggregate( AggDecl * aggregateDecl ) {
564                filter( aggregateDecl->members, isTypedef, true );
565        }
566
567        void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
568                handleAggregate( aggregateDecl );
569        }
570
571        void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
572                handleAggregate( aggregateDecl );
573        }
574
575        void EliminateTypedef::previsit( AdtDecl * aggregateDecl ) {
576                handleAggregate( aggregateDecl );
577        }
578
579        void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
580                // remove and delete decl stmts
581                filter( compoundStmt->kids, [](Statement * stmt) {
582                        if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
583                                if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
584                                        return true;
585                                } // if
586                        } // if
587                        return false;
588                }, true);
589        }
590
591        // expand assertions from trait instance, performing the appropriate type variable substitutions
592        template< typename Iterator >
593        void expandAssertions( TraitInstType * inst, Iterator out ) {
594                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
595                std::list< DeclarationWithType * > asserts;
596                for ( Declaration * decl : inst->baseTrait->members ) {
597                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
598                }
599                // substitute trait decl parameters for instance parameters
600                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
601        }
602
603        ResolveEnumInitializers::ResolveEnumInitializers( const Indexer * other_indexer ) : WithIndexer( true ) {
604                if ( other_indexer ) {
605                        local_indexer = other_indexer;
606                } else {
607                        local_indexer = &indexer;
608                } // if
609        }
610
611        void ResolveEnumInitializers::postvisit( EnumDecl * enumDecl ) {
612                if ( enumDecl->body ) {
613                        for ( Declaration * member : enumDecl->members ) {
614                                ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member );
615                                if ( field->init ) {
616                                        // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information.
617                                        SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init );
618                                        if ( !enumDecl->base || dynamic_cast<BasicType *>(enumDecl->base))
619                                                ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
620                                        else {
621                                                if (dynamic_cast<PointerType *>(enumDecl->base)) {
622                                                        auto typePtr = dynamic_cast<PointerType *>(enumDecl->base);
623                                                        ResolvExpr::findSingleExpression( init->value,
624                                                         new PointerType( Type::Qualifiers(), typePtr->base ), indexer );
625                                                } else {
626                                                        ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
627                                                }
628                                        }
629                                }
630                        }
631
632                } // if
633        }
634
635        /// Fix up assertions - flattens assertion lists, removing all trait instances
636        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
637                for ( TypeDecl * type : forall ) {
638                        std::list< DeclarationWithType * > asserts;
639                        asserts.splice( asserts.end(), type->assertions );
640                        // expand trait instances into their members
641                        for ( DeclarationWithType * assertion : asserts ) {
642                                if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
643                                        // expand trait instance into all of its members
644                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
645                                        delete traitInst;
646                                } else {
647                                        // pass other assertions through
648                                        type->assertions.push_back( assertion );
649                                } // if
650                        } // for
651                        // apply FixFunction to every assertion to check for invalid void type
652                        for ( DeclarationWithType *& assertion : type->assertions ) {
653                                bool isVoid = fixFunction( assertion );
654                                if ( isVoid ) {
655                                        SemanticError( node, "invalid type void in assertion of function " );
656                                } // if
657                        } // for
658                        // normalizeAssertions( type->assertions );
659                } // for
660        }
661
662        /// Replace all traits in assertion lists with their assertions.
663        void expandTraits( std::list< TypeDecl * > & forall ) {
664                for ( TypeDecl * type : forall ) {
665                        std::list< DeclarationWithType * > asserts;
666                        asserts.splice( asserts.end(), type->assertions );
667                        // expand trait instances into their members
668                        for ( DeclarationWithType * assertion : asserts ) {
669                                if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
670                                        // expand trait instance into all of its members
671                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
672                                        delete traitInst;
673                                } else {
674                                        // pass other assertions through
675                                        type->assertions.push_back( assertion );
676                                } // if
677                        } // for
678                }
679        }
680
681        /// Fix each function in the assertion list and check for invalid void type.
682        void fixAssertions(
683                        std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
684                for ( TypeDecl * type : forall ) {
685                        for ( DeclarationWithType *& assertion : type->assertions ) {
686                                bool isVoid = fixFunction( assertion );
687                                if ( isVoid ) {
688                                        SemanticError( node, "invalid type void in assertion of function " );
689                                } // if
690                        } // for
691                }
692        }
693
694        void ForallPointerDecay_old::previsit( ObjectDecl * object ) {
695                // ensure that operator names only apply to functions or function pointers
696                if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
697                        SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
698                }
699                object->fixUniqueId();
700        }
701
702        void ForallPointerDecay_old::previsit( FunctionDecl * func ) {
703                func->fixUniqueId();
704        }
705
706        void ForallPointerDecay_old::previsit( FunctionType * ftype ) {
707                forallFixer( ftype->forall, ftype );
708        }
709
710        void ForallPointerDecay_old::previsit( StructDecl * aggrDecl ) {
711                forallFixer( aggrDecl->parameters, aggrDecl );
712        }
713
714        void ForallPointerDecay_old::previsit( UnionDecl * aggrDecl ) {
715                forallFixer( aggrDecl->parameters, aggrDecl );
716        }
717
718        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
719                PassVisitor<ReturnChecker> checker;
720                acceptAll( translationUnit, checker );
721        }
722
723        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
724                GuardValue( returnVals );
725                returnVals = functionDecl->get_functionType()->get_returnVals();
726        }
727
728        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
729                // Previously this also checked for the existence of an expr paired with no return values on
730                // the  function return type. This is incorrect, since you can have an expression attached to
731                // a return statement in a void-returning function in C. The expression is treated as if it
732                // were cast to void.
733                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
734                        SemanticError( returnStmt, "Non-void function returns no values: " );
735                }
736        }
737
738
739        void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
740                PassVisitor<ReplaceTypedef> eliminator;
741                mutateAll( translationUnit, eliminator );
742                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
743                        // grab and remember declaration of size_t
744                        Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
745                } else {
746                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
747                        // eventually should have a warning for this case.
748                        Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
749                }
750        }
751
752        void ReplaceTypedef::premutate( QualifiedType * ) {
753                visit_children = false;
754        }
755
756        Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
757                // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
758                qualType->parent = qualType->parent->acceptMutator( * visitor );
759                return qualType;
760        }
761
762        static bool isNonParameterAttribute( Attribute * attr ) {
763                static const std::vector<std::string> bad_names = {
764                        "aligned", "__aligned__",
765                };
766                for ( auto name : bad_names ) {
767                        if ( name == attr->name ) {
768                                return true;
769                        }
770                }
771                return false;
772        }
773
774        Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
775                // instances of typedef types will come here. If it is an instance
776                // of a typdef type, link the instance to its actual type.
777                TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
778                if ( def != typedefNames.end() ) {
779                        Type * ret = def->second.first->base->clone();
780                        ret->location = typeInst->location;
781                        ret->get_qualifiers() |= typeInst->get_qualifiers();
782                        // GCC ignores certain attributes if they arrive by typedef, this mimics that.
783                        if ( inFunctionType ) {
784                                ret->attributes.remove_if( isNonParameterAttribute );
785                        }
786                        ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
787                        // place instance parameters on the typedef'd type
788                        if ( ! typeInst->parameters.empty() ) {
789                                ReferenceToType * rtt = dynamic_cast<ReferenceToType *>(ret);
790                                if ( ! rtt ) {
791                                        SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
792                                }
793                                rtt->parameters.clear();
794                                cloneAll( typeInst->parameters, rtt->parameters );
795                                mutateAll( rtt->parameters, * visitor );  // recursively fix typedefs on parameters
796                        } // if
797                        delete typeInst;
798                        return ret;
799                } else {
800                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
801                        if ( base == typedeclNames.end() ) {
802                                SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
803                        }
804                        typeInst->set_baseType( base->second );
805                        return typeInst;
806                } // if
807                assert( false );
808        }
809
810        struct VarLenChecker : WithShortCircuiting {
811                void previsit( FunctionType * ) { visit_children = false; }
812                void previsit( ArrayType * at ) {
813                        isVarLen |= at->isVarLen;
814                }
815                bool isVarLen = false;
816        };
817
818        bool isVariableLength( Type * t ) {
819                PassVisitor<VarLenChecker> varLenChecker;
820                maybeAccept( t, varLenChecker );
821                return varLenChecker.pass.isVarLen;
822        }
823
824        Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
825                if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
826                        // typedef to the same name from the same scope
827                        // must be from the same type
828
829                        Type * t1 = tyDecl->base;
830                        Type * t2 = typedefNames[ tyDecl->name ].first->base;
831                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
832                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
833                        }
834                        // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
835                        // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
836                        // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
837                        // to fix this corner case likely outweighs the utility of allowing it.
838                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
839                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
840                        }
841                } else {
842                        typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
843                } // if
844
845                // When a typedef is a forward declaration:
846                //    typedef struct screen SCREEN;
847                // the declaration portion must be retained:
848                //    struct screen;
849                // because the expansion of the typedef is:
850                //    void rtn( SCREEN * p ) => void rtn( struct screen * p )
851                // hence the type-name "screen" must be defined.
852                // Note, qualifiers on the typedef are superfluous for the forward declaration.
853
854                Type * designatorType = tyDecl->base->stripDeclarator();
855                if ( StructInstType * aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
856                        declsToAddBefore.push_back( new StructDecl( aggDecl->name, AggregateDecl::Struct, noAttributes, tyDecl->linkage ) );
857                } else if ( UnionInstType * aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
858                        declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
859                } else if ( EnumInstType * enumInst = dynamic_cast< EnumInstType * >( designatorType ) ) {
860                        if ( enumInst->baseEnum ) {
861                                const EnumDecl * enumDecl = enumInst->baseEnum;
862                                declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, enumDecl->isTyped, tyDecl->linkage, enumDecl->base ) );
863                        } else {
864                                declsToAddBefore.push_back( new EnumDecl( enumInst->name, noAttributes, tyDecl->linkage ) );
865                        }
866                } // if
867                return tyDecl->clone();
868        }
869
870        void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
871                typedefNames.erase( typeDecl->name );
872                typedeclNames.insert( typeDecl->name, typeDecl );
873        }
874
875        void ReplaceTypedef::premutate( FunctionDecl * ) {
876                GuardScope( typedefNames );
877                GuardScope( typedeclNames );
878        }
879
880        void ReplaceTypedef::premutate( ObjectDecl * ) {
881                GuardScope( typedefNames );
882                GuardScope( typedeclNames );
883        }
884
885        DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
886                if ( FunctionType * funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
887                        // replace the current object declaration with a function declaration
888                        FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
889                        objDecl->attributes.clear();
890                        objDecl->set_type( nullptr );
891                        delete objDecl;
892                        return newDecl;
893                } // if
894                return objDecl;
895        }
896
897        void ReplaceTypedef::premutate( CastExpr * ) {
898                GuardScope( typedefNames );
899                GuardScope( typedeclNames );
900        }
901
902        void ReplaceTypedef::premutate( CompoundStmt * ) {
903                GuardScope( typedefNames );
904                GuardScope( typedeclNames );
905                scopeLevel += 1;
906                GuardAction( [this](){ scopeLevel -= 1; } );
907        }
908
909        template<typename AggDecl>
910        void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
911                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
912                        Type * type = nullptr;
913                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
914                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
915                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
916                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
917                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
918                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
919                        } // if
920                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
921                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
922                        // add the implicit typedef to the AST
923                        declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
924                } // if
925        }
926
927        template< typename AggDecl >
928        void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
929                SemanticErrorException errors;
930
931                ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
932                ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter  );
933                declsToAddBefore.clear();
934                declsToAddAfter.clear();
935
936                GuardScope( typedefNames );
937                GuardScope( typedeclNames );
938                mutateAll( aggr->parameters, * visitor );
939                mutateAll( aggr->attributes, * visitor );
940
941                // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
942                for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
943                        if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
944
945                        try {
946                                * i = maybeMutate( * i, * visitor );
947                        } catch ( SemanticErrorException &e ) {
948                                errors.append( e );
949                        }
950
951                        if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
952                }
953
954                if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
955                if ( !errors.isEmpty() ) { throw errors; }
956        }
957
958        void ReplaceTypedef::premutate( StructDecl * structDecl ) {
959                visit_children = false;
960                addImplicitTypedef( structDecl );
961                handleAggregate( structDecl );
962        }
963
964        void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
965                visit_children = false;
966                addImplicitTypedef( unionDecl );
967                handleAggregate( unionDecl );
968        }
969
970        void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
971                addImplicitTypedef( enumDecl );
972        }
973
974        void ReplaceTypedef::premutate( FunctionType * ) {
975                GuardValue( inFunctionType );
976                inFunctionType = true;
977        }
978
979        void ReplaceTypedef::premutate( TraitDecl * ) {
980                GuardScope( typedefNames );
981                GuardScope( typedeclNames);
982        }
983
984        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
985                PassVisitor<VerifyCtorDtorAssign> verifier;
986                acceptAll( translationUnit, verifier );
987        }
988
989        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
990                FunctionType * funcType = funcDecl->get_functionType();
991                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
992                std::list< DeclarationWithType * > &params = funcType->get_parameters();
993
994                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
995                        if ( params.size() == 0 ) {
996                                SemanticError( funcDecl->location, "Constructors, destructors, and assignment functions require at least one parameter." );
997                        }
998                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
999                        if ( ! refType ) {
1000                                SemanticError( funcDecl->location, "First parameter of a constructor, destructor, or assignment function must be a reference." );
1001                        }
1002                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
1003                                if(!returnVals.front()->get_type()->isVoid()) {
1004                                        SemanticError( funcDecl->location, "Constructors and destructors cannot have explicit return values." );
1005                                }
1006                        }
1007                }
1008        }
1009
1010        // Test for special name on a generic parameter.  Special treatment for the
1011        // special name is a bootstrapping hack.  In most cases, the worlds of T's
1012        // and of N's don't overlap (normal treamtemt).  The foundations in
1013        // array.hfa use tagging for both types and dimensions.  Tagging treats
1014        // its subject parameter even more opaquely than T&, which assumes it is
1015        // possible to have a pointer/reference to such an object.  Tagging only
1016        // seeks to identify the type-system resident at compile time.  Both N's
1017        // and T's can make tags.  The tag definition uses the special name, which
1018        // is treated as "an N or a T."  This feature is not inteded to be used
1019        // outside of the definition and immediate uses of a tag.
1020        static inline bool isReservedTysysIdOnlyName( const std::string & name ) {
1021                // name's prefix was __CFA_tysys_id_only, before it got wrapped in __..._generic
1022                int foundAt = name.find("__CFA_tysys_id_only");
1023                if (foundAt == 0) return true;
1024                if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true;
1025                return false;
1026        }
1027
1028        template< typename Aggr >
1029        void validateGeneric( Aggr * inst ) {
1030                std::list< TypeDecl * > * params = inst->get_baseParameters();
1031                if ( params ) {
1032                        std::list< Expression * > & args = inst->get_parameters();
1033
1034                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1035                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1036                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1037                        //   vector(int) v;
1038                        // after insertion of default values becomes
1039                        //   vector(int, heap_allocator(T))
1040                        // and the substitution is built with T=int so that after substitution, the result is
1041                        //   vector(int, heap_allocator(int))
1042                        TypeSubstitution sub;
1043                        auto paramIter = params->begin();
1044                        auto argIter = args.begin();
1045                        for ( ; paramIter != params->end(); ++paramIter, ++argIter ) {
1046                                if ( argIter != args.end() ) {
1047                                        TypeExpr * expr = dynamic_cast< TypeExpr * >( * argIter );
1048                                        if ( expr ) {
1049                                                sub.add( (* paramIter)->get_name(), expr->get_type()->clone() );
1050                                        }
1051                                } else {
1052                                        Type * defaultType = (* paramIter)->get_init();
1053                                        if ( defaultType ) {
1054                                                args.push_back( new TypeExpr( defaultType->clone() ) );
1055                                                sub.add( (* paramIter)->get_name(), defaultType->clone() );
1056                                                argIter = std::prev(args.end());
1057                                        } else {
1058                                                SemanticError( inst, "Too few type arguments in generic type " );
1059                                        }
1060                                }
1061                                assert( argIter != args.end() );
1062                                bool typeParamDeclared = (*paramIter)->kind != TypeDecl::Kind::Dimension;
1063                                bool typeArgGiven;
1064                                if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) {
1065                                        // coerce a match when declaration is reserved name, which means "either"
1066                                        typeArgGiven = typeParamDeclared;
1067                                } else {
1068                                        typeArgGiven = dynamic_cast< TypeExpr * >( * argIter );
1069                                }
1070                                if ( ! typeParamDeclared &&   typeArgGiven ) SemanticError( inst, "Type argument given for value parameter: " );
1071                                if (   typeParamDeclared && ! typeArgGiven ) SemanticError( inst, "Expression argument given for type parameter: " );
1072                        }
1073
1074                        sub.apply( inst );
1075                        if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1076                }
1077        }
1078
1079        void ValidateGenericParameters::previsit( StructInstType * inst ) {
1080                validateGeneric( inst );
1081        }
1082
1083        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1084                validateGeneric( inst );
1085        }
1086
1087        void TranslateDimensionGenericParameters::translateDimensions( std::list< Declaration * > &translationUnit ) {
1088                PassVisitor<TranslateDimensionGenericParameters> translator;
1089                mutateAll( translationUnit, translator );
1090        }
1091
1092        TranslateDimensionGenericParameters::TranslateDimensionGenericParameters() : WithIndexer( false ) {}
1093
1094        // Declaration of type variable:           forall( [N] )          ->  forall( N & | sized( N ) )
1095        TypeDecl * TranslateDimensionGenericParameters::postmutate( TypeDecl * td ) {
1096                if ( td->kind == TypeDecl::Dimension ) {
1097                        td->kind = TypeDecl::Dtype;
1098                        if ( ! isReservedTysysIdOnlyName( td->name ) ) {
1099                                td->sized = true;
1100                        }
1101                }
1102                return td;
1103        }
1104
1105        // Situational awareness:
1106        // array( float, [[currentExpr]]     )  has  visitingChildOfSUIT == true
1107        // array( float, [[currentExpr]] - 1 )  has  visitingChildOfSUIT == false
1108        // size_t x =    [[currentExpr]]        has  visitingChildOfSUIT == false
1109        void TranslateDimensionGenericParameters::changeState_ChildOfSUIT( bool newVal ) {
1110                GuardValue( nextVisitedNodeIsChildOfSUIT );
1111                GuardValue( visitingChildOfSUIT );
1112                visitingChildOfSUIT = nextVisitedNodeIsChildOfSUIT;
1113                nextVisitedNodeIsChildOfSUIT = newVal;
1114        }
1115        void TranslateDimensionGenericParameters::premutate( StructInstType * sit ) {
1116                (void) sit;
1117                changeState_ChildOfSUIT(true);
1118        }
1119        void TranslateDimensionGenericParameters::premutate( UnionInstType * uit ) {
1120                (void) uit;
1121                changeState_ChildOfSUIT(true);
1122        }
1123        void TranslateDimensionGenericParameters::premutate( BaseSyntaxNode * node ) {
1124                (void) node;
1125                changeState_ChildOfSUIT(false);
1126        }
1127
1128        // Passing values as dimension arguments:  array( float,     7 )  -> array( float, char[             7 ] )
1129        // Consuming dimension parameters:         size_t x =    N - 1 ;  -> size_t x =          sizeof(N) - 1   ;
1130        // Intertwined reality:                    array( float, N     )  -> array( float,              N        )
1131        //                                         array( float, N - 1 )  -> array( float, char[ sizeof(N) - 1 ] )
1132        // Intertwined case 1 is not just an optimization.
1133        // Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
1134        //   forall([N]) void f( array(float, N) & );
1135        //   array(float, 7) a;
1136        //   f(a);
1137
1138        Expression * TranslateDimensionGenericParameters::postmutate( DimensionExpr * de ) {
1139                // Expression de is an occurrence of N in LHS of above examples.
1140                // Look up the name that de references.
1141                // If we are in a struct body, then this reference can be to an entry of the stuct's forall list.
1142                // Whether or not we are in a struct body, this reference can be to an entry of a containing function's forall list.
1143                // If we are in a struct body, then the stuct's forall declarations are innermost (functions don't occur in structs).
1144                // Thus, a potential struct's declaration is highest priority.
1145                // A struct's forall declarations are already renamed with _generic_ suffix.  Try that name variant first.
1146
1147                std::string useName = "__" + de->name + "_generic_";
1148                TypeDecl * namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1149
1150                if ( ! namedParamDecl ) {
1151                        useName = de->name;
1152                        namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1153                }
1154
1155                // Expect to find it always.  A misspelled name would have been parsed as an identifier.
1156                assert( namedParamDecl && "Type-system-managed value name not found in symbol table" );
1157
1158                delete de;
1159
1160                TypeInstType * refToDecl = new TypeInstType( 0, useName, namedParamDecl );
1161
1162                if ( visitingChildOfSUIT ) {
1163                        // As in postmutate( Expression * ), topmost expression needs a TypeExpr wrapper
1164                        // But avoid ArrayType-Sizeof
1165                        return new TypeExpr( refToDecl );
1166                } else {
1167                        // the N occurrence is being used directly as a runtime value,
1168                        // if we are in a type instantiation, then the N is within a bigger value computation
1169                        return new SizeofExpr( refToDecl );
1170                }
1171        }
1172
1173        Expression * TranslateDimensionGenericParameters::postmutate( Expression * e ) {
1174                if ( visitingChildOfSUIT ) {
1175                        // e is an expression used as an argument to instantiate a type
1176                        if (! dynamic_cast< TypeExpr * >( e ) ) {
1177                                // e is a value expression
1178                                // but not a DimensionExpr, which has a distinct postmutate
1179                                Type * typeExprContent = new ArrayType( 0, new BasicType( 0, BasicType::Char ), e, true, false );
1180                                TypeExpr * result = new TypeExpr( typeExprContent );
1181                                return result;
1182                        }
1183                }
1184                return e;
1185        }
1186
1187        void CompoundLiteral::premutate( ObjectDecl * objectDecl ) {
1188                storageClasses = objectDecl->get_storageClasses();
1189        }
1190
1191        Expression * CompoundLiteral::postmutate( CompoundLiteralExpr * compLitExpr ) {
1192                // transform [storage_class] ... (struct S){ 3, ... };
1193                // into [storage_class] struct S temp =  { 3, ... };
1194                static UniqueName indexName( "_compLit" );
1195
1196                ObjectDecl * tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1197                compLitExpr->set_result( nullptr );
1198                compLitExpr->set_initializer( nullptr );
1199                delete compLitExpr;
1200                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1201                return new VariableExpr( tempvar );
1202        }
1203
1204        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1205                PassVisitor<ReturnTypeFixer> fixer;
1206                acceptAll( translationUnit, fixer );
1207        }
1208
1209        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1210                FunctionType * ftype = functionDecl->get_functionType();
1211                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1212                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1213                if ( retVals.size() == 1 ) {
1214                        // 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).
1215                        // ensure other return values have a name.
1216                        DeclarationWithType * ret = retVals.front();
1217                        if ( ret->get_name() == "" ) {
1218                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1219                        }
1220                        ret->get_attributes().push_back( new Attribute( "unused" ) );
1221                }
1222        }
1223
1224        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1225                // xxx - need to handle named return values - this information needs to be saved somehow
1226                // so that resolution has access to the names.
1227                // Note that this pass needs to happen early so that other passes which look for tuple types
1228                // find them in all of the right places, including function return types.
1229                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1230                if ( retVals.size() > 1 ) {
1231                        // generate a single return parameter which is the tuple of all of the return values
1232                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1233                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1234                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer *>(), noDesignators, false ) );
1235                        deleteAll( retVals );
1236                        retVals.clear();
1237                        retVals.push_back( newRet );
1238                }
1239        }
1240
1241        void FixObjectType::fix( std::list< Declaration * > & translationUnit ) {
1242                PassVisitor<FixObjectType> fixer;
1243                acceptAll( translationUnit, fixer );
1244        }
1245
1246        void FixObjectType::previsit( ObjectDecl * objDecl ) {
1247                Type * new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer );
1248                objDecl->set_type( new_type );
1249        }
1250
1251        void FixObjectType::previsit( FunctionDecl * funcDecl ) {
1252                Type * new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer );
1253                funcDecl->set_type( new_type );
1254        }
1255
1256        void FixObjectType::previsit( TypeDecl * typeDecl ) {
1257                if ( typeDecl->get_base() ) {
1258                        Type * new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer );
1259                        typeDecl->set_base( new_type );
1260                } // if
1261        }
1262
1263        void InitializerLength::computeLength( std::list< Declaration * > & translationUnit ) {
1264                PassVisitor<InitializerLength> len;
1265                acceptAll( translationUnit, len );
1266        }
1267
1268        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1269                PassVisitor<ArrayLength> len;
1270                acceptAll( translationUnit, len );
1271        }
1272
1273        void InitializerLength::previsit( ObjectDecl * objDecl ) {
1274                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1275                        if ( at->dimension ) return;
1276                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1277                                at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
1278                        }
1279                }
1280        }
1281
1282        void ArrayLength::previsit( ArrayType * type ) {
1283                if ( type->dimension ) {
1284                        // need to resolve array dimensions early so that constructor code can correctly determine
1285                        // if a type is a VLA (and hence whether its elements need to be constructed)
1286                        ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
1287
1288                        // must re-evaluate whether a type is a VLA, now that more information is available
1289                        // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1290                        type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
1291                }
1292        }
1293
1294        struct LabelFinder {
1295                std::set< Label > & labels;
1296                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1297                void previsit( Statement * stmt ) {
1298                        for ( Label & l : stmt->labels ) {
1299                                labels.insert( l );
1300                        }
1301                }
1302        };
1303
1304        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1305                GuardValue( labels );
1306                PassVisitor<LabelFinder> finder( labels );
1307                funcDecl->accept( finder );
1308        }
1309
1310        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1311                // convert &&label into label address
1312                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1313                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1314                                if ( labels.count( nameExpr->name ) ) {
1315                                        Label name = nameExpr->name;
1316                                        delete addrExpr;
1317                                        return new LabelAddressExpr( name );
1318                                }
1319                        }
1320                }
1321                return addrExpr;
1322        }
1323
1324} // namespace SymTab
1325
1326// Local Variables: //
1327// tab-width: 4 //
1328// mode: c++ //
1329// compile-command: "make install" //
1330// End: //
Note: See TracBrowser for help on using the repository browser.