Index: src/AST/Convert.cpp
===================================================================
--- src/AST/Convert.cpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/Convert.cpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -47,8 +47,11 @@
 
 //================================================================================================
-namespace {
+namespace ast {
 
 // This is to preserve the FindSpecialDecls hack. It does not (and perhaps should not)
 // allow us to use the same stratagy in the new ast.
+// xxx - since convert back pass works, this concern seems to be unnecessary.
+
+// these need to be accessed in new FixInit now
 ast::Type * sizeType = nullptr;
 ast::FunctionDecl * dereferenceOperator = nullptr;
@@ -63,4 +66,9 @@
 	using Cache = std::unordered_map< const ast::Node *, BaseSyntaxNode * >;
 	Cache cache;
+
+	// Statements can no longer be shared.
+	// however, since StmtExprResult is now implemented, need to still maintain
+	// readonly references.
+	Cache readonlyCache;
 
 	template<typename T>
@@ -154,12 +162,12 @@
 	}
 
-	const ast::DeclWithType * visit( const ast::ObjectDecl * node ) override final {
-		auto&& bfwd = get<Expression>().accept1( node->bitfieldWidth );
-		auto&& type = get<Type>().accept1( node->type );
-		auto&& init = get<Initializer>().accept1( node->init );
-		auto&& attr = get<Attribute>().acceptL( node->attributes );
+	const ast::DeclWithType * visit( const ast::ObjectDecl * node ) override final {	
 		if ( inCache( node ) ) {
 			return nullptr;
 		}
+		auto bfwd = get<Expression>().accept1( node->bitfieldWidth );
+		auto type = get<Type>().accept1( node->type );
+		auto attr = get<Attribute>().acceptL( node->attributes );
+
 		auto decl = new ObjectDecl(
 			node->name,
@@ -168,9 +176,17 @@
 			bfwd,
 			type->clone(),
-			init,
+			nullptr, // prevent infinite loop
 			attr,
 			Type::FuncSpecifiers( node->funcSpec.val )
 		);
-		return declWithTypePostamble( decl, node );
+
+		// handles the case where node->init references itself
+		// xxx - does it really happen?
+		declWithTypePostamble(decl, node);
+		auto init = get<Initializer>().accept1( node->init );
+		decl->init = init;
+		
+		this->node = decl;
+		return nullptr;
 	}
 
@@ -205,8 +221,8 @@
 		decl->statements = get<CompoundStmt>().accept1( node->stmts );
 		decl->withExprs = get<Expression>().acceptL( node->withExprs );
-		if ( dereferenceOperator == node ) {
+		if ( ast::dereferenceOperator == node ) {
 			Validate::dereferenceOperator = decl;
 		}
-		if ( dtorStructDestroy == node ) {
+		if ( ast::dtorStructDestroy == node ) {
 			Validate::dtorStructDestroy = decl;
 		}
@@ -267,5 +283,5 @@
 		);
 
-		if ( dtorStruct == node ) {
+		if ( ast::dtorStruct == node ) {
 			Validate::dtorStruct = decl;
 		}
@@ -320,5 +336,7 @@
 
 	const ast::Stmt * stmtPostamble( Statement * stmt, const ast::Stmt * node ) {
-		cache.emplace( node, stmt );
+		// force statements in old tree to be unique.
+		// cache.emplace( node, stmt );
+		readonlyCache.emplace( node, stmt );
 		stmt->location = node->location;
 		stmt->labels = makeLabelL( stmt, node->labels );
@@ -337,5 +355,4 @@
 		if ( inCache( node ) ) return nullptr;
 		auto stmt = new ExprStmt( nullptr );
-		cache.emplace( node, stmt );
 		stmt->expr = get<Expression>().accept1( node->expr );
 		return stmtPostamble( stmt, node );
@@ -1011,7 +1028,6 @@
 		auto stmts = node->stmts;
 		// disable sharing between multiple StmtExprs explicitly.
-		if (inCache(stmts)) {
-			stmts = ast::deepCopy(stmts.get());
-		}
+		// this should no longer be true.
+
 		auto rslt = new StmtExpr(
 			get<CompoundStmt>().accept1(stmts)
@@ -1020,4 +1036,8 @@
 		rslt->returnDecls = get<ObjectDecl>().acceptL(node->returnDecls);
 		rslt->dtors       = get<Expression>().acceptL(node->dtors);
+		if (node->resultExpr) {
+			// this MUST be found by children visit
+			rslt->resultExpr  = strict_dynamic_cast<ExprStmt *>(readonlyCache.at(node->resultExpr));
+		}
 
 		auto expr = visitBaseExpr( node, rslt );
@@ -1036,5 +1056,5 @@
 
 		auto expr = visitBaseExpr( node, rslt );
-		this->node = expr;
+		this->node = expr->clone();
 		return nullptr;
 	}
@@ -1126,5 +1146,5 @@
 		auto type = new BasicType{ cv( node ), (BasicType::Kind)(unsigned)node->kind };
 		// I believe this should always be a BasicType.
-		if ( sizeType == node ) {
+		if ( ast::sizeType == node ) {
 			Validate::SizeType = type;
 		}
@@ -1529,4 +1549,6 @@
 
 		// function type is now derived from parameter decls instead of storing them
+
+		/*
 		auto ftype = new ast::FunctionType((ast::ArgumentFlag)old->type->isVarArgs, cv(old->type));
 		ftype->params.reserve(paramVars.size());
@@ -1540,5 +1562,8 @@
 		}
 		ftype->forall = std::move(forall);
-		visitType(old->type, ftype);
+		*/
+
+		// can function type have attributes? seems not to be the case.
+		// visitType(old->type, ftype);
 
 		auto decl = new ast::FunctionDecl{
@@ -1546,4 +1571,5 @@
 			old->name,
 			// GET_ACCEPT_1(type, FunctionType),
+			std::move(forall),
 			std::move(paramVars),
 			std::move(returnVars),
@@ -1552,8 +1578,9 @@
 			{ old->linkage.val },
 			GET_ACCEPT_V(attributes, Attribute),
-			{ old->get_funcSpec().val }
+			{ old->get_funcSpec().val },
+			old->type->isVarArgs
 		};
 
-		decl->type = ftype;
+		// decl->type = ftype;
 		cache.emplace( old, decl );
 
@@ -1570,9 +1597,9 @@
 
 		if ( Validate::dereferenceOperator == old ) {
-			dereferenceOperator = decl;
+			ast::dereferenceOperator = decl;
 		}
 
 		if ( Validate::dtorStructDestroy == old ) {
-			dtorStructDestroy = decl;
+			ast::dtorStructDestroy = decl;
 		}
 	}
@@ -1599,5 +1626,5 @@
 
 		if ( Validate::dtorStruct == old ) {
-			dtorStruct = decl;
+			ast::dtorStruct = decl;
 		}
 	}
@@ -2531,5 +2558,5 @@
 		// I believe this should always be a BasicType.
 		if ( Validate::SizeType == old ) {
-			sizeType = type;
+			ast::sizeType = type;
 		}
 		visitType( old, type );
Index: src/AST/Decl.cpp
===================================================================
--- src/AST/Decl.cpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/Decl.cpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -48,4 +48,23 @@
 
 // --- FunctionDecl
+
+FunctionDecl::FunctionDecl( const CodeLocation & loc, const std::string & name, 
+		std::vector<ptr<TypeDecl>>&& forall,
+		std::vector<ptr<DeclWithType>>&& params, std::vector<ptr<DeclWithType>>&& returns,
+		CompoundStmt * stmts, Storage::Classes storage, Linkage::Spec linkage,
+		std::vector<ptr<Attribute>>&& attrs, Function::Specs fs, bool isVarArgs)
+	: DeclWithType( loc, name, storage, linkage, std::move(attrs), fs ), params(std::move(params)), returns(std::move(returns)),
+	  stmts( stmts ) {
+		  FunctionType * ftype = new FunctionType(static_cast<ArgumentFlag>(isVarArgs));
+		  for (auto & param : this->params) {
+			  ftype->params.emplace_back(param->get_type());
+		  }
+		  for (auto & ret : this->returns) {
+			  ftype->returns.emplace_back(ret->get_type());
+		  }
+		  ftype->forall = std::move(forall);
+		  this->type = ftype;
+	  }
+
 
 const Type * FunctionDecl::get_type() const { return type.get(); }
Index: src/AST/Decl.hpp
===================================================================
--- src/AST/Decl.hpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/Decl.hpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -131,10 +131,10 @@
 	std::vector< ptr<Expr> > withExprs;
 
-	FunctionDecl( const CodeLocation & loc, const std::string & name, 
+	FunctionDecl( const CodeLocation & loc, const std::string & name, std::vector<ptr<TypeDecl>>&& forall,
 		std::vector<ptr<DeclWithType>>&& params, std::vector<ptr<DeclWithType>>&& returns,
 		CompoundStmt * stmts, Storage::Classes storage = {}, Linkage::Spec linkage = Linkage::C,
-		std::vector<ptr<Attribute>>&& attrs = {}, Function::Specs fs = {})
-	: DeclWithType( loc, name, storage, linkage, std::move(attrs), fs ), params(std::move(params)), returns(std::move(returns)),
-	  stmts( stmts ) {}
+		std::vector<ptr<Attribute>>&& attrs = {}, Function::Specs fs = {}, bool isVarArgs = false);
+	// : DeclWithType( loc, name, storage, linkage, std::move(attrs), fs ), params(std::move(params)), returns(std::move(returns)),
+	//  stmts( stmts ) {}
 
 	const Type * get_type() const override;
Index: src/AST/DeclReplacer.cpp
===================================================================
--- src/AST/DeclReplacer.cpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/DeclReplacer.cpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -38,4 +38,14 @@
 			const ast::TypeInstType * previsit( const ast::TypeInstType * );
 		};
+
+		struct VarExprReplacer {
+		private:
+			const ExprMap & exprMap;
+			
+		public:
+			VarExprReplacer(const ExprMap & exprMap): exprMap (exprMap) {}
+
+			const Expr * postvisit (const VariableExpr *);
+		};
 	}
 
@@ -54,4 +64,9 @@
 		DeclMap declMap;
 		return replace( node, declMap, typeMap, debug );
+	}
+
+	const ast::Node * replace( const ast::Node * node, const ExprMap & exprMap) {
+		Pass<VarExprReplacer> replacer = {exprMap};
+		return node->accept( replacer );
 	}
 
@@ -88,4 +103,11 @@
 			return ninst;
 		}
+
+		const Expr * VarExprReplacer::postvisit( const VariableExpr * expr ) {
+			if (!exprMap.count(expr->var)) return expr;
+
+			return exprMap.at(expr->var);
+		}
+
 	}
 }
Index: src/AST/DeclReplacer.hpp
===================================================================
--- src/AST/DeclReplacer.hpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/DeclReplacer.hpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -23,12 +23,15 @@
 	class DeclWithType;
 	class TypeDecl;
+	class Expr;
 
 	namespace DeclReplacer {
 		using DeclMap = std::unordered_map< const DeclWithType *, const DeclWithType * >;
 		using TypeMap = std::unordered_map< const TypeDecl *, const TypeDecl * >;
+		using ExprMap = std::unordered_map< const DeclWithType *, const Expr * >;
 
 		const Node * replace( const Node * node, const DeclMap & declMap, bool debug = false );
 		const Node * replace( const Node * node, const TypeMap & typeMap, bool debug = false );
 		const Node * replace( const Node * node, const DeclMap & declMap, const TypeMap & typeMap, bool debug = false );
+		const Node * replace( const Node * node, const ExprMap & exprMap);
 	}
 }
Index: src/AST/Expr.cpp
===================================================================
--- src/AST/Expr.cpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/Expr.cpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -67,5 +67,5 @@
 // --- UntypedExpr
 
