source: src/InitTweak/FixInit.cc@ fba44f8

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

insert implicit ctor/dtors if field is unhandled in a struct ctor/dtor

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