source: src/InitTweak/FixInit.cc@ 546e712

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum stuck-waitfor-destruct
Last change on this file since 546e712 was 546e712, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Fix for 1 bug of N

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