-UntypedExpr * UntypedExpr::createDeref( const CodeLocation & loc, Expr * arg ) {
+UntypedExpr * UntypedExpr::createDeref( const CodeLocation & loc, const Expr * arg ) {
 	assert( arg );
 
@@ -92,5 +92,5 @@
 }
 
-UntypedExpr * UntypedExpr::createAssign( const CodeLocation & loc, Expr * lhs, Expr * rhs ) {
+UntypedExpr * UntypedExpr::createAssign( const CodeLocation & loc, const Expr * lhs, const Expr * rhs ) {
 	assert( lhs && rhs );
 
Index: src/AST/Expr.hpp
===================================================================
--- src/AST/Expr.hpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/Expr.hpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -226,7 +226,7 @@
 
 	/// Creates a new dereference expression
-	static UntypedExpr * createDeref( const CodeLocation & loc, Expr * arg );
+	static UntypedExpr * createDeref( const CodeLocation & loc, const Expr * arg );
 	/// Creates a new assignment expression
-	static UntypedExpr * createAssign( const CodeLocation & loc, Expr * lhs, Expr * rhs );
+	static UntypedExpr * createAssign( const CodeLocation & loc, const Expr * lhs, const Expr * rhs );
 
 	const Expr * accept( Visitor & v ) const override { return v.visit( this ); }
@@ -422,5 +422,5 @@
 		const CodeLocation & loc, const Type * ty, const std::string & r,
 			std::optional<unsigned long long> i )
-	: Expr( loc, ty ), rep( r ), ival( i ) {}
+	: Expr( loc, ty ), rep( r ), ival( i ), underlyer(ty) {}
 
 	/// Gets the integer value of this constant, if one is appropriate to its type.
@@ -617,5 +617,5 @@
 
 	ImplicitCopyCtorExpr( const CodeLocation& loc, const ApplicationExpr * call )
-	: Expr( loc, call->result ) { assert( call ); }
+	: Expr( loc, call->result ), callExpr(call) { assert( call ); assert(call->result); }
 
 	const Expr * accept( Visitor & v ) const override { return v.visit( this ); }
@@ -742,4 +742,6 @@
 	std::vector<ptr<Expr>> dtors;              ///< destructor(s) for return variable(s)
 
+	readonly<ExprStmt> resultExpr;
+
 	StmtExpr( const CodeLocation & loc, const CompoundStmt * ss );
 
Index: src/AST/Fwd.hpp
===================================================================
--- src/AST/Fwd.hpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/Fwd.hpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -137,3 +137,8 @@
 typedef unsigned int UniqueId;
 
+extern Type * sizeType;
+extern FunctionDecl * dereferenceOperator;
+extern StructDecl   * dtorStruct;
+extern FunctionDecl * dtorStructDestroy;
+
 }
Index: src/AST/Node.hpp
===================================================================
--- src/AST/Node.hpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/Node.hpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -49,4 +49,5 @@
 
 	bool unique() const { return strong_count == 1; }
+	bool isManaged() const {return strong_count > 0; }
 
 private:
Index: src/AST/Pass.hpp
===================================================================
--- src/AST/Pass.hpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/Pass.hpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -236,4 +236,8 @@
 	const ast::Expr * call_accept( const ast::Expr * );
 
+	// requests WithStmtsToAdd directly add to this statement, as if it is a compound.
+
+	const ast::Stmt * call_accept_as_compound(const ast::Stmt *);
+
 	template< typename node_t >
 	auto call_accept( const node_t * node ) -> typename std::enable_if<
@@ -257,4 +261,7 @@
 	template<typename node_t, typename parent_t, typename child_t>
 	void maybe_accept(const node_t * &, child_t parent_t::* child);
+
+	template<typename node_t, typename parent_t, typename child_t>
+	void maybe_accept_as_compound(const node_t * &, child_t parent_t::* child);
 
 private:
Index: src/AST/Pass.impl.hpp
===================================================================
--- src/AST/Pass.impl.hpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/Pass.impl.hpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -167,4 +167,12 @@
 		__pedantic_pass_assert( stmt );
 
+		return stmt->accept( *this );
+	}
+
+	template< typename core_t >
+	const ast::Stmt * ast::Pass< core_t >::call_accept_as_compound( const ast::Stmt * stmt ) {
+		__pedantic_pass_assert( __visit_children() );
+		__pedantic_pass_assert( stmt );
+
 		// add a few useful symbols to the scope
 		using __pass::empty;
@@ -324,4 +332,28 @@
 
 		auto new_val = call_accept( old_val );
+
+		static_assert( !std::is_same<const ast::Node *, decltype(new_val)>::value || std::is_same<int, decltype(old_val)>::value, "ERROR");
+
+		if( __pass::differs(old_val, new_val) ) {
+			auto new_parent = __pass::mutate<core_t>(parent);
+			new_parent->*child = new_val;
+			parent = new_parent;
+		}
+	}
+
+	template< typename core_t >
+	template<typename node_t, typename parent_t, typename child_t>
+	void ast::Pass< core_t >::maybe_accept_as_compound(
+		const node_t * & parent,
+		child_t parent_t::*child
+	) {
+		static_assert( std::is_base_of<parent_t, node_t>::value, "Error deducing member object" );
+
+		if(__pass::skip(parent->*child)) return;
+		const auto & old_val = __pass::get(parent->*child, 0);
+
+		static_assert( !std::is_same<const ast::Node * &, decltype(old_val)>::value, "ERROR");
+
+		auto new_val = call_accept_as_compound( old_val );
 
 		static_assert( !std::is_same<const ast::Node *, decltype(new_val)>::value || std::is_same<int, decltype(old_val)>::value, "ERROR");
@@ -703,6 +735,6 @@
 		maybe_accept( node, &IfStmt::inits    );
 		maybe_accept( node, &IfStmt::cond     );
-		maybe_accept( node, &IfStmt::thenPart );
-		maybe_accept( node, &IfStmt::elsePart );
+		maybe_accept_as_compound( node, &IfStmt::thenPart );
+		maybe_accept_as_compound( node, &IfStmt::elsePart );
 	})
 
@@ -721,5 +753,5 @@
 		maybe_accept( node, &WhileStmt::inits );
 		maybe_accept( node, &WhileStmt::cond  );
-		maybe_accept( node, &WhileStmt::body  );
+		maybe_accept_as_compound( node, &WhileStmt::body  );
 	})
 
@@ -736,8 +768,9 @@
 		// for statements introduce a level of scope (for the initialization)
 		guard_symtab guard { *this };
+		// xxx - old ast does not create WithStmtsToAdd scope for loop inits. should revisit this later.
 		maybe_accept( node, &ForStmt::inits );
 		maybe_accept( node, &ForStmt::cond  );
 		maybe_accept( node, &ForStmt::inc   );
-		maybe_accept( node, &ForStmt::body  );
+		maybe_accept_as_compound( node, &ForStmt::body  );
 	})
 
@@ -834,5 +867,5 @@
 		maybe_accept( node, &CatchStmt::decl );
 		maybe_accept( node, &CatchStmt::cond );
-		maybe_accept( node, &CatchStmt::body );
+		maybe_accept_as_compound( node, &CatchStmt::body );
 	})
 
Index: src/AST/SymbolTable.cpp
===================================================================
--- src/AST/SymbolTable.cpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/SymbolTable.cpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -335,11 +335,11 @@
 }
 
-/*
-void SymbolTable::addFunctionType( const FunctionType * ftype ) {
-	addTypes( ftype->forall );
-	addIds( ftype->returns );
-	addIds( ftype->params );
-}
-*/
+
+void SymbolTable::addFunction( const FunctionDecl * func ) {
+	addTypes( func->type->forall );
+	addIds( func->returns );
+	addIds( func->params );
+}
+
 
 void SymbolTable::lazyInitScope() {
Index: src/AST/SymbolTable.hpp
===================================================================
--- src/AST/SymbolTable.hpp	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/AST/SymbolTable.hpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -145,5 +145,5 @@
 
 	/// convenience function for adding all of the declarations in a function type to the indexer
-	// void addFunctionType( const FunctionType * ftype );
+	void addFunction( const FunctionDecl * );
 
 private:
Index: src/Common/utility.h
===================================================================
--- src/Common/utility.h	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/Common/utility.h	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -360,7 +360,8 @@
 	reverse_iterate_t( T & ref ) : ref(ref) {}
 
-	typedef typename T::reverse_iterator iterator;
-	iterator begin() { return ref.rbegin(); }
-	iterator end() { return ref.rend(); }
+	// this does NOT work on const T!!!
+	// typedef typename T::reverse_iterator iterator;
+	auto begin() { return ref.rbegin(); }
+	auto end() { return ref.rend(); }
 };
 
Index: src/GenPoly/GenPoly.cc
===================================================================
--- src/GenPoly/GenPoly.cc	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/GenPoly/GenPoly.cc	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -46,4 +46,12 @@
 		}
 
+		bool hasPolyParams( const std::vector<ast::ptr<ast::Expr>> & params, const ast::TypeSubstitution * env) {
+			for (auto &param : params) {
+				auto paramType = param.strict_as<ast::TypeExpr>();
+				if (isPolyType(paramType->type, env)) return true;
+			}
+			return false;
+		}
+
 		/// Checks a parameter list for polymorphic parameters from tyVars; will substitute according to env if present
 		bool hasPolyParams( std::list< Expression* >& params, const TyVarMap &tyVars, const TypeSubstitution *env ) {
@@ -56,4 +64,12 @@
 		}
 
+		bool hasPolyParams( const std::vector<ast::ptr<ast::Expr>> & params, const TyVarMap & tyVars, const ast::TypeSubstitution * env) {
+			for (auto &param : params) {
+				auto paramType = param.strict_as<ast::TypeExpr>();
+				if (isPolyType(paramType->type, tyVars, env)) return true;
+			}
+			return false;
+		}
+
 		/// Checks a parameter list for dynamic-layout parameters from tyVars; will substitute according to env if present
 		bool hasDynParams( std::list< Expression* >& params, const TyVarMap &tyVars, const TypeSubstitution *env ) {
@@ -92,4 +108,13 @@
 			Type *newType = env->lookup( typeInst->get_name() );
 			if ( newType ) return newType;
+		}
+		return type;
+	}
+
+	const ast::Type * replaceTypeInst(const ast::Type * type, const ast::TypeSubstitution * env) {
+		if (!env) return type;
+		if (auto typeInst = dynamic_cast<const ast::TypeInstType*> (type)) {
+			auto newType = env->lookup(typeInst->name);
+			if (newType) return newType;
 		}
 		return type;
@@ -111,4 +136,19 @@
 	}
 
+	const ast::Type * isPolyType(const ast::Type * type, const ast::TypeSubstitution * env) {
+		type = replaceTypeInst( type, env );
+
+		if ( dynamic_cast< const ast::TypeInstType * >( type ) ) {
+			return type;
+		} else if ( auto arrayType = dynamic_cast< const ast::ArrayType * >( type ) ) {
+			return isPolyType( arrayType->base, env );
+		} else if ( auto structType = dynamic_cast< const ast::StructInstType* >( type ) ) {
+			if ( hasPolyParams( structType->params, env ) ) return type;
+		} else if ( auto unionType = dynamic_cast< const ast::UnionInstType* >( type ) ) {
+			if ( hasPolyParams( unionType->params, env ) ) return type;
+		}
+		return 0;
+	}
+
 	Type *isPolyType( Type *type, const TyVarMap &tyVars, const TypeSubstitution *env ) {
 		type = replaceTypeInst( type, env );
@@ -126,4 +166,19 @@
 		}
 		return 0;
+	}
+
+	const ast::Type * isPolyType(const ast::Type * type, const TyVarMap & tyVars, const ast::TypeSubstitution * env) {
+		type = replaceTypeInst( type, env );
+
+		if ( auto typeInst = dynamic_cast< const ast::TypeInstType * >( type ) ) {
+			return tyVars.find(typeInst->name) != tyVars.end() ? type : nullptr;
+		} else if ( auto arrayType = dynamic_cast< const ast::ArrayType * >( type ) ) {
+			return isPolyType( arrayType->base, env );
+		} else if ( auto structType = dynamic_cast< const ast::StructInstType* >( type ) ) {
+			if ( hasPolyParams( structType->params, env ) ) return type;
+		} else if ( auto unionType = dynamic_cast< const ast::UnionInstType* >( type ) ) {
+			if ( hasPolyParams( unionType->params, env ) ) return type;
+		}
+		return nullptr;
 	}
 
@@ -449,4 +504,12 @@
 	}
 
+	namespace {
+		// temporary hack to avoid re-implementing anything related to TyVarMap
+		// does this work? these two structs have identical definitions.
+		inline TypeDecl::Data convData(const ast::TypeDecl::Data & data) {
+			return *reinterpret_cast<const TypeDecl::Data *>(&data);
+		}
+	}
+
 	bool needsBoxing( Type * param, Type * arg, const TyVarMap &exprTyVars, const TypeSubstitution * env ) {
 		// is parameter is not polymorphic, don't need to box
@@ -459,4 +522,13 @@
 	}
 
+	bool needsBoxing( const ast::Type * param, const ast::Type * arg, const TyVarMap &exprTyVars, const ast::TypeSubstitution * env) {
+		// is parameter is not polymorphic, don't need to box
+		if ( ! isPolyType( param, exprTyVars ) ) return false;
+		ast::ptr<ast::Type> newType = arg;
+		if ( env ) env->apply( newType );
+		// if the argument's type is polymorphic, we don't need to box again!
+		return ! isPolyType( newType );
+	}
+
 	bool needsBoxing( Type * param, Type * arg, ApplicationExpr * appExpr, const TypeSubstitution * env ) {
 		FunctionType * function = getFunctionType( appExpr->function->result );
@@ -467,6 +539,19 @@
 	}
 
+	bool needsBoxing( const ast::Type * param, const ast::Type * arg, const ast::ApplicationExpr * appExpr, const ast::TypeSubstitution * env) {
+		const ast::FunctionType * function = getFunctionType(appExpr->func->result);
+		assertf( function, "ApplicationExpr has non-function type: %s", toString( appExpr->func->result ).c_str() );
+		TyVarMap exprTyVars(TypeDecl::Data{});
+		makeTyVarMap(function, exprTyVars);
+		return needsBoxing(param, arg, exprTyVars, env);
+
+	}
+
 	void addToTyVarMap( TypeDecl * tyVar, TyVarMap &tyVarMap ) {
 		tyVarMap.insert( tyVar->name, TypeDecl::Data{ tyVar } );
+	}
+
+	void addToTyVarMap( const ast::TypeDecl * tyVar, TyVarMap & tyVarMap) {
+		tyVarMap.insert(tyVar->name, convData(ast::TypeDecl::Data{tyVar}));
 	}
 
@@ -478,4 +563,16 @@
 		if ( PointerType *pointer = dynamic_cast< PointerType* >( type ) ) {
 			makeTyVarMap( pointer->get_base(), tyVarMap );
+		}
+	}
+
+	void makeTyVarMap(const ast::Type * type, TyVarMap & tyVarMap) {
+		if (auto ptype = dynamic_cast<const ast::ParameterizedType *>(type)) {
+ 			for (auto & tyVar : ptype->forall) {
+				assert (tyVar);
+				addToTyVarMap(tyVar, tyVarMap);
+			}
+		}
+		if (auto pointer = dynamic_cast<const ast::PointerType *>(type)) {
+			makeTyVarMap(pointer->base, tyVarMap);
 		}
 	}
