Index: src/AST/Create.cpp
===================================================================
--- src/AST/Create.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/Create.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -42,17 +42,11 @@
 		return nullptr;
 	}
-	return new ast::FunctionDecl( decl->location,
-		decl->name,
-		vectorCopy( decl->type_params ),
-		vectorCopy( decl->assertions ),
-		vectorCopy( decl->params ),
-		vectorCopy( decl->returns ),
-		nullptr,
-		decl->storage,
-		decl->linkage,
-		vectorCopy( decl->attributes ),
-		decl->funcSpec,
-		decl->type->isVarArgs
-	);
+	// The cast and changing the original should be safe as long as the
+	// change is reverted before anything else sees it. It's also faster.
+	FunctionDecl * mutDecl = const_cast<FunctionDecl *>( decl );
+	CompoundStmt const * stmts = mutDecl->stmts.release();
+	FunctionDecl * copy = deepCopy( mutDecl );
+	mutDecl->stmts = stmts;
+	return copy;
 }
 
Index: src/AST/Decl.cpp
===================================================================
--- src/AST/Decl.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/Decl.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -115,5 +115,6 @@
 	static_assert( sizeof(kindNames) / sizeof(kindNames[0]) == TypeDecl::NUMBER_OF_KINDS, "typeString: kindNames is out of sync." );
 	assertf( kind < TypeDecl::NUMBER_OF_KINDS, "TypeDecl kind is out of bounds." );
-	return sized ? kindNames[ kind ] : &kindNames[ kind ][ sizeof("sized") ]; // sizeof includes '\0'
+	// sizeof("sized") includes '\0' and gives the offset to remove "sized ".
+	return sized ? kindNames[ kind ] : &kindNames[ kind ][ sizeof("sized") ];
 }
 
Index: src/AST/Decl.hpp
===================================================================
--- src/AST/Decl.hpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/Decl.hpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -69,5 +69,4 @@
 public:
 	/// Represents the type with all types and typedefs expanded.
-	/// This field is generated by SymTab::Validate::Pass2
 	std::string mangleName;
 	/// Stores the scope level at which the variable was declared.
