Index: src/CodeGen/CodeGenerator.cc
===================================================================
--- src/CodeGen/CodeGenerator.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/CodeGen/CodeGenerator.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -48,21 +48,36 @@
 	}
 
-	ostream & CodeGenerator::Indenter::operator()( ostream & output ) {
+	ostream & CodeGenerator::Indenter::operator()( ostream & output ) const {
 	  return output << string( cg.cur_indent, ' ' );
 	}
 
-	ostream & operator<<( ostream & output, CodeGenerator::Indenter &indent ) {
+	ostream & operator<<( ostream & output, const CodeGenerator::Indenter &indent ) {
 		return indent( output );
 	}
 
-	CodeGenerator::CodeGenerator( std::ostream &os ) : indent( *this), cur_indent( 0 ), insideFunction( false ), output( os ) { }
+	CodeGenerator::LabelPrinter & CodeGenerator::LabelPrinter::operator()( std::list< Label > & l ) {
+		labels = &l;
+		return *this;
+	}
+
+	ostream & operator<<( ostream & output, CodeGenerator::LabelPrinter &printLabels ) {
+		std::list< Label > & labs = *printLabels.labels;
+		// l.unique(); // assumes a sorted list. Why not use set? Does order matter?
+		for ( Label & l : labs ) {
+			output << l.get_name() + ": ";
+			printLabels.cg.genAttributes( l.get_attributes() );
+		}
+		return output;
+	}
+
+	CodeGenerator::CodeGenerator( std::ostream &os ) : indent( *this), cur_indent( 0 ), insideFunction( false ), output( os ), printLabels( *this ) { }
 
 	CodeGenerator::CodeGenerator( std::ostream &os, std::string init, int indentation, bool infunp )
-			: indent( *this), cur_indent( indentation ), insideFunction( infunp ), output( os ) {
+			: indent( *this), cur_indent( indentation ), insideFunction( infunp ), output( os ), printLabels( *this ) {
 		//output << std::string( init );
 	}
 
 	CodeGenerator::CodeGenerator( std::ostream &os, char *init, int indentation, bool infunp )
-			: indent( *this ), cur_indent( indentation ), insideFunction( infunp ), output( os ) {
+			: indent( *this ), cur_indent( indentation ), insideFunction( infunp ), output( os ), printLabels( *this ) {
 		//output << std::string( init );
 	}
@@ -735,9 +750,5 @@
 	void CodeGenerator::visit( ReturnStmt *returnStmt ) {
 		output << "return ";
-
-		// xxx -- check for null expression;
-		if ( returnStmt->get_expr() ) {
-			returnStmt->get_expr()->accept( *this );
-		} // if
+		maybeAccept( returnStmt->get_expr(), *this );
 		output << ";";
 	}
@@ -799,14 +810,4 @@
 			output << ";";
 		} // if
-	}
-
-	std::string CodeGenerator::printLabels( std::list< Label > &l ) {
-		std::string str( "" );
-		l.unique(); // assumes a sorted list. Why not use set?
-
-		for ( std::list< Label >::iterator i = l.begin(); i != l.end(); i++ )
-			str += *i + ": ";
-
-		return str;
 	}
 
Index: src/CodeGen/CodeGenerator.h
===================================================================
--- src/CodeGen/CodeGenerator.h	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/CodeGen/CodeGenerator.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -94,5 +94,12 @@
 			Indenter(CodeGenerator &cg) : cg(cg) {}
 			CodeGenerator & cg;
-			std::ostream& operator()(std::ostream & os);
+			std::ostream& operator()(std::ostream & os) const;
+		};
+
+		struct LabelPrinter {
+			LabelPrinter(CodeGenerator &cg) : cg(cg), labels( 0 ) {}
+			LabelPrinter & operator()( std::list< Label > & l );
+			CodeGenerator & cg;
+			std::list< Label > * labels;
 		};
 
@@ -108,7 +115,7 @@
 		bool insideFunction;
 		std::ostream &output;
+		LabelPrinter printLabels;
 
 		void printDesignators( std::list< Expression * > & );
-		static std::string printLabels ( std::list < Label > & );
 		void handleStorageClass( Declaration *decl );
 		void handleAggregate( AggregateDecl *aggDecl );
Index: src/ControlStruct/LabelFixer.cc
===================================================================
--- src/ControlStruct/LabelFixer.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/ControlStruct/LabelFixer.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -5,5 +5,5 @@
 // file "LICENCE" distributed with Cforall.
 //
-// LabelFixer.cc -- 
+// LabelFixer.cc --
 //
 // Author           : Rodolfo G. Esteves
@@ -86,5 +86,5 @@
 
 
-	// sets the definition of the labelTable entry to be the provided 
+	// sets the definition of the labelTable entry to be the provided
 	// statement for every label in the list parameter. Happens for every kind of statement
 	Label LabelFixer::setLabelsDef( std::list< Label > &llabel, Statement *definition ) {
@@ -95,24 +95,26 @@
 
 		for ( std::list< Label >::iterator i = llabel.begin(); i != llabel.end(); i++ ) {
-			if ( labelTable.find( *i ) == labelTable.end() ) {
+			Label & l = *i;
+			l.set_statement( definition ); // attach statement to the label to be used later
+			if ( labelTable.find( l ) == labelTable.end() ) {
 				// all labels on this statement need to use the same entry, so this should only be created once
 				// undefined and unused until now, add an entry
-				labelTable[ *i ] =  e;
-			} else if ( labelTable[ *i ]->defined() ) {
+				labelTable[ l ] =  e;
+			} else if ( labelTable[ l ]->defined() ) {
 				// defined twice, error
-				throw SemanticError( "Duplicate definition of label: " + *i );
+				throw SemanticError( "Duplicate definition of label: " + l.get_name() );
 			}	else {
 				// used previously, but undefined until now -> link with this entry
-				delete labelTable[ *i ];
-				labelTable[ *i ] = e;
+				delete labelTable[ l ];
+				labelTable[ l ] = e;
 			} // if
 		} // for
 
-		// produce one of the labels attached to this statement to be 
+		// produce one of the labels attached to this statement to be
 		// temporarily used as the canonical label
 		return labelTable[ llabel.front() ]->get_label();
 	}
 
-	// A label was used, add it ot the table if it isn't already there
+	// A label was used, add it to the table if it isn't already there
 	template< typename UsageNode >
 	void LabelFixer::setLabelsUsg( Label orgValue, UsageNode *use ) {
@@ -130,5 +132,5 @@
 		for ( std::map< Label, Entry * >::iterator i = labelTable.begin(); i != labelTable.end(); ++i ) {
 			if ( ! i->second->defined() ) {
-				throw SemanticError( "Use of undefined label: " + i->first );
+				throw SemanticError( "Use of undefined label: " + i->first.get_name() );
 			}
 			(*ret)[ i->first ] = i->second->get_definition();
Index: src/ControlStruct/LabelFixer.h
===================================================================
--- src/ControlStruct/LabelFixer.h	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/ControlStruct/LabelFixer.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -5,5 +5,5 @@
 // file "LICENCE" distributed with Cforall.
 //
-// LabelFixer.h -- 
+// LabelFixer.h --
 //
 // Author           : Rodolfo G. Esteves
@@ -20,6 +20,6 @@
 #include "SynTree/SynTree.h"
 #include "SynTree/Visitor.h"
+#include "SynTree/Label.h"
 #include "LabelGenerator.h"
-
 #include <map>
 
@@ -74,8 +74,8 @@
 
 		  private:
-			Label label;  
+			Label label;
 			Statement *definition;
 		};
-	          
+
 		std::map < Label, Entry *> labelTable;
 		LabelGenerator *generator;
Index: src/ControlStruct/LabelGenerator.cc
===================================================================
--- src/ControlStruct/LabelGenerator.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/ControlStruct/LabelGenerator.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -5,5 +5,5 @@
 // file "LICENCE" distributed with Cforall.
 //
-// LabelGenerator.cc -- 
+// LabelGenerator.cc --
 //
 // Author           : Rodolfo G. Esteves
@@ -18,4 +18,6 @@
 
 #include "LabelGenerator.h"
+#include "SynTree/Label.h"
+#include "SynTree/Attribute.h"
 
 namespace ControlStruct {
@@ -33,5 +35,7 @@
 		os << "__L" << current++ << "__" << suffix;
 		std::string ret = os.str();
-		return Label( ret );
+		Label l( ret );
+		l.get_attributes().push_back( new Attribute("unused") );
+		return l;
 	}
 } // namespace ControlStruct
Index: src/ControlStruct/MLEMutator.cc
===================================================================
--- src/ControlStruct/MLEMutator.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/ControlStruct/MLEMutator.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -5,5 +5,5 @@
 // file "LICENCE" distributed with Cforall.
 //
-// MLEMutator.cc -- 
+// MLEMutator.cc --
 //
 // Author           : Rodolfo G. Esteves
@@ -14,5 +14,5 @@
 //
 
-// NOTE: There are two known subtle differences from the code that uC++ 
+// NOTE: There are two known subtle differences from the code that uC++
 // generates for the same input
 // -CFA puts the break label inside at the end of a switch, uC++ puts it after
@@ -27,4 +27,5 @@
 #include "SynTree/Statement.h"
 #include "SynTree/Expression.h"
+#include "SynTree/Attribute.h"
 
 namespace ControlStruct {
@@ -33,8 +34,11 @@
 		targetTable = 0;
 	}
-
-	// break labels have to come after the statement they break out of, 
+	namespace {
+		Statement * isLoop( Statement * stmt ) { return dynamic_cast< WhileStmt * >( stmt ) ? stmt : dynamic_cast< ForStmt * >( stmt ) ? stmt : 0; }
+	}
+
+	// break labels have to come after the statement they break out of,
 	// so mutate a statement, then if they inform us through the breakLabel field
-	// tha they need a place to jump to on a break statement, add the break label 
+	// tha they need a place to jump to on a break statement, add the break label
 	// to the body of statements
 	void MLEMutator::fixBlock( std::list< Statement * > &kids ) {
@@ -44,11 +48,6 @@
 			if ( ! get_breakLabel().empty() ) {
 				std::list< Statement * >::iterator next = k+1;
-				if ( next == kids.end() ) {
-					std::list<Label> ls; ls.push_back( get_breakLabel() );
-					kids.push_back( new NullStmt( ls ) );
-				} else {
-					(*next)->get_labels().push_back( get_breakLabel() );
-				}
-
+				std::list<Label> ls; ls.push_back( get_breakLabel() );
+				kids.insert( next, new NullStmt( ls ) );
 				set_breakLabel("");
 			} // if
@@ -60,5 +59,5 @@
 		if ( labeledBlock ) {
 			Label brkLabel = generator->newLabel("blockBreak");
-			enclosingBlocks.push_back( Entry( cmpndStmt, brkLabel ) );
+			enclosingControlStructures.push_back( Entry( cmpndStmt, brkLabel ) );
 		} // if
 
@@ -69,9 +68,9 @@
 
 		if ( labeledBlock ) {
-			assert( ! enclosingBlocks.empty() );
-			if ( ! enclosingBlocks.back().useBreakExit().empty() ) {
-				set_breakLabel( enclosingBlocks.back().useBreakExit() );
-			}
-			enclosingBlocks.pop_back();
+			assert( ! enclosingControlStructures.empty() );
+			if ( ! enclosingControlStructures.back().useBreakExit().empty() ) {
+				set_breakLabel( enclosingControlStructures.back().useBreakExit() );
+			}
+			enclosingControlStructures.pop_back();
 		} // if
 
@@ -81,5 +80,5 @@
 	template< typename LoopClass >
 	Statement *MLEMutator::handleLoopStmt( LoopClass *loopStmt ) {
-		// remember this as the most recent enclosing loop, then mutate 
+		// remember this as the most recent enclosing loop, then mutate
 		// the body of the loop -- this will determine whether brkLabel
 		// and contLabel are used with branch statements
@@ -87,9 +86,9 @@
 		Label brkLabel = generator->newLabel("loopBreak");
 		Label contLabel = generator->newLabel("loopContinue");
-		enclosingLoops.push_back( Entry( loopStmt, brkLabel, contLabel ) );
+		enclosingControlStructures.push_back( Entry( loopStmt, brkLabel, contLabel ) );
 		loopStmt->set_body ( loopStmt->get_body()->acceptMutator( *this ) );
 
 		// sanity check that the enclosing loops have been popped correctly
-		Entry &e = enclosingLoops.back();
+		Entry &e = enclosingControlStructures.back();
 		assert ( e == loopStmt );
 
@@ -97,5 +96,5 @@
 		// two labels, if they are used.
 		loopStmt->set_body( mutateLoop( loopStmt->get_body(), e ) );
-		enclosingLoops.pop_back();
+		enclosingControlStructures.pop_back();
 
 		return loopStmt;
@@ -111,16 +110,16 @@
 	template< typename SwitchClass >
 	Statement *MLEMutator::handleSwitchStmt( SwitchClass *switchStmt ) {
-		// generate a label for breaking out of a labeled switch 
+		// generate a label for breaking out of a labeled switch
 		Label brkLabel = generator->newLabel("switchBreak");
-		enclosingSwitches.push_back( Entry(switchStmt, brkLabel) );
-		mutateAll( switchStmt->get_branches(), *this ); 
-
-		Entry &e = enclosingSwitches.back();
+		enclosingControlStructures.push_back( Entry(switchStmt, brkLabel) );
+		mutateAll( switchStmt->get_branches(), *this );
+
+		Entry &e = enclosingControlStructures.back();
 		assert ( e == switchStmt );
 
 		// only generate break label if labeled break is used
 		if (e.isBreakUsed()) {
-			// for the purposes of keeping switch statements uniform (i.e. all statements that are 
-			// direct children of a switch should be CastStmts), append the exit label + break to the 
+			// for the purposes of keeping switch statements uniform (i.e. all statements that are
+			// direct children of a switch should be CastStmts), append the exit label + break to the
 			// last case statement; create a default case if there are no cases
 			std::list< Statement * > &branches = switchStmt->get_branches();
@@ -131,10 +130,10 @@
 			if ( CaseStmt * c = dynamic_cast< CaseStmt * >( branches.back() ) ) {
 				std::list<Label> temp; temp.push_back( brkLabel );
-				c->get_statements().push_back( new BranchStmt( temp, Label(""), BranchStmt::Break ) );
+				c->get_statements().push_back( new BranchStmt( temp, Label("brkLabel"), BranchStmt::Break ) );
 			} else assert(0); // as of this point, all branches of a switch are still CaseStmts
 		}
 
-		assert ( enclosingSwitches.back() == switchStmt );
-		enclosingSwitches.pop_back();
+		assert ( enclosingControlStructures.back() == switchStmt );
+		enclosingControlStructures.pop_back();
 		return switchStmt;
 	}
@@ -143,35 +142,28 @@
 		std::string originalTarget = branchStmt->get_originalTarget();
 
-		if ( branchStmt->get_type() == BranchStmt::Goto )
+		std::list< Entry >::reverse_iterator targetEntry;
+		if ( branchStmt->get_type() == BranchStmt::Goto ) {
 			return branchStmt;
-
-		// test if continue target is a loop
-		if ( branchStmt->get_type() == BranchStmt::Continue) {
-			if ( enclosingLoops.empty() ) {
-				throw SemanticError( "'continue' outside a loop" );
-			} else if ( branchStmt->get_target() != "" && std::find( enclosingLoops.begin(), enclosingLoops.end(), (*targetTable)[branchStmt->get_target()] ) == enclosingLoops.end() ) {
-				throw SemanticError( "'continue' target label must be an enclosing loop: " + originalTarget );
-			}
-		}
-
-		if ( branchStmt->get_type() == BranchStmt::Break && (enclosingLoops.empty() && enclosingSwitches.empty() && enclosingBlocks.empty() ) )
-			throw SemanticError( "'break' outside a loop or switch" );
-
-		if ( branchStmt->get_target() == "" ) return branchStmt;
-
-		if ( targetTable->find( branchStmt->get_target() ) == targetTable->end() )
+		} else if ( branchStmt->get_type() == BranchStmt::Continue) {
+			// continue target must be a loop
+			if ( branchStmt->get_target() == "" ) {
+				targetEntry = std::find_if( enclosingControlStructures.rbegin(), enclosingControlStructures.rend(), [](Entry &e) { return isLoop( e.get_controlStructure() ); } );
+			} else {
+				// labelled continue - lookup label in table ot find attached control structure
+				targetEntry = std::find( enclosingControlStructures.rbegin(), enclosingControlStructures.rend(), (*targetTable)[branchStmt->get_target()] );
+			}
+			if ( targetEntry == enclosingControlStructures.rend() || ! isLoop( targetEntry->get_controlStructure() ) ) {
+				throw SemanticError( "'continue' target must be an enclosing loop: " + originalTarget );
+			}
+		} else if ( branchStmt->get_type() == BranchStmt::Break ) {
+			if ( enclosingControlStructures.empty() ) throw SemanticError( "'break' outside a loop, switch, or labelled block" );
+			targetEntry = enclosingControlStructures.rbegin();
+		} else {
+			assert( false );
+		}
+
+		if ( branchStmt->get_target() != "" && targetTable->find( branchStmt->get_target() ) == targetTable->end() ) {
 			throw SemanticError("The label defined in the exit loop statement does not exist: " + originalTarget );  // shouldn't happen (since that's already checked)
-
-		std::list< Entry >::iterator check;
-		if ( ( check = std::find( enclosingLoops.begin(), enclosingLoops.end(), (*targetTable)[branchStmt->get_target()] ) ) == enclosingLoops.end() )
-			// not in loop, checking if in block
-			if ( (check = std::find( enclosingBlocks.begin(), enclosingBlocks.end(), (*targetTable)[branchStmt->get_target()] )) == enclosingBlocks.end() )
-				// neither in loop nor in block, checking if in switch/choose
-				if ( (check = std::find( enclosingSwitches.begin(), enclosingSwitches.end(), (*targetTable)[branchStmt->get_target()] )) == enclosingSwitches.end() )
-					throw SemanticError("The target specified in the exit loop statement does not correspond to an enclosing control structure: " + originalTarget );
-
-		// what about exiting innermost block or switch???
-		if ( enclosingLoops.back() == (*check) )
-			return branchStmt;				// exit the innermost loop (labels unnecessary)
+		}
 
 		// branch error checks, get the appropriate label name and create a goto
@@ -179,10 +171,10 @@
 		switch ( branchStmt->get_type() ) {
 		  case BranchStmt::Break:
-				assert( check->useBreakExit() != "");
-				exitLabel = check->useBreakExit();
+				assert( targetEntry->useBreakExit() != "");
+				exitLabel = targetEntry->useBreakExit();
 				break;
 		  case BranchStmt::Continue:
-				assert( check->useContExit() != "");
-				exitLabel = check->useContExit();
+				assert( targetEntry->useContExit() != "");
+				exitLabel = targetEntry->useContExit();
 				break;
 		  default:
@@ -190,5 +182,14 @@
 		} // switch
 
-		return new BranchStmt( std::list<Label>(), exitLabel, BranchStmt::Goto );
+		if ( branchStmt->get_target() == "" && branchStmt->get_type() != BranchStmt::Continue ) {
+			// unlabelled break/continue - can keep branch as break/continue for extra semantic information, but add
+			// exitLabel as its destination so that label passes can easily determine where the break/continue goes to
+			branchStmt->set_target( exitLabel );
+			return branchStmt;
+		} else {
+			// labelled break/continue - can't easily emulate this with break and continue, so transform into a goto
+			delete branchStmt;
+			return new BranchStmt( std::list<Label>(), exitLabel, BranchStmt::Goto );
+		}
 	}
 
@@ -206,11 +207,11 @@
 			// continue label goes in the body as the last statement
 			std::list< Label > labels; labels.push_back( e.useContExit() );
-			newBody->get_kids().push_back( new NullStmt( labels ) );			
+			newBody->get_kids().push_back( new NullStmt( labels ) );
 		}
 
 		if ( e.isBreakUsed() ) {
-			// break label goes after the loop -- it'll get set by the 
+			// break label goes after the loop -- it'll get set by the
 			// outer mutator if we do this
-			set_breakLabel( e.useBreakExit() );			
+			set_breakLabel( e.useBreakExit() );
 		}
 
@@ -231,5 +232,5 @@
 
 	Statement *MLEMutator::mutate( ChooseStmt *switchStmt ) {
-		return handleSwitchStmt( switchStmt );		
+		return handleSwitchStmt( switchStmt );
 	}
 
Index: src/ControlStruct/MLEMutator.h
===================================================================
--- src/ControlStruct/MLEMutator.h	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/ControlStruct/MLEMutator.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -5,5 +5,5 @@
 // file "LICENCE" distributed with Cforall.
 //
-// MLEMutator.h -- 
+// MLEMutator.h --
 //
 // Author           : Rodolfo G. Esteves
@@ -23,4 +23,5 @@
 #include "SynTree/SynTree.h"
 #include "SynTree/Mutator.h"
+#include "SynTree/Label.h"
 
 #include "LabelGenerator.h"
@@ -38,5 +39,5 @@
 		Statement *mutate( BranchStmt *branchStmt ) throw ( SemanticError );
 
-		Statement *mutate( CaseStmt *caseStmt ); 
+		Statement *mutate( CaseStmt *caseStmt );
 		Statement *mutate( SwitchStmt *switchStmt );
 		Statement *mutate( ChooseStmt *switchStmt );
@@ -55,7 +56,7 @@
 			bool operator!=( const Statement *stmt ) { return ( loop != stmt ); }
 
-			bool operator==( const Entry &other ) { return ( loop == other.get_loop() ); }
+			bool operator==( const Entry &other ) { return ( loop == other.get_controlStructure() ); }
 
-			Statement *get_loop() const { return loop; }
+			Statement *get_controlStructure() const { return loop; }
 
 			Label useContExit() { contUsed = true; return contExit; }
@@ -72,5 +73,5 @@
 
 		std::map< Label, Statement * > *targetTable;
-		std::list< Entry > enclosingBlocks, enclosingLoops, enclosingSwitches;
+		std::list< Entry > enclosingControlStructures;
 		Label breakLabel;
 		LabelGenerator *generator;
@@ -79,5 +80,5 @@
 		Statement *handleLoopStmt( LoopClass *loopStmt );
 
-		template< typename SwitchClass > 
+		template< typename SwitchClass >
 		Statement *handleSwitchStmt( SwitchClass *switchStmt );
 
Index: src/ControlStruct/Mutate.cc
===================================================================
--- src/ControlStruct/Mutate.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/ControlStruct/Mutate.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -5,5 +5,5 @@
 // file "LICENCE" distributed with Cforall.
 //
-// Mutate.cc -- 
+// Mutate.cc --
 //
 // Author           : Rodolfo G. Esteves
@@ -39,10 +39,10 @@
 		ForExprMutator formut;
 
+		// transform choose statements into switch statements
+		ChooseMutator chmut;
+
 		// normalizes label definitions and generates multi-level
 		// exit labels
 		LabelFixer lfix;
-
-		// transform choose statements into switch statements
-		ChooseMutator chmut;
 
 		// expand case ranges and turn fallthru into a null statement
@@ -53,6 +53,6 @@
 
 		mutateAll( translationUnit, formut );
+		mutateAll( translationUnit, chmut );
 		acceptAll( translationUnit, lfix );
-		mutateAll( translationUnit, chmut );
 		mutateAll( translationUnit, ranges );
 		//mutateAll( translationUnit, exc );
Index: src/GenPoly/Specialize.cc
===================================================================
--- src/GenPoly/Specialize.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/GenPoly/Specialize.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -99,5 +99,5 @@
 		} // if
 		// create new thunk with same signature as formal type (C linkage, empty body)
-		FunctionDecl *thunkFunc = new FunctionDecl( thunkNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, newType, new CompoundStmt( std::list< std::string >() ), false, false );
+		FunctionDecl *thunkFunc = new FunctionDecl( thunkNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, newType, new CompoundStmt( noLabels ), false, false );
 		thunkFunc->fixUniqueId();
 
Index: src/InitTweak/FixInit.cc
===================================================================
--- src/InitTweak/FixInit.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/InitTweak/FixInit.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -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 = false;
 #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,584 @@
 		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; )