Index: src/GenPoly/GenPoly.h
===================================================================
--- src/GenPoly/GenPoly.h	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/GenPoly/GenPoly.h	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -26,6 +26,6 @@
 
 namespace GenPoly {
+
 	typedef ErasableScopedMap< std::string, TypeDecl::Data > TyVarMap;
-
 	/// Replaces a TypeInstType by its referrent in the environment, if applicable
 	Type* replaceTypeInst( Type* type, const TypeSubstitution* env );
@@ -33,7 +33,9 @@
 	/// returns polymorphic type if is polymorphic type, NULL otherwise; will look up substitution in env if provided
 	Type *isPolyType( Type *type, const TypeSubstitution *env = 0 );
+	const ast::Type * isPolyType(const ast::Type * type, const ast::TypeSubstitution * env = nullptr);
 
 	/// returns polymorphic type if is polymorphic type in tyVars, NULL otherwise; will look up substitution in env if provided
 	Type *isPolyType( Type *type, const TyVarMap &tyVars, const TypeSubstitution *env = 0 );
+	const ast::Type * isPolyType(const ast::Type * type, const TyVarMap & tyVars, const ast::TypeSubstitution * env = nullptr);
 
 	/// returns dynamic-layout type if is dynamic-layout type in tyVars, NULL otherwise; will look up substitution in env if provided
@@ -84,7 +86,9 @@
 	/// true if arg requires boxing given exprTyVars
 	bool needsBoxing( Type * param, Type * arg, const TyVarMap &exprTyVars, const TypeSubstitution * env );
+	bool needsBoxing( const ast::Type * param, const ast::Type * arg, const TyVarMap &exprTyVars, const ast::TypeSubstitution * env);
 
 	/// true if arg requires boxing in the call to appExpr
 	bool needsBoxing( Type * param, Type * arg, ApplicationExpr * appExpr, const TypeSubstitution * env );
+	bool needsBoxing( const ast::Type * param, const ast::Type * arg, const ast::ApplicationExpr * appExpr, const ast::TypeSubstitution * env);
 
 	/// Adds the type variable `tyVar` to `tyVarMap`
@@ -93,4 +97,5 @@
 	/// Adds the declarations in the forall list of type (and its pointed-to type if it's a pointer type) to `tyVarMap`
 	void makeTyVarMap( Type *type, TyVarMap &tyVarMap );
+	void makeTyVarMap(const ast::Type * type, TyVarMap & tyVarMap);
 
 	/// Prints type variable map
Index: src/InitTweak/FixGlobalInit.cc
===================================================================
--- src/InitTweak/FixGlobalInit.cc	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/InitTweak/FixGlobalInit.cc	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -34,4 +34,8 @@
 #include "SynTree/Visitor.h"       // for acceptAll, Visitor
 
+#include "AST/Expr.hpp"
+#include "AST/Node.hpp"
+#include "AST/Pass.hpp"
+
 namespace InitTweak {
 	class GlobalFixer : public WithShortCircuiting {
@@ -50,4 +54,18 @@
 		FunctionDecl * initFunction;
 		FunctionDecl * destroyFunction;
+	};
+
+	class GlobalFixer_new : public ast::WithShortCircuiting {
+	public:
+		void previsit (const ast::ObjectDecl *);
+		void previsit (const ast::FunctionDecl *) { visit_children = false; }
+		void previsit (const ast::StructDecl *) { visit_children = false; }
+		void previsit (const ast::UnionDecl *) { visit_children = false; }
+		void previsit (const ast::EnumDecl *) { visit_children = false; }
+		void previsit (const ast::TraitDecl *) { visit_children = false; }
+		void previsit (const ast::TypeDecl *) { visit_children = false; }
+
+		std::list< ast::ptr<ast::Stmt> > initStmts;
+		std::list< ast::ptr<ast::Stmt> > destroyStmts;
 	};
 
@@ -91,4 +109,27 @@
 	}
 
+	void fixGlobalInit(std::list<ast::ptr<ast::Decl>> & translationUnit, bool inLibrary) {
+		ast::Pass<GlobalFixer_new> fixer;
+		accept_all(translationUnit, fixer);
+
+		if ( !fixer.core.initStmts.empty() ) {
+			std::vector<ast::ptr<ast::Expr>> ctorParams;
+			if (inLibrary) ctorParams.emplace_back(ast::ConstantExpr::from_int({}, 200));
+			auto initFunction = new ast::FunctionDecl({}, "__global_init__", {}, {}, {}, new ast::CompoundStmt({}, std::move(fixer.core.initStmts)), 
+				ast::Storage::Static, ast::Linkage::C, {new ast::Attribute("constructor", std::move(ctorParams))});
+
+			translationUnit.emplace_back( initFunction );
+		} // if
+
+		if ( !fixer.core.destroyStmts.empty() ) {
+			std::vector<ast::ptr<ast::Expr>> dtorParams;
+			if (inLibrary) dtorParams.emplace_back(ast::ConstantExpr::from_int({}, 200));
+			auto destroyFunction = new ast::FunctionDecl({}, "__global_destroy__", {}, {}, {}, new ast::CompoundStmt({}, std::move(fixer.core.destroyStmts)), 
+				ast::Storage::Static, ast::Linkage::C, {new ast::Attribute("destructor", std::move(dtorParams))});
+
+			translationUnit.emplace_back(destroyFunction);
+		} // if
+	}
+
 	void GlobalFixer::previsit( ObjectDecl *objDecl ) {
 		std::list< Statement * > & initStatements = initFunction->get_statements()->get_kids();
@@ -127,4 +168,33 @@
 	}
 
+	void GlobalFixer_new::previsit(const ast::ObjectDecl * objDecl) {
+		auto mutDecl = mutate(objDecl);
+		assertf(mutDecl == objDecl, "Global object decl must be unique");
+		if ( auto ctorInit = objDecl->init.as<ast::ConstructorInit>() ) {
+			// a decision should have been made by the resolver, so ctor and init are not both non-NULL
+			assert( ! ctorInit->ctor || ! ctorInit->init );
+
+			const ast::Stmt * dtor = ctorInit->dtor;
+			if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
+				// don't need to call intrinsic dtor, because it does nothing, but
+				// non-intrinsic dtors must be called
+				destroyStmts.push_front( dtor );
+				// ctorInit->dtor = nullptr;
+			} // if
+			if ( const ast::Stmt * ctor = ctorInit->ctor ) {
+				initStmts.push_back( ctor );
+				mutDecl->init = nullptr;
+				// ctorInit->ctor = nullptr;
+			} else if ( const ast::Init * init = ctorInit->init ) {
+				mutDecl->init = init;
+				// ctorInit->init = nullptr;
+			} else {
+				// no constructor and no initializer, which is okay
+				mutDecl->init = nullptr;
+			} // if
+			// delete ctorInit;
+		} // if
+	}
+
 	// only modify global variables
 	void GlobalFixer::previsit( FunctionDecl * ) { visit_children = false; }
Index: src/InitTweak/FixGlobalInit.h
===================================================================
--- src/InitTweak/FixGlobalInit.h	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/InitTweak/FixGlobalInit.h	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -19,4 +19,7 @@
 #include <string>  // for string
 
+#include <AST/Fwd.hpp>
+
+
 class Declaration;
 
@@ -26,4 +29,5 @@
 	/// function is for library code.
 	void fixGlobalInit( std::list< Declaration * > & translationUnit, bool inLibrary );
+	void fixGlobalInit( std::list< ast::ptr<ast::Decl> > & translationUnit, bool inLibrary );
 } // namespace
 
Index: src/InitTweak/FixInit.cc
===================================================================
--- src/InitTweak/FixInit.cc	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/InitTweak/FixInit.cc	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -219,5 +219,5 @@
 		};
 
