source: src/InitTweak/FixInit.cc@ a180ded

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

Run ResolveCopyCtors on StmtExpr generated as part of a TupleAssignExpr to generate result temporary and ctor/dtor

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