source: src/InitTweak/FixInit.cc@ babeeda

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 stuck-waitfor-destruct with_gc
Last change on this file since babeeda was babeeda, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Implement self assignment warning

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