Index: src/GenPoly/Lvalue.cc
===================================================================
--- src/GenPoly/Lvalue.cc	(revision 6b9b04774733cb2fbec40e4c126e7097d99a9290)
+++ src/GenPoly/Lvalue.cc	(revision 1d776fdacfdd4e1c1e1f7ae9e1b4a6bd650bf24e)
@@ -34,27 +34,24 @@
 #include "InitTweak/InitTweak.h"
 
+#include "Common/PassVisitor.h"
+
+// need to be careful about polymorphic references... e.g. in *? (___operator_deref__A0_1_0_0__Fd0_Pd0_intrinsic___1)
+// the variable is automatically dereferenced and this causes errors dereferencing void*.
+
 namespace GenPoly {
 	namespace {
-		/// Replace uses of lvalue returns with appropriate pointers
-		class Pass1 : public Mutator {
-		  public:
-			typedef Mutator Parent;
-			Pass1();
-
-			// xxx - should this happen to every expression with reference result type? probably just appexpr and varexpr?
-			virtual Type *mutate( ReferenceType * refType );
-			virtual Expression *mutate( VariableExpr *varExpr );
-			virtual Expression *mutate( ApplicationExpr *appExpr );
-			virtual Statement *mutate( ReturnStmt *appExpr );
-			virtual DeclarationWithType *mutate( FunctionDecl *funDecl );
-		  private:
-			DeclarationWithType* retval;
-		};
-
-		/// Replace declarations of lvalue returns with appropriate pointers
-		class Pass2 : public Visitor {
-		  public:
-			virtual void visit( FunctionType *funType );
-		  private:
+		struct ReferenceConversions final {
+			Expression * postmutate( CastExpr * castExpr );
+		};
+
+		/// Intrinsic functions that take reference parameters don't REALLY take reference parameters -- their reference arguments must always be implicitly dereferenced.
+		struct FixIntrinsicArgs final {
+			Expression * postmutate( ApplicationExpr *appExpr );
+		};
+
+
+		/// Replace reference types with pointer types
+		struct ReferenceTypeElimination final {
+			Type * postmutate( ReferenceType * refType );
 		};
 
@@ -62,17 +59,18 @@
 		/// https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Lvalues.html#Lvalues
 		/// Replaces &(a,b) with (a, &b), &(a ? b : c) with (a ? &b : &c)
-		class GeneralizedLvalue : public Mutator {
-			typedef Mutator Parent;
-
-			virtual Expression * mutate( AddressExpr * addressExpr );
+		struct GeneralizedLvalue final {
+			Expression * postmutate( AddressExpr * addressExpr );
 		};
 	} // namespace
 
 	void convertLvalue( std::list< Declaration* >& translationUnit ) {
-		Pass1 p1;
-		Pass2 p2;
-		GeneralizedLvalue genLval;
-		mutateAll( translationUnit, p1 );
-		acceptAll( translationUnit, p2 );
+		std::cerr << "convertLvalue" << std::endl;
+		PassVisitor<ReferenceConversions> refCvt;
+		PassVisitor<ReferenceTypeElimination> elim;
+		PassVisitor<GeneralizedLvalue> genLval;
+		PassVisitor<FixIntrinsicArgs> fixer;
+		mutateAll( translationUnit, refCvt );
+		mutateAll( translationUnit, fixer );
+		mutateAll( translationUnit, elim );
 		mutateAll( translationUnit, genLval );
 	}
@@ -82,5 +80,5 @@
 			if ( function->get_returnVals().empty() ) return 0;
 			Type *ty = function->get_returnVals().front()->get_type();
-			return ty->get_lvalue() ? ty : 0;
+			return dynamic_cast< ReferenceType * >( ty ) ;
 		}
 
@@ -93,22 +91,131 @@
 		}
 
-		Pass1::Pass1() {
-		}
-
-		DeclarationWithType * Pass1::mutate( FunctionDecl *funcDecl ) {
-			if ( funcDecl->get_statements() ) {
-				DeclarationWithType* oldRetval = retval;
-				retval = 0;
-				if ( ! LinkageSpec::isBuiltin( funcDecl->get_linkage() ) && isLvalueRet( funcDecl->get_functionType() ) ) {
-					retval = funcDecl->get_functionType()->get_returnVals().front();
-				}
-				// fix expressions and return statements in this function
-				funcDecl->set_statements( funcDecl->get_statements()->acceptMutator( *this ) );
-				retval = oldRetval;
-			} // if
-			return funcDecl;
-		}
-
-		Type * Pass1::mutate( ReferenceType * refType ) {
+		bool isDeref( Expression * expr ) {
+			if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
+				return InitTweak::getFunctionName( untyped ) == "*?";
+			} else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
+				if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
+					return func->get_linkage() == LinkageSpec::Intrinsic && InitTweak::getFunctionName( appExpr ) == "*?";
+				}
+			}
+			return false;
+		}
+
+		bool isIntrinsicReference( Expression * expr ) {
+			if ( isDeref( expr ) ) return true;
+			else if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
+				return InitTweak::getFunctionName( untyped ) == "?[?]";
+			} else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
+				if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
+					return func->get_linkage() == LinkageSpec::Intrinsic && InitTweak::getFunctionName( appExpr ) == "?[?]";
+				}
+			}
+			return false;
+		}
+
+		void fixArg( Expression *& arg, Type * formal ) {
+			// if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( arg ) ) {
+				if ( dynamic_cast<ReferenceType*>( formal ) ) { // xxx - but might be deref, in which case result isn't REALLY a reference, at least not in the sense that we need to add another deref...
+					// doesn't work, for some reason left arg is skipped in assign
+					ReferenceType * refType = safe_dynamic_cast< ReferenceType * >( arg->get_result() ) ;
+					std::cerr << "appexpr arg is non-deref/index intrinsic call" << std::endl;
+					std::cerr << arg << std::endl;
+					PointerType * ptrType = new PointerType( Type::Qualifiers(), refType->get_base()->clone() );
+					delete refType;
+					arg->set_result( ptrType );
+					arg = UntypedExpr::createDeref( arg );
+				}
+
+			// }
+		}
+
+		Expression * FixIntrinsicArgs::postmutate( ApplicationExpr * appExpr ) {
+			if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
+				if ( function->get_linkage() == LinkageSpec::Intrinsic ) { // intrinsic functions that turn pointers into references
+					FunctionType * ftype = GenPoly::getFunctionType( function->get_type() );
+					assertf( ftype, "Function declaration does not have function type." );
+					for ( auto p : group_iterate( appExpr->get_args(), ftype->get_parameters() ) ) {
+						Expression *& arg = std::get<0>( p );
+						DeclarationWithType * formal = std::get<1>( p );
+						std::cerr << "pair<0>: " << arg << std::endl;
+						std::cerr << "pair<1>: " << formal->get_type() << std::endl;
+						if ( isIntrinsicReference( arg ) ) {
+							std::cerr << "skipping intrinsic reference" << std::endl;
+							continue;
+						} else {
+							fixArg( arg, formal->get_type() );
+						}
+					}
+				}
+			}
+			return appExpr;
+		}
+
+		Expression * ReferenceConversions::postmutate( CastExpr * castExpr ) {
+			// conversion to reference type
+			if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->get_result() ) ) {
+				(void)refType;
+				if ( ReferenceType * otherRef = dynamic_cast< ReferenceType * >( castExpr->get_arg()->get_result() ) ) {
+					// nothing to do if casting from reference to reference.
+					(void)otherRef;
+					std::cerr << "convert reference to reference -- nop" << std::endl;
+					if ( isIntrinsicReference( castExpr->get_arg() ) ) {
+						Expression * callExpr = castExpr->get_arg();
+						Expression ** arg = nullptr;
+						Expression *& arg0 = InitTweak::getCallArg( callExpr, 0 );
+						if ( dynamic_cast<PointerType *>( arg0->get_result() ) ) {
+							arg = &arg0;
+						} else {
+							arg = &InitTweak::getCallArg( callExpr, 1 );
+						}
+
+						castExpr->set_arg( *arg );
+						*arg = castExpr;
+						std::cerr << "but arg is deref -- &" << std::endl;
+						std::cerr << callExpr << std::endl;
+						// castExpr->set_arg( new AddressExpr( castExpr->get_arg() ) );
+
+						// move environment out to new top-level
+						callExpr->set_env( castExpr->get_env() );
+						castExpr->set_env( nullptr );
+						return callExpr;
+					}
+					std::cerr << castExpr << std::endl;
+					return castExpr;
+				} else if ( castExpr->get_arg()->get_result()->get_lvalue() ) {
+					// conversion from lvalue to reference
+					// xxx - keep cast, but turn into pointer cast??
+					// xxx - memory
+					std::cerr << "convert lvalue to reference -- &" << std::endl;
+					std::cerr << castExpr->get_arg() << std::endl;
+					castExpr->set_arg( new AddressExpr( castExpr->get_arg() ) );
+					// return new AddressExpr( castExpr->get_arg() );
+					return castExpr;
+				} else {
+					// rvalue to reference conversion -- introduce temporary
+				}
+				assertf( false, "Only conversions to reference from lvalue are currently supported: %s", toString( castExpr ).c_str() );
+			} else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->get_arg()->get_result() ) ) {
+				// should be easy, just need to move deref code up here?
+				std::cerr << "convert reference to rvalue -- *" << std::endl;
+				if ( isIntrinsicReference( castExpr->get_arg() ) ) {
+					std::cerr << "but arg is intrinsic reference -- nop" << std::endl;
+					return castExpr;
+				}
+				std::cerr << castExpr << std::endl;
+
+				PointerType * ptrType = new PointerType( refType->get_qualifiers(), refType->get_base()->clone() );
+				delete castExpr->get_result();
+				castExpr->set_result( ptrType );
+				Expression * deref = UntypedExpr::createDeref( castExpr );
+				deref->set_env( castExpr->get_env() );
+				castExpr->set_env( nullptr );
+				return deref;
+				// assertf( false, "Conversions from reference types are not currently supported." );
+			}
+			return castExpr;
+		}
+
+		Type * ReferenceTypeElimination::postmutate( ReferenceType * refType ) {
 			Type * base = refType->get_base();
 			refType->set_base( nullptr );
@@ -117,82 +224,5 @@
 		}
 
