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