Index: src/AST/LinkageSpec.cpp
===================================================================
--- src/AST/LinkageSpec.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/LinkageSpec.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -27,31 +27,30 @@
 namespace Linkage {
 
-	Spec update( CodeLocation loc, Spec spec, const std::string * cmd ) {
-		assert( cmd );
-		std::unique_ptr<const std::string> guard( cmd ); // allocated by lexer
-		if ( *cmd == "\"Cforall\"" ) {
-			spec.is_mangled = true;
-			return spec;
-		} else if ( *cmd == "\"C\"" ) {
-			spec.is_mangled = false;
-			return spec;
-		} else {
-			SemanticError( loc, "Invalid linkage specifier " + *cmd );
-		}
+Spec update( CodeLocation loc, Spec spec, const std::string * cmd ) {
+	assert( cmd );
+	std::unique_ptr<const std::string> guard( cmd ); // allocated by lexer
+	if ( *cmd == "\"Cforall\"" ) {
+		spec.is_mangled = true;
+		return spec;
+	} else if ( *cmd == "\"C\"" ) {
+		spec.is_mangled = false;
+		return spec;
+	} else {
+		SemanticError( loc, "Invalid linkage specifier " + *cmd );
 	}
+}
 
-
-	std::string name( Spec spec ) {
-		switch ( spec.val ) {
-		case Intrinsic.val:  return "intrinsic";
-		case C.val:          return "C";
-		case Cforall.val:    return "Cforall";
-		case AutoGen.val:    return "autogenerated cfa";
-		case Compiler.val:   return "compiler built-in";
-		case BuiltinCFA.val: return "cfa built-in";
-		case BuiltinC.val:   return "c built-in";
-		default:         return "<unnamed linkage spec>";
-		}
+std::string name( Spec spec ) {
+	switch ( spec.val ) {
+	case Intrinsic.val:  return "intrinsic";
+	case C.val:          return "C";
+	case Cforall.val:    return "Cforall";
+	case AutoGen.val:    return "autogenerated cfa";
+	case Compiler.val:   return "compiler built-in";
+	case BuiltinCFA.val: return "cfa built-in";
+	case BuiltinC.val:   return "c built-in";
+	default:             return "<unnamed linkage spec>";
 	}
+}
 
 }
Index: src/AST/LinkageSpec.hpp
===================================================================
--- src/AST/LinkageSpec.hpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/LinkageSpec.hpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -25,54 +25,55 @@
 namespace Linkage {
 
-	/// Bitflags for linkage specifiers
-	enum {
-		Mangle       = 1 << 0,
-		Generate     = 1 << 1,
-		Overrideable = 1 << 2,
-		Builtin      = 1 << 3,
-		GccBuiltin   = 1 << 4
+/// Bitflags for linkage specifiers
+enum {
+	Mangle       = 1 << 0,
+	Generate     = 1 << 1,
+	Overrideable = 1 << 2,
+	Builtin      = 1 << 3,
+	GccBuiltin   = 1 << 4
+};
+
+/// Bitflag type for storage classes
+struct spec_flags {
+	union {
+		unsigned int val;
+		struct {
+			bool is_mangled      : 1;
+			bool is_generatable  : 1;
+			bool is_overrideable : 1;
+			bool is_builtin      : 1;
+			bool is_gcc_builtin  : 1;
+		};
 	};
 
-	/// Bitflag type for storage classes
-	struct spec_flags {
-		union {
-			unsigned int val;
-			struct {
-				bool is_mangled      : 1;
-				bool is_generatable  : 1;
-				bool is_overrideable : 1;
-				bool is_builtin      : 1;
-				bool is_gcc_builtin  : 1;
-			};
-		};
+	constexpr spec_flags( unsigned int val ) : val(val) {}
+};
 
-		constexpr spec_flags( unsigned int val ) : val(val) {}
-	};
+using Spec = bitfield<spec_flags>;
 
-	using Spec = bitfield<spec_flags>;
+/// If `cmd` = "C" returns `spec` with `is_mangled = false`.
+/// If `cmd` = "Cforall" returns `spec` with `is_mangled = true`.
+Spec update( CodeLocation loc, Spec spec, const std::string * cmd );
 
-	/// If `cmd` = "C" returns `spec` with `is_mangled = false`.
-	/// If `cmd` = "Cforall" returns `spec` with `is_mangled = true`.
-	Spec update( CodeLocation loc, Spec spec, const std::string * cmd );
+/// A human-readable name for this spec
+std::string name( Spec spec );
 
-	/// A human-readable name for this spec
-	std::string name( Spec spec );
+// Pre-defined flag combinations
 
-	// Pre-defined flag combinations
+/// C built-in defined in prelude
+constexpr Spec Intrinsic  = { Mangle | Generate | Overrideable | Builtin };
+/// Ordinary Cforall
+constexpr Spec Cforall    = { Mangle | Generate };
+/// C code: not overloadable, not mangled
+constexpr Spec C          = { Generate };
+/// Built by translator (e.g. struct assignment)
+constexpr Spec AutoGen    = { Mangle | Generate | Overrideable };
+/// GCC internal
+constexpr Spec Compiler   = { Mangle | Builtin | GccBuiltin };
+/// Mangled builtins
+constexpr Spec BuiltinCFA = { Mangle | Generate | Builtin };
+/// Non-mangled builtins
+constexpr Spec BuiltinC   = { Generate | Builtin };
 
-	/// C built-in defined in prelude
-	constexpr Spec Intrinsic  = { Mangle | Generate | Overrideable | Builtin };
-	/// Ordinary Cforall
-	constexpr Spec Cforall    = { Mangle | Generate };
-	/// C code: not overloadable, not mangled
-	constexpr Spec C          = { Generate };
-	/// Built by translator (e.g. struct assignment)
-	constexpr Spec AutoGen    = { Mangle | Generate | Overrideable };
-	/// GCC internal
-	constexpr Spec Compiler   = { Mangle | Builtin | GccBuiltin };
-	/// Mangled builtins
-	constexpr Spec BuiltinCFA = { Mangle | Generate | Builtin };
-	/// Non-mangled builtins
-	constexpr Spec BuiltinC   = { Generate | Builtin };
 }
 
Index: src/AST/Pass.impl.hpp
===================================================================
--- src/AST/Pass.impl.hpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/Pass.impl.hpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -53,76 +53,71 @@
 #endif
 
-namespace ast {
+namespace ast::__pass {
+	// Check if this is either a null pointer or a pointer to an empty container
+	template<typename T>
+	static inline bool empty( T * ptr ) {
+		return !ptr || ptr->empty();
+	}
+
+	template< typename core_t, typename node_t >
+	static inline node_t* mutate(const node_t *node) {
+		return std::is_base_of<PureVisitor, core_t>::value ? ::ast::shallowCopy(node) : ::ast::mutate(node);
+	}
+
+	//------------------------------
+	template<typename it_t, template <class...> class container_t>
+	static inline void take_all( it_t it, container_t<ast::ptr<ast::Decl>> * decls, bool * mutated = nullptr ) {
+		if ( empty( decls ) ) return;
+
+		std::transform(decls->begin(), decls->end(), it, [](const ast::Decl * decl) -> auto {
+				return new DeclStmt( decl->location, decl );
+			});
+		decls->clear();
+		if ( mutated ) *mutated = true;
+	}
+
+	template<typename it_t, template <class...> class container_t>
+	static inline void take_all( it_t it, container_t<ast::ptr<ast::Stmt>> * stmts, bool * mutated = nullptr ) {
+		if ( empty( stmts ) ) return;
+
+		std::move(stmts->begin(), stmts->end(), it);
+		stmts->clear();
+		if ( mutated ) *mutated = true;
+	}
+
+	//------------------------------
+	/// Check if should be skipped, different for pointers and containers
 	template<typename node_t>
-	node_t * shallowCopy( const node_t * node );
-
-	namespace __pass {
-		// Check if this is either a null pointer or a pointer to an empty container
-		template<typename T>
-		static inline bool empty( T * ptr ) {
-			return !ptr || ptr->empty();
-		}
-
-		template< typename core_t, typename node_t >
-		static inline node_t* mutate(const node_t *node) {
-			return std::is_base_of<PureVisitor, core_t>::value ? ::ast::shallowCopy(node) : ::ast::mutate(node);
-		}
-
-		//------------------------------
-		template<typename it_t, template <class...> class container_t>
-		static inline void take_all( it_t it, container_t<ast::ptr<ast::Decl>> * decls, bool * mutated = nullptr ) {
-			if ( empty( decls ) ) return;
-
-			std::transform(decls->begin(), decls->end(), it, [](const ast::Decl * decl) -> auto {
-					return new DeclStmt( decl->location, decl );
-				});
-			decls->clear();
-			if ( mutated ) *mutated = true;
-		}
-
-		template<typename it_t, template <class...> class container_t>
-		static inline void take_all( it_t it, container_t<ast::ptr<ast::Stmt>> * stmts, bool * mutated = nullptr ) {
-			if ( empty( stmts ) ) return;
-
-			std::move(stmts->begin(), stmts->end(), it);
-			stmts->clear();
-			if ( mutated ) *mutated = true;
-		}
-
-		//------------------------------
-		/// Check if should be skipped, different for pointers and containers
-		template<typename node_t>
-		bool skip( const ast::ptr<node_t> & val ) {
-			return !val;
-		}
-
-		template< template <class...> class container_t, typename node_t >
-		bool skip( const container_t<ast::ptr< node_t >> & val ) {
-			return val.empty();
-		}
-
-		//------------------------------
-		/// Get the value to visit, different for pointers and containers
-		template<typename node_t>
-		auto get( const ast::ptr<node_t> & val, int ) -> decltype(val.get()) {
-			return val.get();
-		}
-
-		template<typename node_t>
-		const node_t & get( const node_t & val, long ) {
-			return val;
-		}
-
-		//------------------------------
-		/// Check if value was mutated, different for pointers and containers
-		template<typename lhs_t, typename rhs_t>
-		bool differs( const lhs_t * old_val, const rhs_t * new_val ) {
-			return old_val != new_val;
-		}
-
-		template< template <class...> class container_t, typename node_t >
-		bool differs( const container_t<ast::ptr< node_t >> &, const container_t<ast::ptr< node_t >> & new_val ) {
-			return !new_val.empty();
-		}
+	bool skip( const ast::ptr<node_t> & val ) {
+		return !val;
+	}
+
+	template< template <class...> class container_t, typename node_t >
+	bool skip( const container_t<ast::ptr< node_t >> & val ) {
+		return val.empty();
+	}
+
+	//------------------------------
+	/// Get the value to visit, different for pointers and containers
+	template<typename node_t>
+	auto get( const ast::ptr<node_t> & val, int ) -> decltype(val.get()) {
+		return val.get();
+	}
+
+	template<typename node_t>
+	const node_t & get( const node_t & val, long ) {
+		return val;
+	}
+
+	//------------------------------
+	/// Check if value was mutated, different for pointers and containers
+	template<typename lhs_t, typename rhs_t>
+	bool differs( const lhs_t * old_val, const rhs_t * new_val ) {
+		return old_val != new_val;
+	}
+
+	template< template <class...> class container_t, typename node_t >
+	bool differs( const container_t<ast::ptr< node_t >> &, const container_t<ast::ptr< node_t >> & new_val ) {
+		return !new_val.empty();
 	}
 }
@@ -1920,5 +1915,5 @@
 	VISIT_START( node );
 
-	__pass::symtab::addStruct( core, 0, node->name );
+	__pass::symtab::addStructId( core, 0, node->name );
 
 	if ( __visit_children() ) {
@@ -1936,5 +1931,5 @@
 	VISIT_START( node );
 
-	__pass::symtab::addUnion( core, 0, node->name );
+	__pass::symtab::addUnionId( core, 0, node->name );
 
 	if ( __visit_children() ) {
Index: src/AST/Pass.proto.hpp
===================================================================
--- src/AST/Pass.proto.hpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/Pass.proto.hpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -488,22 +488,22 @@
 
 	template<typename core_t>
-	static inline auto addStruct( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addStruct( str ), void() ) {
+	static inline auto addStructId( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addStructId( str ), void() ) {
 		if ( ! core.symtab.lookupStruct( str ) ) {
-			core.symtab.addStruct( str );
-		}
-	}
-
-	template<typename core_t>
-	static inline void addStruct( core_t &, long, const std::string & ) {}
-
-	template<typename core_t>
-	static inline auto addUnion( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addUnion( str ), void() ) {
+			core.symtab.addStructId( str );
+		}
+	}
+
+	template<typename core_t>
+	static inline void addStructId( core_t &, long, const std::string & ) {}
+
+	template<typename core_t>
+	static inline auto addUnionId( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addUnionId( str ), void() ) {
 		if ( ! core.symtab.lookupUnion( str ) ) {
-			core.symtab.addUnion( str );
-		}
-	}
-
-	template<typename core_t>
-	static inline void addUnion( core_t &, long, const std::string & ) {}
+			core.symtab.addUnionId( str );
+		}
+	}
+
+	template<typename core_t>
+	static inline void addUnionId( core_t &, long, const std::string & ) {}
 
 	#undef SYMTAB_FUNC1
Index: src/AST/SymbolTable.cpp
===================================================================
--- src/AST/SymbolTable.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/SymbolTable.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -19,7 +19,4 @@
 
 #include "Copy.hpp"
-#include <iostream>
-#include <algorithm>
-
 #include "Decl.hpp"
 #include "Expr.hpp"
@@ -206,6 +203,4 @@
 			out.push_back(decl.second);
 		}
-
-		// std::cerr << otypeKey << ' ' << out.size() << std::endl;
 	}
 
@@ -328,5 +323,5 @@
 }
 
-void SymbolTable::addStruct( const std::string &id ) {
+void SymbolTable::addStructId( const std::string &id ) {
 	addStruct( new StructDecl( CodeLocation(), id ) );
 }
@@ -370,5 +365,5 @@
 }
 
-void SymbolTable::addUnion( const std::string &id ) {
+void SymbolTable::addUnionId( const std::string &id ) {
 	addUnion( new UnionDecl( CodeLocation(), id ) );
 }
Index: src/AST/SymbolTable.hpp
===================================================================
--- src/AST/SymbolTable.hpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/SymbolTable.hpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -150,5 +150,5 @@
 	void addType( const NamedTypeDecl * decl );
 	/// Adds a struct declaration to the symbol table by name
-	void addStruct( const std::string & id );
+	void addStructId( const std::string & id );
 	/// Adds a struct declaration to the symbol table
 	void addStruct( const StructDecl * decl );
@@ -156,5 +156,5 @@
 	void addEnum( const EnumDecl * decl );
 	/// Adds a union declaration to the symbol table by name
-	void addUnion( const std::string & id );
+	void addUnionId( const std::string & id );
 	/// Adds a union declaration to the symbol table
 	void addUnion( const UnionDecl * decl );
Index: src/AST/Util.cpp
===================================================================
--- src/AST/Util.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/AST/Util.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -20,6 +20,10 @@
 #include "Pass.hpp"
 #include "TranslationUnit.hpp"
+#include "Common/utility.h"
+#include "GenPoly/ScopedSet.h"
 
 #include <vector>
+
+using GenPoly::ScopedSet;
 
 namespace ast {
@@ -102,4 +106,15 @@
 }
 
+/// Check for Floating Nodes:
+/// Every node should be reachable from a root (the TranslationUnit) via a
+/// chain of structural references (tracked with ptr). This cannot check all
+/// of that, it just checks if a given node's field has a strong reference.
+template<typename node_t, typename field_t>
+void noFloatingNode( const node_t * node, field_t node_t::*field_ptr ) {
+	const field_t & field = node->*field_ptr;
+	if ( nullptr == field ) return;
+	assertf( field->isManaged(), "Floating node found." );
+}
+
 struct InvariantCore {
 	// To save on the number of visits: this is a kind of composed core.
@@ -127,4 +142,9 @@
 	}
 
+	void previsit( const VariableExpr * node ) {
+		previsit( (const ParseNode *)node );
+		noFloatingNode( node, &VariableExpr::var );
+	}
+
 	void previsit( const MemberExpr * node ) {
 		previsit( (const ParseNode *)node );
@@ -132,4 +152,24 @@
 	}
 
+	void previsit( const StructInstType * node ) {
+		previsit( (const Node *)node );
+		noFloatingNode( node, &StructInstType::base );
+	}
+
+	void previsit( const UnionInstType * node ) {
+		previsit( (const Node *)node );
+		noFloatingNode( node, &UnionInstType::base );
+	}
+
+	void previsit( const EnumInstType * node ) {
+		previsit( (const Node *)node );
+		noFloatingNode( node, &EnumInstType::base );
+	}
+
+	void previsit( const TypeInstType * node ) {
+		previsit( (const Node *)node );
+		noFloatingNode( node, &TypeInstType::base );
+	}
+
 	void postvisit( const Node * node ) {
 		no_strong_cycles.postvisit( node );
@@ -137,8 +177,195 @@
 };
 
+/// Checks that referred to nodes are in scope.
+/// This checks many readonly pointers to see if the declaration they are
+/// referring to is in scope by the structural rules of code.
+// Any escapes marked with a bug should be removed once the bug is fixed.
+struct InScopeCore : public ast::WithShortCircuiting {
+	ScopedSet<DeclWithType const *> typedDecls;
+	ScopedSet<TypeDecl const *> typeDecls;
+	// These 3 are really hard to check, because uses that originally ref. at
+	// a forward declaration can be rewired to point a later full definition.
+	ScopedSet<StructDecl const *> structDecls;
+	ScopedSet<UnionDecl const *> unionDecls;
+	ScopedSet<EnumDecl const *> enumDecls;
+	ScopedSet<TraitDecl const *> traitDecls;
+
+	bool isInGlobal = false;
+
+	void beginScope() {
+		typedDecls.beginScope();
+		typeDecls.beginScope();
+		structDecls.beginScope();
+		unionDecls.beginScope();
+		enumDecls.beginScope();
+		traitDecls.beginScope();
+	}
+
+	void endScope() {
+		typedDecls.endScope();
+		typeDecls.endScope();
+		structDecls.endScope();
+		unionDecls.endScope();
+		enumDecls.endScope();
+		traitDecls.endScope();
+	}
+
+	void previsit( ApplicationExpr const * expr ) {
+		// All isInGlobal manipulation is just to isolate this check.
+		// The invalid compound literals lead to bad ctor/dtors. [#280]
+		VariableExpr const * func = nullptr;
+		CastExpr const * cast = nullptr;
+		VariableExpr const * arg = nullptr;
+		if ( isInGlobal
+				&& 1 == expr->args.size()
+				&& ( func = expr->func.as<VariableExpr>() )
+				&& ( "?{}" == func->var->name || "^?{}" == func->var->name )
+				&& ( cast = expr->args[0].as<CastExpr>() )
+				&& ( arg = cast->arg.as<VariableExpr>() )
+				&& isPrefix( arg->var->name, "_compLit" ) ) {
+			visit_children = false;
+		}
+	}
+
+	void previsit( VariableExpr const * expr ) {
+		if ( !expr->var ) return;
+		// bitwise assignment escape [#281]
+		if ( expr->var->location.isUnset() ) return;
+		assert( typedDecls.contains( expr->var ) );
+	}
+
+	void previsit( FunctionType const * type ) {
+		// This is to avoid checking the assertions, which can point at the
+		// function's declaration and not the enclosing function.
+		for ( auto type_param : type->forall ) {
+			if ( type_param->formal_usage ) {
+				visit_children = false;
+				// We could check non-assertion fields here.
+			}
+		}
+	}
+
+	void previsit( TypeInstType const * type ) {
+		if ( !type->base ) return;
+		assertf( type->base->isManaged(), "Floating Node" );
+
+		// bitwise assignment escape [#281]
+		if ( type->base->location.isUnset() ) return;
+		// Formal types can actually look at out of scope variables.
+		if ( type->formal_usage ) return;
+		assert( typeDecls.contains( type->base ) );
+	}
+
+	void previsit( TraitInstType const * type ) {
+		if ( !type->base ) return;
+		assert( traitDecls.contains( type->base ) );
+	}
+
+	void previsit( ObjectDecl const * decl ) {
+		typedDecls.insert( decl );
+		// There are some ill-formed compound literals. [#280]
+		// The only known problem cases are at the top level.
+		if ( isPrefix( decl->name, "_compLit" ) ) {
+			visit_children = false;
+		}
+	}
+
+	void previsit( FunctionDecl const * decl ) {
+		typedDecls.insert( decl );
+		beginScope();
+		for ( auto & type_param : decl->type_params ) {
+			typeDecls.insert( type_param );
+		}
+		for ( auto & assertion : decl->assertions ) {
+			typedDecls.insert( assertion );
+		}
+		for ( auto & param : decl->params ) {
+			typedDecls.insert( param );
+		}
+		for ( auto & ret : decl->returns ) {
+			typedDecls.insert( ret );
+		}
+		// No special handling of withExprs.
+
+		// Part of the compound literal escape. [#280]
+		if ( "__global_init__" == decl->name
+				|| "__global_destroy__" == decl->name ) {
+			assert( !isInGlobal );
+			isInGlobal = true;
+		}
+	}
+
+	void postvisit( FunctionDecl const * decl ) {
+		endScope();
+		// Part of the compound literal escape. [#280]
+		if ( isInGlobal && ( "__global_init__" == decl->name
+				|| "__global_destroy__" == decl->name ) ) {
+			isInGlobal = false;
+		}
+	}
+
+	void previsit( StructDecl const * decl ) {
+		structDecls.insert( decl );
+		beginScope();
+		for ( auto & type_param : decl->params ) {
+			typeDecls.insert( type_param );
+		}
+	}
+
+	void postvisit( StructDecl const * ) {
+		endScope();
+	}
+
+	void previsit( UnionDecl const * decl ) {
+		unionDecls.insert( decl );
+		beginScope();
+		for ( auto & type_param : decl->params ) {
+			typeDecls.insert( type_param );
+		}
+	}
+
+	void postvisit( UnionDecl const * ) {
+		endScope();
+	}
+
+	void previsit( EnumDecl const * decl ) {
+		enumDecls.insert( decl );
+		if ( ast::EnumDecl::EnumHiding::Visible == decl->hide ) {
+			for ( auto & member : decl->members ) {
+				typedDecls.insert( member.strict_as<ast::DeclWithType>() );
+			}
+		}
+		beginScope();
+		for ( auto & type_param : decl->params ) {
+			typeDecls.insert( type_param );
+		}
+	}
+
+	void postvisit( EnumDecl const * ) {
+		endScope();
+	}
+
+	void previsit( TraitDecl const * decl ) {
+		traitDecls.insert( decl );
+		beginScope();
+		for ( auto & type_param : decl->params ) {
+			typeDecls.insert( type_param );
+		}
+	}
+
+	void postvisit( TraitDecl const * ) {
+		endScope();
+	}
+
+	void previsit( Designation const * ) {
+		visit_children = false;
+	}
+};
+
 } // namespace
 
 void checkInvariants( TranslationUnit & transUnit ) {
-	ast::Pass<InvariantCore>::run( transUnit );
+	Pass<InvariantCore>::run( transUnit );
+	Pass<InScopeCore>::run( transUnit );
 }
 
Index: src/Common/ScopedMap.h
===================================================================
--- src/Common/ScopedMap.h	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Common/ScopedMap.h	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -199,7 +199,6 @@
 	friend class ScopedMap;
 	friend class const_iterator;
-	typedef typename ScopedMap::MapType::iterator wrapped_iterator;
-	typedef typename ScopedMap::ScopeList scope_list;
-	typedef typename scope_list::size_type size_type;
+	typedef typename MapType::iterator wrapped_iterator;
+	typedef typename ScopeList::size_type size_type;
 
 	/// Checks if this iterator points to a valid item
@@ -220,5 +219,5 @@
 	}
 
-	iterator(scope_list & _scopes, const wrapped_iterator & _it, size_type inLevel)
+	iterator(ScopeList & _scopes, const wrapped_iterator & _it, size_type inLevel)
 		: scopes(&_scopes), it(_it), level(inLevel) {}
 public:
@@ -266,5 +265,5 @@
 
 private:
-	scope_list *scopes;
+	ScopeList *scopes;
 	wrapped_iterator it;
 	size_type level;
Index: src/Concurrency/KeywordsNew.cpp
===================================================================
--- src/Concurrency/KeywordsNew.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Concurrency/KeywordsNew.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -534,8 +534,11 @@
 void ConcurrentSueKeyword::addGetRoutines(
 		const ast::ObjectDecl * field, const ast::FunctionDecl * forward ) {
+	// Clone the signature and then build the body.
+	ast::FunctionDecl * decl = ast::deepCopy( forward );
+
 	// Say it is generated at the "same" places as the forward declaration.
-	const CodeLocation & location = forward->location;
-
-	const ast::DeclWithType * param = forward->params.front();
+	const CodeLocation & location = decl->location;
+
+	const ast::DeclWithType * param = decl->params.front();
 	ast::Stmt * stmt = new ast::ReturnStmt( location,
 		new ast::AddressExpr( location,
@@ -551,5 +554,4 @@
 	);
 
-	ast::FunctionDecl * decl = ast::deepCopy( forward );
 	decl->stmts = new ast::CompoundStmt( location, { stmt } );
 	declsToAddAfter.push_back( decl );
@@ -1236,4 +1238,12 @@
 }
 
+void flattenTuple( const ast::UntypedTupleExpr * tuple, std::vector<ast::ptr<ast::Expr>> & output ) {
+    for ( auto & expr : tuple->exprs ) {
+        const ast::UntypedTupleExpr * innerTuple = dynamic_cast<const ast::UntypedTupleExpr *>(expr.get());
+        if ( innerTuple ) flattenTuple( innerTuple, output );
+        else output.emplace_back( ast::deepCopy( expr ));
+    }
+}
+
 ast::CompoundStmt * MutexKeyword::addStatements(
 		const ast::CompoundStmt * body,
@@ -1248,4 +1258,12 @@
 	// std::string lockFnName = mutex_func_namer.newName();
 	// std::string unlockFnName = mutex_func_namer.newName();
+
+    // If any arguments to the mutex stmt are tuples, flatten them
+    std::vector<ast::ptr<ast::Expr>> flattenedArgs;
+    for ( auto & arg : args ) {
+        const ast::UntypedTupleExpr * tuple = dynamic_cast<const ast::UntypedTupleExpr *>(args.at(0).get());
+        if ( tuple ) flattenTuple( tuple, flattenedArgs );
+        else flattenedArgs.emplace_back( ast::deepCopy( arg ));
+    }
 
 	// Make pointer to the monitors.
@@ -1257,5 +1275,5 @@
 				new ast::VoidType()
 			),
-			ast::ConstantExpr::from_ulong( location, args.size() ),
+			ast::ConstantExpr::from_ulong( location, flattenedArgs.size() ),
 			ast::FixedLen,
 			ast::DynamicDim
@@ -1264,5 +1282,5 @@
 			location,
 			map_range<std::vector<ast::ptr<ast::Init>>>(
-				args, [](const ast::Expr * expr) {
+				flattenedArgs, [](const ast::Expr * expr) {
 					return new ast::SingleInit(
 						expr->location,
@@ -1287,5 +1305,5 @@
 
 	// adds a nested try stmt for each lock we are locking
-	for ( long unsigned int i = 0; i < args.size(); i++ ) {
+	for ( long unsigned int i = 0; i < flattenedArgs.size(); i++ ) {
 		ast::UntypedExpr * innerAccess = new ast::UntypedExpr( 
 			location,
@@ -1298,10 +1316,10 @@
 		// make the try body
 		ast::CompoundStmt * currTryBody = new ast::CompoundStmt( location );
-		ast::IfStmt * lockCall = genTypeDiscrimLockUnlock( "lock", args, location, innerAccess );
+		ast::IfStmt * lockCall = genTypeDiscrimLockUnlock( "lock", flattenedArgs, location, innerAccess );
 		currTryBody->push_back( lockCall );
 
 		// make the finally stmt
 		ast::CompoundStmt * currFinallyBody = new ast::CompoundStmt( location );
-		ast::IfStmt * unlockCall = genTypeDiscrimLockUnlock( "unlock", args, location, innerAccess );
+		ast::IfStmt * unlockCall = genTypeDiscrimLockUnlock( "unlock", flattenedArgs, location, innerAccess );
 		currFinallyBody->push_back( unlockCall );
 
@@ -1343,5 +1361,5 @@
 						new ast::SingleInit(
 							location,
-							ast::ConstantExpr::from_ulong( location, args.size() ) ),
+							ast::ConstantExpr::from_ulong( location, flattenedArgs.size() ) ),
 					},
 					{},
Index: src/Concurrency/Waituntil.cpp
===================================================================
--- src/Concurrency/Waituntil.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Concurrency/Waituntil.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -142,4 +142,5 @@
     UniqueName namer_target = "__clause_target_"s;
     UniqueName namer_when = "__when_cond_"s;
+    UniqueName namer_label = "__waituntil_label_"s;
 
     string idxName = "__CFA_clause_idx_";
@@ -173,9 +174,9 @@
     void addPredicates( const WaitUntilStmt * stmt, string & satName, string & runName );
     void setUpClause( const WhenClause * clause, ClauseData * data, string & pCountName, CompoundStmt * body );
-    ForStmt * genStatusCheckFor( const WaitUntilStmt * stmt, vector<ClauseData *> & clauseData, string & predName );
+    CompoundStmt * genStatusCheckFor( const WaitUntilStmt * stmt, vector<ClauseData *> & clauseData, string & predName );
     Expr * genSelectTraitCall( const WhenClause * clause, const ClauseData * data, string fnName );
     CompoundStmt * genStmtBlock( const WhenClause * clause, const ClauseData * data );
     Stmt * genElseClauseBranch( const WaitUntilStmt * stmt, string & runName, string & arrName, vector<ClauseData *> & clauseData );
-    Stmt * genNoElseClauseBranch( const WaitUntilStmt * stmt, string & satName, string & runName, string & arrName, string & pCountName, vector<ClauseData *> & clauseData );
+    Stmt * genNoElseClauseBranch( const WaitUntilStmt * stmt, string & runName, string & arrName, string & pCountName, vector<ClauseData *> & clauseData );
     void genClauseInits( const WaitUntilStmt * stmt, vector<ClauseData *> & clauseData, CompoundStmt * body, string & statusName, string & elseWhenName );
     Stmt * recursiveOrIfGen( const WaitUntilStmt * stmt, vector<ClauseData *> & data, vector<ClauseData*>::size_type idx, string & elseWhenName );
@@ -626,8 +627,8 @@
     return new CompoundStmt( cLoc,
         {
-            new ExprStmt( cLoc,
-                genSelectTraitCall( clause, data, "on_selected" )
-            ),
-            ast::deepCopy( clause->stmt )
+            new IfStmt( cLoc,
+                genSelectTraitCall( clause, data, "on_selected" ),
+                ast::deepCopy( clause->stmt )
+            )
         }
     );
@@ -653,7 +654,9 @@
     }
 }*/
-ForStmt * GenerateWaitUntilCore::genStatusCheckFor( const WaitUntilStmt * stmt, vector<ClauseData *> & clauseData, string & predName ) {
+CompoundStmt * GenerateWaitUntilCore::genStatusCheckFor( const WaitUntilStmt * stmt, vector<ClauseData *> & clauseData, string & predName ) {
     CompoundStmt * ifBody = new CompoundStmt( stmt->location );
     const CodeLocation & loc = stmt->location;
+
+    string switchLabel = namer_label.newName();
 
     /* generates:
@@ -707,5 +710,5 @@
                                 )
                             ),
-                            new BranchStmt( cLoc, BranchStmt::Kind::Break, Label( cLoc ) )
+                            new BranchStmt( cLoc, BranchStmt::Kind::Break, Label( cLoc, switchLabel ) )
                         }
                     )
@@ -719,5 +722,6 @@
         new SwitchStmt( loc,
             new NameExpr( loc, idxName ),
-            std::move( switchCases )
+            std::move( switchCases ),
+            { Label( loc, switchLabel ) }
         )
     );
@@ -744,5 +748,8 @@
     );
 
-    return new ForStmt( loc,
+    string forLabel = namer_label.newName();
+
+    // we hoist init here so that this pass can happen after hoistdecls pass
+    return new CompoundStmt( loc,
         {
             new DeclStmt( loc,
@@ -752,29 +759,33 @@
                     new SingleInit( loc, ConstantExpr::from_int( loc, 0 ) )
                 )
-            )
-        },  // inits
-        new UntypedExpr ( loc,
-            new NameExpr( loc, "?<?" ),
-            {
-                new NameExpr( loc, idxName ),
-                ConstantExpr::from_int( loc, stmt->clauses.size() )
-            }
-        ),  // cond
-        new UntypedExpr ( loc,
-            new NameExpr( loc, "?++" ),
-            { new NameExpr( loc, idxName ) }
-        ),  // inc
-        new CompoundStmt( loc,
-            {
-                new IfStmt( loc,
-                    new UntypedExpr ( loc,
-                        new NameExpr( loc, predName ),
-                        { new NameExpr( loc, clauseData.at(0)->statusName ) }
-                    ),
-                    new BranchStmt( loc, BranchStmt::Kind::Break, Label( loc ) )
-                ),
-                ifSwitch
-            }
-        )   // body
+            ),
+            new ForStmt( loc,
+                {},  // inits
+                new UntypedExpr ( loc,
+                    new NameExpr( loc, "?<?" ),
+                    {
+                        new NameExpr( loc, idxName ),
+                        ConstantExpr::from_int( loc, stmt->clauses.size() )
+                    }
+                ),  // cond
+                new UntypedExpr ( loc,
+                    new NameExpr( loc, "?++" ),
+                    { new NameExpr( loc, idxName ) }
+                ),  // inc
+                new CompoundStmt( loc,
+                    {
+                        new IfStmt( loc,
+                            new UntypedExpr ( loc,
+                                new NameExpr( loc, predName ),
+                                { new NameExpr( loc, clauseData.at(0)->statusName ) }
+                            ),
+                            new BranchStmt( loc, BranchStmt::Kind::Break, Label( loc, forLabel ) )
+                        ),
+                        ifSwitch
+                    }
+                ),   // body
+                { Label( loc, forLabel ) }
+            )
+        }
     );
 }
@@ -809,5 +820,5 @@
 }
 
-Stmt * GenerateWaitUntilCore::genNoElseClauseBranch( const WaitUntilStmt * stmt, string & satName, string & runName, string & arrName, string & pCountName, vector<ClauseData *> & clauseData ) {
+Stmt * GenerateWaitUntilCore::genNoElseClauseBranch( const WaitUntilStmt * stmt, string & runName, string & arrName, string & pCountName, vector<ClauseData *> & clauseData ) {
     CompoundStmt * whileBody = new CompoundStmt( stmt->location );
     const CodeLocation & loc = stmt->location;
@@ -823,14 +834,13 @@
     );
 
-    whileBody->push_back( genStatusCheckFor( stmt, clauseData, satName ) );
+    whileBody->push_back( genStatusCheckFor( stmt, clauseData, runName ) );
 
     return new CompoundStmt( loc,
         {
             new WhileDoStmt( loc,
-                genNotSatExpr( stmt, satName, arrName ),
+                genNotSatExpr( stmt, runName, arrName ),
                 whileBody,  // body
                 {}          // no inits
-            ),
-            genStatusCheckFor( stmt, clauseData, runName )
+            )
         }
     );
@@ -856,5 +866,10 @@
                 new ObjectDecl( cLoc,
                     currClause->targetName,
-                    new ReferenceType( new TypeofType( ast::deepCopy( stmt->clauses.at(i)->target ) ) ),
+                    new ReferenceType( 
+                        new TypeofType( new UntypedExpr( cLoc,
+                            new NameExpr( cLoc, "__CFA_select_get_type" ),
+                            { ast::deepCopy( stmt->clauses.at(i)->target ) }
+                        ))
+                    ),
                     new SingleInit( cLoc, ast::deepCopy( stmt->clauses.at(i)->target ) )
                 )
@@ -1268,25 +1283,25 @@
                 new NameExpr( stmt->else_cond->location, elseWhenName ),
                 genElseClauseBranch( stmt, runName, statusArrName, clauseData ),
-                genNoElseClauseBranch( stmt, satName, runName, statusArrName, pCountName, clauseData )
+                genNoElseClauseBranch( stmt, runName, statusArrName, pCountName, clauseData )
             )
         );
     } else if ( !stmt->else_stmt ) { // normal gen
-        tryBody->push_back( genNoElseClauseBranch( stmt, satName, runName, statusArrName, pCountName, clauseData ) );
+        tryBody->push_back( genNoElseClauseBranch( stmt, runName, statusArrName, pCountName, clauseData ) );
     } else { // generate just else
         tryBody->push_back( genElseClauseBranch( stmt, runName, statusArrName, clauseData ) );
     }
 
+    // Collection of unregister calls on resources to be put in finally clause
+    // for each clause: 
+    // if ( !__CFA_has_clause_run( clause_statuses[i] )) && unregister_select( ... , clausei ) ) { ... clausei stmt ... }
+    // OR if when( ... ) defined on resource
+    // if ( when_cond_i && (!__CFA_has_clause_run( clause_statuses[i] )) && unregister_select( ... , clausei ) ) { ... clausei stmt ... }
     CompoundStmt * unregisters = new CompoundStmt( loc );
-    // generates for each clause: 
-    // if ( !has_run( clause_statuses[i] ) ) 
-    // OR if when_cond defined
-    // if ( when_cond_i && !has_run( clause_statuses[i] ) )
-    // body of if is:
-    // { if (unregister_select(A, clause1) && on_selected(A, clause1)) clause1->stmt; } // this conditionally runs the block unregister_select returns true (needed by some primitives)
-    Expr * ifCond;
-    UntypedExpr * statusExpr; // !clause_statuses[i]
+
+    Expr * statusExpr; // !__CFA_has_clause_run( clause_statuses[i] )
     for ( int i = 0; i < numClauses; i++ ) {
         const CodeLocation & cLoc = stmt->clauses.at(i)->location;
 
+        // Generates: !__CFA_has_clause_run( clause_statuses[i] )
         statusExpr = new UntypedExpr ( cLoc,
             new NameExpr( cLoc, "!?" ),
@@ -1300,8 +1315,23 @@
             }
         );
-
-        if ( stmt->clauses.at(i)->when_cond ) {
-            // generates: if( when_cond_i && !has_run(clause_statuses[i]) )
-            ifCond = new LogicalExpr( cLoc,
+        
+        // Generates:
+        // (!__CFA_has_clause_run( clause_statuses[i] )) && unregister_select( ... , clausei );
+        statusExpr = new LogicalExpr( cLoc,
+            new CastExpr( cLoc,
+                statusExpr, 
+                new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast 
+            ),
+            new CastExpr( cLoc,
+                genSelectTraitCall( stmt->clauses.at(i), clauseData.at(i), "unregister_select" ),
+                new BasicType( BasicType::Kind::Bool ), GeneratedFlag::ExplicitCast 
+            ),
+            LogicalFlag::AndExpr
+        );
+        
+        // if when cond defined generates:
+        // when_cond_i && (!__CFA_has_clause_run( clause_statuses[i] )) && unregister_select( ... , clausei );
+        if ( stmt->clauses.at(i)->when_cond )
+            statusExpr = new LogicalExpr( cLoc,
                 new CastExpr( cLoc,
                     new NameExpr( cLoc, clauseData.at(i)->whenName ), 
@@ -1314,22 +1344,29 @@
                 LogicalFlag::AndExpr
             );
-        } else // generates: if( !clause_statuses[i] )
-            ifCond = statusExpr;
-        
+
+        // generates:
+        // if ( statusExpr ) { ... clausei stmt ... }
         unregisters->push_back( 
             new IfStmt( cLoc,
-                ifCond,
+                statusExpr,
                 new CompoundStmt( cLoc,
                     {
                         new IfStmt( cLoc,
-                            genSelectTraitCall( stmt->clauses.at(i), clauseData.at(i), "unregister_select" ),
-                            // ast::deepCopy( stmt->clauses.at(i)->stmt )
-                            genStmtBlock( stmt->clauses.at(i), clauseData.at(i) )
+                            genSelectTraitCall( stmt->clauses.at(i), clauseData.at(i), "on_selected" ),
+                            ast::deepCopy( stmt->clauses.at(i)->stmt )
                         )
                     }
                 )
-                
-            )
-        );
+            )
+        );
+
+        // // generates:
+        // // if ( statusExpr ) { ... clausei stmt ... }
+        // unregisters->push_back( 
+        //     new IfStmt( cLoc,
+        //         statusExpr,
+        //         genStmtBlock( stmt->clauses.at(i), clauseData.at(i) )
+        //     )
+        // );
     }
 
Index: src/ControlStruct/ExceptDeclNew.cpp
===================================================================
--- src/ControlStruct/ExceptDeclNew.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/ControlStruct/ExceptDeclNew.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -242,5 +242,5 @@
 }
 
-ast::ObjectDecl const * createExternVTable(
+ast::ObjectDecl * createExternVTable(
 		CodeLocation const & location,
 		std::string const & exceptionName,
@@ -299,5 +299,6 @@
 		} ),
 		ast::Storage::Classes(),
-		ast::Linkage::Cforall
+		ast::Linkage::Cforall,
+		{ new ast::Attribute( "cfa_linkonce" ) }
 	);
 }
@@ -352,9 +353,10 @@
 		} ),
 		ast::Storage::Classes(),
-		ast::Linkage::Cforall
-	);
-}
-
-ast::ObjectDecl const * createVirtualTable(
+		ast::Linkage::Cforall,
+		{ new ast::Attribute( "cfa_linkonce" ) }
+	);
+}
+
+ast::ObjectDecl * createVirtualTable(
 		CodeLocation const & location,
 		std::string const & exceptionName,
@@ -451,4 +453,5 @@
 	std::string const & tableName = decl->name;
 
+	ast::ObjectDecl * retDecl;
 	if ( decl->storage.is_extern ) {
 		// Unique type-ids are only needed for polymorphic instances.
@@ -457,5 +460,5 @@
 				createExternTypeId( location, exceptionName, params ) );
 		}
-		return createExternVTable( location, exceptionName, params, tableName );
+		retDecl = createExternVTable( location, exceptionName, params, tableName );
 	} else {
 		// Unique type-ids are only needed for polymorphic instances.
@@ -468,7 +471,13 @@
 		declsToAddBefore.push_back(
 			createMsg( location, exceptionName, params ) );
-		return createVirtualTable(
+		retDecl = createVirtualTable(
 			location, exceptionName, params, tableName );
 	}
+
+	for ( ast::ptr<ast::Attribute> const & attr : decl->attributes ) {
+		retDecl->attributes.push_back( attr );
+	}
+
+	return retDecl;
 }
 
@@ -478,4 +487,5 @@
 
 		std::string vtableName = Virtual::vtableTypeName( inst->name );
+
 		auto newType = new ast::StructInstType( vtableName );
 		for ( ast::ptr<ast::Expr> const & param : inst->params ) {
Index: src/GenPoly/Box.cc
===================================================================
--- src/GenPoly/Box.cc	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/GenPoly/Box.cc	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -1538,33 +1538,32 @@
 		}
 
+		/// Checks if memberDecl matches the decl from an aggregate.
+		bool isMember( DeclarationWithType *memberDecl, Declaration * decl ) {
+			if ( memberDecl->get_name() != decl->get_name() )
+				return false;
+
+			if ( memberDecl->get_name().empty() ) {
+				// Plan-9 Field: match on unique_id.
+				return ( memberDecl->get_uniqueId() == decl->get_uniqueId() );
+			}
+
+			DeclarationWithType *declWithType = strict_dynamic_cast< DeclarationWithType* >( decl );
+
+			if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty() ) {
+				// Tuple-Element Field: expect neither had mangled name; accept match on simple name (like field_2) only.
+				assert( memberDecl->get_mangleName().empty() && declWithType->get_mangleName().empty() );
+				return true;
+			}
+
+			// Ordinary Field: Use full name to accommodate overloading.
+			return ( memberDecl->get_mangleName() == declWithType->get_mangleName() );
+		}
+
 		/// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
 		long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
 			for ( auto pair : enumerate( baseDecls ) ) {
-				Declaration * decl = pair.val;
-				size_t i = pair.idx;
-				if ( memberDecl->get_name() != decl->get_name() )
-					continue;
-
-				if ( memberDecl->get_name().empty() ) {
-					// plan-9 field: match on unique_id
-					if ( memberDecl->get_uniqueId() == decl->get_uniqueId() )
-						return i;
-					else
-						continue;
-				}
-
-				DeclarationWithType *declWithType = strict_dynamic_cast< DeclarationWithType* >( decl );
-
-				if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty() ) {
-					// tuple-element field: expect neither had mangled name; accept match on simple name (like field_2) only
-					assert( memberDecl->get_mangleName().empty() && declWithType->get_mangleName().empty() );
-					return i;
-				}
-
-				// ordinary field: use full name to accommodate overloading
-				if ( memberDecl->get_mangleName() == declWithType->get_mangleName() )
-					return i;
-				else
-					continue;
+				if ( isMember( memberDecl, pair.val ) ) {
+					return pair.idx;
+				}
 			}
 			return -1;
Index: src/GenPoly/ErasableScopedMap.h
===================================================================
--- src/GenPoly/ErasableScopedMap.h	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/GenPoly/ErasableScopedMap.h	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -57,6 +57,5 @@
 	/// Starts a new scope
 	void beginScope() {
-		Scope scope;
-		scopes.push_back(scope);
+		scopes.emplace_back();
 	}
 
@@ -145,7 +144,6 @@
 		public std::iterator< std::bidirectional_iterator_tag, value_type > {
 	friend class ErasableScopedMap;
-	typedef typename std::map< Key, Value >::iterator wrapped_iterator;
-	typedef typename std::vector< std::map< Key, Value > > scope_list;
-	typedef typename scope_list::size_type size_type;
+	typedef typename Scope::iterator wrapped_iterator;
+	typedef typename ScopeList::size_type size_type;
 
 	/// Checks if this iterator points to a valid item
Index: src/GenPoly/ScopedSet.h
===================================================================
--- src/GenPoly/ScopedSet.h	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/GenPoly/ScopedSet.h	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -47,6 +47,5 @@
 	/// Starts a new scope
 	void beginScope() {
-		Scope scope;
-		scopes.push_back(scope);
+		scopes.emplace_back();
 	}
 
@@ -85,5 +84,5 @@
 	iterator findNext( const_iterator &it, const Value &key ) {
 		if ( it.i == 0 ) return end();
-			for ( size_type i = it.i - 1; ; --i ) {
+		for ( size_type i = it.i - 1; ; --i ) {
 			typename Scope::iterator val = scopes[i].find( key );
 			if ( val != scopes[i].end() ) return iterator( scopes, val, i );
@@ -112,7 +111,6 @@
 	friend class ScopedSet;
 	friend class const_iterator;
-	typedef typename std::set< Value >::iterator wrapped_iterator;
-	typedef typename std::vector< std::set< Value > > scope_list;
-	typedef typename scope_list::size_type size_type;
+	typedef typename Scope::iterator wrapped_iterator;
+	typedef typename ScopeList::size_type size_type;
 
 	/// Checks if this iterator points to a valid item
@@ -133,5 +131,5 @@
 	}
 
-	iterator(scope_list const &_scopes, const wrapped_iterator &_it, size_type _i)
+	iterator(ScopeList const &_scopes, const wrapped_iterator &_it, size_type _i)
 		: scopes(&_scopes), it(_it), i(_i) {}
 public:
@@ -176,5 +174,5 @@
 
 private:
-	scope_list const *scopes;
+	ScopeList const *scopes;
 	wrapped_iterator it;
 	size_type i;
@@ -185,8 +183,7 @@
 		public std::iterator< std::bidirectional_iterator_tag, value_type > {
 	friend class ScopedSet;
-	typedef typename std::set< Value >::iterator wrapped_iterator;
-	typedef typename std::set< Value >::const_iterator wrapped_const_iterator;
-	typedef typename std::vector< std::set< Value > > scope_list;
-	typedef typename scope_list::size_type size_type;
+	typedef typename Scope::iterator wrapped_iterator;
+	typedef typename Scope::const_iterator wrapped_const_iterator;
+	typedef typename ScopeList::size_type size_type;
 
 	/// Checks if this iterator points to a valid item
@@ -207,5 +204,5 @@
 	}
 
-	const_iterator(scope_list const &_scopes, const wrapped_const_iterator &_it, size_type _i)
+	const_iterator(ScopeList const &_scopes, const wrapped_const_iterator &_it, size_type _i)
 		: scopes(&_scopes), it(_it), i(_i) {}
 public:
@@ -255,5 +252,5 @@
 
 private:
-	scope_list const *scopes;
+	ScopeList const *scopes;
 	wrapped_const_iterator it;
 	size_type i;
Index: src/GenPoly/SpecializeNew.cpp
===================================================================
--- src/GenPoly/SpecializeNew.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/GenPoly/SpecializeNew.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -104,5 +104,5 @@
 
 bool needsPolySpecialization(
-		const ast::Type * formalType,
+		const ast::Type * /*formalType*/,
 		const ast::Type * actualType,
 		const ast::TypeSubstitution * subs ) {
@@ -126,6 +126,5 @@
 			if ( closedVars.find( *inst ) == closedVars.end() ) {
 				return true;
-			}
-			else {
+			} else {
 				assertf(false, "closed: %s", inst->name.c_str());
 			}
Index: src/InitTweak/FixInitNew.cpp
===================================================================
--- src/InitTweak/FixInitNew.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/InitTweak/FixInitNew.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -22,7 +22,5 @@
 #include "AST/SymbolTable.hpp"
 #include "AST/Type.hpp"
-#include "CodeGen/GenType.h"           // for genPrettyType
-#include "CodeGen/OperatorTable.h"
-#include "Common/PassVisitor.h"        // for PassVisitor, WithStmtsToAdd
+#include "CodeGen/OperatorTable.h"     // for isConstructor, isCtorDtor, isD...
 #include "Common/SemanticError.h"      // for SemanticError
 #include "Common/ToString.hpp"         // for toCString
@@ -33,22 +31,5 @@
 #include "ResolvExpr/Resolver.h"       // for findVoidExpression
 #include "ResolvExpr/Unify.h"          // for typesCompatible
-#include "SymTab/Autogen.h"            // for genImplicitCall
 #include "SymTab/GenImplicitCall.hpp"  // 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
 
 extern bool ctordtorp; // print all debug
@@ -61,204 +42,1310 @@
 
 namespace InitTweak {
+
 namespace {
 
-	// Shallow copy the pointer list for return.
-	std::vector<ast::ptr<ast::TypeDecl>> getGenericParams( const ast::Type * t ) {
-		if ( auto inst = dynamic_cast<const ast::StructInstType *>( t ) ) {
-			return inst->base->params;
-		}
-		if ( auto inst = dynamic_cast<const ast::UnionInstType *>( t ) ) {
-			return inst->base->params;
-		}
-		return {};
-	}
-
-	/// Given type T, generate type of default ctor/dtor, i.e. function type void (*) (T &).
-	ast::FunctionDecl * genDefaultFunc(
-			const CodeLocation loc,
-			const std::string fname,
-			const ast::Type * paramType,
-			bool maybePolymorphic = true) {
-		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
+// Shallow copy the pointer list for return.
+std::vector<ast::ptr<ast::TypeDecl>> getGenericParams( const ast::Type * t ) {
+	if ( auto inst = dynamic_cast<const ast::StructInstType *>( t ) ) {
+		return inst->base->params;
+	}
+	if ( auto inst = dynamic_cast<const ast::UnionInstType *>( t ) ) {
+		return inst->base->params;
+	}
+	return {};
+}
+
+/// Given type T, generate type of default ctor/dtor, i.e. function type void (*) (T &).
+ast::FunctionDecl * genDefaultFunc(
+		const CodeLocation loc,
+		const std::string fname,
+		const ast::Type * paramType,
+		bool maybePolymorphic = true) {
+	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),
+		{},
+		ast::Linkage::Cforall
+	);
+}
+
+struct SelfAssignChecker {
+	void previsit( const ast::ApplicationExpr * appExpr );
+};
+
+struct StmtExprResult {
+	const ast::StmtExpr * previsit( const ast::StmtExpr * stmtExpr );
+};
+
+/// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
+/// function calls need their parameters to be copy constructed
+struct InsertImplicitCalls : public ast::WithShortCircuiting {
+	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;
+};
+
+/// 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
+struct ResolveCopyCtors final : public ast::WithGuards, public ast::WithStmtsToAdd<>, public ast::WithSymbolTable, public ast::WithShortCircuiting, public ast::WithVisitorRef<ResolveCopyCtors>, public ast::WithConstTranslationUnit {
+	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         = nullptr;
+	bool                    envModified = false;
+};
+
+/// 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 );
+};
+
+/// insert destructor calls at the appropriate places.  must happen before CtorInit nodes are removed
+/// (currently by FixInit)
+struct InsertDtors final : public ObjDeclCollector, public ast::WithStmtsToAdd<> {
+	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;
+};
+
+/// expand each object declaration to use its constructor after it is declared.
+struct FixInit : public ast::WithStmtsToAdd<> {
+	static void fixInitializers( ast::TranslationUnit &translationUnit );
+
+	const ast::DeclWithType * postvisit( const ast::ObjectDecl *objDecl );
+
+	std::list< ast::ptr< ast::Decl > > staticDtorDecls;
+};
+
+/// 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
+struct GenStructMemberCalls final : public ast::WithGuards, public ast::WithShortCircuiting, public ast::WithSymbolTable, public ast::WithVisitorRef<GenStructMemberCalls>, public ast::WithConstTranslationUnit {
+	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;
+};
+
+/// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
+struct FixCtorExprs final : public ast::WithDeclsToAdd<>, public ast::WithSymbolTable, public ast::WithShortCircuiting, public ast::WithConstTranslationUnit {
+	const ast::Expr * postvisit( const ast::ConstructorExpr * ctorExpr );
+};
+
+/// add CompoundStmts around top-level expressions so that temporaries are destroyed in the correct places.
+struct SplitExpressions : public ast::WithShortCircuiting {
+	ast::Stmt * postvisit( const ast::ExprStmt * stmt );
+	void previsit( const ast::TupleAssignExpr * expr );
+};
+
+/// 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 = 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 FixInit::fixInitializers( ast::TranslationUnit & 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.decls.begin(); i != translationUnit.decls.end(); ++i ) {
+		try {
+			// maybeAccept( *i, fixer ); translationUnit should never contain null
+			*i = (*i)->accept(fixer);
+			translationUnit.decls.splice( i, fixer.core.staticDtorDecls );
+		} catch( SemanticErrorException &e ) {
+			errors.append( e );
+		} // try
+	} // for
+	if ( ! errors.isEmpty() ) {
+		throw errors;
+	} // if
+}
+
+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 {
+	// Strip all casts and then dynamic_cast.
+	template<typename T>
+	static const T * cast( 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 dynamic_cast< const T * >( expr );
+	}
+
+	void previsit( const ast::Expr * ) {
+		// anything else does not qualify
+		result = false;
+	}
+
+	// ignore casts
+	void previsit( const ast::CastExpr * ) {}
+
+	void previsit( const ast::MemberExpr * memExpr ) {
+		if ( auto otherMember = cast< ast::MemberExpr >( other ) ) {
+			if ( otherMember->member == memExpr->member ) {
+				other = otherMember->aggregate;
+				return;
+			}
+		}
+		result = false;
+	}
+
+	void previsit( const ast::VariableExpr * varExpr ) {
+		if ( auto otherVar = cast< ast::VariableExpr >( other ) ) {
+			if ( otherVar->var == varExpr->var ) {
+				return;
+			}
+		}
+		result = false;
+	}
+
+	void previsit( const ast::AddressExpr * ) {
+		if ( auto addrExpr = cast< ast::AddressExpr >( other ) ) {
+			other = addrExpr->arg;
+			return;
+		}
+		result = false;
+	}
+
+	const ast::Expr * other;
+	bool result = true;
+	StructuralChecker( const ast::Expr * other ) : other(other) {}
+};
+
+bool structurallySimilar( const ast::Expr * e1, const ast::Expr * e2 ) {
+	return ast::Pass<StructuralChecker>::read( e1, e2 );
+}
+
+void SelfAssignChecker::previsit( const ast::ApplicationExpr * appExpr ) {
+	auto function = getFunction( appExpr );
+	// Doesn't use isAssignment, because ?+=?, etc. should not count as self-assignment.
+	if ( function->name == "?=?" && 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).
+			&& 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. The substitution
+	// is needed to obtain the type of temporary variables so that copy
+	// constructor calls can be resolved.
+	expr->env = tmp;
+	return expr;
+}
+
+void ResolveCopyCtors::previsit(const ast::Expr * expr) {
+	if ( nullptr == expr->env ) {
+		return;
+	}
+	GuardValue( env ) = expr->env->clone();
+	GuardValue( envModified ) = false;
+}
+
+const ast::Expr * ResolveCopyCtors::postvisit(const ast::Expr * expr) {
+	// No local environment, skip.
+	if ( nullptr == expr->env ) {
+		return expr;
+	// Environment was modified, mutate and replace.
+	} else if ( envModified ) {
+		auto mutExpr = mutate(expr);
+		mutExpr->env = env;
+		return mutExpr;
+	// Environment was not mutated, delete the shallow copy before guard.
+	} else {
+		delete env;
+		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
+
+	// 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, transUnit().global } );
+	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;
+		auto mut = mutate(resolved.get());
+		assertf(mut == resolved.get(), "newly resolved expression must be unique");
+		mut->env = nullptr;
+	} // if
+	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");
+	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?
+	assert( env );
+	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(loc, "__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 ) {
+	auto global = transUnit().global;
+	// 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( global.dtorStruct, "Destructor generation requires __Destructor definition." );
+	assertf( global.dtorStruct->members.size() == 2, "__Destructor definition does not have expected fields." );
+	assertf( global.dtorDestroy, "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 ) );
+	}
+
+	if ( ! dtor->env ) dtor->env = maybeClone( env );
+	auto dtorFunc = getDtorFunc( ret, new ast::ExprStmt(loc, dtor ), stmtsToAddBefore );
+
+	auto dtorStructType = new ast::StructInstType( global.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, global.dtorDestroy ) } ) );
+	stmtsToAddBefore.push_back( new ast::DeclStmt(loc, retDtor ) );
+
+	if ( arg ) {
+		auto member = new ast::MemberExpr(loc, global.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");
+		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
 		);
-		return new ast::FunctionDecl( loc,
-			fname,
-			std::move(typeParams),
-			{dstParam},
-			{},
-			new ast::CompoundStmt(loc),
-			{},
-			ast::Linkage::Cforall
-		);
-	}
-
-	struct SelfAssignChecker {
-		void previsit( const ast::ApplicationExpr * appExpr );
-	};
-
-	struct StmtExprResult {
-		const ast::StmtExpr * previsit( const ast::StmtExpr * stmtExpr );
-	};
-
-	/// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
-	/// function calls need their parameters to be copy constructed
-	struct InsertImplicitCalls : public ast::WithShortCircuiting {
-		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;
-	};
-
-	/// 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
-	struct ResolveCopyCtors final : public ast::WithGuards, public ast::WithStmtsToAdd<>, public ast::WithSymbolTable, public ast::WithShortCircuiting, public ast::WithVisitorRef<ResolveCopyCtors>, public ast::WithConstTranslationUnit {
-		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         = nullptr;
-		bool                    envModified = false;
-	};
-
-	/// 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 );
-	};
-
-	/// insert destructor calls at the appropriate places.  must happen before CtorInit nodes are removed
-	/// (currently by FixInit)
-	struct InsertDtors final : public ObjDeclCollector, public ast::WithStmtsToAdd<> {
-		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;
-	};
-
-	/// expand each object declaration to use its constructor after it is declared.
-	struct FixInit : public ast::WithStmtsToAdd<> {
-		static void fixInitializers( ast::TranslationUnit &translationUnit );
-
-		const ast::DeclWithType * postvisit( const ast::ObjectDecl *objDecl );
-
-		std::list< ast::ptr< ast::Decl > > staticDtorDecls;
-	};
-
-	/// 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
-	struct GenStructMemberCalls final : public ast::WithGuards, public ast::WithShortCircuiting, public ast::WithSymbolTable, public ast::WithVisitorRef<GenStructMemberCalls>, public ast::WithConstTranslationUnit {
-		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;
-	};
-
-	/// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
-	struct FixCtorExprs final : public ast::WithDeclsToAdd<>, public ast::WithSymbolTable, public ast::WithShortCircuiting, public ast::WithConstTranslationUnit {
-		const ast::Expr * postvisit( const ast::ConstructorExpr * ctorExpr );
-	};
-
-	/// add CompoundStmts around top-level expressions so that temporaries are destroyed in the correct places.
-	struct SplitExpressions : public ast::WithShortCircuiting {
-		ast::Stmt * postvisit( const ast::ExprStmt * stmt );
-		void previsit( const ast::TupleAssignExpr * expr );
-	};
+
+		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, CodeLocation const & loc ) {
+	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( loc, {} );
+		}
+	} 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( loc, {} );
+		}
+	}
+
+	return new ast::ListInit( loc, {
+		new ast::SingleInit( loc, ast::ConstantExpr::from_int( loc, 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->location ) );
+			mutExpr->var = new ast::VariableExpr( mutExpr->location, mutExpr->object );
+		}
+
+		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 ) {
+				addDataSectionAttribute(objDecl);
+				// 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 );
+					objDecl->init = nullptr;
+
+					// 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 );
+		auto global = transUnit().global;
+
+		// 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( global.dtorStruct, "builtin __Destructor not found." );
+						assertf( global.dtorDestroy, "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( global.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( loc, global.dtorDestroy ) } ) );
+						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... Params >
+void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
+	SemanticErrorException err( loc, toString( params... ) );
+	errors.append( err );
+}
+
+const ast::Expr * GenStructMemberCalls::postvisit( const ast::UntypedExpr * untypedExpr ) {
+	// xxx - functions returning ast::ptr seems wrong...
+	auto res = ResolvExpr::findVoidExpression( untypedExpr, { symtab, transUnit().global } );
+	return res.release();
+}
+
+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 );
+
+	// 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, transUnit().global } );
+	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
 
