Index: src/InitTweak/FixInit.cc
===================================================================
--- src/InitTweak/FixInit.cc	(revision 71a145de5bcbf8c7e9f1fd14beb7458d90bb060d)
+++ src/InitTweak/FixInit.cc	(revision c2931ea2efda8cee0e0cd69b27d7bea9755849eb)
@@ -16,4 +16,6 @@
 #include <stack>
 #include <list>
+#include <iterator>
+#include <algorithm>
 #include "FixInit.h"
 #include "InitTweak.h"
@@ -28,7 +30,13 @@
 #include "SymTab/Indexer.h"
 #include "GenPoly/PolyMutator.h"
+#include "SynTree/AddStmtVisitor.h"
 
 bool ctordtorp = false;
+bool ctorp = false;
+bool cpctorp = false;
+bool dtorp = true;
 #define PRINT( text ) if ( ctordtorp ) { text }
+#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
+#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
 
 namespace InitTweak {
@@ -36,429 +44,583 @@
 		const std::list<Label> noLabels;
 		const std::list<Expression*> noDesignators;
-	}
-
-	class InsertImplicitCalls : public GenPoly::PolyMutator {
-	public:
-		/// wrap function application expressions as ImplicitCopyCtorExpr nodes
-		/// so that it is easy to identify which function calls need their parameters
-		/// to be copy constructed
-		static void insert( std::list< Declaration * > & translationUnit );
-
-		virtual Expression * mutate( ApplicationExpr * appExpr );
-	};
-
-	class ResolveCopyCtors : public SymTab::Indexer {
-	public:
-		/// generate temporary ObjectDecls for each argument and return value of each
-		/// ImplicitCopyCtorExpr, generate/resolve copy construction expressions for each,
-		/// and generate/resolve destructors for both arguments and return value temporaries
-		static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
-
-		virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
-
-		/// create and resolve ctor/dtor expression: fname(var, [cpArg])
-		ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
-		/// true if type does not need to be copy constructed to ensure correctness
-		bool skipCopyConstruct( Type * );
-	private:
-		TypeSubstitution * env;
-	};
-
-	class FixInit : public GenPoly::PolyMutator {
-	  public:
-		/// expand each object declaration to use its constructor after it is declared.
-		/// insert destructor calls at the appropriate places
-		static void fixInitializers( std::list< Declaration * > &translationUnit );
-
-		virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
-
-		virtual CompoundStmt * mutate( CompoundStmt * compoundStmt );
-		virtual Statement * mutate( ReturnStmt * returnStmt );
-		virtual Statement * mutate( BranchStmt * branchStmt );
-
-	  private:
-		// stack of list of statements - used to differentiate scopes
-		std::list< std::list< Statement * > > dtorStmts;
-	};
-
-	class FixCopyCtors : public GenPoly::PolyMutator {
-	  public:
-		/// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors,
-		/// call expression, and destructors
-		static void fixCopyCtors( std::list< Declaration * > &translationUnit );
-
-		virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
-
-	  private:
-		// stack of list of statements - used to differentiate scopes
-		std::list< std::list< Statement * > > dtorStmts;
-	};
+
+		class InsertImplicitCalls : public GenPoly::PolyMutator {
+		public:
+			/// wrap function application expressions as ImplicitCopyCtorExpr nodes
+			/// so that it is easy to identify which function calls need their parameters
+			/// to be copy constructed
+			static void insert( std::list< Declaration * > & translationUnit );
+
+			virtual Expression * mutate( ApplicationExpr * appExpr );
+		};
+
+		class ResolveCopyCtors : public SymTab::Indexer {
+		public:
+			/// generate temporary ObjectDecls for each argument and return value of each
+			/// ImplicitCopyCtorExpr, generate/resolve copy construction expressions for each,
+			/// and generate/resolve destructors for both arguments and return value temporaries
+			static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
+
+			virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
+
+			/// create and resolve ctor/dtor expression: fname(var, [cpArg])
+			ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
+			/// true if type does not need to be copy constructed to ensure correctness
+			bool skipCopyConstruct( Type * );
+		private:
+			TypeSubstitution * env;
+		};
+
+		/// collects constructed object decls - used as a base class
+		class ObjDeclCollector : public AddStmtVisitor {
+		  public:
+			typedef AddStmtVisitor Parent;
+			using Parent::visit;
+			typedef std::set< ObjectDecl * > ObjectSet;
+			virtual void visit( CompoundStmt *compoundStmt );
+			virtual void visit( DeclStmt *stmt );
+		  protected:
+			ObjectSet curVars;
+		};
+
+		struct printSet {
+			typedef ObjDeclCollector::ObjectSet ObjectSet;
+			printSet( const ObjectSet & objs ) : objs( objs ) {}
+			const ObjectSet & objs;
+		};
+		std::ostream & operator<<( std::ostream & out, const printSet & set) {
+			out << "{ ";
+			for ( ObjectDecl * obj : set.objs ) {
+				out << obj->get_name() << ", " ;
+			}
+			out << " }";
+			return out;
+		}
+
+		class LabelFinder : public ObjDeclCollector {
+		  public:
+			typedef ObjDeclCollector Parent;
+			typedef std::map< Label, ObjectSet > LabelMap;
+			// map of Label -> live variables at that label
+			LabelMap vars;
+
+			void handleStmt( Statement * stmt );
+
+			// xxx - This needs to be done better.
+			// allow some generalization among different kinds of nodes with
+			// with similar parentage (e.g. all expressions, all statements, etc.)
+			// important to have this to provide a single entry point so that as
+			// new subclasses are added, there is only one place that the code has
+			// to be updated, rather than ensure that every specialized class knows
+			// about every new kind of statement that might be added.
+			virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( ChooseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( FallthruStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+			virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
+		};
+
+		class InsertDtors : public ObjDeclCollector {
+		public:
+			/// insert destructor calls at the appropriate places.
+			/// must happen before CtorInit nodes are removed (currently by FixInit)
+			static void insert( std::list< Declaration * > & translationUnit );
+
+			typedef ObjDeclCollector Parent;
+			typedef std::list< ObjectDecl * > OrderedDecls;
+			typedef std::list< OrderedDecls > OrderedDeclsStack;
+
+			InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {}
+
+			virtual void visit( ObjectDecl * objDecl );
+
+			virtual void visit( CompoundStmt * compoundStmt );
+			virtual void visit( ReturnStmt * returnStmt );
+			virtual void visit( BranchStmt * stmt );
+		private:
+			void handleGoto( BranchStmt * stmt );
+
+			LabelFinder::LabelMap & labelVars;
+			OrderedDeclsStack reverseDeclOrder;
+		};
+
+		class FixInit : public GenPoly::PolyMutator {
+		  public:
+			/// expand each object declaration to use its constructor after it is declared.
+			static void fixInitializers( std::list< Declaration * > &translationUnit );
+
+			virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
+		};
+
+		class FixCopyCtors : public GenPoly::PolyMutator {
+		  public:
+			/// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors,
+			/// call expression, and destructors
+			static void fixCopyCtors( std::list< Declaration * > &translationUnit );
+
+			virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
+		};
+	} // namespace
 
 	void fix( std::list< Declaration * > & translationUnit ) {
 		InsertImplicitCalls::insert( translationUnit );
 		ResolveCopyCtors::resolveImplicitCalls( translationUnit );
+		InsertDtors::insert( translationUnit );
 		FixInit::fixInitializers( translationUnit );
+
 		// FixCopyCtors must happen after FixInit, so that destructors are placed correctly
 		FixCopyCtors::fixCopyCtors( translationUnit );
 	}
 
-	void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
-		InsertImplicitCalls inserter;
-		mutateAll( translationUnit, inserter );
-	}
-
-	void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
-		ResolveCopyCtors resolver;
-		acceptAll( translationUnit, resolver );
-	}
-
-	void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
-		FixInit fixer;
-		mutateAll( translationUnit, fixer );
-	}
-
-	void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
-		FixCopyCtors fixer;
-		mutateAll( translationUnit, fixer );
-	}
-
-	Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
-		appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
-		assert( appExpr );
-
-		if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
-			if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
-				// optimization: don't need to copy construct in order to call intrinsic functions
-				return appExpr;
-			} else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
-				FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
-				assert( ftype );
-				if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
-					Type * t1 = ftype->get_parameters().front()->get_type();
-					Type * t2 = ftype->get_parameters().back()->get_type();
-					PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
-					assert( ptrType );
-
-					if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
-						// optimization: don't need to copy construct in order to call a copy constructor or
-						// assignment operator
+	namespace {
+		void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
+			InsertImplicitCalls inserter;
+			mutateAll( translationUnit, inserter );
+		}
+
+		void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
+			ResolveCopyCtors resolver;
+			acceptAll( translationUnit, resolver );
+		}
+
+		void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
+			FixInit fixer;
+			mutateAll( translationUnit, fixer );
+		}
+
+		void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
+			LabelFinder finder;
+			InsertDtors inserter( finder );
+			acceptAll( translationUnit, finder );
+			acceptAll( translationUnit, inserter );
+		}
+
+		void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
+			FixCopyCtors fixer;
+			mutateAll( translationUnit, fixer );
+		}
+
+		Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
+			appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
+			assert( appExpr );
+
+			if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
+				if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
+					// optimization: don't need to copy construct in order to call intrinsic functions
+					return appExpr;
+				} else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
+					FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
+					assert( ftype );
+					if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
+						Type * t1 = ftype->get_parameters().front()->get_type();
+						Type * t2 = ftype->get_parameters().back()->get_type();
+						PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
+						assert( ptrType );
+
+						if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
+							// optimization: don't need to copy construct in order to call a copy constructor or
+							// assignment operator
+							return appExpr;
+						}
+					} else if ( funcDecl->get_name() == "^?{}" ) {
+						// correctness: never copy construct arguments to a destructor
 						return appExpr;
 					}