-		struct SplitExpressions : public WithShortCircuiting, public WithTypeSubstitution, public WithStmtsToAdd {
+		struct SplitExpressions : public WithShortCircuiting, /*public WithTypeSubstitution, */public WithStmtsToAdd {
 			/// add CompoundStmts around top-level expressions so that temporaries are destroyed in the correct places.
 			static void split( std::list< Declaration * > &translationUnit );
Index: src/InitTweak/FixInit.h
===================================================================
--- src/InitTweak/FixInit.h	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/InitTweak/FixInit.h	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -19,4 +19,6 @@
 #include <string>  // for string
 
+#include <AST/Fwd.hpp>
+
 class Declaration;
 
@@ -24,4 +26,6 @@
 	/// replace constructor initializers with expression statements and unwrap basic C-style initializers
 	void fix( std::list< Declaration * > & translationUnit, bool inLibrary );
+
+	void fix( std::list<ast::ptr<ast::Decl>> & translationUnit, bool inLibrary);
 } // namespace
 
Index: src/InitTweak/FixInitNew.cpp
===================================================================
--- src/InitTweak/FixInitNew.cpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
+++ src/InitTweak/FixInitNew.cpp	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -0,0 +1,1439 @@
+#include "FixInit.h"
+
+#include <stddef.h>                    // for NULL
+#include <algorithm>                   // for set_difference, copy_if
+#include <cassert>                     // for assert, strict_dynamic_cast
+#include <iostream>                    // for operator<<, ostream, basic_ost...
+#include <iterator>                    // for insert_iterator, back_inserter
+#include <list>                        // for _List_iterator, list, list<>::...
+#include <map>                         // for _Rb_tree_iterator, _Rb_tree_co...
+#include <memory>                      // for allocator_traits<>::value_type
+#include <set>                         // for set, set<>::value_type
+#include <unordered_map>               // for unordered_map, unordered_map<>...
+#include <unordered_set>               // for unordered_set
+#include <utility>                     // for pair
+
+#include "CodeGen/GenType.h"           // for genPrettyType
+#include "CodeGen/OperatorTable.h"
+#include "Common/PassVisitor.h"        // for PassVisitor, WithStmtsToAdd
+#include "Common/SemanticError.h"      // for SemanticError
+#include "Common/UniqueName.h"         // for UniqueName
+#include "Common/utility.h"            // for CodeLocation, ValueGuard, toSt...
+#include "FixGlobalInit.h"             // for fixGlobalInit
+#include "GenInit.h"                   // for genCtorDtor
+#include "GenPoly/GenPoly.h"           // for getFunctionType
+#include "InitTweak.h"                 // for getFunctionName, getCallArg
+#include "ResolvExpr/Resolver.h"       // for findVoidExpression
+#include "ResolvExpr/typeops.h"        // for typesCompatible
+#include "SymTab/Autogen.h"            // for genImplicitCall
+#include "SymTab/Indexer.h"            // for Indexer
+#include "SymTab/Mangler.h"            // for Mangler
+#include "SynTree/LinkageSpec.h"       // for C, Spec, Cforall, isBuiltin
+#include "SynTree/Attribute.h"         // for Attribute
+#include "SynTree/Constant.h"          // for Constant
+#include "SynTree/Declaration.h"       // for ObjectDecl, FunctionDecl, Decl...
+#include "SynTree/Expression.h"        // for UniqueExpr, VariableExpr, Unty...
+#include "SynTree/Initializer.h"       // for ConstructorInit, SingleInit
+#include "SynTree/Label.h"             // for Label, operator<
+#include "SynTree/Mutator.h"           // for mutateAll, Mutator, maybeMutate
+#include "SynTree/Statement.h"         // for ExprStmt, CompoundStmt, Branch...
+#include "SynTree/Type.h"              // for Type, Type::StorageClasses
+#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution, operator<<
+#include "SynTree/DeclReplacer.h"      // for DeclReplacer
+#include "SynTree/Visitor.h"           // for acceptAll, maybeAccept
+#include "Validate/FindSpecialDecls.h" // for dtorStmt, dtorStructDestroy
+
+#include "AST/Expr.hpp"
+#include "AST/Node.hpp"
+#include "AST/Pass.hpp"
+#include "AST/Print.hpp"
+#include "AST/SymbolTable.hpp"
+#include "AST/Type.hpp"
+#include "AST/DeclReplacer.hpp"
+
+extern bool ctordtorp; // print all debug
+extern bool ctorp; // print ctor debug
+extern bool cpctorp; // print copy ctor debug
+extern bool dtorp; // print dtor debug
+#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 {
+	namespace {
+		struct SelfAssignChecker {
+			void previsit( const ast::ApplicationExpr * appExpr );
+		};
+
+		struct StmtExprResult {
+			static void link( std::list<ast::ptr<ast::Decl> > & translationUnit );
+
+			const ast::StmtExpr * previsit( const ast::StmtExpr * stmtExpr );
+		};
+
+		struct InsertImplicitCalls : public ast::WithConstTypeSubstitution, public ast::WithShortCircuiting {
+			/// 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<ast::ptr<ast::Decl> > & translationUnit );
+
+			const ast::Expr * postvisit( const ast::ApplicationExpr * appExpr );
+
+			// only handles each UniqueExpr once
+			// if order of visit does not change, this should be safe
+			void previsit (const ast::UniqueExpr *);
+
+			std::unordered_set<decltype(ast::UniqueExpr::id)> visitedIds;
+		};
+
+		struct ResolveCopyCtors final : public ast::WithGuards, public ast::WithStmtsToAdd<>, public ast::WithSymbolTable, public ast::WithShortCircuiting, public ast::WithVisitorRef<ResolveCopyCtors> {
+			/// 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<ast::ptr<ast::Decl> > & translationUnit );
+
+			const ast::Expr * postvisit( const ast::ImplicitCopyCtorExpr * impCpCtorExpr );
+			const ast::StmtExpr * previsit( const ast::StmtExpr * stmtExpr );
+			const ast::UniqueExpr * previsit( const ast::UniqueExpr * unqExpr );
+
+			/// handles distant mutations of environment manually. 
+			/// WithConstTypeSubstitution cannot remember where the environment is from
+
+			/// MUST be called at start of overload previsit
+			void previsit( const ast::Expr * expr);
+			/// MUST be called at return of overload postvisit
+			const ast::Expr * postvisit(const ast::Expr * expr);
+
+			/// create and resolve ctor/dtor expression: fname(var, [cpArg])
+			const ast::Expr * makeCtorDtor( const std::string & fname, const ast::ObjectDecl * var, const ast::Expr * cpArg = nullptr );
+			/// true if type does not need to be copy constructed to ensure correctness
+			bool skipCopyConstruct( const ast::Type * type );
+			ast::ptr< ast::Expr > copyConstructArg( const ast::Expr * arg, const ast::ImplicitCopyCtorExpr * impCpCtorExpr, const ast::Type * formal );
+			ast::Expr * destructRet( const ast::ObjectDecl * ret, const ast::Expr * arg );
+		private:
+			/// hack to implement WithTypeSubstitution while conforming to mutation safety.
+			ast::TypeSubstitution * env;
+			bool                    envModified;
+		};
+
+		/// collects constructed object decls - used as a base class
+		struct ObjDeclCollector : public ast::WithGuards, public ast::WithShortCircuiting {
+			// use ordered data structure to maintain ordering for set_difference and for consistent error messages
+			typedef std::list< const ast::ObjectDecl * > ObjectSet;
+			void previsit( const ast::CompoundStmt *compoundStmt );
+			void previsit( const ast::DeclStmt *stmt );
+
+			// don't go into other functions
+			void previsit( const ast::FunctionDecl * ) { visit_children = false; }
+
+		  protected:
+			ObjectSet curVars;
+		};
+
+		// debug
+		template<typename ObjectSet>
+		struct PrintSet {
+			PrintSet( const ObjectSet & objs ) : objs( objs ) {}
+			const ObjectSet & objs;
+		};
+		template<typename ObjectSet>
+		PrintSet<ObjectSet> printSet( const ObjectSet & objs ) { return PrintSet<ObjectSet>( objs ); }
+		template<typename ObjectSet>
+		std::ostream & operator<<( std::ostream & out, const PrintSet<ObjectSet> & set) {
+			out << "{ ";
+			for ( auto & obj : set.objs ) {
+				out << obj->name << ", " ;
+			} // for
+			out << " }";
+			return out;
+		}
+
+		struct LabelFinder final : public ObjDeclCollector {
+			typedef std::map< std::string, ObjectSet > LabelMap;
+			// map of Label -> live variables at that label
+			LabelMap vars;
+
+			typedef ObjDeclCollector Parent;
+			using Parent::previsit;
+			void previsit( const ast::Stmt * stmt );
+
+			void previsit( const ast::CompoundStmt *compoundStmt );
+			void previsit( const ast::DeclStmt *stmt );
+		};
+
+		struct InsertDtors final : public ObjDeclCollector, public ast::WithStmtsToAdd<> {
+			/// insert destructor calls at the appropriate places.  must happen before CtorInit nodes are removed
+			/// (currently by FixInit)
+			static void insert( std::list< ast::ptr<ast::Decl> > & translationUnit );
+
+			typedef std::list< ObjectDecl * > OrderedDecls;
+			typedef std::list< OrderedDecls > OrderedDeclsStack;
+
+			InsertDtors( ast::Pass<LabelFinder> & finder ) : finder( finder ), labelVars( finder.core.vars ) {}
+
+			typedef ObjDeclCollector Parent;
+			using Parent::previsit;
+
+			void previsit( const ast::FunctionDecl * funcDecl );
+
+			void previsit( const ast::BranchStmt * stmt );
+		private:
+			void handleGoto( const ast::BranchStmt * stmt );
+
+			ast::Pass<LabelFinder> & finder;
+			LabelFinder::LabelMap & labelVars;
+			OrderedDeclsStack reverseDeclOrder;
+		};
+
+		class FixInit : public ast::WithStmtsToAdd<> {
+		  public:
+			/// expand each object declaration to use its constructor after it is declared.
+			static void fixInitializers( std::list< ast::ptr<ast::Decl> > &translationUnit );
+
+			const ast::DeclWithType * postvisit( const ast::ObjectDecl *objDecl );
+
+			std::list< ast::ptr< ast::Decl > > staticDtorDecls;
+		};
+
+		struct GenStructMemberCalls final : public ast::WithGuards, public ast::WithShortCircuiting, public ast::WithSymbolTable, public ast::WithVisitorRef<GenStructMemberCalls> {
+			/// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
+			/// for any member that is missing a corresponding ctor/dtor call.
+			/// error if a member is used before constructed
+			static void generate( std::list< ast::ptr<ast::Decl> > & translationUnit );
+
+			void previsit( const ast::FunctionDecl * funcDecl );
+			const ast::DeclWithType * postvisit( const ast::FunctionDecl * funcDecl );
+
+			void previsit( const ast::MemberExpr * memberExpr );
+			void previsit( const ast::ApplicationExpr * appExpr );
+
+			/// Note: this post mutate used to be in a separate visitor. If this pass breaks, one place to examine is whether it is
+			/// okay for this part of the recursion to occur alongside the rest.
+			const ast::Expr * postvisit( const ast::UntypedExpr * expr );
+
+			SemanticErrorException errors;
+		  private:
+			template< typename... Params >
+			void emit( CodeLocation, const Params &... params );
+
+			ast::FunctionDecl * function = nullptr;
+			std::set< const ast::DeclWithType * > unhandled;
+			std::map< const ast::DeclWithType *, CodeLocation > usedUninit;
+			const ast::ObjectDecl * thisParam = nullptr;
+			bool isCtor = false; // true if current function is a constructor
+			const ast::StructDecl * structDecl = nullptr;
+		};
+
+		struct FixCtorExprs final : public ast::WithDeclsToAdd<>, public ast::WithSymbolTable, public ast::WithShortCircuiting {
+			/// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
+			static void fix( std::list< ast::ptr<ast::Decl> > & translationUnit );
+
+			const ast::Expr * postvisit( const ast::ConstructorExpr * ctorExpr );
+		};
+
+		struct SplitExpressions : public ast::WithShortCircuiting {
+			/// add CompoundStmts around top-level expressions so that temporaries are destroyed in the correct places.
+			static void split( std::list<ast::ptr<ast::Decl> > & translationUnit );
+
+			ast::Stmt * postvisit( const ast::ExprStmt * stmt );
+			void previsit( const ast::TupleAssignExpr * expr );
+		};
+	} // namespace
+
+	void fix( std::list< ast::ptr<ast::Decl> > & translationUnit, bool inLibrary ) {
+		ast::Pass<SelfAssignChecker> checker;
+		accept_all( translationUnit, checker );
+
+		// fixes StmtExpr to properly link to their resulting expression
+		StmtExprResult::link( translationUnit );
+
+		// fixes ConstructorInit for global variables. should happen before fixInitializers.
+		InitTweak::fixGlobalInit( translationUnit, inLibrary );
+
+		// must happen before ResolveCopyCtors because temporaries have to be inserted into the correct scope
+		SplitExpressions::split( translationUnit );
+
+		InsertImplicitCalls::insert( translationUnit );
+
+		// Needs to happen before ResolveCopyCtors, because argument/return temporaries should not be considered in
+		// error checking branch statements
+		InsertDtors::insert( translationUnit );
+
+		ResolveCopyCtors::resolveImplicitCalls( translationUnit );
+		FixInit::fixInitializers( translationUnit );
+		GenStructMemberCalls::generate( translationUnit );
+
+		// Needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
+		// don't have the correct form, and a member can be constructed more than once.
+		FixCtorExprs::fix( translationUnit );
+	}
+
+	namespace {
+		/// find and return the destructor used in `input`. If `input` is not a simple destructor call, generate a thunk
+		/// that wraps the destructor, insert it into `stmtsToAdd` and return the new function declaration
+		const ast::DeclWithType * getDtorFunc( const ast::ObjectDecl * objDecl, const ast::Stmt * input, std::list< ast::ptr<ast::Stmt> > & stmtsToAdd ) {
+			const CodeLocation loc = input->location;
+			// unwrap implicit statement wrapper
+			// Statement * dtor = input;
+			assert( input );
+			// std::list< const ast::Expr * > matches;
+			auto matches = collectCtorDtorCalls( input );
+
+			if ( dynamic_cast< const ast::ExprStmt * >( input ) ) {
+				// only one destructor call in the expression
+				if ( matches.size() == 1 ) {
+					auto func = getFunction( matches.front() );
+					assertf( func, "getFunction failed to find function in %s", toString( matches.front() ).c_str() );
+
+					// cleanup argument must be a function, not an object (including function pointer)
+					if ( auto dtorFunc = dynamic_cast< const ast::FunctionDecl * > ( func ) ) {
+						if ( dtorFunc->type->forall.empty() ) {
+							// simple case where the destructor is a monomorphic function call - can simply
+							// use that function as the cleanup function.
+							return func;
+						}
+					}
+				}
+			}
+
+			// otherwise the cleanup is more complicated - need to build a single argument cleanup function that
+			// wraps the more complicated code.
+			static UniqueName dtorNamer( "__cleanup_dtor" );
+			std::string name = dtorNamer.newName();
+			ast::FunctionDecl * dtorFunc = SymTab::genDefaultFunc( loc, name, objDecl->type->stripReferences(), false );
+			stmtsToAdd.push_back( new ast::DeclStmt(loc, dtorFunc ) );
+
+			// the original code contains uses of objDecl - replace them with the newly generated 'this' parameter.
+			const ast::ObjectDecl * thisParam = getParamThis( dtorFunc );
+			const ast::Expr * replacement = new ast::VariableExpr( loc, thisParam );
+
+			auto base = replacement->result->stripReferences();
+			if ( dynamic_cast< const ast::ArrayType * >( base ) || dynamic_cast< const ast::TupleType * > ( base ) ) {
+				// need to cast away reference for array types, since the destructor is generated without the reference type,
+				// and for tuple types since tuple indexing does not work directly on a reference
+				replacement = new ast::CastExpr( replacement, base );
+			}
+			auto dtor = ast::DeclReplacer::replace( input, ast::DeclReplacer::ExprMap{ std::make_pair( objDecl, replacement ) } );
+			auto mutStmts = dtorFunc->stmts.get_and_mutate();
+			mutStmts->push_back(strict_dynamic_cast<const ast::Stmt *>( dtor ));
+			dtorFunc->stmts = mutStmts;
+
+			return dtorFunc;
+		}
+
+		void StmtExprResult::link( std::list<ast::ptr<ast::Decl> > & translationUnit ) {
+			ast::Pass<StmtExprResult> linker;
+			accept_all( translationUnit, linker );
+		}
+
+		void SplitExpressions::split( std::list<ast::ptr<ast::Decl> > & translationUnit ) {
+			ast::Pass<SplitExpressions> splitter;
+			accept_all( translationUnit, splitter );
+		}
+
+		void InsertImplicitCalls::insert( std::list<ast::ptr<ast::Decl> > & translationUnit ) {
+			ast::Pass<InsertImplicitCalls> inserter;
+			accept_all( translationUnit, inserter );
+		}
+
+		void ResolveCopyCtors::resolveImplicitCalls( std::list< ast::ptr<ast::Decl> > & translationUnit ) {
+			ast::Pass<ResolveCopyCtors> resolver;
+			accept_all( translationUnit, resolver );
+		}
+
+		void FixInit::fixInitializers( std::list< ast::ptr<ast::Decl> > & translationUnit ) {
+			ast::Pass<FixInit> fixer;
+
+			// can't use mutateAll, because need to insert declarations at top-level
+			// can't use DeclMutator, because sometimes need to insert IfStmt, etc.
+			SemanticErrorException errors;
+			for ( auto i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
+				try {
+					// maybeAccept( *i, fixer ); translationUnit should never contain null
+					*i = (*i)->accept(fixer);
+					translationUnit.splice( i, fixer.core.staticDtorDecls );
+				} catch( SemanticErrorException &e ) {
+					errors.append( e );
+				} // try
+			} // for
+			if ( ! errors.isEmpty() ) {
+				throw errors;
+			} // if
+		}
+
+		void InsertDtors::insert( std::list< ast::ptr<ast::Decl> > & translationUnit ) {
+			ast::Pass<LabelFinder> finder;
+			ast::Pass<InsertDtors> inserter( finder );
+			accept_all( translationUnit, inserter );
+		}
+
+		void GenStructMemberCalls::generate( std::list< ast::ptr<ast::Decl> > & translationUnit ) {
+			ast::Pass<GenStructMemberCalls> warner;
+			accept_all( translationUnit, warner );
+		}
+
+		void FixCtorExprs::fix( std::list< ast::ptr<ast::Decl> > & translationUnit ) {
+			ast::Pass<FixCtorExprs> fixer;
+			accept_all( translationUnit, fixer );
+		}
+
+		const ast::StmtExpr * StmtExprResult::previsit( const ast::StmtExpr * stmtExpr ) {
+			// we might loose the result expression here so add a pointer to trace back
+			assert( stmtExpr->result );
+			const ast::Type * result = stmtExpr->result;
+			if ( ! result->isVoid() ) {
+				auto mutExpr = mutate(stmtExpr);
+				const ast::CompoundStmt * body = mutExpr->stmts;
+				assert( ! body->kids.empty() );
+				mutExpr->resultExpr = body->kids.back().strict_as<ast::ExprStmt>();
+				return mutExpr;
+			}
+			return stmtExpr;
+		}
+
+		ast::Stmt * SplitExpressions::postvisit( const ast::ExprStmt * stmt ) {
+			// wrap each top-level ExprStmt in a block so that destructors for argument and return temporaries are destroyed
+			// in the correct places
+			ast::CompoundStmt * ret = new ast::CompoundStmt( stmt->location, { stmt } );
+			return ret;
+		}
+
+		void SplitExpressions::previsit( const ast::TupleAssignExpr * ) {
+			// don't do this within TupleAssignExpr, since it is already broken up into multiple expressions
+			visit_children = false;
+		}
+
+		// Relatively simple structural comparison for expressions, needed to determine
+		// if two expressions are "the same" (used to determine if self assignment occurs)
+		struct StructuralChecker {
+			const ast::Expr * stripCasts( const ast::Expr * expr ) {
+				// this might be too permissive. It's possible that only particular casts are relevant.
+				while ( auto cast = dynamic_cast< const ast::CastExpr * >( expr ) ) {
+					expr = cast->arg;
+				}
+				return expr;
+			}
+
+			void previsit( const ast::Expr * ) {
+				// anything else does not qualify
+				isSimilar = false;
+			}
+
+			template<typename T>
+			T * cast( const ast::Expr * node ) {
+				// all expressions need to ignore casts, so this bit has been factored out
+				return dynamic_cast< T * >( stripCasts( node ) );
+			}
+
+			// ignore casts
+			void previsit( const ast::CastExpr * ) {}
+
+			void previsit( const ast::MemberExpr * memExpr ) {
+				if ( auto otherMember = cast< const ast::MemberExpr >( other ) ) {
+					if ( otherMember->member == memExpr->member ) {
+						other = otherMember->aggregate;
+						return;
+					}
+				}
+				isSimilar = false;
+			}
+
+			void previsit( const ast::VariableExpr * varExpr ) {
+				if ( auto otherVar = cast< const ast::VariableExpr >( other ) ) {
+					if ( otherVar->var == varExpr->var ) {
+						return;
+					}
+				}
+				isSimilar = false;
+			}
+
+			void previsit( const ast::AddressExpr * ) {
+				if ( auto addrExpr = cast< const ast::AddressExpr >( other ) ) {
+					other = addrExpr->arg;
+					return;
+				}
+				isSimilar = false;
+			}
+
+			const ast::Expr * other = nullptr;
+			bool isSimilar = true;
+		};
+
+		bool structurallySimilar( const ast::Expr * e1, const ast::Expr * e2 ) {
+			ast::Pass<StructuralChecker> checker;
+			checker.core.other = e2;
+			e1->accept( checker );
+			return checker.core.isSimilar;
+		}
+
+		void SelfAssignChecker::previsit( const ast::ApplicationExpr * appExpr ) {
+			auto function = getFunction( appExpr );
+			if ( function->name == "?=?" ) { // doesn't use isAssignment, because ?+=?, etc. should not count as self-assignment
+				if ( appExpr->args.size() == 2 ) {
+					// check for structural similarity (same variable use, ignore casts, etc. - but does not look too deeply, anything looking like a function is off limits)
+					if ( structurallySimilar( appExpr->args.front(), appExpr->args.back() ) ) {
+						SemanticWarning( appExpr->location, Warning::SelfAssignment, toCString( appExpr->args.front() ) );
+					}
+				}
+			}
+		}
+
+		const ast::Expr * InsertImplicitCalls::postvisit( const ast::ApplicationExpr * appExpr ) {
+			if ( auto function = appExpr->func.as<ast::VariableExpr>() ) {
+				if ( function->var->linkage.is_builtin ) {
+					// optimization: don't need to copy construct in order to call intrinsic functions
+					return appExpr;
+				} else if ( auto funcDecl = function->var.as<ast::DeclWithType>() ) {
+					auto ftype = dynamic_cast< const ast::FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
+					assertf( ftype, "Function call without function type: %s", toString( funcDecl ).c_str() );
+					if ( CodeGen::isConstructor( funcDecl->name ) && ftype->params.size() == 2 ) {
+						auto t1 = getPointerBase( ftype->params.front() );
+						auto t2 = ftype->params.back();
+						assert( t1 );
+
+						if ( ResolvExpr::typesCompatible( t1, t2 ) ) {
+							// optimization: don't need to copy construct in order to call a copy constructor
+							return appExpr;
+						} // if
+					} else if ( CodeGen::isDestructor( funcDecl->name ) ) {
+						// correctness: never copy construct arguments to a destructor
+						return appExpr;
+					} // if
+				} // if
+			} // if
+			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
+			ast::ptr<ast::TypeSubstitution> tmp = appExpr->env;
+			auto mutExpr = mutate(appExpr);
+			mutExpr->env = nullptr;
+
+			auto expr = new ast::ImplicitCopyCtorExpr( appExpr->location, mutExpr );
+			// Move the type substitution to the new top-level, if it is attached to the appExpr.
+			// 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.
+			assert( typeSubs );
+			// assert (mutExpr->env);
+			expr->env = tmp;
+			// mutExpr->env = nullptr;
+			//std::swap( expr->env, appExpr->env );
+			return expr;
+		}
+
+		void ResolveCopyCtors::previsit(const ast::Expr * expr) {
+			if (expr->env) {
+				GuardValue(env);
+				GuardValue(envModified);
+				env = expr->env->clone();
+				envModified = false;
+			}
+		}
+
+		const ast::Expr * ResolveCopyCtors::postvisit(const ast::Expr * expr) {
+			if (expr->env) {
+				if (envModified) {
+					auto mutExpr = mutate(expr);
+					mutExpr->env = env;
+					return mutExpr;
+				}
+				else {
+					// env was not mutated, skip and delete the shallow copy
+					delete env;
+					return expr;
+				}
+			}
+			else {
+				return expr;
+			}
+		}
+
+		bool ResolveCopyCtors::skipCopyConstruct( const ast::Type * type ) { return ! isConstructable( type ); }
+
+		const ast::Expr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, const ast::ObjectDecl * var, const ast::Expr * cpArg ) {
+			assert( var );
+			assert (var->isManaged());
+			assert (!cpArg || cpArg->isManaged());
+			// arrays are not copy constructed, so this should always be an ExprStmt
+			ast::ptr< ast::Stmt > stmt = genCtorDtor(var->location, fname, var, cpArg );
+			assertf( stmt, "ResolveCopyCtors: genCtorDtor returned nullptr: %s / %s / %s", fname.c_str(), toString( var ).c_str(), toString( cpArg ).c_str() );
+			auto exprStmt = stmt.strict_as<ast::ImplicitCtorDtorStmt>()->callStmt.strict_as<ast::ExprStmt>();
+			ast::ptr<ast::Expr> untyped = exprStmt->expr; // take ownership of expr
+			// exprStmt->expr = nullptr; 
+
+			// 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; )
+			ast::ptr<ast::Expr> resolved = ResolvExpr::findVoidExpression(untyped, symtab);
+			assert( resolved );
+			if ( resolved->env ) {
+				// Extract useful information and discard new environments. Keeping them causes problems in PolyMutator passes.
+				env->add( *resolved->env );
+				envModified = true;
+				// delete resolved->env;
+				auto mut = mutate(resolved.get());
+				assertf(mut == resolved.get(), "newly resolved expression must be unique");
+				mut->env = nullptr;
+			} // if
+			// delete stmt;
+			if ( auto assign = resolved.as<ast::TupleAssignExpr>() ) {
+				// fix newly generated StmtExpr
+				previsit( assign->stmtExpr );
+			}
+			return resolved.release();
+		}
+
+		ast::ptr<ast::Expr> ResolveCopyCtors::copyConstructArg( 
+			const ast::Expr * arg, const ast::ImplicitCopyCtorExpr * impCpCtorExpr, const ast::Type * formal )
+		{
+			static UniqueName tempNamer("_tmp_cp");
+			assert( env );
+			const CodeLocation loc = impCpCtorExpr->location;
+			// CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *env << std::endl; )
+			assert( arg->result );
+			ast::ptr<ast::Type> result = arg->result;
+			if ( skipCopyConstruct( result ) ) return arg; // skip certain non-copyable types
+
+			// type may involve type variables, so apply type substitution to get temporary variable's actual type,
+			// since result type may not be substituted (e.g., if the type does not appear in the parameter list)
+			// Use applyFree so that types bound in function pointers are not substituted, e.g. in forall(dtype T) void (*)(T).
+			
+			// xxx - this originally mutates arg->result in place. is it correct?
+			result = env->applyFree( result.get() ).node;
+			auto mutResult = result.get_and_mutate();
+			mutResult->set_const(false);
+
+			auto mutArg = mutate(arg);
+			mutArg->result = mutResult;
+
+			ast::ptr<ast::Expr> guard = mutArg;
+
+			ast::ptr<ast::ObjectDecl> tmp = new ast::ObjectDecl({}, "__tmp", mutResult, nullptr );
+
+			// create and resolve copy constructor
+			CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
+			auto cpCtor = makeCtorDtor( "?{}", tmp, mutArg );
+
+			if ( auto appExpr = dynamic_cast< const ast::ApplicationExpr * >( cpCtor ) ) {
+				// if the chosen constructor is intrinsic, the copy is unnecessary, so
+				// don't create the temporary and don't call the copy constructor
+				auto function = appExpr->func.strict_as<ast::VariableExpr>();
+				if ( function->var->linkage == ast::Linkage::Intrinsic ) {
+					// arguments that need to be boxed need a temporary regardless of whether the copy constructor is intrinsic,
+					// so that the object isn't changed inside of the polymorphic function
+					if ( ! GenPoly::needsBoxing( formal, result, impCpCtorExpr->callExpr, env ) ) {
+						// xxx - should arg->result be mutated? see comment above.
+						return guard;
+					}
+				}
+			}
+
+			// set a unique name for the temporary once it's certain the call is necessary
+			auto mut = tmp.get_and_mutate();
+			assertf (mut == tmp, "newly created ObjectDecl must be unique");
+			mut->name = tempNamer.newName();
+
+			// replace argument to function call with temporary
+			stmtsToAddBefore.push_back( new ast::DeclStmt(loc, tmp ) );
+			arg = cpCtor;
+			return destructRet( tmp, arg );
+
+			// impCpCtorExpr->dtors.push_front( makeCtorDtor( "^?{}", tmp ) );
+		}
+
+		ast::Expr * ResolveCopyCtors::destructRet( const ast::ObjectDecl * ret, const ast::Expr * arg ) {
+			// TODO: refactor code for generating cleanup attribute, since it's common and reused in ~3-4 places
+			// check for existing cleanup attribute before adding another(?)
+			// need to add __Destructor for _tmp_cp variables as well
+
+			assertf( ast::dtorStruct && ast::dtorStruct->members.size() == 2, "Destructor generation requires __Destructor definition." );
+			assertf( ast::dtorStructDestroy, "Destructor generation requires __destroy_Destructor." );
+
+			const CodeLocation loc = ret->location;
+
+			// generate a __Destructor for ret that calls the destructor
+			auto res = makeCtorDtor( "^?{}", ret );
+			auto dtor = mutate(res);
+
+			// if the chosen destructor is intrinsic, elide the generated dtor handler
+			if ( arg && isIntrinsicCallExpr( dtor ) ) {
+				return new ast::CommaExpr(loc, arg, new ast::VariableExpr(loc, ret ) );
+				// return;
+			}
+
+			if ( ! dtor->env ) dtor->env = maybeClone( env );
+			auto dtorFunc = getDtorFunc( ret, new ast::ExprStmt(loc, dtor ), stmtsToAddBefore );
+
+			auto dtorStructType = new ast::StructInstType(ast::dtorStruct);
+
+			// what does this do???
+			dtorStructType->params.push_back( new ast::TypeExpr(loc, new ast::VoidType() ) );
+
+			// cast destructor pointer to void (*)(void *), to silence GCC incompatible pointer warnings
+			auto dtorFtype = new ast::FunctionType();
+			dtorFtype->params.push_back( new ast::PointerType(new ast::VoidType( ) ) );
+			auto dtorType = new ast::PointerType( dtorFtype );
+
+			static UniqueName namer( "_ret_dtor" );
+			auto retDtor = new ast::ObjectDecl(loc, namer.newName(), dtorStructType, new ast::ListInit(loc, { new ast::SingleInit(loc, ast::ConstantExpr::null(loc) ), new ast::SingleInit(loc, new ast::CastExpr( new ast::VariableExpr(loc, dtorFunc ), dtorType ) ) } ) );
+			retDtor->attributes.push_back( new ast::Attribute( "cleanup", { new ast::VariableExpr(loc, ast::dtorStructDestroy ) } ) );
+			stmtsToAddBefore.push_back( new ast::DeclStmt(loc, retDtor ) );
+
+			if ( arg ) {
+				auto member = new ast::MemberExpr(loc, ast::dtorStruct->members.front().strict_as<ast::DeclWithType>(), new ast::VariableExpr(loc, retDtor ) );
+				auto object = new ast::CastExpr( new ast::AddressExpr( new ast::VariableExpr(loc, ret ) ), new ast::PointerType(new ast::VoidType() ) );
+				ast::Expr * assign = createBitwiseAssignment( member, object );
+				return new ast::CommaExpr(loc, new ast::CommaExpr(loc, arg, assign ), new ast::VariableExpr(loc, ret ) );
+			}
+			return nullptr;
+			// impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
+		}
+
+		const ast::Expr * ResolveCopyCtors::postvisit( const ast::ImplicitCopyCtorExpr *impCpCtorExpr ) {
+			CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
+
+			ast::ApplicationExpr * appExpr = mutate(impCpCtorExpr->callExpr.get());
+			const ast::ObjectDecl * returnDecl = nullptr;
+			const CodeLocation loc = appExpr->location;
+
+			// take each argument and attempt to copy construct it.
+			auto ftype = GenPoly::getFunctionType( appExpr->func->result );
+			assert( ftype );
+			auto & params = ftype->params;
+			auto iter = params.begin();
+			for ( auto & arg : appExpr->args ) {
+				const ast::Type * formal = nullptr;
+				if ( iter != params.end() ) { // does not copy construct C-style variadic arguments
+					// DeclarationWithType * param = *iter++;
+					formal = *iter++;
+				}
+
+				arg = copyConstructArg( arg, impCpCtorExpr, formal );
+			} // for
+
+			// 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 named return values?
+			const ast::Type * result = appExpr->result;
+			if ( ! result->isVoid() ) {
+				static UniqueName retNamer("_tmp_cp_ret");
+				// result = result->clone();
+				auto subResult = env->apply( result ).node;
+				auto ret = new ast::ObjectDecl(loc, retNamer.newName(), subResult, nullptr );
+				auto mutType = mutate(ret->type.get());
+				mutType->set_const( false );
+				ret->type = mutType;
+				returnDecl = ret;
+				stmtsToAddBefore.push_back( new ast::DeclStmt(loc, ret ) );
+				CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
+			} // for
+			CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
+			// ------------------------------------------------------
+
+			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
+
+			// xxx - actual env might be somewhere else, need to keep invariant
+
+			// deletion of wrapper should be handled by pass template now
+			
+			// impCpCtorExpr->callExpr = nullptr;
+			assert (appExpr->env == nullptr);
+			appExpr->env = impCpCtorExpr->env;
+			// std::swap( impCpCtorExpr->env, appExpr->env );
+			// assert( impCpCtorExpr->env == nullptr );
+			// delete impCpCtorExpr;
+
+			if ( returnDecl ) {
+				ast::Expr * assign = createBitwiseAssignment( new ast::VariableExpr(loc, returnDecl ), appExpr );
+				if ( ! dynamic_cast< const ast::ReferenceType * >( result ) ) {
+					// destructing reference returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary
+					assign = destructRet( returnDecl, assign );
+					assert(assign);
+				} else {
+					assign = new ast::CommaExpr(loc, assign, new ast::VariableExpr(loc, returnDecl ) );
+				}
+				// move env from appExpr to retExpr
+				// std::swap( assign->env, appExpr->env );
+				assign->env = appExpr->env;
+				// actual env is handled by common routine that replaces WithTypeSubstitution
+				return postvisit((const ast::Expr *)assign);
+			} else {
+				return postvisit((const ast::Expr *)appExpr);
+			} // if
+		}
+
+		const ast::StmtExpr * ResolveCopyCtors::previsit( const ast::StmtExpr * _stmtExpr ) {
+			// function call temporaries should be placed at statement-level, rather than nested inside of a new statement expression,
+			// since temporaries can be shared across sub-expressions, e.g.
+			//   [A, A] f();       // decl
+			//   g([A] x, [A] y);  // decl
+			//   g(f());           // call
+			// f is executed once, so the return temporary is shared across the tuple constructors for x and y.
+			// Explicitly mutating children instead of mutating the inner compound statement forces the temporaries to be added
+			// to the outer context, rather than inside of the statement expression.
+
+			// call the common routine that replaces WithTypeSubstitution
+			previsit((const ast::Expr *) _stmtExpr);
+
+			visit_children = false;
+			const CodeLocation loc = _stmtExpr->location;
+
+			assert( env );
+
+			symtab.enterScope();
+			// visit all statements
+			auto stmtExpr = mutate(_stmtExpr);
+			auto mutStmts = mutate(stmtExpr->stmts.get());
+
+			auto & stmts = mutStmts->kids;
+			for ( auto & stmt : stmts ) {
+				stmt = stmt->accept( *visitor );
+			} // for
+			stmtExpr->stmts = mutStmts;
+			symtab.leaveScope();
+
+			assert( stmtExpr->result );
+			// const ast::Type * result = stmtExpr->result;
+			if ( ! stmtExpr->result->isVoid() ) {
+				static UniqueName retNamer("_tmp_stmtexpr_ret");
+
+				// result = result->clone();
+				auto result = env->apply( stmtExpr->result.get() ).node;
+				if ( ! InitTweak::isConstructable( result ) ) {
+					// delete result;
+					return stmtExpr;
+				}
+				auto mutResult = result.get_and_mutate();
+				mutResult->set_const(false);
+
+				// create variable that will hold the result of the stmt expr
+				auto ret = new ast::ObjectDecl(loc, retNamer.newName(), mutResult, nullptr );
+				stmtsToAddBefore.push_back( new ast::DeclStmt(loc, ret ) );
+
+				assertf(
+					stmtExpr->resultExpr,
+					"Statement-Expression should have a resulting expression at %s:%d",
+					stmtExpr->location.filename.c_str(),
+					stmtExpr->location.first_line
+				);
+
+				const ast::ExprStmt * last = stmtExpr->resultExpr;
+				// xxx - if this is non-unique, need to copy while making resultExpr ref
+				assertf(last->unique(), "attempt to modify weakly shared statement");
+				auto mutLast = mutate(last);
+				// above assertion means in-place mutation is OK
+				try {
+					mutLast->expr = makeCtorDtor( "?{}", ret, mutLast->expr );
+				} catch(...) {
+					std::cerr << "*CFA internal error: ";
+					std::cerr << "can't resolve implicit constructor";
+					std::cerr << " at " << stmtExpr->location.filename;
+					std::cerr << ":" << stmtExpr->location.first_line << std::endl;
+
+					abort();
+				}
+
+				// add destructors after current statement
+				stmtsToAddAfter.push_back( new ast::ExprStmt(loc, makeCtorDtor( "^?{}", ret ) ) );
+
+				// must have a non-empty body, otherwise it wouldn't have a result
+				assert( ! stmts.empty() );
+
+				// if there is a return decl, add a use as the last statement; will not have return decl on non-constructable returns
+				stmts.push_back( new ast::ExprStmt(loc, new ast::VariableExpr(loc, ret ) ) );
+			} // if
+
+			assert( stmtExpr->returnDecls.empty() );
+			assert( stmtExpr->dtors.empty() );
+
+			return stmtExpr;
+		}
+
+		// to prevent warnings ('_unq0' may be used uninitialized in this function),
+		// insert an appropriate zero initializer for UniqueExpr temporaries.
+		ast::Init * makeInit( const ast::Type * t ) {
+			if ( auto inst = dynamic_cast< const ast::StructInstType * >( t ) ) {
+				// initizer for empty struct must be empty
+				if ( inst->base->members.empty() ) return new ast::ListInit({}, {});
+			} else if ( auto inst = dynamic_cast< const ast::UnionInstType * >( t ) ) {
+				// initizer for empty union must be empty
+				if ( inst->base->members.empty() ) return new ast::ListInit({}, {});
+			}
+
+			return new ast::ListInit( {}, { new ast::SingleInit( {}, ast::ConstantExpr::from_int({}, 0) ) } );
+		}
+
+		const ast::UniqueExpr * ResolveCopyCtors::previsit( const ast::UniqueExpr * unqExpr ) {
+			visit_children = false;
+			// xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
+			static std::unordered_map< int, const ast::UniqueExpr * > unqMap;
+			auto mutExpr = mutate(unqExpr);
+			if ( ! unqMap.count( unqExpr->id ) ) {
+				// resolve expr and find its
+
+				auto impCpCtorExpr = mutExpr->expr.as<ast::ImplicitCopyCtorExpr>();
+				// PassVisitor<ResolveCopyCtors> fixer;
+				
+				mutExpr->expr = mutExpr->expr->accept( *visitor );
+				// it should never be necessary to wrap a void-returning expression in a UniqueExpr - if this assumption changes, this needs to be rethought
+				assert( unqExpr->result );
+				if ( impCpCtorExpr ) {
+					auto comma = unqExpr->expr.strict_as<ast::CommaExpr>();
+					auto var = comma->arg2.strict_as<ast::VariableExpr>();
+					// note the variable used as the result from the call
+					mutExpr->var = var;
+				} else {
+					// expr isn't a call expr, so create a new temporary variable to use to hold the value of the unique expression
+					mutExpr->object = new ast::ObjectDecl( mutExpr->location, toString("_unq", mutExpr->id), mutExpr->result, makeInit( mutExpr->result ) );
+					mutExpr->var = new ast::VariableExpr( mutExpr->location, mutExpr->object );
+				}
+
+				// stmtsToAddBefore.splice( stmtsToAddBefore.end(), fixer.pass.stmtsToAddBefore );
+				// stmtsToAddAfter.splice( stmtsToAddAfter.end(), fixer.pass.stmtsToAddAfter );
+				unqMap[mutExpr->id] = mutExpr;
+			} else {
+				// take data from other UniqueExpr to ensure consistency
+				// delete unqExpr->get_expr();
+				mutExpr->expr = unqMap[mutExpr->id]->expr;
+				// delete unqExpr->result;
+				mutExpr->result = mutExpr->expr->result;
+			}
+			return mutExpr;
+		}
+
+		const ast::DeclWithType * FixInit::postvisit( const ast::ObjectDecl *_objDecl ) {
+			const CodeLocation loc = _objDecl->location;
+
+			// since this removes the init field from objDecl, it must occur after children are mutated (i.e. postvisit)
+			if ( ast::ptr<ast::ConstructorInit> ctorInit = _objDecl->init.as<ast::ConstructorInit>() ) {
+				auto objDecl = mutate(_objDecl);
+
+				// could this be non-unique?
+				if (objDecl != _objDecl) {
+					std::cerr << "FixInit: non-unique object decl " << objDecl->location << objDecl->name << std::endl;
+				}
+				// a decision should have been made by the resolver, so ctor and init are not both non-NULL
+				assert( ! ctorInit->ctor || ! ctorInit->init );
+				if ( const ast::Stmt * ctor = ctorInit->ctor ) {
+					if ( objDecl->storage.is_static ) {
+						// originally wanted to take advantage of gcc nested functions, but
+						// we get memory errors with this approach. To remedy this, the static
+						// variable is hoisted when the destructor needs to be called.
+						//
+						// generate:
+						// static T __objName_static_varN;
+						// void __objName_dtor_atexitN() {
+						//   __dtor__...;
+						// }
+						// int f(...) {
+						//   ...
+						//   static bool __objName_uninitialized = true;
+						//   if (__objName_uninitialized) {
+						//     __ctor(__objName);
+						//     __objName_uninitialized = false;
+						//     atexit(__objName_dtor_atexitN);
+						//   }
+						//   ...
+						// }
+
+						static UniqueName dtorCallerNamer( "_dtor_atexit" );
+
+						// static bool __objName_uninitialized = true
+						auto boolType = new ast::BasicType( ast::BasicType::Kind::Bool );
+						auto boolInitExpr = new ast::SingleInit(loc, ast::ConstantExpr::from_int(loc, 1 ) );
+						auto isUninitializedVar = new ast::ObjectDecl(loc, objDecl->mangleName + "_uninitialized", boolType, boolInitExpr, ast::Storage::Static, ast::Linkage::Cforall);
+						isUninitializedVar->fixUniqueId();
+
+						// __objName_uninitialized = false;
+						auto setTrue = new ast::UntypedExpr(loc, new ast::NameExpr(loc, "?=?" ) );
+						setTrue->args.push_back( new ast::VariableExpr(loc, isUninitializedVar ) );
+						setTrue->args.push_back( ast::ConstantExpr::from_int(loc, 0 ) );
+
+						// generate body of if
+						auto initStmts = new ast::CompoundStmt(loc);
+						auto & body = initStmts->kids;
+						body.push_back( ctor );
+						body.push_back( new ast::ExprStmt(loc, setTrue ) );
+
+						// put it all together
+						auto ifStmt = new ast::IfStmt(loc, new ast::VariableExpr(loc, isUninitializedVar ), initStmts, 0 );
+						stmtsToAddAfter.push_back( new ast::DeclStmt(loc, isUninitializedVar ) );
+						stmtsToAddAfter.push_back( ifStmt );
+
+						const ast::Stmt * dtor = ctorInit->dtor;
+
+						// these should be automatically managed once reassigned
+						// objDecl->set_init( nullptr );
+						// ctorInit->set_ctor( nullptr );
+						// ctorInit->set_dtor( nullptr );
+						if ( dtor ) {
+							// if the object has a non-trivial destructor, have to
+							// hoist it and the object into the global space and
+							// call the destructor function with atexit.
+
+							// Statement * dtorStmt = dtor->clone();
+
+							// void __objName_dtor_atexitN(...) {...}
+							ast::FunctionDecl * dtorCaller = new ast::FunctionDecl(loc, objDecl->mangleName + dtorCallerNamer.newName(), {}, {}, {}, new ast::CompoundStmt(loc, {dtor}), ast::Storage::Static, ast::Linkage::C );
+							dtorCaller->fixUniqueId();
+							// dtorCaller->stmts->push_back( dtor );
+
+							// atexit(dtor_atexit);
+							auto callAtexit = new ast::UntypedExpr(loc, new ast::NameExpr(loc, "atexit" ) );
+							callAtexit->args.push_back( new ast::VariableExpr(loc, dtorCaller ) );
+
+							body.push_back( new ast::ExprStmt(loc, callAtexit ) );
+
+							// hoist variable and dtor caller decls to list of decls that will be added into global scope
+							staticDtorDecls.push_back( objDecl );
+							staticDtorDecls.push_back( dtorCaller );
+
+							// need to rename object uniquely since it now appears
+							// at global scope and there could be multiple function-scoped
+							// static variables with the same name in different functions.
+							// Note: it isn't sufficient to modify only the mangleName, because
+							// then subsequent Indexer passes can choke on seeing the object's name
+							// if another object has the same name and type. An unfortunate side-effect
+							// of renaming the object is that subsequent NameExprs may fail to resolve,
+							// but there shouldn't be any remaining past this point.
+							static UniqueName staticNamer( "_static_var" );
+							objDecl->name = objDecl->name + staticNamer.newName();
+							objDecl->mangleName = Mangle::mangle( objDecl );
+
+							// xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
+							// create a new object which is never used
+							static UniqueName dummyNamer( "_dummy" );
+							auto dummy = new ast::ObjectDecl(loc, dummyNamer.newName(), new ast::PointerType(new ast::VoidType()), nullptr, ast::Storage::Static, ast::Linkage::Cforall, 0, { new ast::Attribute("unused") } );
+							// delete ctorInit;
+							return dummy;
+						} else {
+							objDecl->init = nullptr;
+							return objDecl;
+						}
+					} else {
+						auto implicit = strict_dynamic_cast< const ast::ImplicitCtorDtorStmt * > ( ctor );
+						auto ctorStmt = implicit->callStmt.as<ast::ExprStmt>();
+						const ast::ApplicationExpr * ctorCall = nullptr;
+						if ( ctorStmt && (ctorCall = isIntrinsicCallExpr( ctorStmt->expr )) && ctorCall->args.size() == 2 ) {
+							// clean up intrinsic copy constructor calls by making them into SingleInits
+							const ast::Expr * ctorArg = ctorCall->args.back();
+							// ctorCall should be gone afterwards
+							auto mutArg = mutate(ctorArg);
+							mutArg->env = ctorCall->env;
+							// std::swap( ctorArg->env, ctorCall->env );
+							objDecl->init = new ast::SingleInit(loc, mutArg );
+
+							// ctorCall->args.pop_back();
+						} else {
+							stmtsToAddAfter.push_back( ctor );
+							objDecl->init = nullptr;
+							// ctorInit->ctor = nullptr;
+						}
+
+						const ast::Stmt * dtor = ctorInit->dtor;
+						if ( dtor ) {
+							auto implicit = strict_dynamic_cast< const ast::ImplicitCtorDtorStmt * >( dtor );
+							const ast::Stmt * dtorStmt = implicit->callStmt;
+
+							// don't need to call intrinsic dtor, because it does nothing, but
+							// non-intrinsic dtors must be called
+							if ( ! isIntrinsicSingleArgCallStmt( dtorStmt ) ) {
+								// set dtor location to the object's location for error messages
+								auto dtorFunc = getDtorFunc( objDecl, dtorStmt, stmtsToAddBefore );
+								objDecl->attributes.push_back( new ast::Attribute( "cleanup", { new ast::VariableExpr(loc, dtorFunc ) } ) );
+								// ctorInit->dtor = nullptr;
+							} // if
+						}
+					} // if
+				} else if ( const ast::Init * init = ctorInit->init ) {
+					objDecl->init = init;
+					// ctorInit->init = nullptr;
+				} else {
+					// no constructor and no initializer, which is okay
+					objDecl->init = nullptr;
+				} // if
+				// delete ctorInit;
+				return objDecl;
+			} // if
+			return _objDecl;
+		}
+
+		void ObjDeclCollector::previsit( const ast::CompoundStmt * ) {
+			GuardValue( curVars );
+		}
+
+		void ObjDeclCollector::previsit( const ast::DeclStmt * stmt ) {
+			// keep track of all variables currently in scope
+			if ( auto objDecl = stmt->decl.as<ast::ObjectDecl>() ) {
+				curVars.push_back( objDecl );
+			} // if
+		}
+
+		void LabelFinder::previsit( const ast::Stmt * stmt ) {
+			// for each label, remember the variables in scope at that label.
+			for ( auto l : stmt->labels ) {
+				vars[l] = curVars;
+			} // for
+		}
+
+		void LabelFinder::previsit( const ast::CompoundStmt * stmt ) {
+			previsit( (const ast::Stmt *) stmt );
+			Parent::previsit( stmt );
+		}
+
+		void LabelFinder::previsit( const ast::DeclStmt * stmt ) {
+			previsit( (const ast::Stmt *)stmt );
+			Parent::previsit( stmt );
+		}
+
+
+		void InsertDtors::previsit( const ast::FunctionDecl * funcDecl ) {
+			// each function needs to have its own set of labels
+			GuardValue( labelVars );
+			labelVars.clear();
+			// LabelFinder does not recurse into FunctionDecl, so need to visit
+			// its children manually.
+			if (funcDecl->type) funcDecl->type->accept(finder);
+			// maybeAccept( funcDecl->type, finder );
+			if (funcDecl->stmts) funcDecl->stmts->accept(finder) ;
+
+			// all labels for this function have been collected, insert destructors as appropriate via implicit recursion.
+		}
+
+		// 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( const ast::BranchStmt * stmt ) {
+			// can't do anything for computed goto
+			if ( stmt->computedTarget ) return;
+
+			assertf( stmt->target.name != "", "BranchStmt missing a label: %s", toString( stmt ).c_str() );
+			// 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->target ];
+
+			DTOR_PRINT(
+				std::cerr << "at goto label: " << stmt->target.name << std::endl;
+				std::cerr << "S_G = " << printSet( curVars ) << std::endl;
+				std::cerr << "S_L = " << printSet( lvars ) << std::endl;
+			)
+
+
+			// std::set_difference requires that the inputs be sorted.
+			lvars.sort();
+			curVars.sort();
+
+			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() ) {
+				SemanticError( stmt, std::string("jump to label '") + stmt->target.name + "' crosses initialization of " + (*diff.begin())->name + " " );
+			} // if
+		}
+
+		void InsertDtors::previsit( const ast::BranchStmt * stmt ) {
+			switch( stmt->kind ) {
+			  case ast::BranchStmt::Continue:
+			  case ast::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 ast::BranchStmt::Goto:
+				handleGoto( stmt );
+				break;
+			  default:
+				assert( false );
+			} // switch
+		}
+
+		bool checkWarnings( const ast::FunctionDecl * funcDecl ) {
+			// only check for warnings if the current function is a user-defined
+			// constructor or destructor
+			if ( ! funcDecl ) return false;
+			if ( ! funcDecl->stmts ) return false;
+			return CodeGen::isCtorDtor( funcDecl->name ) && ! funcDecl->linkage.is_overrideable;
+		}
+
+		void GenStructMemberCalls::previsit( const ast::FunctionDecl * funcDecl ) {
+			GuardValue( function );
+			GuardValue( unhandled );
+			GuardValue( usedUninit );
+			GuardValue( thisParam );
+			GuardValue( isCtor );
+			GuardValue( structDecl );
+			errors = SemanticErrorException();  // clear previous errors
+
+			// need to start with fresh sets
+			unhandled.clear();
+			usedUninit.clear();
+
+			function = mutate(funcDecl);
+			// could this be non-unique?
+			if (function != funcDecl) {
+				std::cerr << "GenStructMemberCalls: non-unique FunctionDecl " << funcDecl->location << funcDecl->name << std::endl;
+			}
+
+			isCtor = CodeGen::isConstructor( function->name );
+			if ( checkWarnings( function ) ) {
+				// const ast::FunctionType * type = function->type;
+				// assert( ! type->params.empty() );
+				thisParam = function->params.front().strict_as<ast::ObjectDecl>();
+				auto thisType = getPointerBase( thisParam->get_type() );
+				auto structType = dynamic_cast< const ast::StructInstType * >( thisType );
+				if ( structType ) {
+					structDecl = structType->base;
+					for ( auto & member : structDecl->members ) {
+						if ( auto field = member.as<ast::ObjectDecl>() ) {
+							// record all of the struct type's members that need to be constructed or
+							// destructed by the end of the function
+							unhandled.insert( field );
+						}
+					}
+				}
+			}
+		}
+
+		const ast::DeclWithType * GenStructMemberCalls::postvisit( const ast::FunctionDecl * funcDecl ) {
+			// remove the unhandled objects from usedUninit, because a call is inserted
+			// to handle them - only objects that are later constructed are used uninitialized.
+			std::map< const ast::DeclWithType *, CodeLocation > diff;
+			// need the comparator since usedUninit and unhandled have different types
+			struct comp_t {
+				typedef decltype(usedUninit)::value_type usedUninit_t;
+				typedef decltype(unhandled)::value_type unhandled_t;
+				bool operator()(usedUninit_t x, unhandled_t y) { return x.first < y; }
+				bool operator()(unhandled_t x, usedUninit_t y) { return x < y.first; }
+			} comp;
+			std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ), comp );
+			for ( auto p : diff ) {
+				auto member = p.first;
+				auto loc = p.second;
+				// xxx - make error message better by also tracking the location that the object is constructed at?
+				emit( loc, "in ", function->name, ", field ", member->name, " used before being constructed" );
+			}
+
+			const CodeLocation loc = funcDecl->location;
+
+			if ( ! unhandled.empty() ) {
+				auto mutStmts = function->stmts.get_and_mutate();
+				// need to explicitly re-add function parameters to the indexer in order to resolve copy constructors
+				auto guard = makeFuncGuard( [this]() { symtab.enterScope(); }, [this]() { symtab.leaveScope(); } );
+				symtab.addFunction( function );
+
+				// need to iterate through members in reverse in order for
+				// ctor/dtor statements to come out in the right order
+				for ( auto & member : reverseIterate( structDecl->members ) ) {
+					auto field = member.as<ast::ObjectDecl>();
+					// skip non-DWT members
+					if ( ! field ) continue;
+					// skip non-constructable members
+					if ( ! tryConstruct( field ) ) continue;
+					// skip handled members
+					if ( ! unhandled.count( field ) ) continue;
+
+					// insert and resolve default/copy constructor call for each field that's unhandled
+					// std::list< const ast::Stmt * > stmt;
+					ast::Expr * arg2 = nullptr;
+					if ( function->name == "?{}" && isCopyFunction( function ) ) {
+						// if copy ctor, need to pass second-param-of-this-function.field
+						// std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
+						assert( function->params.size() == 2 );
+						arg2 = new ast::MemberExpr(funcDecl->location, field, new ast::VariableExpr(funcDecl->location, function->params.back() ) );
+					}
+					InitExpander_new srcParam( arg2 );
+					// cast away reference type and construct field.
+					ast::Expr * thisExpr = new ast::CastExpr(funcDecl->location, new ast::VariableExpr(funcDecl->location, thisParam ), thisParam->get_type()->stripReferences());
+					ast::Expr * memberDest = new ast::MemberExpr(funcDecl->location, field, thisExpr );
+					ast::ptr<ast::Stmt> callStmt = SymTab::genImplicitCall( srcParam, memberDest, loc, function->name, field, static_cast<SymTab::LoopDirection>(isCtor) );
+
+					if ( callStmt ) {
+						// auto & callStmt = stmt.front();
+
+						try {
+							callStmt = callStmt->accept( *visitor );
+							if ( isCtor ) {
+								mutStmts->push_front( callStmt );
+							} else { // TODO: don't generate destructor function/object for intrinsic calls
+								// destructor statements should be added at the end
+								// function->get_statements()->push_back( callStmt );
+
+								// Optimization: do not need to call intrinsic destructors on members
+								if ( isIntrinsicSingleArgCallStmt( callStmt ) ) continue;
+
+								// __Destructor _dtor0 = { (void *)&b.a1, (void (*)(void *)_destroy_A };
+								std::list< ast::ptr<ast::Stmt> > stmtsToAdd;
+
+								static UniqueName memberDtorNamer = { "__memberDtor" };
+								assertf( Validate::dtorStruct, "builtin __Destructor not found." );
+								assertf( Validate::dtorStructDestroy, "builtin __destroy_Destructor not found." );
+
+								ast::Expr * thisExpr = new ast::CastExpr( new ast::AddressExpr( new ast::VariableExpr(loc, thisParam ) ), new ast::PointerType( new ast::VoidType(), ast::CV::Qualifiers() ) );
+								ast::Expr * dtorExpr = new ast::VariableExpr(loc, getDtorFunc( thisParam, callStmt, stmtsToAdd ) );
+
+								// cast destructor pointer to void (*)(void *), to silence GCC incompatible pointer warnings
+								auto dtorFtype = new ast::FunctionType();
+								dtorFtype->params.emplace_back( new ast::PointerType( new ast::VoidType() ) );
+								auto dtorType = new ast::PointerType( dtorFtype );
+
+								auto destructor = new ast::ObjectDecl(loc, memberDtorNamer.newName(), new ast::StructInstType( ast::dtorStruct ), new ast::ListInit(loc, { new ast::SingleInit(loc, thisExpr ), new ast::SingleInit(loc, new ast::CastExpr( dtorExpr, dtorType ) ) } ) );
+								destructor->attributes.push_back( new ast::Attribute( "cleanup", { new ast::VariableExpr({}, ast::dtorStructDestroy ) } ) );
+								mutStmts->push_front( new ast::DeclStmt(loc, destructor ) );
+								mutStmts->kids.splice( mutStmts->kids.begin(), stmtsToAdd );
+							}
+						} catch ( SemanticErrorException & error ) {
+							emit( funcDecl->location, "in ", function->name , ", field ", field->name, " not explicitly ", isCtor ? "constructed" : "destructed",  " and no ", isCtor ? "default constructor" : "destructor", " found" );
+						}
+					}
+				}
+				function->stmts = mutStmts;
+			}
+			if (! errors.isEmpty()) {
+				throw errors;
+			}
+			// return funcDecl;
+			return function;
+		}
+
+		/// true if expr is effectively just the 'this' parameter
+		bool isThisExpression( const ast::Expr * expr, const ast::DeclWithType * thisParam ) {
+			// TODO: there are more complicated ways to pass 'this' to a constructor, e.g. &*, *&, etc.
+			if ( auto varExpr = dynamic_cast< const ast::VariableExpr * >( expr ) ) {
+				return varExpr->var == thisParam;
+			} else if ( auto castExpr = dynamic_cast< const ast::CastExpr * > ( expr ) ) {
+				return isThisExpression( castExpr->arg, thisParam );
+			}
+			return false;
+		}
+
+		/// returns a MemberExpr if expr is effectively just member access on the 'this' parameter, else nullptr
+		const ast::MemberExpr * isThisMemberExpr( const ast::Expr * expr, const ast::DeclWithType * thisParam ) {
+			if ( auto memberExpr = dynamic_cast< const ast::MemberExpr * >( expr ) ) {
+				if ( isThisExpression( memberExpr->aggregate, thisParam ) ) {
+					return memberExpr;
+				}
+			} else if ( auto castExpr = dynamic_cast< const ast::CastExpr * >( expr ) ) {
+				return isThisMemberExpr( castExpr->arg, thisParam );
+			}
+			return nullptr;
+		}
+
+		void GenStructMemberCalls::previsit( const ast::ApplicationExpr * appExpr ) {
+			if ( ! checkWarnings( function ) ) {
+				visit_children = false;
+				return;
+			}
+
+			std::string fname = getFunctionName( appExpr );
+			if ( fname == function->name ) {
+				// call to same kind of function
+				const ast::Expr * firstParam = appExpr->args.front();
+
+				if ( isThisExpression( firstParam, thisParam ) ) {
+					// if calling another constructor on thisParam, assume that function handles
+					// all members - if it doesn't a warning will appear in that function.
+					unhandled.clear();
+				} else if ( auto memberExpr = isThisMemberExpr( firstParam, thisParam ) ) {
+					// if first parameter is a member expression on the this parameter,
+					// then remove the member from unhandled set.
+					if ( isThisExpression( memberExpr->aggregate, thisParam ) ) {
+						unhandled.erase( memberExpr->member );
+					}
+				}
+			}
+		}
+
+		void GenStructMemberCalls::previsit( const ast::MemberExpr * memberExpr ) {
+			if ( ! checkWarnings( function ) || ! isCtor ) {
+				visit_children = false;
+				return;
+			}
+
+			if ( isThisExpression( memberExpr->aggregate, thisParam ) ) {
+				if ( unhandled.count( memberExpr->member ) ) {
+					// emit a warning because a member was used before it was constructed
+					usedUninit.insert( { memberExpr->member, memberExpr->location } );
+				}
+			}
+		}
+
+		template< typename Visitor, typename... Params >
+		void error( Visitor & v, CodeLocation loc, const Params &... params ) {
+			SemanticErrorException err( loc, toString( params... ) );
+			v.errors.append( err );
+		}
+
+		template< typename... Params >
+		void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
+			// toggle warnings vs. errors here.
+			// warn( params... );
+			error( *this, loc, params... );
+		}
+
+		const ast::Expr * GenStructMemberCalls::postvisit( const ast::UntypedExpr * untypedExpr ) {
+			// Expression * newExpr = untypedExpr;
+			// xxx - functions returning ast::ptr seems wrong...
+			auto res = ResolvExpr::findVoidExpression( untypedExpr, symtab );
+			return res.release();
+			// return newExpr;
+		}
+
+		void InsertImplicitCalls::previsit(const ast::UniqueExpr * unqExpr) {
+			if (visitedIds.count(unqExpr->id)) visit_children = false;
+			else visitedIds.insert(unqExpr->id);
+		}
+
+		const ast::Expr * FixCtorExprs::postvisit( const ast::ConstructorExpr * ctorExpr ) {
+			const CodeLocation loc = ctorExpr->location;
+			static UniqueName tempNamer( "_tmp_ctor_expr" );
+			// xxx - is the size check necessary?
+			assert( ctorExpr->result && ctorExpr->result->size() == 1 );
+
+			// xxx - this can be TupleAssignExpr now. Need to properly handle this case.
+			// take possession of expr and env
+			ast::ptr<ast::ApplicationExpr> callExpr = ctorExpr->callExpr.strict_as<ast::ApplicationExpr>();
+			ast::ptr<ast::TypeSubstitution> env = ctorExpr->env;
+			// ctorExpr->set_callExpr( nullptr );
+			// ctorExpr->set_env( nullptr );
+
+			// xxx - ideally we would reuse the temporary generated from the copy constructor passes from within firstArg if it exists and not generate a temporary if it's unnecessary.
+			auto tmp = new ast::ObjectDecl(loc, tempNamer.newName(), callExpr->args.front()->result );
+			declsToAddBefore.push_back( tmp );
+			// delete ctorExpr;
+
+			// build assignment and replace constructor's first argument with new temporary
+			auto mutCallExpr = callExpr.get_and_mutate();
+			const ast::Expr * firstArg = callExpr->args.front();
+			ast::Expr * assign = new ast::UntypedExpr(loc, new ast::NameExpr(loc, "?=?" ), { new ast::AddressExpr(loc, new ast::VariableExpr(loc, tmp ) ), new ast::AddressExpr( firstArg ) } );
+			firstArg = new ast::VariableExpr(loc, tmp );
+			mutCallExpr->args.front() = firstArg;
+
+			// resolve assignment and dispose of new env
+			auto resolved = ResolvExpr::findVoidExpression( assign, symtab );
+			auto mut = resolved.get_and_mutate();
+			assertf(resolved.get() == mut, "newly resolved expression must be unique");
+			mut->env = nullptr;
+
+			// for constructor expr:
+			//   T x;
+			//   x{};
+			// results in:
+			//   T x;
+			//   T & tmp;
+			//   &tmp = &x, ?{}(tmp), tmp
+			ast::CommaExpr * commaExpr = new ast::CommaExpr(loc, resolved, new ast::CommaExpr(loc, mutCallExpr, new ast::VariableExpr(loc, tmp ) ) );
+			commaExpr->env = env;
+			return commaExpr;
+		}
+	} // namespace
+} // namespace InitTweak
+
+// Local Variables: //
+// tab-width: 4 //
+// mode: c++ //
+// compile-command: "make install" //
+// End: //
Index: src/InitTweak/GenInit.cc
===================================================================
--- src/InitTweak/GenInit.cc	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/InitTweak/GenInit.cc	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -283,4 +283,11 @@
 		assert( stmts.size() <= 1 );
 		return stmts.size() == 1 ? strict_dynamic_cast< ImplicitCtorDtorStmt * >( stmts.front() ) : nullptr;