@@ -293,1110 +1380,4 @@
 }
 
-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 = 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 FixInit::fixInitializers( ast::TranslationUnit & 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.decls.begin(); i != translationUnit.decls.end(); ++i ) {
-			try {
-				// maybeAccept( *i, fixer ); translationUnit should never contain null
-				*i = (*i)->accept(fixer);
-				translationUnit.decls.splice( i, fixer.core.staticDtorDecls );
-			} catch( SemanticErrorException &e ) {
-				errors.append( e );
-			} // try
-		} // for
-		if ( ! errors.isEmpty() ) {
-			throw errors;
-		} // if
-	}
-
-	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 {
-		// Strip all casts and then dynamic_cast.
-		template<typename T>
-		static const T * cast( 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 dynamic_cast< const T * >( expr );
-		}
-
-		void previsit( const ast::Expr * ) {
-			// anything else does not qualify
-			result = false;
-		}
-
-		// ignore casts
-		void previsit( const ast::CastExpr * ) {}
-
-		void previsit( const ast::MemberExpr * memExpr ) {
-			if ( auto otherMember = cast< ast::MemberExpr >( other ) ) {
-				if ( otherMember->member == memExpr->member ) {
-					other = otherMember->aggregate;
-					return;
-				}
-			}
-			result = false;
-		}
-
-		void previsit( const ast::VariableExpr * varExpr ) {
-			if ( auto otherVar = cast< ast::VariableExpr >( other ) ) {
-				if ( otherVar->var == varExpr->var ) {
-					return;
-				}
-			}
-			result = false;
-		}
-
-		void previsit( const ast::AddressExpr * ) {
-			if ( auto addrExpr = cast< ast::AddressExpr >( other ) ) {
-				other = addrExpr->arg;
-				return;
-			}
-			result = false;
-		}
-
-		const ast::Expr * other;
-		bool result = true;
-		StructuralChecker( const ast::Expr * other ) : other(other) {}
-	};
-
-	bool structurallySimilar( const ast::Expr * e1, const ast::Expr * e2 ) {
-		return ast::Pass<StructuralChecker>::read( e1, e2 );
-	}
-
-	void SelfAssignChecker::previsit( const ast::ApplicationExpr * appExpr ) {
-		auto function = getFunction( appExpr );
-		// Doesn't use isAssignment, because ?+=?, etc. should not count as self-assignment.
-		if ( function->name == "?=?" && 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).
-				&& 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. The substitution
-		// is needed to obtain the type of temporary variables so that copy
-		// constructor calls can be resolved.
-		expr->env = tmp;
-		return expr;
-	}
-
-	void ResolveCopyCtors::previsit(const ast::Expr * expr) {
-		if ( nullptr == expr->env ) {
-			return;
-		}
-		GuardValue( env ) = expr->env->clone();
-		GuardValue( envModified ) = false;
-	}
-
-	const ast::Expr * ResolveCopyCtors::postvisit(const ast::Expr * expr) {
-		// No local environment, skip.
-		if ( nullptr == expr->env ) {
-			return expr;
-		// Environment was modified, mutate and replace.
-		} else if ( envModified ) {
-			auto mutExpr = mutate(expr);
-			mutExpr->env = env;
-			return mutExpr;
-		// Environment was not mutated, delete the shallow copy before guard.
-		} else {
-			delete env;
-			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
-
-		// 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, transUnit().global } );
-		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;
-			auto mut = mutate(resolved.get());
-			assertf(mut == resolved.get(), "newly resolved expression must be unique");
-			mut->env = nullptr;
-		} // if
-		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");
-		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?
-		assert( env );
-		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(loc, "__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 ) {
-		auto global = transUnit().global;
-		// 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( global.dtorStruct, "Destructor generation requires __Destructor definition." );
-		assertf( global.dtorStruct->members.size() == 2, "__Destructor definition does not have expected fields." );
-		assertf( global.dtorDestroy, "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 ) );
-		}
-
-		if ( ! dtor->env ) dtor->env = maybeClone( env );
-		auto dtorFunc = getDtorFunc( ret, new ast::ExprStmt(loc, dtor ), stmtsToAddBefore );
-
-		auto dtorStructType = new ast::StructInstType( global.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, global.dtorDestroy ) } ) );
-		stmtsToAddBefore.push_back( new ast::DeclStmt(loc, retDtor ) );
-
-		if ( arg ) {
-			auto member = new ast::MemberExpr(loc, global.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");
-			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, CodeLocation const & loc ) {
-		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( loc, {} );
-			}
-		} 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( loc, {} );
-			}
-		}
-
-		return new ast::ListInit( loc, {
-			new ast::SingleInit( loc, ast::ConstantExpr::from_int( loc, 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->location ) );
-				mutExpr->var = new ast::VariableExpr( mutExpr->location, mutExpr->object );
-			}
-
-			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 ) {
-					addDataSectionAttribute(objDecl);
-					// 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 );
-						objDecl->init = nullptr;
-
-						// 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 );
-			auto global = transUnit().global;
-
-			// 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( global.dtorStruct, "builtin __Destructor not found." );
-							assertf( global.dtorDestroy, "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( global.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( loc, global.dtorDestroy ) } ) );
-							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... Params >
-	void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
-		SemanticErrorException err( loc, toString( params... ) );
-		errors.append( err );
-	}
-
-	const ast::Expr * GenStructMemberCalls::postvisit( const ast::UntypedExpr * untypedExpr ) {
-		// xxx - functions returning ast::ptr seems wrong...
-		auto res = ResolvExpr::findVoidExpression( untypedExpr, { symtab, transUnit().global } );
-		return res.release();
-	}
-
-	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 );
-
-		// 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, transUnit().global } );
-		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
 
