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 : Wed Jun 21 17:35:05 2017 |
---|
13 | // Update Count : 74 |
---|
14 | // |
---|
15 | #include "FixInit.h" |
---|
16 | |
---|
17 | #include <stddef.h> // for NULL |
---|
18 | #include <algorithm> // for set_difference, copy_if |
---|
19 | #include <cassert> // for assert, strict_dynamic_cast |
---|
20 | #include <iostream> // for operator<<, ostream, basic_ost... |
---|
21 | #include <iterator> // for insert_iterator, back_inserter |
---|
22 | #include <list> // for _List_iterator, list, list<>::... |
---|
23 | #include <map> // for _Rb_tree_iterator, _Rb_tree_co... |
---|
24 | #include <memory> // for allocator_traits<>::value_type |
---|
25 | #include <set> // for set, set<>::value_type |
---|
26 | #include <unordered_map> // for unordered_map, unordered_map<>... |
---|
27 | #include <unordered_set> // for unordered_set |
---|
28 | #include <utility> // for pair |
---|
29 | |
---|
30 | #include "CodeGen/GenType.h" // for genPrettyType |
---|
31 | #include "CodeGen/OperatorTable.h" |
---|
32 | #include "Common/PassVisitor.h" // for PassVisitor, WithStmtsToAdd |
---|
33 | #include "Common/SemanticError.h" // for SemanticError |
---|
34 | #include "Common/UniqueName.h" // for UniqueName |
---|
35 | #include "Common/utility.h" // for CodeLocation, ValueGuard, toSt... |
---|
36 | #include "FixGlobalInit.h" // for fixGlobalInit |
---|
37 | #include "GenInit.h" // for genCtorDtor |
---|
38 | #include "GenPoly/GenPoly.h" // for getFunctionType |
---|
39 | #include "InitTweak.h" // for getFunctionName, getCallArg |
---|
40 | #include "Parser/LinkageSpec.h" // for C, Spec, Cforall, isBuiltin |
---|
41 | #include "ResolvExpr/Resolver.h" // for findVoidExpression |
---|
42 | #include "ResolvExpr/typeops.h" // for typesCompatible |
---|
43 | #include "SymTab/Autogen.h" // for genImplicitCall |
---|
44 | #include "SymTab/Indexer.h" // for Indexer |
---|
45 | #include "SymTab/Mangler.h" // for Mangler |
---|
46 | #include "SynTree/Attribute.h" // for Attribute |
---|
47 | #include "SynTree/Constant.h" // for Constant |
---|
48 | #include "SynTree/Declaration.h" // for ObjectDecl, FunctionDecl, Decl... |
---|
49 | #include "SynTree/Expression.h" // for UniqueExpr, VariableExpr, Unty... |
---|
50 | #include "SynTree/Initializer.h" // for ConstructorInit, SingleInit |
---|
51 | #include "SynTree/Label.h" // for Label, noLabels, operator< |
---|
52 | #include "SynTree/Mutator.h" // for mutateAll, Mutator, maybeMutate |
---|
53 | #include "SynTree/Statement.h" // for ExprStmt, CompoundStmt, Branch... |
---|
54 | #include "SynTree/Type.h" // for Type, Type::StorageClasses |
---|
55 | #include "SynTree/TypeSubstitution.h" // for TypeSubstitution, operator<< |
---|
56 | #include "SynTree/VarExprReplacer.h" // for VarExprReplacer |
---|
57 | #include "SynTree/Visitor.h" // for acceptAll, maybeAccept |
---|
58 | |
---|
59 | bool ctordtorp = false; // print all debug |
---|
60 | bool ctorp = false; // print ctor debug |
---|
61 | bool cpctorp = false; // print copy ctor debug |
---|
62 | bool dtorp = false; // print dtor debug |
---|
63 | #define PRINT( text ) if ( ctordtorp ) { text } |
---|
64 | #define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text } |
---|
65 | #define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text } |
---|
66 | |
---|
67 | namespace InitTweak { |
---|
68 | namespace { |
---|
69 | typedef std::unordered_map< int, int > UnqCount; |
---|
70 | |
---|
71 | struct InsertImplicitCalls : public WithTypeSubstitution { |
---|
72 | /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which |
---|
73 | /// function calls need their parameters to be copy constructed |
---|
74 | static void insert( std::list< Declaration * > & translationUnit ); |
---|
75 | |
---|
76 | Expression * postmutate( ApplicationExpr * appExpr ); |
---|
77 | }; |
---|
78 | |
---|
79 | struct ResolveCopyCtors final : public WithIndexer, public WithShortCircuiting, public WithTypeSubstitution { |
---|
80 | /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr, |
---|
81 | /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both |
---|
82 | /// arguments and return value temporaries |
---|
83 | static void resolveImplicitCalls( std::list< Declaration * > & translationUnit, UnqCount & unqCount ); |
---|
84 | |
---|
85 | ResolveCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ) {} |
---|
86 | |
---|
87 | void postvisit( ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
88 | void postvisit( StmtExpr * stmtExpr ); |
---|
89 | void previsit( UniqueExpr * unqExpr ); |
---|
90 | void postvisit( UniqueExpr * unqExpr ); |
---|
91 | |
---|
92 | /// create and resolve ctor/dtor expression: fname(var, [cpArg]) |
---|
93 | Expression * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL ); |
---|
94 | /// true if type does not need to be copy constructed to ensure correctness |
---|
95 | bool skipCopyConstruct( Type * type ); |
---|
96 | void copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr, Type * formal ); |
---|
97 | void destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
98 | |
---|
99 | UnqCount & unqCount; // count the number of times each unique expr ID appears |
---|
100 | std::unordered_set< int > vars; |
---|
101 | }; |
---|
102 | |
---|
103 | /// collects constructed object decls - used as a base class |
---|
104 | struct ObjDeclCollector : public WithGuards, public WithShortCircuiting { |
---|
105 | // use ordered data structure to maintain ordering for set_difference and for consistent error messages |
---|
106 | typedef std::list< ObjectDecl * > ObjectSet; |
---|
107 | void previsit( CompoundStmt *compoundStmt ); |
---|
108 | void previsit( DeclStmt *stmt ); |
---|
109 | |
---|
110 | // don't go into other functions |
---|
111 | void previsit( FunctionDecl * ) { visit_children = false; } |
---|
112 | |
---|
113 | protected: |
---|
114 | ObjectSet curVars; |
---|
115 | }; |
---|
116 | |
---|
117 | // debug |
---|
118 | template<typename ObjectSet> |
---|
119 | struct PrintSet { |
---|
120 | PrintSet( const ObjectSet & objs ) : objs( objs ) {} |
---|
121 | const ObjectSet & objs; |
---|
122 | }; |
---|
123 | template<typename ObjectSet> |
---|
124 | PrintSet<ObjectSet> printSet( const ObjectSet & objs ) { return PrintSet<ObjectSet>( objs ); } |
---|
125 | template<typename ObjectSet> |
---|
126 | std::ostream & operator<<( std::ostream & out, const PrintSet<ObjectSet> & set) { |
---|
127 | out << "{ "; |
---|
128 | for ( ObjectDecl * obj : set.objs ) { |
---|
129 | out << obj->get_name() << ", " ; |
---|
130 | } // for |
---|
131 | out << " }"; |
---|
132 | return out; |
---|
133 | } |
---|
134 | |
---|
135 | struct LabelFinder final : public ObjDeclCollector { |
---|
136 | typedef std::map< Label, ObjectSet > LabelMap; |
---|
137 | // map of Label -> live variables at that label |
---|
138 | LabelMap vars; |
---|
139 | |
---|
140 | typedef ObjDeclCollector Parent; |
---|
141 | using Parent::previsit; |
---|
142 | void previsit( Statement * stmt ); |
---|
143 | |
---|
144 | void previsit( CompoundStmt *compoundStmt ); |
---|
145 | void previsit( DeclStmt *stmt ); |
---|
146 | }; |
---|
147 | |
---|
148 | struct InsertDtors final : public ObjDeclCollector, public WithStmtsToAdd { |
---|
149 | /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed |
---|
150 | /// (currently by FixInit) |
---|
151 | static void insert( std::list< Declaration * > & translationUnit ); |
---|
152 | |
---|
153 | typedef std::list< ObjectDecl * > OrderedDecls; |
---|
154 | typedef std::list< OrderedDecls > OrderedDeclsStack; |
---|
155 | |
---|
156 | InsertDtors( PassVisitor<LabelFinder> & finder ) : finder( finder ), labelVars( finder.pass.vars ) {} |
---|
157 | |
---|
158 | typedef ObjDeclCollector Parent; |
---|
159 | using Parent::previsit; |
---|
160 | |
---|
161 | void previsit( FunctionDecl * funcDecl ); |
---|
162 | |
---|
163 | void previsit( BranchStmt * stmt ); |
---|
164 | private: |
---|
165 | void handleGoto( BranchStmt * stmt ); |
---|
166 | |
---|
167 | PassVisitor<LabelFinder> & finder; |
---|
168 | LabelFinder::LabelMap & labelVars; |
---|
169 | OrderedDeclsStack reverseDeclOrder; |
---|
170 | }; |
---|
171 | |
---|
172 | class FixInit : public WithStmtsToAdd { |
---|
173 | public: |
---|
174 | /// expand each object declaration to use its constructor after it is declared. |
---|
175 | static void fixInitializers( std::list< Declaration * > &translationUnit ); |
---|
176 | |
---|
177 | DeclarationWithType * postmutate( ObjectDecl *objDecl ); |
---|
178 | |
---|
179 | std::list< Declaration * > staticDtorDecls; |
---|
180 | }; |
---|
181 | |
---|
182 | class FixCopyCtors final : public WithStmtsToAdd, public WithShortCircuiting, public WithVisitorRef<FixCopyCtors> { |
---|
183 | public: |
---|
184 | FixCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ){} |
---|
185 | /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression, |
---|
186 | /// and destructors |
---|
187 | static void fixCopyCtors( std::list< Declaration * > &translationUnit, UnqCount & unqCount ); |
---|
188 | |
---|
189 | Expression * postmutate( ImplicitCopyCtorExpr * impCpCtorExpr ); |
---|
190 | void premutate( StmtExpr * stmtExpr ); |
---|
191 | void premutate( UniqueExpr * unqExpr ); |
---|
192 | |
---|
193 | UnqCount & unqCount; |
---|
194 | }; |
---|
195 | |
---|
196 | struct GenStructMemberCalls final : public WithGuards, public WithShortCircuiting, public WithIndexer { |
---|
197 | /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors |
---|
198 | /// for any member that is missing a corresponding ctor/dtor call. |
---|
199 | /// error if a member is used before constructed |
---|
200 | static void generate( std::list< Declaration * > & translationUnit ); |
---|
201 | |
---|
202 | void previsit( StructDecl * structDecl ); |
---|
203 | |
---|
204 | void previsit( FunctionDecl * funcDecl ); |
---|
205 | void postvisit( FunctionDecl * funcDecl ); |
---|
206 | |
---|
207 | void previsit( MemberExpr * memberExpr ); |
---|
208 | void previsit( ApplicationExpr * appExpr ); |
---|
209 | |
---|
210 | SemanticError errors; |
---|
211 | private: |
---|
212 | template< typename... Params > |
---|
213 | void emit( CodeLocation, const Params &... params ); |
---|
214 | |
---|
215 | FunctionDecl * function = nullptr; |
---|
216 | std::set< DeclarationWithType * > unhandled; |
---|
217 | std::map< DeclarationWithType *, CodeLocation > usedUninit; |
---|
218 | ObjectDecl * thisParam = nullptr; |
---|
219 | bool isCtor = false; // true if current function is a constructor |
---|
220 | StructDecl * structDecl = nullptr; |
---|
221 | |
---|
222 | // special built-in functions necessary for this to work |
---|
223 | StructDecl * dtorStruct = nullptr; |
---|
224 | FunctionDecl * dtorStructDestroy = nullptr; |
---|
225 | }; |
---|
226 | |
---|
227 | // very simple resolver-like mutator class - used to |
---|
228 | // resolve UntypedExprs that are found within newly |
---|
229 | // generated constructor/destructor calls |
---|
230 | class MutatingResolver final : public Mutator { |
---|
231 | public: |
---|
232 | MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {} |
---|
233 | |
---|
234 | using Mutator::mutate; |
---|
235 | virtual DeclarationWithType* mutate( ObjectDecl *objectDecl ) override; |
---|
236 | virtual Expression* mutate( UntypedExpr *untypedExpr ) override; |
---|
237 | |
---|
238 | private: |
---|
239 | SymTab::Indexer & indexer; |
---|
240 | }; |
---|
241 | |
---|
242 | struct FixCtorExprs final : public WithDeclsToAdd, public WithIndexer { |
---|
243 | /// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument |
---|
244 | static void fix( std::list< Declaration * > & translationUnit ); |
---|
245 | |
---|
246 | Expression * postmutate( ConstructorExpr * ctorExpr ); |
---|
247 | }; |
---|
248 | } // namespace |
---|
249 | |
---|
250 | void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) { |
---|
251 | // fixes ConstructorInit for global variables. should happen before fixInitializers. |
---|
252 | InitTweak::fixGlobalInit( translationUnit, filename, inLibrary ); |
---|
253 | |
---|
254 | UnqCount unqCount; |
---|
255 | |
---|
256 | InsertImplicitCalls::insert( translationUnit ); |
---|
257 | ResolveCopyCtors::resolveImplicitCalls( translationUnit, unqCount ); |
---|
258 | InsertDtors::insert( translationUnit ); |
---|
259 | FixInit::fixInitializers( translationUnit ); |
---|
260 | |
---|
261 | // FixCopyCtors must happen after FixInit, so that destructors are placed correctly |
---|
262 | FixCopyCtors::fixCopyCtors( translationUnit, unqCount ); |
---|
263 | |
---|
264 | GenStructMemberCalls::generate( translationUnit ); |
---|
265 | |
---|
266 | // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a |
---|
267 | // hack in the way untyped assignments are generated, where the first argument cannot have |
---|
268 | // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr. |
---|
269 | // Thus such assignment exprs must never pushed through expression resolution (and thus should |
---|
270 | // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed. |
---|
271 | // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs |
---|
272 | // don't look right, and a member can be constructed more than once. |
---|
273 | FixCtorExprs::fix( translationUnit ); |
---|
274 | } |
---|
275 | |
---|
276 | namespace { |
---|
277 | void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) { |
---|
278 | PassVisitor<InsertImplicitCalls> inserter; |
---|
279 | mutateAll( translationUnit, inserter ); |
---|
280 | } |
---|
281 | |
---|
282 | void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) { |
---|
283 | PassVisitor<ResolveCopyCtors> resolver( unqCount ); |
---|
284 | acceptAll( translationUnit, resolver ); |
---|
285 | } |
---|
286 | |
---|
287 | void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) { |
---|
288 | PassVisitor<FixInit> fixer; |
---|
289 | |
---|
290 | // can't use mutateAll, because need to insert declarations at top-level |
---|
291 | // can't use DeclMutator, because sometimes need to insert IfStmt, etc. |
---|
292 | SemanticError errors; |
---|
293 | for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) { |
---|
294 | try { |
---|
295 | maybeMutate( *i, fixer ); |
---|
296 | translationUnit.splice( i, fixer.pass.staticDtorDecls ); |
---|
297 | } catch( SemanticError &e ) { |
---|
298 | e.set_location( (*i)->location ); |
---|
299 | errors.append( e ); |
---|
300 | } // try |
---|
301 | } // for |
---|
302 | if ( ! errors.isEmpty() ) { |
---|
303 | throw errors; |
---|
304 | } // if |
---|
305 | } |
---|
306 | |
---|
307 | void InsertDtors::insert( std::list< Declaration * > & translationUnit ) { |
---|
308 | PassVisitor<LabelFinder> finder; |
---|
309 | PassVisitor<InsertDtors> inserter( finder ); |
---|
310 | acceptAll( translationUnit, inserter ); |
---|
311 | } |
---|
312 | |
---|
313 | void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) { |
---|
314 | PassVisitor<FixCopyCtors> fixer( unqCount ); |
---|
315 | mutateAll( translationUnit, fixer ); |
---|
316 | } |
---|
317 | |
---|
318 | void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) { |
---|
319 | PassVisitor<GenStructMemberCalls> warner; |
---|
320 | acceptAll( translationUnit, warner ); |
---|
321 | } |
---|
322 | |
---|
323 | void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) { |
---|
324 | PassVisitor<FixCtorExprs> fixer; |
---|
325 | mutateAll( translationUnit, fixer ); |
---|
326 | } |
---|
327 | |
---|
328 | Expression * InsertImplicitCalls::postmutate( ApplicationExpr * appExpr ) { |
---|
329 | if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) { |
---|
330 | if ( function->var->linkage.is_builtin ) { |
---|
331 | // optimization: don't need to copy construct in order to call intrinsic functions |
---|
332 | return appExpr; |
---|
333 | } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) { |
---|
334 | FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) ); |
---|
335 | assertf( ftype, "Function call without function type: %s", toString( funcDecl ).c_str() ); |
---|
336 | if ( CodeGen::isConstructor( funcDecl->get_name() ) && ftype->parameters.size() == 2 ) { |
---|
337 | Type * t1 = getPointerBase( ftype->parameters.front()->get_type() ); |
---|
338 | Type * t2 = ftype->parameters.back()->get_type(); |
---|
339 | assert( t1 ); |
---|
340 | |
---|
341 | if ( ResolvExpr::typesCompatible( t1, t2, SymTab::Indexer() ) ) { |
---|
342 | // optimization: don't need to copy construct in order to call a copy constructor |
---|
343 | return appExpr; |
---|
344 | } // if |
---|
345 | } else if ( CodeGen::isDestructor( funcDecl->get_name() ) ) { |
---|
346 | // correctness: never copy construct arguments to a destructor |
---|
347 | return appExpr; |
---|
348 | } // if |
---|
349 | } // if |
---|
350 | } // if |
---|
351 | CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; ) |
---|
352 | |
---|
353 | // wrap each function call so that it is easy to identify nodes that have to be copy constructed |
---|
354 | ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr ); |
---|
355 | // Move the type substitution to the new top-level, if it is attached to the appExpr. |
---|
356 | // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion. |
---|
357 | // The substitution is needed to obtain the type of temporary variables so that copy constructor |
---|
358 | // calls can be resolved. |
---|
359 | assert( env ); |
---|
360 | std::swap( expr->env, appExpr->env ); |
---|
361 | return expr; |
---|
362 | } |
---|
363 | |
---|
364 | bool ResolveCopyCtors::skipCopyConstruct( Type * type ) { return ! isConstructable( type ); } |
---|
365 | |
---|
366 | Expression * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) { |
---|
367 | assert( var ); |
---|
368 | // arrays are not copy constructed, so this should always be an ExprStmt |
---|
369 | ImplicitCtorDtorStmt * stmt = genCtorDtor( fname, var, cpArg ); |
---|
370 | ExprStmt * exprStmt = strict_dynamic_cast< ExprStmt * >( stmt->get_callStmt() ); |
---|
371 | Expression * resolved = exprStmt->expr; |
---|
372 | exprStmt->expr = nullptr; // take ownership of expr |
---|
373 | |
---|
374 | // resolve copy constructor |
---|
375 | // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed |
---|
376 | // (VariableExpr and already resolved expression) |
---|
377 | CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << resolved << std::endl; ) |
---|
378 | ResolvExpr::findVoidExpression( resolved, indexer ); |
---|
379 | assert( resolved ); |
---|
380 | if ( resolved->get_env() ) { |
---|
381 | // Extract useful information and discard new environments. Keeping them causes problems in PolyMutator passes. |
---|
382 | env->add( *resolved->get_env() ); |
---|
383 | delete resolved->get_env(); |
---|
384 | resolved->set_env( nullptr ); |
---|
385 | } // if |
---|
386 | delete stmt; |
---|
387 | return resolved; |
---|
388 | } |
---|
389 | |
---|
390 | void ResolveCopyCtors::copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr, Type * formal ) { |
---|
391 | static UniqueName tempNamer("_tmp_cp"); |
---|
392 | assert( env ); |
---|
393 | CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *env << std::endl; ) |
---|
394 | assert( arg->result ); |
---|
395 | Type * result = arg->result; |
---|
396 | if ( skipCopyConstruct( result ) ) return; // skip certain non-copyable types |
---|
397 | |
---|
398 | // type may involve type variables, so apply type substitution to get temporary variable's actual type. |
---|
399 | // Use applyFree so that types bound in function pointers are not substituted, e.g. in forall(dtype T) void (*)(T). |
---|
400 | result = result->clone(); |
---|
401 | env->applyFree( result ); |
---|
402 | ObjectDecl * tmp = ObjectDecl::newObject( "__tmp", result, nullptr ); |
---|
403 | tmp->get_type()->set_const( false ); |
---|
404 | |
---|
405 | // create and resolve copy constructor |
---|
406 | CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; ) |
---|
407 | Expression * cpCtor = makeCtorDtor( "?{}", tmp, arg ); |
---|
408 | |
---|
409 | if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( cpCtor ) ) { |
---|
410 | // if the chosen constructor is intrinsic, the copy is unnecessary, so |
---|
411 | // don't create the temporary and don't call the copy constructor |
---|
412 | VariableExpr * function = strict_dynamic_cast< VariableExpr * >( appExpr->function ); |
---|
413 | if ( function->var->linkage == LinkageSpec::Intrinsic ) { |
---|
414 | // arguments that need to be boxed need a temporary regardless of whether the copy constructor is intrinsic, |
---|
415 | // so that the object isn't changed inside of the polymorphic function |
---|
416 | if ( ! GenPoly::needsBoxing( formal, result, impCpCtorExpr->callExpr, env ) ) return; |
---|
417 | } |
---|
418 | } |
---|
419 | |
---|
420 | // set a unique name for the temporary once it's certain the call is necessary |
---|
421 | tmp->name = tempNamer.newName(); |
---|
422 | |
---|
423 | // replace argument to function call with temporary |
---|
424 | arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) ); |
---|
425 | impCpCtorExpr->tempDecls.push_back( tmp ); |
---|
426 | impCpCtorExpr->dtors.push_front( makeCtorDtor( "^?{}", tmp ) ); |
---|
427 | } |
---|
428 | |
---|
429 | void ResolveCopyCtors::destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr ) { |
---|
430 | impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) ); |
---|
431 | } |
---|
432 | |
---|
433 | void ResolveCopyCtors::postvisit( ImplicitCopyCtorExpr *impCpCtorExpr ) { |
---|
434 | CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; ) |
---|
435 | |
---|
436 | ApplicationExpr * appExpr = impCpCtorExpr->callExpr; |
---|
437 | |
---|
438 | // take each argument and attempt to copy construct it. |
---|
439 | FunctionType * ftype = GenPoly::getFunctionType( appExpr->function->result ); |
---|
440 | assert( ftype ); |
---|
441 | auto & params = ftype->parameters; |
---|
442 | auto iter = params.begin(); |
---|
443 | for ( Expression * & arg : appExpr->args ) { |
---|
444 | Type * formal = nullptr; |
---|
445 | if ( iter != params.end() ) { |
---|
446 | DeclarationWithType * param = *iter++; |
---|
447 | formal = param->get_type(); |
---|
448 | } |
---|
449 | |
---|
450 | copyConstructArg( arg, impCpCtorExpr, formal ); |
---|
451 | } // for |
---|
452 | |
---|
453 | // each return value from the call needs to be connected with an ObjectDecl at the call site, which is |
---|
454 | // initialized with the return value and is destructed later |
---|
455 | // xxx - handle named return values? |
---|
456 | Type * result = appExpr->result; |
---|
457 | if ( ! result->isVoid() ) { |
---|
458 | static UniqueName retNamer("_tmp_cp_ret"); |
---|
459 | result = result->clone(); |
---|
460 | env->apply( result ); |
---|
461 | ObjectDecl * ret = ObjectDecl::newObject( retNamer.newName(), result, nullptr ); |
---|
462 | ret->type->set_const( false ); |
---|
463 | impCpCtorExpr->returnDecls.push_back( ret ); |
---|
464 | CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; ) |
---|
465 | if ( ! dynamic_cast< ReferenceType * >( result ) ) { |
---|
466 | // destructing reference returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary |
---|
467 | destructRet( ret, impCpCtorExpr ); |
---|
468 | } |
---|
469 | } // for |
---|
470 | CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; ) |
---|
471 | } |
---|
472 | |
---|
473 | void ResolveCopyCtors::postvisit( StmtExpr * stmtExpr ) { |
---|
474 | assert( env ); |
---|
475 | assert( stmtExpr->get_result() ); |
---|
476 | Type * result = stmtExpr->get_result(); |
---|
477 | if ( ! result->isVoid() ) { |
---|
478 | static UniqueName retNamer("_tmp_stmtexpr_ret"); |
---|
479 | |
---|
480 | // create variable that will hold the result of the stmt expr |
---|
481 | result = result->clone(); |
---|
482 | env->apply( result ); |
---|
483 | ObjectDecl * ret = ObjectDecl::newObject( retNamer.newName(), result, nullptr ); |
---|
484 | ret->get_type()->set_const( false ); |
---|
485 | stmtExpr->get_returnDecls().push_front( ret ); |
---|
486 | |
---|
487 | // must have a non-empty body, otherwise it wouldn't have a result |
---|
488 | CompoundStmt * body = stmtExpr->get_statements(); |
---|
489 | assert( ! body->get_kids().empty() ); |
---|
490 | // must be an ExprStmt, otherwise it wouldn't have a result |
---|
491 | ExprStmt * last = strict_dynamic_cast< ExprStmt * >( body->get_kids().back() ); |
---|
492 | last->set_expr( makeCtorDtor( "?{}", ret, last->get_expr() ) ); |
---|
493 | |
---|
494 | stmtExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) ); |
---|
495 | } // if |
---|
496 | } |
---|
497 | |
---|
498 | void ResolveCopyCtors::previsit( UniqueExpr * unqExpr ) { |
---|
499 | unqCount[ unqExpr->get_id() ]++; // count the number of unique expressions for each ID |
---|
500 | if ( vars.count( unqExpr->get_id() ) ) { |
---|
501 | // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated |
---|
502 | visit_children = false; |
---|
503 | } |
---|
504 | } |
---|
505 | |
---|
506 | void ResolveCopyCtors::postvisit( UniqueExpr * unqExpr ) { |
---|
507 | if ( vars.count( unqExpr->get_id() ) ) { |
---|
508 | // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated |
---|
509 | return; |
---|
510 | } |
---|
511 | |
---|
512 | // it should never be necessary to wrap a void-returning expression in a UniqueExpr - if this assumption changes, this needs to be rethought |
---|
513 | assert( unqExpr->get_result() ); |
---|
514 | if ( ImplicitCopyCtorExpr * impCpCtorExpr = dynamic_cast<ImplicitCopyCtorExpr*>( unqExpr->get_expr() ) ) { |
---|
515 | // note the variable used as the result from the call |
---|
516 | assert( impCpCtorExpr->get_result() && impCpCtorExpr->get_returnDecls().size() == 1 ); |
---|
517 | unqExpr->set_var( new VariableExpr( impCpCtorExpr->get_returnDecls().front() ) ); |
---|
518 | } else { |
---|
519 | // expr isn't a call expr, so create a new temporary variable to use to hold the value of the unique expression |
---|
520 | unqExpr->set_object( ObjectDecl::newObject( toString("_unq", unqExpr->get_id()), unqExpr->get_result()->clone(), nullptr ) ); |
---|
521 | unqExpr->set_var( new VariableExpr( unqExpr->get_object() ) ); |
---|
522 | } |
---|
523 | vars.insert( unqExpr->get_id() ); |
---|
524 | } |
---|
525 | |
---|
526 | Expression * FixCopyCtors::postmutate( ImplicitCopyCtorExpr * impCpCtorExpr ) { |
---|
527 | CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; ) |
---|
528 | |
---|
529 | std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls(); |
---|
530 | std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls(); |
---|
531 | std::list< Expression * > & dtors = impCpCtorExpr->get_dtors(); |
---|
532 | |
---|
533 | // add all temporary declarations and their constructors |
---|
534 | for ( ObjectDecl * obj : tempDecls ) { |
---|
535 | stmtsToAddBefore.push_back( new DeclStmt( noLabels, obj ) ); |
---|
536 | } // for |
---|
537 | for ( ObjectDecl * obj : returnDecls ) { |
---|
538 | stmtsToAddBefore.push_back( new DeclStmt( noLabels, obj ) ); |
---|
539 | } // for |
---|
540 | |
---|
541 | // add destructors after current statement |
---|
542 | for ( Expression * dtor : dtors ) { |
---|
543 | stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) ); |
---|
544 | } // for |
---|
545 | |
---|
546 | ObjectDecl * returnDecl = returnDecls.empty() ? nullptr : returnDecls.front(); |
---|
547 | Expression * callExpr = impCpCtorExpr->get_callExpr(); |
---|
548 | |
---|
549 | CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; ) |
---|
550 | |
---|
551 | // detach fields from wrapper node so that it can be deleted without deleting too much |
---|
552 | dtors.clear(); |
---|
553 | tempDecls.clear(); |
---|
554 | returnDecls.clear(); |
---|
555 | impCpCtorExpr->set_callExpr( nullptr ); |
---|
556 | std::swap( impCpCtorExpr->env, callExpr->env ); |
---|
557 | assert( impCpCtorExpr->env == nullptr ); |
---|
558 | delete impCpCtorExpr; |
---|
559 | |
---|
560 | if ( returnDecl ) { |
---|
561 | UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
562 | assign->get_args().push_back( new VariableExpr( returnDecl ) ); |
---|
563 | assign->get_args().push_back( callExpr ); |
---|
564 | // know the result type of the assignment is the type of the LHS (minus the pointer), so |
---|
565 | // add that onto the assignment expression so that later steps have the necessary information |
---|
566 | assign->set_result( returnDecl->get_type()->clone() ); |
---|
567 | |
---|
568 | Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) ); |
---|
569 | // move env from callExpr to retExpr |
---|
570 | std::swap( retExpr->env, callExpr->env ); |
---|
571 | return retExpr; |
---|
572 | } else { |
---|
573 | return callExpr; |
---|
574 | } // if |
---|
575 | } |
---|
576 | |
---|
577 | void FixCopyCtors::premutate( StmtExpr * stmtExpr ) { |
---|
578 | // function call temporaries should be placed at statement-level, rather than nested inside of a new statement expression, |
---|
579 | // since temporaries can be shared across sub-expressions, e.g. |
---|
580 | // [A, A] f(); |
---|
581 | // g([A] x, [A] y); |
---|
582 | // g(f()); |
---|
583 | // f is executed once, so the return temporary is shared across the tuple constructors for x and y. |
---|
584 | // Explicitly mutating children instead of mutating the inner compound statment forces the temporaries to be added |
---|
585 | // to the outer context, rather than inside of the statement expression. |
---|
586 | visit_children = false; |
---|
587 | std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids(); |
---|
588 | for ( Statement *& stmt : stmts ) { |
---|
589 | stmt = stmt->acceptMutator( *visitor ); |
---|
590 | } // for |
---|
591 | assert( stmtExpr->get_result() ); |
---|
592 | Type * result = stmtExpr->get_result(); |
---|
593 | if ( ! result->isVoid() ) { |
---|
594 | for ( ObjectDecl * obj : stmtExpr->get_returnDecls() ) { |
---|
595 | stmtsToAddBefore.push_back( new DeclStmt( noLabels, obj ) ); |
---|
596 | } // for |
---|
597 | // add destructors after current statement |
---|
598 | for ( Expression * dtor : stmtExpr->get_dtors() ) { |
---|
599 | stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) ); |
---|
600 | } // for |
---|
601 | // must have a non-empty body, otherwise it wouldn't have a result |
---|
602 | assert( ! stmts.empty() ); |
---|
603 | assert( ! stmtExpr->get_returnDecls().empty() ); |
---|
604 | stmts.push_back( new ExprStmt( noLabels, new VariableExpr( stmtExpr->get_returnDecls().front() ) ) ); |
---|
605 | stmtExpr->get_returnDecls().clear(); |
---|
606 | stmtExpr->get_dtors().clear(); |
---|
607 | } |
---|
608 | assert( stmtExpr->get_returnDecls().empty() ); |
---|
609 | assert( stmtExpr->get_dtors().empty() ); |
---|
610 | } |
---|
611 | |
---|
612 | void FixCopyCtors::premutate( UniqueExpr * unqExpr ) { |
---|
613 | visit_children = false; |
---|
614 | unqCount[ unqExpr->get_id() ]--; |
---|
615 | static std::unordered_map< int, std::list< Statement * > > dtors; |
---|
616 | static std::unordered_map< int, UniqueExpr * > unqMap; |
---|
617 | // has to be done to clean up ImplicitCopyCtorExpr nodes, even when this node was skipped in previous passes |
---|
618 | if ( unqMap.count( unqExpr->get_id() ) ) { |
---|
619 | // take data from other UniqueExpr to ensure consistency |
---|
620 | delete unqExpr->get_expr(); |
---|
621 | unqExpr->set_expr( unqMap[unqExpr->get_id()]->get_expr()->clone() ); |
---|
622 | delete unqExpr->get_result(); |
---|
623 | unqExpr->set_result( maybeClone( unqExpr->get_expr()->get_result() ) ); |
---|
624 | if ( unqCount[ unqExpr->get_id() ] == 0 ) { // insert destructor after the last use of the unique expression |
---|
625 | stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] ); |
---|
626 | } |
---|
627 | return; |
---|
628 | } |
---|
629 | PassVisitor<FixCopyCtors> fixer( unqCount ); |
---|
630 | unqExpr->set_expr( unqExpr->get_expr()->acceptMutator( fixer ) ); // stmtexprs contained should not be separately fixed, so this must occur after the lookup |
---|
631 | stmtsToAddBefore.splice( stmtsToAddBefore.end(), fixer.pass.stmtsToAddBefore ); |
---|
632 | unqMap[unqExpr->get_id()] = unqExpr; |
---|
633 | if ( unqCount[ unqExpr->get_id() ] == 0 ) { // insert destructor after the last use of the unique expression |
---|
634 | stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] ); |
---|
635 | } else { // remember dtors for last instance of unique expr |
---|
636 | dtors[ unqExpr->get_id() ] = fixer.pass.stmtsToAddAfter; |
---|
637 | } |
---|
638 | return; |
---|
639 | } |
---|
640 | |
---|
641 | DeclarationWithType * getDtorFunc( ObjectDecl * objDecl, Statement * dtor, std::list< Statement * > & stmtsToAdd ) { |
---|
642 | if ( dynamic_cast< ExprStmt * >( dtor ) ) { |
---|
643 | if ( DeclarationWithType * func = getFunction( getCtorDtorCall( dtor ) ) ) { |
---|
644 | // cleanup argument must be a function, not an object (including function pointer) |
---|
645 | if ( FunctionDecl * dtorFunc = dynamic_cast< FunctionDecl * > ( func ) ) { |
---|
646 | if ( dtorFunc->type->forall.empty() ) { |
---|
647 | // simple case where the destructor is a monomorphic function call - can simply |
---|
648 | // use that function as the cleanup function. |
---|
649 | delete dtor; |
---|
650 | return func; |
---|
651 | } |
---|
652 | } |
---|
653 | } |
---|
654 | } |
---|
655 | |
---|
656 | // otherwise the cleanup is more complicated - need to build a single argument cleanup function that |
---|
657 | // wraps the more complicated code. |
---|
658 | static UniqueName dtorNamer( "__cleanup_dtor" ); |
---|
659 | FunctionDecl * dtorFunc = FunctionDecl::newFunction( dtorNamer.newName(), SymTab::genDefaultType( objDecl->type->stripReferences(), false ), new CompoundStmt( noLabels ) ); |
---|
660 | stmtsToAdd.push_back( new DeclStmt( noLabels, dtorFunc ) ); |
---|
661 | |
---|
662 | // the original code contains uses of objDecl - replace them with the newly generated 'this' parameter. |
---|
663 | ObjectDecl * thisParam = getParamThis( dtorFunc->type ); |
---|
664 | VarExprReplacer::replace( dtor, { std::make_pair( objDecl, thisParam ) } ); |
---|
665 | dtorFunc->statements->push_back( dtor ); |
---|
666 | |
---|
667 | return dtorFunc; |
---|
668 | } |
---|
669 | |
---|
670 | DeclarationWithType * FixInit::postmutate( ObjectDecl *objDecl ) { |
---|
671 | // since this removes the init field from objDecl, it must occur after children are mutated (i.e. postmutate) |
---|
672 | if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) { |
---|
673 | // a decision should have been made by the resolver, so ctor and init are not both non-NULL |
---|
674 | assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() ); |
---|
675 | if ( Statement * ctor = ctorInit->get_ctor() ) { |
---|
676 | if ( objDecl->get_storageClasses().is_static ) { |
---|
677 | // originally wanted to take advantage of gcc nested functions, but |
---|
678 | // we get memory errors with this approach. To remedy this, the static |
---|
679 | // variable is hoisted when the destructor needs to be called. |
---|
680 | // |
---|
681 | // generate: |
---|
682 | // static T __objName_static_varN; |
---|
683 | // void __objName_dtor_atexitN() { |
---|
684 | // __dtor__...; |
---|
685 | // } |
---|
686 | // int f(...) { |
---|
687 | // ... |
---|
688 | // static bool __objName_uninitialized = true; |
---|
689 | // if (__objName_uninitialized) { |
---|
690 | // __ctor(__objName); |
---|
691 | // __objName_uninitialized = false; |
---|
692 | // atexit(__objName_dtor_atexitN); |
---|
693 | // } |
---|
694 | // ... |
---|
695 | // } |
---|
696 | |
---|
697 | static UniqueName dtorCallerNamer( "_dtor_atexit" ); |
---|
698 | |
---|
699 | // static bool __objName_uninitialized = true |
---|
700 | BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool ); |
---|
701 | SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant::from_int( 1 ) ) ); |
---|
702 | ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, boolType, boolInitExpr ); |
---|
703 | isUninitializedVar->fixUniqueId(); |
---|
704 | |
---|
705 | // __objName_uninitialized = false; |
---|
706 | UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) ); |
---|
707 | setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) ); |
---|
708 | setTrue->get_args().push_back( new ConstantExpr( Constant::from_int( 0 ) ) ); |
---|
709 | |
---|
710 | // generate body of if |
---|
711 | CompoundStmt * initStmts = new CompoundStmt( noLabels ); |
---|
712 | std::list< Statement * > & body = initStmts->get_kids(); |
---|
713 | body.push_back( ctor ); |
---|
714 | body.push_back( new ExprStmt( noLabels, setTrue ) ); |
---|
715 | |
---|
716 | // put it all together |
---|
717 | IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 ); |
---|
718 | stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) ); |
---|
719 | stmtsToAddAfter.push_back( ifStmt ); |
---|
720 | |
---|
721 | Statement * dtor = ctorInit->get_dtor(); |
---|
722 | objDecl->set_init( nullptr ); |
---|
723 | ctorInit->set_ctor( nullptr ); |
---|
724 | ctorInit->set_dtor( nullptr ); |
---|
725 | if ( dtor ) { |
---|
726 | // if the object has a non-trivial destructor, have to |
---|
727 | // hoist it and the object into the global space and |
---|
728 | // call the destructor function with atexit. |
---|
729 | |
---|
730 | Statement * dtorStmt = dtor->clone(); |
---|
731 | |
---|
732 | // void __objName_dtor_atexitN(...) {...} |
---|
733 | FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ) ); |
---|
734 | dtorCaller->fixUniqueId(); |
---|
735 | dtorCaller->get_statements()->push_back( dtorStmt ); |
---|
736 | |
---|
737 | // atexit(dtor_atexit); |
---|
738 | UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) ); |
---|
739 | callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) ); |
---|
740 | |
---|
741 | body.push_back( new ExprStmt( noLabels, callAtexit ) ); |
---|
742 | |
---|
743 | // hoist variable and dtor caller decls to list of decls that will be added into global scope |
---|
744 | staticDtorDecls.push_back( objDecl ); |
---|
745 | staticDtorDecls.push_back( dtorCaller ); |
---|
746 | |
---|
747 | // need to rename object uniquely since it now appears |
---|
748 | // at global scope and there could be multiple function-scoped |
---|
749 | // static variables with the same name in different functions. |
---|
750 | // Note: it isn't sufficient to modify only the mangleName, because |
---|
751 | // then subsequent Indexer passes can choke on seeing the object's name |
---|
752 | // if another object has the same name and type. An unfortunate side-effect |
---|
753 | // of renaming the object is that subsequent NameExprs may fail to resolve, |
---|
754 | // but there shouldn't be any remaining past this point. |
---|
755 | static UniqueName staticNamer( "_static_var" ); |
---|
756 | objDecl->set_name( objDecl->get_name() + staticNamer.newName() ); |
---|
757 | objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) ); |
---|
758 | |
---|
759 | // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope |
---|
760 | // create a new object which is never used |
---|
761 | static UniqueName dummyNamer( "_dummy" ); |
---|
762 | ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } ); |
---|
763 | delete ctorInit; |
---|
764 | return dummy; |
---|
765 | } |
---|
766 | } else { |
---|
767 | ImplicitCtorDtorStmt * implicit = strict_dynamic_cast< ImplicitCtorDtorStmt * > ( ctor ); |
---|
768 | ExprStmt * ctorStmt = dynamic_cast< ExprStmt * >( implicit->callStmt ); |
---|
769 | ApplicationExpr * ctorCall = nullptr; |
---|
770 | if ( ctorStmt && (ctorCall = isIntrinsicCallExpr( ctorStmt->expr )) && ctorCall->get_args().size() == 2 ) { |
---|
771 | // clean up intrinsic copy constructor calls by making them into SingleInits |
---|
772 | Expression * ctorArg = ctorCall->args.back(); |
---|
773 | std::swap( ctorArg->env, ctorCall->env ); |
---|
774 | objDecl->init = new SingleInit( ctorArg ); |
---|
775 | |
---|
776 | ctorCall->args.pop_back(); |
---|
777 | } else { |
---|
778 | stmtsToAddAfter.push_back( ctor ); |
---|
779 | objDecl->init = nullptr; |
---|
780 | ctorInit->ctor = nullptr; |
---|
781 | } |
---|
782 | |
---|
783 | Statement * dtor = ctorInit->dtor; |
---|
784 | if ( dtor ) { |
---|
785 | ImplicitCtorDtorStmt * implicit = strict_dynamic_cast< ImplicitCtorDtorStmt * >( dtor ); |
---|
786 | Statement * dtorStmt = implicit->callStmt; |
---|
787 | // don't need to call intrinsic dtor, because it does nothing, but |
---|
788 | // non-intrinsic dtors must be called |
---|
789 | if ( ! isIntrinsicSingleArgCallStmt( dtorStmt ) ) { |
---|
790 | // set dtor location to the object's location for error messages |
---|
791 | DeclarationWithType * dtorFunc = getDtorFunc( objDecl, dtorStmt, stmtsToAddBefore ); |
---|
792 | objDecl->attributes.push_back( new Attribute( "cleanup", { new VariableExpr( dtorFunc ) } ) ); |
---|
793 | // objDecl->attributes.push_back( new Attribute( "cleanup", { new NameExpr( dtorFunc->name ) } ) ); |
---|
794 | ctorInit->dtor = nullptr; |
---|
795 | } // if |
---|
796 | } |
---|
797 | } // if |
---|
798 | } else if ( Initializer * init = ctorInit->init ) { |
---|
799 | objDecl->init = init; |
---|
800 | ctorInit->init = nullptr; |
---|
801 | } else { |
---|
802 | // no constructor and no initializer, which is okay |
---|
803 | objDecl->init = nullptr; |
---|
804 | } // if |
---|
805 | delete ctorInit; |
---|
806 | } // if |
---|
807 | return objDecl; |
---|
808 | } |
---|
809 | |
---|
810 | void ObjDeclCollector::previsit( CompoundStmt * ) { |
---|
811 | GuardValue( curVars ); |
---|
812 | } |
---|
813 | |
---|
814 | void ObjDeclCollector::previsit( DeclStmt * stmt ) { |
---|
815 | // keep track of all variables currently in scope |
---|
816 | if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) { |
---|
817 | curVars.push_back( objDecl ); |
---|
818 | } // if |
---|
819 | } |
---|
820 | |
---|
821 | void LabelFinder::previsit( Statement * stmt ) { |
---|
822 | // for each label, remember the variables in scope at that label. |
---|
823 | for ( Label l : stmt->get_labels() ) { |
---|
824 | vars[l] = curVars; |
---|
825 | } // for |
---|
826 | } |
---|
827 | |
---|
828 | void LabelFinder::previsit( CompoundStmt * stmt ) { |
---|
829 | previsit( (Statement *)stmt ); |
---|
830 | Parent::previsit( stmt ); |
---|
831 | } |
---|
832 | |
---|
833 | void LabelFinder::previsit( DeclStmt * stmt ) { |
---|
834 | previsit( (Statement *)stmt ); |
---|
835 | Parent::previsit( stmt ); |
---|
836 | } |
---|
837 | |
---|
838 | |
---|
839 | void InsertDtors::previsit( FunctionDecl * funcDecl ) { |
---|
840 | // each function needs to have its own set of labels |
---|
841 | GuardValue( labelVars ); |
---|
842 | labelVars.clear(); |
---|
843 | // LabelFinder does not recurse into FunctionDecl, so need to visit |
---|
844 | // its children manually. |
---|
845 | maybeAccept( funcDecl->type, finder ); |
---|
846 | maybeAccept( funcDecl->statements, finder ); |
---|
847 | |
---|
848 | // all labels for this function have been collected, insert destructors as appropriate via implicit recursion. |
---|
849 | } |
---|
850 | |
---|
851 | // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the |
---|
852 | // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope |
---|
853 | // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user |
---|
854 | // of the error. See C++ Reference 6.6 Jump Statements for details. |
---|
855 | void InsertDtors::handleGoto( BranchStmt * stmt ) { |
---|
856 | // can't do anything for computed goto |
---|
857 | if ( stmt->computedTarget ) return; |
---|
858 | |
---|
859 | assertf( stmt->get_target() != "", "BranchStmt missing a label: %s", toString( stmt ).c_str() ); |
---|
860 | // S_L = lvars = set of objects in scope at label definition |
---|
861 | // S_G = curVars = set of objects in scope at goto statement |
---|
862 | ObjectSet & lvars = labelVars[ stmt->get_target() ]; |
---|
863 | |
---|
864 | DTOR_PRINT( |
---|
865 | std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl; |
---|
866 | std::cerr << "S_G = " << printSet( curVars ) << std::endl; |
---|
867 | std::cerr << "S_L = " << printSet( lvars ) << std::endl; |
---|
868 | ) |
---|
869 | |
---|
870 | ObjectSet diff; |
---|
871 | // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty |
---|
872 | std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) ); |
---|
873 | DTOR_PRINT( |
---|
874 | std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl; |
---|
875 | ) |
---|
876 | if ( ! diff.empty() ) { |
---|
877 | throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt ); |
---|
878 | } // if |
---|
879 | } |
---|
880 | |
---|
881 | void InsertDtors::previsit( BranchStmt * stmt ) { |
---|
882 | switch( stmt->get_type() ) { |
---|
883 | case BranchStmt::Continue: |
---|
884 | case BranchStmt::Break: |
---|
885 | // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should |
---|
886 | // always be empty), but it serves as a small sanity check. |
---|
887 | case BranchStmt::Goto: |
---|
888 | handleGoto( stmt ); |
---|
889 | break; |
---|
890 | default: |
---|
891 | assert( false ); |
---|
892 | } // switch |
---|
893 | } |
---|
894 | |
---|
895 | bool checkWarnings( FunctionDecl * funcDecl ) { |
---|
896 | // only check for warnings if the current function is a user-defined |
---|
897 | // constructor or destructor |
---|
898 | if ( ! funcDecl ) return false; |
---|
899 | if ( ! funcDecl->get_statements() ) return false; |
---|
900 | return CodeGen::isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() ); |
---|
901 | } |
---|
902 | |
---|
903 | void addIds( SymTab::Indexer & indexer, const std::list< DeclarationWithType * > & decls ) { |
---|
904 | for ( auto d : decls ) { |
---|
905 | indexer.addId( d ); |
---|
906 | } |
---|
907 | } |
---|
908 | |
---|
909 | void addTypes( SymTab::Indexer & indexer, const std::list< TypeDecl * > & tds ) { |
---|
910 | for ( auto td : tds ) { |
---|
911 | indexer.addType( td ); |
---|
912 | addIds( indexer, td->assertions ); |
---|
913 | } |
---|
914 | } |
---|
915 | |
---|
916 | void GenStructMemberCalls::previsit( StructDecl * structDecl ) { |
---|
917 | if ( ! dtorStruct && structDecl->name == "__Destructor" ) { |
---|
918 | dtorStruct = structDecl; |
---|
919 | } |
---|
920 | } |
---|
921 | |
---|
922 | void GenStructMemberCalls::previsit( FunctionDecl * funcDecl ) { |
---|
923 | GuardValue( function ); |
---|
924 | GuardValue( unhandled ); |
---|
925 | GuardValue( usedUninit ); |
---|
926 | GuardValue( thisParam ); |
---|
927 | GuardValue( isCtor ); |
---|
928 | GuardValue( structDecl ); |
---|
929 | errors = SemanticError(); // clear previous errors |
---|
930 | |
---|
931 | // need to start with fresh sets |
---|
932 | unhandled.clear(); |
---|
933 | usedUninit.clear(); |
---|
934 | |
---|
935 | if ( ! dtorStructDestroy && funcDecl->name == "__destroy_Destructor" ) { |
---|
936 | dtorStructDestroy = funcDecl; |
---|
937 | return; |
---|
938 | } |
---|
939 | |
---|
940 | function = funcDecl; |
---|
941 | isCtor = CodeGen::isConstructor( function->get_name() ); |
---|
942 | if ( checkWarnings( function ) ) { |
---|
943 | FunctionType * type = function->get_functionType(); |
---|
944 | assert( ! type->get_parameters().empty() ); |
---|
945 | thisParam = strict_dynamic_cast< ObjectDecl * >( type->get_parameters().front() ); |
---|
946 | Type * thisType = getPointerBase( thisParam->get_type() ); |
---|
947 | StructInstType * structType = dynamic_cast< StructInstType * >( thisType ); |
---|
948 | if ( structType ) { |
---|
949 | structDecl = structType->get_baseStruct(); |
---|
950 | if ( structDecl == dtorStruct ) return; |
---|
951 | for ( Declaration * member : structDecl->get_members() ) { |
---|
952 | if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) { |
---|
953 | // record all of the struct type's members that need to be constructed or |
---|
954 | // destructed by the end of the function |
---|
955 | unhandled.insert( field ); |
---|
956 | } |
---|
957 | } |
---|
958 | } |
---|
959 | } |
---|
960 | } |
---|
961 | |
---|
962 | void GenStructMemberCalls::postvisit( FunctionDecl * funcDecl ) { |
---|
963 | // remove the unhandled objects from usedUninit, because a call is inserted |
---|
964 | // to handle them - only objects that are later constructed are used uninitialized. |
---|
965 | std::map< DeclarationWithType *, CodeLocation > diff; |
---|
966 | // need the comparator since usedUninit and unhandled have different types |
---|
967 | struct comp_t { |
---|
968 | typedef decltype(usedUninit)::value_type usedUninit_t; |
---|
969 | typedef decltype(unhandled)::value_type unhandled_t; |
---|
970 | bool operator()(usedUninit_t x, unhandled_t y) { return x.first < y; } |
---|
971 | bool operator()(unhandled_t x, usedUninit_t y) { return x < y.first; } |
---|
972 | } comp; |
---|
973 | std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ), comp ); |
---|
974 | for ( auto p : diff ) { |
---|
975 | DeclarationWithType * member = p.first; |
---|
976 | CodeLocation loc = p.second; |
---|
977 | // xxx - make error message better by also tracking the location that the object is constructed at? |
---|
978 | emit( loc, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", member->get_name(), " used before being constructed" ); |
---|
979 | } |
---|
980 | |
---|
981 | if ( ! unhandled.empty() ) { |
---|
982 | // need to explicitly re-add function parameters to the indexer in order to resolve copy constructors |
---|
983 | auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this]() { indexer.leaveScope(); } ); |
---|
984 | addTypes( indexer, function->type->forall ); |
---|
985 | addIds( indexer, function->type->returnVals ); |
---|
986 | addIds( indexer, function->type->parameters ); |
---|
987 | |
---|
988 | // need to iterate through members in reverse in order for |
---|
989 | // ctor/dtor statements to come out in the right order |
---|
990 | for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) { |
---|
991 | DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member ); |
---|
992 | // skip non-DWT members |
---|
993 | if ( ! field ) continue; |
---|
994 | // skip non-constructable members |
---|
995 | if ( ! tryConstruct( field ) ) continue; |
---|
996 | // skip handled members |
---|
997 | if ( ! unhandled.count( field ) ) continue; |
---|
998 | |
---|
999 | // insert and resolve default/copy constructor call for each field that's unhandled |
---|
1000 | std::list< Statement * > stmt; |
---|
1001 | Expression * arg2 = 0; |
---|
1002 | if ( isCopyConstructor( function ) ) { |
---|
1003 | // if copy ctor, need to pass second-param-of-this-function.field |
---|
1004 | std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters(); |
---|
1005 | assert( params.size() == 2 ); |
---|
1006 | arg2 = new MemberExpr( field, new VariableExpr( params.back() ) ); |
---|
1007 | } |
---|
1008 | InitExpander srcParam( arg2 ); |
---|
1009 | // cast away reference type and construct field. |
---|
1010 | Expression * thisExpr = new CastExpr( new VariableExpr( thisParam ), thisParam->get_type()->stripReferences()->clone() ); |
---|
1011 | Expression * memberDest = new MemberExpr( field, thisExpr ); |
---|
1012 | SymTab::genImplicitCall( srcParam, memberDest, function->get_name(), back_inserter( stmt ), field, isCtor ); |
---|
1013 | |
---|
1014 | assert( stmt.size() <= 1 ); |
---|
1015 | if ( stmt.size() == 1 ) { |
---|
1016 | Statement * callStmt = stmt.front(); |
---|
1017 | |
---|
1018 | MutatingResolver resolver( indexer ); |
---|
1019 | try { |
---|
1020 | callStmt->acceptMutator( resolver ); |
---|
1021 | if ( isCtor ) { |
---|
1022 | function->statements->push_front( callStmt ); |
---|
1023 | } else { |
---|
1024 | // destructor statements should be added at the end |
---|
1025 | // function->get_statements()->push_back( callStmt ); |
---|
1026 | |
---|
1027 | // Destructor _dtor0 = { &b.a1, _destroy_A }; |
---|
1028 | std::list< Statement * > stmtsToAdd; |
---|
1029 | |
---|
1030 | static UniqueName memberDtorNamer = { "__memberDtor" }; |
---|
1031 | assertf( dtorStruct, "builtin __Destructor not found." ); |
---|
1032 | assertf( dtorStructDestroy, "builtin __destroy_Destructor not found." ); |
---|
1033 | |
---|
1034 | Expression * thisExpr = new AddressExpr( new VariableExpr( thisParam ) ); |
---|
1035 | Expression * dtorExpr = new VariableExpr( getDtorFunc( thisParam, callStmt, stmtsToAdd ) ); |
---|
1036 | |
---|
1037 | ObjectDecl * destructor = ObjectDecl::newObject( memberDtorNamer.newName(), new StructInstType( Type::Qualifiers(), dtorStruct ), new ListInit( { new SingleInit( thisExpr ), new SingleInit( dtorExpr ) } ) ); |
---|
1038 | function->statements->push_front( new DeclStmt( noLabels, destructor ) ); |
---|
1039 | destructor->attributes.push_back( new Attribute( "cleanup", { new VariableExpr( dtorStructDestroy ) } ) ); |
---|
1040 | |
---|
1041 | function->statements->kids.splice( function->statements->kids.begin(), stmtsToAdd ); |
---|
1042 | } |
---|
1043 | } catch ( SemanticError & error ) { |
---|
1044 | emit( funcDecl->location, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", field->get_name(), " not explicitly ", isCtor ? "constructed" : "destructed", " and no ", isCtor ? "default constructor" : "destructor", " found" ); |
---|
1045 | } |
---|
1046 | } |
---|
1047 | } |
---|
1048 | } |
---|
1049 | if (! errors.isEmpty()) { |
---|
1050 | throw errors; |
---|
1051 | } |
---|
1052 | } |
---|
1053 | |
---|
1054 | /// true if expr is effectively just the 'this' parameter |
---|
1055 | bool isThisExpression( Expression * expr, DeclarationWithType * thisParam ) { |
---|
1056 | // TODO: there are more complicated ways to pass 'this' to a constructor, e.g. &*, *&, etc. |
---|
1057 | if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) { |
---|
1058 | return varExpr->get_var() == thisParam; |
---|
1059 | } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * > ( expr ) ) { |
---|
1060 | return isThisExpression( castExpr->get_arg(), thisParam ); |
---|
1061 | } |
---|
1062 | return false; |
---|
1063 | } |
---|
1064 | |
---|
1065 | /// returns a MemberExpr if expr is effectively just member access on the 'this' parameter, else nullptr |
---|
1066 | MemberExpr * isThisMemberExpr( Expression * expr, DeclarationWithType * thisParam ) { |
---|
1067 | if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) { |
---|
1068 | if ( isThisExpression( memberExpr->get_aggregate(), thisParam ) ) { |
---|
1069 | return memberExpr; |
---|
1070 | } |
---|
1071 | } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) { |
---|
1072 | return isThisMemberExpr( castExpr->get_arg(), thisParam ); |
---|
1073 | } |
---|
1074 | return nullptr; |
---|
1075 | } |
---|
1076 | |
---|
1077 | void GenStructMemberCalls::previsit( ApplicationExpr * appExpr ) { |
---|
1078 | if ( ! checkWarnings( function ) ) { |
---|
1079 | visit_children = false; |
---|
1080 | return; |
---|
1081 | } |
---|
1082 | |
---|
1083 | std::string fname = getFunctionName( appExpr ); |
---|
1084 | if ( fname == function->get_name() ) { |
---|
1085 | // call to same kind of function |
---|
1086 | Expression * firstParam = appExpr->get_args().front(); |
---|
1087 | |
---|
1088 | if ( isThisExpression( firstParam, thisParam ) ) { |
---|
1089 | // if calling another constructor on thisParam, assume that function handles |
---|
1090 | // all members - if it doesn't a warning will appear in that function. |
---|
1091 | unhandled.clear(); |
---|
1092 | } else if ( MemberExpr * memberExpr = isThisMemberExpr( firstParam, thisParam ) ) { |
---|
1093 | // if first parameter is a member expression on the this parameter, |
---|
1094 | // then remove the member from unhandled set. |
---|
1095 | if ( isThisExpression( memberExpr->get_aggregate(), thisParam ) ) { |
---|
1096 | unhandled.erase( memberExpr->get_member() ); |
---|
1097 | } |
---|
1098 | } |
---|
1099 | } |
---|
1100 | } |
---|
1101 | |
---|
1102 | void GenStructMemberCalls::previsit( MemberExpr * memberExpr ) { |
---|
1103 | if ( ! checkWarnings( function ) || ! isCtor ) { |
---|
1104 | visit_children = false; |
---|
1105 | return; |
---|
1106 | } |
---|
1107 | |
---|
1108 | if ( isThisExpression( memberExpr->get_aggregate(), thisParam ) ) { |
---|
1109 | if ( unhandled.count( memberExpr->get_member() ) ) { |
---|
1110 | // emit a warning because a member was used before it was constructed |
---|
1111 | usedUninit.insert( { memberExpr->get_member(), memberExpr->location } ); |
---|
1112 | } |
---|
1113 | } |
---|
1114 | } |
---|
1115 | |
---|
1116 | template< typename Visitor, typename... Params > |
---|
1117 | void error( Visitor & v, CodeLocation loc, const Params &... params ) { |
---|
1118 | SemanticError err( toString( params... ) ); |
---|
1119 | err.set_location( loc ); |
---|
1120 | v.errors.append( err ); |
---|
1121 | } |
---|
1122 | |
---|
1123 | template< typename... Params > |
---|
1124 | void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) { |
---|
1125 | // toggle warnings vs. errors here. |
---|
1126 | // warn( params... ); |
---|
1127 | error( *this, loc, params... ); |
---|
1128 | } |
---|
1129 | |
---|
1130 | DeclarationWithType * MutatingResolver::mutate( ObjectDecl * objectDecl ) { |
---|
1131 | // add object to the indexer assumes that there will be no name collisions |
---|
1132 | // in generated code. If this changes, add mutate methods for entities with |
---|
1133 | // scope and call {enter,leave}Scope explicitly. |
---|
1134 | indexer.addId( objectDecl ); |
---|
1135 | return objectDecl; |
---|
1136 | } |
---|
1137 | |
---|
1138 | Expression * MutatingResolver::mutate( UntypedExpr * untypedExpr ) { |
---|
1139 | Expression * newExpr = untypedExpr; |
---|
1140 | ResolvExpr::findVoidExpression( newExpr, indexer ); |
---|
1141 | return newExpr; |
---|
1142 | } |
---|
1143 | |
---|
1144 | Expression * FixCtorExprs::postmutate( ConstructorExpr * ctorExpr ) { |
---|
1145 | static UniqueName tempNamer( "_tmp_ctor_expr" ); |
---|
1146 | // xxx - is the size check necessary? |
---|
1147 | assert( ctorExpr->result && ctorExpr->get_result()->size() == 1 ); |
---|
1148 | |
---|
1149 | // xxx - ideally we would reuse the temporary generated from the copy constructor passes from within firstArg if it exists and not generate a temporary if it's unnecessary. |
---|
1150 | ObjectDecl * tmp = ObjectDecl::newObject( tempNamer.newName(), ctorExpr->get_result()->clone(), nullptr ); |
---|
1151 | declsToAddBefore.push_back( tmp ); |
---|
1152 | |
---|
1153 | // xxx - this can be TupleAssignExpr now. Need to properly handle this case. |
---|
1154 | ApplicationExpr * callExpr = strict_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() ); |
---|
1155 | TypeSubstitution * env = ctorExpr->get_env(); |
---|
1156 | ctorExpr->set_callExpr( nullptr ); |
---|
1157 | ctorExpr->set_env( nullptr ); |
---|
1158 | delete ctorExpr; |
---|
1159 | |
---|
1160 | // build assignment and replace constructor's first argument with new temporary |
---|
1161 | Expression *& firstArg = callExpr->get_args().front(); |
---|
1162 | Expression * assign = new UntypedExpr( new NameExpr( "?=?" ), { new AddressExpr( new VariableExpr( tmp ) ), new AddressExpr( firstArg ) } ); |
---|
1163 | firstArg = new VariableExpr( tmp ); |
---|
1164 | |
---|
1165 | // resolve assignment and dispose of new env |
---|
1166 | ResolvExpr::findVoidExpression( assign, indexer ); |
---|
1167 | delete assign->env; |
---|
1168 | assign->env = nullptr; |
---|
1169 | |
---|
1170 | // for constructor expr: |
---|
1171 | // T x; |
---|
1172 | // x{}; |
---|
1173 | // results in: |
---|
1174 | // T x; |
---|
1175 | // T & tmp; |
---|
1176 | // &tmp = &x, ?{}(tmp), tmp |
---|
1177 | CommaExpr * commaExpr = new CommaExpr( assign, new CommaExpr( callExpr, new VariableExpr( tmp ) ) ); |
---|
1178 | commaExpr->set_env( env ); |
---|
1179 | return commaExpr; |
---|
1180 | } |
---|
1181 | } // namespace |
---|
1182 | } // namespace InitTweak |
---|
1183 | |
---|
1184 | // Local Variables: // |
---|
1185 | // tab-width: 4 // |
---|
1186 | // mode: c++ // |
---|
1187 | // compile-command: "make install" // |
---|
1188 | // End: // |
---|