source: src/SymTab/Validate.cc@ 54f89d5

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 54f89d5 was 3ff4c1e, checked in by Fangren Yu <f37yu@…>, 5 years ago

restore ArrayLength as it seems to serve other purposes

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