source: src/SymTab/Validate.cc@ 4fbdfae0

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 with_gc
Last change on this file since 4fbdfae0 was 4fbdfae0, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Find intrinsic dereference declaration so that dereference ApplicationExprs can be built without the resolver

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