source: src/SymTab/Validate.cc@ b60f9d9

new-env
Last change on this file since b60f9d9 was 42107b4, checked in by Aaron Moss <a3moss@…>, 8 years ago

Leftover cleanup from merge

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