source: src/InitTweak/FixInit.cc@ 850fda6

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 850fda6 was b16898e, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

walk function type when resolving member constructors

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