source: src/InitTweak/FixInit.cc@ cdd1695

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

Removed more warnings

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