Index: src/InitTweak/GenInit.cc
===================================================================
--- src/InitTweak/GenInit.cc	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/InitTweak/GenInit.cc	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -300,72 +300,167 @@
 
 #	warning Remove the _New suffix after the conversion is complete.
+
+	// Outer pass finds declarations, for their type could wrap a type that needs hoisting
 	struct HoistArrayDimension_NoResolve_New final :
 			public ast::WithDeclsToAdd<>, public ast::WithShortCircuiting,
 			public ast::WithGuards, public ast::WithConstTranslationUnit,
-			public ast::WithVisitorRef<HoistArrayDimension_NoResolve_New> {
-		void previsit( const ast::ObjectDecl * decl );
-		const ast::DeclWithType * postvisit( const ast::ObjectDecl * decl );
-		// Do not look for objects inside there declarations (and type).
-		void previsit( const ast::AggregateDecl * ) { visit_children = false; }
-		void previsit( const ast::NamedTypeDecl * ) { visit_children = false; }
-		void previsit( const ast::FunctionType * ) { visit_children = false; }
-
-		const ast::Type * hoist( const ast::Type * type );
+			public ast::WithVisitorRef<HoistArrayDimension_NoResolve_New>,
+			public ast::WithSymbolTableX<ast::SymbolTable::ErrorDetection::IgnoreErrors> {
+
+		// Inner pass looks within a type, for a part that depends on an expression
+		struct HoistDimsFromTypes final :
+				public ast::WithShortCircuiting, public ast::WithGuards {
+
+			HoistArrayDimension_NoResolve_New * outer;
+			HoistDimsFromTypes( HoistArrayDimension_NoResolve_New * outer ) : outer(outer) {}
+
+			// Only intended for visiting through types.
+			// Tolerate, and short-circuit at, the dimension expression of an array type.
+			//    (We'll operate on the dimension expression of an array type directly
+			//    from the parent type, not by visiting through it)
+			// Look inside type exprs.
+			void previsit( const ast::Node * ) {
+				assert( false && "unsupported node type" );
+			};
+			const ast::Expr * allowedExpr = nullptr;
+			void previsit( const ast::Type * ) {
+				GuardValue( allowedExpr ) = nullptr;
+			}
+			void previsit( const ast::ArrayType * t ) {
+				GuardValue( allowedExpr ) = t->dimension.get();
+			}
+			void previsit( const ast::PointerType * t ) {
+				GuardValue( allowedExpr ) = t->dimension.get();
+			}
+			void previsit( const ast::TypeofType * t ) {
+				GuardValue( allowedExpr ) = t->expr.get();
+			}
+			void previsit( const ast::Expr * e ) {
+				assert( e == allowedExpr &&
+				    "only expecting to visit exprs that are dimension exprs or typeof(-) inner exprs" );
+
+				// Skip the tolerated expressions
+				visit_children = false;
+			}
+			void previsit( const ast::TypeExpr * ) {}
+
+			const ast::Type * postvisit(
+					const ast::ArrayType * arrayType ) {
+				static UniqueName dimensionName( "_array_dim" );
+
+				if ( nullptr == arrayType->dimension ) {  // if no dimension is given, don't presume to invent one
+					return arrayType;
+				}
+
+				// find size_t; use it as the type for a dim expr
+				ast::ptr<ast::Type> dimType = outer->transUnit().global.sizeType;
+				assert( dimType );
+				add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) );
+
+				// Special-case handling: leave the user's dimension expression alone
+				// - requires the user to have followed a careful convention
+				// - may apply to extremely simple applications, but only as windfall
+				// - users of advanced applications will be following the convention on purpose
+				// - CFA maintainers must protect the criteria against leaving too much alone
+
+				// Actual leave-alone cases following are conservative approximations of "cannot vary"
+
+				// Leave alone: literals and enum constants
+				if ( dynamic_cast< const ast::ConstantExpr * >( arrayType->dimension.get() ) ) {
+					return arrayType;
+				}
+
+				// Leave alone: direct use of an object declared to be const
+				const ast::NameExpr * dimn = dynamic_cast< const ast::NameExpr * >( arrayType->dimension.get() );
+				if ( dimn ) {
+					std::vector<ast::SymbolTable::IdData> dimnDefs = outer->symtab.lookupId( dimn->name );
+					if ( dimnDefs.size() == 1 ) {
+						const ast::DeclWithType * dimnDef = dimnDefs[0].id.get();
+						assert( dimnDef && "symbol table binds a name to nothing" );
+						const ast::ObjectDecl * dimOb = dynamic_cast< const ast::ObjectDecl * >( dimnDef );
+						if( dimOb ) {
+							const ast::Type * dimTy = dimOb->type.get();
+							assert( dimTy && "object declaration bearing no type" );
+							// must not hoist some: size_t
+							// must hoist all: pointers and references
+							// the analysis is conservative; BasicType is a simple approximation
+							if ( dynamic_cast< const ast::BasicType * >( dimTy ) ||
+							     dynamic_cast< const ast::SueInstType<ast::EnumDecl> * >( dimTy ) ) {
+								if ( dimTy->is_const() ) {
+									// The dimension is certainly re-evaluable, giving the same answer each time.
+									// Our user might be hoping to write the array type in multiple places, having them unify.
+									// Leave the type alone.
+
+									// We believe the new criterion leaves less alone than the old criterion.
+									// Thus, the old criterion should have left the current case alone.
+									// Catch cases that weren't thought through.
+									assert( !Tuples::maybeImpure( arrayType->dimension ) );
+
+									return arrayType;
+								}
+							};
+						}
+					}
+				}
+
+				// Leave alone: any sizeof expression (answer cannot vary during current lexical scope)
+				const ast::SizeofExpr * sz = dynamic_cast< const ast::SizeofExpr * >( arrayType->dimension.get() );
+				if ( sz ) {
+					return arrayType;
+				}
+
+				// General-case handling: change the array-type's dim expr (hoist the user-given content out of the type)
+				// - always safe
+				// - user-unnoticeable in common applications (benign noise in -CFA output)
+				// - may annoy a responsible user of advanced applications (but they can work around)
+				// - protects against misusing advanced features
+				//
+				// The hoist, by example, is:
+				// FROM USER:  float a[ rand() ];
+				// TO GCC:     const size_t __len_of_a = rand(); float a[ __len_of_a ];
+
+				ast::ObjectDecl * arrayDimension = new ast::ObjectDecl(
+					arrayType->dimension->location,
+					dimensionName.newName(),
+					dimType,
+					new ast::SingleInit(
+						arrayType->dimension->location,
+						arrayType->dimension
+					)
+				);
+
+				ast::ArrayType * mutType = ast::mutate( arrayType );
+				mutType->dimension = new ast::VariableExpr(
+						arrayDimension->location, arrayDimension );
+				outer->declsToAddBefore.push_back( arrayDimension );
+
+				return mutType;
+			}  // postvisit( const ast::ArrayType * )
+		}; // struct HoistDimsFromTypes
 
 		ast::Storage::Classes storageClasses;
+		void previsit(
+				const ast::ObjectDecl * decl ) {
+			GuardValue( storageClasses ) = decl->storage;
+		}
+
+		const ast::DeclWithType * postvisit(
+				const ast::ObjectDecl * objectDecl ) {
+
+			if ( !isInFunction() || storageClasses.is_static ) {
+				return objectDecl;
+			}
+
+			const ast::Type * mid = objectDecl->type;
+
+			ast::Pass<HoistDimsFromTypes> hoist{this};
+			const ast::Type * result = mid->accept( hoist );
+
+			return mutate_field( objectDecl, &ast::ObjectDecl::type, result );
+		}
 	};
 
-	void HoistArrayDimension_NoResolve_New::previsit(
-			const ast::ObjectDecl * decl ) {
-		GuardValue( storageClasses ) = decl->storage;
-	}
-
-	const ast::DeclWithType * HoistArrayDimension_NoResolve_New::postvisit(
-			const ast::ObjectDecl * objectDecl ) {
-		return mutate_field( objectDecl, &ast::ObjectDecl::type,
-				hoist( objectDecl->type ) );
-	}
-
-	const ast::Type * HoistArrayDimension_NoResolve_New::hoist(
-			const ast::Type * type ) {
-		static UniqueName dimensionName( "_array_dim" );
-
-		if ( !isInFunction() || storageClasses.is_static ) {
-			return type;
-		}
-
-		if ( auto arrayType = dynamic_cast< const ast::ArrayType * >( type ) ) {
-			if ( nullptr == arrayType->dimension ) {
-				return type;
-			}
-
-			if ( !Tuples::maybeImpure( arrayType->dimension ) ) {
-				return type;
-			}
-
-			ast::ptr<ast::Type> dimType = transUnit().global.sizeType;
-			assert( dimType );
-			add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) );
-
-			ast::ObjectDecl * arrayDimension = new ast::ObjectDecl(
-				arrayType->dimension->location,
-				dimensionName.newName(),
-				dimType,
-				new ast::SingleInit(
-					arrayType->dimension->location,
-					arrayType->dimension
-				)
-			);
-
-			ast::ArrayType * mutType = ast::mutate( arrayType );
-			mutType->dimension = new ast::VariableExpr(
-					arrayDimension->location, arrayDimension );
-			declsToAddBefore.push_back( arrayDimension );
-
-			mutType->base = hoist( mutType->base );
-			return mutType;
-		}
-		return type;
-	}
+
+
 
 	struct ReturnFixer_New final :
Index: src/InitTweak/InitTweak.cc
===================================================================
--- src/InitTweak/InitTweak.cc	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/InitTweak/InitTweak.cc	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -882,5 +882,5 @@
 		if (!assign) {
 			auto td = new ast::TypeDecl(CodeLocation(), "T", {}, nullptr, ast::TypeDecl::Dtype, true);
-			assign = new ast::FunctionDecl(CodeLocation(), "?=?", {},
+			assign = new ast::FunctionDecl(CodeLocation(), "?=?", {td},
 			{ new ast::ObjectDecl(CodeLocation(), "_dst", new ast::ReferenceType(new ast::TypeInstType("T", td))),
 			  new ast::ObjectDecl(CodeLocation(), "_src", new ast::TypeInstType("T", td))},
@@ -891,6 +891,5 @@
 				dst = new ast::AddressExpr(dst);
 			}
-		}
-		else {
+		} else {
 			dst = new ast::CastExpr(dst, new ast::ReferenceType(dst->result, {}));
 		}
@@ -900,5 +899,9 @@
 			}
 		}
-		return new ast::ApplicationExpr(dst->location, ast::VariableExpr::functionPointer(dst->location, assign), {dst, src});
+		auto var = ast::VariableExpr::functionPointer(dst->location, assign);
+		auto app = new ast::ApplicationExpr(dst->location, var, {dst, src});
+		// Skip the resolver, just set the result to the correct type.
+		app->result = ast::deepCopy( src->result );
+		return app;
 	}
 
Index: src/Parser/StatementNode.cc
===================================================================
--- src/Parser/StatementNode.cc	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Parser/StatementNode.cc	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -10,7 +10,7 @@
 // Author           : Rodolfo G. Esteves
 // Created On       : Sat May 16 14:59:41 2015
-// Last Modified By : Andrew Beach
-// Last Modified On : Tue Apr 11 10:16:00 2023
-// Update Count     : 428
+// Last Modified By : Peter A. Buhr
+// Last Modified On : Fri Aug 11 11:44:15 2023
+// Update Count     : 429
 //
 