-				} else if ( funcDecl->get_name() == "^?{}" ) {
-					// correctness: never copy construct arguments to a destructor
-					return appExpr;
 				}
 			}
-		}
-		PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
-
-		// wrap each function call so that it is easy to identify nodes that have to be copy constructed
-		ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
-		// save the type substitution onto the new node so that it is easy to find.
-		// Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
-		// The substitution is needed to obtain the type of temporary variables so that copy constructor
-		// calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
-		// copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
-		// saves the environment, or compute the types of temporaries here, but it's much simpler to
-		// save the environment here, and more cohesive to compute temporary variables and resolve copy
-		// constructor calls together.
-		assert( env );
-		expr->set_env( env );
-		return expr;
-	}
-
-	bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
-		return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
-	}
-
-	ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
-		assert( var );
-		UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
-		untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
-		if (cpArg) untyped->get_args().push_back( cpArg );
-
-		// resolve copy constructor
-		// should only be one alternative for copy ctor and dtor expressions, since
-		// all arguments are fixed (VariableExpr and already resolved expression)
-		PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
-		ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
-		if ( resolved->get_env() ) {
-			env->add( *resolved->get_env() );
-		}
-
-		assert( resolved );
-		delete untyped;
-		return resolved;
-	}
-
-	void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
-		static UniqueName tempNamer("_tmp_cp");
-		static UniqueName retNamer("_tmp_cp_ret");
-
-		PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
-		Visitor::visit( impCpCtorExpr );
-		env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
-
-		ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
-
-		// take each argument and attempt to copy construct it.
-		for ( Expression * & arg : appExpr->get_args() ) {
-			PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
-			// xxx - need to handle tuple arguments
-			assert( ! arg->get_results().empty() );
-			Type * result = arg->get_results().front();
-			if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
-			// type may involve type variables, so apply type substitution to get temporary variable's actual type
-			result = result->clone();
-			impCpCtorExpr->get_env()->apply( result );
-			ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
-			tmp->get_type()->set_isConst( false );
-
-			// create and resolve copy constructor
-			PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
-			ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
-
-			// if the chosen constructor is intrinsic, the copy is unnecessary, so
-			// don't create the temporary and don't call the copy constructor
-			VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
-			assert( function );
-			if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
-				// replace argument to function call with temporary
-				arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
-				impCpCtorExpr->get_tempDecls().push_back( tmp );
-				impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
-			}
-		}
-
-		// each return value from the call needs to be connected with an ObjectDecl
-		// at the call site, which is initialized with the return value and is destructed
-		// later
-		// xxx - handle multiple return values
-		ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
-		// xxx - is this right? callExpr may not have the right environment, because it was attached
-		// at a higher level. Trying to pass that environment along.
-		callExpr->set_env( impCpCtorExpr->get_env()->clone() );
-		for ( Type * result : appExpr->get_results() ) {
-			result = result->clone();
-			impCpCtorExpr->get_env()->apply( result );
-			ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
-			ret->get_type()->set_isConst( false );
-			impCpCtorExpr->get_returnDecls().push_back( ret );
-			PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
-			impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
-		}
-		PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
-	}
-
-
-	Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
-		PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
-
-		impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
-		assert( impCpCtorExpr );
-
-		std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
-		std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
-		std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
-
-		// add all temporary declarations and their constructors
-		for ( ObjectDecl * obj : tempDecls ) {
-			stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
-		}
-		for ( ObjectDecl * obj : returnDecls ) {
-			stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
-		}
-
-		// add destructors after current statement
-		for ( Expression * dtor : dtors ) {
-			stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
-		}
-
-		// xxx - update to work with multiple return values
-		ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
-		Expression * callExpr = impCpCtorExpr->get_callExpr();
-
-		PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
-
-		// detach fields from wrapper node so that it can be deleted without deleting too much
-		dtors.clear();
-		tempDecls.clear();
-		returnDecls.clear();
-		impCpCtorExpr->set_callExpr( NULL );
-		impCpCtorExpr->set_env( NULL );
-		delete impCpCtorExpr;
-
-		if ( returnDecl ) {
-			UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
-			assign->get_args().push_back( new VariableExpr( returnDecl ) );
-			assign->get_args().push_back( callExpr );
-			// know the result type of the assignment is the type of the LHS (minus the pointer), so
-			// add that onto the assignment expression so that later steps have the necessary information
-			assign->add_result( returnDecl->get_type()->clone() );
-
-			Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
-			if ( callExpr->get_results().front()->get_isLvalue() ) {
-				// lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any
-				// lvalue returning non-intrinsic function. Add an AddressExpr to the call to negate
-				// the derefence and change the type of the return temporary from T to T* to properly
-				// capture the return value. Then dereference the result of the comma expression, since
-				// the lvalue returning call was originally wrapped with an AddressExpr.
-				// Effectively, this turns
-				//   lvalue T f();
-				//   &*f()
-				// into
-				//   T * tmp_cp_retN;
-				//   tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
-				// which work out in terms of types, but is pretty messy. It would be nice to find a better way.
-				assign->get_args().back() = new AddressExpr( assign->get_args().back() );
-
-				Type * resultType = returnDecl->get_type()->clone();
-				returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
-				UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
-				deref->get_args().push_back( retExpr );
-				deref->add_result( resultType );
-				retExpr = deref;
-			}
-			// xxx - might need to set env on retExpr...
-			// retExpr->set_env( env->clone() );
-			return retExpr;
-		} else {
-			return callExpr;
-		}
-	}
-
-	DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
-		// first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors
-		// when the init is removed from the ObjectDecl
-		objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
-
-		if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
-			// a decision should have been made by the resolver, so ctor and init are not both non-NULL
-			assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
-			if ( Statement * ctor = ctorInit->get_ctor() ) {
-				if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
-					// generate:
-					// static bool __objName_uninitialized = true;
-					// if (__objName_uninitialized) {
-					//   __ctor(__objName);
-					//   void dtor_atexit() {
-					//     __dtor(__objName);
-					//   }
-					//   on_exit(dtorOnExit, &__objName);
-					//   __objName_uninitialized = false;
-					// }
-
-					// generate first line
-					BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
-					SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
-					ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
-					isUninitializedVar->fixUniqueId();
-
-					// void dtor_atexit(...) {...}
-					FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + "_dtor_atexit", DeclarationNode::NoStorageClass, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
-					dtorCaller->fixUniqueId();
-					dtorCaller->get_statements()->get_kids().push_back( ctorInit->get_dtor() );
-
-					// on_exit(dtor_atexit);
-					UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
-					callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
-
-					// __objName_uninitialized = false;
-					UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
-					setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
-					setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
-
-					// generate body of if
-					CompoundStmt * initStmts = new CompoundStmt( noLabels );
-					std::list< Statement * > & body = initStmts->get_kids();
-					body.push_back( ctor );
-					body.push_back( new DeclStmt( noLabels, dtorCaller ) );
-					body.push_back( new ExprStmt( noLabels, callAtexit ) );
-					body.push_back( new ExprStmt( noLabels, setTrue ) );
-
-					// put it all together
-					IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
-					stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
-					stmtsToAddAfter.push_back( ifStmt );
+			CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
+
+			// wrap each function call so that it is easy to identify nodes that have to be copy constructed
+			ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
+			// save the type substitution onto the new node so that it is easy to find.
+			// Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
+			// The substitution is needed to obtain the type of temporary variables so that copy constructor
+			// calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
+			// copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
+			// saves the environment, or compute the types of temporaries here, but it's much simpler to
+			// save the environment here, and more cohesive to compute temporary variables and resolve copy
+			// constructor calls together.
+			assert( env );
+			expr->set_env( env );
+			return expr;
+		}
+
+		bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
+			return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
+		}
+
+		ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
+			assert( var );
+			UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
+			untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
+			if (cpArg) untyped->get_args().push_back( cpArg );
+
+			// resolve copy constructor
+			// should only be one alternative for copy ctor and dtor expressions, since
+			// all arguments are fixed (VariableExpr and already resolved expression)
+			CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
+			ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
+			if ( resolved->get_env() ) {
+				env->add( *resolved->get_env() );
+			}
+
+			assert( resolved );
+			delete untyped;
+			return resolved;
+		}
+
+		void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
+			static UniqueName tempNamer("_tmp_cp");
+			static UniqueName retNamer("_tmp_cp_ret");
+
+			CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
+			Visitor::visit( impCpCtorExpr );
+			env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
+
+			ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
+
+			// take each argument and attempt to copy construct it.
+			for ( Expression * & arg : appExpr->get_args() ) {
+				CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
+				// xxx - need to handle tuple arguments
+				assert( ! arg->get_results().empty() );
+				Type * result = arg->get_results().front();
+				if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
+				// type may involve type variables, so apply type substitution to get temporary variable's actual type
+				result = result->clone();
+				impCpCtorExpr->get_env()->apply( result );
+				ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
+				tmp->get_type()->set_isConst( false );
+
+				// create and resolve copy constructor
+				CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
+				ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
+
+				// if the chosen constructor is intrinsic, the copy is unnecessary, so
+				// don't create the temporary and don't call the copy constructor
+				VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
+				assert( function );
+				if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
+					// replace argument to function call with temporary
+					arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
+					impCpCtorExpr->get_tempDecls().push_back( tmp );
+					impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
+				}
+			}
+
+			// each return value from the call needs to be connected with an ObjectDecl
+			// at the call site, which is initialized with the return value and is destructed
+			// later
+			// xxx - handle multiple return values
+			ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
+			// xxx - is this right? callExpr may not have the right environment, because it was attached
+			// at a higher level. Trying to pass that environment along.
+			callExpr->set_env( impCpCtorExpr->get_env()->clone() );
+			for ( Type * result : appExpr->get_results() ) {
+				result = result->clone();
+				impCpCtorExpr->get_env()->apply( result );
+				ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
+				ret->get_type()->set_isConst( false );
+				impCpCtorExpr->get_returnDecls().push_back( ret );
+				CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
+				impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
+			}
+			CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
+		}
+
+
+		Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
+			CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
+
+			impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
+			assert( impCpCtorExpr );
+
+			std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
+			std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
+			std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
+
+			// add all temporary declarations and their constructors
+			for ( ObjectDecl * obj : tempDecls ) {
+				stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
+			}
+			for ( ObjectDecl * obj : returnDecls ) {
+				stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
+			}
+
+			// add destructors after current statement
+			for ( Expression * dtor : dtors ) {
+				stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
+			}
+
+			// xxx - update to work with multiple return values
+			ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
+			Expression * callExpr = impCpCtorExpr->get_callExpr();
+
+			CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
+
+			// detach fields from wrapper node so that it can be deleted without deleting too much
+			dtors.clear();
+			tempDecls.clear();
+			returnDecls.clear();
+			impCpCtorExpr->set_callExpr( NULL );
+			impCpCtorExpr->set_env( NULL );
+			delete impCpCtorExpr;
+
+			if ( returnDecl ) {
+				UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
+				assign->get_args().push_back( new VariableExpr( returnDecl ) );
+				assign->get_args().push_back( callExpr );
+				// know the result type of the assignment is the type of the LHS (minus the pointer), so
+				// add that onto the assignment expression so that later steps have the necessary information
+				assign->add_result( returnDecl->get_type()->clone() );
+
+				Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
+				if ( callExpr->get_results().front()->get_isLvalue() ) {
+					// lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any
+					// lvalue returning non-intrinsic function. Add an AddressExpr to the call to negate
+					// the derefence and change the type of the return temporary from T to T* to properly
+					// capture the return value. Then dereference the result of the comma expression, since
+					// the lvalue returning call was originally wrapped with an AddressExpr.
+					// Effectively, this turns
+					//   lvalue T f();
+					//   &*f()
+					// into
+					//   T * tmp_cp_retN;
+					//   tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
+					// which work out in terms of types, but is pretty messy. It would be nice to find a better way.
+					assign->get_args().back() = new AddressExpr( assign->get_args().back() );
+
+					Type * resultType = returnDecl->get_type()->clone();
+					returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
+					UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
+					deref->get_args().push_back( retExpr );
+					deref->add_result( resultType );
+					retExpr = deref;
+				}
+				// xxx - might need to set env on retExpr...
+				// retExpr->set_env( env->clone() );
+				return retExpr;
+			} else {
+				return callExpr;
+			}
+		}
+
+		DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
+			// first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors
+			// when the init is removed from the ObjectDecl
+			objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
+
+			if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
+				// a decision should have been made by the resolver, so ctor and init are not both non-NULL
+				assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
+				if ( Statement * ctor = ctorInit->get_ctor() ) {
+					if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
+						// generate:
+						// static bool __objName_uninitialized = true;
+						// if (__objName_uninitialized) {
+						//   __ctor(__objName);
+						//   void dtor_atexit() {
+						//     __dtor(__objName);
+						//   }
+						//   on_exit(dtorOnExit, &__objName);
+						//   __objName_uninitialized = false;
+						// }
+
+						// generate first line
+						BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
+						SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
+						ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
+						isUninitializedVar->fixUniqueId();
+
+						// void dtor_atexit(...) {...}
+						FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + "_dtor_atexit", DeclarationNode::NoStorageClass, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
+						dtorCaller->fixUniqueId();
+						dtorCaller->get_statements()->get_kids().push_back( ctorInit->get_dtor() );
+
+						// on_exit(dtor_atexit);
+						UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
+						callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
+
+						// __objName_uninitialized = false;
+						UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
+						setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
+						setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
+
+						// generate body of if
+						CompoundStmt * initStmts = new CompoundStmt( noLabels );
+						std::list< Statement * > & body = initStmts->get_kids();
+						body.push_back( ctor );
+						body.push_back( new DeclStmt( noLabels, dtorCaller ) );
+						body.push_back( new ExprStmt( noLabels, callAtexit ) );
+						body.push_back( new ExprStmt( noLabels, setTrue ) );
+
+						// put it all together
+						IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
+						stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
+						stmtsToAddAfter.push_back( ifStmt );
+					} else {
+						stmtsToAddAfter.push_back( ctor );
+					}
+					objDecl->set_init( NULL );
+					ctorInit->set_ctor( NULL );
+				} else if ( Initializer * init = ctorInit->get_init() ) {
+					objDecl->set_init( init );
+					ctorInit->set_init( NULL );
 				} else {
-					stmtsToAddAfter.push_back( ctor );
-					dtorStmts.back().push_front( ctorInit->get_dtor() );
+					// no constructor and no initializer, which is okay
+					objDecl->set_init( NULL );
 				}
