source: src/InitTweak/FixInit.cc@ d82daa1

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 d82daa1 was be9288a, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Fixed errors made by the clean-up tool

  • Property mode set to 100644
File size: 54.9 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, 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 "Common/PassVisitor.h" // for PassVisitor, WithStmtsToAdd
32#include "Common/SemanticError.h" // for SemanticError
33#include "Common/UniqueName.h" // for UniqueName
34#include "Common/utility.h" // for CodeLocation, ValueGuard, toSt...
35#include "FixGlobalInit.h" // for fixGlobalInit
36#include "GenInit.h" // for genCtorDtor
37#include "GenPoly/DeclMutator.h" // for DeclMutator
38#include "GenPoly/GenPoly.h" // for getFunctionType
39#include "GenPoly/PolyMutator.h" // for PolyMutator
40#include "InitTweak.h" // for getFunctionName, getCallArg
41#include "Parser/LinkageSpec.h" // for C, Spec, Cforall, isBuiltin
42#include "ResolvExpr/Resolver.h" // for findVoidExpression
43#include "ResolvExpr/typeops.h" // for typesCompatible
44#include "SymTab/Autogen.h" // for genImplicitCall
45#include "SymTab/Indexer.h" // for Indexer
46#include "SymTab/Mangler.h" // for Mangler
47#include "SynTree/AddStmtVisitor.h" // for AddStmtVisitor
48#include "SynTree/Attribute.h" // for Attribute
49#include "SynTree/Constant.h" // for Constant
50#include "SynTree/Declaration.h" // for ObjectDecl, FunctionDecl, Decl...
51#include "SynTree/Expression.h" // for UniqueExpr, VariableExpr, Unty...
52#include "SynTree/Initializer.h" // for ConstructorInit, SingleInit
53#include "SynTree/Label.h" // for Label, noLabels, operator<
54#include "SynTree/Mutator.h" // for mutateAll, Mutator, maybeMutate
55#include "SynTree/Statement.h" // for ExprStmt, CompoundStmt, Branch...
56#include "SynTree/Type.h" // for Type, Type::StorageClasses
57#include "SynTree/TypeSubstitution.h" // for TypeSubstitution, operator<<
58#include "SynTree/Visitor.h" // for acceptAll, maybeAccept
59#include "Tuples/Tuples.h" // for isTtype
60
61bool ctordtorp = false; // print all debug
62bool ctorp = false; // print ctor debug
63bool cpctorp = false; // print copy ctor debug
64bool dtorp = false; // print dtor debug
65#define PRINT( text ) if ( ctordtorp ) { text }
66#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
67#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
68
69namespace InitTweak {
70 namespace {
71 typedef std::unordered_map< Expression *, TypeSubstitution * > EnvMap;
72 typedef std::unordered_map< int, int > UnqCount;
73
74 class InsertImplicitCalls : public WithTypeSubstitution {
75 public:
76 /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
77 /// function calls need their parameters to be copy constructed
78 static void insert( std::list< Declaration * > & translationUnit, EnvMap & envMap );
79
80 InsertImplicitCalls( EnvMap & envMap ) : envMap( envMap ) {}
81
82 Expression * postmutate( ApplicationExpr * appExpr );
83 void premutate( StmtExpr * stmtExpr );
84
85 // collects environments for relevant nodes
86 EnvMap & envMap;
87 };
88
89 class ResolveCopyCtors final : public SymTab::Indexer {
90 public:
91 /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
92 /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
93 /// arguments and return value temporaries
94 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap, UnqCount & unqCount );
95
96 typedef SymTab::Indexer Parent;
97 using Parent::visit;
98
99 ResolveCopyCtors( const EnvMap & envMap, UnqCount & unqCount ) : envMap( envMap ), unqCount( unqCount ) {}
100
101 virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
102 virtual void visit( UniqueExpr * unqExpr ) override;
103 virtual void visit( StmtExpr * stmtExpr ) override;
104
105 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
106 Expression * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
107 /// true if type does not need to be copy constructed to ensure correctness
108 bool skipCopyConstruct( Type * type );
109 void copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr );
110 void destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr );
111
112 TypeSubstitution * env;
113 const EnvMap & envMap;
114 UnqCount & unqCount; // count the number of times each unique expr ID appears
115 };
116
117 /// collects constructed object decls - used as a base class
118 class ObjDeclCollector : public AddStmtVisitor {
119 public:
120 typedef AddStmtVisitor Parent;
121 using Parent::visit;
122 // use ordered data structure to maintain ordering for set_difference and for consistent error messages
123 typedef std::list< ObjectDecl * > ObjectSet;
124 virtual void visit( CompoundStmt *compoundStmt ) override;
125 virtual void visit( DeclStmt *stmt ) override;
126
127 // don't go into other functions
128 virtual void visit( __attribute__((unused)) FunctionDecl *decl ) override {}
129
130 protected:
131 ObjectSet curVars;
132 };
133
134 // debug
135 template<typename ObjectSet>
136 struct PrintSet {
137 PrintSet( const ObjectSet & objs ) : objs( objs ) {}
138 const ObjectSet & objs;
139 };
140 template<typename ObjectSet>
141 PrintSet<ObjectSet> printSet( const ObjectSet & objs ) { return PrintSet<ObjectSet>( objs ); }
142 template<typename ObjectSet>
143 std::ostream & operator<<( std::ostream & out, const PrintSet<ObjectSet> & set) {
144 out << "{ ";
145 for ( ObjectDecl * obj : set.objs ) {
146 out << obj->get_name() << ", " ;
147 } // for
148 out << " }";
149 return out;
150 }
151
152 class LabelFinder final : public ObjDeclCollector {
153 public:
154 typedef ObjDeclCollector Parent;
155 typedef std::map< Label, ObjectSet > LabelMap;
156 // map of Label -> live variables at that label
157 LabelMap vars;
158
159 void handleStmt( Statement * stmt );
160
161 // xxx - This needs to be done better.
162 // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
163 // expressions, all statements, etc.) important to have this to provide a single entry point so that as new
164 // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
165 // every specialized class knows about every new kind of statement that might be added.
166 using Parent::visit;
167 virtual void visit( CompoundStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
168 virtual void visit( ExprStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
169 virtual void visit( AsmStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
170 virtual void visit( IfStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
171 virtual void visit( WhileStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
172 virtual void visit( ForStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
173 virtual void visit( SwitchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
174 virtual void visit( CaseStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
175 virtual void visit( BranchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
176 virtual void visit( ReturnStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
177 virtual void visit( TryStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
178 virtual void visit( CatchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
179 virtual void visit( FinallyStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
180 virtual void visit( NullStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
181 virtual void visit( DeclStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
182 virtual void visit( ImplicitCtorDtorStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
183 };
184
185 class InsertDtors final : public ObjDeclCollector {
186 public:
187 /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
188 /// (currently by FixInit)
189 static void insert( std::list< Declaration * > & translationUnit );
190
191 typedef ObjDeclCollector Parent;
192 typedef std::list< ObjectDecl * > OrderedDecls;
193 typedef std::list< OrderedDecls > OrderedDeclsStack;
194
195 InsertDtors( LabelFinder & finder ) : finder( finder ), labelVars( finder.vars ) {}
196
197 using Parent::visit;
198
199 virtual void visit( ObjectDecl * objDecl ) override;
200 virtual void visit( FunctionDecl * funcDecl ) override;
201
202 virtual void visit( CompoundStmt * compoundStmt ) override;
203 virtual void visit( ReturnStmt * returnStmt ) override;
204 virtual void visit( BranchStmt * stmt ) override;
205 private:
206 void handleGoto( BranchStmt * stmt );
207
208 LabelFinder & finder;
209 LabelFinder::LabelMap & labelVars;
210 OrderedDeclsStack reverseDeclOrder;
211 };
212
213 class FixInit : public WithStmtsToAdd {
214 public:
215 /// expand each object declaration to use its constructor after it is declared.
216 static void fixInitializers( std::list< Declaration * > &translationUnit );
217
218 DeclarationWithType * postmutate( ObjectDecl *objDecl );
219
220 std::list< Declaration * > staticDtorDecls;
221 };
222
223 class FixCopyCtors final : public GenPoly::PolyMutator {
224 public:
225 FixCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ){}
226 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
227 /// and destructors
228 static void fixCopyCtors( std::list< Declaration * > &translationUnit, UnqCount & unqCount );
229
230 typedef GenPoly::PolyMutator Parent;
231 using Parent::mutate;
232 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
233 virtual Expression * mutate( UniqueExpr * unqExpr ) override;
234 virtual Expression * mutate( StmtExpr * stmtExpr ) override;
235
236 UnqCount & unqCount;
237 };
238
239 class GenStructMemberCalls final : public SymTab::Indexer {
240 public:
241 typedef Indexer Parent;
242 /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
243 /// for any member that is missing a corresponding ctor/dtor call.
244 /// error if a member is used before constructed
245 static void generate( std::list< Declaration * > & translationUnit );
246
247 using Parent::visit;
248
249 virtual void visit( FunctionDecl * funcDecl ) override;
250
251 virtual void visit( MemberExpr * memberExpr ) override;
252 virtual void visit( ApplicationExpr * appExpr ) override;
253
254 SemanticError errors;
255 private:
256 void handleFirstParam( Expression * firstParam );
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 ( isConstructor( funcDecl->get_name() ) && ftype->get_parameters().size() == 2 ) {
382 Type * t1 = ftype->get_parameters().front()->get_type();
383 Type * t2 = ftype->get_parameters().back()->get_type();
384 PointerType * ptrType = safe_dynamic_cast< PointerType * > ( t1 );
385
386 if ( ResolvExpr::typesCompatible( ptrType->get_base(), 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 ( 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 ) || 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 ( ! result->get_lvalue() ) {
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 if ( callExpr->get_result()->get_lvalue() ) {
610 // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
611 // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
612 // type of the return temporary from T to T* to properly capture the return value. Then dereference
613 // the result of the comma expression, since the lvalue returning call was originally wrapped with
614 // an AddressExpr. Effectively, this turns
615 // lvalue T f();
616 // &*f();
617 // into
618 // T * f();
619 // T * tmp_cp_retN;
620 // &*(tmp_cp_retN = &*f(), tmp_cp_retN); // the first * and second & are generated here
621 // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
622 assign->get_args().back() = new AddressExpr( assign->get_args().back() );
623
624 returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
625 retExpr->set_result( new PointerType( Type::Qualifiers(), retExpr->get_result() ) );
626 retExpr = UntypedExpr::createDeref( retExpr );
627 } // if
628 // move env from callExpr to retExpr
629 retExpr->set_env( callExpr->get_env() );
630 callExpr->set_env( nullptr );
631 return retExpr;
632 } else {
633 return callExpr;
634 } // if
635 }
636
637 Expression * FixCopyCtors::mutate( StmtExpr * stmtExpr ) {
638 // function call temporaries should be placed at statement-level, rather than nested inside of a new statement expression,
639 // since temporaries can be shared across sub-expressions, e.g.
640 // [A, A] f();
641 // g([A] x, [A] y);
642 // f(g());
643 // f is executed once, so the return temporary is shared across the tuple constructors for x and y.
644 std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids();
645 for ( Statement *& stmt : stmts ) {
646 stmt = stmt->acceptMutator( *this );
647 } // for
648 // stmtExpr = safe_dynamic_cast< StmtExpr * >( Parent::mutate( stmtExpr ) );
649 assert( stmtExpr->get_result() );
650 Type * result = stmtExpr->get_result();
651 if ( ! result->isVoid() ) {
652 for ( ObjectDecl * obj : stmtExpr->get_returnDecls() ) {
653 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
654 } // for
655 // add destructors after current statement
656 for ( Expression * dtor : stmtExpr->get_dtors() ) {
657 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
658 } // for
659 // must have a non-empty body, otherwise it wouldn't have a result
660 CompoundStmt * body = stmtExpr->get_statements();
661 assert( ! body->get_kids().empty() );
662 assert( ! stmtExpr->get_returnDecls().empty() );
663 body->get_kids().push_back( new ExprStmt( noLabels, new VariableExpr( stmtExpr->get_returnDecls().front() ) ) );
664 stmtExpr->get_returnDecls().clear();
665 stmtExpr->get_dtors().clear();
666 }
667 assert( stmtExpr->get_returnDecls().empty() );
668 assert( stmtExpr->get_dtors().empty() );
669 return stmtExpr;
670 }
671
672 Expression * FixCopyCtors::mutate( UniqueExpr * unqExpr ) {
673 unqCount[ unqExpr->get_id() ]--;
674 static std::unordered_map< int, std::list< Statement * > > dtors;
675 static std::unordered_map< int, UniqueExpr * > unqMap;
676 static std::unordered_set< int > addDeref;
677 // has to be done to clean up ImplicitCopyCtorExpr nodes, even when this node was skipped in previous passes
678 if ( unqMap.count( unqExpr->get_id() ) ) {
679 // take data from other UniqueExpr to ensure consistency
680 delete unqExpr->get_expr();
681 unqExpr->set_expr( unqMap[unqExpr->get_id()]->get_expr()->clone() );
682 delete unqExpr->get_result();
683 unqExpr->set_result( maybeClone( unqExpr->get_expr()->get_result() ) );
684 if ( unqCount[ unqExpr->get_id() ] == 0 ) { // insert destructor after the last use of the unique expression
685 stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
686 }
687 if ( addDeref.count( unqExpr->get_id() ) ) {
688 // other UniqueExpr was dereferenced because it was an lvalue return, so this one should be too
689 return UntypedExpr::createDeref( unqExpr );
690 }
691 return unqExpr;
692 }
693 FixCopyCtors fixer( unqCount );
694 unqExpr->set_expr( unqExpr->get_expr()->acceptMutator( fixer ) ); // stmtexprs contained should not be separately fixed, so this must occur after the lookup
695 stmtsToAdd.splice( stmtsToAdd.end(), fixer.stmtsToAdd );
696 unqMap[unqExpr->get_id()] = unqExpr;
697 if ( unqCount[ unqExpr->get_id() ] == 0 ) { // insert destructor after the last use of the unique expression
698 stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
699 } else { // remember dtors for last instance of unique expr
700 dtors[ unqExpr->get_id() ] = fixer.stmtsToAddAfter;
701 }
702 if ( UntypedExpr * deref = dynamic_cast< UntypedExpr * >( unqExpr->get_expr() ) ) {
703 // unique expression is now a dereference, because the inner expression is an lvalue returning function call.
704 // Normalize the expression by dereferencing the unique expression, rather than the inner expression
705 // (i.e. move the dereference out a level)
706 assert( getFunctionName( deref ) == "*?" );
707 unqExpr->set_expr( getCallArg( deref, 0 ) );
708 getCallArg( deref, 0 ) = unqExpr;
709 addDeref.insert( unqExpr->get_id() );
710 return deref;
711 }
712 return unqExpr;
713 }
714
715 DeclarationWithType *FixInit::postmutate( ObjectDecl *objDecl ) {
716 // since this removes the init field from objDecl, it must occur after children are mutated (i.e. postmutate)
717 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
718 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
719 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
720 if ( Statement * ctor = ctorInit->get_ctor() ) {
721 if ( objDecl->get_storageClasses().is_static ) {
722 // originally wanted to take advantage of gcc nested functions, but
723 // we get memory errors with this approach. To remedy this, the static
724 // variable is hoisted when the destructor needs to be called.
725 //
726 // generate:
727 // static T __objName_static_varN;
728 // void __objName_dtor_atexitN() {
729 // __dtor__...;
730 // }
731 // int f(...) {
732 // ...
733 // static bool __objName_uninitialized = true;
734 // if (__objName_uninitialized) {
735 // __ctor(__objName);
736 // __objName_uninitialized = false;
737 // atexit(__objName_dtor_atexitN);
738 // }
739 // ...
740 // }
741
742 static UniqueName dtorCallerNamer( "_dtor_atexit" );
743
744 // static bool __objName_uninitialized = true
745 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
746 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant::from_int( 1 ) ) );
747 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, boolType, boolInitExpr );
748 isUninitializedVar->fixUniqueId();
749
750 // __objName_uninitialized = false;
751 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
752 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
753 setTrue->get_args().push_back( new ConstantExpr( Constant::from_int( 0 ) ) );
754
755 // generate body of if
756 CompoundStmt * initStmts = new CompoundStmt( noLabels );
757 std::list< Statement * > & body = initStmts->get_kids();
758 body.push_back( ctor );
759 body.push_back( new ExprStmt( noLabels, setTrue ) );
760
761 // put it all together
762 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
763 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
764 stmtsToAddAfter.push_back( ifStmt );
765
766 Statement * dtor = ctorInit->get_dtor();
767 objDecl->set_init( nullptr );
768 ctorInit->set_ctor( nullptr );
769 ctorInit->set_dtor( nullptr );
770 if ( dtor ) {
771 // if the object has a non-trivial destructor, have to
772 // hoist it and the object into the global space and
773 // call the destructor function with atexit.
774
775 Statement * dtorStmt = dtor->clone();
776
777 // void __objName_dtor_atexitN(...) {...}
778 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ) );
779 dtorCaller->fixUniqueId();
780 dtorCaller->get_statements()->push_back( dtorStmt );
781
782 // atexit(dtor_atexit);
783 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
784 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
785
786 body.push_back( new ExprStmt( noLabels, callAtexit ) );
787
788 // hoist variable and dtor caller decls to list of decls that will be added into global scope
789 staticDtorDecls.push_back( objDecl );
790 staticDtorDecls.push_back( dtorCaller );
791
792 // need to rename object uniquely since it now appears
793 // at global scope and there could be multiple function-scoped
794 // static variables with the same name in different functions.
795 // Note: it isn't sufficient to modify only the mangleName, because
796 // then subsequent Indexer passes can choke on seeing the object's name
797 // if another object has the same name and type. An unfortunate side-effect
798 // of renaming the object is that subsequent NameExprs may fail to resolve,
799 // but there shouldn't be any remaining past this point.
800 static UniqueName staticNamer( "_static_var" );
801 objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
802 objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
803
804 // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
805 // create a new object which is never used
806 static UniqueName dummyNamer( "_dummy" );
807 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") } );
808 delete ctorInit;
809 return dummy;
810 }
811 } else {
812 ImplicitCtorDtorStmt * implicit = safe_dynamic_cast< ImplicitCtorDtorStmt * > ( ctor );
813 ExprStmt * ctorStmt = dynamic_cast< ExprStmt * >( implicit->get_callStmt() );
814 ApplicationExpr * ctorCall = nullptr;
815 if ( ctorStmt && (ctorCall = isIntrinsicCallExpr( ctorStmt->get_expr() )) && ctorCall->get_args().size() == 2 ) {
816 // clean up intrinsic copy constructor calls by making them into SingleInits
817 objDecl->set_init( new SingleInit( ctorCall->get_args().back() ) );
818 ctorCall->get_args().pop_back();
819 } else {
820 stmtsToAddAfter.push_back( ctor );
821 objDecl->set_init( nullptr );
822 ctorInit->set_ctor( nullptr );
823 }
824 } // if
825 } else if ( Initializer * init = ctorInit->get_init() ) {
826 objDecl->set_init( init );
827 ctorInit->set_init( nullptr );
828 } else {
829 // no constructor and no initializer, which is okay
830 objDecl->set_init( nullptr );
831 } // if
832 delete ctorInit;
833 } // if
834 return objDecl;
835 }
836
837 void ObjDeclCollector::visit( CompoundStmt * compoundStmt ) {
838 ObjectSet prevVars = curVars;
839 Parent::visit( compoundStmt );
840 curVars = prevVars;
841 }
842
843 void ObjDeclCollector::visit( DeclStmt * stmt ) {
844 // keep track of all variables currently in scope
845 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
846 curVars.push_back( objDecl );
847 } // if
848 Parent::visit( stmt );
849 }
850
851 void LabelFinder::handleStmt( Statement * stmt ) {
852 // for each label, remember the variables in scope at that label.
853 for ( Label l : stmt->get_labels() ) {
854 vars[l] = curVars;
855 } // for
856 }
857
858 template<typename Iterator, typename OutputIterator>
859 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
860 for ( Iterator it = begin ; it != end ; ++it ) {
861 // extract destructor statement from the object decl and insert it into the output. Note that this is
862 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
863 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
864 // contain side effects.
865 ObjectDecl * objDecl = *it;
866 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
867 assert( ctorInit && ctorInit->get_dtor() );
868 *out++ = ctorInit->get_dtor()->clone();
869 } // for
870 }
871
872 void InsertDtors::visit( ObjectDecl * objDecl ) {
873 // remember non-static destructed objects so that their destructors can be inserted later
874 if ( ! objDecl->get_storageClasses().is_static ) {
875 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
876 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
877 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
878 Statement * dtor = ctorInit->get_dtor();
879 if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
880 // don't need to call intrinsic dtor, because it does nothing, but
881 // non-intrinsic dtors must be called
882 reverseDeclOrder.front().push_front( objDecl );
883 } // if
884 } // if
885 } // if
886 Parent::visit( objDecl );
887 }
888
889 template< typename Visitor >
890 void handleFuncDecl( FunctionDecl * funcDecl, Visitor & visitor ) {
891 maybeAccept( funcDecl->get_functionType(), visitor );
892 maybeAccept( funcDecl->get_statements(), visitor );
893 }
894
895 void InsertDtors::visit( FunctionDecl * funcDecl ) {
896 // each function needs to have its own set of labels
897 ValueGuard< LabelFinder::LabelMap > oldLabels( labelVars );
898 labelVars.clear();
899 handleFuncDecl( funcDecl, finder );
900
901 // all labels for this function have been collected, insert destructors as appropriate.
902 // can't be Parent::mutate, because ObjDeclCollector bottoms out on FunctionDecl
903 handleFuncDecl( funcDecl, *this );
904 }
905
906 void InsertDtors::visit( CompoundStmt * compoundStmt ) {
907 // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors
908 // when block is left, just the destructors associated with variables defined in this block, so push a new
909 // list to the top of the stack so that we can differentiate scopes
910 reverseDeclOrder.push_front( OrderedDecls() );
911 Parent::visit( compoundStmt );
912
913 // add destructors for the current scope that we're exiting, unless the last statement is a return, which
914 // causes unreachable code warnings
915 std::list< Statement * > & statements = compoundStmt->get_kids();
916 if ( ! statements.empty() && ! dynamic_cast< ReturnStmt * >( statements.back() ) ) {
917 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
918 }
919 reverseDeclOrder.pop_front();
920 }
921
922 void InsertDtors::visit( __attribute((unused)) ReturnStmt * returnStmt ) {
923 // return exits all scopes, so dump destructors for all scopes
924 for ( OrderedDecls & od : reverseDeclOrder ) {
925 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
926 } // for
927 }
928
929 // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
930 // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
931 // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
932 // of the error. See C++ Reference 6.6 Jump Statements for details.
933 void InsertDtors::handleGoto( BranchStmt * stmt ) {
934 assert( stmt->get_target() != "" && "BranchStmt missing a label" );
935 // S_L = lvars = set of objects in scope at label definition
936 // S_G = curVars = set of objects in scope at goto statement
937 ObjectSet & lvars = labelVars[ stmt->get_target() ];
938
939 DTOR_PRINT(
940 std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
941 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
942 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
943 )
944
945 ObjectSet diff;
946 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
947 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
948 DTOR_PRINT(
949 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
950 )
951 if ( ! diff.empty() ) {
952 throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
953 } // if
954 // S_G-S_L results in set of objects that must be destructed
955 diff.clear();
956 std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
957 DTOR_PRINT(
958 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
959 )
960 if ( ! diff.empty() ) {
961 // create an auxilliary set for fast lookup -- can't make diff a set, because diff ordering should be consistent for error messages.
962 std::unordered_set<ObjectDecl *> needsDestructor( diff.begin(), diff.end() );
963
964 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
965 OrderedDecls ordered;
966 for ( OrderedDecls & rdo : reverseDeclOrder ) {
967 // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
968 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return needsDestructor.count( objDecl ); } );
969 } // for
970 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
971 } // if
972 }
973
974 void InsertDtors::visit( BranchStmt * stmt ) {
975 switch( stmt->get_type() ) {
976 case BranchStmt::Continue:
977 case BranchStmt::Break:
978 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
979 // always be empty), but it serves as a small sanity check.
980 case BranchStmt::Goto:
981 handleGoto( stmt );
982 break;
983 default:
984 assert( false );
985 } // switch
986 }
987
988 bool checkWarnings( FunctionDecl * funcDecl ) {
989 // only check for warnings if the current function is a user-defined
990 // constructor or destructor
991 if ( ! funcDecl ) return false;
992 if ( ! funcDecl->get_statements() ) return false;
993 return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
994 }
995
996 void GenStructMemberCalls::visit( FunctionDecl * funcDecl ) {
997 ValueGuard< FunctionDecl * > oldFunction( funcDecl );
998 ValueGuard< std::set< DeclarationWithType * > > oldUnhandled( unhandled );
999 ValueGuard< std::map< DeclarationWithType *, CodeLocation > > oldUsedUninit( usedUninit );
1000 ValueGuard< ObjectDecl * > oldThisParam( thisParam );
1001 ValueGuard< bool > oldIsCtor( isCtor );
1002 ValueGuard< StructDecl * > oldStructDecl( structDecl );
1003 errors = SemanticError(); // clear previous errors
1004
1005 // need to start with fresh sets
1006 unhandled.clear();
1007 usedUninit.clear();
1008
1009 function = funcDecl;
1010 isCtor = isConstructor( function->get_name() );
1011 if ( checkWarnings( function ) ) {
1012 FunctionType * type = function->get_functionType();
1013 assert( ! type->get_parameters().empty() );
1014 thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
1015 PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() );
1016 StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() );
1017 if ( structType ) {
1018 structDecl = structType->get_baseStruct();
1019 for ( Declaration * member : structDecl->get_members() ) {
1020 if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
1021 // record all of the struct type's members that need to be constructed or
1022 // destructed by the end of the function
1023 unhandled.insert( field );
1024 }
1025 }
1026 }
1027 }
1028 Parent::visit( function );
1029
1030 // remove the unhandled objects from usedUninit, because a call is inserted
1031 // to handle them - only objects that are later constructed are used uninitialized.
1032 std::map< DeclarationWithType *, CodeLocation > diff;
1033 // need the comparator since usedUninit and unhandled have different types
1034 struct comp_t {
1035 typedef decltype(usedUninit)::value_type usedUninit_t;
1036 typedef decltype(unhandled)::value_type unhandled_t;
1037 bool operator()(usedUninit_t x, unhandled_t y) { return x.first < y; }
1038 bool operator()(unhandled_t x, usedUninit_t y) { return x < y.first; }
1039 } comp;
1040 std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ), comp );
1041 for ( auto p : diff ) {
1042 DeclarationWithType * member = p.first;
1043 CodeLocation loc = p.second;
1044 // xxx - make error message better by also tracking the location that the object is constructed at?
1045 emit( loc, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", member->get_name(), " used before being constructed" );
1046 }
1047
1048 if ( ! unhandled.empty() ) {
1049 // need to explicitly re-add function parameters in order to resolve copy constructors
1050 enterScope();
1051 maybeAccept( function->get_functionType(), *this );
1052
1053 // need to iterate through members in reverse in order for
1054 // ctor/dtor statements to come out in the right order
1055 for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
1056 DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member );
1057 // skip non-DWT members
1058 if ( ! field ) continue;
1059 // skip handled members
1060 if ( ! unhandled.count( field ) ) continue;
1061
1062 // insert and resolve default/copy constructor call for each field that's unhandled
1063 std::list< Statement * > stmt;
1064 UntypedExpr * deref = UntypedExpr::createDeref( new VariableExpr( thisParam ) );
1065
1066 Expression * arg2 = 0;
1067 if ( isCopyConstructor( function ) ) {
1068 // if copy ctor, need to pass second-param-of-this-function.field
1069 std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
1070 assert( params.size() == 2 );
1071 arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
1072 }
1073 InitExpander srcParam( arg2 );
1074 SymTab::genImplicitCall( srcParam, new MemberExpr( field, deref ), function->get_name(), back_inserter( stmt ), field, isCtor );
1075
1076 assert( stmt.size() <= 1 );
1077 if ( stmt.size() == 1 ) {
1078 Statement * callStmt = stmt.front();
1079
1080 MutatingResolver resolver( *this );
1081 try {
1082 callStmt->acceptMutator( resolver );
1083 if ( isCtor ) {
1084 function->get_statements()->push_front( callStmt );
1085 } else {
1086 // destructor statements should be added at the end
1087 function->get_statements()->push_back( callStmt );
1088 }
1089 } catch ( SemanticError & error ) {
1090 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" );
1091 }
1092 }
1093 }
1094 leaveScope();
1095 }
1096 if (! errors.isEmpty()) {
1097 throw errors;
1098 }
1099 }
1100
1101 void GenStructMemberCalls::visit( ApplicationExpr * appExpr ) {
1102 if ( ! checkWarnings( function ) ) return;
1103
1104 std::string fname = getFunctionName( appExpr );
1105 if ( fname == function->get_name() ) {
1106 // call to same kind of function
1107 Expression * firstParam = appExpr->get_args().front();
1108
1109 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) {
1110 // if calling another constructor on thisParam, assume that function handles
1111 // all members - if it doesn't a warning will appear in that function.
1112 if ( varExpr->get_var() == thisParam ) {
1113 unhandled.clear();
1114 }
1115 } else {
1116 // if first parameter is a member expression then
1117 // remove the member from unhandled set.
1118 handleFirstParam( firstParam );
1119 }
1120 }
1121
1122 Parent::visit( appExpr );
1123 }
1124
1125 void GenStructMemberCalls::handleFirstParam( Expression * firstParam ) {
1126 using namespace std;
1127 if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) {
1128 if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) {
1129 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
1130 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
1131 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
1132 if ( varExpr->get_var() == thisParam ) {
1133 unhandled.erase( memberExpr->get_member() );
1134 }
1135 }
1136 }
1137 }
1138 }
1139 }
1140 }
1141
1142 void GenStructMemberCalls::visit( MemberExpr * memberExpr ) {
1143 if ( ! checkWarnings( function ) ) return;
1144 if ( ! isCtor ) return;
1145
1146 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
1147 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
1148 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
1149 if ( varExpr->get_var() == thisParam ) {
1150 if ( unhandled.count( memberExpr->get_member() ) ) {
1151 // emit a warning because a member was used before it was constructed
1152 usedUninit.insert( { memberExpr->get_member(), memberExpr->location } );
1153 }
1154 }
1155 }
1156 }
1157 }
1158 Parent::visit( memberExpr );
1159 }
1160
1161 template< typename Visitor, typename... Params >
1162 void error( Visitor & v, CodeLocation loc, const Params &... params ) {
1163 SemanticError err( toString( params... ) );
1164 err.set_location( loc );
1165 v.errors.append( err );
1166 }
1167
1168 template< typename... Params >
1169 void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
1170 // toggle warnings vs. errors here.
1171 // warn( params... );
1172 error( *this, loc, params... );
1173 }
1174
1175 DeclarationWithType * MutatingResolver::mutate( ObjectDecl *objectDecl ) {
1176 // add object to the indexer assumes that there will be no name collisions
1177 // in generated code. If this changes, add mutate methods for entities with
1178 // scope and call {enter,leave}Scope explicitly.
1179 objectDecl->accept( indexer );
1180 return objectDecl;
1181 }
1182
1183 Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) {
1184 return safe_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) );
1185 }
1186
1187 Expression * FixCtorExprs::mutate( ConstructorExpr * ctorExpr ) {
1188 static UniqueName tempNamer( "_tmp_ctor_expr" );
1189 // xxx - is the size check necessary?
1190 assert( ctorExpr->has_result() && ctorExpr->get_result()->size() == 1 );
1191
1192 // 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.
1193 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, nullptr, ctorExpr->get_result()->clone(), nullptr );
1194 addDeclaration( tmp );
1195
1196 // xxx - this can be TupleAssignExpr now. Need to properly handle this case.
1197 ApplicationExpr * callExpr = safe_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
1198 TypeSubstitution * env = ctorExpr->get_env();
1199 ctorExpr->set_callExpr( nullptr );
1200 ctorExpr->set_env( nullptr );
1201
1202 Expression *& firstArg = callExpr->get_args().front();
1203 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
1204 assign->get_args().push_back( new VariableExpr( tmp ) );
1205 assign->get_args().push_back( firstArg );
1206 assign->set_result( ctorExpr->get_result()->clone() );
1207 firstArg = assign;
1208
1209 CommaExpr * commaExpr = new CommaExpr( callExpr, new VariableExpr( tmp ) );
1210 commaExpr->set_env( env );
1211 delete ctorExpr;
1212 return commaExpr;
1213 }
1214 } // namespace
1215} // namespace InitTweak
1216
1217// Local Variables: //
1218// tab-width: 4 //
1219// mode: c++ //
1220// compile-command: "make install" //
1221// End: //
Note: See TracBrowser for help on using the repository browser.