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/Statement.h" |
---|
29 | #include "SynTree/Initializer.h" |
---|
30 | #include "SynTree/Mutator.h" |
---|
31 | #include "SymTab/Indexer.h" |
---|
32 | #include "GenPoly/PolyMutator.h" |
---|
33 | #include "SynTree/AddStmtVisitor.h" |
---|
34 | |
---|
35 | bool ctordtorp = false; |
---|
36 | bool ctorp = false; |
---|
37 | bool cpctorp = false; |
---|
38 | bool dtorp = false; |
---|
39 | #define PRINT( text ) if ( ctordtorp ) { text } |
---|
40 | #define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text } |
---|
41 | #define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text } |
---|
42 | |
---|
43 | namespace InitTweak { |
---|
44 | namespace { |
---|
45 | const std::list<Label> noLabels; |
---|
46 | const std::list<Expression*> noDesignators; |
---|
47 | |
---|
48 | class InsertImplicitCalls : public GenPoly::PolyMutator { |
---|
49 | public: |
---|
50 | /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which |
---|
51 | /// function calls need their parameters to be copy constructed |
---|
52 | static void insert( std::list< Declaration * > & translationUnit ); |
---|
53 | |
---|
54 | virtual Expression * mutate( ApplicationExpr * appExpr ); |
---|
55 | }; |
---|
56 | |
---|
57 | class ResolveCopyCtors : public SymTab::Indexer { |
---|
58 | public: |
---|
59 | /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr, |
---|
60 | /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both |
---|
61 | /// arguments and return value temporaries |
---|
62 | static void resolveImplicitCalls( std::list< Declaration * > & translationUnit ); |
---|
63 | |
---|
64 | virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
65 | |
---|
66 | /// create and resolve ctor/dtor expression: fname(var, [cpArg]) |
---|
67 | ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL ); |
---|
68 | /// true if type does not need to be copy constructed to ensure correctness |
---|
69 | bool skipCopyConstruct( Type * ); |
---|
70 | private: |
---|
71 | TypeSubstitution * env; |
---|
72 | }; |
---|
73 | |
---|
74 | /// collects constructed object decls - used as a base class |
---|
75 | class ObjDeclCollector : public AddStmtVisitor { |
---|
76 | public: |
---|
77 | typedef AddStmtVisitor Parent; |
---|
78 | using Parent::visit; |
---|
79 | typedef std::set< ObjectDecl * > ObjectSet; |
---|
80 | virtual void visit( CompoundStmt *compoundStmt ); |
---|
81 | virtual void visit( DeclStmt *stmt ); |
---|
82 | protected: |
---|
83 | ObjectSet curVars; |
---|
84 | }; |
---|
85 | |
---|
86 | // debug |
---|
87 | struct printSet { |
---|
88 | typedef ObjDeclCollector::ObjectSet ObjectSet; |
---|
89 | printSet( const ObjectSet & objs ) : objs( objs ) {} |
---|
90 | const ObjectSet & objs; |
---|
91 | }; |
---|
92 | std::ostream & operator<<( std::ostream & out, const printSet & set) { |
---|
93 | out << "{ "; |
---|
94 | for ( ObjectDecl * obj : set.objs ) { |
---|
95 | out << obj->get_name() << ", " ; |
---|
96 | } // for |
---|
97 | out << " }"; |
---|
98 | return out; |
---|
99 | } |
---|
100 | |
---|
101 | class LabelFinder : public ObjDeclCollector { |
---|
102 | public: |
---|
103 | typedef ObjDeclCollector Parent; |
---|
104 | typedef std::map< Label, ObjectSet > LabelMap; |
---|
105 | // map of Label -> live variables at that label |
---|
106 | LabelMap vars; |
---|
107 | |
---|
108 | void handleStmt( Statement * stmt ); |
---|
109 | |
---|
110 | // xxx - This needs to be done better. |
---|
111 | // allow some generalization among different kinds of nodes with with similar parentage (e.g. all |
---|
112 | // expressions, all statements, etc.) important to have this to provide a single entry point so that as new |
---|
113 | // subclasses are added, there is only one place that the code has to be updated, rather than ensure that |
---|
114 | // every specialized class knows about every new kind of statement that might be added. |
---|
115 | virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
116 | virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
117 | virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
118 | virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
119 | virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
120 | virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
121 | virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
122 | virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
123 | virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
124 | virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
125 | virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
126 | virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
127 | virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
128 | virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
129 | virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
130 | virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); } |
---|
131 | }; |
---|
132 | |
---|
133 | class InsertDtors : public ObjDeclCollector { |
---|
134 | public: |
---|
135 | /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed |
---|
136 | /// (currently by FixInit) |
---|
137 | static void insert( std::list< Declaration * > & translationUnit ); |
---|
138 | |
---|
139 | typedef ObjDeclCollector Parent; |
---|
140 | typedef std::list< ObjectDecl * > OrderedDecls; |
---|
141 | typedef std::list< OrderedDecls > OrderedDeclsStack; |
---|
142 | |
---|
143 | InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {} |
---|
144 | |
---|
145 | virtual void visit( ObjectDecl * objDecl ); |
---|
146 | |
---|
147 | virtual void visit( CompoundStmt * compoundStmt ); |
---|
148 | virtual void visit( ReturnStmt * returnStmt ); |
---|
149 | virtual void visit( BranchStmt * stmt ); |
---|
150 | private: |
---|
151 | void handleGoto( BranchStmt * stmt ); |
---|
152 | |
---|
153 | LabelFinder::LabelMap & labelVars; |
---|
154 | OrderedDeclsStack reverseDeclOrder; |
---|
155 | }; |
---|
156 | |
---|
157 | class FixInit : public GenPoly::PolyMutator { |
---|
158 | public: |
---|
159 | /// expand each object declaration to use its constructor after it is declared. |
---|
160 | static void fixInitializers( std::list< Declaration * > &translationUnit ); |
---|
161 | |
---|
162 | virtual DeclarationWithType * mutate( ObjectDecl *objDecl ); |
---|
163 | |
---|
164 | std::list< Declaration * > staticDtorDecls; |
---|
165 | }; |
---|
166 | |
---|
167 | class FixCopyCtors : public GenPoly::PolyMutator { |
---|
168 | public: |
---|
169 | /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression, |
---|
170 | /// and destructors |
---|
171 | static void fixCopyCtors( std::list< Declaration * > &translationUnit ); |
---|
172 | |
---|
173 | virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
174 | }; |
---|
175 | } // namespace |
---|
176 | |
---|
177 | void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) { |
---|
178 | // fixes ConstructorInit for global variables. should happen before fixInitializers. |
---|
179 | InitTweak::fixGlobalInit( translationUnit, filename, inLibrary ); |
---|
180 | |
---|
181 | InsertImplicitCalls::insert( translationUnit ); |
---|
182 | ResolveCopyCtors::resolveImplicitCalls( translationUnit ); |
---|
183 | InsertDtors::insert( translationUnit ); |
---|
184 | FixInit::fixInitializers( translationUnit ); |
---|
185 | |
---|
186 | // FixCopyCtors must happen after FixInit, so that destructors are placed correctly |
---|
187 | FixCopyCtors::fixCopyCtors( translationUnit ); |
---|
188 | } |
---|
189 | |
---|
190 | namespace { |
---|
191 | void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) { |
---|
192 | InsertImplicitCalls inserter; |
---|
193 | mutateAll( translationUnit, inserter ); |
---|
194 | } |
---|
195 | |
---|
196 | void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) { |
---|
197 | ResolveCopyCtors resolver; |
---|
198 | acceptAll( translationUnit, resolver ); |
---|
199 | } |
---|
200 | |
---|
201 | void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) { |
---|
202 | FixInit fixer; |
---|
203 | |
---|
204 | // can't use mutateAll, because need to insert declarations at top-level |
---|
205 | // can't use DeclMutator, because sometimes need to insert IfStmt, etc. |
---|
206 | SemanticError errors; |
---|
207 | for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) { |
---|
208 | try { |
---|
209 | *i = maybeMutate( *i, fixer ); |
---|
210 | // if (! fixer.staticDtorDecls.empty() ) { |
---|
211 | translationUnit.splice( i, fixer.staticDtorDecls ); |
---|
212 | // } |
---|
213 | } catch( SemanticError &e ) { |
---|
214 | errors.append( e ); |
---|
215 | } // try |
---|
216 | } // for |
---|
217 | if ( ! errors.isEmpty() ) { |
---|
218 | throw errors; |
---|
219 | } // if |
---|
220 | } |
---|
221 | |
---|
222 | void InsertDtors::insert( std::list< Declaration * > & translationUnit ) { |
---|
223 | LabelFinder finder; |
---|
224 | InsertDtors inserter( finder ); |
---|
225 | acceptAll( translationUnit, finder ); |
---|
226 | acceptAll( translationUnit, inserter ); |
---|
227 | } |
---|
228 | |
---|
229 | void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) { |
---|
230 | FixCopyCtors fixer; |
---|
231 | mutateAll( translationUnit, fixer ); |
---|
232 | } |
---|
233 | |
---|
234 | Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) { |
---|
235 | appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) ); |
---|
236 | assert( appExpr ); |
---|
237 | |
---|
238 | if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) { |
---|
239 | if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) { |
---|
240 | // optimization: don't need to copy construct in order to call intrinsic functions |
---|
241 | return appExpr; |
---|
242 | } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) { |
---|
243 | FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) ); |
---|
244 | assert( ftype ); |
---|
245 | if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) { |
---|
246 | Type * t1 = ftype->get_parameters().front()->get_type(); |
---|
247 | Type * t2 = ftype->get_parameters().back()->get_type(); |
---|
248 | PointerType * ptrType = dynamic_cast< PointerType * > ( t1 ); |
---|
249 | assert( ptrType ); |
---|
250 | |
---|
251 | if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) { |
---|
252 | // optimization: don't need to copy construct in order to call a copy constructor or |
---|
253 | // assignment operator |
---|
254 | return appExpr; |
---|
255 | } // if |
---|
256 | } else if ( funcDecl->get_name() == "^?{}" ) { |
---|
257 | // correctness: never copy construct arguments to a destructor |
---|
258 | return appExpr; |
---|
259 | } // if |
---|
260 | } // if |
---|
261 | } // if |
---|
262 | CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; ) |
---|
263 | |
---|
264 | // wrap each function call so that it is easy to identify nodes that have to be copy constructed |
---|
265 | ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr ); |
---|
266 | // save the type substitution onto the new node so that it is easy to find. |
---|
267 | // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion. |
---|
268 | // The substitution is needed to obtain the type of temporary variables so that copy constructor |
---|
269 | // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves |
---|
270 | // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which |
---|
271 | // saves the environment, or compute the types of temporaries here, but it's much simpler to |
---|
272 | // save the environment here, and more cohesive to compute temporary variables and resolve copy |
---|
273 | // constructor calls together. |
---|
274 | assert( env ); |
---|
275 | expr->set_env( env ); |
---|
276 | return expr; |
---|
277 | } |
---|
278 | |
---|
279 | bool ResolveCopyCtors::skipCopyConstruct( Type * type ) { |
---|
280 | return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type ); |
---|
281 | } |
---|
282 | |
---|
283 | ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) { |
---|
284 | assert( var ); |
---|
285 | UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) ); |
---|
286 | untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) ); |
---|
287 | if (cpArg) untyped->get_args().push_back( cpArg ); |
---|
288 | |
---|
289 | // resolve copy constructor |
---|
290 | // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed |
---|
291 | // (VariableExpr and already resolved expression) |
---|
292 | CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; ) |
---|
293 | ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) ); |
---|
294 | if ( resolved->get_env() ) { |
---|
295 | env->add( *resolved->get_env() ); |
---|
296 | } // if |
---|
297 | |
---|
298 | assert( resolved ); |
---|
299 | delete untyped; |
---|
300 | return resolved; |
---|
301 | } |
---|
302 | |
---|
303 | void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) { |
---|
304 | static UniqueName tempNamer("_tmp_cp"); |
---|
305 | static UniqueName retNamer("_tmp_cp_ret"); |
---|
306 | |
---|
307 | CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; ) |
---|
308 | Visitor::visit( impCpCtorExpr ); |
---|
309 | env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer... |
---|
310 | |
---|
311 | ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr(); |
---|
312 | |
---|
313 | // take each argument and attempt to copy construct it. |
---|
314 | for ( Expression * & arg : appExpr->get_args() ) { |
---|
315 | CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; ) |
---|
316 | // xxx - need to handle tuple arguments |
---|
317 | assert( ! arg->get_results().empty() ); |
---|
318 | Type * result = arg->get_results().front(); |
---|
319 | if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types |
---|
320 | // type may involve type variables, so apply type substitution to get temporary variable's actual type |
---|
321 | result = result->clone(); |
---|
322 | impCpCtorExpr->get_env()->apply( result ); |
---|
323 | ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 ); |
---|
324 | tmp->get_type()->set_isConst( false ); |
---|
325 | |
---|
326 | // create and resolve copy constructor |
---|
327 | CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; ) |
---|
328 | ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg ); |
---|
329 | |
---|
330 | // if the chosen constructor is intrinsic, the copy is unnecessary, so |
---|
331 | // don't create the temporary and don't call the copy constructor |
---|
332 | VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() ); |
---|
333 | assert( function ); |
---|
334 | if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) { |
---|
335 | // replace argument to function call with temporary |
---|
336 | arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) ); |
---|
337 | impCpCtorExpr->get_tempDecls().push_back( tmp ); |
---|
338 | impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) ); |
---|
339 | } // if |
---|
340 | } // for |
---|
341 | |
---|
342 | // each return value from the call needs to be connected with an ObjectDecl at the call site, which is |
---|
343 | // initialized with the return value and is destructed later |
---|
344 | // xxx - handle multiple return values |
---|
345 | ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr(); |
---|
346 | // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher |
---|
347 | // level. Trying to pass that environment along. |
---|
348 | callExpr->set_env( impCpCtorExpr->get_env()->clone() ); |
---|
349 | for ( Type * result : appExpr->get_results() ) { |
---|
350 | result = result->clone(); |
---|
351 | impCpCtorExpr->get_env()->apply( result ); |
---|
352 | ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 ); |
---|
353 | ret->get_type()->set_isConst( false ); |
---|
354 | impCpCtorExpr->get_returnDecls().push_back( ret ); |
---|
355 | CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; ) |
---|
356 | impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) ); |
---|
357 | } // for |
---|
358 | CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; ) |
---|
359 | } |
---|
360 | |
---|
361 | |
---|
362 | Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) { |
---|
363 | CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; ) |
---|
364 | |
---|
365 | impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) ); |
---|
366 | assert( impCpCtorExpr ); |
---|
367 | |
---|
368 | std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls(); |
---|
369 | std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls(); |
---|
370 | std::list< Expression * > & dtors = impCpCtorExpr->get_dtors(); |
---|
371 | |
---|
372 | // add all temporary declarations and their constructors |
---|
373 | for ( ObjectDecl * obj : tempDecls ) { |
---|
374 | stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) ); |
---|
375 | } // for |
---|
376 | for ( ObjectDecl * obj : returnDecls ) { |
---|
377 | stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) ); |
---|
378 | } // for |
---|
379 | |
---|
380 | // add destructors after current statement |
---|
381 | for ( Expression * dtor : dtors ) { |
---|
382 | stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) ); |
---|
383 | } // for |
---|
384 | |
---|
385 | // xxx - update to work with multiple return values |
---|
386 | ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front(); |
---|
387 | Expression * callExpr = impCpCtorExpr->get_callExpr(); |
---|
388 | |
---|
389 | CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; ) |
---|
390 | |
---|
391 | // detach fields from wrapper node so that it can be deleted without deleting too much |
---|
392 | dtors.clear(); |
---|
393 | tempDecls.clear(); |
---|
394 | returnDecls.clear(); |
---|
395 | impCpCtorExpr->set_callExpr( NULL ); |
---|
396 | impCpCtorExpr->set_env( NULL ); |
---|
397 | delete impCpCtorExpr; |
---|
398 | |
---|
399 | if ( returnDecl ) { |
---|
400 | UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
401 | assign->get_args().push_back( new VariableExpr( returnDecl ) ); |
---|
402 | assign->get_args().push_back( callExpr ); |
---|
403 | // know the result type of the assignment is the type of the LHS (minus the pointer), so |
---|
404 | // add that onto the assignment expression so that later steps have the necessary information |
---|
405 | assign->add_result( returnDecl->get_type()->clone() ); |
---|
406 | |
---|
407 | Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) ); |
---|
408 | if ( callExpr->get_results().front()->get_isLvalue() ) { |
---|
409 | // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning |
---|
410 | // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the |
---|
411 | // type of the return temporary from T to T* to properly capture the return value. Then dereference |
---|
412 | // the result of the comma expression, since the lvalue returning call was originally wrapped with |
---|
413 | // an AddressExpr. Effectively, this turns |
---|
414 | // lvalue T f(); |
---|
415 | // &*f() |
---|
416 | // into |
---|
417 | // T * tmp_cp_retN; |
---|
418 | // tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret); |
---|
419 | // which work out in terms of types, but is pretty messy. It would be nice to find a better way. |
---|
420 | assign->get_args().back() = new AddressExpr( assign->get_args().back() ); |
---|
421 | |
---|
422 | Type * resultType = returnDecl->get_type()->clone(); |
---|
423 | returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) ); |
---|
424 | UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) ); |
---|
425 | deref->get_args().push_back( retExpr ); |
---|
426 | deref->add_result( resultType ); |
---|
427 | retExpr = deref; |
---|
428 | } // if |
---|
429 | // xxx - might need to set env on retExpr... |
---|
430 | // retExpr->set_env( env->clone() ); |
---|
431 | return retExpr; |
---|
432 | } else { |
---|
433 | return callExpr; |
---|
434 | } // if |
---|
435 | } |
---|
436 | |
---|
437 | DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) { |
---|
438 | // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init |
---|
439 | // is removed from the ObjectDecl |
---|
440 | objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) ); |
---|
441 | |
---|
442 | if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) { |
---|
443 | // a decision should have been made by the resolver, so ctor and init are not both non-NULL |
---|
444 | assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() ); |
---|
445 | if ( Statement * ctor = ctorInit->get_ctor() ) { |
---|
446 | if ( objDecl->get_storageClass() == DeclarationNode::Static ) { |
---|
447 | // originally wanted to take advantage of gcc nested functions, but |
---|
448 | // we get memory errors with this approach. To remedy this, create a |
---|
449 | // global static pointer that is set to refer to the object and make |
---|
450 | // the dtor-caller function global so that. |
---|
451 | // |
---|
452 | // generate: |
---|
453 | // T * __objName_static_ptrN; |
---|
454 | // void __objName_dtor_atexitN() { |
---|
455 | // __dtor(__objName_static_ptrN); |
---|
456 | // } |
---|
457 | // int f(...) { |
---|
458 | // ... |
---|
459 | // static T __objName; |
---|
460 | // static bool __objName_uninitialized = true; |
---|
461 | // if (__objName_uninitialized) { |
---|
462 | // __objName_ptr = &__objName; |
---|
463 | // __ctor(__objName); |
---|
464 | // on_exit(__objName_dtor_atexitN, &__objName); |
---|
465 | // __objName_uninitialized = false; |
---|
466 | // } |
---|
467 | // ... |
---|
468 | // } |
---|
469 | |
---|
470 | static UniqueName ptrNamer( "_static_ptr" ); |
---|
471 | static UniqueName dtorCallerNamer( "_dtor_atexit" ); |
---|
472 | |
---|
473 | // T * __objName_ptrN |
---|
474 | ObjectDecl * objPtr = new ObjectDecl( objDecl->get_mangleName() + ptrNamer.newName(), DeclarationNode::Static, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), objDecl->get_type()->clone() ), 0 ); |
---|
475 | objPtr->fixUniqueId(); |
---|
476 | |
---|
477 | // void __objName_dtor_atexitN(...) {...} |
---|
478 | // need to modify dtor call so that it refers to objPtr, since function will be global |
---|
479 | Statement * dtorStmt = ctorInit->get_dtor()->clone(); |
---|
480 | ApplicationExpr * dtor = dynamic_cast< ApplicationExpr * >( InitTweak::getCtorDtorCall( dtorStmt ) ); |
---|
481 | assert( dtor ); |
---|
482 | delete dtor->get_args().front(); |
---|
483 | dtor->get_args().front() = new VariableExpr( objPtr ); |
---|
484 | |
---|
485 | FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false ); |
---|
486 | dtorCaller->fixUniqueId(); |
---|
487 | dtorCaller->get_statements()->get_kids().push_back( dtorStmt ); |
---|
488 | |
---|
489 | // static bool __objName_uninitialized = true |
---|
490 | BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool ); |
---|
491 | SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators ); |
---|
492 | ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr ); |
---|
493 | isUninitializedVar->fixUniqueId(); |
---|
494 | |
---|
495 | // __objName_static_ptrN = &__objName; |
---|
496 | UntypedExpr * ptrAssign = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
497 | ptrAssign->get_args().push_back( new VariableExpr( objPtr ) ); |
---|
498 | ptrAssign->get_args().push_back( new AddressExpr( new VariableExpr( objDecl ) ) ); |
---|
499 | |
---|
500 | // atexit(dtor_atexit); |
---|
501 | UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) ); |
---|
502 | callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) ); |
---|
503 | |
---|
504 | // __objName_uninitialized = false; |
---|
505 | UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
506 | setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) ); |
---|
507 | setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) ); |
---|
508 | |
---|
509 | // generate body of if |
---|
510 | CompoundStmt * initStmts = new CompoundStmt( noLabels ); |
---|
511 | std::list< Statement * > & body = initStmts->get_kids(); |
---|
512 | body.push_back( ctor ); |
---|
513 | body.push_back( new ExprStmt( noLabels, ptrAssign ) ); |
---|
514 | body.push_back( new ExprStmt( noLabels, callAtexit ) ); |
---|
515 | body.push_back( new ExprStmt( noLabels, setTrue ) ); |
---|
516 | |
---|
517 | // put it all together |
---|
518 | IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 ); |
---|
519 | stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) ); |
---|
520 | stmtsToAddAfter.push_back( ifStmt ); |
---|
521 | |
---|
522 | // add pointer and dtor caller decls to list of decls that will be added into global scope |
---|
523 | staticDtorDecls.push_back( objPtr ); |
---|
524 | staticDtorDecls.push_back( dtorCaller ); |
---|
525 | } else { |
---|
526 | stmtsToAddAfter.push_back( ctor ); |
---|
527 | } // if |
---|
528 | objDecl->set_init( NULL ); |
---|
529 | ctorInit->set_ctor( NULL ); |
---|
530 | } else if ( Initializer * init = ctorInit->get_init() ) { |
---|
531 | objDecl->set_init( init ); |
---|
532 | ctorInit->set_init( NULL ); |
---|
533 | } else { |
---|
534 | // no constructor and no initializer, which is okay |
---|
535 | objDecl->set_init( NULL ); |
---|
536 | } // if |
---|
537 | delete ctorInit; |
---|
538 | } // if |
---|
539 | return objDecl; |
---|
540 | } |
---|
541 | |
---|
542 | void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) { |
---|
543 | std::set< ObjectDecl * > prevVars = curVars; |
---|
544 | Parent::visit( compoundStmt ); |
---|
545 | curVars = prevVars; |
---|
546 | } |
---|
547 | |
---|
548 | void ObjDeclCollector::visit( DeclStmt *stmt ) { |
---|
549 | // keep track of all variables currently in scope |
---|
550 | if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) { |
---|
551 | curVars.insert( objDecl ); |
---|
552 | } // if |
---|
553 | Parent::visit( stmt ); |
---|
554 | } |
---|
555 | |
---|
556 | void LabelFinder::handleStmt( Statement * stmt ) { |
---|
557 | // for each label, remember the variables in scope at that label. |
---|
558 | for ( Label l : stmt->get_labels() ) { |
---|
559 | vars[l] = curVars; |
---|
560 | } // for |
---|
561 | } |
---|
562 | |
---|
563 | template<typename Iterator, typename OutputIterator> |
---|
564 | void insertDtors( Iterator begin, Iterator end, OutputIterator out ) { |
---|
565 | for ( Iterator it = begin ; it != end ; ++it ) { |
---|
566 | // extract destructor statement from the object decl and insert it into the output. Note that this is |
---|
567 | // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually |
---|
568 | // calls an intrinsic dtor then the call must (and will) still be generated since the argument may |
---|
569 | // contain side effects. |
---|
570 | ObjectDecl * objDecl = *it; |
---|
571 | ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ); |
---|
572 | assert( ctorInit && ctorInit->get_dtor() ); |
---|
573 | *out++ = ctorInit->get_dtor()->clone(); |
---|
574 | } // for |
---|
575 | } |
---|
576 | |
---|
577 | void InsertDtors::visit( ObjectDecl * objDecl ) { |
---|
578 | // remember non-static destructed objects so that their destructors can be inserted later |
---|
579 | if ( objDecl->get_storageClass() != DeclarationNode::Static ) { |
---|
580 | if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) { |
---|
581 | // a decision should have been made by the resolver, so ctor and init are not both non-NULL |
---|
582 | assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() ); |
---|
583 | Statement * dtor = ctorInit->get_dtor(); |
---|
584 | if ( dtor && ! isInstrinsicSingleArgCallStmt( dtor ) ) { |
---|
585 | // don't need to call intrinsic dtor, because it does nothing, but |
---|
586 | // non-intrinsic dtors must be called |
---|
587 | reverseDeclOrder.front().push_front( objDecl ); |
---|
588 | } // if |
---|
589 | } // if |
---|
590 | } // if |
---|
591 | Parent::visit( objDecl ); |
---|
592 | } |
---|
593 | |
---|
594 | void InsertDtors::visit( CompoundStmt * compoundStmt ) { |
---|
595 | // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors |
---|
596 | // when block is left, just the destructors associated with variables defined in this block, so push a new |
---|
597 | // list to the top of the stack so that we can differentiate scopes |
---|
598 | reverseDeclOrder.push_front( OrderedDecls() ); |
---|
599 | Parent::visit( compoundStmt ); |
---|
600 | |
---|
601 | // add destructors for the current scope that we're exiting |
---|
602 | std::list< Statement * > & statements = compoundStmt->get_kids(); |
---|
603 | insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) ); |
---|
604 | reverseDeclOrder.pop_front(); |
---|
605 | } |
---|
606 | |
---|
607 | void InsertDtors::visit( ReturnStmt * returnStmt ) { |
---|
608 | // return exits all scopes, so dump destructors for all scopes |
---|
609 | for ( OrderedDecls & od : reverseDeclOrder ) { |
---|
610 | insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) ); |
---|
611 | } // for |
---|
612 | } |
---|
613 | |
---|
614 | // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the |
---|
615 | // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope |
---|
616 | // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user |
---|
617 | // of the error. See C++ Reference 6.6 Jump Statements for details. |
---|
618 | void InsertDtors::handleGoto( BranchStmt * stmt ) { |
---|
619 | assert( stmt->get_target() != "" && "BranchStmt missing a label" ); |
---|
620 | // S_L = lvars = set of objects in scope at label definition |
---|
621 | // S_G = curVars = set of objects in scope at goto statement |
---|
622 | ObjectSet & lvars = labelVars[ stmt->get_target() ]; |
---|
623 | |
---|
624 | DTOR_PRINT( |
---|
625 | std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl; |
---|
626 | std::cerr << "S_G = " << printSet( curVars ) << std::endl; |
---|
627 | std::cerr << "S_L = " << printSet( lvars ) << std::endl; |
---|
628 | ) |
---|
629 | |
---|
630 | ObjectSet diff; |
---|
631 | // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty |
---|
632 | std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) ); |
---|
633 | DTOR_PRINT( |
---|
634 | std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl; |
---|
635 | ) |
---|
636 | if ( ! diff.empty() ) { |
---|
637 | throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt ); |
---|
638 | } // if |
---|
639 | // S_G-S_L results in set of objects that must be destructed |
---|
640 | diff.clear(); |
---|
641 | std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) ); |
---|
642 | DTOR_PRINT( |
---|
643 | std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl; |
---|
644 | ) |
---|
645 | if ( ! diff.empty() ) { |
---|
646 | // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor |
---|
647 | OrderedDecls ordered; |
---|
648 | for ( OrderedDecls & rdo : reverseDeclOrder ) { |
---|
649 | // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order. |
---|
650 | copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } ); |
---|
651 | } // for |
---|
652 | insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) ); |
---|
653 | } // if |
---|
654 | } |
---|
655 | |
---|
656 | void InsertDtors::visit( BranchStmt * stmt ) { |
---|
657 | switch( stmt->get_type() ) { |
---|
658 | case BranchStmt::Continue: |
---|
659 | case BranchStmt::Break: |
---|
660 | // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should |
---|
661 | // always be empty), but it serves as a small sanity check. |
---|
662 | case BranchStmt::Goto: |
---|
663 | handleGoto( stmt ); |
---|
664 | break; |
---|
665 | default: |
---|
666 | assert( false ); |
---|
667 | } // switch |
---|
668 | } |
---|
669 | } // namespace |
---|
670 | } // namespace InitTweak |
---|
671 | |
---|
672 | // Local Variables: // |
---|
673 | // tab-width: 4 // |
---|
674 | // mode: c++ // |
---|
675 | // compile-command: "make install" // |
---|
676 | // End: // |
---|