Index: src/InitTweak/GenInit.cc
===================================================================
--- src/InitTweak/GenInit.cc	(revision a0fdbd51112d9506c6a29aefc759d19bbb0828fe)
+++ src/InitTweak/GenInit.cc	(revision a0fdbd51112d9506c6a29aefc759d19bbb0828fe)
@@ -0,0 +1,249 @@
+//
+// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
+//
+// The contents of this file are covered under the licence agreement in the
+// file "LICENCE" distributed with Cforall.
+//
+// GenInit.cc --
+//
+// Author           : Rob Schluntz
+// Created On       : Mon May 18 07:44:20 2015
+// Last Modified By : Rob Schluntz
+// Last Modified On : Thu Apr 28 12:26:47 2016
+// Update Count     : 166
+//
+
+#include <stack>
+#include <list>
+#include "GenInit.h"
+#include "SynTree/Declaration.h"
+#include "SynTree/Type.h"
+#include "SynTree/Expression.h"
+#include "SynTree/Statement.h"
+#include "SynTree/Initializer.h"
+#include "SynTree/Mutator.h"
+#include "SymTab/Autogen.h"
+#include "GenPoly/PolyMutator.h"
+
+namespace InitTweak {
+	namespace {
+		const std::list<Label> noLabels;
+		const std::list<Expression *> noDesignators;
+	}
+
+	class ReturnFixer : public GenPoly::PolyMutator {
+	  public:
+		/// consistently allocates a temporary variable for the return value
+		/// of a function so that anything which the resolver decides can be constructed
+		/// into the return type of a function can be returned.
+		static void makeReturnTemp( std::list< Declaration * > &translationUnit );
+
+		ReturnFixer();
+
+		virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
+
+		virtual Statement * mutate( ReturnStmt * returnStmt );
+
+	  protected:
+		std::list<DeclarationWithType*> returnVals;
+		UniqueName tempNamer;
+		std::string funcName;
+	};
+
+	class CtorDtor : public GenPoly::PolyMutator {
+	  public:
+		/// create constructor and destructor statements for object declarations.
+		/// Destructors are inserted directly into the code, whereas constructors
+		/// will be added in after the resolver has run so that the initializer expression
+		/// is only removed if a constructor is found
+		static void generateCtorDtor( std::list< Declaration * > &translationUnit );
+
+		CtorDtor() : inFunction( false ) {}
+
+		virtual DeclarationWithType * mutate( ObjectDecl * );
+		virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
+		virtual Declaration* mutate( StructDecl *aggregateDecl );
+		virtual Declaration* mutate( UnionDecl *aggregateDecl );
+		virtual Declaration* mutate( EnumDecl *aggregateDecl );
+		virtual Declaration* mutate( TraitDecl *aggregateDecl );
+		virtual TypeDecl* mutate( TypeDecl *typeDecl );
+		virtual Declaration* mutate( TypedefDecl *typeDecl );
+
+		virtual Type * mutate( FunctionType *funcType );
+
+	  protected:
+		bool inFunction;
+	};
+
+	void genInit( std::list< Declaration * > & translationUnit ) {
+		ReturnFixer::makeReturnTemp( translationUnit );
+		CtorDtor::generateCtorDtor( translationUnit );
+	}
+
+	void ReturnFixer::makeReturnTemp( std::list< Declaration * > & translationUnit ) {
+		ReturnFixer fixer;
+		mutateAll( translationUnit, fixer );
+	}
+
+	ReturnFixer::ReturnFixer() : tempNamer( "_retVal" ) {}
+
+	Statement *ReturnFixer::mutate( ReturnStmt *returnStmt ) {
+		// update for multiple return values
+		assert( returnVals.size() == 0 || returnVals.size() == 1 );
+		// hands off if the function returns an lvalue - we don't want to allocate a temporary if a variable's address
+		// is being returned
+		if ( returnStmt->get_expr() && returnVals.size() == 1 && funcName != "?=?" && ! returnVals.front()->get_type()->get_isLvalue() ) {
+			// ensure return value is not destructed by explicitly creating
+			// an empty SingleInit node wherein maybeConstruct is false
+			ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, returnVals.front()->get_type()->clone(), new ListInit( std::list<Initializer*>(), noDesignators, false ) );
+			stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
+
+			// and explicitly create the constructor expression separately
+			UntypedExpr *construct = new UntypedExpr( new NameExpr( "?{}" ) );
+			construct->get_args().push_back( new AddressExpr( new VariableExpr( newObj ) ) );
+			construct->get_args().push_back( returnStmt->get_expr() );
+			stmtsToAdd.push_back(new ExprStmt(noLabels, construct));
+
+			returnStmt->set_expr( new VariableExpr( newObj ) );
+		} // if
+		return returnStmt;
+	}
+
+	DeclarationWithType* ReturnFixer::mutate( FunctionDecl *functionDecl ) {
+		std::list<DeclarationWithType*> oldReturnVals = returnVals;
+		std::string oldFuncName = funcName;
+
+		FunctionType * type = functionDecl->get_functionType();
+		returnVals = type->get_returnVals();
+		funcName = functionDecl->get_name();
+		DeclarationWithType * decl = Mutator::mutate( functionDecl );
+		returnVals = oldReturnVals;
+		funcName = oldFuncName;
+		return decl;
+	}
+
+
+	void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
+		CtorDtor ctordtor;
+		mutateAll( translationUnit, ctordtor );
+	}
+
+	namespace {
+		bool tryConstruct( ObjectDecl * objDecl ) {
+			// xxx - handle designations
+			return ! LinkageSpec::isBuiltin( objDecl->get_linkage() ) &&
+	 			(objDecl->get_init() == NULL ||
+				( objDecl->get_init() != NULL && objDecl->get_init()->get_maybeConstructed() ));
+		}
+
+		Expression * makeCtorDtorExpr( std::string name, ObjectDecl * objDecl, std::list< Expression * > args ) {
+			UntypedExpr * expr = new UntypedExpr( new NameExpr( name ) );
+			expr->get_args().push_back( new AddressExpr( new VariableExpr( objDecl ) ) );
+			expr->get_args().splice( expr->get_args().end(), args );
+			return expr;
+		}
+
+		class InitExpander : public Visitor {
+		  public:
+		  InitExpander() {}
+		  // ~InitExpander() {}
+			virtual void visit( SingleInit * singleInit );
+			virtual void visit( ListInit * listInit );
+			std::list< Expression * > argList;
+		};
+
+		void InitExpander::visit( SingleInit * singleInit ) {
+			argList.push_back( singleInit->get_value()->clone() );
+		}
+
+		void InitExpander::visit( ListInit * listInit ) {
+			// xxx - for now, assume no nested list inits
+			std::list<Initializer*>::iterator it = listInit->begin_initializers();
+			for ( ; it != listInit->end_initializers(); ++it ) {
+				(*it)->accept( *this );
+			}
+		}
+
+		std::list< Expression * > makeInitList( Initializer * init ) {
+			InitExpander expander;
+			maybeAccept( init, expander );
+			return expander.argList;
+		}
+	}
+
+	DeclarationWithType * CtorDtor::mutate( ObjectDecl * objDecl ) {
+		// hands off if designated or if @=
+		if ( tryConstruct( objDecl ) ) {
+			if ( inFunction ) {
+				if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
+					// call into makeArrayFunction from validate.cc to generate calls to ctor/dtor for each element of array
+					// TODO: walk initializer and generate appropriate copy ctor if element has initializer
+					std::list< Statement * > ctor;
+					std::list< Statement * > dtor;
+
+					SymTab::makeArrayFunction( NULL, new VariableExpr( objDecl ), at, "?{}", back_inserter( ctor ) );
+					SymTab::makeArrayFunction( NULL, new VariableExpr( objDecl ), at, "^?{}", front_inserter( dtor ), false );
+
+					// Currently makeArrayFunction produces a single Statement - a CompoundStmt
+					// which  wraps everything that needs to happen. As such, it's technically
+					// possible to use a Statement ** in the above calls, but this is inherently
+					// unsafe, so instead we take the slightly less efficient route, but will be
+					// immediately informed if somehow the above assumption is broken. In this case,
+					// we could always wrap the list of statements at this point with a CompoundStmt,
+					// but it seems reasonable at the moment for this to be done by makeArrayFunction
+					// itself
+					assert( ctor.size() == 1 );
+					assert( dtor.size() == 1 );
+
+					objDecl->set_init( new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() ) );
+				} else {
+					// it's sufficient to attempt to call the ctor/dtor for the given object and its initializer
+					Expression * ctor = makeCtorDtorExpr( "?{}", objDecl, makeInitList( objDecl->get_init() ) );
+					Expression * dtor = makeCtorDtorExpr( "^?{}", objDecl, std::list< Expression * >() );
+
+					// need to remember init expression, in case no ctors exist
+					// if ctor does exist, want to use ctor expression instead of init
+					// push this decision to the resolver
+					ExprStmt * ctorStmt = new ExprStmt( noLabels, ctor );
+					ExprStmt * dtorStmt = new ExprStmt( noLabels, dtor );
+					objDecl->set_init( new ConstructorInit( ctorStmt, dtorStmt, objDecl->get_init() ) );
+				}
+			} else {
+				// xxx - find a way to construct/destruct globals
+				// hack: implicit "static" initialization routine for each struct type? or something similar?
+				// --ties into module system
+				// this can be done by mangling main and replacing it with our own main which calls each
+				// module initialization routine in some decided order (order given in link command?)
+				// and finally calls mangled main
+			}
+		}
+		return Mutator::mutate( objDecl );
+	}
+
+	DeclarationWithType * CtorDtor::mutate( FunctionDecl *functionDecl ) {
+		// parameters should not be constructed and destructed, so don't mutate FunctionType
+		bool oldInFunc = inFunction;
+		mutateAll( functionDecl->get_oldDecls(), *this );
+		inFunction = true;
+		functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
+		inFunction = oldInFunc;
+		return functionDecl;
+	}
+
+	// should not traverse into any of these declarations to find objects
+	// that need to be constructed or destructed
+	Declaration* CtorDtor::mutate( StructDecl *aggregateDecl ) { return aggregateDecl; }
+	Declaration* CtorDtor::mutate( UnionDecl *aggregateDecl ) { return aggregateDecl; }
+	Declaration* CtorDtor::mutate( EnumDecl *aggregateDecl ) { return aggregateDecl; }
+	Declaration* CtorDtor::mutate( TraitDecl *aggregateDecl ) { return aggregateDecl; }
+	TypeDecl* CtorDtor::mutate( TypeDecl *typeDecl ) { return typeDecl; }
+	Declaration* CtorDtor::mutate( TypedefDecl *typeDecl ) { return typeDecl; }
+	Type* CtorDtor::mutate( FunctionType *funcType ) { return funcType; }
+
+} // namespace InitTweak
+
+// Local Variables: //
+// tab-width: 4 //
+// mode: c++ //
+// compile-command: "make install" //
+// End: //