@@ -361,90 +361,82 @@
 
 ast::WaitUntilStmt::ClauseNode * build_waituntil_clause( const CodeLocation & loc, ExpressionNode * when, ExpressionNode * targetExpr, StatementNode * stmt ) {
-    ast::WhenClause * clause = new ast::WhenClause( loc );
-    clause->when_cond = notZeroExpr( maybeMoveBuild( when ) );
-    clause->stmt = maybeMoveBuild( stmt );
-    clause->target = maybeMoveBuild( targetExpr );
-    return new ast::WaitUntilStmt::ClauseNode( clause );
+	ast::WhenClause * clause = new ast::WhenClause( loc );
+	clause->when_cond = notZeroExpr( maybeMoveBuild( when ) );
+	clause->stmt = maybeMoveBuild( stmt );
+	clause->target = maybeMoveBuild( targetExpr );
+	return new ast::WaitUntilStmt::ClauseNode( clause );
 }
 ast::WaitUntilStmt::ClauseNode * build_waituntil_else( const CodeLocation & loc, ExpressionNode * when, StatementNode * stmt ) {
-    ast::WhenClause * clause = new ast::WhenClause( loc );
-    clause->when_cond = notZeroExpr( maybeMoveBuild( when ) );
-    clause->stmt = maybeMoveBuild( stmt );
-    return new ast::WaitUntilStmt::ClauseNode( ast::WaitUntilStmt::ClauseNode::Op::ELSE, clause );
-}
-ast::WaitUntilStmt::ClauseNode * build_waituntil_timeout( const CodeLocation & loc, ExpressionNode * when, ExpressionNode * timeout, StatementNode * stmt ) {
-    ast::WhenClause * clause = new ast::WhenClause( loc );
-    clause->when_cond = notZeroExpr( maybeMoveBuild( when ) );
-    clause->stmt = maybeMoveBuild( stmt );
-    clause->target = maybeMoveBuild( timeout );
-    return new ast::WaitUntilStmt::ClauseNode( ast::WaitUntilStmt::ClauseNode::Op::TIMEOUT, clause );
+	ast::WhenClause * clause = new ast::WhenClause( loc );
+	clause->when_cond = notZeroExpr( maybeMoveBuild( when ) );
+	clause->stmt = maybeMoveBuild( stmt );
+	return new ast::WaitUntilStmt::ClauseNode( ast::WaitUntilStmt::ClauseNode::Op::ELSE, clause );
 }
 
 ast::WaitUntilStmt * build_waituntil_stmt( const CodeLocation & loc, ast::WaitUntilStmt::ClauseNode * root ) {
-    ast::WaitUntilStmt * retStmt = new ast::WaitUntilStmt( loc );
-    retStmt->predicateTree = root;
-    
-    // iterative tree traversal
-    std::vector<ast::WaitUntilStmt::ClauseNode *> nodeStack; // stack needed for iterative traversal
-    ast::WaitUntilStmt::ClauseNode * currNode = nullptr;
-    ast::WaitUntilStmt::ClauseNode * lastInternalNode = nullptr;
-    ast::WaitUntilStmt::ClauseNode * cleanup = nullptr; // used to cleanup removed else/timeout
-    nodeStack.push_back(root);
-
-    do {
-        currNode = nodeStack.back();
-        nodeStack.pop_back(); // remove node since it will be processed
-
-        switch (currNode->op) {
-            case ast::WaitUntilStmt::ClauseNode::LEAF:
-                retStmt->clauses.push_back(currNode->leaf);
-                break;
-            case ast::WaitUntilStmt::ClauseNode::ELSE:
-                retStmt->else_stmt = currNode->leaf->stmt 
-                    ? ast::deepCopy( currNode->leaf->stmt )
-                    : nullptr;
-                
-                retStmt->else_cond = currNode->leaf->when_cond
-                    ? ast::deepCopy( currNode->leaf->when_cond )
-                    : nullptr;
-
-                delete currNode->leaf;
-                break;
-            case ast::WaitUntilStmt::ClauseNode::TIMEOUT:
-                retStmt->timeout_time = currNode->leaf->target 
-                    ? ast::deepCopy( currNode->leaf->target )
-                    : nullptr;
-                retStmt->timeout_stmt = currNode->leaf->stmt
-                    ? ast::deepCopy( currNode->leaf->stmt )
-                    : nullptr;
-                retStmt->timeout_cond = currNode->leaf->when_cond
-                    ? ast::deepCopy( currNode->leaf->when_cond )
-                    : nullptr;
-
-                delete currNode->leaf;
-                break;
-            default:
-                nodeStack.push_back( currNode->right ); // process right after left
-                nodeStack.push_back( currNode->left );
-
-                // Cut else/timeout out of the tree
-                if ( currNode->op == ast::WaitUntilStmt::ClauseNode::LEFT_OR ) {
-                    if ( lastInternalNode )
-                        lastInternalNode->right = currNode->left;
-                    else    // if not set then root is LEFT_OR 
-                        retStmt->predicateTree = currNode->left;
-    
-                    currNode->left = nullptr;
-                    cleanup = currNode;
-                }
-                
-                lastInternalNode = currNode;
-                break;
-        }
-    } while ( !nodeStack.empty() );
-
-    if ( cleanup ) delete cleanup;
-
-    return retStmt;
+	ast::WaitUntilStmt * retStmt = new ast::WaitUntilStmt( loc );
+	retStmt->predicateTree = root;
+
+	// iterative tree traversal
+	std::vector<ast::WaitUntilStmt::ClauseNode *> nodeStack; // stack needed for iterative traversal
+	ast::WaitUntilStmt::ClauseNode * currNode = nullptr;
+	ast::WaitUntilStmt::ClauseNode * lastInternalNode = nullptr;
+	ast::WaitUntilStmt::ClauseNode * cleanup = nullptr; // used to cleanup removed else/timeout
+	nodeStack.push_back(root);
+
+	do {
+		currNode = nodeStack.back();
+		nodeStack.pop_back(); // remove node since it will be processed
+
+		switch (currNode->op) {
+		case ast::WaitUntilStmt::ClauseNode::LEAF:
+			retStmt->clauses.push_back(currNode->leaf);
+			break;
+		case ast::WaitUntilStmt::ClauseNode::ELSE:
+			retStmt->else_stmt = currNode->leaf->stmt
+				? ast::deepCopy( currNode->leaf->stmt )
+				: nullptr;
+			retStmt->else_cond = currNode->leaf->when_cond
+				? ast::deepCopy( currNode->leaf->when_cond )
+				: nullptr;
+
+			delete currNode->leaf;
+			break;
+		case ast::WaitUntilStmt::ClauseNode::TIMEOUT:
+			retStmt->timeout_time = currNode->leaf->target
+				? ast::deepCopy( currNode->leaf->target )
+				: nullptr;
+			retStmt->timeout_stmt = currNode->leaf->stmt
+				? ast::deepCopy( currNode->leaf->stmt )
+				: nullptr;
+			retStmt->timeout_cond = currNode->leaf->when_cond
+				? ast::deepCopy( currNode->leaf->when_cond )
+				: nullptr;
+
+			delete currNode->leaf;
+			break;
+		default:
+			nodeStack.push_back( currNode->right ); // process right after left
+			nodeStack.push_back( currNode->left );
+
+			// Cut else/timeout out of the tree
+			if ( currNode->op == ast::WaitUntilStmt::ClauseNode::LEFT_OR ) {
+				if ( lastInternalNode )
+					lastInternalNode->right = currNode->left;
+				else // if not set then root is LEFT_OR
+					retStmt->predicateTree = currNode->left;
+
+				currNode->left = nullptr;
+				cleanup = currNode;
+			}
+
+			lastInternalNode = currNode;
+			break;
+		}
+	} while ( !nodeStack.empty() );
+
+	if ( cleanup ) delete cleanup;
+
+	return retStmt;
 }
 
Index: src/Parser/StatementNode.h
===================================================================
--- src/Parser/StatementNode.h	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Parser/StatementNode.h	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -9,7 +9,7 @@
 // Author           : Andrew Beach
 // Created On       : Wed Apr  5 11:42:00 2023
-// Last Modified By : Andrew Beach
-// Last Modified On : Tue Apr 11  9:43:00 2023
-// Update Count     : 1
+// Last Modified By : Peter A. Buhr
+// Last Modified On : Fri Aug 11 11:44:07 2023
+// Update Count     : 2
 //
 
@@ -102,5 +102,4 @@
 ast::WaitUntilStmt::ClauseNode * build_waituntil_clause( const CodeLocation &, ExpressionNode * when, ExpressionNode * targetExpr, StatementNode * stmt );
 ast::WaitUntilStmt::ClauseNode * build_waituntil_else( const CodeLocation &, ExpressionNode * when, StatementNode * stmt );
-ast::WaitUntilStmt::ClauseNode * build_waituntil_timeout( const CodeLocation &, ExpressionNode * when, ExpressionNode * timeout, StatementNode * stmt );
 ast::WaitUntilStmt * build_waituntil_stmt( const CodeLocation &, ast::WaitUntilStmt::ClauseNode * root );
 ast::Stmt * build_with( const CodeLocation &, ExpressionNode * exprs, StatementNode * stmt );
Index: src/Parser/TypedefTable.cc
===================================================================
--- src/Parser/TypedefTable.cc	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Parser/TypedefTable.cc	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -10,6 +10,6 @@
 // Created On       : Sat May 16 15:20:13 2015
 // Last Modified By : Peter A. Buhr
-// Last Modified On : Tue Feb 15 08:27:24 2022
-// Update Count     : 275
+// Last Modified On : Wed Jul 12 06:11:28 2023
+// Update Count     : 276
 //
 
@@ -17,13 +17,13 @@
 #include "TypedefTable.h"
 
-#include <cassert>                                // for assert
-#include <string>                                 // for string
-#include <iostream>                               // for iostream
+#include <cassert>										// for assert
+#include <string>										// for string
+#include <iostream>										// for iostream
 
-#include "ExpressionNode.h"                       // for LabelNode
-#include "ParserTypes.h"                          // for Token
-#include "StatementNode.h"                        // for CondCtl, ForCtrl
+#include "ExpressionNode.h"								// for LabelNode
+#include "ParserTypes.h"								// for Token
+#include "StatementNode.h"								// for CondCtl, ForCtrl
 // This (generated) header must come late as it is missing includes.
-#include "parser.hh"              // for IDENTIFIER, TYPEDEFname, TYPEGENname
+#include "parser.hh"									// for IDENTIFIER, TYPEDEFname, TYPEGENname
 
 using namespace std;
@@ -72,5 +72,5 @@
 // "struct". Only generate the typedef, if the name is not in use. The typedef is implicitly (silently) removed if the
 // name is explicitly used.