+
+	}
+
+	ast::ptr<ast::Stmt> genCtorDtor (const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg) {
+		assertf(objDecl, "genCtorDtor passed null objDecl");
+		InitExpander_new srcParam(arg);
+		return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl);
 	}
 
Index: src/InitTweak/GenInit.h
===================================================================
--- src/InitTweak/GenInit.h	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/InitTweak/GenInit.h	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -33,4 +33,5 @@
 	/// generates a single ctor/dtor statement using objDecl as the 'this' parameter and arg as the optional argument
 	ImplicitCtorDtorStmt * genCtorDtor( const std::string & fname, ObjectDecl * objDecl, Expression * arg = nullptr );
+	ast::ptr<ast::Stmt> genCtorDtor (const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg = nullptr);
 
 	/// creates an appropriate ConstructorInit node which contains a constructor, destructor, and C-initializer
Index: src/InitTweak/InitTweak.cc
===================================================================
--- src/InitTweak/InitTweak.cc	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/InitTweak/InitTweak.cc	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -498,4 +498,11 @@
 	}
 
+	const ast::ObjectDecl * getParamThis(const ast::FunctionDecl * func) {
+		assertf( func, "getParamThis: nullptr ftype" );
+		auto & params = func->params;
+		assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( func ).c_str());
+		return params.front().strict_as<ast::ObjectDecl>();
+	}
+
 	bool tryConstruct( DeclarationWithType * dwt ) {
 		ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
@@ -511,4 +518,18 @@
 	}
 
