source: src/InitTweak/FixInit.cc@ 9a707e4e

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 9a707e4e was 9a707e4e, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Convert GenStructMemberCalls to PassVisitor

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