source: src/SymTab/Validate.cc@ 63db8fd7

ADT ast-experimental enum pthread-emulation qualifiedEnum
Last change on this file since 63db8fd7 was a76202d, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Removed some code from Validate that had been used for the translation of validate_D.

  • Property mode set to 100644
File size: 82.0 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Validate.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Sun May 17 21:50:04 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Fri Nov 12 11:00:00 2021
13// Update Count : 364
14//
15
16// The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
17// as regular in structure as possible. Some assumptions can be made regarding the state of the tree after this pass is
18// complete, including:
19//
20// - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
21// union.
22//
23// - All enumeration constants have type EnumInstType.
24//
25// - The type "void" never occurs in lists of function parameter or return types. A function
26// taking no arguments has no argument types.
27//
28// - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
29// by the particular set of type arguments.
30//
31// - Every declaration is assigned a unique id.
32//
33// - No typedef declarations or instances exist; the actual type is substituted for each instance.
34//
35// - Each type, struct, and union definition is followed by an appropriate assignment operator.
36//
37// - Each use of a struct or union is connected to a complete definition of that struct or union, even if that
38// definition occurs later in the input.
39
40#include "Validate.h"
41
42#include <cassert> // for assertf, assert
43#include <cstddef> // for size_t
44#include <list> // for list
45#include <string> // for string
46#include <unordered_map> // for unordered_map
47#include <utility> // for pair
48
49#include "AST/Chain.hpp"
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"
55#include "AST/TypeSubstitution.hpp"
56#include "CodeGen/CodeGenerator.h" // for genName
57#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
58#include "ControlStruct/Mutate.h" // for ForExprMutator
59#include "Common/CodeLocation.h" // for CodeLocation
60#include "Common/Stats.h" // for Stats::Heap
61#include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd
62#include "Common/ScopedMap.h" // for ScopedMap
63#include "Common/SemanticError.h" // for SemanticError
64#include "Common/UniqueName.h" // for UniqueName
65#include "Common/utility.h" // for operator+, cloneAll, deleteAll
66#include "CompilationState.h" // skip some passes in new-ast build
67#include "Concurrency/Keywords.h" // for applyKeywords
68#include "FixFunction.h" // for FixFunction
69#include "Indexer.h" // for Indexer
70#include "InitTweak/GenInit.h" // for fixReturnStatements
71#include "InitTweak/InitTweak.h" // for isCtorDtorAssign
72#include "ResolvExpr/typeops.h" // for typesCompatible
73#include "ResolvExpr/Resolver.h" // for findSingleExpression
74#include "ResolvExpr/ResolveTypeof.h" // for resolveTypeof
75#include "SymTab/Autogen.h" // for SizeType
76#include "SynTree/LinkageSpec.h" // for C
77#include "SynTree/Attribute.h" // for noAttributes, Attribute
78#include "SynTree/Constant.h" // for Constant
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
87#include "Validate/HandleAttributes.h" // for handleAttributes
88#include "Validate/FindSpecialDecls.h" // for FindSpecialDecls
89
90class CompoundStmt;
91class ReturnStmt;
92class SwitchStmt;
93
94#define debugPrint( x ) if ( doDebug ) x
95
96namespace SymTab {
97 /// hoists declarations that are difficult to hoist while parsing
98 struct HoistTypeDecls final : public WithDeclsToAdd {
99 void previsit( SizeofExpr * );
100 void previsit( AlignofExpr * );
101 void previsit( UntypedOffsetofExpr * );
102 void previsit( CompoundLiteralExpr * );
103 void handleType( Type * );
104 };
105
106 struct FixQualifiedTypes final : public WithIndexer {
107 FixQualifiedTypes() : WithIndexer(false) {}
108 Type * postmutate( QualifiedType * );
109 };
110
111 struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
112 /// Flattens nested struct types
113 static void hoistStruct( std::list< Declaration * > &translationUnit );
114
115 void previsit( StructDecl * aggregateDecl );
116 void previsit( UnionDecl * aggregateDecl );
117 void previsit( StaticAssertDecl * assertDecl );
118 void previsit( StructInstType * type );
119 void previsit( UnionInstType * type );
120 void previsit( EnumInstType * type );
121
122 private:
123 template< typename AggDecl > void handleAggregate( AggDecl * aggregateDecl );
124
125 AggregateDecl * parentAggr = nullptr;
126 };
127
128 /// Fix return types so that every function returns exactly one value
129 struct ReturnTypeFixer {
130 static void fix( std::list< Declaration * > &translationUnit );
131
132 void postvisit( FunctionDecl * functionDecl );
133 void postvisit( FunctionType * ftype );
134 };
135
136 /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
137 struct EnumAndPointerDecay_old {
138 void previsit( EnumDecl * aggregateDecl );
139 void previsit( FunctionType * func );
140 };
141
142 /// Associates forward declarations of aggregates with their definitions
143 struct LinkReferenceToTypes_old final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes_old>, public WithShortCircuiting {
144 LinkReferenceToTypes_old( const Indexer * indexer );
145 void postvisit( TypeInstType * typeInst );
146
147 void postvisit( EnumInstType * enumInst );
148 void postvisit( StructInstType * structInst );
149 void postvisit( UnionInstType * unionInst );
150 void postvisit( TraitInstType * traitInst );
151 void previsit( QualifiedType * qualType );
152 void postvisit( QualifiedType * qualType );
153
154 void postvisit( EnumDecl * enumDecl );
155 void postvisit( StructDecl * structDecl );
156 void postvisit( UnionDecl * unionDecl );
157 void postvisit( TraitDecl * traitDecl );
158
159 void previsit( StructDecl * structDecl );
160 void previsit( UnionDecl * unionDecl );
161
162 void renameGenericParams( std::list< TypeDecl * > & params );
163
164 private:
165 const Indexer * local_indexer;
166
167 typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
168 typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
169 typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
170 ForwardEnumsType forwardEnums;
171 ForwardStructsType forwardStructs;
172 ForwardUnionsType forwardUnions;
173 /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
174 bool inGeneric = false;
175 };
176
177 /// Does early resolution on the expressions that give enumeration constants their values
178 struct ResolveEnumInitializers final : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveEnumInitializers>, public WithShortCircuiting {
179 ResolveEnumInitializers( const Indexer * indexer );
180 void postvisit( EnumDecl * enumDecl );
181
182 private:
183 const Indexer * local_indexer;
184
185 };
186
187 /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
188 struct ForallPointerDecay_old final {
189 void previsit( ObjectDecl * object );
190 void previsit( FunctionDecl * func );
191 void previsit( FunctionType * ftype );
192 void previsit( StructDecl * aggrDecl );
193 void previsit( UnionDecl * aggrDecl );
194 };
195
196 // These structs are the sub-sub-passes of ForallPointerDecay_old.
197
198 struct TraitExpander_old final {
199 void previsit( FunctionType * );
200 void previsit( StructDecl * );
201 void previsit( UnionDecl * );
202 };
203
204 struct AssertionFixer_old final {
205 void previsit( FunctionType * );
206 void previsit( StructDecl * );
207 void previsit( UnionDecl * );
208 };
209
210 struct CheckOperatorTypes_old final {
211 void previsit( ObjectDecl * );
212 };
213
214 struct FixUniqueIds_old final {
215 void previsit( DeclarationWithType * );
216 };
217
218 struct ReturnChecker : public WithGuards {
219 /// Checks that return statements return nothing if their return type is void
220 /// and return something if the return type is non-void.
221 static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
222
223 void previsit( FunctionDecl * functionDecl );
224 void previsit( ReturnStmt * returnStmt );
225
226 typedef std::list< DeclarationWithType * > ReturnVals;
227 ReturnVals returnVals;
228 };
229
230 struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
231 ReplaceTypedef() : scopeLevel( 0 ) {}
232 /// Replaces typedefs by forward declarations
233 static void replaceTypedef( std::list< Declaration * > &translationUnit );
234
235 void premutate( QualifiedType * );
236 Type * postmutate( QualifiedType * qualType );
237 Type * postmutate( TypeInstType * aggregateUseType );
238 Declaration * postmutate( TypedefDecl * typeDecl );
239 void premutate( TypeDecl * typeDecl );
240 void premutate( FunctionDecl * funcDecl );
241 void premutate( ObjectDecl * objDecl );
242 DeclarationWithType * postmutate( ObjectDecl * objDecl );
243
244 void premutate( CastExpr * castExpr );
245
246 void premutate( CompoundStmt * compoundStmt );
247
248 void premutate( StructDecl * structDecl );
249 void premutate( UnionDecl * unionDecl );
250 void premutate( EnumDecl * enumDecl );
251 void premutate( TraitDecl * );
252
253 void premutate( FunctionType * ftype );
254
255 private:
256 template<typename AggDecl>
257 void addImplicitTypedef( AggDecl * aggDecl );
258 template< typename AggDecl >
259 void handleAggregate( AggDecl * aggr );
260
261 typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
262 typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
263 typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
264 TypedefMap typedefNames;
265 TypeDeclMap typedeclNames;
266 int scopeLevel;
267 bool inFunctionType = false;
268 };
269
270 struct EliminateTypedef {
271 /// removes TypedefDecls from the AST
272 static void eliminateTypedef( std::list< Declaration * > &translationUnit );
273
274 template<typename AggDecl>
275 void handleAggregate( AggDecl * aggregateDecl );
276
277 void previsit( StructDecl * aggregateDecl );
278 void previsit( UnionDecl * aggregateDecl );
279 void previsit( CompoundStmt * compoundStmt );
280 };
281
282 struct VerifyCtorDtorAssign {
283 /// ensure that constructors, destructors, and assignment have at least one
284 /// parameter, the first of which must be a pointer, and that ctor/dtors have no
285 /// return values.
286 static void verify( std::list< Declaration * > &translationUnit );
287
288 void previsit( FunctionDecl * funcDecl );
289 };
290
291 /// ensure that generic types have the correct number of type arguments
292 struct ValidateGenericParameters {
293 void previsit( StructInstType * inst );
294 void previsit( UnionInstType * inst );
295 };
296
297 /// desugar declarations and uses of dimension paramaters like [N],
298 /// from type-system managed values, to tunnneling via ordinary types,
299 /// as char[-] in and sizeof(-) out
300 struct TranslateDimensionGenericParameters : public WithIndexer, public WithGuards {
301 static void translateDimensions( std::list< Declaration * > &translationUnit );
302 TranslateDimensionGenericParameters();
303
304 bool nextVisitedNodeIsChildOfSUIT = false; // SUIT = Struct or Union -Inst Type
305 bool visitingChildOfSUIT = false;
306 void changeState_ChildOfSUIT( bool newVal );
307 void premutate( StructInstType * sit );
308 void premutate( UnionInstType * uit );
309 void premutate( BaseSyntaxNode * node );
310
311 TypeDecl * postmutate( TypeDecl * td );
312 Expression * postmutate( DimensionExpr * de );
313 Expression * postmutate( Expression * e );
314 };
315
316 struct FixObjectType : public WithIndexer {
317 /// resolves typeof type in object, function, and type declarations
318 static void fix( std::list< Declaration * > & translationUnit );
319
320 void previsit( ObjectDecl * );
321 void previsit( FunctionDecl * );
322 void previsit( TypeDecl * );
323 };
324
325 struct InitializerLength {
326 /// for array types without an explicit length, compute the length and store it so that it
327 /// is known to the rest of the phases. For example,
328 /// int x[] = { 1, 2, 3 };
329 /// int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
330 /// here x and y are known at compile-time to have length 3, so change this into
331 /// int x[3] = { 1, 2, 3 };
332 /// int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
333 static void computeLength( std::list< Declaration * > & translationUnit );
334
335 void previsit( ObjectDecl * objDecl );
336 };
337
338 struct ArrayLength : public WithIndexer {
339 static void computeLength( std::list< Declaration * > & translationUnit );
340
341 void previsit( ArrayType * arrayType );
342 };
343
344 struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
345 Type::StorageClasses storageClasses;
346
347 void premutate( ObjectDecl * objectDecl );
348 Expression * postmutate( CompoundLiteralExpr * compLitExpr );
349 };
350
351 struct LabelAddressFixer final : public WithGuards {
352 std::set< Label > labels;
353
354 void premutate( FunctionDecl * funcDecl );
355 Expression * postmutate( AddressExpr * addrExpr );
356 };
357
358 void validate_A( std::list< Declaration * > & translationUnit ) {
359 PassVisitor<EnumAndPointerDecay_old> epc;
360 PassVisitor<HoistTypeDecls> hoistDecls;
361 {
362 Stats::Heap::newPass("validate-A");
363 Stats::Time::BlockGuard guard("validate-A");
364 VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors
365 acceptAll( translationUnit, hoistDecls );
366 ReplaceTypedef::replaceTypedef( translationUnit );
367 ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
368 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
369 }
370 }
371
372 void validate_B( std::list< Declaration * > & translationUnit ) {
373 PassVisitor<LinkReferenceToTypes_old> lrt( nullptr );
374 PassVisitor<FixQualifiedTypes> fixQual;
375 {
376 Stats::Heap::newPass("validate-B");
377 Stats::Time::BlockGuard guard("validate-B");
378 acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
379 mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes_old, because aggregate members are accessed
380 HoistStruct::hoistStruct( translationUnit );
381 EliminateTypedef::eliminateTypedef( translationUnit );
382 }
383 }
384
385 void validate_C( std::list< Declaration * > & translationUnit ) {
386 PassVisitor<ValidateGenericParameters> genericParams;
387 PassVisitor<ResolveEnumInitializers> rei( nullptr );
388 {
389 Stats::Heap::newPass("validate-C");
390 Stats::Time::BlockGuard guard("validate-C");
391 Stats::Time::TimeBlock("Validate Generic Parameters", [&]() {
392 acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes_old; observed failing when attempted before eliminateTypedef
393 });
394 Stats::Time::TimeBlock("Translate Dimensions", [&]() {
395 TranslateDimensionGenericParameters::translateDimensions( translationUnit );
396 });
397 Stats::Time::TimeBlock("Resolve Enum Initializers", [&]() {
398 acceptAll( translationUnit, rei ); // must happen after translateDimensions because rei needs identifier lookup, which needs name mangling
399 });
400 Stats::Time::TimeBlock("Check Function Returns", [&]() {
401 ReturnChecker::checkFunctionReturns( translationUnit );
402 });
403 Stats::Time::TimeBlock("Fix Return Statements", [&]() {
404 InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
405 });
406 }
407 }
408
409 static void decayForallPointers( std::list< Declaration * > & translationUnit ) {
410 PassVisitor<TraitExpander_old> te;
411 acceptAll( translationUnit, te );
412 PassVisitor<AssertionFixer_old> af;
413 acceptAll( translationUnit, af );
414 PassVisitor<CheckOperatorTypes_old> cot;
415 acceptAll( translationUnit, cot );
416 PassVisitor<FixUniqueIds_old> fui;
417 acceptAll( translationUnit, fui );
418 }
419
420 void validate_D( std::list< Declaration * > & translationUnit ) {
421 {
422 Stats::Heap::newPass("validate-D");
423 Stats::Time::BlockGuard guard("validate-D");
424 Stats::Time::TimeBlock("Apply Concurrent Keywords", [&]() {
425 Concurrency::applyKeywords( translationUnit );
426 });
427 Stats::Time::TimeBlock("Forall Pointer Decay", [&]() {
428 decayForallPointers( translationUnit ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
429 });
430 Stats::Time::TimeBlock("Hoist Control Declarations", [&]() {
431 ControlStruct::hoistControlDecls( translationUnit ); // hoist initialization out of for statements; must happen before autogenerateRoutines
432 });
433 Stats::Time::TimeBlock("Generate Autogen routines", [&]() {
434 autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay_old
435 });
436 }
437 }
438
439 void validate_E( std::list< Declaration * > & translationUnit ) {
440 PassVisitor<CompoundLiteral> compoundliteral;
441 {
442 Stats::Heap::newPass("validate-E");
443 Stats::Time::BlockGuard guard("validate-E");
444 Stats::Time::TimeBlock("Implement Mutex Func", [&]() {
445 Concurrency::implementMutexFuncs( translationUnit );
446 });
447 Stats::Time::TimeBlock("Implement Thread Start", [&]() {
448 Concurrency::implementThreadStarter( translationUnit );
449 });
450 Stats::Time::TimeBlock("Compound Literal", [&]() {
451 mutateAll( translationUnit, compoundliteral );
452 });
453 if (!useNewAST) {
454 Stats::Time::TimeBlock("Resolve With Expressions", [&]() {
455 ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables
456 });
457 }
458 }
459 }
460
461 void validate_F( std::list< Declaration * > & translationUnit ) {
462 PassVisitor<LabelAddressFixer> labelAddrFixer;
463 {
464 Stats::Heap::newPass("validate-F");
465 Stats::Time::BlockGuard guard("validate-F");
466 if (!useNewAST) {
467 Stats::Time::TimeCall("Fix Object Type",
468 FixObjectType::fix, translationUnit);
469 }
470 Stats::Time::TimeCall("Initializer Length",
471 InitializerLength::computeLength, translationUnit);
472 if (!useNewAST) {
473 Stats::Time::TimeCall("Array Length",
474 ArrayLength::computeLength, translationUnit);
475 }
476 Stats::Time::TimeCall("Find Special Declarations",
477 Validate::findSpecialDecls, translationUnit);
478 Stats::Time::TimeCall("Fix Label Address",
479 mutateAll<LabelAddressFixer>, translationUnit, labelAddrFixer);
480 if (!useNewAST) {
481 Stats::Time::TimeCall("Handle Attributes",
482 Validate::handleAttributes, translationUnit);
483 }
484 }
485 }
486
487 void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
488 validate_A( translationUnit );
489 validate_B( translationUnit );
490 validate_C( translationUnit );
491 validate_D( translationUnit );
492 validate_E( translationUnit );
493 validate_F( translationUnit );
494 }
495
496 void validateType( Type * type, const Indexer * indexer ) {
497 PassVisitor<EnumAndPointerDecay_old> epc;
498 PassVisitor<LinkReferenceToTypes_old> lrt( indexer );
499 PassVisitor<TraitExpander_old> te;
500 PassVisitor<AssertionFixer_old> af;
501 PassVisitor<CheckOperatorTypes_old> cot;
502 PassVisitor<FixUniqueIds_old> fui;
503 type->accept( epc );
504 type->accept( lrt );
505 type->accept( te );
506 type->accept( af );
507 type->accept( cot );
508 type->accept( fui );
509 }
510
511 void HoistTypeDecls::handleType( Type * type ) {
512 // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
513 AggregateDecl * aggr = nullptr;
514 if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
515 aggr = inst->baseStruct;
516 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
517 aggr = inst->baseUnion;
518 } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
519 aggr = inst->baseEnum;
520 }
521 if ( aggr && aggr->body ) {
522 declsToAddBefore.push_front( aggr );
523 }
524 }
525
526 void HoistTypeDecls::previsit( SizeofExpr * expr ) {
527 handleType( expr->type );
528 }
529
530 void HoistTypeDecls::previsit( AlignofExpr * expr ) {
531 handleType( expr->type );
532 }
533
534 void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
535 handleType( expr->type );
536 }
537
538 void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
539 handleType( expr->result );
540 }
541
542
543 Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
544 Type * parent = qualType->parent;
545 Type * child = qualType->child;
546 if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
547 // .T => lookup T at global scope
548 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
549 auto td = indexer.globalLookupType( inst->name );
550 if ( ! td ) {
551 SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
552 }
553 auto base = td->base;
554 assert( base );
555 Type * ret = base->clone();
556 ret->get_qualifiers() = qualType->get_qualifiers();
557 return ret;
558 } else {
559 // .T => T is not a type name
560 assertf( false, "unhandled global qualified child type: %s", toCString(child) );
561 }
562 } else {
563 // S.T => S must be an aggregate type, find the declaration for T in S.
564 AggregateDecl * aggr = nullptr;
565 if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
566 aggr = inst->baseStruct;
567 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
568 aggr = inst->baseUnion;
569 } else {
570 SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
571 }
572 assert( aggr ); // TODO: need to handle forward declarations
573 for ( Declaration * member : aggr->members ) {
574 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
575 // name on the right is a typedef
576 if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
577 if ( aggr->name == inst->name ) {
578 assert( aggr->base );
579 Type * ret = aggr->base->clone();
580 ret->get_qualifiers() = qualType->get_qualifiers();
581 TypeSubstitution sub = parent->genericSubstitution();
582 sub.apply(ret);
583 return ret;
584 }
585 }
586 } else {
587 // S.T - S is not an aggregate => error
588 assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
589 }
590 }
591 // failed to find a satisfying definition of type
592 SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
593 }
594
595 // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
596 }
597
598
599 void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
600 PassVisitor<HoistStruct> hoister;
601 acceptAll( translationUnit, hoister );
602 }
603
604 bool shouldHoist( Declaration * decl ) {
605 return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
606 }
607
608 namespace {
609 void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
610 if ( aggr->parent ) qualifiedName( aggr->parent, ss );
611 ss << "__" << aggr->name;
612 }
613
614 // mangle nested type names using entire parent chain
615 std::string qualifiedName( AggregateDecl * aggr ) {
616 std::ostringstream ss;
617 qualifiedName( aggr, ss );
618 return ss.str();
619 }
620 }
621
622 template< typename AggDecl >
623 void HoistStruct::handleAggregate( AggDecl * aggregateDecl ) {
624 if ( parentAggr ) {
625 aggregateDecl->parent = parentAggr;
626 aggregateDecl->name = qualifiedName( aggregateDecl );
627 // Add elements in stack order corresponding to nesting structure.
628 declsToAddBefore.push_front( aggregateDecl );
629 } else {
630 GuardValue( parentAggr );
631 parentAggr = aggregateDecl;
632 } // if
633 // Always remove the hoisted aggregate from the inner structure.
634 GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
635 }
636
637 void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
638 if ( parentAggr ) {
639 declsToAddBefore.push_back( assertDecl );
640 }
641 }
642
643 void HoistStruct::previsit( StructDecl * aggregateDecl ) {
644 handleAggregate( aggregateDecl );
645 }
646
647 void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
648 handleAggregate( aggregateDecl );
649 }
650
651 void HoistStruct::previsit( StructInstType * type ) {
652 // need to reset type name after expanding to qualified name
653 assert( type->baseStruct );
654 type->name = type->baseStruct->name;
655 }
656
657 void HoistStruct::previsit( UnionInstType * type ) {
658 assert( type->baseUnion );
659 type->name = type->baseUnion->name;
660 }
661
662 void HoistStruct::previsit( EnumInstType * type ) {
663 assert( type->baseEnum );
664 type->name = type->baseEnum->name;
665 }
666
667
668 bool isTypedef( Declaration * decl ) {
669 return dynamic_cast< TypedefDecl * >( decl );
670 }
671
672 void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
673 PassVisitor<EliminateTypedef> eliminator;
674 acceptAll( translationUnit, eliminator );
675 filter( translationUnit, isTypedef, true );
676 }
677
678 template< typename AggDecl >
679 void EliminateTypedef::handleAggregate( AggDecl * aggregateDecl ) {
680 filter( aggregateDecl->members, isTypedef, true );
681 }
682
683 void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
684 handleAggregate( aggregateDecl );
685 }
686
687 void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
688 handleAggregate( aggregateDecl );
689 }
690
691 void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
692 // remove and delete decl stmts
693 filter( compoundStmt->kids, [](Statement * stmt) {
694 if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
695 if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
696 return true;
697 } // if
698 } // if
699 return false;
700 }, true);
701 }
702
703 void EnumAndPointerDecay_old::previsit( EnumDecl * enumDecl ) {
704 // Set the type of each member of the enumeration to be EnumConstant
705 for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
706 ObjectDecl * obj = dynamic_cast< ObjectDecl * >( * i );
707 assert( obj );
708 obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
709 } // for
710 }
711
712 namespace {
713 template< typename DWTList >
714 void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
715 auto nvals = dwts.size();
716 bool containsVoid = false;
717 for ( auto & dwt : dwts ) {
718 // fix each DWT and record whether a void was found
719 containsVoid |= fixFunction( dwt );
720 }
721
722 // the only case in which "void" is valid is where it is the only one in the list
723 if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
724 SemanticError( func, "invalid type void in function type " );
725 }
726
727 // one void is the only thing in the list; remove it.
728 if ( containsVoid ) {
729 delete dwts.front();
730 dwts.clear();
731 }
732 }
733 }
734
735 void EnumAndPointerDecay_old::previsit( FunctionType * func ) {
736 // Fix up parameters and return types
737 fixFunctionList( func->parameters, func->isVarArgs, func );
738 fixFunctionList( func->returnVals, false, func );
739 }
740
741 LinkReferenceToTypes_old::LinkReferenceToTypes_old( const Indexer * other_indexer ) : WithIndexer( false ) {
742 if ( other_indexer ) {
743 local_indexer = other_indexer;
744 } else {
745 local_indexer = &indexer;
746 } // if
747 }
748
749 void LinkReferenceToTypes_old::postvisit( EnumInstType * enumInst ) {
750 const EnumDecl * st = local_indexer->lookupEnum( enumInst->name );
751 // it's not a semantic error if the enum is not found, just an implicit forward declaration
752 if ( st ) {
753 enumInst->baseEnum = const_cast<EnumDecl *>(st); // Just linking in the node
754 } // if
755 if ( ! st || ! st->body ) {
756 // use of forward declaration
757 forwardEnums[ enumInst->name ].push_back( enumInst );
758 } // if
759 }
760
761 void LinkReferenceToTypes_old::postvisit( StructInstType * structInst ) {
762 const StructDecl * st = local_indexer->lookupStruct( structInst->name );
763 // it's not a semantic error if the struct is not found, just an implicit forward declaration
764 if ( st ) {
765 structInst->baseStruct = const_cast<StructDecl *>(st); // Just linking in the node
766 } // if
767 if ( ! st || ! st->body ) {
768 // use of forward declaration
769 forwardStructs[ structInst->name ].push_back( structInst );
770 } // if
771 }
772
773 void LinkReferenceToTypes_old::postvisit( UnionInstType * unionInst ) {
774 const UnionDecl * un = local_indexer->lookupUnion( unionInst->name );
775 // it's not a semantic error if the union is not found, just an implicit forward declaration
776 if ( un ) {
777 unionInst->baseUnion = const_cast<UnionDecl *>(un); // Just linking in the node
778 } // if
779 if ( ! un || ! un->body ) {
780 // use of forward declaration
781 forwardUnions[ unionInst->name ].push_back( unionInst );
782 } // if
783 }
784
785 void LinkReferenceToTypes_old::previsit( QualifiedType * ) {
786 visit_children = false;
787 }
788
789 void LinkReferenceToTypes_old::postvisit( QualifiedType * qualType ) {
790 // linking only makes sense for the 'oldest ancestor' of the qualified type
791 qualType->parent->accept( * visitor );
792 }
793
794 template< typename Decl >
795 void normalizeAssertions( std::list< Decl * > & assertions ) {
796 // ensure no duplicate trait members after the clone
797 auto pred = [](Decl * d1, Decl * d2) {
798 // only care if they're equal
799 DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
800 DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
801 if ( dwt1 && dwt2 ) {
802 if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
803 // std::cerr << "=========== equal:" << std::endl;
804 // std::cerr << "d1: " << d1 << std::endl;
805 // std::cerr << "d2: " << d2 << std::endl;
806 return false;
807 }
808 }
809 return d1 < d2;
810 };
811 std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
812 // if ( unique_members.size() != assertions.size() ) {
813 // std::cerr << "============different" << std::endl;
814 // std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
815 // }
816
817 std::list< Decl * > order;
818 order.splice( order.end(), assertions );
819 std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
820 return unique_members.count( decl );
821 });
822 }
823
824 // expand assertions from trait instance, performing the appropriate type variable substitutions
825 template< typename Iterator >
826 void expandAssertions( TraitInstType * inst, Iterator out ) {
827 assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
828 std::list< DeclarationWithType * > asserts;
829 for ( Declaration * decl : inst->baseTrait->members ) {
830 asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
831 }
832 // substitute trait decl parameters for instance parameters
833 applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
834 }
835
836 void LinkReferenceToTypes_old::postvisit( TraitDecl * traitDecl ) {
837 if ( traitDecl->name == "sized" ) {
838 // "sized" is a special trait - flick the sized status on for the type variable
839 assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
840 TypeDecl * td = traitDecl->parameters.front();
841 td->set_sized( true );
842 }
843
844 // move assertions from type parameters into the body of the trait
845 for ( TypeDecl * td : traitDecl->parameters ) {
846 for ( DeclarationWithType * assert : td->assertions ) {
847 if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
848 expandAssertions( inst, back_inserter( traitDecl->members ) );
849 } else {
850 traitDecl->members.push_back( assert->clone() );
851 }
852 }
853 deleteAll( td->assertions );
854 td->assertions.clear();
855 } // for
856 }
857
858 void LinkReferenceToTypes_old::postvisit( TraitInstType * traitInst ) {
859 // handle other traits
860 const TraitDecl * traitDecl = local_indexer->lookupTrait( traitInst->name );
861 if ( ! traitDecl ) {
862 SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
863 } // if
864 if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
865 SemanticError( traitInst, "incorrect number of trait parameters: " );
866 } // if
867 traitInst->baseTrait = const_cast<TraitDecl *>(traitDecl); // Just linking in the node
868
869 // need to carry over the 'sized' status of each decl in the instance
870 for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
871 TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
872 if ( ! expr ) {
873 SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
874 }
875 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
876 TypeDecl * formalDecl = std::get<0>(p);
877 TypeDecl * instDecl = inst->baseType;
878 if ( formalDecl->get_sized() ) instDecl->set_sized( true );
879 }
880 }
881 // normalizeAssertions( traitInst->members );
882 }
883
884 void LinkReferenceToTypes_old::postvisit( EnumDecl * enumDecl ) {
885 // visit enum members first so that the types of self-referencing members are updated properly
886 if ( enumDecl->body ) {
887 ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
888 if ( fwds != forwardEnums.end() ) {
889 for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
890 (* inst)->baseEnum = enumDecl;
891 } // for
892 forwardEnums.erase( fwds );
893 } // if
894 } // if
895 }
896
897 void LinkReferenceToTypes_old::renameGenericParams( std::list< TypeDecl * > & params ) {
898 // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
899 // forall(otype T)
900 // struct Box {
901 // T x;
902 // };
903 // forall(otype T)
904 // void f(Box(T) b) {
905 // ...
906 // }
907 // The T in Box and the T in f are different, so internally the naming must reflect that.
908 GuardValue( inGeneric );
909 inGeneric = ! params.empty();
910 for ( TypeDecl * td : params ) {
911 td->name = "__" + td->name + "_generic_";
912 }
913 }
914
915 void LinkReferenceToTypes_old::previsit( StructDecl * structDecl ) {
916 renameGenericParams( structDecl->parameters );
917 }
918
919 void LinkReferenceToTypes_old::previsit( UnionDecl * unionDecl ) {
920 renameGenericParams( unionDecl->parameters );
921 }
922
923 void LinkReferenceToTypes_old::postvisit( StructDecl * structDecl ) {
924 // visit struct members first so that the types of self-referencing members are updated properly
925 // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
926 if ( structDecl->body ) {
927 ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
928 if ( fwds != forwardStructs.end() ) {
929 for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
930 (* inst)->baseStruct = structDecl;
931 } // for
932 forwardStructs.erase( fwds );
933 } // if
934 } // if
935 }
936
937 void LinkReferenceToTypes_old::postvisit( UnionDecl * unionDecl ) {
938 if ( unionDecl->body ) {
939 ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
940 if ( fwds != forwardUnions.end() ) {
941 for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
942 (* inst)->baseUnion = unionDecl;
943 } // for
944 forwardUnions.erase( fwds );
945 } // if
946 } // if
947 }
948
949 void LinkReferenceToTypes_old::postvisit( TypeInstType * typeInst ) {
950 // ensure generic parameter instances are renamed like the base type
951 if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
952 if ( const NamedTypeDecl * namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
953 if ( const TypeDecl * typeDecl = dynamic_cast< const TypeDecl * >( namedTypeDecl ) ) {
954 typeInst->set_isFtype( typeDecl->kind == TypeDecl::Ftype );
955 } // if
956 } // if
957 }
958
959 ResolveEnumInitializers::ResolveEnumInitializers( const Indexer * other_indexer ) : WithIndexer( true ) {
960 if ( other_indexer ) {
961 local_indexer = other_indexer;
962 } else {
963 local_indexer = &indexer;
964 } // if
965 }
966
967 void ResolveEnumInitializers::postvisit( EnumDecl * enumDecl ) {
968 if ( enumDecl->body ) {
969 for ( Declaration * member : enumDecl->members ) {
970 ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member );
971 if ( field->init ) {
972 // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information.
973 SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init );
974 ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
975 }
976 }
977 } // if
978 }
979
980 /// Fix up assertions - flattens assertion lists, removing all trait instances
981 void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
982 for ( TypeDecl * type : forall ) {
983 std::list< DeclarationWithType * > asserts;
984 asserts.splice( asserts.end(), type->assertions );
985 // expand trait instances into their members
986 for ( DeclarationWithType * assertion : asserts ) {
987 if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
988 // expand trait instance into all of its members
989 expandAssertions( traitInst, back_inserter( type->assertions ) );
990 delete traitInst;
991 } else {
992 // pass other assertions through
993 type->assertions.push_back( assertion );
994 } // if
995 } // for
996 // apply FixFunction to every assertion to check for invalid void type
997 for ( DeclarationWithType *& assertion : type->assertions ) {
998 bool isVoid = fixFunction( assertion );
999 if ( isVoid ) {
1000 SemanticError( node, "invalid type void in assertion of function " );
1001 } // if
1002 } // for
1003 // normalizeAssertions( type->assertions );
1004 } // for
1005 }
1006
1007 /// Replace all traits in assertion lists with their assertions.
1008 void expandTraits( std::list< TypeDecl * > & forall ) {
1009 for ( TypeDecl * type : forall ) {
1010 std::list< DeclarationWithType * > asserts;
1011 asserts.splice( asserts.end(), type->assertions );
1012 // expand trait instances into their members
1013 for ( DeclarationWithType * assertion : asserts ) {
1014 if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
1015 // expand trait instance into all of its members
1016 expandAssertions( traitInst, back_inserter( type->assertions ) );
1017 delete traitInst;
1018 } else {
1019 // pass other assertions through
1020 type->assertions.push_back( assertion );
1021 } // if
1022 } // for
1023 }
1024 }
1025
1026 /// Fix each function in the assertion list and check for invalid void type.
1027 void fixAssertions(
1028 std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
1029 for ( TypeDecl * type : forall ) {
1030 for ( DeclarationWithType *& assertion : type->assertions ) {
1031 bool isVoid = fixFunction( assertion );
1032 if ( isVoid ) {
1033 SemanticError( node, "invalid type void in assertion of function " );
1034 } // if
1035 } // for
1036 }
1037 }
1038
1039 void ForallPointerDecay_old::previsit( ObjectDecl * object ) {
1040 // ensure that operator names only apply to functions or function pointers
1041 if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
1042 SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." ) );
1043 }
1044 object->fixUniqueId();
1045 }
1046
1047 void ForallPointerDecay_old::previsit( FunctionDecl * func ) {
1048 func->fixUniqueId();
1049 }
1050
1051 void ForallPointerDecay_old::previsit( FunctionType * ftype ) {
1052 forallFixer( ftype->forall, ftype );
1053 }
1054
1055 void ForallPointerDecay_old::previsit( StructDecl * aggrDecl ) {
1056 forallFixer( aggrDecl->parameters, aggrDecl );
1057 }
1058
1059 void ForallPointerDecay_old::previsit( UnionDecl * aggrDecl ) {
1060 forallFixer( aggrDecl->parameters, aggrDecl );
1061 }
1062
1063 void TraitExpander_old::previsit( FunctionType * ftype ) {
1064 expandTraits( ftype->forall );
1065 }
1066
1067 void TraitExpander_old::previsit( StructDecl * aggrDecl ) {
1068 expandTraits( aggrDecl->parameters );
1069 }
1070
1071 void TraitExpander_old::previsit( UnionDecl * aggrDecl ) {
1072 expandTraits( aggrDecl->parameters );
1073 }
1074
1075 void AssertionFixer_old::previsit( FunctionType * ftype ) {
1076 fixAssertions( ftype->forall, ftype );
1077 }
1078
1079 void AssertionFixer_old::previsit( StructDecl * aggrDecl ) {
1080 fixAssertions( aggrDecl->parameters, aggrDecl );
1081 }
1082
1083 void AssertionFixer_old::previsit( UnionDecl * aggrDecl ) {
1084 fixAssertions( aggrDecl->parameters, aggrDecl );
1085 }
1086
1087 void CheckOperatorTypes_old::previsit( ObjectDecl * object ) {
1088 // ensure that operator names only apply to functions or function pointers
1089 if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
1090 SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." ) );
1091 }
1092 }
1093
1094 void FixUniqueIds_old::previsit( DeclarationWithType * decl ) {
1095 decl->fixUniqueId();
1096 }
1097
1098 void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
1099 PassVisitor<ReturnChecker> checker;
1100 acceptAll( translationUnit, checker );
1101 }
1102
1103 void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
1104 GuardValue( returnVals );
1105 returnVals = functionDecl->get_functionType()->get_returnVals();
1106 }
1107
1108 void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
1109 // Previously this also checked for the existence of an expr paired with no return values on
1110 // the function return type. This is incorrect, since you can have an expression attached to
1111 // a return statement in a void-returning function in C. The expression is treated as if it
1112 // were cast to void.
1113 if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
1114 SemanticError( returnStmt, "Non-void function returns no values: " );
1115 }
1116 }
1117
1118
1119 void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
1120 PassVisitor<ReplaceTypedef> eliminator;
1121 mutateAll( translationUnit, eliminator );
1122 if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
1123 // grab and remember declaration of size_t
1124 Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
1125 } else {
1126 // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
1127 // eventually should have a warning for this case.
1128 Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1129 }
1130 }
1131
1132 void ReplaceTypedef::premutate( QualifiedType * ) {
1133 visit_children = false;
1134 }
1135
1136 Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
1137 // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
1138 qualType->parent = qualType->parent->acceptMutator( * visitor );
1139 return qualType;
1140 }
1141
1142 static bool isNonParameterAttribute( Attribute * attr ) {
1143 static const std::vector<std::string> bad_names = {
1144 "aligned", "__aligned__",
1145 };
1146 for ( auto name : bad_names ) {
1147 if ( name == attr->name ) {
1148 return true;
1149 }
1150 }
1151 return false;
1152 }
1153
1154 Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
1155 // instances of typedef types will come here. If it is an instance
1156 // of a typdef type, link the instance to its actual type.
1157 TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
1158 if ( def != typedefNames.end() ) {
1159 Type * ret = def->second.first->base->clone();
1160 ret->location = typeInst->location;
1161 ret->get_qualifiers() |= typeInst->get_qualifiers();
1162 // GCC ignores certain attributes if they arrive by typedef, this mimics that.
1163 if ( inFunctionType ) {
1164 ret->attributes.remove_if( isNonParameterAttribute );
1165 }
1166 ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
1167 // place instance parameters on the typedef'd type
1168 if ( ! typeInst->parameters.empty() ) {
1169 ReferenceToType * rtt = dynamic_cast<ReferenceToType *>(ret);
1170 if ( ! rtt ) {
1171 SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
1172 }
1173 rtt->parameters.clear();
1174 cloneAll( typeInst->parameters, rtt->parameters );
1175 mutateAll( rtt->parameters, * visitor ); // recursively fix typedefs on parameters
1176 } // if
1177 delete typeInst;
1178 return ret;
1179 } else {
1180 TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
1181 if ( base == typedeclNames.end() ) {
1182 SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
1183 }
1184 typeInst->set_baseType( base->second );
1185 return typeInst;
1186 } // if
1187 assert( false );
1188 }
1189
1190 struct VarLenChecker : WithShortCircuiting {
1191 void previsit( FunctionType * ) { visit_children = false; }
1192 void previsit( ArrayType * at ) {
1193 isVarLen |= at->isVarLen;
1194 }
1195 bool isVarLen = false;
1196 };
1197
1198 bool isVariableLength( Type * t ) {
1199 PassVisitor<VarLenChecker> varLenChecker;
1200 maybeAccept( t, varLenChecker );
1201 return varLenChecker.pass.isVarLen;
1202 }
1203
1204 Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
1205 if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
1206 // typedef to the same name from the same scope
1207 // must be from the same type
1208
1209 Type * t1 = tyDecl->base;
1210 Type * t2 = typedefNames[ tyDecl->name ].first->base;
1211 if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
1212 SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1213 }
1214 // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
1215 // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
1216 // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
1217 // to fix this corner case likely outweighs the utility of allowing it.
1218 if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
1219 SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1220 }
1221 } else {
1222 typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
1223 } // if
1224
1225 // When a typedef is a forward declaration:
1226 // typedef struct screen SCREEN;
1227 // the declaration portion must be retained:
1228 // struct screen;
1229 // because the expansion of the typedef is:
1230 // void rtn( SCREEN * p ) => void rtn( struct screen * p )
1231 // hence the type-name "screen" must be defined.
1232 // Note, qualifiers on the typedef are superfluous for the forward declaration.
1233
1234 Type * designatorType = tyDecl->base->stripDeclarator();
1235 if ( StructInstType * aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
1236 declsToAddBefore.push_back( new StructDecl( aggDecl->name, AggregateDecl::Struct, noAttributes, tyDecl->linkage ) );
1237 } else if ( UnionInstType * aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
1238 declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
1239 } else if ( EnumInstType * enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
1240 declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage ) );
1241 } // if
1242 return tyDecl->clone();
1243 }
1244
1245 void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
1246 TypedefMap::iterator i = typedefNames.find( typeDecl->name );
1247 if ( i != typedefNames.end() ) {
1248 typedefNames.erase( i ) ;
1249 } // if
1250
1251 typedeclNames.insert( typeDecl->name, typeDecl );
1252 }
1253
1254 void ReplaceTypedef::premutate( FunctionDecl * ) {
1255 GuardScope( typedefNames );
1256 GuardScope( typedeclNames );
1257 }
1258
1259 void ReplaceTypedef::premutate( ObjectDecl * ) {
1260 GuardScope( typedefNames );
1261 GuardScope( typedeclNames );
1262 }
1263
1264 DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
1265 if ( FunctionType * funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
1266 // replace the current object declaration with a function declaration
1267 FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
1268 objDecl->attributes.clear();
1269 objDecl->set_type( nullptr );
1270 delete objDecl;
1271 return newDecl;
1272 } // if
1273 return objDecl;
1274 }
1275
1276 void ReplaceTypedef::premutate( CastExpr * ) {
1277 GuardScope( typedefNames );
1278 GuardScope( typedeclNames );
1279 }
1280
1281 void ReplaceTypedef::premutate( CompoundStmt * ) {
1282 GuardScope( typedefNames );
1283 GuardScope( typedeclNames );
1284 scopeLevel += 1;
1285 GuardAction( [this](){ scopeLevel -= 1; } );
1286 }
1287
1288 template<typename AggDecl>
1289 void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
1290 if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
1291 Type * type = nullptr;
1292 if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
1293 type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
1294 } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
1295 type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
1296 } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) {
1297 type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
1298 } // if
1299 TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
1300 typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
1301 // add the implicit typedef to the AST
1302 declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
1303 } // if
1304 }
1305
1306 template< typename AggDecl >
1307 void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
1308 SemanticErrorException errors;
1309
1310 ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
1311 ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter );
1312 declsToAddBefore.clear();
1313 declsToAddAfter.clear();
1314
1315 GuardScope( typedefNames );
1316 GuardScope( typedeclNames );
1317 mutateAll( aggr->parameters, * visitor );
1318 mutateAll( aggr->attributes, * visitor );
1319
1320 // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
1321 for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
1322 if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
1323
1324 try {
1325 * i = maybeMutate( * i, * visitor );
1326 } catch ( SemanticErrorException &e ) {
1327 errors.append( e );
1328 }
1329
1330 if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
1331 }
1332
1333 if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
1334 if ( !errors.isEmpty() ) { throw errors; }
1335 }
1336
1337 void ReplaceTypedef::premutate( StructDecl * structDecl ) {
1338 visit_children = false;
1339 addImplicitTypedef( structDecl );
1340 handleAggregate( structDecl );
1341 }
1342
1343 void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
1344 visit_children = false;
1345 addImplicitTypedef( unionDecl );
1346 handleAggregate( unionDecl );
1347 }
1348
1349 void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
1350 addImplicitTypedef( enumDecl );
1351 }
1352
1353 void ReplaceTypedef::premutate( FunctionType * ) {
1354 GuardValue( inFunctionType );
1355 inFunctionType = true;
1356 }
1357
1358 void ReplaceTypedef::premutate( TraitDecl * ) {
1359 GuardScope( typedefNames );
1360 GuardScope( typedeclNames);
1361 }
1362
1363 void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
1364 PassVisitor<VerifyCtorDtorAssign> verifier;
1365 acceptAll( translationUnit, verifier );
1366 }
1367
1368 void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
1369 FunctionType * funcType = funcDecl->get_functionType();
1370 std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1371 std::list< DeclarationWithType * > &params = funcType->get_parameters();
1372
1373 if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
1374 if ( params.size() == 0 ) {
1375 SemanticError( funcDecl->location, "Constructors, destructors, and assignment functions require at least one parameter." );
1376 }
1377 ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
1378 if ( ! refType ) {
1379 SemanticError( funcDecl->location, "First parameter of a constructor, destructor, or assignment function must be a reference." );
1380 }
1381 if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
1382 if(!returnVals.front()->get_type()->isVoid()) {
1383 SemanticError( funcDecl->location, "Constructors and destructors cannot have explicit return values." );
1384 }
1385 }
1386 }
1387 }
1388
1389 // Test for special name on a generic parameter. Special treatment for the
1390 // special name is a bootstrapping hack. In most cases, the worlds of T's
1391 // and of N's don't overlap (normal treamtemt). The foundations in
1392 // array.hfa use tagging for both types and dimensions. Tagging treats
1393 // its subject parameter even more opaquely than T&, which assumes it is
1394 // possible to have a pointer/reference to such an object. Tagging only
1395 // seeks to identify the type-system resident at compile time. Both N's
1396 // and T's can make tags. The tag definition uses the special name, which
1397 // is treated as "an N or a T." This feature is not inteded to be used
1398 // outside of the definition and immediate uses of a tag.
1399 static inline bool isReservedTysysIdOnlyName( const std::string & name ) {
1400 // name's prefix was __CFA_tysys_id_only, before it got wrapped in __..._generic
1401 int foundAt = name.find("__CFA_tysys_id_only");
1402 if (foundAt == 0) return true;
1403 if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true;
1404 return false;
1405 }
1406
1407 template< typename Aggr >
1408 void validateGeneric( Aggr * inst ) {
1409 std::list< TypeDecl * > * params = inst->get_baseParameters();
1410 if ( params ) {
1411 std::list< Expression * > & args = inst->get_parameters();
1412
1413 // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1414 // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1415 // forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1416 // vector(int) v;
1417 // after insertion of default values becomes
1418 // vector(int, heap_allocator(T))
1419 // and the substitution is built with T=int so that after substitution, the result is
1420 // vector(int, heap_allocator(int))
1421 TypeSubstitution sub;
1422 auto paramIter = params->begin();
1423 auto argIter = args.begin();
1424 for ( ; paramIter != params->end(); ++paramIter, ++argIter ) {
1425 if ( argIter != args.end() ) {
1426 TypeExpr * expr = dynamic_cast< TypeExpr * >( * argIter );
1427 if ( expr ) {
1428 sub.add( (* paramIter)->get_name(), expr->get_type()->clone() );
1429 }
1430 } else {
1431 Type * defaultType = (* paramIter)->get_init();
1432 if ( defaultType ) {
1433 args.push_back( new TypeExpr( defaultType->clone() ) );
1434 sub.add( (* paramIter)->get_name(), defaultType->clone() );
1435 argIter = std::prev(args.end());
1436 } else {
1437 SemanticError( inst, "Too few type arguments in generic type " );
1438 }
1439 }
1440 assert( argIter != args.end() );
1441 bool typeParamDeclared = (*paramIter)->kind != TypeDecl::Kind::Dimension;
1442 bool typeArgGiven;
1443 if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) {
1444 // coerce a match when declaration is reserved name, which means "either"
1445 typeArgGiven = typeParamDeclared;
1446 } else {
1447 typeArgGiven = dynamic_cast< TypeExpr * >( * argIter );
1448 }
1449 if ( ! typeParamDeclared && typeArgGiven ) SemanticError( inst, "Type argument given for value parameter: " );
1450 if ( typeParamDeclared && ! typeArgGiven ) SemanticError( inst, "Expression argument given for type parameter: " );
1451 }
1452
1453 sub.apply( inst );
1454 if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1455 }
1456 }
1457
1458 void ValidateGenericParameters::previsit( StructInstType * inst ) {
1459 validateGeneric( inst );
1460 }
1461
1462 void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1463 validateGeneric( inst );
1464 }
1465
1466 void TranslateDimensionGenericParameters::translateDimensions( std::list< Declaration * > &translationUnit ) {
1467 PassVisitor<TranslateDimensionGenericParameters> translator;
1468 mutateAll( translationUnit, translator );
1469 }
1470
1471 TranslateDimensionGenericParameters::TranslateDimensionGenericParameters() : WithIndexer( false ) {}
1472
1473 // Declaration of type variable: forall( [N] ) -> forall( N & | sized( N ) )
1474 TypeDecl * TranslateDimensionGenericParameters::postmutate( TypeDecl * td ) {
1475 if ( td->kind == TypeDecl::Dimension ) {
1476 td->kind = TypeDecl::Dtype;
1477 if ( ! isReservedTysysIdOnlyName( td->name ) ) {
1478 td->sized = true;
1479 }
1480 }
1481 return td;
1482 }
1483
1484 // Situational awareness:
1485 // array( float, [[currentExpr]] ) has visitingChildOfSUIT == true
1486 // array( float, [[currentExpr]] - 1 ) has visitingChildOfSUIT == false
1487 // size_t x = [[currentExpr]] has visitingChildOfSUIT == false
1488 void TranslateDimensionGenericParameters::changeState_ChildOfSUIT( bool newVal ) {
1489 GuardValue( nextVisitedNodeIsChildOfSUIT );
1490 GuardValue( visitingChildOfSUIT );
1491 visitingChildOfSUIT = nextVisitedNodeIsChildOfSUIT;
1492 nextVisitedNodeIsChildOfSUIT = newVal;
1493 }
1494 void TranslateDimensionGenericParameters::premutate( StructInstType * sit ) {
1495 (void) sit;
1496 changeState_ChildOfSUIT(true);
1497 }
1498 void TranslateDimensionGenericParameters::premutate( UnionInstType * uit ) {
1499 (void) uit;
1500 changeState_ChildOfSUIT(true);
1501 }
1502 void TranslateDimensionGenericParameters::premutate( BaseSyntaxNode * node ) {
1503 (void) node;
1504 changeState_ChildOfSUIT(false);
1505 }
1506
1507 // Passing values as dimension arguments: array( float, 7 ) -> array( float, char[ 7 ] )
1508 // Consuming dimension parameters: size_t x = N - 1 ; -> size_t x = sizeof(N) - 1 ;
1509 // Intertwined reality: array( float, N ) -> array( float, N )
1510 // array( float, N - 1 ) -> array( float, char[ sizeof(N) - 1 ] )
1511 // Intertwined case 1 is not just an optimization.
1512 // Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
1513 // forall([N]) void f( array(float, N) & );
1514 // array(float, 7) a;
1515 // f(a);
1516
1517 Expression * TranslateDimensionGenericParameters::postmutate( DimensionExpr * de ) {
1518 // Expression de is an occurrence of N in LHS of above examples.
1519 // Look up the name that de references.
1520 // If we are in a struct body, then this reference can be to an entry of the stuct's forall list.
1521 // Whether or not we are in a struct body, this reference can be to an entry of a containing function's forall list.
1522 // If we are in a struct body, then the stuct's forall declarations are innermost (functions don't occur in structs).
1523 // Thus, a potential struct's declaration is highest priority.
1524 // A struct's forall declarations are already renamed with _generic_ suffix. Try that name variant first.
1525
1526 std::string useName = "__" + de->name + "_generic_";
1527 TypeDecl * namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1528
1529 if ( ! namedParamDecl ) {
1530 useName = de->name;
1531 namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1532 }
1533
1534 // Expect to find it always. A misspelled name would have been parsed as an identifier.
1535 assert( namedParamDecl && "Type-system-managed value name not found in symbol table" );
1536
1537 delete de;
1538
1539 TypeInstType * refToDecl = new TypeInstType( 0, useName, namedParamDecl );
1540
1541 if ( visitingChildOfSUIT ) {
1542 // As in postmutate( Expression * ), topmost expression needs a TypeExpr wrapper
1543 // But avoid ArrayType-Sizeof
1544 return new TypeExpr( refToDecl );
1545 } else {
1546 // the N occurrence is being used directly as a runtime value,
1547 // if we are in a type instantiation, then the N is within a bigger value computation
1548 return new SizeofExpr( refToDecl );
1549 }
1550 }
1551
1552 Expression * TranslateDimensionGenericParameters::postmutate( Expression * e ) {
1553 if ( visitingChildOfSUIT ) {
1554 // e is an expression used as an argument to instantiate a type
1555 if (! dynamic_cast< TypeExpr * >( e ) ) {
1556 // e is a value expression
1557 // but not a DimensionExpr, which has a distinct postmutate
1558 Type * typeExprContent = new ArrayType( 0, new BasicType( 0, BasicType::Char ), e, true, false );
1559 TypeExpr * result = new TypeExpr( typeExprContent );
1560 return result;
1561 }
1562 }
1563 return e;
1564 }
1565
1566 void CompoundLiteral::premutate( ObjectDecl * objectDecl ) {
1567 storageClasses = objectDecl->get_storageClasses();
1568 }
1569
1570 Expression * CompoundLiteral::postmutate( CompoundLiteralExpr * compLitExpr ) {
1571 // transform [storage_class] ... (struct S){ 3, ... };
1572 // into [storage_class] struct S temp = { 3, ... };
1573 static UniqueName indexName( "_compLit" );
1574
1575 ObjectDecl * tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1576 compLitExpr->set_result( nullptr );
1577 compLitExpr->set_initializer( nullptr );
1578 delete compLitExpr;
1579 declsToAddBefore.push_back( tempvar ); // add modified temporary to current block
1580 return new VariableExpr( tempvar );
1581 }
1582
1583 void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1584 PassVisitor<ReturnTypeFixer> fixer;
1585 acceptAll( translationUnit, fixer );
1586 }
1587
1588 void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1589 FunctionType * ftype = functionDecl->get_functionType();
1590 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1591 assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1592 if ( retVals.size() == 1 ) {
1593 // 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).
1594 // ensure other return values have a name.
1595 DeclarationWithType * ret = retVals.front();
1596 if ( ret->get_name() == "" ) {
1597 ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1598 }
1599 ret->get_attributes().push_back( new Attribute( "unused" ) );
1600 }
1601 }
1602
1603 void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1604 // xxx - need to handle named return values - this information needs to be saved somehow
1605 // so that resolution has access to the names.
1606 // Note that this pass needs to happen early so that other passes which look for tuple types
1607 // find them in all of the right places, including function return types.
1608 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1609 if ( retVals.size() > 1 ) {
1610 // generate a single return parameter which is the tuple of all of the return values
1611 TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1612 // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1613 ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer *>(), noDesignators, false ) );
1614 deleteAll( retVals );
1615 retVals.clear();
1616 retVals.push_back( newRet );
1617 }
1618 }
1619
1620 void FixObjectType::fix( std::list< Declaration * > & translationUnit ) {
1621 PassVisitor<FixObjectType> fixer;
1622 acceptAll( translationUnit, fixer );
1623 }
1624
1625 void FixObjectType::previsit( ObjectDecl * objDecl ) {
1626 Type * new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer );
1627 objDecl->set_type( new_type );
1628 }
1629
1630 void FixObjectType::previsit( FunctionDecl * funcDecl ) {
1631 Type * new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer );
1632 funcDecl->set_type( new_type );
1633 }
1634
1635 void FixObjectType::previsit( TypeDecl * typeDecl ) {
1636 if ( typeDecl->get_base() ) {
1637 Type * new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer );
1638 typeDecl->set_base( new_type );
1639 } // if
1640 }
1641
1642 void InitializerLength::computeLength( std::list< Declaration * > & translationUnit ) {
1643 PassVisitor<InitializerLength> len;
1644 acceptAll( translationUnit, len );
1645 }
1646
1647 void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1648 PassVisitor<ArrayLength> len;
1649 acceptAll( translationUnit, len );
1650 }
1651
1652 void InitializerLength::previsit( ObjectDecl * objDecl ) {
1653 if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1654 if ( at->dimension ) return;
1655 if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1656 at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
1657 }
1658 }
1659 }
1660
1661 void ArrayLength::previsit( ArrayType * type ) {
1662 if ( type->dimension ) {
1663 // need to resolve array dimensions early so that constructor code can correctly determine
1664 // if a type is a VLA (and hence whether its elements need to be constructed)
1665 ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
1666
1667 // must re-evaluate whether a type is a VLA, now that more information is available
1668 // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1669 type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
1670 }
1671 }
1672
1673 struct LabelFinder {
1674 std::set< Label > & labels;
1675 LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1676 void previsit( Statement * stmt ) {
1677 for ( Label & l : stmt->labels ) {
1678 labels.insert( l );
1679 }
1680 }
1681 };
1682
1683 void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1684 GuardValue( labels );
1685 PassVisitor<LabelFinder> finder( labels );
1686 funcDecl->accept( finder );
1687 }
1688
1689 Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1690 // convert &&label into label address
1691 if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1692 if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1693 if ( labels.count( nameExpr->name ) ) {
1694 Label name = nameExpr->name;
1695 delete addrExpr;
1696 return new LabelAddressExpr( name );
1697 }
1698 }
1699 }
1700 return addrExpr;
1701 }
1702
1703namespace {
1704 /// Replaces enum types by int, and function/array types in function parameter and return
1705 /// lists by appropriate pointers
1706 /*
1707 struct EnumAndPointerDecay_new {
1708 const ast::EnumDecl * previsit( const ast::EnumDecl * enumDecl ) {
1709 // set the type of each member of the enumeration to be EnumConstant
1710 for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1711 // build new version of object with EnumConstant
1712 ast::ptr< ast::ObjectDecl > obj =
1713 enumDecl->members[i].strict_as< ast::ObjectDecl >();
1714 obj.get_and_mutate()->type =
1715 new ast::EnumInstType{ enumDecl->name, ast::CV::Const };
1716
1717 // set into decl
1718 ast::EnumDecl * mut = mutate( enumDecl );
1719 mut->members[i] = obj.get();
1720 enumDecl = mut;
1721 }
1722 return enumDecl;
1723 }
1724
1725 static const ast::FunctionType * fixFunctionList(
1726 const ast::FunctionType * func,
1727 std::vector< ast::ptr< ast::DeclWithType > > ast::FunctionType::* field,
1728 ast::ArgumentFlag isVarArgs = ast::FixedArgs
1729 ) {
1730 const auto & dwts = func->* field;
1731 unsigned nvals = dwts.size();
1732 bool hasVoid = false;
1733 for ( unsigned i = 0; i < nvals; ++i ) {
1734 func = ast::mutate_field_index( func, field, i, fixFunction( dwts[i], hasVoid ) );
1735 }
1736
1737 // the only case in which "void" is valid is where it is the only one in the list
1738 if ( hasVoid && ( nvals > 1 || isVarArgs ) ) {
1739 SemanticError(
1740 dwts.front()->location, func, "invalid type void in function type" );
1741 }
1742
1743 // one void is the only thing in the list, remove it
1744 if ( hasVoid ) {
1745 func = ast::mutate_field(
1746 func, field, std::vector< ast::ptr< ast::DeclWithType > >{} );
1747 }
1748
1749 return func;
1750 }
1751
1752 const ast::FunctionType * previsit( const ast::FunctionType * func ) {
1753 func = fixFunctionList( func, &ast::FunctionType::params, func->isVarArgs );
1754 return fixFunctionList( func, &ast::FunctionType::returns );
1755 }
1756 };
1757
1758 /// expand assertions from a trait instance, performing appropriate type variable substitutions
1759 void expandAssertions(
1760 const ast::TraitInstType * inst, std::vector< ast::ptr< ast::DeclWithType > > & out
1761 ) {
1762 assertf( inst->base, "Trait instance not linked to base trait: %s", toCString( inst ) );
1763
1764 // build list of trait members, substituting trait decl parameters for instance parameters
1765 ast::TypeSubstitution sub{
1766 inst->base->params.begin(), inst->base->params.end(), inst->params.begin() };
1767 // deliberately take ast::ptr by-value to ensure this does not mutate inst->base
1768 for ( ast::ptr< ast::Decl > decl : inst->base->members ) {
1769 auto member = decl.strict_as< ast::DeclWithType >();
1770 sub.apply( member );
1771 out.emplace_back( member );
1772 }
1773 }
1774
1775 /// Associates forward declarations of aggregates with their definitions
1776 class LinkReferenceToTypes_new final
1777 : public ast::WithSymbolTable, public ast::WithGuards, public
1778 ast::WithVisitorRef<LinkReferenceToTypes_new>, public ast::WithShortCircuiting {
1779
1780 // these maps of uses of forward declarations of types need to have the actual type
1781 // declaration switched in * after * they have been traversed. To enable this in the
1782 // ast::Pass framework, any node that needs to be so mutated has mutate() called on it
1783 // before it is placed in the map, properly updating its parents in the usual traversal,
1784 // then can have the actual mutation applied later
1785 using ForwardEnumsType = std::unordered_multimap< std::string, ast::EnumInstType * >;
1786 using ForwardStructsType = std::unordered_multimap< std::string, ast::StructInstType * >;
1787 using ForwardUnionsType = std::unordered_multimap< std::string, ast::UnionInstType * >;
1788
1789 const CodeLocation & location;
1790 const ast::SymbolTable * localSymtab;
1791
1792 ForwardEnumsType forwardEnums;
1793 ForwardStructsType forwardStructs;
1794 ForwardUnionsType forwardUnions;
1795
1796 /// true if currently in a generic type body, so that type parameter instances can be
1797 /// renamed appropriately
1798 bool inGeneric = false;
1799
1800 public:
1801 /// contstruct using running symbol table
1802 LinkReferenceToTypes_new( const CodeLocation & loc )
1803 : location( loc ), localSymtab( &symtab ) {}
1804
1805 /// construct using provided symbol table
1806 LinkReferenceToTypes_new( const CodeLocation & loc, const ast::SymbolTable & syms )
1807 : location( loc ), localSymtab( &syms ) {}
1808
1809 const ast::Type * postvisit( const ast::TypeInstType * typeInst ) {
1810 // ensure generic parameter instances are renamed like the base type
1811 if ( inGeneric && typeInst->base ) {
1812 typeInst = ast::mutate_field(
1813 typeInst, &ast::TypeInstType::name, typeInst->base->name );
1814 }
1815
1816 if (
1817 auto typeDecl = dynamic_cast< const ast::TypeDecl * >(
1818 localSymtab->lookupType( typeInst->name ) )
1819 ) {
1820 typeInst = ast::mutate_field( typeInst, &ast::TypeInstType::kind, typeDecl->kind );
1821 }
1822
1823 return typeInst;
1824 }
1825
1826 const ast::Type * postvisit( const ast::EnumInstType * inst ) {
1827 const ast::EnumDecl * decl = localSymtab->lookupEnum( inst->name );
1828 // not a semantic error if the enum is not found, just an implicit forward declaration
1829 if ( decl ) {
1830 inst = ast::mutate_field( inst, &ast::EnumInstType::base, decl );
1831 }
1832 if ( ! decl || ! decl->body ) {
1833 // forward declaration
1834 auto mut = mutate( inst );
1835 forwardEnums.emplace( inst->name, mut );
1836 inst = mut;
1837 }
1838 return inst;
1839 }
1840
1841 void checkGenericParameters( const ast::BaseInstType * inst ) {
1842 for ( const ast::Expr * param : inst->params ) {
1843 if ( ! dynamic_cast< const ast::TypeExpr * >( param ) ) {
1844 SemanticError(
1845 location, inst, "Expression parameters for generic types are currently "
1846 "unsupported: " );
1847 }
1848 }
1849 }
1850
1851 const ast::StructInstType * postvisit( const ast::StructInstType * inst ) {
1852 const ast::StructDecl * decl = localSymtab->lookupStruct( inst->name );
1853 // not a semantic error if the struct is not found, just an implicit forward declaration
1854 if ( decl ) {
1855 inst = ast::mutate_field( inst, &ast::StructInstType::base, decl );
1856 }
1857 if ( ! decl || ! decl->body ) {
1858 // forward declaration
1859 auto mut = mutate( inst );
1860 forwardStructs.emplace( inst->name, mut );
1861 inst = mut;
1862 }
1863 checkGenericParameters( inst );
1864 return inst;
1865 }
1866
1867 const ast::UnionInstType * postvisit( const ast::UnionInstType * inst ) {
1868 const ast::UnionDecl * decl = localSymtab->lookupUnion( inst->name );
1869 // not a semantic error if the struct is not found, just an implicit forward declaration
1870 if ( decl ) {
1871 inst = ast::mutate_field( inst, &ast::UnionInstType::base, decl );
1872 }
1873 if ( ! decl || ! decl->body ) {
1874 // forward declaration
1875 auto mut = mutate( inst );
1876 forwardUnions.emplace( inst->name, mut );
1877 inst = mut;
1878 }
1879 checkGenericParameters( inst );
1880 return inst;
1881 }
1882
1883 const ast::Type * postvisit( const ast::TraitInstType * traitInst ) {
1884 // handle other traits
1885 const ast::TraitDecl * traitDecl = localSymtab->lookupTrait( traitInst->name );
1886 if ( ! traitDecl ) {
1887 SemanticError( location, "use of undeclared trait " + traitInst->name );
1888 }
1889 if ( traitDecl->params.size() != traitInst->params.size() ) {
1890 SemanticError( location, traitInst, "incorrect number of trait parameters: " );
1891 }
1892 traitInst = ast::mutate_field( traitInst, &ast::TraitInstType::base, traitDecl );
1893
1894 // need to carry over the "sized" status of each decl in the instance
1895 for ( unsigned i = 0; i < traitDecl->params.size(); ++i ) {
1896 auto expr = traitInst->params[i].as< ast::TypeExpr >();
1897 if ( ! expr ) {
1898 SemanticError(
1899 traitInst->params[i].get(), "Expression parameters for trait instances "
1900 "are currently unsupported: " );
1901 }
1902
1903 if ( auto inst = expr->type.as< ast::TypeInstType >() ) {
1904 if ( traitDecl->params[i]->sized && ! inst->base->sized ) {
1905 // traitInst = ast::mutate_field_index(
1906 // traitInst, &ast::TraitInstType::params, i,
1907 // ...
1908 // );
1909 ast::TraitInstType * mut = ast::mutate( traitInst );
1910 ast::chain_mutate( mut->params[i] )
1911 ( &ast::TypeExpr::type )
1912 ( &ast::TypeInstType::base )->sized = true;
1913 traitInst = mut;
1914 }
1915 }
1916 }
1917
1918 return traitInst;
1919 }
1920
1921 void previsit( const ast::QualifiedType * ) { visit_children = false; }
1922
1923 const ast::Type * postvisit( const ast::QualifiedType * qualType ) {
1924 // linking only makes sense for the "oldest ancestor" of the qualified type
1925 return ast::mutate_field(
1926 qualType, &ast::QualifiedType::parent, qualType->parent->accept( * visitor ) );
1927 }
1928
1929 const ast::Decl * postvisit( const ast::EnumDecl * enumDecl ) {
1930 // visit enum members first so that the types of self-referencing members are updated
1931 // properly
1932 if ( ! enumDecl->body ) return enumDecl;
1933
1934 // update forward declarations to point here
1935 auto fwds = forwardEnums.equal_range( enumDecl->name );
1936 if ( fwds.first != fwds.second ) {
1937 auto inst = fwds.first;
1938 do {
1939 // forward decl is stored * mutably * in map, can thus be updated
1940 inst->second->base = enumDecl;
1941 } while ( ++inst != fwds.second );
1942 forwardEnums.erase( fwds.first, fwds.second );
1943 }
1944
1945 // ensure that enumerator initializers are properly set
1946 for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1947 auto field = enumDecl->members[i].strict_as< ast::ObjectDecl >();
1948 if ( field->init ) {
1949 // need to resolve enumerator initializers early so that other passes that
1950 // determine if an expression is constexpr have appropriate information
1951 auto init = field->init.strict_as< ast::SingleInit >();
1952
1953 enumDecl = ast::mutate_field_index(
1954 enumDecl, &ast::EnumDecl::members, i,
1955 ast::mutate_field( field, &ast::ObjectDecl::init,
1956 ast::mutate_field( init, &ast::SingleInit::value,
1957 ResolvExpr::findSingleExpression(
1958 init->value, new ast::BasicType{ ast::BasicType::SignedInt },
1959 symtab ) ) ) );
1960 }
1961 }
1962
1963 return enumDecl;
1964 }
1965
1966 /// rename generic type parameters uniquely so that they do not conflict with user defined
1967 /// function forall parameters, e.g. the T in Box and the T in f, below
1968 /// forall(otype T)
1969 /// struct Box {
1970 /// T x;
1971 /// };
1972 /// forall(otype T)
1973 /// void f(Box(T) b) {
1974 /// ...
1975 /// }
1976 template< typename AggrDecl >
1977 const AggrDecl * renameGenericParams( const AggrDecl * aggr ) {
1978 GuardValue( inGeneric );
1979 inGeneric = ! aggr->params.empty();
1980
1981 for ( unsigned i = 0; i < aggr->params.size(); ++i ) {
1982 const ast::TypeDecl * td = aggr->params[i];
1983
1984 aggr = ast::mutate_field_index(
1985 aggr, &AggrDecl::params, i,
1986 ast::mutate_field( td, &ast::TypeDecl::name, "__" + td->name + "_generic_" ) );
1987 }
1988 return aggr;
1989 }
1990
1991 const ast::StructDecl * previsit( const ast::StructDecl * structDecl ) {
1992 return renameGenericParams( structDecl );
1993 }
1994
1995 void postvisit( const ast::StructDecl * structDecl ) {
1996 // visit struct members first so that the types of self-referencing members are
1997 // updated properly
1998 if ( ! structDecl->body ) return;
1999
2000 // update forward declarations to point here
2001 auto fwds = forwardStructs.equal_range( structDecl->name );
2002 if ( fwds.first != fwds.second ) {
2003 auto inst = fwds.first;
2004 do {
2005 // forward decl is stored * mutably * in map, can thus be updated
2006 inst->second->base = structDecl;
2007 } while ( ++inst != fwds.second );
2008 forwardStructs.erase( fwds.first, fwds.second );
2009 }
2010 }
2011
2012 const ast::UnionDecl * previsit( const ast::UnionDecl * unionDecl ) {
2013 return renameGenericParams( unionDecl );
2014 }
2015
2016 void postvisit( const ast::UnionDecl * unionDecl ) {
2017 // visit union members first so that the types of self-referencing members are updated
2018 // properly
2019 if ( ! unionDecl->body ) return;
2020
2021 // update forward declarations to point here
2022 auto fwds = forwardUnions.equal_range( unionDecl->name );
2023 if ( fwds.first != fwds.second ) {
2024 auto inst = fwds.first;
2025 do {
2026 // forward decl is stored * mutably * in map, can thus be updated
2027 inst->second->base = unionDecl;
2028 } while ( ++inst != fwds.second );
2029 forwardUnions.erase( fwds.first, fwds.second );
2030 }
2031 }
2032
2033 const ast::Decl * postvisit( const ast::TraitDecl * traitDecl ) {
2034 // set the "sized" status for the special "sized" trait
2035 if ( traitDecl->name == "sized" ) {
2036 assertf( traitDecl->params.size() == 1, "Built-in trait 'sized' has incorrect "
2037 "number of parameters: %zd", traitDecl->params.size() );
2038
2039 traitDecl = ast::mutate_field_index(
2040 traitDecl, &ast::TraitDecl::params, 0,
2041 ast::mutate_field(
2042 traitDecl->params.front().get(), &ast::TypeDecl::sized, true ) );
2043 }
2044
2045 // move assertions from type parameters into the body of the trait
2046 std::vector< ast::ptr< ast::DeclWithType > > added;
2047 for ( const ast::TypeDecl * td : traitDecl->params ) {
2048 for ( const ast::DeclWithType * assn : td->assertions ) {
2049 auto inst = dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
2050 if ( inst ) {
2051 expandAssertions( inst, added );
2052 } else {
2053 added.emplace_back( assn );
2054 }
2055 }
2056 }
2057 if ( ! added.empty() ) {
2058 auto mut = mutate( traitDecl );
2059 for ( const ast::DeclWithType * decl : added ) {
2060 mut->members.emplace_back( decl );
2061 }
2062 traitDecl = mut;
2063 }
2064
2065 return traitDecl;
2066 }
2067 };
2068
2069 /// Replaces array and function types in forall lists by appropriate pointer type and assigns
2070 /// each object and function declaration a unique ID
2071 class ForallPointerDecay_new {
2072 const CodeLocation & location;
2073 public:
2074 ForallPointerDecay_new( const CodeLocation & loc ) : location( loc ) {}
2075
2076 const ast::ObjectDecl * previsit( const ast::ObjectDecl * obj ) {
2077 // ensure that operator names only apply to functions or function pointers
2078 if (
2079 CodeGen::isOperator( obj->name )
2080 && ! dynamic_cast< const ast::FunctionType * >( obj->type->stripDeclarator() )
2081 ) {
2082 SemanticError( obj->location, toCString( "operator ", obj->name.c_str(), " is not "
2083 "a function or function pointer." ) );
2084 }
2085
2086 // ensure object has unique ID
2087 if ( obj->uniqueId ) return obj;
2088 auto mut = mutate( obj );
2089 mut->fixUniqueId();
2090 return mut;
2091 }
2092
2093 const ast::FunctionDecl * previsit( const ast::FunctionDecl * func ) {
2094 // ensure function has unique ID
2095 if ( func->uniqueId ) return func;
2096 auto mut = mutate( func );
2097 mut->fixUniqueId();
2098 return mut;
2099 }
2100
2101 /// Fix up assertions -- flattens assertion lists, removing all trait instances
2102 template< typename node_t, typename parent_t >
2103 static const node_t * forallFixer(
2104 const CodeLocation & loc, const node_t * node,
2105 ast::FunctionType::ForallList parent_t::* forallField
2106 ) {
2107 for ( unsigned i = 0; i < (node->* forallField).size(); ++i ) {
2108 const ast::TypeDecl * type = (node->* forallField)[i];
2109 if ( type->assertions.empty() ) continue;
2110
2111 std::vector< ast::ptr< ast::DeclWithType > > asserts;
2112 asserts.reserve( type->assertions.size() );
2113
2114 // expand trait instances into their members
2115 for ( const ast::DeclWithType * assn : type->assertions ) {
2116 auto traitInst =
2117 dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
2118 if ( traitInst ) {
2119 // expand trait instance to all its members
2120 expandAssertions( traitInst, asserts );
2121 } else {
2122 // pass other assertions through
2123 asserts.emplace_back( assn );
2124 }
2125 }
2126
2127 // apply FixFunction to every assertion to check for invalid void type
2128 for ( ast::ptr< ast::DeclWithType > & assn : asserts ) {
2129 bool isVoid = false;
2130 assn = fixFunction( assn, isVoid );
2131 if ( isVoid ) {
2132 SemanticError( loc, node, "invalid type void in assertion of function " );
2133 }
2134 }
2135
2136 // place mutated assertion list in node
2137 auto mut = mutate( type );
2138 mut->assertions = move( asserts );
2139 node = ast::mutate_field_index( node, forallField, i, mut );
2140 }
2141 return node;
2142 }
2143
2144 const ast::FunctionType * previsit( const ast::FunctionType * ftype ) {
2145 return forallFixer( location, ftype, &ast::FunctionType::forall );
2146 }
2147
2148 const ast::StructDecl * previsit( const ast::StructDecl * aggrDecl ) {
2149 return forallFixer( aggrDecl->location, aggrDecl, &ast::StructDecl::params );
2150 }
2151
2152 const ast::UnionDecl * previsit( const ast::UnionDecl * aggrDecl ) {
2153 return forallFixer( aggrDecl->location, aggrDecl, &ast::UnionDecl::params );
2154 }
2155 };
2156 */
2157} // anonymous namespace
2158
2159/*
2160const ast::Type * validateType(
2161 const CodeLocation & loc, const ast::Type * type, const ast::SymbolTable & symtab ) {
2162 // ast::Pass< EnumAndPointerDecay_new > epc;
2163 ast::Pass< LinkReferenceToTypes_new > lrt{ loc, symtab };
2164 ast::Pass< ForallPointerDecay_new > fpd{ loc };
2165
2166 return type->accept( lrt )->accept( fpd );
2167}
2168*/
2169
2170} // namespace SymTab
2171
2172// Local Variables: //
2173// tab-width: 4 //
2174// mode: c++ //
2175// compile-command: "make install" //
2176// End: //
Note: See TracBrowser for help on using the repository browser.