source: src/SymTab/Validate.cc@ c194661

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr no_list persistent-indexer pthread-emulation qualifiedEnum
Last change on this file since c194661 was 29f9e20, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Reorganize validate passes and reduce scope of HoistStruct pass

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