source: src/InitTweak/FixInit.cc@ fbfb38e

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor deferred_resn demangler enum forall-pointer-decay gc_noraii jacob/cs343-translation jenkins-sandbox memory 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 fbfb38e was b617e4b, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

ensure temporaries created for copy construction are not const

  • Property mode set to 100644
File size: 15.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 : Rob Schluntz
12// Last Modified On : Thu Apr 14 17:29:21 2016
13// Update Count : 30
14//
15
16#include <stack>
17#include <list>
18#include "RemoveInit.h"
19#include "ResolvExpr/Resolver.h"
20#include "SynTree/Declaration.h"
21#include "SynTree/Type.h"
22#include "SynTree/Expression.h"
23#include "SynTree/Statement.h"
24#include "SynTree/Initializer.h"
25#include "SynTree/Mutator.h"
26#include "SymTab/Indexer.h"
27#include "GenPoly/PolyMutator.h"
28
29namespace InitTweak {
30 namespace {
31 const std::list<Label> noLabels;
32 const std::list<Expression*> noDesignators;
33 }
34
35 class InsertImplicitCalls : public Mutator {
36 public:
37 /// wrap function application expressions as ImplicitCopyCtorExpr nodes
38 /// so that it is easy to identify which function calls need their parameters
39 /// to be copy constructed
40 static void insert( std::list< Declaration * > & translationUnit );
41
42 virtual Expression * mutate( ApplicationExpr * appExpr );
43 };
44
45 class ResolveCopyCtors : public SymTab::Indexer {
46 public:
47 /// generate temporary ObjectDecls for each argument and return value of each
48 /// ImplicitCopyCtorExpr, generate/resolve copy construction expressions for each,
49 /// and generate/resolve destructors for both arguments and return value temporaries
50 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
51
52 virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
53
54 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
55 ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
56 };
57
58 class FixInit : public GenPoly::PolyMutator {
59 public:
60 /// expand each object declaration to use its constructor after it is declared.
61 /// insert destructor calls at the appropriate places
62 static void fixInitializers( std::list< Declaration * > &translationUnit );
63
64 virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
65
66 virtual CompoundStmt * mutate( CompoundStmt * compoundStmt );
67 virtual Statement * mutate( ReturnStmt * returnStmt );
68 virtual Statement * mutate( BranchStmt * branchStmt );
69
70 private:
71 // stack of list of statements - used to differentiate scopes
72 std::list< std::list< Statement * > > dtorStmts;
73 };
74
75 class FixCopyCtors : public GenPoly::PolyMutator {
76 public:
77 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors,
78 /// call expression, and destructors
79 static void fixCopyCtors( std::list< Declaration * > &translationUnit );
80
81 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
82
83 private:
84 // stack of list of statements - used to differentiate scopes
85 std::list< std::list< Statement * > > dtorStmts;
86 };
87
88 void fix( std::list< Declaration * > & translationUnit ) {
89 InsertImplicitCalls::insert( translationUnit );
90 ResolveCopyCtors::resolveImplicitCalls( translationUnit );
91 FixInit::fixInitializers( translationUnit );
92 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
93 FixCopyCtors::fixCopyCtors( translationUnit );
94 }
95
96 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
97 InsertImplicitCalls inserter;
98 mutateAll( translationUnit, inserter );
99 }
100
101 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
102 ResolveCopyCtors resolver;
103 acceptAll( translationUnit, resolver );
104 }
105
106 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
107 FixInit fixer;
108 mutateAll( translationUnit, fixer );
109 }
110
111 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
112 FixCopyCtors fixer;
113 mutateAll( translationUnit, fixer );
114 }
115
116 Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
117 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
118 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
119 // optimization: don't need to copy construct in order to call intrinsic functions
120 return appExpr;
121 } else if ( FunctionDecl * func = dynamic_cast< FunctionDecl * > ( function->get_var() ) ) {
122 // if ( )
123 // // optimization: don't need to copy construct in order to call a copy constructor
124 // return appExpr;
125 }
126 }
127 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
128 appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
129 assert( appExpr );
130 return new ImplicitCopyCtorExpr( appExpr );
131 }
132
133 ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
134 assert( var );
135 UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
136 untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
137 if (cpArg) untyped->get_args().push_back( cpArg );
138
139 // resolve copy constructor
140 // should only be one alternative for copy ctor and dtor expressions, since
141 // all arguments are fixed (VariableExpr and already resolved expression)
142 ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
143
144 assert( resolved );
145 delete untyped;
146 return resolved;
147 }
148
149 void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
150 static UniqueName tempNamer("_tmp_cp");
151 static UniqueName retNamer("_tmp_cp_ret");
152
153 // resolve function call
154 ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( impCpCtorExpr->get_callExpr(), *this ) );
155 assert( appExpr );
156 delete impCpCtorExpr->get_callExpr();
157 impCpCtorExpr->set_callExpr( appExpr );
158
159 // Visitor::visit( impCpCtorExpr );
160
161 // take each argument and attempt to copy construct it.
162 for ( Expression * & arg : appExpr->get_args() ) {
163 // xxx - need to handle tuple arguments
164 assert( ! arg->get_results().empty() );
165 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, arg->get_results().front()->clone(), 0 );
166 tmp->get_type()->set_isConst( false );
167
168 // create and resolve copy constructor
169 ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
170
171 // if the chosen constructor is intrinsic, the copy is unnecessary, so
172 // don't create the temporary and don't call the copy constructor
173 VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
174 assert( function );
175 if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
176 // replace argument to function call with temporary
177 arg = new VariableExpr( tmp );
178 impCpCtorExpr->get_tempDecls().push_back( tmp );
179 impCpCtorExpr->get_copyCtors().push_back( cpCtor );
180 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
181 }
182 }
183
184 // each return value from the call needs to be connected with an ObjectDecl
185 // at the call site, which is initialized with the return value and is destructed
186 // later
187 // xxx - handle multiple return values
188 for ( Type * result : appExpr->get_results() ) {
189 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result->clone(), new SingleInit( impCpCtorExpr->get_callExpr() ) );
190 ret->get_type()->set_isConst( false );
191 impCpCtorExpr->get_returnDecls().push_back( ret );
192 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
193 }
194 }
195
196
197 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
198 impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
199 assert( impCpCtorExpr );
200
201 std::list< Expression * > & copyCtors = impCpCtorExpr->get_copyCtors();
202 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
203 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
204 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
205
206 // add all temporary declarations and their constructors
207 for ( ObjectDecl * obj : tempDecls ) {
208 assert( ! copyCtors.empty() );
209 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
210 stmtsToAdd.push_back( new ExprStmt( noLabels, copyCtors.front() ) );
211 copyCtors.pop_front();
212 }
213
214 // add destructors after current statement
215 for ( Expression * dtor : dtors ) {
216 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
217 }
218
219 // xxx - update to work with multiple return values
220 ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
221
222 // xxx - some of these aren't necessary, and can be removed once this is stable
223 copyCtors.clear();
224 dtors.clear();
225 tempDecls.clear();
226 returnDecls.clear();
227
228 if ( returnDecl ) {
229 // call is currently attached to first returnDecl
230 stmtsToAdd.push_back( new DeclStmt( noLabels, returnDecl ) );
231 return new VariableExpr( returnDecl );
232 } else {
233 // add call expression - if no return values, can call directly
234 return impCpCtorExpr->get_callExpr();
235 }
236 }
237
238 DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
239 // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors
240 // when the init is removed from the ObjectDecl
241 objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
242
243 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
244 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
245 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
246 if ( Statement * ctor = ctorInit->get_ctor() ) {
247 if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
248 // generate:
249 // static bool __objName_uninitialized = true;
250 // if (__objName_uninitialized) {
251 // __ctor(__objName);
252 // void dtor_atexit() {
253 // __dtor(__objName);
254 // }
255 // on_exit(dtorOnExit, &__objName);
256 // __objName_uninitialized = false;
257 // }
258
259 // generate first line
260 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
261 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
262 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
263 isUninitializedVar->fixUniqueId();
264
265 // void dtor_atexit(...) {...}
266 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + "_dtor_atexit", DeclarationNode::NoStorageClass, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
267 dtorCaller->fixUniqueId();
268 dtorCaller->get_statements()->get_kids().push_back( ctorInit->get_dtor() );
269
270 // on_exit(dtor_atexit);
271 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
272 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
273
274 // __objName_uninitialized = false;
275 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
276 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
277 setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
278
279 // generate body of if
280 CompoundStmt * initStmts = new CompoundStmt( noLabels );
281 std::list< Statement * > & body = initStmts->get_kids();
282 body.push_back( ctor );
283 body.push_back( new DeclStmt( noLabels, dtorCaller ) );
284 body.push_back( new ExprStmt( noLabels, callAtexit ) );
285 body.push_back( new ExprStmt( noLabels, setTrue ) );
286
287 // put it all together
288 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
289 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
290 stmtsToAddAfter.push_back( ifStmt );
291 } else {
292 stmtsToAddAfter.push_back( ctor );
293 dtorStmts.back().push_front( ctorInit->get_dtor() );
294 }
295 objDecl->set_init( NULL );
296 ctorInit->set_ctor( NULL );
297 ctorInit->set_dtor( NULL ); // xxx - only destruct when constructing? Probably not?
298 } else if ( Initializer * init = ctorInit->get_init() ) {
299 objDecl->set_init( init );
300 ctorInit->set_init( NULL );
301 } else {
302 // no constructor and no initializer, which is okay
303 objDecl->set_init( NULL );
304 }
305 delete ctorInit;
306 }
307 return objDecl;
308 }
309
310 template<typename Iterator, typename OutputIterator>
311 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
312 for ( Iterator it = begin ; it != end ; ++it ) {
313 // remove if instrinsic destructor statement
314 // xxx - test user manually calling intrinsic functions - what happens?
315 if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( *it ) ) {
316 ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( exprStmt->get_expr() );
317 assert( appExpr );
318 VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
319 assert( function );
320 // check for Intrinsic only - don't want to remove all overridable dtors because autogenerated dtor
321 // will call all member dtors, and some members may have a user defined dtor.
322 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
323 // don't need to call intrinsic dtor, because it does nothing
324 } else {
325 // non-intrinsic dtors must be called
326 *out++ = (*it)->clone();
327 }
328 } else {
329 // could also be a compound statement with a loop, in the case of an array
330 *out++ = (*it)->clone();
331 }
332 }
333 }
334
335
336 CompoundStmt * FixInit::mutate( CompoundStmt * compoundStmt ) {
337 // mutate statements - this will also populate dtorStmts list.
338 // don't want to dump all destructors when block is left,
339 // just the destructors associated with variables defined in this block,
340 // so push a new list to the top of the stack so that we can differentiate scopes
341 dtorStmts.push_back( std::list<Statement *>() );
342
343 compoundStmt = PolyMutator::mutate( compoundStmt );
344 std::list< Statement * > & statements = compoundStmt->get_kids();
345
346 insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( statements ) );
347
348 deleteAll( dtorStmts.back() );
349 dtorStmts.pop_back();
350 return compoundStmt;
351 }
352
353 Statement * FixInit::mutate( ReturnStmt * returnStmt ) {
354 for ( std::list< std::list< Statement * > >::reverse_iterator list = dtorStmts.rbegin(); list != dtorStmts.rend(); ++list ) {
355 insertDtors( list->begin(), list->end(), back_inserter( stmtsToAdd ) );
356 }
357 return Mutator::mutate( returnStmt );
358 }
359
360 Statement * FixInit::mutate( BranchStmt * branchStmt ) {
361 // TODO: adding to the end of a block isn't sufficient, since
362 // return/break/goto should trigger destructor when block is left.
363 switch( branchStmt->get_type() ) {
364 case BranchStmt::Continue:
365 case BranchStmt::Break:
366 insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( stmtsToAdd ) );
367 break;
368 case BranchStmt::Goto:
369 // xxx
370 // if goto leaves a block, generate dtors for every block it leaves
371 // if goto is in same block but earlier statement, destruct every object that was defined after the statement
372 break;
373 default:
374 assert( false );
375 }
376 return Mutator::mutate( branchStmt );
377 }
378
379
380} // namespace InitTweak
381
382// Local Variables: //
383// tab-width: 4 //
384// mode: c++ //
385// compile-command: "make install" //
386// End: //
Note: See TracBrowser for help on using the repository browser.