-void TypedefTable::makeTypedef( const string & name, int kind ) {
+void TypedefTable::makeTypedef( const string & name, int kind, const char * locn __attribute__((unused)) ) {
 //    Check for existence is necessary to handle:
 //        struct Fred {};
@@ -80,4 +80,5 @@
 //           Fred();
 //        }
+	debugPrint( cerr << "Make typedef at " << locn << " \"" << name << "\" as " << kindName( kind ) << " scope " << kindTable.currentScope() << endl );
 	if ( ! typedefTable.exists( name ) ) {
 		typedefTable.addToEnclosingScope( name, kind, "MTD" );
@@ -85,11 +86,12 @@
 } // TypedefTable::makeTypedef
 
-void TypedefTable::makeTypedef( const string & name ) {
-	return makeTypedef( name, TYPEDEFname );
+void TypedefTable::makeTypedef( const string & name, const char * locn __attribute__((unused)) ) {
+	debugPrint( cerr << "Make typedef at " << locn << " \"" << name << " scope " << kindTable.currentScope() << endl );
+	return makeTypedef( name, TYPEDEFname, "makeTypede" );
 } // TypedefTable::makeTypedef
 
 void TypedefTable::addToScope( const string & identifier, int kind, const char * locn __attribute__((unused)) ) {
 	KindTable::size_type scope = kindTable.currentScope();
-	debugPrint( cerr << "Adding current at " << locn << " " << identifier << " as " << kindName( kind ) << " scope " << scope << endl );
+	debugPrint( cerr << "Adding current at " << locn << " \"" << identifier << "\" as " << kindName( kind ) << " scope " << scope << endl );
 	kindTable.insertAt( scope, identifier, kind );
 } // TypedefTable::addToScope
@@ -98,5 +100,5 @@
 	KindTable::size_type scope = kindTable.currentScope() - 1 - kindTable.getNote( kindTable.currentScope() - 1 ).level;
 //	size_type scope = level - kindTable.getNote( kindTable.currentScope() - 1 ).level;
-	debugPrint( cerr << "Adding enclosing at " << locn << " " << identifier << " as " << kindName( kind ) << " scope " << scope << " level " << level << " note " << kindTable.getNote( kindTable.currentScope() - 1 ).level << endl );
+	debugPrint( cerr << "Adding enclosing at " << locn << " \"" << identifier << "\" as " << kindName( kind ) << " scope " << scope << " level " << level << " note " << kindTable.getNote( kindTable.currentScope() - 1 ).level << endl );
 	pair< KindTable::iterator, bool > ret = kindTable.insertAt( scope, identifier, kind );
 	if ( ! ret.second ) ret.first->second = kind;		// exists => update
Index: src/Parser/TypedefTable.h
===================================================================
--- src/Parser/TypedefTable.h	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Parser/TypedefTable.h	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -10,6 +10,6 @@
 // Created On       : Sat May 16 15:24:36 2015
 // Last Modified By : Peter A. Buhr
-// Last Modified On : Sat Feb 15 08:06:37 2020
-// Update Count     : 117
+// Last Modified On : Wed Jul 12 06:09:37 2023
+// Update Count     : 118
 //
 
@@ -21,5 +21,8 @@
 
 class TypedefTable {
-	struct Note { size_t level; bool forall; };
+	struct Note {
+		size_t level;
+		bool forall;
+	};
 	typedef ScopedMap< std::string, int, Note > KindTable;
 	KindTable kindTable;
@@ -31,6 +34,6 @@
 	bool existsCurr( const std::string & identifier ) const;
 	int isKind( const std::string & identifier ) const;
-	void makeTypedef( const std::string & name, int kind );
-	void makeTypedef( const std::string & name );
+	void makeTypedef( const std::string & name, int kind, const char * );
+	void makeTypedef( const std::string & name, const char * );
 	void addToScope( const std::string & identifier, int kind, const char * );
 	void addToEnclosingScope( const std::string & identifier, int kind, const char * );
Index: src/Parser/parser.yy
===================================================================
--- src/Parser/parser.yy	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Parser/parser.yy	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -10,6 +10,6 @@
 // Created On       : Sat Sep  1 20:22:55 2001
 // Last Modified By : Peter A. Buhr
-// Last Modified On : Sat Jun 17 18:53:24 2023
-// Update Count     : 6347
+// Last Modified On : Tue Jul 18 22:51:30 2023
+// Update Count     : 6391
 //
 
@@ -385,24 +385,24 @@
 %type<str> string_literal_list
 
-%type<enum_hiding> hide_opt					visible_hide_opt
+%type<enum_hiding> hide_opt				visible_hide_opt
 
 // expressions
 %type<expr> constant
-%type<expr> tuple							tuple_expression_list
+%type<expr> tuple						tuple_expression_list
 %type<oper> ptrref_operator				unary_operator				assignment_operator			simple_assignment_operator	compound_assignment_operator
 %type<expr> primary_expression			postfix_expression			unary_expression
-%type<expr> cast_expression_list			cast_expression				exponential_expression		multiplicative_expression	additive_expression
-%type<expr> shift_expression				relational_expression		equality_expression
+%type<expr> cast_expression_list		cast_expression				exponential_expression		multiplicative_expression	additive_expression
+%type<expr> shift_expression			relational_expression		equality_expression
 %type<expr> AND_expression				exclusive_OR_expression		inclusive_OR_expression
 %type<expr> logical_AND_expression		logical_OR_expression
 %type<expr> conditional_expression		constant_expression			assignment_expression		assignment_expression_opt
-%type<expr> comma_expression				comma_expression_opt
-%type<expr> argument_expression_list_opt	argument_expression_list	argument_expression			default_initializer_opt
+%type<expr> comma_expression			comma_expression_opt
+%type<expr> argument_expression_list_opt argument_expression_list	argument_expression			default_initializer_opt
 %type<ifctl> conditional_declaration
-%type<forctl> for_control_expression		for_control_expression_list
+%type<forctl> for_control_expression	for_control_expression_list
 %type<oper> upupeq updown updowneq downupdowneq
 %type<expr> subrange
 %type<decl> asm_name_opt
-%type<expr> asm_operands_opt				asm_operands_list			asm_operand
+%type<expr> asm_operands_opt			asm_operands_list			asm_operand
 %type<labels> label_list
 %type<expr> asm_clobbers_list_opt
@@ -412,12 +412,12 @@
 
 // statements
-%type<stmt> statement						labeled_statement			compound_statement
+%type<stmt> statement					labeled_statement			compound_statement
 %type<stmt> statement_decl				statement_decl_list			statement_list_nodecl
 %type<stmt> selection_statement			if_statement
-%type<clause> switch_clause_list_opt		switch_clause_list
+%type<clause> switch_clause_list_opt	switch_clause_list
 %type<expr> case_value
-%type<clause> case_clause				case_value_list				case_label					case_label_list
+%type<clause> case_clause				case_value_list				case_label	case_label_list
 %type<stmt> iteration_statement			jump_statement
-%type<stmt> expression_statement			asm_statement
+%type<stmt> expression_statement		asm_statement
 %type<stmt> with_statement
 %type<expr> with_clause_opt
@@ -427,5 +427,5 @@
 %type<stmt> mutex_statement
 %type<expr> when_clause					when_clause_opt				waitfor		waituntil		timeout
-%type<stmt> waitfor_statement				waituntil_statement
+%type<stmt> waitfor_statement			waituntil_statement
 %type<wfs> wor_waitfor_clause
 %type<wucn> waituntil_clause			wand_waituntil_clause       wor_waituntil_clause
@@ -601,5 +601,5 @@
 // around the list separator.
 //
-//  int f( forall(T) T (*f1) T , forall( S ) S (*f2)( S ) );
+//  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 //      push               pop   push                   pop
 
@@ -689,15 +689,15 @@
 	// | RESUME '(' comma_expression ')' compound_statement
 	//   	{ SemanticError( yylloc, "Resume expression is currently unimplemented." ); $$ = nullptr; }
-	| IDENTIFIER IDENTIFIER								// invalid syntax rules
+	| IDENTIFIER IDENTIFIER								// invalid syntax rule
 		{ IdentifierBeforeIdentifier( *$1.str, *$2.str, "n expression" ); $$ = nullptr; }
-	| IDENTIFIER type_qualifier							// invalid syntax rules
+	| IDENTIFIER type_qualifier							// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "type qualifier" ); $$ = nullptr; }
-	| IDENTIFIER storage_class							// invalid syntax rules
+	| IDENTIFIER storage_class							// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "storage class" ); $$ = nullptr; }
-	| IDENTIFIER basic_type_name						// invalid syntax rules
+	| IDENTIFIER basic_type_name						// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
-	| IDENTIFIER TYPEDEFname							// invalid syntax rules
+	| IDENTIFIER TYPEDEFname							// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
-	| IDENTIFIER TYPEGENname							// invalid syntax rules
+	| IDENTIFIER TYPEGENname							// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
 	;
@@ -1275,5 +1275,5 @@
 	| DEFAULT ':'								{ $$ = new ClauseNode( build_default( yylloc ) ); }
 		// A semantic check is required to ensure only one default clause per switch/choose statement.
-	| DEFAULT error										//  invalid syntax rules
+	| DEFAULT error										//  invalid syntax rule
 		{ SemanticError( yylloc, "syntax error, colon missing after default." ); $$ = nullptr; }
 	;
@@ -1405,13 +1405,13 @@
 			else { SemanticError( yylloc, MISSING_HIGH ); $$ = nullptr; }
 		}
-	| comma_expression updowneq comma_expression '~' '@' // CFA, invalid syntax rules
+	| comma_expression updowneq comma_expression '~' '@' // CFA, invalid syntax rule
 		{ SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
-	| '@' updowneq '@'									// CFA, invalid syntax rules
+	| '@' updowneq '@'									// CFA, invalid syntax rule
 		{ SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
-	| '@' updowneq comma_expression '~' '@'				// CFA, invalid syntax rules
+	| '@' updowneq comma_expression '~' '@'				// CFA, invalid syntax rule
 		{ SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
-	| comma_expression updowneq '@' '~' '@'				// CFA, invalid syntax rules
+	| comma_expression updowneq '@' '~' '@'				// CFA, invalid syntax rule
 		{ SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
-	| '@' updowneq '@' '~' '@'							// CFA, invalid syntax rules
+	| '@' updowneq '@' '~' '@'							// CFA, invalid syntax rule
 		{ SemanticError( yylloc, MISSING_ANON_FIELD ); $$ = nullptr; }
 
@@ -1434,10 +1434,10 @@
 			else $$ = forCtrl( yylloc, $3, $1, $3->clone(), $4, nullptr, NEW_ONE );
 		}
-	| comma_expression ';' '@' updowneq '@'				// CFA, invalid syntax rules
+	| comma_expression ';' '@' updowneq '@'				// CFA, invalid syntax rule
 		{ SemanticError( yylloc, "syntax error, missing low/high value for up/down-to range so index is uninitialized." ); $$ = nullptr; }
 
 	| comma_expression ';' comma_expression updowneq comma_expression '~' comma_expression // CFA
 		{ $$ = forCtrl( yylloc, $3, $1, UPDOWN( $4, $3->clone(), $5 ), $4, UPDOWN( $4, $5->clone(), $3->clone() ), $7 ); }
-	| comma_expression ';' '@' updowneq comma_expression '~' comma_expression // CFA, invalid syntax rules
+	| comma_expression ';' '@' updowneq comma_expression '~' comma_expression // CFA, invalid syntax rule
 		{
 			if ( $4 == OperKinds::LThan || $4 == OperKinds::LEThan ) { SemanticError( yylloc, MISSING_LOW ); $$ = nullptr; }
@@ -1452,5 +1452,5 @@
 	| comma_expression ';' comma_expression updowneq comma_expression '~' '@' // CFA
 		{ $$ = forCtrl( yylloc, $3, $1, UPDOWN( $4, $3->clone(), $5 ), $4, UPDOWN( $4, $5->clone(), $3->clone() ), nullptr ); }
-	| comma_expression ';' '@' updowneq comma_expression '~' '@' // CFA, invalid syntax rules
+	| comma_expression ';' '@' updowneq comma_expression '~' '@' // CFA, invalid syntax rule
 		{
 			if ( $4 == OperKinds::LThan || $4 == OperKinds::LEThan ) { SemanticError( yylloc, MISSING_LOW ); $$ = nullptr; }
@@ -1511,5 +1511,5 @@
 			else $$ = forCtrl( yylloc, $1, $2, $3, nullptr, nullptr );
 		}
-	| declaration '@' updowneq '@' '~' '@'				// CFA, invalid syntax rules
+	| declaration '@' updowneq '@' '~' '@'				// CFA, invalid syntax rule
 		{ SemanticError( yylloc, "syntax error, missing low/high value for up/down-to range so index is uninitialized." ); $$ = nullptr; }
 
@@ -1666,5 +1666,5 @@
 		{ $$ = build_waitfor_timeout( yylloc, $1, $3, $4, maybe_build_compound( yylloc, $5 ) ); }
 	// "else" must be conditional after timeout or timeout is never triggered (i.e., it is meaningless)
-	| wor_waitfor_clause wor when_clause_opt timeout statement wor ELSE statement // invalid syntax rules
+	| wor_waitfor_clause wor when_clause_opt timeout statement wor ELSE statement // invalid syntax rule
 		{ SemanticError( yylloc, "syntax error, else clause must be conditional after timeout or timeout never triggered." ); $$ = nullptr; }
 	| wor_waitfor_clause wor when_clause_opt timeout statement wor when_clause ELSE statement
@@ -1708,23 +1708,9 @@
 	| wor_waituntil_clause wor when_clause_opt ELSE statement
 		{ $$ = new ast::WaitUntilStmt::ClauseNode( ast::WaitUntilStmt::ClauseNode::Op::LEFT_OR, $1, build_waituntil_else( yylloc, $3, maybe_build_compound( yylloc, $5 ) ) ); }
-	| wor_waituntil_clause wor when_clause_opt timeout statement	%prec THEN
-		{ $$ = new ast::WaitUntilStmt::ClauseNode( ast::WaitUntilStmt::ClauseNode::Op::LEFT_OR, $1, build_waituntil_timeout( yylloc, $3, $4, maybe_build_compound( yylloc, $5 ) ) ); }
-	// "else" must be conditional after timeout or timeout is never triggered (i.e., it is meaningless)
-	| wor_waituntil_clause wor when_clause_opt timeout statement wor ELSE statement // invalid syntax rules
-		{ SemanticError( yylloc, "syntax error, else clause must be conditional after timeout or timeout never triggered." ); $$ = nullptr; }
-	| wor_waituntil_clause wor when_clause_opt timeout statement wor when_clause ELSE statement
-		{ $$ = new ast::WaitUntilStmt::ClauseNode( ast::WaitUntilStmt::ClauseNode::Op::LEFT_OR, $1,
-                new ast::WaitUntilStmt::ClauseNode( ast::WaitUntilStmt::ClauseNode::Op::OR, 
-                    build_waituntil_timeout( yylloc, $3, $4, maybe_build_compound( yylloc, $5 ) ), 
-                    build_waituntil_else( yylloc, $7, maybe_build_compound( yylloc, $9 ) ) ) ); }
 	;
 
 waituntil_statement:
 	wor_waituntil_clause								%prec THEN
-		// SKULLDUGGERY: create an empty compound statement to test parsing of waituntil statement.
-		{
-            $$ = new StatementNode( build_waituntil_stmt( yylloc, $1 ) );
-            // $$ = new StatementNode( build_compound( yylloc, nullptr ) );
-        }
+		{ $$ = new StatementNode( build_waituntil_stmt( yylloc, $1 ) );	}
 	;
 
@@ -1868,8 +1854,8 @@
 
 KR_parameter_list:
-	push c_declaration pop ';'
-		{ $$ = $2; }
-	| KR_parameter_list push c_declaration pop ';'
-		{ $$ = $1->appendList( $3 ); }
+	c_declaration ';'
+		{ $$ = $1; }
+	| KR_parameter_list c_declaration ';'
+		{ $$ = $1->appendList( $2 ); }
 	;
 
@@ -2007,15 +1993,15 @@
 	TYPEDEF cfa_variable_specifier
 		{
-			typedefTable.addToEnclosingScope( *$2->name, TYPEDEFname, "1" );
+			typedefTable.addToEnclosingScope( *$2->name, TYPEDEFname, "cfa_typedef_declaration 1" );
 			$$ = $2->addTypedef();
 		}
 	| TYPEDEF cfa_function_specifier
 		{
-			typedefTable.addToEnclosingScope( *$2->name, TYPEDEFname, "2" );
+			typedefTable.addToEnclosingScope( *$2->name, TYPEDEFname, "cfa_typedef_declaration 2" );
 			$$ = $2->addTypedef();
 		}
 	| cfa_typedef_declaration pop ',' push identifier
 		{
-			typedefTable.addToEnclosingScope( *$5, TYPEDEFname, "3" );
+			typedefTable.addToEnclosingScope( *$5, TYPEDEFname, "cfa_typedef_declaration 3" );
 			$$ = $1->appendList( $1->cloneType( $5 ) );
 		}
@@ -2028,13 +2014,13 @@
 	TYPEDEF type_specifier declarator
 		{
-			typedefTable.addToEnclosingScope( *$3->name, TYPEDEFname, "4" );
+			typedefTable.addToEnclosingScope( *$3->name, TYPEDEFname, "typedef_declaration 1" );
 			if ( $2->type->forall || ($2->type->kind == TypeData::Aggregate && $2->type->aggregate.params) ) {
 				SemanticError( yylloc, "forall qualifier in typedef is currently unimplemented." ); $$ = nullptr;
 			} else $$ = $3->addType( $2 )->addTypedef(); // watchout frees $2 and $3
 		}
-	| typedef_declaration pop ',' push declarator
-		{
-			typedefTable.addToEnclosingScope( *$5->name, TYPEDEFname, "5" );
-			$$ = $1->appendList( $1->cloneBaseType( $5 )->addTypedef() );
+	| typedef_declaration ',' declarator
+		{
+			typedefTable.addToEnclosingScope( *$3->name, TYPEDEFname, "typedef_declaration 2" );
+			$$ = $1->appendList( $1->cloneBaseType( $3 )->addTypedef() );
 		}
 	| type_qualifier_list TYPEDEF type_specifier declarator // remaining OBSOLESCENT (see 2 )
@@ -2052,5 +2038,5 @@
 			SemanticError( yylloc, "TYPEDEF expression is deprecated, use typeof(...) instead." ); $$ = nullptr;
 		}
-	| typedef_expression pop ',' push identifier '=' assignment_expression
+	| typedef_expression ',' identifier '=' assignment_expression
 		{
 			SemanticError( yylloc, "TYPEDEF expression is deprecated, use typeof(...) instead." ); $$ = nullptr;
@@ -2465,5 +2451,5 @@
 	| aggregate_key attribute_list_opt identifier
 		{
-			typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname ); // create typedef
+			typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname, "aggregate_type: 1" );
 			forall = false;								// reset
 		}
@@ -2474,5 +2460,5 @@
 	| aggregate_key attribute_list_opt TYPEDEFname		// unqualified type name
 		{
-			typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname ); // create typedef
+			typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname, "aggregate_type: 2" );
 			forall = false;								// reset
 		}
@@ -2484,5 +2470,5 @@
 	| aggregate_key attribute_list_opt TYPEGENname		// unqualified type name
 		{
-			typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname ); // create typedef
+			typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname, "aggregate_type: 3" );
 			forall = false;								// reset
 		}
@@ -2505,5 +2491,5 @@
 	aggregate_key attribute_list_opt identifier
 		{
-			typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname );
+			typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname, "aggregate_type_nobody" );
 			forall = false;								// reset
 			$$ = DeclarationNode::newAggregate( $1, $3, nullptr, nullptr, false )->addQualifiers( $2 );
@@ -2680,10 +2666,11 @@
 	ENUM attribute_list_opt '{' enumerator_list comma_opt '}'
 		{ $$ = DeclarationNode::newEnum( nullptr, $4, true, false )->addQualifiers( $2 ); }
+	| ENUM attribute_list_opt '!' '{' enumerator_list comma_opt '}'	// invalid syntax rule
+		{ SemanticError( yylloc, "syntax error, hiding '!' the enumerator names of an anonymous enumeration means the names are inaccessible." ); $$ = nullptr; }
 	| ENUM attribute_list_opt identifier
-		{ typedefTable.makeTypedef( *$3 ); }
+		{ typedefTable.makeTypedef( *$3, "enum_type 1" ); }
 	  hide_opt '{' enumerator_list comma_opt '}'
 		{ $$ = DeclarationNode::newEnum( $3, $7, true, false, nullptr, $5 )->addQualifiers( $2 ); }
-	| ENUM attribute_list_opt typedef_name				// unqualified type name
-	  hide_opt '{' enumerator_list comma_opt '}'
+	| ENUM attribute_list_opt typedef_name hide_opt '{' enumerator_list comma_opt '}' // unqualified type name
 		{ $$ = DeclarationNode::newEnum( $3->name, $6, true, false, nullptr, $4 )->addQualifiers( $2 ); }
 	| ENUM '(' cfa_abstract_parameter_declaration ')' attribute_list_opt '{' enumerator_list comma_opt '}'
@@ -2694,4 +2681,12 @@
 			$$ = DeclarationNode::newEnum( nullptr, $7, true, true, $3 )->addQualifiers( $5 );
 		}
+	| ENUM '(' cfa_abstract_parameter_declaration ')' attribute_list_opt '!' '{' enumerator_list comma_opt '}' // unqualified type name
+		{ SemanticError( yylloc, "syntax error, hiding '!' the enumerator names of an anonymous enumeration means the names are inaccessible." ); $$ = nullptr; }
+	| ENUM '(' ')' attribute_list_opt '{' enumerator_list comma_opt '}'
+		{
+			$$ = DeclarationNode::newEnum( nullptr, $6, true, true )->addQualifiers( $4 );
+		}
+	| ENUM '(' ')' attribute_list_opt '!' '{' enumerator_list comma_opt '}'	// invalid syntax rule
+		{ SemanticError( yylloc, "syntax error, hiding '!' the enumerator names of an anonymous enumeration means the names are inaccessible." ); $$ = nullptr; }
 	| ENUM '(' cfa_abstract_parameter_declaration ')' attribute_list_opt identifier attribute_list_opt
 		{
@@ -2699,5 +2694,5 @@
 				SemanticError( yylloc, "syntax error, storage-class and CV qualifiers are not meaningful for enumeration constants, which are const." );
 			}
-			typedefTable.makeTypedef( *$6 );
+			typedefTable.makeTypedef( *$6, "enum_type 2" );
 		}
 	  hide_opt '{' enumerator_list comma_opt '}'
@@ -2705,8 +2700,15 @@
 			$$ = DeclarationNode::newEnum( $6, $11, true, true, $3, $9 )->addQualifiers( $5 )->addQualifiers( $7 );
 		}
-	| ENUM '(' cfa_abstract_parameter_declaration ')' attribute_list_opt typedef_name attribute_list_opt
-	  hide_opt '{' enumerator_list comma_opt '}'
+	| ENUM '(' ')' attribute_list_opt identifier attribute_list_opt hide_opt '{' enumerator_list comma_opt '}'
+		{
+			$$ = DeclarationNode::newEnum( $5, $9, true, true, nullptr, $7 )->addQualifiers( $4 )->addQualifiers( $6 );
+		}
+	| ENUM '(' cfa_abstract_parameter_declaration ')' attribute_list_opt typedef_name attribute_list_opt hide_opt '{' enumerator_list comma_opt '}'
 		{
 			$$ = DeclarationNode::newEnum( $6->name, $10, true, true, $3, $8 )->addQualifiers( $5 )->addQualifiers( $7 );
+		}
+	| ENUM '(' ')' attribute_list_opt typedef_name attribute_list_opt hide_opt '{' enumerator_list comma_opt '}'
+		{
+			$$ = DeclarationNode::newEnum( $5->name, $9, true, true, nullptr, $7 )->addQualifiers( $4 )->addQualifiers( $6 );
 		}
 	| enum_type_nobody
@@ -2722,7 +2724,13 @@
 enum_type_nobody:										// enum - {...}
 	ENUM attribute_list_opt identifier
-		{ typedefTable.makeTypedef( *$3 ); $$ = DeclarationNode::newEnum( $3, nullptr, false, false )->addQualifiers( $2 ); }
+		{
+			typedefTable.makeTypedef( *$3, "enum_type_nobody 1" );
+			$$ = DeclarationNode::newEnum( $3, nullptr, false, false )->addQualifiers( $2 );
+		}
 	| ENUM attribute_list_opt type_name
-		{ typedefTable.makeTypedef( *$3->type->symbolic.name );	$$ = DeclarationNode::newEnum( $3->type->symbolic.name, nullptr, false, false )->addQualifiers( $2 ); }
+		{
+			typedefTable.makeTypedef( *$3->type->symbolic.name, "enum_type_nobody 2" );
+			$$ = DeclarationNode::newEnum( $3->type->symbolic.name, nullptr, false, false )->addQualifiers( $2 );
+		}
 	;
 
@@ -2792,5 +2800,5 @@
 		{ $$ = nullptr; }
 	| parameter_list
-	| parameter_list pop ',' push ELLIPSIS
+	| parameter_list ',' ELLIPSIS
 		{ $$ = $1->addVarArgs(); }
 	;
@@ -2799,8 +2807,8 @@
 	abstract_parameter_declaration
 	| parameter_declaration
-	| parameter_list pop ',' push abstract_parameter_declaration
-		{ $$ = $1->appendList( $5 ); }
-	| parameter_list pop ',' push parameter_declaration
-		{ $$ = $1->appendList( $5 ); }
+	| parameter_list ',' abstract_parameter_declaration
+		{ $$ = $1->appendList( $3 ); }
+	| parameter_list ',' parameter_declaration
+		{ $$ = $1->appendList( $3 ); }
 	;
 
@@ -2969,5 +2977,5 @@
 	type_class identifier_or_type_name
 		{
-			typedefTable.addToScope( *$2, TYPEDEFname, "9" );
+			typedefTable.addToScope( *$2, TYPEDEFname, "type_parameter 1" );
 			if ( $1 == ast::TypeDecl::Otype ) { SemanticError( yylloc, "otype keyword is deprecated, use T " ); }
 			if ( $1 == ast::TypeDecl::Dtype ) { SemanticError( yylloc, "dtype keyword is deprecated, use T &" ); }
@@ -2977,10 +2985,10 @@
 		{ $$ = DeclarationNode::newTypeParam( $1, $2 )->addTypeInitializer( $4 )->addAssertions( $5 ); }
 	| identifier_or_type_name new_type_class
-		{ typedefTable.addToScope( *$1, TYPEDEFname, "9" ); }
+		{ typedefTable.addToScope( *$1, TYPEDEFname, "type_parameter 2" ); }
 	  type_initializer_opt assertion_list_opt
 		{ $$ = DeclarationNode::newTypeParam( $2, $1 )->addTypeInitializer( $4 )->addAssertions( $5 ); }
 	| '[' identifier_or_type_name ']'
 		{
-			typedefTable.addToScope( *$2, TYPEDIMname, "9" );
+			typedefTable.addToScope( *$2, TYPEDIMname, "type_parameter 3" );
 			$$ = DeclarationNode::newTypeParam( ast::TypeDecl::Dimension, $2 );
 		}
@@ -3064,10 +3072,10 @@
 	identifier_or_type_name
 		{
-			typedefTable.addToEnclosingScope( *$1, TYPEDEFname, "10" );
+			typedefTable.addToEnclosingScope( *$1, TYPEDEFname, "type_declarator_name 1" );
 			$$ = DeclarationNode::newTypeDecl( $1, nullptr );
 		}
 	| identifier_or_type_name '(' type_parameter_list ')'
 		{
-			typedefTable.addToEnclosingScope( *$1, TYPEGENname, "11" );
+			typedefTable.addToEnclosingScope( *$1, TYPEGENname, "type_declarator_name 2" );
 			$$ = DeclarationNode::newTypeDecl( $1, $3 );
 		}
@@ -3163,13 +3171,13 @@
 	| IDENTIFIER IDENTIFIER
 		{ IdentifierBeforeIdentifier( *$1.str, *$2.str, " declaration" ); $$ = nullptr; }
-	| IDENTIFIER type_qualifier							// invalid syntax rules
+	| IDENTIFIER type_qualifier							// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "type qualifier" ); $$ = nullptr; }
-	| IDENTIFIER storage_class							// invalid syntax rules
+	| IDENTIFIER storage_class							// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "storage class" ); $$ = nullptr; }
-	| IDENTIFIER basic_type_name						// invalid syntax rules
+	| IDENTIFIER basic_type_name						// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
-	| IDENTIFIER TYPEDEFname							// invalid syntax rules
+	| IDENTIFIER TYPEDEFname							// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
-	| IDENTIFIER TYPEGENname							// invalid syntax rules
+	| IDENTIFIER TYPEGENname							// invalid syntax rule
 		{ IdentifierBeforeType( *$1.str, "type" ); $$ = nullptr; }
 	| external_function_definition
@@ -3458,8 +3466,8 @@
 
 variable_function:
-	'(' variable_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $2->addParamList( $6 ); }
-	| '(' attribute_list variable_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $3->addQualifiers( $2 )->addParamList( $7 ); }
+	'(' variable_ptr ')' '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $2->addParamList( $5 ); }
+	| '(' attribute_list variable_ptr ')' '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $3->addQualifiers( $2 )->addParamList( $6 ); }
 	| '(' variable_function ')'							// redundant parenthesis
 		{ $$ = $2; }
@@ -3481,10 +3489,10 @@
 
 function_no_ptr:
-	paren_identifier '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $1->addParamList( $4 ); }
-	| '(' function_ptr ')' '(' push parameter_type_list_opt pop ')'
-		{ $$ = $2->addParamList( $6 ); }
-	| '(' attribute_list function_ptr ')' '(' push parameter_type_list_opt pop ')'
-		{ $$ = $3->addQualifiers( $2 )->addParamList( $7 ); }
+	paren_identifier '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $1->addParamList( $3 ); }
+	| '(' function_ptr ')' '(' parameter_type_list_opt ')'
+		{ $$ = $2->addParamList( $5 ); }
+	| '(' attribute_list function_ptr ')' '(' parameter_type_list_opt ')'
+		{ $$ = $3->addQualifiers( $2 )->addParamList( $6 ); }
 	| '(' function_no_ptr ')'							// redundant parenthesis
 		{ $$ = $2; }
@@ -3535,8 +3543,8 @@
 	paren_identifier '(' identifier_list ')'			// function_declarator handles empty parameter
 		{ $$ = $1->addIdList( $3 ); }
