source: src/SymTab/Validate.cc@ fdbd4fd

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since fdbd4fd was c884f2d, checked in by tdelisle <tdelisle@…>, 7 years ago

Fixed error for % of parent printing in timing sections and added more timing instrumentation

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