//
// 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 : Fri May 13 11:37:48 2016
// Update Count     : 166
//

#include <stack>
#include <list>
#include "GenInit.h"
#include "InitTweak.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"
#include "GenPoly/DeclMutator.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.
		/// the actual call statements will be added in after the resolver has run
		/// so that the initializer expression is only removed if a constructor is found
		/// and the same destructor call is inserted in all of the appropriate locations.
		static void generateCtorDtor( std::list< Declaration * > &translationUnit );

		virtual DeclarationWithType * mutate( ObjectDecl * );
		virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
		// should not traverse into any of these declarations to find objects
		// that need to be constructed or destructed
		virtual Declaration* mutate( StructDecl *aggregateDecl ) { return aggregateDecl; }
		virtual Declaration* mutate( UnionDecl *aggregateDecl ) { return aggregateDecl; }
		virtual Declaration* mutate( EnumDecl *aggregateDecl ) { return aggregateDecl; }
		virtual Declaration* mutate( TraitDecl *aggregateDecl ) { return aggregateDecl; }
		virtual TypeDecl* mutate( TypeDecl *typeDecl ) { return typeDecl; }
		virtual Declaration* mutate( TypedefDecl *typeDecl ) { return typeDecl; }

		virtual Type * mutate( FunctionType *funcType ) { return funcType; }

	  protected:
	};

	class HoistArrayDimension : public GenPoly::DeclMutator {
	  public:
		typedef GenPoly::DeclMutator Parent;

		/// hoist dimension from array types in object declaration so that it uses a single
		/// const variable of type size_t, so that side effecting array dimensions are only
		/// computed once.
		static void hoistArrayDimension( std::list< Declaration * > & translationUnit );

	  private:
		virtual DeclarationWithType * mutate( ObjectDecl * objectDecl );
		virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
		// should not traverse into any of these declarations to find objects
		// that need to be constructed or destructed
		virtual Declaration* mutate( StructDecl *aggregateDecl ) { return aggregateDecl; }
		virtual Declaration* mutate( UnionDecl *aggregateDecl ) { return aggregateDecl; }
		virtual Declaration* mutate( EnumDecl *aggregateDecl ) { return aggregateDecl; }
		virtual Declaration* mutate( TraitDecl *aggregateDecl ) { return aggregateDecl; }
		virtual TypeDecl* mutate( TypeDecl *typeDecl ) { return typeDecl; }
		virtual Declaration* mutate( TypedefDecl *typeDecl ) { return typeDecl; }

		virtual Type* mutate( FunctionType *funcType ) { return funcType; }

		void hoist( Type * type );

		DeclarationNode::StorageClass storageclass = DeclarationNode::NoStorageClass;
		bool inFunction = false;
	};

	void genInit( std::list< Declaration * > & translationUnit ) {
		ReturnFixer::makeReturnTemp( translationUnit );
		HoistArrayDimension::hoistArrayDimension( 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;
	}

	// precompute array dimension expression, because constructor generation may duplicate it,
	// which would be incorrect if it is a side-effecting computation.
	void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
		HoistArrayDimension hoister;
		hoister.mutateDeclarationList( translationUnit );
	}

	DeclarationWithType * HoistArrayDimension::mutate( ObjectDecl * objectDecl ) {
		storageclass = objectDecl->get_storageClass();
		DeclarationWithType * temp = Parent::mutate( objectDecl );
		hoist( objectDecl->get_type() );
		storageclass = DeclarationNode::NoStorageClass;
		return temp;
	}

	void HoistArrayDimension::hoist( Type * type ) {
		// if in function, generate const size_t var
		static UniqueName dimensionName( "_array_dim" );

		// C doesn't allow variable sized arrays at global scope or for static variables,
		// so don't hoist dimension.
		if ( ! inFunction ) return;
		if ( storageclass == DeclarationNode::Static ) return;

		if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
			if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist?

			// don't need to hoist dimension if it's a constexpr - only need to if there's potential
			// for side effects.
			if ( isConstExpr( arrayType->get_dimension() ) ) return;

			ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageclass, LinkageSpec::C, 0, SymTab::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) );
			arrayDimension->get_type()->set_isConst( true );

			arrayType->set_dimension( new VariableExpr( arrayDimension ) );
			addDeclaration( arrayDimension );

			hoist( arrayType->get_base() );
			return;
		}
	}

	DeclarationWithType * HoistArrayDimension::mutate( FunctionDecl *functionDecl ) {
		bool oldInFunc = inFunction;
		inFunction = true;
		DeclarationWithType * decl = Parent::mutate( functionDecl );
		inFunction = oldInFunc;
		return decl;
	}

	void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
		CtorDtor ctordtor;
		mutateAll( translationUnit, ctordtor );
	}

	DeclarationWithType * CtorDtor::mutate( ObjectDecl * objDecl ) {
		// hands off if designated, if @=, or if extern
		if ( tryConstruct( objDecl ) ) {
			// call into genImplicitCall from Autogen.h to generate calls to ctor/dtor
			// for each constructable object
			std::list< Statement * > ctor;
			std::list< Statement * > dtor;

			InitExpander srcParam( objDecl->get_init() );
			InitExpander nullParam( (Initializer *)NULL );
			SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), "?{}", back_inserter( ctor ), objDecl );
			SymTab::genImplicitCall( nullParam, new VariableExpr( objDecl ), "^?{}", front_inserter( dtor ), objDecl, false );

			// Currently genImplicitCall 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 genImplicitCall
			// itself. It is possible that genImplicitCall produces no statements (e.g. if
			// an array type does not have a dimension). In this case, it's fine to ignore
			// the object for the purposes of construction.
			assert( ctor.size() == dtor.size() && ctor.size() <= 1 );
			if ( ctor.size() == 1 ) {
				// 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
				assert( dynamic_cast< ImplicitCtorDtorStmt * > ( ctor.front() ) && dynamic_cast< ImplicitCtorDtorStmt * > ( dtor.front() ) );
				objDecl->set_init( new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() ) );
			}
		}
		return Mutator::mutate( objDecl );
	}

	DeclarationWithType * CtorDtor::mutate( FunctionDecl *functionDecl ) {
		// parameters should not be constructed and destructed, so don't mutate FunctionType
		mutateAll( functionDecl->get_oldDecls(), *this );
		functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
		return functionDecl;
	}
} // namespace InitTweak

// Local Variables: //
// tab-width: 4 //
// mode: c++ //
// compile-command: "make install" //
// End: //