-	| '(' KR_function_ptr ')' '(' push parameter_type_list_opt pop ')'
-		{ $$ = $2->addParamList( $6 ); }
-	| '(' attribute_list KR_function_ptr ')' '(' push parameter_type_list_opt pop ')'
-		{ $$ = $3->addQualifiers( $2 )->addParamList( $7 ); }
+	| '(' KR_function_ptr ')' '(' parameter_type_list_opt ')'
+		{ $$ = $2->addParamList( $5 ); }
+	| '(' attribute_list KR_function_ptr ')' '(' parameter_type_list_opt ')'
+		{ $$ = $3->addQualifiers( $2 )->addParamList( $6 ); }
 	| '(' KR_function_no_ptr ')'						// redundant parenthesis
 		{ $$ = $2; }
@@ -3582,5 +3590,5 @@
 		{
 			// hide type name in enclosing scope by variable name
-			typedefTable.addToEnclosingScope( *$1->name, IDENTIFIER, "ID" );
+			typedefTable.addToEnclosingScope( *$1->name, IDENTIFIER, "paren_type" );
 		}
 	| '(' paren_type ')'
@@ -3627,8 +3635,8 @@
 
 variable_type_function:
-	'(' variable_type_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $2->addParamList( $6 ); }
-	| '(' attribute_list variable_type_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $3->addQualifiers( $2 )->addParamList( $7 ); }
+	'(' variable_type_ptr ')' '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $2->addParamList( $5 ); }
+	| '(' attribute_list variable_type_ptr ')' '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $3->addQualifiers( $2 )->addParamList( $6 ); }
 	| '(' variable_type_function ')'					// redundant parenthesis
 		{ $$ = $2; }
@@ -3650,10 +3658,10 @@
 
 function_type_no_ptr:
-	paren_type '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $1->addParamList( $4 ); }
-	| '(' function_type_ptr ')' '(' push parameter_type_list_opt pop ')'
-		{ $$ = $2->addParamList( $6 ); }
-	| '(' attribute_list function_type_ptr ')' '(' push parameter_type_list_opt pop ')'
-		{ $$ = $3->addQualifiers( $2 )->addParamList( $7 ); }
+	paren_type '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $1->addParamList( $3 ); }
+	| '(' function_type_ptr ')' '(' parameter_type_list_opt ')'
+		{ $$ = $2->addParamList( $5 ); }
+	| '(' attribute_list function_type_ptr ')' '(' parameter_type_list_opt ')'
+		{ $$ = $3->addQualifiers( $2 )->addParamList( $6 ); }
 	| '(' function_type_no_ptr ')'						// redundant parenthesis
 		{ $$ = $2; }
@@ -3726,8 +3734,8 @@
 
 identifier_parameter_function:
-	paren_identifier '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $1->addParamList( $4 ); }
-	| '(' identifier_parameter_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $2->addParamList( $6 ); }
+	paren_identifier '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $1->addParamList( $3 ); }
+	| '(' identifier_parameter_ptr ')' '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $2->addParamList( $5 ); }
 	| '(' identifier_parameter_function ')'				// redundant parenthesis
 		{ $$ = $2; }
@@ -3779,8 +3787,8 @@
 
 type_parameter_function:
-	typedef_name '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $1->addParamList( $4 ); }
-	| '(' type_parameter_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $2->addParamList( $6 ); }
+	typedef_name '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $1->addParamList( $3 ); }
+	| '(' type_parameter_ptr ')' '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $2->addParamList( $5 ); }
 	;
 
@@ -3829,8 +3837,8 @@
 
 abstract_function:
-	'(' push parameter_type_list_opt pop ')'			// empty parameter list OBSOLESCENT (see 3)
-		{ $$ = DeclarationNode::newFunction( nullptr, nullptr, $3, nullptr ); }
-	| '(' abstract_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $2->addParamList( $6 ); }
+	'(' parameter_type_list_opt ')'			// empty parameter list OBSOLESCENT (see 3)
+		{ $$ = DeclarationNode::newFunction( nullptr, nullptr, $2, nullptr ); }
+	| '(' abstract_ptr ')' '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $2->addParamList( $5 ); }
 	| '(' abstract_function ')'							// redundant parenthesis
 		{ $$ = $2; }
@@ -3952,8 +3960,8 @@
 
 abstract_parameter_function:
-	'(' push parameter_type_list_opt pop ')'			// empty parameter list OBSOLESCENT (see 3)
-		{ $$ = DeclarationNode::newFunction( nullptr, nullptr, $3, nullptr ); }
-	| '(' abstract_parameter_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $2->addParamList( $6 ); }
+	'(' parameter_type_list_opt ')'			// empty parameter list OBSOLESCENT (see 3)
+		{ $$ = DeclarationNode::newFunction( nullptr, nullptr, $2, nullptr ); }
+	| '(' abstract_parameter_ptr ')' '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $2->addParamList( $5 ); }
 	| '(' abstract_parameter_function ')'				// redundant parenthesis
 		{ $$ = $2; }
@@ -3992,10 +4000,10 @@
 // This pattern parses a declaration of an abstract variable, but does not allow "int ()" for a function pointer.
 //
-//		struct S {
-//          int;
-//          int *;
-//          int [10];
-//          int (*)();
-//      };
+//   struct S {
+//       int;
+//       int *;
+//       int [10];
+//       int (*)();
+//   };
 
 variable_abstract_declarator:
@@ -4031,6 +4039,6 @@
 
 variable_abstract_function:
-	'(' variable_abstract_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
-		{ $$ = $2->addParamList( $6 ); }
+	'(' variable_abstract_ptr ')' '(' parameter_type_list_opt ')' // empty parameter list OBSOLESCENT (see 3)
+		{ $$ = $2->addParamList( $5 ); }
 	| '(' variable_abstract_function ')'				// redundant parenthesis
 		{ $$ = $2; }