-
-		// xxx - some of these aren't necessary, and can be removed once this is stable
-		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 ) {
+			// keep track of all variables currently in scope
+			if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
+				curVars.insert( objDecl );
+			}
+			Parent::visit( stmt );
+		}
+
+		void LabelFinder::handleStmt( Statement * stmt ) {
+			// for each label, remember the variables in scope at that label.
+			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 );
+
+			// add destructors for the current scope that we're exiting
+			std::list< Statement * > & statements = compoundStmt->get_kids();
+			insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
+			reverseDeclOrder.pop_front();
+		}
+
+		void InsertDtors::visit( ReturnStmt * returnStmt ) {
+			// return exits all scopes, so dump destructors for all scopes
+			for ( OrderedDecls & od : reverseDeclOrder ) {
+				insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
+			}
+		}
+
+		// Handle break/continue/goto in the same manner as C++.
+		// Basic idea: any objects that are in scope at the BranchStmt
+		// but not at the labelled (target) statement must be destructed.
+		// If there are any objects in scope at the target location but
+		// not at the BranchStmt then those objects would be uninitialized
+		// so notify the user of the error.
+		// See C++ Reference 6.6 Jump Statements for details.
+		void InsertDtors::handleGoto( BranchStmt * stmt ) {
+			assert( stmt->get_target() != "" && "BranchStmt missing a label" );
+			// 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 ) {
+			switch( stmt->get_type() ) {
+				case BranchStmt::Continue:
+				case BranchStmt::Break:
+				// could optimize the break/continue case, because the S_L-S_G check
+				// is unnecessary (this set should always be empty), but it serves
+				// as a small sanity check.
+				case BranchStmt::Goto:
+					handleGoto( stmt );
+					break;
+				default:
+					assert( false );
+			}
+		}
+	} // namespace
 } // namespace InitTweak
 