+	bool tryConstruct( const ast::DeclWithType * dwt ) {
+		auto objDecl = dynamic_cast< const ast::ObjectDecl * >( dwt );
+		if ( ! objDecl ) return false;
+		return (objDecl->init == nullptr ||
+				( objDecl->init != nullptr && objDecl->init->maybeConstructed ))
+			&& ! objDecl->storage.is_extern
+			&& isConstructable( objDecl->type );
+	}
+
+	bool isConstructable( const ast::Type * type ) {
+		return ! dynamic_cast< const ast::VarArgsType * >( type ) && ! dynamic_cast< const ast::ReferenceType * >( type ) 
+		&& ! dynamic_cast< const ast::FunctionType * >( type ) && ! Tuples::isTtype( type );
+	}
+
 	struct CallFinder_old {
 		CallFinder_old( const std::list< std::string > & names ) : names( names ) {}
@@ -536,5 +557,5 @@
 
 	struct CallFinder_new final {
-		std::vector< ast::ptr< ast::Expr > > matches;
+		std::vector< const ast::Expr * > matches;
 		const std::vector< std::string > names;
 
@@ -558,5 +579,5 @@
 	}
 
-	std::vector< ast::ptr< ast::Expr > > collectCtorDtorCalls( const ast::Stmt * stmt ) {
+	std::vector< const ast::Expr * > collectCtorDtorCalls( const ast::Stmt * stmt ) {
 		ast::Pass< CallFinder_new > finder{ std::vector< std::string >{ "?{}", "^?{}" } };
 		maybe_accept( stmt, finder );
@@ -696,5 +717,5 @@
 		template <typename Predicate>
 		bool allofCtorDtor( const ast::Stmt * stmt, const Predicate & pred ) {
-			std::vector< ast::ptr< ast::Expr > > callExprs = collectCtorDtorCalls( stmt );
+			std::vector< const ast::Expr * > callExprs = collectCtorDtorCalls( stmt );
 			return std::all_of( callExprs.begin(), callExprs.end(), pred );
 		}
@@ -939,4 +960,31 @@
 	}
 
+	// looks like some other such codegen uses UntypedExpr and does not create fake function. should revisit afterwards
+	// following passes may accidentally resolve this expression if returned as untyped...
+	ast::Expr * createBitwiseAssignment (const ast::Expr * dst, const ast::Expr * src) {
+		static ast::ptr<ast::FunctionDecl> assign = nullptr;
+		if (!assign) {
+			auto td = new ast::TypeDecl({}, "T", {}, nullptr, ast::TypeDecl::Dtype, true);
+			assign = new ast::FunctionDecl({}, "?=?", {}, 
+			{ new ast::ObjectDecl({}, "_dst", new ast::ReferenceType(new ast::TypeInstType("T", td))),
+			  new ast::ObjectDecl({}, "_src", new ast::TypeInstType("T", td))},
+			{ new ast::ObjectDecl({}, "_ret", new ast::TypeInstType("T", td))}, nullptr, {}, ast::Linkage::Intrinsic);
+		}
+		if (dst->result.as<ast::ReferenceType>()) {
+			for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
+				dst = new ast::AddressExpr(dst);
+			}
+		}
+		else {
+			dst = new ast::CastExpr(dst, new ast::ReferenceType(dst->result, {}));
+		}
+		if (src->result.as<ast::ReferenceType>()) {
+			for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
+				src = new ast::AddressExpr(src);
+			}
+		}
+		return new ast::ApplicationExpr(dst->location, ast::VariableExpr::functionPointer(dst->location, assign), {dst, src});
+	}
+
 	struct ConstExprChecker : public WithShortCircuiting {
 		// most expressions are not const expr
Index: src/InitTweak/InitTweak.h
===================================================================
--- src/InitTweak/InitTweak.h	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/InitTweak/InitTweak.h	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -38,7 +38,10 @@
 	/// returns the first parameter of a constructor/destructor/assignment function
 	ObjectDecl * getParamThis( FunctionType * ftype );
+	const ast::ObjectDecl * getParamThis(const ast::FunctionDecl * func);
 
 	/// generate a bitwise assignment operation.
 	ApplicationExpr * createBitwiseAssignment( Expression * dst, Expression * src );
+
+	ast::Expr * createBitwiseAssignment( const ast::Expr * dst, const ast::Expr * src);
 
 	/// transform Initializer into an argument list that can be passed to a call expression
@@ -48,7 +51,9 @@
 	/// True if the resolver should try to construct dwt
 	bool tryConstruct( DeclarationWithType * dwt );
+	bool tryConstruct( const ast::DeclWithType * dwt );
 
 	/// True if the type can have a user-defined constructor
 	bool isConstructable( Type * t );
+	bool isConstructable( const ast::Type * t );
 
 	/// True if the Initializer contains designations
@@ -79,5 +84,5 @@
 	/// get all Ctor/Dtor call expressions from a Statement
 	void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches );
