source: src/SymTab/Validate.cc@ 2f42718

no_list
Last change on this file since 2f42718 was 2f42718, checked in by tdelisle <tdelisle@…>, 7 years ago

Parameters and return value of functions are now vectors (and some related clean-up)

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