Index: src/InitTweak/InitTweak.cc
===================================================================
--- src/InitTweak/InitTweak.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/InitTweak/InitTweak.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -115,11 +115,11 @@
 
 	namespace {
-		template<typename CallExpr>
-		std::string funcName( CallExpr * expr ) {
-			Expression * func = expr->get_function();
+		std::string funcName( Expression * func ) {
 			if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
 				return nameExpr->get_name();
 			} else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
 				return varExpr->get_var()->get_name();
+			}	else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
+				return funcName( castExpr->get_arg() );
 			} else {
 				assert( false && "Unexpected expression type being called as a function in call expression" );
@@ -130,8 +130,9 @@
 	std::string getFunctionName( Expression * expr ) {
 		if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
-			return funcName( appExpr );
+			return funcName( appExpr->get_function() );
 		} else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
-			return funcName( untypedExpr );
+			return funcName( untypedExpr->get_function() );
 		} else {
+			std::cerr << expr << std::endl;
 			assert( false && "Unexpected expression type passed to getFunctionName" );
 		}
Index: src/Makefile.in
===================================================================
--- src/Makefile.in	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/Makefile.in	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -194,4 +194,5 @@
 	SynTree/driver_cfa_cpp-Visitor.$(OBJEXT) \
 	SynTree/driver_cfa_cpp-Mutator.$(OBJEXT) \
+	SynTree/driver_cfa_cpp-AddStmtVisitor.$(OBJEXT) \
 	SynTree/driver_cfa_cpp-TypeSubstitution.$(OBJEXT) \
 	SynTree/driver_cfa_cpp-Attribute.$(OBJEXT) \
@@ -412,6 +413,6 @@
 	SynTree/NamedTypeDecl.cc SynTree/TypeDecl.cc \
 	SynTree/Initializer.cc SynTree/Visitor.cc SynTree/Mutator.cc \