-	std::vector< ast::ptr< ast::Expr > > collectCtorDtorCalls( const ast::Stmt * stmt );
+	std::vector< const ast::Expr * > collectCtorDtorCalls( const ast::Stmt * stmt );
 
 	/// get the Ctor/Dtor call expression from a Statement that looks like a generated ctor/dtor call
Index: src/InitTweak/module.mk
===================================================================
--- src/InitTweak/module.mk	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/InitTweak/module.mk	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -23,5 +23,6 @@
 	InitTweak/GenInit.h \
 	InitTweak/InitTweak.cc \
-	InitTweak/InitTweak.h
+	InitTweak/InitTweak.h \
+	InitTweak/FixInitNew.cpp
 
 SRCDEMANGLE += \
Index: src/ResolvExpr/Resolver.cc
===================================================================
--- src/ResolvExpr/Resolver.cc	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/ResolvExpr/Resolver.cc	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -1105,5 +1105,7 @@
 		}
 
-		/// Establish post-resolver invariants for expressions
+		
+	} // anonymous namespace
+/// Establish post-resolver invariants for expressions
 		void finishExpr(
 			ast::ptr< ast::Expr > & expr, const ast::TypeEnvironment & env,
@@ -1118,6 +1120,4 @@
 			StripCasts_new::strip( expr );
 		}
