source: src/SymTab/Validate.cc@ c3acf0aa

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new stuck-waitfor-destruct with_gc
Last change on this file since c3acf0aa was c3acf0aa, checked in by Thierry Delisle <tdelisle@…>, 9 years ago

More header cleaning

  • Property mode set to 100644
File size: 38.1 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Validate.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Sun May 17 21:50:04 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Tus Aug 8 13:27:00 2017
13// Update Count : 358
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 <algorithm> // for move, transform
43#include <cassert> // for safe_dynamic_cast, assertf
44#include <cstddef> // for size_t
45#include <iterator> // for back_inserter, inserter, back_...
46#include <list> // for list, _List_iterator, list<>::...
47#include <map> // for _Rb_tree_iterator, map, map<>:...
48#include <memory> // for unique_ptr, allocator
49#include <string> // for string, operator+, operator==
50#include <tuple> // for get
51#include <type_traits> // for remove_reference<>::type
52#include <utility> // for pair, make_pair
53
54#include "AddVisit.h" // for addVisit
55#include "Autogen.h" // for SizeType, autogenerateRoutines
56#include "CodeGen/CodeGenerator.h" // for genName
57#include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd
58#include "Common/ScopedMap.h" // for ScopedMap<>::const_iterator
59#include "Common/SemanticError.h" // for SemanticError
60#include "Common/UniqueName.h" // for UniqueName
61#include "Common/utility.h" // for operator+, cloneAll, deleteAll
62#include "Concurrency/Keywords.h" // for applyKeywords, implementMutexF...
63#include "FixFunction.h" // for FixFunction
64#include "Indexer.h" // for Indexer
65#include "InitTweak/InitTweak.h" // for isCtorDtor, isCtorDtorAssign
66#include "Parser/LinkageSpec.h" // for C, Cforall
67#include "Parser/ParseNode.h" // for DeclarationNode, DeclarationNo...
68#include "PassVisitor.h" // for acceptAll, mutateAll
69#include "ResolvExpr/typeops.h" // for extractResultType, typesCompat...
70#include "SynTree/Attribute.h" // for noAttributes, Attribute
71#include "SynTree/Constant.h" // for Constant
72#include "SynTree/Declaration.h" // for EnumDecl, StructDecl, TypedefDecl
73#include "SynTree/Expression.h" // for TypeExpr, CompoundLiteralExpr
74#include "SynTree/Initializer.h" // for ListInit, Initializer, noDesig...
75#include "SynTree/Mutator.h" // for mutateAll, Mutator
76#include "SynTree/Statement.h" // for CompoundStmt, DeclStmt, Return...
77#include "SynTree/Type.h" // for Type, TypeInstType, TraitInstType
78#include "SynTree/TypeSubstitution.h" // for TypeSubstitution, applySubstit...
79#include "SynTree/Visitor.h" // for acceptAll, Visitor
80
81#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
82
83namespace SymTab {
84 class HoistStruct final : public Visitor {
85 template< typename Visitor >
86 friend void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor );
87 template< typename Visitor >
88 friend void addVisitStatementList( std::list< Statement* > &stmts, Visitor &visitor );
89 public:
90 /// Flattens nested struct types
91 static void hoistStruct( std::list< Declaration * > &translationUnit );
92
93 std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
94
95 virtual void visit( EnumInstType *enumInstType );
96 virtual void visit( StructInstType *structInstType );
97 virtual void visit( UnionInstType *unionInstType );
98 virtual void visit( StructDecl *aggregateDecl );
99 virtual void visit( UnionDecl *aggregateDecl );
100
101 virtual void visit( CompoundStmt *compoundStmt );
102 virtual void visit( SwitchStmt *switchStmt );
103 private:
104 HoistStruct();
105
106 template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
107
108 std::list< Declaration * > declsToAdd, declsToAddAfter;
109 bool inStruct;
110 };
111
112 /// Fix return types so that every function returns exactly one value
113 struct ReturnTypeFixer {
114 static void fix( std::list< Declaration * > &translationUnit );
115
116 void postvisit( FunctionDecl * functionDecl );
117 void postvisit( FunctionType * ftype );
118 };
119
120 /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
121 struct EnumAndPointerDecay {
122 void previsit( EnumDecl *aggregateDecl );
123 void previsit( FunctionType *func );
124 };
125
126 /// Associates forward declarations of aggregates with their definitions
127 class LinkReferenceToTypes final : public Indexer {
128 typedef Indexer Parent;
129 public:
130 LinkReferenceToTypes( bool doDebug, const Indexer *indexer );
131 using Parent::visit;
132 void visit( EnumInstType *enumInst ) final;
133 void visit( StructInstType *structInst ) final;
134 void visit( UnionInstType *unionInst ) final;
135 void visit( TraitInstType *contextInst ) final;
136 void visit( EnumDecl *enumDecl ) final;
137 void visit( StructDecl *structDecl ) final;
138 void visit( UnionDecl *unionDecl ) final;
139 void visit( TypeInstType *typeInst ) final;
140 private:
141 const Indexer *indexer;
142
143 typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
144 typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
145 typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
146 ForwardEnumsType forwardEnums;
147 ForwardStructsType forwardStructs;
148 ForwardUnionsType forwardUnions;
149 };
150
151 /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
152 class ForallPointerDecay final : public Indexer {
153 typedef Indexer Parent;
154 public:
155 using Parent::visit;
156 ForallPointerDecay( const Indexer *indexer );
157
158 virtual void visit( ObjectDecl *object ) override;
159 virtual void visit( FunctionDecl *func ) override;
160
161 const Indexer *indexer;
162 };
163
164 struct ReturnChecker : public WithGuards {
165 /// Checks that return statements return nothing if their return type is void
166 /// and return something if the return type is non-void.
167 static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
168
169 void previsit( FunctionDecl * functionDecl );
170 void previsit( ReturnStmt * returnStmt );
171
172 typedef std::list< DeclarationWithType * > ReturnVals;
173 ReturnVals returnVals;
174 };
175
176 class EliminateTypedef : public Mutator {
177 public:
178 EliminateTypedef() : scopeLevel( 0 ) {}
179 /// Replaces typedefs by forward declarations
180 static void eliminateTypedef( std::list< Declaration * > &translationUnit );
181 private:
182 virtual Declaration *mutate( TypedefDecl *typeDecl );
183 virtual TypeDecl *mutate( TypeDecl *typeDecl );
184 virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
185 virtual DeclarationWithType *mutate( ObjectDecl *objDecl );
186 virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
187 virtual Type *mutate( TypeInstType *aggregateUseType );
188 virtual Expression *mutate( CastExpr *castExpr );
189
190 virtual Declaration *mutate( StructDecl * structDecl );
191 virtual Declaration *mutate( UnionDecl * unionDecl );
192 virtual Declaration *mutate( EnumDecl * enumDecl );
193 virtual Declaration *mutate( TraitDecl * contextDecl );
194
195 template<typename AggDecl>
196 AggDecl *handleAggregate( AggDecl * aggDecl );
197
198 template<typename AggDecl>
199 void addImplicitTypedef( AggDecl * aggDecl );
200
201 typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
202 typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
203 typedef std::map< std::string, TypeDecl * > TypeDeclMap;
204 TypedefMap typedefNames;
205 TypeDeclMap typedeclNames;
206 int scopeLevel;
207 };
208
209 struct VerifyCtorDtorAssign {
210 /// ensure that constructors, destructors, and assignment have at least one
211 /// parameter, the first of which must be a pointer, and that ctor/dtors have no
212 /// return values.
213 static void verify( std::list< Declaration * > &translationUnit );
214
215 void previsit( FunctionDecl *funcDecl );
216 };
217
218 /// ensure that generic types have the correct number of type arguments
219 struct ValidateGenericParameters {
220 void previsit( StructInstType * inst );
221 void previsit( UnionInstType * inst );
222 };
223
224 struct ArrayLength {
225 /// for array types without an explicit length, compute the length and store it so that it
226 /// is known to the rest of the phases. For example,
227 /// int x[] = { 1, 2, 3 };
228 /// int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
229 /// here x and y are known at compile-time to have length 3, so change this into
230 /// int x[3] = { 1, 2, 3 };
231 /// int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
232 static void computeLength( std::list< Declaration * > & translationUnit );
233
234 void previsit( ObjectDecl * objDecl );
235 };
236
237 struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
238 Type::StorageClasses storageClasses;
239
240 void premutate( ObjectDecl *objectDecl );
241 Expression * postmutate( CompoundLiteralExpr *compLitExpr );
242 };
243
244 void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
245 PassVisitor<EnumAndPointerDecay> epc;
246 LinkReferenceToTypes lrt( doDebug, 0 );
247 ForallPointerDecay fpd( 0 );
248 PassVisitor<CompoundLiteral> compoundliteral;
249 PassVisitor<ValidateGenericParameters> genericParams;
250
251 EliminateTypedef::eliminateTypedef( translationUnit );
252 HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
253 ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
254 acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
255 acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes
256 acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist
257 VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors
258 Concurrency::applyKeywords( translationUnit );
259 autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
260 Concurrency::implementMutexFuncs( translationUnit );
261 Concurrency::implementThreadStarter( translationUnit );
262 ReturnChecker::checkFunctionReturns( translationUnit );
263 mutateAll( translationUnit, compoundliteral );
264 acceptAll( translationUnit, fpd );
265 ArrayLength::computeLength( translationUnit );
266 }
267
268 void validateType( Type *type, const Indexer *indexer ) {
269 PassVisitor<EnumAndPointerDecay> epc;
270 LinkReferenceToTypes lrt( false, indexer );
271 ForallPointerDecay fpd( indexer );
272 type->accept( epc );
273 type->accept( lrt );
274 type->accept( fpd );
275 }
276
277 void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
278 HoistStruct hoister;
279 acceptAndAdd( translationUnit, hoister );
280 }
281
282 HoistStruct::HoistStruct() : inStruct( false ) {
283 }
284
285 void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
286 std::list< Declaration * >::iterator i = declList.begin();
287 while ( i != declList.end() ) {
288 std::list< Declaration * >::iterator next = i;
289 ++next;
290 if ( pred( *i ) ) {
291 if ( doDelete ) {
292 delete *i;
293 } // if
294 declList.erase( i );
295 } // if
296 i = next;
297 } // while
298 }
299
300 bool isStructOrUnion( Declaration *decl ) {
301 return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
302 }
303
304 template< typename AggDecl >
305 void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
306 if ( inStruct ) {
307 // Add elements in stack order corresponding to nesting structure.
308 declsToAdd.push_front( aggregateDecl );
309 Visitor::visit( aggregateDecl );
310 } else {
311 inStruct = true;
312 Visitor::visit( aggregateDecl );
313 inStruct = false;
314 } // if
315 // Always remove the hoisted aggregate from the inner structure.
316 filter( aggregateDecl->get_members(), isStructOrUnion, false );
317 }
318
319 void HoistStruct::visit( EnumInstType *structInstType ) {
320 if ( structInstType->get_baseEnum() ) {
321 declsToAdd.push_front( structInstType->get_baseEnum() );
322 }
323 }
324
325 void HoistStruct::visit( StructInstType *structInstType ) {
326 if ( structInstType->get_baseStruct() ) {
327 declsToAdd.push_front( structInstType->get_baseStruct() );
328 }
329 }
330
331 void HoistStruct::visit( UnionInstType *structInstType ) {
332 if ( structInstType->get_baseUnion() ) {
333 declsToAdd.push_front( structInstType->get_baseUnion() );
334 }
335 }
336
337 void HoistStruct::visit( StructDecl *aggregateDecl ) {
338 handleAggregate( aggregateDecl );
339 }
340
341 void HoistStruct::visit( UnionDecl *aggregateDecl ) {
342 handleAggregate( aggregateDecl );
343 }
344
345 void HoistStruct::visit( CompoundStmt *compoundStmt ) {
346 addVisit( compoundStmt, *this );
347 }
348
349 void HoistStruct::visit( SwitchStmt *switchStmt ) {
350 addVisit( switchStmt, *this );
351 }
352
353 void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
354 // Set the type of each member of the enumeration to be EnumConstant
355 for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
356 ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
357 assert( obj );
358 obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->get_name() ) );
359 } // for
360 }
361
362 namespace {
363 template< typename DWTList >
364 void fixFunctionList( DWTList & dwts, FunctionType * func ) {
365 // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
366 // entirely. other fix ups are handled by the FixFunction class
367 typedef typename DWTList::iterator DWTIterator;
368 DWTIterator begin( dwts.begin() ), end( dwts.end() );
369 if ( begin == end ) return;
370 FixFunction fixer;
371 DWTIterator i = begin;
372 *i = (*i)->acceptMutator( fixer );
373 if ( fixer.get_isVoid() ) {
374 DWTIterator j = i;
375 ++i;
376 delete *j;
377 dwts.erase( j );
378 if ( i != end ) {
379 throw SemanticError( "invalid type void in function type ", func );
380 } // if
381 } else {
382 ++i;
383 for ( ; i != end; ++i ) {
384 FixFunction fixer;
385 *i = (*i)->acceptMutator( fixer );
386 if ( fixer.get_isVoid() ) {
387 throw SemanticError( "invalid type void in function type ", func );
388 } // if
389 } // for
390 } // if
391 }
392 }
393
394 void EnumAndPointerDecay::previsit( FunctionType *func ) {
395 // Fix up parameters and return types
396 fixFunctionList( func->get_parameters(), func );
397 fixFunctionList( func->get_returnVals(), func );
398 }
399
400 LinkReferenceToTypes::LinkReferenceToTypes( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
401 if ( other_indexer ) {
402 indexer = other_indexer;
403 } else {
404 indexer = this;
405 } // if
406 }
407
408 void LinkReferenceToTypes::visit( EnumInstType *enumInst ) {
409 Parent::visit( enumInst );
410 EnumDecl *st = indexer->lookupEnum( enumInst->get_name() );
411 // it's not a semantic error if the enum is not found, just an implicit forward declaration
412 if ( st ) {
413 //assert( ! enumInst->get_baseEnum() || enumInst->get_baseEnum()->get_members().empty() || ! st->get_members().empty() );
414 enumInst->set_baseEnum( st );
415 } // if
416 if ( ! st || st->get_members().empty() ) {
417 // use of forward declaration
418 forwardEnums[ enumInst->get_name() ].push_back( enumInst );
419 } // if
420 }
421
422 void LinkReferenceToTypes::visit( StructInstType *structInst ) {
423 Parent::visit( structInst );
424 StructDecl *st = indexer->lookupStruct( structInst->get_name() );
425 // it's not a semantic error if the struct is not found, just an implicit forward declaration
426 if ( st ) {
427 //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
428 structInst->set_baseStruct( st );
429 } // if
430 if ( ! st || st->get_members().empty() ) {
431 // use of forward declaration
432 forwardStructs[ structInst->get_name() ].push_back( structInst );
433 } // if
434 }
435
436 void LinkReferenceToTypes::visit( UnionInstType *unionInst ) {
437 Parent::visit( unionInst );
438 UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
439 // it's not a semantic error if the union is not found, just an implicit forward declaration
440 if ( un ) {
441 unionInst->set_baseUnion( un );
442 } // if
443 if ( ! un || un->get_members().empty() ) {
444 // use of forward declaration
445 forwardUnions[ unionInst->get_name() ].push_back( unionInst );
446 } // if
447 }
448
449 void LinkReferenceToTypes::visit( TraitInstType *traitInst ) {
450 Parent::visit( traitInst );
451 if ( traitInst->get_name() == "sized" ) {
452 // "sized" is a special trait with no members - just flick the sized status on for the type variable
453 if ( traitInst->get_parameters().size() != 1 ) {
454 throw SemanticError( "incorrect number of trait parameters: ", traitInst );
455 }
456 TypeExpr * param = safe_dynamic_cast< TypeExpr * > ( traitInst->get_parameters().front() );
457 TypeInstType * inst = safe_dynamic_cast< TypeInstType * > ( param->get_type() );
458 TypeDecl * decl = inst->get_baseType();
459 decl->set_sized( true );
460 // since "sized" is special, the next few steps don't apply
461 return;
462 }
463 TraitDecl *traitDecl = indexer->lookupTrait( traitInst->get_name() );
464 if ( ! traitDecl ) {
465 throw SemanticError( "use of undeclared trait " + traitInst->get_name() );
466 } // if
467 if ( traitDecl->get_parameters().size() != traitInst->get_parameters().size() ) {
468 throw SemanticError( "incorrect number of trait parameters: ", traitInst );
469 } // if
470
471 for ( TypeDecl * td : traitDecl->get_parameters() ) {
472 for ( DeclarationWithType * assert : td->get_assertions() ) {
473 traitInst->get_members().push_back( assert->clone() );
474 } // for
475 } // for
476
477 // need to clone members of the trait for ownership purposes
478 std::list< Declaration * > members;
479 std::transform( traitDecl->get_members().begin(), traitDecl->get_members().end(), back_inserter( members ), [](Declaration * dwt) { return dwt->clone(); } );
480
481 applySubstitution( traitDecl->get_parameters().begin(), traitDecl->get_parameters().end(), traitInst->get_parameters().begin(), members.begin(), members.end(), back_inserter( traitInst->get_members() ) );
482
483 // need to carry over the 'sized' status of each decl in the instance
484 for ( auto p : group_iterate( traitDecl->get_parameters(), traitInst->get_parameters() ) ) {
485 TypeExpr * expr = safe_dynamic_cast< TypeExpr * >( std::get<1>(p) );
486 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
487 TypeDecl * formalDecl = std::get<0>(p);
488 TypeDecl * instDecl = inst->get_baseType();
489 if ( formalDecl->get_sized() ) instDecl->set_sized( true );
490 }
491 }
492 }
493
494 void LinkReferenceToTypes::visit( EnumDecl *enumDecl ) {
495 // visit enum members first so that the types of self-referencing members are updated properly
496 Parent::visit( enumDecl );
497 if ( ! enumDecl->get_members().empty() ) {
498 ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->get_name() );
499 if ( fwds != forwardEnums.end() ) {
500 for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
501 (*inst )->set_baseEnum( enumDecl );
502 } // for
503 forwardEnums.erase( fwds );
504 } // if
505 } // if
506 }
507
508 void LinkReferenceToTypes::visit( StructDecl *structDecl ) {
509 // visit struct members first so that the types of self-referencing members are updated properly
510 // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and and their defaults)
511 Parent::visit( structDecl );
512 if ( ! structDecl->get_members().empty() ) {
513 ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
514 if ( fwds != forwardStructs.end() ) {
515 for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
516 (*inst )->set_baseStruct( structDecl );
517 } // for
518 forwardStructs.erase( fwds );
519 } // if
520 } // if
521 }
522
523 void LinkReferenceToTypes::visit( UnionDecl *unionDecl ) {
524 Parent::visit( unionDecl );
525 if ( ! unionDecl->get_members().empty() ) {
526 ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
527 if ( fwds != forwardUnions.end() ) {
528 for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
529 (*inst )->set_baseUnion( unionDecl );
530 } // for
531 forwardUnions.erase( fwds );
532 } // if
533 } // if
534 }
535
536 void LinkReferenceToTypes::visit( TypeInstType *typeInst ) {
537 if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
538 if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
539 typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
540 } // if
541 } // if
542 }
543
544 ForallPointerDecay::ForallPointerDecay( const Indexer *other_indexer ) : Indexer( false ) {
545 if ( other_indexer ) {
546 indexer = other_indexer;
547 } else {
548 indexer = this;
549 } // if
550 }
551
552 /// Fix up assertions - flattens assertion lists, removing all trait instances
553 void forallFixer( Type * func ) {
554 for ( TypeDecl * type : func->get_forall() ) {
555 std::list< DeclarationWithType * > toBeDone, nextRound;
556 toBeDone.splice( toBeDone.end(), type->get_assertions() );
557 while ( ! toBeDone.empty() ) {
558 for ( DeclarationWithType * assertion : toBeDone ) {
559 if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
560 // expand trait instance into all of its members
561 for ( Declaration * member : traitInst->get_members() ) {
562 DeclarationWithType *dwt = safe_dynamic_cast< DeclarationWithType * >( member );
563 nextRound.push_back( dwt->clone() );
564 }
565 delete traitInst;
566 } else {
567 // pass assertion through
568 FixFunction fixer;
569 assertion = assertion->acceptMutator( fixer );
570 if ( fixer.get_isVoid() ) {
571 throw SemanticError( "invalid type void in assertion of function ", func );
572 }
573 type->get_assertions().push_back( assertion );
574 } // if
575 } // for
576 toBeDone.clear();
577 toBeDone.splice( toBeDone.end(), nextRound );
578 } // while
579 } // for
580 }
581
582 void ForallPointerDecay::visit( ObjectDecl *object ) {
583 forallFixer( object->get_type() );
584 if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
585 forallFixer( pointer->get_base() );
586 } // if
587 Parent::visit( object );
588 object->fixUniqueId();
589 }
590
591 void ForallPointerDecay::visit( FunctionDecl *func ) {
592 forallFixer( func->get_type() );
593 Parent::visit( func );
594 func->fixUniqueId();
595 }
596
597 void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
598 PassVisitor<ReturnChecker> checker;
599 acceptAll( translationUnit, checker );
600 }
601
602 void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
603 GuardValue( returnVals );
604 returnVals = functionDecl->get_functionType()->get_returnVals();
605 }
606
607 void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
608 // Previously this also checked for the existence of an expr paired with no return values on
609 // the function return type. This is incorrect, since you can have an expression attached to
610 // a return statement in a void-returning function in C. The expression is treated as if it
611 // were cast to void.
612 if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
613 throw SemanticError( "Non-void function returns no values: " , returnStmt );
614 }
615 }
616
617
618 bool isTypedef( Declaration *decl ) {
619 return dynamic_cast< TypedefDecl * >( decl );
620 }
621
622 void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
623 EliminateTypedef eliminator;
624 mutateAll( translationUnit, eliminator );
625 if ( eliminator.typedefNames.count( "size_t" ) ) {
626 // grab and remember declaration of size_t
627 SizeType = eliminator.typedefNames["size_t"].first->get_base()->clone();
628 } else {
629 // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
630 // eventually should have a warning for this case.
631 SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
632 }
633 filter( translationUnit, isTypedef, true );
634
635 }
636
637 Type *EliminateTypedef::mutate( TypeInstType * typeInst ) {
638 // instances of typedef types will come here. If it is an instance
639 // of a typdef type, link the instance to its actual type.
640 TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
641 if ( def != typedefNames.end() ) {
642 Type *ret = def->second.first->get_base()->clone();
643 ret->get_qualifiers() |= typeInst->get_qualifiers();
644 // place instance parameters on the typedef'd type
645 if ( ! typeInst->get_parameters().empty() ) {
646 ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
647 if ( ! rtt ) {
648 throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
649 }
650 rtt->get_parameters().clear();
651 cloneAll( typeInst->get_parameters(), rtt->get_parameters() );
652 mutateAll( rtt->get_parameters(), *this ); // recursively fix typedefs on parameters
653 } // if
654 delete typeInst;
655 return ret;
656 } else {
657 TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
658 assertf( base != typedeclNames.end(), "Can't find typedecl name %s", typeInst->get_name().c_str() );
659 typeInst->set_baseType( base->second );
660 } // if
661 return typeInst;
662 }
663
664 Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) {
665 Declaration *ret = Mutator::mutate( tyDecl );
666
667 if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
668 // typedef to the same name from the same scope
669 // must be from the same type
670
671 Type * t1 = tyDecl->get_base();
672 Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
673 if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
674 throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
675 }
676 } else {
677 typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
678 } // if
679
680 // When a typedef is a forward declaration:
681 // typedef struct screen SCREEN;
682 // the declaration portion must be retained:
683 // struct screen;
684 // because the expansion of the typedef is:
685 // void rtn( SCREEN *p ) => void rtn( struct screen *p )
686 // hence the type-name "screen" must be defined.
687 // Note, qualifiers on the typedef are superfluous for the forward declaration.
688
689 Type *designatorType = tyDecl->get_base()->stripDeclarator();
690 if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
691 return new StructDecl( aggDecl->get_name(), DeclarationNode::Struct, noAttributes, tyDecl->get_linkage() );
692 } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
693 return new UnionDecl( aggDecl->get_name(), noAttributes, tyDecl->get_linkage() );
694 } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
695 return new EnumDecl( enumDecl->get_name(), noAttributes, tyDecl->get_linkage() );
696 } else {
697 return ret->clone();
698 } // if
699 }
700
701 TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) {
702 TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
703 if ( i != typedefNames.end() ) {
704 typedefNames.erase( i ) ;
705 } // if
706
707 typedeclNames[ typeDecl->get_name() ] = typeDecl;
708 return Mutator::mutate( typeDecl );
709 }
710
711 DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) {
712 typedefNames.beginScope();
713 DeclarationWithType *ret = Mutator::mutate( funcDecl );
714 typedefNames.endScope();
715 return ret;
716 }
717
718 DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) {
719 typedefNames.beginScope();
720 DeclarationWithType *ret = Mutator::mutate( objDecl );
721 typedefNames.endScope();
722
723 if ( FunctionType *funtype = dynamic_cast<FunctionType *>( ret->get_type() ) ) { // function type?
724 // replace the current object declaration with a function declaration
725 FunctionDecl * newDecl = new FunctionDecl( ret->get_name(), ret->get_storageClasses(), ret->get_linkage(), funtype, 0, objDecl->get_attributes(), ret->get_funcSpec() );
726 objDecl->get_attributes().clear();
727 objDecl->set_type( nullptr );
728 delete objDecl;
729 return newDecl;
730 } // if
731 return ret;
732 }
733
734 Expression *EliminateTypedef::mutate( CastExpr * castExpr ) {
735 typedefNames.beginScope();
736 Expression *ret = Mutator::mutate( castExpr );
737 typedefNames.endScope();
738 return ret;
739 }
740
741 CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) {
742 typedefNames.beginScope();
743 scopeLevel += 1;
744 CompoundStmt *ret = Mutator::mutate( compoundStmt );
745 scopeLevel -= 1;
746 std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
747 while ( i != compoundStmt->get_kids().end() ) {
748 std::list< Statement * >::iterator next = i+1;
749 if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
750 if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
751 delete *i;
752 compoundStmt->get_kids().erase( i );
753 } // if
754 } // if
755 i = next;
756 } // while
757 typedefNames.endScope();
758 return ret;
759 }
760
761 // there may be typedefs nested within aggregates. in order for everything to work properly, these should be removed
762 // as well
763 template<typename AggDecl>
764 AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
765 std::list<Declaration *>::iterator it = aggDecl->get_members().begin();
766 for ( ; it != aggDecl->get_members().end(); ) {
767 std::list< Declaration * >::iterator next = it+1;
768 if ( dynamic_cast< TypedefDecl * >( *it ) ) {
769 delete *it;
770 aggDecl->get_members().erase( it );
771 } // if
772 it = next;
773 }
774 return aggDecl;
775 }
776
777 template<typename AggDecl>
778 void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
779 if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
780 Type *type = nullptr;
781 if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
782 type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
783 } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
784 type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
785 } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) {
786 type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
787 } // if
788 TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), Type::StorageClasses(), type, aggDecl->get_linkage() ) );
789 typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
790 } // if
791 }
792
793 Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) {
794 addImplicitTypedef( structDecl );
795 Mutator::mutate( structDecl );
796 return handleAggregate( structDecl );
797 }
798
799 Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) {
800 addImplicitTypedef( unionDecl );
801 Mutator::mutate( unionDecl );
802 return handleAggregate( unionDecl );
803 }
804
805 Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) {
806 addImplicitTypedef( enumDecl );
807 Mutator::mutate( enumDecl );
808 return handleAggregate( enumDecl );
809 }
810
811 Declaration *EliminateTypedef::mutate( TraitDecl * contextDecl ) {
812 Mutator::mutate( contextDecl );
813 return handleAggregate( contextDecl );
814 }
815
816 void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
817 PassVisitor<VerifyCtorDtorAssign> verifier;
818 acceptAll( translationUnit, verifier );
819 }
820
821 void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
822 FunctionType * funcType = funcDecl->get_functionType();
823 std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
824 std::list< DeclarationWithType * > &params = funcType->get_parameters();
825
826 if ( InitTweak::isCtorDtorAssign( funcDecl->get_name() ) ) {
827 if ( params.size() == 0 ) {
828 throw SemanticError( "Constructors, destructors, and assignment functions require at least one parameter ", funcDecl );
829 }
830 PointerType * ptrType = dynamic_cast< PointerType * >( params.front()->get_type() );
831 if ( ! ptrType || ptrType->is_array() ) {
832 throw SemanticError( "First parameter of a constructor, destructor, or assignment function must be a pointer ", funcDecl );
833 }
834 if ( InitTweak::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
835 throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
836 }
837 }
838 }
839
840 template< typename Aggr >
841 void validateGeneric( Aggr * inst ) {
842 std::list< TypeDecl * > * params = inst->get_baseParameters();
843 if ( params ) {
844 std::list< Expression * > & args = inst->get_parameters();
845
846 // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
847 // A substitution is used to ensure that defaults are replaced correctly, e.g.,
848 // forall(otype T, otype alloc = heap_allocator(T)) struct vector;
849 // vector(int) v;
850 // after insertion of default values becomes
851 // vector(int, heap_allocator(T))
852 // and the substitution is built with T=int so that after substitution, the result is
853 // vector(int, heap_allocator(int))
854 TypeSubstitution sub;
855 auto paramIter = params->begin();
856 for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
857 if ( i < args.size() ) {
858 TypeExpr * expr = safe_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
859 sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
860 } else if ( i == args.size() ) {
861 Type * defaultType = (*paramIter)->get_init();
862 if ( defaultType ) {
863 args.push_back( new TypeExpr( defaultType->clone() ) );
864 sub.add( (*paramIter)->get_name(), defaultType->clone() );
865 }
866 }
867 }
868
869 sub.apply( inst );
870 if ( args.size() < params->size() ) throw SemanticError( "Too few type arguments in generic type ", inst );
871 if ( args.size() > params->size() ) throw SemanticError( "Too many type arguments in generic type ", inst );
872 }
873 }
874
875 void ValidateGenericParameters::previsit( StructInstType * inst ) {
876 validateGeneric( inst );
877 }
878
879 void ValidateGenericParameters::previsit( UnionInstType * inst ) {
880 validateGeneric( inst );
881 }
882
883 void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
884 storageClasses = objectDecl->get_storageClasses();
885 }
886
887 Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
888 // transform [storage_class] ... (struct S){ 3, ... };
889 // into [storage_class] struct S temp = { 3, ... };
890 static UniqueName indexName( "_compLit" );
891
892 ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
893 compLitExpr->set_result( nullptr );
894 compLitExpr->set_initializer( nullptr );
895 delete compLitExpr;
896 declsToAddBefore.push_back( tempvar ); // add modified temporary to current block
897 return new VariableExpr( tempvar );
898 }
899
900 void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
901 PassVisitor<ReturnTypeFixer> fixer;
902 acceptAll( translationUnit, fixer );
903 }
904
905 void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
906 FunctionType * ftype = functionDecl->get_functionType();
907 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
908 assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
909 if ( retVals.size() == 1 ) {
910 // 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).
911 // ensure other return values have a name.
912 DeclarationWithType * ret = retVals.front();
913 if ( ret->get_name() == "" ) {
914 ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
915 }
916 ret->get_attributes().push_back( new Attribute( "unused" ) );
917 }
918 }
919
920 void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
921 // xxx - need to handle named return values - this information needs to be saved somehow
922 // so that resolution has access to the names.
923 // Note that this pass needs to happen early so that other passes which look for tuple types
924 // find them in all of the right places, including function return types.
925 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
926 if ( retVals.size() > 1 ) {
927 // generate a single return parameter which is the tuple of all of the return values
928 TupleType * tupleType = safe_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
929 // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
930 ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
931 deleteAll( retVals );
932 retVals.clear();
933 retVals.push_back( newRet );
934 }
935 }
936
937 void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
938 PassVisitor<ArrayLength> len;
939 acceptAll( translationUnit, len );
940 }
941
942 void ArrayLength::previsit( ObjectDecl * objDecl ) {
943 if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
944 if ( at->get_dimension() ) return;
945 if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->get_init() ) ) {
946 at->set_dimension( new ConstantExpr( Constant::from_ulong( init->get_initializers().size() ) ) );
947 }
948 }
949 }
950} // namespace SymTab
951
952// Local Variables: //
953// tab-width: 4 //
954// mode: c++ //
955// compile-command: "make install" //
956// End: //
Note: See TracBrowser for help on using the repository browser.