-	SynTree/TypeSubstitution.cc SynTree/Attribute.cc \
-	Tuples/Mutate.cc Tuples/AssignExpand.cc \
+	SynTree/AddStmtVisitor.cc SynTree/TypeSubstitution.cc \
+	SynTree/Attribute.cc Tuples/Mutate.cc Tuples/AssignExpand.cc \
 	Tuples/FunctionFixer.cc Tuples/TupleAssignment.cc \
 	Tuples/FunctionChecker.cc Tuples/NameMatcher.cc
@@ -782,4 +783,6 @@
 SynTree/driver_cfa_cpp-Mutator.$(OBJEXT): SynTree/$(am__dirstamp) \
 	SynTree/$(DEPDIR)/$(am__dirstamp)
+SynTree/driver_cfa_cpp-AddStmtVisitor.$(OBJEXT):  \
+	SynTree/$(am__dirstamp) SynTree/$(DEPDIR)/$(am__dirstamp)
 SynTree/driver_cfa_cpp-TypeSubstitution.$(OBJEXT):  \
 	SynTree/$(am__dirstamp) SynTree/$(DEPDIR)/$(am__dirstamp)
@@ -878,4 +881,5 @@
 	-rm -f SymTab/driver_cfa_cpp-TypeEquality.$(OBJEXT)
 	-rm -f SymTab/driver_cfa_cpp-Validate.$(OBJEXT)
+	-rm -f SynTree/driver_cfa_cpp-AddStmtVisitor.$(OBJEXT)
 	-rm -f SynTree/driver_cfa_cpp-AddressExpr.$(OBJEXT)
 	-rm -f SynTree/driver_cfa_cpp-AggregateDecl.$(OBJEXT)
@@ -988,4 +992,5 @@
 @AMDEP_TRUE@@am__include@ @am__quote@SymTab/$(DEPDIR)/driver_cfa_cpp-TypeEquality.Po@am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote@SymTab/$(DEPDIR)/driver_cfa_cpp-Validate.Po@am__quote@