-	} // anonymous namespace
-
 
 	ast::ptr< ast::Expr > resolveInVoidContext(
@@ -1139,6 +1139,5 @@
 	}
 
-	namespace {
-		/// Resolve `untyped` to the expression whose candidate is the best match for a `void`
+	/// Resolve `untyped` to the expression whose candidate is the best match for a `void`
 		/// context.
 		ast::ptr< ast::Expr > findVoidExpression(
@@ -1151,4 +1150,7 @@
 			return newExpr;
 		}
+
+	namespace {
+		
 
 		/// resolve `untyped` to the expression whose candidate satisfies `pred` with the
@@ -1162,5 +1164,5 @@
 			CandidateRef choice =
 				findUnfinishedKindExpression( untyped, symtab, kind, pred, mode );
-			finishExpr( choice->expr, choice->env, untyped->env );
+			ResolvExpr::finishExpr( choice->expr, choice->env, untyped->env );
 			return std::move( choice->expr );
 		}
Index: src/ResolvExpr/Resolver.h
===================================================================
--- src/ResolvExpr/Resolver.h	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/ResolvExpr/Resolver.h	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -66,4 +66,6 @@
 	ast::ptr< ast::Expr > findSingleExpression(
 		const ast::Expr * untyped, const ast::Type * type, const ast::SymbolTable & symtab );
+	ast::ptr< ast::Expr > findVoidExpression(
+		const ast::Expr * untyped, const ast::SymbolTable & symtab);
 	/// Resolves a constructor init expression
 	ast::ptr< ast::Init > resolveCtorInit( 
Index: src/SymTab/Autogen.cc
===================================================================
--- src/SymTab/Autogen.cc	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/SymTab/Autogen.cc	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -233,4 +233,15 @@
 	}
 
+	// shallow copy the pointer list for return
+	std::vector<ast::ptr<ast::TypeDecl>> getGenericParams (const ast::Type * t) {
+		if (auto structInst = dynamic_cast<const ast::StructInstType*>(t)) {
+			return structInst->base->params;
+		}
+		if (auto unionInst = dynamic_cast<const ast::UnionInstType*>(t)) {
+			return unionInst->base->params;
+		}
+		return {};
+	}
+
 	/// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
 	FunctionType * genDefaultType( Type * paramType, bool maybePolymorphic ) {
@@ -244,4 +255,12 @@
 		ftype->parameters.push_back( dstParam );
 		return ftype;
+	}
+
+	/// 
+	ast::FunctionDecl * genDefaultFunc(const CodeLocation loc, const std::string fname, const ast::Type * paramType, bool maybePolymorphic) {
+		std::vector<ast::ptr<ast::TypeDecl>> typeParams;
+		if (maybePolymorphic) typeParams = getGenericParams(paramType);
+		auto dstParam = new ast::ObjectDecl(loc, "_dst", new ast::ReferenceType(paramType), nullptr, {}, ast::Linkage::Cforall);
+		return new ast::FunctionDecl(loc, fname, std::move(typeParams), {dstParam}, {}, new ast::CompoundStmt(loc));
 	}
 
Index: src/SymTab/Autogen.h
===================================================================
--- src/SymTab/Autogen.h	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/SymTab/Autogen.h	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -55,4 +55,6 @@
 	/// maybePolymorphic is true if the resulting FunctionType is allowed to be polymorphic
 	FunctionType * genDefaultType( Type * paramType, bool maybePolymorphic = true );
+
+	ast::FunctionDecl * genDefaultFunc(const CodeLocation loc, const std::string fname, const ast::Type * paramType, bool maybePolymorphic = true);
 
 	/// generate the type of a copy constructor for paramType.
Index: src/main.cc
===================================================================
--- src/main.cc	(revision a025ea8fc842c322ac2309643fd78e59a152cc3b)
+++ src/main.cc	(revision c5328475c954a0cf10db09a145ba92efc50823c8)
@@ -343,16 +343,23 @@
 			auto transUnit = convert( move( translationUnit ) );
 			PASS( "Resolve", ResolvExpr::resolve( transUnit ) );
+			if ( exprp ) {
+				translationUnit = convert( move( transUnit ) );
+				dump( translationUnit );
+				return EXIT_SUCCESS;
+			} // if
+
+			PASS( "Fix Init", InitTweak::fix(transUnit, buildingLibrary()));
 			translationUnit = convert( move( transUnit ) );
 		} else {
 			PASS( "Resolve", ResolvExpr::resolve( translationUnit ) );
+			if ( exprp ) {
+				dump( translationUnit );
+				return EXIT_SUCCESS;
+			}
+
+			PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
 		}
 
-		if ( exprp ) {
-			dump( translationUnit );
-			return EXIT_SUCCESS;
-		} // if
-
 		// fix ObjectDecl - replaces ConstructorInit nodes
-		PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
 		if ( ctorinitp ) {
 			dump ( translationUnit );
