source: src/InitTweak/FixInit.cc@ 12bc63a

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 12bc63a was 906e24d, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

replace results list on Expressions with a single Type field

  • Property mode set to 100644
File size: 41.5 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// FixInit.h --
8//
9// Author : Rob Schluntz
10// Created On : Wed Jan 13 16:29:30 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Tue Jul 12 17:41:15 2016
13// Update Count : 34
14//
15
16#include <stack>
17#include <list>
18#include <iterator>
19#include <algorithm>
20#include "InitTweak.h"
21#include "FixInit.h"
22#include "FixGlobalInit.h"
23#include "ResolvExpr/Resolver.h"
24#include "ResolvExpr/typeops.h"
25#include "SynTree/Declaration.h"
26#include "SynTree/Type.h"
27#include "SynTree/Expression.h"
28#include "SynTree/Attribute.h"
29#include "SynTree/Statement.h"
30#include "SynTree/Initializer.h"
31#include "SynTree/Mutator.h"
32#include "SymTab/Indexer.h"
33#include "SymTab/Autogen.h"
34#include "GenPoly/PolyMutator.h"
35#include "GenPoly/DeclMutator.h"
36#include "SynTree/AddStmtVisitor.h"
37#include "CodeGen/GenType.h" // for warnings
38
39bool ctordtorp = false;
40bool ctorp = false;
41bool cpctorp = false;
42bool dtorp = false;
43#define PRINT( text ) if ( ctordtorp ) { text }
44#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
45#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
46
47namespace InitTweak {
48 namespace {
49 const std::list<Label> noLabels;
50 const std::list<Expression*> noDesignators;
51
52 class InsertImplicitCalls : public GenPoly::PolyMutator {
53 public:
54 /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
55 /// function calls need their parameters to be copy constructed
56 static void insert( std::list< Declaration * > & translationUnit );
57
58 virtual Expression * mutate( ApplicationExpr * appExpr );
59 };
60
61 class ResolveCopyCtors : public SymTab::Indexer {
62 public:
63 /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
64 /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
65 /// arguments and return value temporaries
66 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
67
68 virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
69
70 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
71 ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
72 /// true if type does not need to be copy constructed to ensure correctness
73 bool skipCopyConstruct( Type * );
74 private:
75 TypeSubstitution * env;
76 };
77
78 /// collects constructed object decls - used as a base class
79 class ObjDeclCollector : public AddStmtVisitor {
80 public:
81 typedef AddStmtVisitor Parent;
82 using Parent::visit;
83 typedef std::set< ObjectDecl * > ObjectSet;
84 virtual void visit( CompoundStmt *compoundStmt );
85 virtual void visit( DeclStmt *stmt );
86 protected:
87 ObjectSet curVars;
88 };
89
90 // debug
91 struct printSet {
92 typedef ObjDeclCollector::ObjectSet ObjectSet;
93 printSet( const ObjectSet & objs ) : objs( objs ) {}
94 const ObjectSet & objs;
95 };
96 std::ostream & operator<<( std::ostream & out, const printSet & set) {
97 out << "{ ";
98 for ( ObjectDecl * obj : set.objs ) {
99 out << obj->get_name() << ", " ;
100 } // for
101 out << " }";
102 return out;
103 }
104
105 class LabelFinder : public ObjDeclCollector {
106 public:
107 typedef ObjDeclCollector Parent;
108 typedef std::map< Label, ObjectSet > LabelMap;
109 // map of Label -> live variables at that label
110 LabelMap vars;
111
112 void handleStmt( Statement * stmt );
113
114 // xxx - This needs to be done better.
115 // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
116 // expressions, all statements, etc.) important to have this to provide a single entry point so that as new
117 // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
118 // every specialized class knows about every new kind of statement that might be added.
119 virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
120 virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
121 virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
122 virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
123 virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
124 virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
125 virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
126 virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
127 virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
128 virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
129 virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
130 virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
131 virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
132 virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
133 virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
134 virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
135 };
136
137 class InsertDtors : public ObjDeclCollector {
138 public:
139 /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
140 /// (currently by FixInit)
141 static void insert( std::list< Declaration * > & translationUnit );
142
143 typedef ObjDeclCollector Parent;
144 typedef std::list< ObjectDecl * > OrderedDecls;
145 typedef std::list< OrderedDecls > OrderedDeclsStack;
146
147 InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {}
148
149 virtual void visit( ObjectDecl * objDecl );
150
151 virtual void visit( CompoundStmt * compoundStmt );
152 virtual void visit( ReturnStmt * returnStmt );
153 virtual void visit( BranchStmt * stmt );
154 private:
155 void handleGoto( BranchStmt * stmt );
156
157 LabelFinder::LabelMap & labelVars;
158 OrderedDeclsStack reverseDeclOrder;
159 };
160
161 class FixInit : public GenPoly::PolyMutator {
162 public:
163 /// expand each object declaration to use its constructor after it is declared.
164 static void fixInitializers( std::list< Declaration * > &translationUnit );
165
166 virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
167
168 std::list< Declaration * > staticDtorDecls;
169 };
170
171 class FixCopyCtors : public GenPoly::PolyMutator {
172 public:
173 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
174 /// and destructors
175 static void fixCopyCtors( std::list< Declaration * > &translationUnit );
176
177 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
178 };
179
180 class GenStructMemberCalls : public SymTab::Indexer {
181 public:
182 typedef Indexer Parent;
183 /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
184 /// for any member that is missing a corresponding ctor/dtor call.
185 /// error if a member is used before constructed
186 static void generate( std::list< Declaration * > & translationUnit );
187
188 virtual void visit( FunctionDecl * funcDecl );
189
190 virtual void visit( MemberExpr * memberExpr );
191 virtual void visit( ApplicationExpr * appExpr );
192
193 SemanticError errors;
194 private:
195 void handleFirstParam( Expression * firstParam );
196 template< typename... Params >
197 void emit( const Params &... params );
198
199 FunctionDecl * function = 0;
200 std::set< DeclarationWithType * > unhandled, usedUninit;
201 ObjectDecl * thisParam = 0;
202 bool isCtor = false; // true if current function is a constructor
203 StructDecl * structDecl = 0;
204 };
205
206 // very simple resolver-like mutator class - used to
207 // resolve UntypedExprs that are found within newly
208 // generated constructor/destructor calls
209 class MutatingResolver : public Mutator {
210 public:
211 MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {}
212
213 virtual DeclarationWithType* mutate( ObjectDecl *objectDecl );
214
215 virtual Expression* mutate( UntypedExpr *untypedExpr );
216 private:
217 SymTab::Indexer & indexer;
218 };
219
220 class FixCtorExprs : public GenPoly::DeclMutator {
221 public:
222 /// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
223 static void fix( std::list< Declaration * > & translationUnit );
224
225 virtual Expression * mutate( ConstructorExpr * ctorExpr );
226 };
227 } // namespace
228
229 void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) {
230 // fixes ConstructorInit for global variables. should happen before fixInitializers.
231 InitTweak::fixGlobalInit( translationUnit, filename, inLibrary );
232
233
234 InsertImplicitCalls::insert( translationUnit );
235 ResolveCopyCtors::resolveImplicitCalls( translationUnit );
236 InsertDtors::insert( translationUnit );
237 FixInit::fixInitializers( translationUnit );
238
239 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
240 FixCopyCtors::fixCopyCtors( translationUnit );
241
242 GenStructMemberCalls::generate( translationUnit );
243 // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a
244 // hack in the way untyped assignments are generated, where the first argument cannot have
245 // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr.
246 // Thus such assignment exprs must never pushed through expression resolution (and thus should
247 // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed.
248 // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
249 // don't look right, and a member can be constructed more than once.
250 FixCtorExprs::fix( translationUnit );
251 }
252
253 namespace {
254 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
255 InsertImplicitCalls inserter;
256 mutateAll( translationUnit, inserter );
257 }
258
259 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
260 ResolveCopyCtors resolver;
261 acceptAll( translationUnit, resolver );
262 }
263
264 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
265 FixInit fixer;
266
267 // can't use mutateAll, because need to insert declarations at top-level
268 // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
269 SemanticError errors;
270 for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
271 try {
272 *i = maybeMutate( *i, fixer );
273 translationUnit.splice( i, fixer.staticDtorDecls );
274 } catch( SemanticError &e ) {
275 errors.append( e );
276 } // try
277 } // for
278 if ( ! errors.isEmpty() ) {
279 throw errors;
280 } // if
281 }
282
283 void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
284 LabelFinder finder;
285 InsertDtors inserter( finder );
286 acceptAll( translationUnit, finder );
287 acceptAll( translationUnit, inserter );
288 }
289
290 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
291 FixCopyCtors fixer;
292 mutateAll( translationUnit, fixer );
293 }
294
295 void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) {
296 GenStructMemberCalls warner;
297 acceptAll( translationUnit, warner );
298
299 // visitor doesn't throw so that it can collect all errors
300 if ( ! warner.errors.isEmpty() ) {
301 throw warner.errors;
302 }
303 }
304
305 void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) {
306 FixCtorExprs fixer;
307 fixer.mutateDeclarationList( translationUnit );
308 }
309
310 Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
311 appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
312 assert( appExpr );
313
314 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
315 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
316 // optimization: don't need to copy construct in order to call intrinsic functions
317 return appExpr;
318 } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
319 FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
320 assert( ftype );
321 if ( (isConstructor( funcDecl->get_name() ) || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
322 Type * t1 = ftype->get_parameters().front()->get_type();
323 Type * t2 = ftype->get_parameters().back()->get_type();
324 PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
325 assert( ptrType );
326
327 if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
328 // optimization: don't need to copy construct in order to call a copy constructor or
329 // assignment operator
330 return appExpr;
331 } // if
332 } else if ( isDestructor( funcDecl->get_name() ) ) {
333 // correctness: never copy construct arguments to a destructor
334 return appExpr;
335 } // if
336 } // if
337 } // if
338 CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
339
340 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
341 ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
342 // save the type substitution onto the new node so that it is easy to find.
343 // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
344 // The substitution is needed to obtain the type of temporary variables so that copy constructor
345 // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
346 // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
347 // saves the environment, or compute the types of temporaries here, but it's much simpler to
348 // save the environment here, and more cohesive to compute temporary variables and resolve copy
349 // constructor calls together.
350 assert( env );
351 expr->set_env( env );
352 return expr;
353 }
354
355 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
356 return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
357 }
358
359 ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
360 assert( var );
361 UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
362 untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
363 if (cpArg) untyped->get_args().push_back( cpArg->clone() );
364
365 // resolve copy constructor
366 // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
367 // (VariableExpr and already resolved expression)
368 CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
369 ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
370 if ( resolved->get_env() ) {
371 env->add( *resolved->get_env() );
372 } // if
373
374 assert( resolved );
375 delete untyped;
376 return resolved;
377 }
378
379 void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
380 static UniqueName tempNamer("_tmp_cp");
381 static UniqueName retNamer("_tmp_cp_ret");
382
383 CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
384 Visitor::visit( impCpCtorExpr );
385 env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
386
387 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
388
389 // take each argument and attempt to copy construct it.
390 for ( Expression * & arg : appExpr->get_args() ) {
391 CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
392 // xxx - need to handle tuple arguments
393 assert( arg->has_result() );
394 Type * result = arg->get_result();
395 if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
396 // type may involve type variables, so apply type substitution to get temporary variable's actual type
397 result = result->clone();
398 impCpCtorExpr->get_env()->apply( result );
399 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
400 tmp->get_type()->set_isConst( false );
401
402 // create and resolve copy constructor
403 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
404 ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
405
406 // if the chosen constructor is intrinsic, the copy is unnecessary, so
407 // don't create the temporary and don't call the copy constructor
408 VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
409 assert( function );
410 if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
411 // replace argument to function call with temporary
412 arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
413 impCpCtorExpr->get_tempDecls().push_back( tmp );
414 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
415 } // if
416 } // for
417
418 // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
419 // initialized with the return value and is destructed later
420 // xxx - handle multiple return values
421 ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
422 // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher
423 // level. Trying to pass that environment along.
424 callExpr->set_env( impCpCtorExpr->get_env()->clone() );
425 Type * result = appExpr->get_result();
426 if ( ! result->isVoid() ) {
427 // need to flatten result type and construct each
428 result = result->clone();
429 impCpCtorExpr->get_env()->apply( result );
430 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
431 ret->get_type()->set_isConst( false );
432 impCpCtorExpr->get_returnDecls().push_back( ret );
433 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
434 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
435 } // for
436 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
437 }
438
439
440 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
441 CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
442
443 impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
444 assert( impCpCtorExpr );
445
446 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
447 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
448 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
449
450 // add all temporary declarations and their constructors
451 for ( ObjectDecl * obj : tempDecls ) {
452 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
453 } // for
454 for ( ObjectDecl * obj : returnDecls ) {
455 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
456 } // for
457
458 // add destructors after current statement
459 for ( Expression * dtor : dtors ) {
460 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
461 } // for
462
463 // xxx - update to work with multiple return values
464 ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
465 Expression * callExpr = impCpCtorExpr->get_callExpr();
466
467 CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
468
469 // detach fields from wrapper node so that it can be deleted without deleting too much
470 dtors.clear();
471 tempDecls.clear();
472 returnDecls.clear();
473 impCpCtorExpr->set_callExpr( NULL );
474 impCpCtorExpr->set_env( NULL );
475 delete impCpCtorExpr;
476
477 if ( returnDecl ) {
478 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
479 assign->get_args().push_back( new VariableExpr( returnDecl ) );
480 assign->get_args().push_back( callExpr );
481 // know the result type of the assignment is the type of the LHS (minus the pointer), so
482 // add that onto the assignment expression so that later steps have the necessary information
483 assign->set_result( returnDecl->get_type()->clone() );
484
485 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
486 if ( callExpr->get_result()->get_isLvalue() ) {
487 // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
488 // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
489 // type of the return temporary from T to T* to properly capture the return value. Then dereference
490 // the result of the comma expression, since the lvalue returning call was originally wrapped with
491 // an AddressExpr. Effectively, this turns
492 // lvalue T f();
493 // &*f()
494 // into
495 // T * tmp_cp_retN;
496 // tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
497 // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
498 assign->get_args().back() = new AddressExpr( assign->get_args().back() );
499
500 Type * resultType = returnDecl->get_type()->clone();
501 returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
502 UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
503 deref->get_args().push_back( retExpr );
504 deref->set_result( resultType );
505 retExpr = deref;
506 } // if
507 retExpr->set_env( env->clone() );
508 return retExpr;
509 } else {
510 return callExpr;
511 } // if
512 }
513
514 DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
515 // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init
516 // is removed from the ObjectDecl
517 objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
518
519 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
520 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
521 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
522 if ( Statement * ctor = ctorInit->get_ctor() ) {
523 if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
524 // originally wanted to take advantage of gcc nested functions, but
525 // we get memory errors with this approach. To remedy this, the static
526 // variable is hoisted when the destructor needs to be called.
527 //
528 // generate:
529 // static T __objName_static_varN;
530 // void __objName_dtor_atexitN() {
531 // __dtor__...;
532 // }
533 // int f(...) {
534 // ...
535 // static bool __objName_uninitialized = true;
536 // if (__objName_uninitialized) {
537 // __ctor(__objName);
538 // __objName_uninitialized = false;
539 // atexit(__objName_dtor_atexitN);
540 // }
541 // ...
542 // }
543
544 static UniqueName dtorCallerNamer( "_dtor_atexit" );
545
546 // static bool __objName_uninitialized = true
547 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
548 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
549 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
550 isUninitializedVar->fixUniqueId();
551
552 // __objName_uninitialized = false;
553 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
554 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
555 setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
556
557 // generate body of if
558 CompoundStmt * initStmts = new CompoundStmt( noLabels );
559 std::list< Statement * > & body = initStmts->get_kids();
560 body.push_back( ctor );
561 body.push_back( new ExprStmt( noLabels, setTrue ) );
562
563 // put it all together
564 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
565 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
566 stmtsToAddAfter.push_back( ifStmt );
567
568 if ( ctorInit->get_dtor() ) {
569 // if the object has a non-trivial destructor, have to
570 // hoist it and the object into the global space and
571 // call the destructor function with atexit.
572
573 Statement * dtorStmt = ctorInit->get_dtor()->clone();
574
575 // void __objName_dtor_atexitN(...) {...}
576 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
577 dtorCaller->fixUniqueId();
578 dtorCaller->get_statements()->push_back( dtorStmt );
579
580 // atexit(dtor_atexit);
581 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
582 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
583
584 body.push_back( new ExprStmt( noLabels, callAtexit ) );
585
586 // hoist variable and dtor caller decls to list of decls that will be added into global scope
587 staticDtorDecls.push_back( objDecl );
588 staticDtorDecls.push_back( dtorCaller );
589
590 // need to rename object uniquely since it now appears
591 // at global scope and there could be multiple function-scoped
592 // static variables with the same name in different functions.
593 // Note: it isn't sufficient to modify only the mangleName, because
594 // then subsequent Indexer passes can choke on seeing the object's name
595 // if another object has the same name and type. An unfortunate side-effect
596 // of renaming the object is that subsequent NameExprs may fail to resolve,
597 // but there shouldn't be any remaining past this point.
598 static UniqueName staticNamer( "_static_var" );
599 objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
600 objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
601
602 objDecl->set_init( NULL );
603 ctorInit->set_ctor( NULL );
604 delete ctorInit;
605
606 // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
607 // create a new object which is never used
608 static UniqueName dummyNamer( "_dummy" );
609 ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), DeclarationNode::Static, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } );
610 return dummy;
611 }
612 } else {
613 stmtsToAddAfter.push_back( ctor );
614 } // if
615 objDecl->set_init( NULL );
616 ctorInit->set_ctor( NULL );
617 } else if ( Initializer * init = ctorInit->get_init() ) {
618 objDecl->set_init( init );
619 ctorInit->set_init( NULL );
620 } else {
621 // no constructor and no initializer, which is okay
622 objDecl->set_init( NULL );
623 } // if
624 delete ctorInit;
625 } // if
626 return objDecl;
627 }
628
629 void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) {
630 std::set< ObjectDecl * > prevVars = curVars;
631 Parent::visit( compoundStmt );
632 curVars = prevVars;
633 }
634
635 void ObjDeclCollector::visit( DeclStmt *stmt ) {
636 // keep track of all variables currently in scope
637 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
638 curVars.insert( objDecl );
639 } // if
640 Parent::visit( stmt );
641 }
642
643 void LabelFinder::handleStmt( Statement * stmt ) {
644 // for each label, remember the variables in scope at that label.
645 for ( Label l : stmt->get_labels() ) {
646 vars[l] = curVars;
647 } // for
648 }
649
650 template<typename Iterator, typename OutputIterator>
651 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
652 for ( Iterator it = begin ; it != end ; ++it ) {
653 // extract destructor statement from the object decl and insert it into the output. Note that this is
654 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
655 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
656 // contain side effects.
657 ObjectDecl * objDecl = *it;
658 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
659 assert( ctorInit && ctorInit->get_dtor() );
660 *out++ = ctorInit->get_dtor()->clone();
661 } // for
662 }
663
664 void InsertDtors::visit( ObjectDecl * objDecl ) {
665 // remember non-static destructed objects so that their destructors can be inserted later
666 if ( objDecl->get_storageClass() != DeclarationNode::Static ) {
667 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
668 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
669 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
670 Statement * dtor = ctorInit->get_dtor();
671 if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
672 // don't need to call intrinsic dtor, because it does nothing, but
673 // non-intrinsic dtors must be called
674 reverseDeclOrder.front().push_front( objDecl );
675 } // if
676 } // if
677 } // if
678 Parent::visit( objDecl );
679 }
680
681 void InsertDtors::visit( CompoundStmt * compoundStmt ) {
682 // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors
683 // when block is left, just the destructors associated with variables defined in this block, so push a new
684 // list to the top of the stack so that we can differentiate scopes
685 reverseDeclOrder.push_front( OrderedDecls() );
686 Parent::visit( compoundStmt );
687
688 // add destructors for the current scope that we're exiting
689 std::list< Statement * > & statements = compoundStmt->get_kids();
690 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
691 reverseDeclOrder.pop_front();
692 }
693
694 void InsertDtors::visit( ReturnStmt * returnStmt ) {
695 // return exits all scopes, so dump destructors for all scopes
696 for ( OrderedDecls & od : reverseDeclOrder ) {
697 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
698 } // for
699 }
700
701 // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
702 // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
703 // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
704 // of the error. See C++ Reference 6.6 Jump Statements for details.
705 void InsertDtors::handleGoto( BranchStmt * stmt ) {
706 assert( stmt->get_target() != "" && "BranchStmt missing a label" );
707 // S_L = lvars = set of objects in scope at label definition
708 // S_G = curVars = set of objects in scope at goto statement
709 ObjectSet & lvars = labelVars[ stmt->get_target() ];
710
711 DTOR_PRINT(
712 std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
713 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
714 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
715 )
716
717 ObjectSet diff;
718 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
719 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
720 DTOR_PRINT(
721 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
722 )
723 if ( ! diff.empty() ) {
724 throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
725 } // if
726 // S_G-S_L results in set of objects that must be destructed
727 diff.clear();
728 std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
729 DTOR_PRINT(
730 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
731 )
732 if ( ! diff.empty() ) {
733 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
734 OrderedDecls ordered;
735 for ( OrderedDecls & rdo : reverseDeclOrder ) {
736 // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
737 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
738 } // for
739 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
740 } // if
741 }
742
743 void InsertDtors::visit( BranchStmt * stmt ) {
744 switch( stmt->get_type() ) {
745 case BranchStmt::Continue:
746 case BranchStmt::Break:
747 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
748 // always be empty), but it serves as a small sanity check.
749 case BranchStmt::Goto:
750 handleGoto( stmt );
751 break;
752 default:
753 assert( false );
754 } // switch
755 }
756
757 bool checkWarnings( FunctionDecl * funcDecl ) {
758 // only check for warnings if the current function is a user-defined
759 // constructor or destructor
760 if ( ! funcDecl ) return false;
761 if ( ! funcDecl->get_statements() ) return false;
762 return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
763 }
764
765 void GenStructMemberCalls::visit( FunctionDecl * funcDecl ) {
766 ValueGuard< FunctionDecl * > oldFunction( funcDecl );
767 ValueGuard< std::set< DeclarationWithType * > > oldUnhandled( unhandled );
768 ValueGuard< std::set< DeclarationWithType * > > oldUsedUninit( usedUninit );
769 ValueGuard< ObjectDecl * > oldThisParam( thisParam );
770 ValueGuard< bool > oldIsCtor( isCtor );
771 ValueGuard< StructDecl * > oldStructDecl( structDecl );
772
773 // need to start with fresh sets
774 unhandled.clear();
775 usedUninit.clear();
776
777 function = funcDecl;
778 isCtor = isConstructor( function->get_name() );
779 if ( checkWarnings( function ) ) {
780 FunctionType * type = function->get_functionType();
781 assert( ! type->get_parameters().empty() );
782 thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
783 PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() );
784 StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() );
785 if ( structType ) {
786 structDecl = structType->get_baseStruct();
787 for ( Declaration * member : structDecl->get_members() ) {
788 if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
789 // record all of the struct type's members that need to be constructed or
790 // destructed by the end of the function
791 unhandled.insert( field );
792 }
793 }
794 }
795 }
796 Parent::visit( function );
797
798 // remove the unhandled objects from usedUninit, because a call is inserted
799 // to handle them - only objects that are later constructed are used uninitialized.
800 std::set< DeclarationWithType * > diff;
801 std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ) );
802 for ( DeclarationWithType * member : diff ) {
803 emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", member->get_name(), " used before being constructed" );
804 }
805
806 if ( ! unhandled.empty() ) {
807 // need to explicitly re-add function parameters in order to resolve copy constructors
808 enterScope();
809 maybeAccept( function->get_functionType(), *this );
810
811 // need to iterate through members in reverse in order for
812 // ctor/dtor statements to come out in the right order
813 for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
814 DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member );
815 // skip non-DWT members
816 if ( ! field ) continue;
817 // skip handled members
818 if ( ! unhandled.count( field ) ) continue;
819
820 // insert and resolve default/copy constructor call for each field that's unhandled
821 std::list< Statement * > stmt;
822 UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
823 deref->get_args().push_back( new VariableExpr( thisParam ) );
824
825 Expression * arg2 = 0;
826 if ( isCopyConstructor( function ) ) {
827 // if copy ctor, need to pass second-param-of-this-function.field
828 std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
829 assert( params.size() == 2 );
830 arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
831 }
832 InitExpander srcParam( arg2 );
833 SymTab::genImplicitCall( srcParam, new MemberExpr( field, deref ), function->get_name(), back_inserter( stmt ), field, isCtor );
834
835 assert( stmt.size() <= 1 );
836 if ( stmt.size() == 1 ) {
837 Statement * callStmt = stmt.front();
838
839 MutatingResolver resolver( *this );
840 try {
841 callStmt->acceptMutator( resolver );
842 if ( isCtor ) {
843 function->get_statements()->push_front( callStmt );
844 } else {
845 // destructor statements should be added at the end
846 function->get_statements()->push_back( callStmt );
847 }
848 } catch ( SemanticError & error ) {
849 emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", field->get_name(), " not explicitly ", isCtor ? "constructed" : "destructed", " and no ", isCtor ? "default constructor" : "destructor", " found" );
850 }
851 }
852 }
853 leaveScope();
854 }
855 }
856
857 void GenStructMemberCalls::visit( ApplicationExpr * appExpr ) {
858 if ( ! checkWarnings( function ) ) return;
859
860 std::string fname = getFunctionName( appExpr );
861 if ( fname == function->get_name() ) {
862 // call to same kind of function
863 Expression * firstParam = appExpr->get_args().front();
864
865 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) {
866 // if calling another constructor on thisParam, assume that function handles
867 // all members - if it doesn't a warning will appear in that function.
868 if ( varExpr->get_var() == thisParam ) {
869 unhandled.clear();
870 }
871 } else {
872 // if first parameter is a member expression then
873 // remove the member from unhandled set.
874 handleFirstParam( firstParam );
875 }
876 }
877
878 Parent::visit( appExpr );
879 }
880
881 void GenStructMemberCalls::handleFirstParam( Expression * firstParam ) {
882 using namespace std;
883 if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) {
884 if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) {
885 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
886 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
887 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
888 if ( varExpr->get_var() == thisParam ) {
889 unhandled.erase( memberExpr->get_member() );
890 }
891 }
892 }
893 }
894 }
895 }
896 }
897
898 void GenStructMemberCalls::visit( MemberExpr * memberExpr ) {
899 if ( ! checkWarnings( function ) ) return;
900 if ( ! isCtor ) return;
901
902 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
903 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
904 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
905 if ( varExpr->get_var() == thisParam ) {
906 if ( unhandled.count( memberExpr->get_member() ) ) {
907 // emit a warning because a member was used before it was constructed
908 usedUninit.insert( memberExpr->get_member() );
909 }
910 }
911 }
912 }
913 }
914 Parent::visit( memberExpr );
915 }
916
917 template< typename Visitor, typename... Params >
918 void error( Visitor & v, const Params &... params ) {
919 v.errors.append( toString( params... ) );
920 }
921
922 template< typename... Params >
923 void GenStructMemberCalls::emit( const Params &... params ) {
924 // toggle warnings vs. errors here.
925 // warn( params... );
926 error( *this, params... );
927 }
928
929 DeclarationWithType * MutatingResolver::mutate( ObjectDecl *objectDecl ) {
930 // add object to the indexer assumes that there will be no name collisions
931 // in generated code. If this changes, add mutate methods for entities with
932 // scope and call {enter,leave}Scope explicitly.
933 objectDecl->accept( indexer );
934 return objectDecl;
935 }
936
937 Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) {
938 return safe_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) );
939 }
940
941 Expression * FixCtorExprs::mutate( ConstructorExpr * ctorExpr ) {
942 static UniqueName tempNamer( "_tmp_ctor_expr" );
943 assert( ctorExpr->has_result() && ctorExpr->get_result()->size() == 1 );
944 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, nullptr, ctorExpr->get_result()->clone(), nullptr );
945 addDeclaration( tmp );
946
947 ApplicationExpr * callExpr = safe_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
948 TypeSubstitution * env = ctorExpr->get_env();
949 ctorExpr->set_callExpr( nullptr );
950 ctorExpr->set_env( nullptr );
951
952 Expression *& firstArg = callExpr->get_args().front();
953 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
954 assign->get_args().push_back( new VariableExpr( tmp ) );
955 assign->get_args().push_back( firstArg );
956 assign->set_result( ctorExpr->get_result()->clone() );
957 firstArg = assign;
958
959 CommaExpr * commaExpr = new CommaExpr( callExpr, new VariableExpr( tmp ) );
960 commaExpr->set_env( env );
961 delete ctorExpr;
962 return commaExpr;
963 }
964 } // namespace
965} // namespace InitTweak
966
967// Local Variables: //
968// tab-width: 4 //
969// mode: c++ //
970// compile-command: "make install" //
971// End: //
Note: See TracBrowser for help on using the repository browser.