source: src/SymTab/Validate.cc@ b8b6c442

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

Refactor FindSpecialDeclarations and associated special declarations

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