source: src/SymTab/Validate.cc@ f52ce6e

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since f52ce6e was c8e4d2f8, checked in by Aaron Moss <a3moss@…>, 6 years ago

Start porting CastExpr resolution

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