source: src/InitTweak/FixInit.cc@ a64644c

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 a64644c was 31f379c, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

add copy constructor code for StmtExpr, fix usage of environments in FixInit

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