-		Expression * Pass1::mutate( VariableExpr *varExpr ) {
-			if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( varExpr->get_result() ) ) {
-				varExpr->set_result( refType->acceptMutator( *this ) );
-				return UntypedExpr::createDeref( varExpr );
-			}
-			return Parent::mutate( varExpr );
-		}
-
-		Expression * Pass1::mutate( ApplicationExpr *appExpr ) {
-			appExpr->get_function()->acceptMutator( *this );
-			mutateAll( appExpr->get_args(), *this );
-
-			PointerType *pointer = safe_dynamic_cast< PointerType* >( appExpr->get_function()->get_result() );
-			FunctionType *function = safe_dynamic_cast< FunctionType* >( pointer->get_base() );
-
-			Type *funType = isLvalueRet( function );
-			if ( funType && ! isIntrinsicApp( appExpr ) ) {
-				Expression *expr = appExpr;
-				Type *appType = appExpr->get_result();
-				if ( isPolyType( funType ) && ! isPolyType( appType ) ) {
-					// make sure cast for polymorphic type is inside dereference
-					expr = new CastExpr( appExpr, new PointerType( Type::Qualifiers(), appType->clone() ) );
-				}
-				UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
-				deref->set_result( appType->clone() );
-				appExpr->set_result( new PointerType( Type::Qualifiers(), appType ) );
-				deref->get_args().push_back( expr );
-				return deref;
-			} else {
-				return appExpr;
-			} // if
-		}
-
-		Statement * Pass1::mutate(ReturnStmt *retStmt) {
-			if ( retval && retStmt->get_expr() ) {
-				if ( retStmt->get_expr()->get_result()->get_lvalue() ) {
-					// ***** Code Removal ***** because casts may be stripped already
-
-					// strip casts because not allowed to take address of cast
-					// while ( CastExpr *castExpr = dynamic_cast< CastExpr* >( retStmt->get_expr() ) ) {
-					// 	retStmt->set_expr( castExpr->get_arg() );
-					// 	retStmt->get_expr()->set_env( castExpr->get_env() );
-					// 	castExpr->set_env( 0 );
-					// 	castExpr->set_arg( 0 );
-					// 	delete castExpr;
-					// } // while
-					retStmt->set_expr( new AddressExpr( retStmt->get_expr()->acceptMutator( *this ) ) );
-				} else {
-					throw SemanticError( "Attempt to return non-lvalue from an lvalue-qualified function" );
-				} // if
-			} // if
-			return retStmt;
-		}
-
-		void Pass2::visit( FunctionType *funType ) {
-			std::string typeName;
-			if ( isLvalueRet( funType ) ) {
-				DeclarationWithType *retParm = funType->get_returnVals().front();
-
-				// make a new parameter that is a pointer to the type of the old return value
-				retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
-			} // if
-
-			Visitor::visit( funType );
-		}
-
-		bool isDeref( Expression * expr ) {
-			if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
-				return InitTweak::getFunctionName( untyped ) == "*?";
-			} else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
-				return InitTweak::getFunctionName( appExpr ) == "*?";
-			} else {
-				return false;
-			}
-		}
-
-		Expression * GeneralizedLvalue::mutate( AddressExpr * addrExpr ) {
-			addrExpr = safe_dynamic_cast< AddressExpr * >( Parent::mutate( addrExpr ) );
+		Expression * GeneralizedLvalue::postmutate( AddressExpr * addrExpr ) {
 			if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( addrExpr->get_arg() ) ) {
 				Expression * arg1 = commaExpr->get_arg1()->clone();
@@ -206,11 +236,4 @@
 				delete addrExpr;
 				return new ConditionalExpr( arg1, new AddressExpr( arg2 ), new AddressExpr( arg3 ) );
-			} else if ( isDeref( addrExpr->get_arg() ) ) {
-				// xxx - this doesn't belong here -- move it somewhere else
-				Expression *& arg = InitTweak::getCallArg( addrExpr->get_arg(), 0 );
-				Expression * inner = arg;
-				arg = nullptr;
-				delete addrExpr;
-				return inner;
 			}
 			return addrExpr;