-				objDecl->set_init( NULL );
-				ctorInit->set_ctor( NULL );
-				ctorInit->set_dtor( NULL );  // xxx - only destruct when constructing? Probably not?
-			} else if ( Initializer * init = ctorInit->get_init() ) {
-				objDecl->set_init( init );
-				ctorInit->set_init( NULL );
-			} else {
-				// no constructor and no initializer, which is okay
-				objDecl->set_init( NULL );
-			}
-			delete ctorInit;
-		}
-		return objDecl;
-	}
-
-	namespace {
+				delete ctorInit;
+			}
+			return objDecl;
+		}
+
+		void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) {
+			std::set< ObjectDecl * > prevVars = curVars;
+			Parent::visit( compoundStmt );
+			curVars = prevVars;
+		}
+
+		void ObjDeclCollector::visit( DeclStmt *stmt ) {
+			if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
+				curVars.insert( objDecl );
+			}
+			return Parent::visit( stmt );
+		}
+
+		void LabelFinder::handleStmt( Statement * stmt ) {
+			for ( Label l : stmt->get_labels() ) {
+				vars[l] = curVars;
+			}
+		}
+
 		template<typename Iterator, typename OutputIterator>
 		void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
 			for ( Iterator it = begin ; it != end ; ++it ) {
-				// remove if instrinsic destructor statement. Note that this is only called
-				// on lists of implicit dtors, so if the user manually calls an intrinsic
-				// dtor then the call must (and will) still be generated since the argument
-				// may contain side effects.
-				if ( ! isInstrinsicSingleArgCallStmt( *it ) ) {
-					// don't need to call intrinsic dtor, because it does nothing, but
-					// non-intrinsic dtors must be called
-					*out++ = (*it)->clone();
+				// extract destructor statement from the object decl and
+				// insert it into the output. Note that this is only called
+				// on lists of non-static objects with implicit non-intrinsic
+				// dtors, so if the user manually calls an intrinsic dtor
+				// then the call must (and will) still be generated since
+				// the argument may contain side effects.
+				ObjectDecl * objDecl = *it;
+				ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
+				assert( ctorInit && ctorInit->get_dtor() );
+				*out++ = ctorInit->get_dtor()->clone();
+			}
+		}
+
+		void InsertDtors::visit( ObjectDecl * objDecl ) {
+			// remember non-static destructed objects so that their destructors can be inserted later
+			if ( objDecl->get_storageClass() != DeclarationNode::Static ) {
+				if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
+					// a decision should have been made by the resolver, so ctor and init are not both non-NULL
+					assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
+					Statement * dtor = ctorInit->get_dtor();
+					if ( dtor && ! isInstrinsicSingleArgCallStmt( dtor ) ) {
+						// don't need to call intrinsic dtor, because it does nothing, but
+						// non-intrinsic dtors must be called
+						reverseDeclOrder.front().push_front( objDecl );
+					}
 				}
 			}
