source: src/SymTab/Validate.cc@ bbc9b64

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 bbc9b64 was fbcde64, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

remove duplication in compound literal, support aggregate-type compound literals

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