source: src/SymTab/Validate.cc@ eff03a94

new-env
Last change on this file since eff03a94 was 28f3a19, checked in by Aaron Moss <a3moss@…>, 7 years ago

Merge branch 'master' into with_gc

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