source: src/InitTweak/FixInit.cc@ b8b6c442

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since b8b6c442 was bcc0946, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Minor code cleanup

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