+@AMDEP_TRUE@@am__include@ @am__quote@SynTree/$(DEPDIR)/driver_cfa_cpp-AddStmtVisitor.Po@am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote@SynTree/$(DEPDIR)/driver_cfa_cpp-AddressExpr.Po@am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote@SynTree/$(DEPDIR)/driver_cfa_cpp-AggregateDecl.Po@am__quote@
@@ -2415,4 +2420,18 @@
 @AMDEP_TRUE@@am__fastdepCXX_FALSE@	DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCXX_FALSE@	$(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -c -o SynTree/driver_cfa_cpp-Mutator.obj `if test -f 'SynTree/Mutator.cc'; then $(CYGPATH_W) 'SynTree/Mutator.cc'; else $(CYGPATH_W) '$(srcdir)/SynTree/Mutator.cc'; fi`
+
+SynTree/driver_cfa_cpp-AddStmtVisitor.o: SynTree/AddStmtVisitor.cc
+@am__fastdepCXX_TRUE@	$(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -MT SynTree/driver_cfa_cpp-AddStmtVisitor.o -MD -MP -MF SynTree/$(DEPDIR)/driver_cfa_cpp-AddStmtVisitor.Tpo -c -o SynTree/driver_cfa_cpp-AddStmtVisitor.o `test -f 'SynTree/AddStmtVisitor.cc' || echo '$(srcdir)/'`SynTree/AddStmtVisitor.cc
+@am__fastdepCXX_TRUE@	$(AM_V_at)$(am__mv) SynTree/$(DEPDIR)/driver_cfa_cpp-AddStmtVisitor.Tpo SynTree/$(DEPDIR)/driver_cfa_cpp-AddStmtVisitor.Po
+@AMDEP_TRUE@@am__fastdepCXX_FALSE@	$(AM_V_CXX)source='SynTree/AddStmtVisitor.cc' object='SynTree/driver_cfa_cpp-AddStmtVisitor.o' libtool=no @AMDEPBACKSLASH@
+@AMDEP_TRUE@@am__fastdepCXX_FALSE@	DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+@am__fastdepCXX_FALSE@	$(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -c -o SynTree/driver_cfa_cpp-AddStmtVisitor.o `test -f 'SynTree/AddStmtVisitor.cc' || echo '$(srcdir)/'`SynTree/AddStmtVisitor.cc
+
+SynTree/driver_cfa_cpp-AddStmtVisitor.obj: SynTree/AddStmtVisitor.cc
+@am__fastdepCXX_TRUE@	$(AM_V_CXX)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -MT SynTree/driver_cfa_cpp-AddStmtVisitor.obj -MD -MP -MF SynTree/$(DEPDIR)/driver_cfa_cpp-AddStmtVisitor.Tpo -c -o SynTree/driver_cfa_cpp-AddStmtVisitor.obj `if test -f 'SynTree/AddStmtVisitor.cc'; then $(CYGPATH_W) 'SynTree/AddStmtVisitor.cc'; else $(CYGPATH_W) '$(srcdir)/SynTree/AddStmtVisitor.cc'; fi`
+@am__fastdepCXX_TRUE@	$(AM_V_at)$(am__mv) SynTree/$(DEPDIR)/driver_cfa_cpp-AddStmtVisitor.Tpo SynTree/$(DEPDIR)/driver_cfa_cpp-AddStmtVisitor.Po
+@AMDEP_TRUE@@am__fastdepCXX_FALSE@	$(AM_V_CXX)source='SynTree/AddStmtVisitor.cc' object='SynTree/driver_cfa_cpp-AddStmtVisitor.obj' libtool=no @AMDEPBACKSLASH@
+@AMDEP_TRUE@@am__fastdepCXX_FALSE@	DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+@am__fastdepCXX_FALSE@	$(AM_V_CXX@am__nodep@)$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(driver_cfa_cpp_CXXFLAGS) $(CXXFLAGS) -c -o SynTree/driver_cfa_cpp-AddStmtVisitor.obj `if test -f 'SynTree/AddStmtVisitor.cc'; then $(CYGPATH_W) 'SynTree/AddStmtVisitor.cc'; else $(CYGPATH_W) '$(srcdir)/SynTree/AddStmtVisitor.cc'; fi`
 
 SynTree/driver_cfa_cpp-TypeSubstitution.o: SynTree/TypeSubstitution.cc
Index: src/Parser/ExpressionNode.cc
===================================================================
--- src/Parser/ExpressionNode.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/Parser/ExpressionNode.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -5,6 +5,6 @@
 // file "LICENCE" distributed with Cforall.
 //
-// ExpressionNode.cc -- 
-// 
+// ExpressionNode.cc --
+//
 // Author           : Rodolfo G. Esteves
 // Created On       : Sat May 16 13:17:07 2015
@@ -12,5 +12,5 @@
 // Last Modified On : Mon Jun 13 14:46:17 2016
 // Update Count     : 307
-// 
+//
 
 #include <cassert>
@@ -231,5 +231,5 @@
 	// "abc" "def" "ghi" => "abcdefghi", remove new text from quotes and insert before last quote in old string.
 	value.insert( value.length() - 1, newValue->substr( 1, newValue->length() - 2 ) );
-	
+
 	delete newValue;									// allocated by lexer
 	return this;
@@ -347,5 +347,5 @@
 
 	if ( isArrayIndex ) {
-		// need to traverse entire structure and change any instances of 0 or 1 to 
+		// need to traverse entire structure and change any instances of 0 or 1 to
 		// ConstantExpr
 		DesignatorFixer fixer;
@@ -440,5 +440,5 @@
 }
 
-CompositeExprNode::CompositeExprNode( const CompositeExprNode &other ) : ExpressionNode( other ), function( maybeClone( other.function ) ) {
+CompositeExprNode::CompositeExprNode( const CompositeExprNode &other ) : ExpressionNode( other ), function( maybeClone( other.function ) ), arguments( 0 ) {
 	ParseNode *cur = other.arguments;
 	while ( cur ) {
@@ -608,5 +608,5 @@
 		{
 			assert( args.size() == 2 );
-			
+
 			if ( TypeValueNode * arg = dynamic_cast<TypeValueNode *>( get_args() ) ) {
 				NameExpr *member = dynamic_cast<NameExpr *>( args.back() );
Index: src/Parser/ParseNode.h
===================================================================
--- src/Parser/ParseNode.h	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/Parser/ParseNode.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -28,4 +28,5 @@
 //#include "SynTree/Declaration.h"
 #include "Common/UniqueName.h"
+#include "SynTree/Label.h"
 
 class ExpressionNode;
@@ -284,8 +285,8 @@
 	virtual void printOneLine( std::ostream &, int indent = 0) const;
 
-	const std::list< std::string > &get_labels() const { return labels; };
+	const std::list< Label > &get_labels() const { return labels; };
 	void append_label( std::string *label ) { labels.push_back( *label ); delete label; }
   private:
-	std::list< std::string > labels;
+	std::list< Label > labels;
 };
 
@@ -532,5 +533,5 @@
 	ExpressionNode *output, *input;
 	ConstantNode *clobber;
-	std::list<std::string> gotolabels;
+	std::list< Label > gotolabels;
 };
 
Index: src/Parser/StatementNode.cc
===================================================================
--- src/Parser/StatementNode.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/Parser/StatementNode.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -5,5 +5,5 @@
 // file "LICENCE" distributed with Cforall.
 //
-// StatementNode.cc -- 
+// StatementNode.cc --
 //
 // Author           : Rodolfo G. Esteves
@@ -27,6 +27,6 @@
 
 const char *StatementNode::StType[] = {
-	"Exp",   "If",       "Switch", "Case",    "Default",  "Choose",   "Fallthru", 
-	"While", "Do",       "For", 
+	"Exp",   "If",       "Switch", "Case",    "Default",  "Choose",   "Fallthru",
+	"While", "Do",       "For",
 	"Goto",  "Continue", "Break",  "Return",  "Throw",
 	"Try",   "Catch",    "Finally", "Asm",
@@ -62,5 +62,5 @@
 StatementNode::StatementNode( Type t, ExpressionNode *ctrl_label, StatementNode *block ) : type( t ), control( ctrl_label ), block( block ), labels( 0 ), target( 0 ), decl( 0 ), isCatchRest ( false ) {
 	this->control = ( t == Default ) ? 0 : control;
-} 
+}
 
 StatementNode::StatementNode( Type t, string *target ) : type( t ), control( 0 ), block( 0 ), labels( 0 ), target( target ), decl( 0 ), isCatchRest ( false ) {}
@@ -74,5 +74,5 @@
 
 StatementNode * StatementNode::newCatchStmt( DeclarationNode *d, StatementNode *s, bool catchRestP ) {
-	StatementNode *ret = new StatementNode( StatementNode::Catch, 0, s ); 
+	StatementNode *ret = new StatementNode( StatementNode::Catch, 0, s );
 	ret->addDeclaration( d );
 	ret->setCatchRest( catchRestP );
@@ -101,5 +101,5 @@
 StatementNode *StatementNode::add_label( const std::string *l ) {
 	if ( l != 0 ) {
-		labels.push_front( *l ); 
+		labels.push_front( *l );
 		delete l;
 	} // if
@@ -156,5 +156,5 @@
 			control->print( os, indent );
 			os << endl;
-		} else 
+		} else
 			os << string( indent, ' ' ) << "Null Statement" << endl;
 		break;
@@ -177,5 +177,5 @@
 		if ( block ) {
 			os << string( indent + ParseNode::indent_by, ' ' ) << "Branches of execution: " << endl;
-			block->printList( os, indent + 2 * ParseNode::indent_by );  
+			block->printList( os, indent + 2 * ParseNode::indent_by );
 		} // if
 		if ( target ) {
@@ -258,5 +258,5 @@
 	  case Fallthru:
 		return new FallthruStmt( labs );
-	  case Case: 
+	  case Case:
 		return new CaseStmt( labs, maybeBuild<Expression>(get_control()), branches );
 	  case Default:
@@ -394,5 +394,5 @@
 		os << string( indent + ParseNode::indent_by, ' ' ) << "Goto Labels:" << endl;
 		os << string( indent + 2 * ParseNode::indent_by, ' ' );
-		for ( std::list<std::string>::const_iterator i = gotolabels.begin();; ) {
+		for ( std::list<Label>::const_iterator i = gotolabels.begin();; ) {
 			os << *i;
 			i++;
@@ -426,5 +426,5 @@
 }
 
-Statement *NullStmtNode::build() const { 
+Statement *NullStmtNode::build() const {
 	return new NullStmt;
 }
Index: src/ResolvExpr/Resolver.cc
===================================================================
--- src/ResolvExpr/Resolver.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/ResolvExpr/Resolver.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -503,4 +503,6 @@
 		delete ctorInit->get_ctor();
 		ctorInit->set_ctor( NULL );
+		delete ctorInit->get_dtor();
+		ctorInit->set_dtor( NULL );
 		maybeAccept( ctorInit->get_init(), *this );
 	}
Index: src/SymTab/Autogen.cc
===================================================================
--- src/SymTab/Autogen.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/SymTab/Autogen.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -482,4 +482,6 @@
 		ObjectDecl *dst = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), typeInst->clone() ), 0 );
 		if ( typeDecl->get_base() ) {
+			// xxx - generate ctor/dtors for typedecls, e.g.
+			// otype T = int *;
 			stmts = new CompoundStmt( std::list< Label >() );
 			UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
Index: src/SymTab/Autogen.h
===================================================================
--- src/SymTab/Autogen.h	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/SymTab/Autogen.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -24,6 +24,4 @@
 
 namespace SymTab {
-  static const std::list< std::string > noLabels;
-
   /// Generates assignment operators, constructors, and destructor for aggregate types as required
   void autogenerateRoutines( std::list< Declaration * > &translationUnit );
Index: src/SymTab/Indexer.h
===================================================================
--- src/SymTab/Indexer.h	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/SymTab/Indexer.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -5,5 +5,5 @@
 // file "LICENCE" distributed with Cforall.
 //
-// Indexer.h -- 
+// Indexer.h --
 //
 // Author           : Richard C. Bilson
@@ -33,5 +33,5 @@
 		Indexer& operator= ( Indexer &&that );
 
-		//using Visitor::visit;
+		using Visitor::visit;
 		virtual void visit( ObjectDecl *objectDecl );
 		virtual void visit( FunctionDecl *functionDecl );
@@ -54,5 +54,5 @@
 		virtual void visit( MemberExpr *memberExpr );
 		virtual void visit( VariableExpr *variableExpr );
-		virtual void visit( ConstantExpr *constantExpr ); 
+		virtual void visit( ConstantExpr *constantExpr );
 		virtual void visit( SizeofExpr *sizeofExpr );
 		virtual void visit( AlignofExpr *alignofExpr );
@@ -93,5 +93,5 @@
 		/// Gets the top-most trait declaration with the given ID
 		TraitDecl *lookupTrait( const std::string &id ) const;
-  
+
 		void print( std::ostream &os, int indent = 0 ) const;
 	  private:
@@ -106,5 +106,5 @@
 		UnionDecl *lookupUnionAtScope( const std::string &id, unsigned long scope ) const;
 		TraitDecl *lookupTraitAtScope( const std::string &id, unsigned long scope ) const;
-		
+
 		void addId( DeclarationWithType *decl );
 		void addType( NamedTypeDecl *decl );
@@ -115,5 +115,5 @@
 		void addUnion( UnionDecl *decl );
 		void addTrait( TraitDecl *decl );
-		
+
 		struct Impl;
 		Impl *tables;         ///< Copy-on-write instance of table data structure
Index: src/SynTree/AddStmtVisitor.cc
===================================================================
--- src/SynTree/AddStmtVisitor.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
+++ src/SynTree/AddStmtVisitor.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -0,0 +1,96 @@
+//
+// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
+//
+// The contents of this file are covered under the licence agreement in the
+// file "LICENCE" distributed with Cforall.
+//
+// AddStmtVisitor.cc --
+//
+// Author           : Rob Schluntz
+// Created On       : Wed Jun 22 12:11:17 2016
+// Last Modified By : Rob Schluntz
+// Last Modified On : Wed Jun 22 12:16:29 2016
+// Update Count     : 11
+//
+
+#include "AddStmtVisitor.h"
+#include "Statement.h"
+#include "Declaration.h"
+#include "Expression.h"
+#include "Common/utility.h"
+
+void AddStmtVisitor::visitStatementList( std::list< Statement* > &statements ) {
+	for ( std::list< Statement* >::iterator i = statements.begin(); i != statements.end(); ++i ) {
+		if ( ! stmtsToAddAfter.empty() ) {
+			statements.splice( i, stmtsToAddAfter );
+		} // if
+		(*i)->accept( *this );
+		if ( ! stmtsToAdd.empty() ) {
+			statements.splice( i, stmtsToAdd );
+		} // if
+	} // for
+	if ( ! stmtsToAddAfter.empty() ) {
+		statements.splice( statements.end(), stmtsToAddAfter );
+	} // if
+}
+
+Statement * AddStmtVisitor::visitStatement( Statement *stmt ) {
+	maybeAccept( stmt, *this );
+	if ( ! stmtsToAdd.empty() || ! stmtsToAddAfter.empty() ) {
+		CompoundStmt *compound = new CompoundStmt( noLabels );
+		compound->get_kids().splice( compound->get_kids().end(), stmtsToAdd );
+		compound->get_kids().push_back( stmt );
+		compound->get_kids().splice( compound->get_kids().end(), stmtsToAddAfter );
+		return compound;
+	} else {
+		return stmt;
+	}
+}
+
+void AddStmtVisitor::visit(CompoundStmt *compoundStmt) {
+	visitStatementList( compoundStmt->get_kids() );
+}
+
+void AddStmtVisitor::visit(IfStmt *ifStmt) {
+	ifStmt->set_thenPart( visitStatement( ifStmt->get_thenPart() ) );
+	ifStmt->set_elsePart( visitStatement( ifStmt->get_elsePart() ) );
+	maybeAccept( ifStmt->get_condition(), *this );
+}
+
+void AddStmtVisitor::visit(WhileStmt *whileStmt) {
+	whileStmt->set_body( visitStatement( whileStmt->get_body() ) );
+	maybeAccept( whileStmt->get_condition(), *this );
+}
+
+void AddStmtVisitor::visit(ForStmt *forStmt) {
+	forStmt->set_body( visitStatement( forStmt->get_body() ) );
+	acceptAll( forStmt->get_initialization(), *this );
+	maybeAccept( forStmt->get_condition(), *this );
+	maybeAccept( forStmt->get_increment(), *this );
+}
+
+void AddStmtVisitor::visit(SwitchStmt *switchStmt) {
+	visitStatementList( switchStmt->get_branches() );
+	maybeAccept( switchStmt->get_condition(), *this );
+}
+
+void AddStmtVisitor::visit(ChooseStmt *switchStmt) {
+	visitStatementList( switchStmt->get_branches() );
+	maybeAccept( switchStmt->get_condition(), *this );
+}
+
+void AddStmtVisitor::visit(CaseStmt *caseStmt) {
+	visitStatementList( caseStmt->get_statements() );
+	maybeAccept( caseStmt->get_condition(), *this );
+}
+
+void AddStmtVisitor::visit(CatchStmt *catchStmt) {
+	catchStmt->set_body( visitStatement( catchStmt->get_body() ) );
+	maybeAccept( catchStmt->get_decl(), *this );
+}
+
+// Local Variables: //
+// tab-width: 4 //
+// mode: c++ //
+// compile-command: "make install" //
+// End: //
Index: src/SynTree/AddStmtVisitor.h
===================================================================
--- src/SynTree/AddStmtVisitor.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
+++ src/SynTree/AddStmtVisitor.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -0,0 +1,45 @@
+//
+// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
+//
+// The contents of this file are covered under the licence agreement in the
+// file "LICENCE" distributed with Cforall.
+//
+// AddStmtVisitor.h --
+//
+// Author           : Rob Schluntz
+// Created On       : Wed Jun 22 12:05:48 2016
+// Last Modified By : Rob Schluntz
+// Last Modified On : Wed Jun 22 12:12:05 2016
+// Update Count     : 7
+//
+
+#ifndef ADD_STATEMENT_VISITOR_H
+#define ADD_STATEMENT_VISITOR_H
+
+#include <list>
+
+#include "SynTree/SynTree.h"
+#include "SynTree/Visitor.h"
+
+class AddStmtVisitor : public Visitor {
+  public:
+	typedef Visitor Parent;
+
+	using Parent::visit;
+	virtual void visit(CompoundStmt *compoundStmt);
+	virtual void visit(IfStmt *ifStmt);
+	virtual void visit(WhileStmt *whileStmt);
+	virtual void visit(ForStmt *forStmt);
+	virtual void visit(SwitchStmt *switchStmt);
+	virtual void visit(ChooseStmt *chooseStmt);
+	virtual void visit(CaseStmt *caseStmt);
+	virtual void visit(CatchStmt *catchStmt);
+
+  protected:
+	void visitStatementList( std::list< Statement * > & );
+	Statement * visitStatement( Statement * );
+	std::list< Statement* > stmtsToAdd;
+	std::list< Statement* > stmtsToAddAfter;
+};
+
+#endif // ADD_STATEMENT_VISITOR_H
Index: src/SynTree/Label.h
===================================================================
--- src/SynTree/Label.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
+++ src/SynTree/Label.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -0,0 +1,59 @@
+//
+// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
+//
+// The contents of this file are covered under the licence agreement in the
+// file "LICENCE" distributed with Cforall.
+//
+// Label.h --
+//
+// Author           : Rob Schluntz
+// Created On       : Wed Jun 8 12:53:12 2016
+// Last Modified By : Rob Schluntz
+// Last Modified On : Wed Jun 8 12:53:28 2016
+// Update Count     : 1
+//
+
+#ifndef LABEL_H
+#define LABEL_H
+
+#include <string>
+#include <list>
+#include <iostream>
+#include "SynTree.h"
+
+class Label {
+  public:
+	Label( const std::string & name = "", Statement * labelled = 0 ) : name( name ), labelled( labelled ) {}
+	Label( const char * name, Statement * labelled = 0 ) : name( name ), labelled( labelled ) {}
+
+	const std::string & get_name() const { return name; }
+	void set_name( const std::string & newValue ) { name = newValue; }
+
+	Statement * get_statement() const { return labelled; }
+	void set_statement( Statement * newValue ) { labelled = newValue; }
+	std::list< Attribute * >& get_attributes() { return attributes; }
+
+	operator std::string() { return name; }
+	bool empty() { return name.empty(); }
+  private:
+	std::string name;
+	Statement * labelled;
+	std::list< Attribute * > attributes;
+};
+
+inline bool operator==( Label l1, Label l2 ) { return l1.get_name() == l2.get_name(); }
+inline bool operator!=( Label l1, Label l2 ) { return ! (l1 == l2); }
+inline bool operator<( Label l1, Label l2 ) { return l1.get_name() < l2.get_name(); }
+// inline Label operator+( Label l1, Label l2 ) { return l1.get_name() + l2.get_name(); }
+// inline Label operator+( Label l1, const char * str ) { return l1.get_name() + Label( str ); }
+inline std::ostream & operator<<( std::ostream & out, const Label & l ) { return out << l.get_name(); }
+
+static const std::list< Label > noLabels;
+
+#endif // LABEL_H
+
+// Local Variables: //
+// tab-width: 4 //
+// mode: c++ //
+// compile-command: "make install" //
+// End: //
Index: src/SynTree/Statement.cc
===================================================================
--- src/SynTree/Statement.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/SynTree/Statement.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -87,5 +87,5 @@
 	Statement( labels ), originalTarget( _target ), target( _target ), computedTarget( NULL ), type( _type ) {
 	//actually this is a syntactic error signaled by the parser
-	if ( type == BranchStmt::Goto && target.size() == 0 )
+	if ( type == BranchStmt::Goto && target.empty() )
 		throw SemanticError("goto without target");
 }
Index: src/SynTree/Statement.h
===================================================================
--- src/SynTree/Statement.h	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/SynTree/Statement.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -22,4 +22,5 @@
 #include "Common/SemanticError.h"
 #include "Type.h"
+#include "Label.h"
 
 class Statement {
Index: src/SynTree/SynTree.h
===================================================================
--- src/SynTree/SynTree.h	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/SynTree/SynTree.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -113,5 +113,6 @@
 class Constant;
 
-typedef std::string Label;
+// typedef std::string Label;
+class Label;
 typedef unsigned int UniqueId;
 
Index: src/SynTree/Visitor.cc
===================================================================
--- src/SynTree/Visitor.cc	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/SynTree/Visitor.cc	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -39,5 +39,5 @@
 }
 
-void Visitor::visit( AggregateDecl *aggregateDecl ) {
+void Visitor::handleAggregateDecl( AggregateDecl *aggregateDecl ) {
 	acceptAll( aggregateDecl->get_parameters(), *this );
 	acceptAll( aggregateDecl->get_members(), *this );
@@ -45,20 +45,20 @@
 
 void Visitor::visit( StructDecl *aggregateDecl ) {
-	visit( static_cast< AggregateDecl* >( aggregateDecl ) );
+	handleAggregateDecl( static_cast< AggregateDecl* >( aggregateDecl ) );
 }
 
 void Visitor::visit( UnionDecl *aggregateDecl ) {
-	visit( static_cast< AggregateDecl* >( aggregateDecl ) );
+	handleAggregateDecl( static_cast< AggregateDecl* >( aggregateDecl ) );
 }
 
 void Visitor::visit( EnumDecl *aggregateDecl ) {
-	visit( static_cast< AggregateDecl* >( aggregateDecl ) );
+	handleAggregateDecl( static_cast< AggregateDecl* >( aggregateDecl ) );
 }
 
 void Visitor::visit( TraitDecl *aggregateDecl ) {
-	visit( static_cast< AggregateDecl* >( aggregateDecl ) );
-}
-
-void Visitor::visit( NamedTypeDecl *typeDecl ) {
+	handleAggregateDecl( static_cast< AggregateDecl* >( aggregateDecl ) );
+}
+
+void Visitor::handleNamedTypeDecl( NamedTypeDecl *typeDecl ) {
 	acceptAll( typeDecl->get_parameters(), *this );
 	acceptAll( typeDecl->get_assertions(), *this );
@@ -67,9 +67,9 @@
 
 void Visitor::visit( TypeDecl *typeDecl ) {
-	visit( static_cast< NamedTypeDecl* >( typeDecl ) );
+	handleNamedTypeDecl( static_cast< NamedTypeDecl* >( typeDecl ) );
 }
 
 void Visitor::visit( TypedefDecl *typeDecl ) {
-	visit( static_cast< NamedTypeDecl* >( typeDecl ) );
+	handleNamedTypeDecl( static_cast< NamedTypeDecl* >( typeDecl ) );
 }
 
@@ -330,5 +330,5 @@
 }
 
-void Visitor::visit( ReferenceToType *aggregateUseType ) {
+void Visitor::handleReferenceToType( ReferenceToType *aggregateUseType ) {
 	acceptAll( aggregateUseType->get_forall(), *this );
 	acceptAll( aggregateUseType->get_parameters(), *this );
@@ -336,22 +336,22 @@
 
 void Visitor::visit( StructInstType *aggregateUseType ) {
-	visit( static_cast< ReferenceToType * >( aggregateUseType ) );
+	handleReferenceToType( static_cast< ReferenceToType * >( aggregateUseType ) );
 }
 
 void Visitor::visit( UnionInstType *aggregateUseType ) {
-	visit( static_cast< ReferenceToType * >( aggregateUseType ) );
+	handleReferenceToType( static_cast< ReferenceToType * >( aggregateUseType ) );
 }
 
 void Visitor::visit( EnumInstType *aggregateUseType ) {
-	visit( static_cast< ReferenceToType * >( aggregateUseType ) );
+	handleReferenceToType( static_cast< ReferenceToType * >( aggregateUseType ) );
 }
 
 void Visitor::visit( TraitInstType *aggregateUseType ) {
-	visit( static_cast< ReferenceToType * >( aggregateUseType ) );
+	handleReferenceToType( static_cast< ReferenceToType * >( aggregateUseType ) );
 	acceptAll( aggregateUseType->get_members(), *this );
 }
 
 void Visitor::visit( TypeInstType *aggregateUseType ) {
-	visit( static_cast< ReferenceToType * >( aggregateUseType ) );
+	handleReferenceToType( static_cast< ReferenceToType * >( aggregateUseType ) );
 }
 
Index: src/SynTree/Visitor.h
===================================================================
--- src/SynTree/Visitor.h	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/SynTree/Visitor.h	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -104,7 +104,7 @@
 	virtual void visit( Constant *constant );
   private:
-	virtual void visit( AggregateDecl *aggregateDecl );
-	virtual void visit( NamedTypeDecl *typeDecl );
-	virtual void visit( ReferenceToType *aggregateUseType );
+	virtual void handleAggregateDecl( AggregateDecl *aggregateDecl );
+	virtual void handleNamedTypeDecl( NamedTypeDecl *typeDecl );
+	virtual void handleReferenceToType( ReferenceToType *aggregateUseType );
 };
 
Index: src/SynTree/module.mk
===================================================================
--- src/SynTree/module.mk	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/SynTree/module.mk	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -46,4 +46,5 @@
        SynTree/Visitor.cc \
        SynTree/Mutator.cc \
+       SynTree/AddStmtVisitor.cc \
        SynTree/TypeSubstitution.cc \
        SynTree/Attribute.cc
Index: src/tests/.expect/dtor-early-exit-ERR1.txt
===================================================================
--- src/tests/.expect/dtor-early-exit-ERR1.txt	(revision 87b5bf0c846782d88723cd4784006befc064183c)
+++ src/tests/.expect/dtor-early-exit-ERR1.txt	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -0,0 +1,4 @@
+CFA Version 1.0.0 (debug)
+Error: jump to label 'L1' crosses initialization of y Branch (Goto)
+
+make: *** [dtor-early-exit-ERR1] Error 1
Index: src/tests/.expect/dtor-early-exit-ERR2.txt
===================================================================
--- src/tests/.expect/dtor-early-exit-ERR2.txt	(revision 87b5bf0c846782d88723cd4784006befc064183c)
+++ src/tests/.expect/dtor-early-exit-ERR2.txt	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -0,0 +1,4 @@
+CFA Version 1.0.0 (debug)
+Error: jump to label 'L2' crosses initialization of y Branch (Goto)
+
+make: *** [dtor-early-exit-ERR2] Error 1
Index: src/tests/.expect/dtor-early-exit.txt
===================================================================
--- src/tests/.expect/dtor-early-exit.txt	(revision 87b5bf0c846782d88723cd4784006befc064183c)
+++ src/tests/.expect/dtor-early-exit.txt	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -0,0 +1,214 @@
+f i=0
+construct x
+construct y
+construct z
+destruct z
+destruct y
+destruct x
+f i=1
+construct x
+construct y
+construct z
+destruct z
+destruct y
+destruct x
+f i=2
+construct x
+construct y
+construct z
+destruct z
+destruct y
+destruct x
+f i=3
+construct x
+construct y
+construct z
+destruct z
+destruct y
+destruct x
+
+g for i=0
+construct x
+destruct x
+g for i=1
+construct x
+destruct x
+g for i=2
+construct x
+destruct x
+g for i=3
+construct x
+destruct x
+g for i=4
+construct x
+destruct x
+g for i=5
+construct x
+destruct x
+g for i=6
+construct x
+destruct x
+g for i=7
+construct x
+destruct x
+g for i=8
+construct x
+destruct x
+g for i=9
+construct x
+destruct x
+
+g while i=0
+construct x
+destruct x
+g while i=1
+construct x
+destruct x
+g while i=2
+construct x
+destruct x
+g while i=3
+construct x
+destruct x
+g while i=4
+construct x
+destruct x
+g while i=5
+construct x
+destruct x
+g while i=6
+construct x
+destruct x
+g while i=7
+construct x
+destruct x
+g while i=8
+construct x
+destruct x
+g while i=9
+construct x
+destruct x
+
+construct y
+g switch i=0
+destruct y
+construct y
+g switch i=1
+destruct y
+construct y
+g switch i=2
+destruct y
+construct y
+g switch i=3
+destruct y
+construct y
+g switch i=4
+destruct y
+construct y
+g switch i=5
+destruct y
+construct y
+g switch i=6
+destruct y
+construct y
+g switch i=7
+destruct y
+construct y
+g switch i=8
+destruct y
+construct y
+g switch i=9
+destruct y
+
+g for k=0
+g for i=0
+construct x
+g for j=0
+construct y
+continue L2
+destruct y
+g for j=1
+construct y
+break L2
+destruct y
+destruct x
+g for i=1
+construct x
+g for j=0
+construct y
+continue L2
+destruct y
+g for j=1
+construct y
+break L2
+destruct y
+destruct x
+g for i=2
+construct x
+continue L1
+destruct x
+g for i=3
+construct x
+break L1
+destruct x
+g for k=1
+g for i=0
+construct x
+g for j=0
+construct y
+continue L2
+destruct y
+g for j=1
+construct y
+break L2
+destruct y
+destruct x
+g for i=1
+construct x
+g for j=0
+construct y
+continue L2
+destruct y
+g for j=1
+construct y
+break L2
+destruct y
+destruct x
+g for i=2
+construct x
+continue L1
+destruct x
+g for i=3
+construct x
+break L1
+destruct x
+
+h
+construct y
+L1
+construct x
+L2
+goto L1
+destruct x
+L1
+construct x
+L2
+goto L2
+L2
+goto L3
+L3
+goto L2-2
+L2
+goto L4
+destruct x
+destruct y
+L4
+goto L0
+construct y
+L1
+construct x
+L2
+goto L4
+destruct x
+destruct y
+L4
Index: src/tests/Makefile.am
===================================================================
--- src/tests/Makefile.am	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/tests/Makefile.am	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -27,5 +27,5 @@
 
 all-local :
-	+python test.py vector_test avl_test operators numericConstants expression enum asmName array typeof cast
+	+python test.py vector_test avl_test operators numericConstants expression enum asmName array typeof cast dtor-early-exit init_once
 
 all-tests :
@@ -46,2 +46,9 @@
 constant0-1NDDP : constant0-1.c
 	${CC} ${CFLAGS} -DNEWDECL -DDUPS ${<} -o ${@}
+
+dtor-early-exit-ERR1: dtor-early-exit.c
+	${CC} ${CFLAGS} -DERR1 ${<} -o ${@}
+
+dtor-early-exit-ERR2: dtor-early-exit.c
+	${CC} ${CFLAGS} -DERR2 ${<} -o ${@}
+
Index: src/tests/Makefile.in
===================================================================
--- src/tests/Makefile.in	(revision 730591531f360bc32d76eb53bb048619f460a13c)
+++ src/tests/Makefile.in	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -634,5 +634,5 @@
 
 all-local :
-	+python test.py vector_test avl_test operators numericConstants expression enum asmName array typeof cast
+	+python test.py vector_test avl_test operators numericConstants expression enum asmName array typeof cast dtor-early-exit init_once
 
 all-tests :
@@ -653,4 +653,10 @@
 constant0-1NDDP : constant0-1.c
 	${CC} ${CFLAGS} -DNEWDECL -DDUPS ${<} -o ${@}
+
+dtor-early-exit-ERR1: dtor-early-exit.c
+	${CC} ${CFLAGS} -DERR1 ${<} -o ${@}
+
+dtor-early-exit-ERR2: dtor-early-exit.c
+	${CC} ${CFLAGS} -DERR2 ${<} -o ${@}
 
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
Index: src/tests/dtor-early-exit.c
===================================================================
--- src/tests/dtor-early-exit.c	(revision 87b5bf0c846782d88723cd4784006befc064183c)
+++ src/tests/dtor-early-exit.c	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -0,0 +1,207 @@
+#include <fstream>
+#include <stdlib>
+extern "C" {
+#define false ((int)0)	// until stdbool.h works
+#define assert(cond) if (! (cond)) { sout | "Assertion failed: (" | #cond | ") at " __FILE__ | ":" | __LINE__ | endl; abort(); }
+}
+
+struct A {
+	char * name;
+	int * x;
+};
+
+// don't want these called
+void ?{}(A * a) { assert( false ); }
+void ?{}(A * a, char * name) { a->name = name; sout | "construct " | name | endl; a->x = malloc(); }
+void ?{}(A * a, char * name, int * ptr) { assert( false ); }
+
+A ?=?(A * a, A a) {  sout | "assign " | a->name | " " | a.name; return a; }
+void ?{}(A * a, A a) { sout | "copy construct " | a.name | endl; a->x = malloc(); }
+void ^?{}(A * a) { sout | "destruct " | a->name | endl; free(a->x); }
+
+// test returns
+void f(int i) {
+	sout | "f i=" | i | endl;
+	A x = { "x" };  // construct x
+	{
+		A y = { "y" }; // construct y
+		{
+			A z = { "z" }; // construct z
+			{
+				if (i == 0) return; // destruct x, y, z
+			}
+			if (i == 1) return; // destruct x, y, z
+			// destruct z
+		}
+		if (i == 2) return; // destruct x, y
+		// destruct y
+	}
+	return; // destruct x
+}
+
+// test loops, switch, etc.
+void g() {
+	for (int i = 0; i < 10; i++) {
+		sout | "g for i=" | i | endl;
+		A x = { "x" };
+		// construct x
+		// destruct x
+	}
+	sout | endl;
+	{
+		int i = 0;
+		while (i < 10) {
+			sout | "g while i=" | i | endl;
+			A x = { "x" };
+			// construct x
+			i++;
+			// destruct x
+		}
+	}
+	sout | endl;
+	for (int i = 0; i < 10; i++) {
+		switch(10) {
+			case 0:
+			case 5:
+			case 10: {
+				A y = { "y" };
+				sout | "g switch i=" | i | endl;
+				// construct y
+				break; // destruct y
+			}
+			default: {
+				sout | "g switch i=" | i | endl;
+				A x = { "x" };
+				// construct x
+				break; // destruct x
+			}
+		}
+	}
+	sout | endl;
+	for (int k = 0; k < 2; k++) {
+		sout | "g for k=" | k | endl;
+		L1: for (int i = 0; i < 10; i++) {
+			sout | "g for i=" | i | endl;
+
+			A x = { "x" };
+			if (i == 2) {
+				sout | "continue L1" | endl;
+				continue;  // destruct x
+			} else if (i == 3) {
+				sout | "break L1" | endl;
+				break;  // destruct x
+			}
+
+			L2: for (int j = 0; j < 10; j++) {
+				sout | "g for j=" | j | endl;
+				A y = { "y" };
+				if (j == 0) {
+					sout | "continue L2" | endl;
+					continue; // destruct y - missing because object that needs to be destructed is not a part of this block, it's a part of the for's block
+				} else if (j == 1) {
+					sout | "break L2" | endl;
+					break;  // destruct y
+				} else if (i == 1) {
+					sout | "continue L1" | endl;
+					continue L1; // destruct x,y - note: continue takes you to destructors for block, so only generate destructor for y
+				} else if (k == 1) {
+					sout | "break L1" | endl;
+					break L1;  // destruct x,y
+				}
+			}
+		}
+	}
+}
+
+// test goto
+void h() {
+	int i = 0;
+	// for each goto G with target label L:
+	// * find all constructed variables alive at G (set S_G)
+	// * find all constructed variables alive at L (set S_L)
+	// * if S_L-S_G is non-empty, error
+	// * emit destructors for all variables in S_G-S_L
+	sout | "h" | endl;
+	{
+		L0: ;
+#ifdef ERR1
+			goto L1; // this is an error in g++ because it skips initialization of y
+#endif
+			A y = { "y" };
+			// S_L1 = { y }
+		L1: sout | "L1" | endl;
+			A x = { "x" };
+			// S_L2 = { y, x }
+		L2: sout | "L2" | endl;
+			if (i == 0) {
+				++i;
+				sout | "goto L1" | endl;
+				// S_G = { y, x }
+				goto L1;  // jump back, destruct b/c before x definition
+				// S_L-S_G = {} => no error
+				// S_G-S_L = { x } => destruct x
+			} else if (i == 1) {
+				++i;
+				sout | "goto L2" | endl;
+				// S_G = { y, x }
+				goto L2;  // jump back, do not destruct
+				// S_L-S_G = {}
+				// S_G-S_L = {} => destruct nothing
+			} else if (i == 2) {
+				++i;
+				sout | "goto L3" | endl;
+				// S_G = { y, x }
+				goto L3;  // jump ahead, do not destruct
+				// S_L-S_G = {}
+				// S_G-S_L = {}
+			} else if (false) {
+				++i;
+				A z = { "z" };
+				sout | "goto L3-2" | endl;
+				// S_G = { z, y, x }
+				goto L3;
+				// S_L-S_G = {}
+				// S_G-S_L = {z} => destruct z
+			} else {
+				++i;
+				sout | "goto L4" | endl;
+				// S_G = { y, x }
+				goto L4;  // jump ahead, destruct b/c left block x was defined in
+				// S_L-S_G = {}
+				// S_G-S_L = { y, x } => destruct y, x
+			}
+			// S_L3 = { y, x }
+		L3: sout | "L3" | endl;
+			sout | "goto L2-2" | endl;
+			// S_G = { y, x }
+			goto L2; // jump back, do not destruct
+			// S_L-S_G = {}
+			// S_G-S_L = {}
+	}
+	// S_L4 = {}
+	L4: sout | "L4" | endl;
+	if (i == 4) {
+		sout | "goto L0" | endl;
+		// S_G = {}
+		goto L0;
+		// S_L-S_G = {}
+		// S_G-S_L = {}
+	}
+	// S_G = {}
+#ifdef ERR2
+	if (i == 5) goto L2; // this is an error in g++ because it skips initialization of y, x
+	// S_L-S_G = { y, x } => non-empty, so error
+#endif
+}
+
+int main() {
+	sepDisable(sout);
+	for (int i = 0; i < 4; i++) {
+		f(i);
+	}
+	sout | endl;
+	g();
+	sout | endl;
+	h();
+}
+
Index: src/tests/init_once.c
===================================================================
--- src/tests/init_once.c	(revision 87b5bf0c846782d88723cd4784006befc064183c)
+++ src/tests/init_once.c	(revision 87b5bf0c846782d88723cd4784006befc064183c)
@@ -0,0 +1,169 @@
+//
+// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
+//
+// The contents of this file are covered under the licence agreement in the
+// file "LICENCE" distributed with Cforall.
+//
+// init_once.c --
+//
+// Author           : Rob Schluntz
+// Created On       : Tue Jun 14 15:43:35 2016
+// Last Modified By : Rob Schluntz
+// Last Modified On : Tue Jun 14 15:45:03 2016
+// Update Count     : 1
+//
+
+// want to ensure ctor/dtor called at most once per object.
+// whole point of ctor/dtor is that you don't know what's in
+// memory when it's first called, so can't rely on member to
+// determine if this is true. instead, keep an array
+// of addresses that have been constructed and remove the element
+// when it's destructed (and vice-versa)
+
+//*** setup
+extern "C" {
+typedef unsigned long int size_t;
+#define NULL 0
+void * malloc(size_t);
+void free(void *);
+#define assert(cond) if (! (cond)) { printf("Assertion failed: (%s) at %s:%d\n", #cond, __FILE__, __LINE__); abort(); }
+void abort();
+int printf(const char *, ...);
+void *memset(void *s, int c, size_t n);
+}
+
+// dummy type
+struct init_once { int * x; };
+
+// array and operations
+// const int size = 1024;
+#define size 1024
+struct array {
+	init_once * elems[size];
+	int length;
+};
+void remove(array * arr, init_once * x) {
+	for (int i = 0; i < arr->length; i++) {
+		if ( arr->elems[i] == x ) {
+			arr->elems[i] = arr->elems[--arr->length];
+			return;
+		}
+	}
+}
+void insert(array * arr, init_once * x) {
+	assert( arr->length < size );
+	arr->elems[arr->length++] = x;
+}
+int find(array * arr, init_once * x) {
+	for (int i = 0; i < arr->length; i++) {
+		if ( arr->elems[i] == x ) {
+			return i;
+		}
+	}
+	return -1;
+}
+void ?{}(array * arr) {
+	memset(arr->elems, 0, sizeof(arr->elems));
+	arr->length = 0;
+}
+array constructed;
+array destructed;
+
+void ?{}(init_once * x) {
+	assert( find( &constructed, x ) == -1 );
+	remove( &destructed, x );
+	insert( &constructed, x );
+
+	x->x = malloc(sizeof(int));
+}
+
+void ?{}(init_once * x, init_once other) {
+	x{};  // reuse default ctor
+}
+
+void ^?{}(init_once * x) {
+	assert( find( &destructed, x ) == -1 );
+	remove( &constructed, x );
+	insert( &destructed, x );
+
+	free(x->x);
+}
+//*** end setup
+
+// test globals
+init_once x;
+init_once y = x;
+
+int main() {
+	// local variables
+	init_once x;
+	init_once y = x;
+
+	// block scoped variables
+	{
+		init_once x;
+		init_once y = x;
+	}
+
+	// loop variables
+	for (int i = 0 ; i < 10; i++) {
+		init_once x;
+		init_once y = x;
+	}
+	int i = 0;
+	while (i < 10) {
+		init_once x;
+		init_once y = x;
+		i++;
+	}
+
+	// declared in a switch block with a break
+	for (int i = 0; i < 10; i++) {
+		switch (10) {
+			case 1: {
+				init_once x;
+				init_once y = x;
+				(&x) {}; // ensure this doesn't execute
+				break;
+			}
+			case 10: {
+				init_once x;
+				init_once y = x;
+			} // fall through
+			default: {
+				init_once x;
+				init_once y = x;
+				break;
+			}
+		}
+	}
+
+	// labeled break/continue
+	L3: for (int k = 0; k < 10; k++) {
+		init_once x;
+		init_once y = x;
+		L1: for (int i = 0; i < 10; i++){
+			init_once x;
+			init_once y = x;
+			L2: for (int j = 0; j < 10; j++) {
+				init_once x;
+				init_once y = x;
+
+				if (i == 0) continue L1;
+				if (i == 1) continue L2;
+				if (i == 2) break L2;
+				if (i == 3) break L1;
+				if (i == 4) continue L3;
+				if (i == 9) break L3;
+				// if (i == 5) goto ;
+			}
+		}
+	}
+
+
+}
+
+// Local Variables: //
+// tab-width: 4 //
+// compile-command: "cfa init_once.c" //
+// End: //