-		}
-	}
-
-	CompoundStmt * FixInit::mutate( CompoundStmt * compoundStmt ) {
-		// mutate statements - this will also populate dtorStmts list.
-		// don't want to dump all destructors when block is left,
-		// just the destructors associated with variables defined in this block,
-		// so push a new list to the top of the stack so that we can differentiate scopes
-		dtorStmts.push_back( std::list<Statement *>() );
-
-		compoundStmt = PolyMutator::mutate( compoundStmt );
-		std::list< Statement * > & statements = compoundStmt->get_kids();
-
-		insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( statements ) );
-
-		deleteAll( dtorStmts.back() );
-		dtorStmts.pop_back();
-		return compoundStmt;
-	}
-
-	Statement * FixInit::mutate( ReturnStmt * returnStmt ) {
-		for ( std::list< std::list< Statement * > >::reverse_iterator list = dtorStmts.rbegin(); list != dtorStmts.rend(); ++list ) {
-			insertDtors( list->begin(), list->end(), back_inserter( stmtsToAdd ) );
-		}
-		return Mutator::mutate( returnStmt );
-	}
-
-	Statement * FixInit::mutate( BranchStmt * branchStmt ) {
-		// TODO: adding to the end of a block isn't sufficient, since
-		// return/break/goto should trigger destructor when block is left.
-		switch( branchStmt->get_type() ) {
-			case BranchStmt::Continue:
-			case BranchStmt::Break:
-				insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( stmtsToAdd ) );
-				break;
-			case BranchStmt::Goto:
-				// xxx
-				// if goto leaves a block, generate dtors for every block it leaves
-				// if goto is in same block but earlier statement, destruct every object that was defined after the statement
-				break;
-			default:
-				assert( false );
-		}
-		return Mutator::mutate( branchStmt );
-	}
-
-
+			Parent::visit( objDecl );
+		}
+
+		void InsertDtors::visit( CompoundStmt * compoundStmt ) {
+			// visit statements - this will also populate reverseDeclOrder list.
+			// don't want to dump all destructors when block is left,
+			// just the destructors associated with variables defined in this block,
+			// so push a new list to the top of the stack so that we can differentiate scopes
+			reverseDeclOrder.push_front( OrderedDecls() );
+			Parent::visit( compoundStmt );
+
+			std::list< Statement * > & statements = compoundStmt->get_kids();
+			insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
+
+			// xxx - ??
+			// deleteAll( dtorStmts.back() );
+			reverseDeclOrder.pop_front();
+		}
+
+		void InsertDtors::visit( ReturnStmt * returnStmt ) {
+			for ( OrderedDecls & od : reverseDeclOrder ) {
+				insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
+			}
+		}
+
+		void InsertDtors::handleGoto( BranchStmt * stmt ) {
+			assert( stmt->get_type() == BranchStmt::Goto );
+			// S_L = lvars = set of objects in scope at label definition
+			// S_G = curVars = set of objects in scope at goto statement
+			ObjectSet & lvars = labelVars[ stmt->get_target() ];
+
+			DTOR_PRINT(
+				std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
+				std::cerr << "S_G = " << printSet( curVars ) << std::endl;
+				std::cerr << "S_L = " << printSet( lvars ) << std::endl;
+			)
+
+			ObjectSet diff;
+			// S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
+			std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
+			DTOR_PRINT(
+				std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
+			)
+			if ( ! diff.empty() ) {
+				throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
+			}
+			// S_G-S_L results in set of objects that must be destructed
+			diff.clear();
+			std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
+			DTOR_PRINT(
+				std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
+			)
+			if ( ! diff.empty() ) {
+				// go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
+				OrderedDecls ordered;
+				for ( OrderedDecls & rdo : reverseDeclOrder ) {
+					// add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
+					copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
+				}
+				insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
+			}
+		}
+
+		void InsertDtors::visit( BranchStmt * stmt ) {
+			// TODO: adding to the end of a block isn't sufficient, since
+			// return/break/goto should trigger destructor when block is left.
+			switch( stmt->get_type() ) {
+				case BranchStmt::Continue:
+				case BranchStmt::Break:
+				// xxx - easiest thing to do: generate a label for every break/continue
+				// this label is unused, so attach unused attribute to it
+				// finally, all of these cases can be the same (this is less efficient than it could be,
+				// because the S_L-S_G check is unnecessary [the set should always be empty], but this
+				// serves as a bit of a sanity check, so I'm okay with it.)
+					// xxx - this is insufficient, because multiple blocks can be opened in a switch or loop
+					insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( stmtsToAdd ) );
+					break;
+				case BranchStmt::Goto:
+					handleGoto( stmt );
+					break;
+				default:
+					assert( false );
+			}
+		}
+	} // namespace
 } // namespace InitTweak
 