Index: src/ResolvExpr/CommonType.cc
===================================================================
--- src/ResolvExpr/CommonType.cc	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/ResolvExpr/CommonType.cc	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -696,17 +696,4 @@
 		void postvisit( const ast::BasicType * basic ) {
 			if ( auto basic2 = dynamic_cast< const ast::BasicType * >( type2 ) ) {
-				#warning remove casts when `commonTypes` moved to new AST
-				
-				/*
-				ast::BasicType::Kind kind = (ast::BasicType::Kind)(int)commonTypes[ (BasicType::Kind)(int)basic->kind ][ (BasicType::Kind)(int)basic2->kind ];
-				if (
-					( ( kind == basic->kind && basic->qualifiers >= basic2->qualifiers )
-						|| widen.first )
-					&& ( ( kind == basic2->kind && basic->qualifiers <= basic2->qualifiers )
-						|| widen.second )
-				) {
-					result = new ast::BasicType{ kind, basic->qualifiers | basic2->qualifiers };
-				}
-				*/
 				ast::BasicType::Kind kind;
 				if (basic->kind != basic2->kind && !widen.first && !widen.second) return;
@@ -719,28 +706,17 @@
 					result = new ast::BasicType{ kind, basic->qualifiers | basic2->qualifiers };
 				}
-				
 			} else if (
 				dynamic_cast< const ast::ZeroType * >( type2 )
 				|| dynamic_cast< const ast::OneType * >( type2 )
 			) {
-				#warning remove casts when `commonTypes` moved to new AST
-				ast::BasicType::Kind kind = (ast::BasicType::Kind)(int)commonTypes[ (BasicType::Kind)(int)basic->kind ][ (BasicType::Kind)(int)ast::BasicType::SignedInt ];
-				/*
-				if ( // xxx - what does qualifier even do here??
-					( ( basic->qualifiers >= type2->qualifiers )
-						|| widen.first )
-					 && ( ( /* kind != basic->kind && basic->qualifiers <= type2->qualifiers )
-						|| widen.second )
-				) 
-				*/
 				if (widen.second) {
 					result = new ast::BasicType{ basic->kind, basic->qualifiers | type2->qualifiers };
 				}
 			} else if ( const ast::EnumInstType * enumInst = dynamic_cast< const ast::EnumInstType * >( type2 ) ) {
-				#warning remove casts when `commonTypes` moved to new AST
 				const ast::EnumDecl* enumDecl = enumInst->base;
 				if ( enumDecl->base ) {
 					result = enumDecl->base.get();
 				} else {
+					#warning remove casts when `commonTypes` moved to new AST
 					ast::BasicType::Kind kind = (ast::BasicType::Kind)(int)commonTypes[ (BasicType::Kind)(int)basic->kind ][ (BasicType::Kind)(int)ast::BasicType::SignedInt ];
 					if (
@@ -763,5 +739,4 @@
 				auto entry = open.find( *var );
 				if ( entry != open.end() ) {
-				// if (tenv.lookup(*var)) {
 					ast::AssertionSet need, have;
 					if ( ! tenv.bindVar(
Index: src/ResolvExpr/ResolveTypeof.h
===================================================================
--- src/ResolvExpr/ResolveTypeof.h	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/ResolvExpr/ResolveTypeof.h	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -30,4 +30,5 @@
 	Type *resolveTypeof( Type*, const SymTab::Indexer &indexer );
 	const ast::Type * resolveTypeof( const ast::Type *, const ResolveContext & );
+	const ast::Type * fixArrayType( const ast::Type *, const ResolveContext & );
 	const ast::ObjectDecl * fixObjectType( const ast::ObjectDecl * decl , const ResolveContext & );
 	const ast::ObjectDecl * fixObjectInit( const ast::ObjectDecl * decl , const ResolveContext &);
Index: src/ResolvExpr/Unify.cc
===================================================================
--- src/ResolvExpr/Unify.cc	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/ResolvExpr/Unify.cc	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -32,4 +32,5 @@
 #include "AST/Type.hpp"
 #include "AST/TypeEnvironment.hpp"
+#include "Common/Eval.h"            // for eval
 #include "Common/PassVisitor.h"     // for PassVisitor
 #include "CommonType.hpp"           // for commonType
@@ -779,4 +780,125 @@
 	}
 
+	// Unification of Expressions
+	//
+	// Boolean outcome (obvious):  Are they basically spelled the same?
+	// Side effect of binding variables (subtle):  if `sizeof(int)` ===_expr `sizeof(T)` then `int` ===_ty `T`
+	//
+	// Context:  if `float[VAREXPR1]` ===_ty `float[VAREXPR2]` then `VAREXPR1` ===_expr `VAREXPR2`
+	// where the VAREXPR are meant as notational metavariables representing the fact that unification always
+	// sees distinct ast::VariableExpr objects at these positions
+
+	static bool unify( const ast::Expr * e1, const ast::Expr * e2, ast::TypeEnvironment & env,
+		ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
+		WidenMode widen );
+
+	class UnifyExpr final : public ast::WithShortCircuiting {
+		const ast::Expr * e2;
+		ast::TypeEnvironment & tenv;
+		ast::AssertionSet & need;
+		ast::AssertionSet & have;
+		const ast::OpenVarSet & open;
+		WidenMode widen;
+	public:
+		bool result;
+
+	private:
+
+		void tryMatchOnStaticValue( const ast::Expr * e1 ) {
+			Evaluation r1 = eval(e1);
+			Evaluation r2 = eval(e2);
+
+			if ( ! r1.hasKnownValue ) return;
+			if ( ! r2.hasKnownValue ) return;
+
+			if (r1.knownValue != r2.knownValue) return;
+
+			visit_children = false;
+			result = true;
+		}
+
+	public:
+
+		void previsit( const ast::Node * ) { assert(false); }
+
+		void previsit( const ast::Expr * e1 ) {
+			tryMatchOnStaticValue( e1 );
+			visit_children = false;
+		}
+
+		void previsit( const ast::CastExpr * e1 ) {
+			tryMatchOnStaticValue( e1 );
+
+			if (result) {
+				assert (visit_children == false);
+			} else {
+				assert (visit_children == true);
+				visit_children = false;
+
+				auto e2c = dynamic_cast< const ast::CastExpr * >( e2 );
+				if ( ! e2c ) return;
+
+				// inspect casts' target types
+				if ( ! unifyExact(
+					e1->result, e2c->result, tenv, need, have, open, widen ) ) return;
+
+				// inspect casts' inner expressions
+				result = unify( e1->arg, e2c->arg, tenv, need, have, open, widen );
+			}
+		}
+
+		void previsit( const ast::VariableExpr * e1 ) {
+			tryMatchOnStaticValue( e1 );
+
+			if (result) {
+				assert (visit_children == false);
+			} else {
+				assert (visit_children == true);
+				visit_children = false;
+
+				auto e2v = dynamic_cast< const ast::VariableExpr * >( e2 );
+				if ( ! e2v ) return;
+
+				assert(e1->var);
+				assert(e2v->var);
+
+				// conservative: variable exprs match if their declarations are represented by the same C++ AST object
+				result = (e1->var == e2v->var);
+			}
+		}
+
+		void previsit( const ast::SizeofExpr * e1 ) {
+			tryMatchOnStaticValue( e1 );
+
+			if (result) {
+				assert (visit_children == false);
+			} else {
+				assert (visit_children == true);
+				visit_children = false;
+
+				auto e2so = dynamic_cast< const ast::SizeofExpr * >( e2 );
+				if ( ! e2so ) return;
+
+				assert((e1->type != nullptr) ^ (e1->expr != nullptr));
+				assert((e2so->type != nullptr) ^ (e2so->expr != nullptr));
+				if ( ! (e1->type && e2so->type) )  return;
+
+				// expression unification calls type unification (mutual recursion)
+				result = unifyExact( e1->type, e2so->type, tenv, need, have, open, widen );
+			}
+		}
+
+		UnifyExpr( const ast::Expr * e2, ast::TypeEnvironment & env, ast::AssertionSet & need,
+			ast::AssertionSet & have, const ast::OpenVarSet & open, WidenMode widen )
+		: e2( e2 ), tenv(env), need(need), have(have), open(open), widen(widen), result(false) {}
+	};
+
+	static bool unify( const ast::Expr * e1, const ast::Expr * e2, ast::TypeEnvironment & env,
+		ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
+		WidenMode widen ) {
+		assert( e1 && e2 );
+		return ast::Pass<UnifyExpr>::read( e1, e2, env, need, have, open, widen );
+	}
+
 	class Unify_new final : public ast::WithShortCircuiting {
 		const ast::Type * type2;
@@ -820,16 +942,12 @@
 			if ( ! array2 ) return;
 
-			// to unify, array types must both be VLA or both not VLA and both must have a
-			// dimension expression or not have a dimension
 			if ( array->isVarLen != array2->isVarLen ) return;
-			if ( ! array->isVarLen && ! array2->isVarLen
-					&& array->dimension && array2->dimension ) {
-				auto ce1 = array->dimension.as< ast::ConstantExpr >();
-				auto ce2 = array2->dimension.as< ast::ConstantExpr >();
-
-				// see C11 Reference Manual 6.7.6.2.6
-				// two array types with size specifiers that are integer constant expressions are
-				// compatible if both size specifiers have the same constant value
-				if ( ce1 && ce2 && ce1->intValue() != ce2->intValue() ) return;
+			if ( (array->dimension != nullptr) != (array2->dimension != nullptr) ) return;
+
+			if ( array->dimension ) {
+				assert( array2->dimension );
+				// type unification calls expression unification (mutual recursion)
+				if ( ! unify(array->dimension, array2->dimension,
+				    tenv, need, have, open, widen) ) return;
 			}
 
@@ -1180,23 +1298,7 @@
 		auto var1 = dynamic_cast< const ast::TypeInstType * >( type1 );
 		auto var2 = dynamic_cast< const ast::TypeInstType * >( type2 );
-		ast::OpenVarSet::const_iterator
-			entry1 = var1 ? open.find( *var1 ) : open.end(),
-			entry2 = var2 ? open.find( *var2 ) : open.end();
-		// bool isopen1 = entry1 != open.end();
-		// bool isopen2 = entry2 != open.end();
 		bool isopen1 = var1 && env.lookup(*var1);
 		bool isopen2 = var2 && env.lookup(*var2);
 
-		/*
-		if ( isopen1 && isopen2 ) {
-			if ( entry1->second.kind != entry2->second.kind ) return false;
-			return env.bindVarToVar(
-				var1, var2, ast::TypeData{ entry1->second, entry2->second }, need, have,
-				open, widen );
-		} else if ( isopen1 ) {
-			return env.bindVar( var1, type2, entry1->second, need, have, open, widen );
-		} else if ( isopen2 ) {
-			return env.bindVar( var2, type1, entry2->second, need, have, open, widen, symtab );
-		} */
 		if ( isopen1 && isopen2 ) {
 			if ( var1->base->kind != var2->base->kind ) return false;
@@ -1208,9 +1310,8 @@
 		} else if ( isopen2 ) {
 			return env.bindVar( var2, type1, ast::TypeData{var2->base}, need, have, open, widen );
-		}else {
+		} else {
 			return ast::Pass<Unify_new>::read(
 				type1, type2, env, need, have, open, widen );
 		}
-		
 	}
 
Index: src/SymTab/FixFunction.cc
===================================================================
--- src/SymTab/FixFunction.cc	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/SymTab/FixFunction.cc	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -109,6 +109,8 @@
 
 		const ast::DeclWithType * postvisit( const ast::FunctionDecl * func ) {
-			return new ast::ObjectDecl{ 
-				func->location, func->name, new ast::PointerType{ func->type }, nullptr, 
+			// Cannot handle cases with asserions.
+			assert( func->assertions.empty() );
+			return new ast::ObjectDecl{
+				func->location, func->name, new ast::PointerType( func->type ), nullptr,
 				func->storage, func->linkage, nullptr, copy( func->attributes ) };
 		}
@@ -117,6 +119,6 @@
 
 		const ast::Type * postvisit( const ast::ArrayType * array ) {
-			return new ast::PointerType{ 
-				array->base, array->dimension, array->isVarLen, array->isStatic, 
+			return new ast::PointerType{
+				array->base, array->dimension, array->isVarLen, array->isStatic,
 				array->qualifiers };
 		}
Index: src/SymTab/GenImplicitCall.cpp
===================================================================
--- src/SymTab/GenImplicitCall.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/SymTab/GenImplicitCall.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -16,4 +16,5 @@
 #include "GenImplicitCall.hpp"
 
+#include "AST/Copy.hpp"                  // for deepCopy
 #include "AST/Decl.hpp"                  // for ObjectDecl
 #include "AST/Expr.hpp"                  // for ConstantExpr, UntypedExpr,...
@@ -115,8 +116,9 @@
 	std::string cmp, update;
 
+	const ast::Expr * dimension = deepCopy( array->dimension );
 	if ( forward ) {
 		// generate: for ( int i = 0; i < N; ++i )
 		begin = ast::ConstantExpr::from_int( loc, 0 );
-		end = array->dimension;
+		end = dimension;
 		cmp = "?<?";
 		update = "++?";
@@ -124,5 +126,5 @@
 		// generate: for ( int i = N-1; i >= 0; --i )
 		begin = ast::UntypedExpr::createCall( loc, "?-?",
-			{ array->dimension, ast::ConstantExpr::from_int( loc, 1 ) } );
+			{ dimension, ast::ConstantExpr::from_int( loc, 1 ) } );
 		end = ast::ConstantExpr::from_int( loc, 0 );
 		cmp = "?>=?";
Index: src/Validate/Autogen.cpp
===================================================================
--- src/Validate/Autogen.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Validate/Autogen.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -532,8 +532,20 @@
 		)
 	);
-	return genImplicitCall(
+	auto stmt = genImplicitCall(
 		srcParam, dstSelect, location, func->name,
 		field, direction
 	);
+	// This could return the above directly, except the generated code is
+	// built using the structure's members and that means all the scoped
+	// names (the forall parameters) are incorrect. This corrects them.
+	if ( stmt && !decl->params.empty() ) {
+		ast::DeclReplacer::TypeMap oldToNew;
+		for ( auto pair : group_iterate( decl->params, func->type_params ) ) {
+			oldToNew.emplace( std::get<0>(pair), std::get<1>(pair) );
+		}
+		auto node = ast::DeclReplacer::replace( stmt, oldToNew );
+		stmt = strict_dynamic_cast<const ast::Stmt *>( node );
+	}
+	return stmt;
 }
 
Index: src/Validate/FixQualifiedTypes.cpp
===================================================================
--- src/Validate/FixQualifiedTypes.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Validate/FixQualifiedTypes.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -89,26 +89,25 @@
 	}
 
-	ast::Expr const * postvisit( ast::QualifiedNameExpr const * t) {
+	ast::Expr const * postvisit( ast::QualifiedNameExpr const * t ) {
 		assert( location );
-		if ( t->type_decl ) {
-        	auto enumName = t->type_decl->name;
-        	const ast::EnumDecl * enumDecl = symtab.lookupEnum( enumName );
-			for ( ast::ptr<ast::Decl> const & member : enumDecl->members ) {
-				if ( auto memberAsObj = member.as<ast::ObjectDecl>() ) {
-					if ( memberAsObj->name == t->name ) {
-						return new ast::VariableExpr( t->location, memberAsObj );
-					}
-				} else {
-					assertf( false, "unhandled qualified child type");
+		if ( !t->type_decl ) return t;
+
+		auto enumName = t->type_decl->name;
+		const ast::EnumDecl * enumDecl = symtab.lookupEnum( enumName );
+		for ( ast::ptr<ast::Decl> const & member : enumDecl->members ) {
+			if ( auto memberAsObj = member.as<ast::ObjectDecl>() ) {
+				if ( memberAsObj->name == t->name ) {
+					return new ast::VariableExpr( t->location, memberAsObj );
 				}
+			} else {
+				assertf( false, "unhandled qualified child type" );
 			}
+		}
 
-        	auto var = new ast::ObjectDecl( t->location, t->name,
-			new ast::EnumInstType(enumDecl, ast::CV::Const), nullptr, {}, ast::Linkage::Cforall );
-			var->mangleName = Mangle::mangle( var );
-			return new ast::VariableExpr( t->location, var );
-        }
-
-		return t;
+		auto var = new ast::ObjectDecl( t->location, t->name,
+			new ast::EnumInstType( enumDecl, ast::CV::Const ),
+			nullptr, {}, ast::Linkage::Cforall );
+		var->mangleName = Mangle::mangle( var );
+		return new ast::VariableExpr( t->location, var );
 	}
 
Index: src/Validate/ForallPointerDecay.cpp
===================================================================
--- src/Validate/ForallPointerDecay.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Validate/ForallPointerDecay.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -23,7 +23,6 @@
 #include "Common/CodeLocation.h"
 #include "Common/ToString.hpp"
+#include "Common/utility.h"
 #include "SymTab/FixFunction.h"
-
-#include "AST/Print.hpp"
 
 namespace Validate {
@@ -51,11 +50,14 @@
 }
 
-template<typename T>
-void append( std::vector<T> & dst, std::vector<T> & src ) {
-	dst.reserve( dst.size() + src.size() );
-	for ( auto el : src ) {
-		dst.emplace_back( std::move( el ) );
-	}
-	src.clear();
+ast::FunctionDecl * updateAssertions( ast::FunctionDecl * decl ) {
+	auto type = ast::mutate( decl->type.get() );
+	type->assertions.clear();
+	type->assertions.reserve( decl->assertions.size() );
+	for ( auto & assertion : decl->assertions ) {
+		type->assertions.emplace_back(
+			new ast::VariableExpr( decl->location, assertion ) );
+	}
+	decl->type = type;
+	return decl;
 }
 
@@ -96,5 +98,5 @@
 					decl->get_type() ) ) {
 				auto moreAsserts = expandTrait( traitInst );
-				append( assertions, moreAsserts );
+				splice( assertions, moreAsserts );
 			} else {
 				assertions.push_back( decl );
@@ -108,4 +110,5 @@
 	static TypeDeclVec expandTypeDecls( const TypeDeclVec & old ) {
 		TypeDeclVec typeDecls;
+		typeDecls.reserve( old.size() );
 		for ( const ast::TypeDecl * typeDecl : old ) {
 			typeDecls.push_back( ast::mutate_field( typeDecl,
@@ -123,12 +126,5 @@
 		mut->assertions = expandAssertions( decl->assertions );
 		// Update the assertion list on the type as well.
-		auto mutType = ast::mutate( mut->type.get() );
-		mutType->assertions.clear();
-		for ( auto & assertion : mut->assertions ) {
-			mutType->assertions.emplace_back(
-				new ast::VariableExpr( mut->location, assertion ) );
-		}
-		mut->type = mutType;
-		return mut;
+		return updateAssertions( mut );
 	}
 
@@ -154,4 +150,5 @@
 		const std::vector<ast::ptr<ast::DeclWithType>> & assertions ) {
 	std::vector<ast::ptr<ast::DeclWithType>> ret;
+	ret.reserve( assertions.size() );
 	for ( const auto & assn : assertions ) {
 		bool isVoid = false;
@@ -187,4 +184,11 @@
 	}
 
+	const ast::FunctionDecl * postvisit( const ast::FunctionDecl * decl ) {
+		if ( decl->assertions.empty() ) {
+			return decl;
+		}
+		return updateAssertions( mutate( decl ) );
+	}
+
 	const ast::StructDecl * previsit( const ast::StructDecl * decl ) {
 		if ( decl->params.empty() ) {
@@ -204,14 +208,12 @@
 };
 
-struct OberatorChecker final {
+struct OperatorChecker final {
 	void previsit( const ast::ObjectDecl * obj ) {
-		if ( CodeGen::isOperator( obj->name ) ) {
-			auto type = obj->type->stripDeclarator();
-			if ( ! dynamic_cast< const ast::FunctionType * >( type ) ) {
-				SemanticError( obj->location,
-					toCString( "operator ", obj->name.c_str(), " is not "
-					"a function or function pointer." ) );
-			}
-		}
+		if ( !CodeGen::isOperator( obj->name ) ) return;
+		auto type = obj->type->stripDeclarator();
+		if ( dynamic_cast< const ast::FunctionType * >( type ) ) return;
+		SemanticError( obj->location,
+			toCString( "operator ", obj->name.c_str(),
+			" is not a function or function pointer." ) );
 	}
 };
@@ -234,5 +236,8 @@
 	ast::Pass<TraitExpander>::run( transUnit );
 	ast::Pass<AssertionFunctionFixer>::run( transUnit );
-	ast::Pass<OberatorChecker>::run( transUnit );
+	ast::Pass<OperatorChecker>::run( transUnit );
+}
+
+void fixUniqueIds( ast::TranslationUnit & transUnit ) {
 	ast::Pass<UniqueFixCore>::run( transUnit );
 }
Index: src/Validate/ForallPointerDecay.hpp
===================================================================
--- src/Validate/ForallPointerDecay.hpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Validate/ForallPointerDecay.hpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -27,10 +27,13 @@
 
 /// Cleans up assertion lists and expands traits.
-/// Also checks that operator names are used properly on functions and
-/// assigns unique IDs. This is a "legacy" pass.
+/// Also checks that operator names are used properly on functions.
+/// This is a "legacy" pass.
+/// Must happen before auto-gen routines are added.
+void decayForallPointers( ast::TranslationUnit & transUnit );
+
+/// Sets uniqueIds on any declarations that do not have one set.
 /// Must be after implement concurrent keywords; because uniqueIds must be
 /// set on declaration before resolution.
-/// Must happen before auto-gen routines are added.
-void decayForallPointers( ast::TranslationUnit & transUnit );
+void fixUniqueIds( ast::TranslationUnit & transUnit );
 
 /// Expand all traits in an assertion list.
Index: src/Validate/GenericParameter.cpp
===================================================================
--- src/Validate/GenericParameter.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Validate/GenericParameter.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -16,5 +16,4 @@
 #include "GenericParameter.hpp"
 
-#include "AST/Copy.hpp"
 #include "AST/Decl.hpp"
 #include "AST/Expr.hpp"
@@ -165,5 +164,6 @@
 
 struct TranslateDimensionCore :
-		public WithNoIdSymbolTable, public ast::WithGuards {
+		public WithNoIdSymbolTable, public ast::WithGuards,
+		public ast::WithVisitorRef<TranslateDimensionCore> {
 
 	// SUIT: Struct- or Union- InstType
@@ -190,4 +190,7 @@
 
 	const ast::TypeDecl * postvisit( const ast::TypeDecl * decl );
+	const ast::Type * postvisit( const ast::FunctionType * type );
+	const ast::Type * postvisit( const ast::TypeInstType * type );
+
 	const ast::Expr * postvisit( const ast::DimensionExpr * expr );
 	const ast::Expr * postvisit( const ast::Expr * expr );
@@ -195,4 +198,5 @@
 };
 
+// Declaration of type variable: forall( [N] )  ->  forall( N & | sized( N ) )
 const ast::TypeDecl * TranslateDimensionCore::postvisit(
 		const ast::TypeDecl * decl ) {
@@ -206,4 +210,24 @@
 	}
 	return decl;
+}
+
+// Makes postvisit( TypeInstType ) get called on the entries of the function declaration's type's forall list.
+// Pass.impl.hpp's visit( FunctionType ) does not consider the forall entries to be child nodes.
+// Workaround is: during the current TranslateDimension pass, manually visit down there.
+const ast::Type * TranslateDimensionCore::postvisit(
+		const ast::FunctionType * type ) {
+	visitor->maybe_accept( type, &ast::FunctionType::forall );
+	return type;
+}
+
+// Use of type variable, assuming `forall( [N] )` in scope:  void (*)( foo( /*dimension*/ N ) & )  ->  void (*)( foo( /*dtype*/ N ) & )
+const ast::Type * TranslateDimensionCore::postvisit(
+		const ast::TypeInstType * type ) {
+	if ( type->kind == ast::TypeDecl::Dimension ) {
+		auto mutType = ast::mutate( type );
+		mutType->kind = ast::TypeDecl::Dtype;
+		return mutType;
+	}
+	return type;
 }
 
Index: src/Validate/LinkReferenceToTypes.cpp
===================================================================
--- src/Validate/LinkReferenceToTypes.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Validate/LinkReferenceToTypes.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -10,6 +10,6 @@
 // Created On       : Thr Apr 21 11:41:00 2022
 // Last Modified By : Andrew Beach
-// Last Modified On : Tue Sep 20 16:17:00 2022
-// Update Count     : 2
+// Last Modified On : Fri Jul 14  9:19:00 2023
+// Update Count     : 3
 //
 
@@ -27,4 +27,5 @@
 struct LinkTypesCore : public WithNoIdSymbolTable,
 		public ast::WithCodeLocation,
+		public ast::WithDeclsToAdd<>,
 		public ast::WithGuards,
 		public ast::WithShortCircuiting,
@@ -63,5 +64,32 @@
 	template<typename AggrDecl>
 	AggrDecl const * renameGenericParams( AggrDecl const * decl );
+
+	// This cluster is used to add declarations (before) but outside of
+	// any "namespaces" which would qualify the names.
+	bool inNamespace = false;
+	std::list<ast::ptr<ast::Decl>> declsToAddOutside;
+	/// The "leaveNamespace" is handled by guard.
+	void enterNamespace();
+	/// Puts the decl on the back of declsToAddAfter once traversal is
+	/// outside of any namespaces.
+	void addDeclAfterOutside( ast::Decl const * );
 };
+
+void LinkTypesCore::enterNamespace() {
+	if ( inNamespace ) return;
+	inNamespace = true;
+	GuardAction( [this](){
+		inNamespace = false;
+		declsToAddAfter.splice( declsToAddAfter.begin(), declsToAddOutside );
+	} );
+}
+
+void LinkTypesCore::addDeclAfterOutside( ast::Decl const * decl ) {
+	if ( inNamespace ) {
+		declsToAddOutside.emplace_back( decl );
+	} else {
+		declsToAddAfter.emplace_back( decl );
+	}
+}
 
 ast::TypeInstType const * LinkTypesCore::postvisit( ast::TypeInstType const * type ) {
@@ -81,16 +109,24 @@
 	ast::EnumDecl const * decl = symtab.lookupEnum( type->name );
 	// It's not a semantic error if the enum is not found, just an implicit forward declaration.
-	if ( decl ) {
-		// Just linking in the node.
-		auto mut = ast::mutate( type );
-		mut->base = decl;
-		type = mut;
-	}
-	if ( !decl || !decl->body ) {
-		auto mut = ast::mutate( type );
+	// The unset code location is used to detect imaginary declarations.
+	// (They may never be used for enumerations.)
+	if ( !decl || decl->location.isUnset() ) {
+		assert( location );
+		ast::EnumDecl * mut = new ast::EnumDecl( *location, type->name );
+		mut->linkage = ast::Linkage::Compiler;
+		decl = mut;
+		symtab.addEnum( decl );
+		addDeclAfterOutside( decl );
+	}
+
+	ast::EnumInstType * mut = ast::mutate( type );
+
+	// Just linking in the node.
+	mut->base = decl;
+
+	if ( !decl->body ) {
 		forwardEnums[ mut->name ].push_back( mut );
-		type = mut;
-	}
-	return type;
+	}
+	return mut;
 }
 
@@ -98,16 +134,23 @@
 	ast::StructDecl const * decl = symtab.lookupStruct( type->name );
 	// It's not a semantic error if the struct is not found, just an implicit forward declaration.
-	if ( decl ) {
-		// Just linking in the node.
-		auto mut = ast::mutate( type );
-		mut->base = decl;
-		type = mut;
-	}
-	if ( !decl || !decl->body ) {
-		auto mut = ast::mutate( type );
+	// The unset code location is used to detect imaginary declarations.
+	if ( !decl || decl->location.isUnset() ) {
+		assert( location );
+		ast::StructDecl * mut = new ast::StructDecl( *location, type->name );
+		mut->linkage = ast::Linkage::Compiler;
+		decl = mut;
+		symtab.addStruct( decl );
+		addDeclAfterOutside( decl );
+	}
+
+	ast::StructInstType * mut = ast::mutate( type );
+
+	// Just linking in the node.
+	mut->base = decl;
+
+	if ( !decl->body ) {
 		forwardStructs[ mut->name ].push_back( mut );
-		type = mut;
-	}
-	return type;
+	}
+	return mut;
 }
 
@@ -115,16 +158,23 @@
 	ast::UnionDecl const * decl = symtab.lookupUnion( type->name );
 	// It's not a semantic error if the union is not found, just an implicit forward declaration.
-	if ( decl ) {
-		// Just linking in the node.
-		auto mut = ast::mutate( type );
-		mut->base = decl;
-		type = mut;
-	}
-	if ( !decl || !decl->body ) {
-		auto mut = ast::mutate( type );
+	// The unset code location is used to detect imaginary declarations.
+	if ( !decl || decl->location.isUnset() ) {
+		assert( location );
+		ast::UnionDecl * mut = new ast::UnionDecl( *location, type->name );
+		mut->linkage = ast::Linkage::Compiler;
+		decl = mut;
+		symtab.addUnion( decl );
+		addDeclAfterOutside( decl );
+	}
+
+	ast::UnionInstType * mut = ast::mutate( type );
+
+	// Just linking in the node.
+	mut->base = decl;
+
+	if ( !decl->body ) {
 		forwardUnions[ mut->name ].push_back( mut );
-		type = mut;
-	}
-	return type;
+	}
+	return mut;
 }
 
@@ -228,4 +278,5 @@
 
 ast::StructDecl const * LinkTypesCore::previsit( ast::StructDecl const * decl ) {
+	enterNamespace();
 	return renameGenericParams( decl );
 }
@@ -246,4 +297,5 @@
 
 ast::UnionDecl const * LinkTypesCore::previsit( ast::UnionDecl const * decl ) {
+	enterNamespace();
 	return renameGenericParams( decl );
 }
@@ -264,15 +316,8 @@
 
 ast::TraitDecl const * LinkTypesCore::postvisit( ast::TraitDecl const * decl ) {
-	auto mut = ast::mutate( decl );
-	if ( mut->name == "sized" ) {
-		// "sized" is a special trait - flick the sized status on for the type variable.
-		assertf( mut->params.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", decl->params.size() );
-		ast::TypeDecl * td = mut->params.front().get_and_mutate();
-		td->sized = true;
-	}
-
 	// There is some overlap with code from decayForallPointers,
 	// perhaps reorganization or shared helper functions are called for.
 	// Move assertions from type parameters into the body of the trait.
+	auto mut = ast::mutate( decl );
 	for ( ast::ptr<ast::TypeDecl> const & td : decl->params ) {
 		auto expanded = expandAssertions( td->assertions );
Index: src/Validate/NoIdSymbolTable.hpp
===================================================================
--- src/Validate/NoIdSymbolTable.hpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Validate/NoIdSymbolTable.hpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -46,7 +46,7 @@
 	FORWARD_1( addUnion , const ast::UnionDecl *     )
 	FORWARD_1( addTrait , const ast::TraitDecl *     )
-	FORWARD_1( addStruct, const std::string &        )
-	FORWARD_1( addUnion , const std::string &        )
 	FORWARD_2( addWith  , const std::vector< ast::ptr<ast::Expr> > &, const ast::Decl * )
+	FORWARD_1( addStructId, const std::string & )
+	FORWARD_1( addUnionId , const std::string & )
 
 	FORWARD_1( globalLookupType, const std::string & )
Index: src/Validate/ReplaceTypedef.cpp
===================================================================
--- src/Validate/ReplaceTypedef.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Validate/ReplaceTypedef.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -20,5 +20,4 @@
 #include "Common/ScopedMap.h"
 #include "Common/UniqueName.h"
-#include "Common/utility.h"
 #include "ResolvExpr/Unify.h"
 
@@ -294,5 +293,5 @@
 		aggrDecl->name, ast::Storage::Classes(), type, aggrDecl->linkage );
 	// Add the implicit typedef to the AST.
-	declsToAddBefore.push_back( ast::deepCopy( typeDecl.get() ) );
+	declsToAddAfter.push_back( ast::deepCopy( typeDecl.get() ) );
 	// Shore the name in the map of names.
 	typedefNames[ aggrDecl->name ] =
@@ -316,8 +315,9 @@
 	auto mut = ast::mutate( decl );
 
-	std::vector<ast::ptr<ast::Decl>> members;
+	std::list<ast::ptr<ast::Decl>> members;
 	// Unroll accept_all for decl->members so that implicit typedefs for
 	// nested types are added to the aggregate body.
 	for ( ast::ptr<ast::Decl> const & member : mut->members ) {
+		assert( declsToAddBefore.empty() );
 		assert( declsToAddAfter.empty() );
 		ast::Decl const * newMember = nullptr;
@@ -328,11 +328,12 @@
 		}
 		if ( !declsToAddBefore.empty() ) {
-			for ( auto declToAdd : declsToAddBefore ) {
-				members.push_back( declToAdd );
-			}
-			declsToAddBefore.clear();
+			members.splice( members.end(), declsToAddBefore );
 		}
 		members.push_back( newMember );
-	}
+		if ( !declsToAddAfter.empty() ) {
+			members.splice( members.end(), declsToAddAfter );
+		}
+	}
+	assert( declsToAddBefore.empty() );
 	assert( declsToAddAfter.empty() );
 	if ( !errors.isEmpty() ) { throw errors; }
Index: src/Virtual/VirtualDtor.cpp
===================================================================
--- src/Virtual/VirtualDtor.cpp	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/Virtual/VirtualDtor.cpp	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -141,4 +141,8 @@
         auto structIter = structDecls.find( instType->aggr() );
         if ( structIter == structDecls.end() ) return;
+
+        // If first param not named we need to name it to use it
+        if ( decl->params.at(0)->name == "" )
+            mutate( decl->params.at(0).get() )->name = "__CFA_Virt_Dtor_param";
 
         if ( decl->name == "^?{}") {
Index: src/main.cc
===================================================================
--- src/main.cc	(revision 923558834ec63344a407046c8e08622d03055144)
+++ src/main.cc	(revision 950c58e5affa0dfadc94439fbe02b463ccdfaa3a)
@@ -334,4 +334,5 @@
 		PASS( "Link Reference To Types", Validate::linkReferenceToTypes, transUnit );
 
+		PASS( "Forall Pointer Decay", Validate::decayForallPointers, transUnit );
 		PASS( "Fix Qualified Types", Validate::fixQualifiedTypes, transUnit );
 		PASS( "Eliminate Typedef", Validate::eliminateTypedef, transUnit );
@@ -342,6 +343,5 @@
 		PASS( "Fix Return Statements", InitTweak::fixReturnStatements, transUnit );
 		PASS( "Implement Concurrent Keywords", Concurrency::implementKeywords, transUnit );
-		PASS( "Forall Pointer Decay", Validate::decayForallPointers, transUnit );
-        PASS( "Implement Waituntil", Concurrency::generateWaitUntil, transUnit  );
+		PASS( "Fix Unique Ids", Validate::fixUniqueIds, transUnit );
 		PASS( "Hoist Control Declarations", ControlStruct::hoistControlDecls, transUnit );
 
@@ -370,4 +370,5 @@
 		PASS( "Translate Throws", ControlStruct::translateThrows, transUnit );
 		PASS( "Fix Labels", ControlStruct::fixLabels, transUnit );
+		PASS( "Implement Waituntil", Concurrency::generateWaitUntil, transUnit  );
 		PASS( "Fix Names", CodeGen::fixNames, transUnit );
 		PASS( "Gen Init", InitTweak::genInit, transUnit );
