/*
 * LateContextCompiler2.cpp
 *
 *  Created on: 10 февр. 2016
 *      Author: pgess
 */

#include "latecontextcompiler2.h"
#include "llvmlayer.h"
#include "pass/compilepass.h"
#include "query/context.h"
#include <iostream>

namespace xreate {

LateContextCompiler2::LateContextCompiler2(compilation::FunctionUnit* f, CompilePass* p)
	: function(f), pass(p){}

//TEST default variants - do not enable specialization context in order to check default variant invocation
llvm::Value*
LateContextCompiler2::findFunction(const std::string& calleeName, llvm::Function* specializationDefault){
		LLVMLayer* llvm = pass->man->llvm;
		llvm::IRBuilder<>& builder = llvm->builder;
		ContextQuery* context = pass->queryContext;
		const string& functionName = function->function->getName();

	const std::list<ManagedFnPtr>& specializations = pass->man->root->getFunctionVariants(calleeName);
	const FunctionContextDemand& decisions = context->getFunctionDemand(functionName);

	assert(decisions.right.count(calleeName) && "Can't determine specialization of the function");
	size_t decisionIndex = decisions.right.at(calleeName);
	const ContextDomain& decisionDomain= context->getFunctionDomain(calleeName);

	llvm::IntegerType* ty32 = llvm::Type::getInt32Ty(llvm::getGlobalContext());
	llvm::Type* tyCallee = specializationDefault->getType();

	llvm::BasicBlock* blockDefault = llvm::BasicBlock::Create(llvm::getGlobalContext(), "caseDefault", this->function->raw);

	llvm::Value* decisionRaw = builder.CreateExtractValue(this->raw, llvm::ArrayRef<unsigned>{decisionIndex});
	llvm::SwitchInst* instrSwitch = builder.CreateSwitch(decisionRaw, blockDefault, decisionDomain.size());

	llvm::BasicBlock *blockEpilog = llvm::BasicBlock::Create(llvm::getGlobalContext(), "ContextDeterminationEnd", this->function->raw);
	builder.SetInsertPoint(blockEpilog);
	llvm::PHINode *ret =  llvm->builder.CreatePHI(tyCallee, decisionDomain.size(), "callee");

	for (const ManagedFnPtr& f: specializations){
		if (!f->guardContext.isValid()) continue;
		const Code& specCode =  decisionDomain.getId(f->guardContext);
		llvm::ConstantInt* rawSpecCode = llvm::ConstantInt::get(ty32, specCode);

		llvm::BasicBlock* blockCase = llvm::BasicBlock::Create(llvm::getGlobalContext(), "case+" + f->guardContext.getValueString(), this->function->raw);
		builder.SetInsertPoint(blockCase);
		builder.CreateBr(blockEpilog);
		ret->addIncoming(pass->getFunctionUnit(f)->compile(), blockCase);

		instrSwitch->addCase(rawSpecCode, blockCase);
	}

		//prepare default specialization
	builder.SetInsertPoint(blockDefault);
	builder.CreateBr(blockEpilog);
	ret->addIncoming(specializationDefault, blockDefault);

	builder.SetInsertPoint(blockEpilog);
	return ret;
}

llvm::Value*
LateContextCompiler2::compileArgument(const std::string& callee, ScopePacked scopeOuter){
	llvm::IRBuilder<>& builder = pass->man->llvm->builder;
	ContextQuery* context = pass->queryContext;
	const string& functionName = function->function->getName();
	const map<string, Expression>& dictStaticDecisions = context->getStaticDecisions(scopeOuter);

	const FunctionContextDemand& decisionsCallee = context->getFunctionDemand(callee);
	const FunctionContextDemand& decisionsSelf = context->getFunctionDemand(functionName);

	llvm::IntegerType* ty32 = llvm::Type::getInt32Ty(llvm::getGlobalContext());
	llvm::Type* tyDemand = llvm::ArrayType::get(ty32, decisionsCallee.size());

	//builder.CreateAlloca(tyDemand, llvm::ConstantInt::get(ty32, 1));
	llvm::Value* res = llvm::ConstantArray::getNullValue(tyDemand);

	for (size_t i=0, size = decisionsCallee.size(); i<size; ++i){
		const string& key = decisionsCallee.left.at(i);

		if (dictStaticDecisions.count(key)){
			const Expression& decision = dictStaticDecisions.at(key);
			const Domain& dom = context->getFunctionDomain(key);
			const Code& decisionCode = dom.getId(decision);

			res = builder.CreateInsertValue(res, llvm::ConstantInt::get(ty32, decisionCode), llvm::ArrayRef<unsigned>{i});
			continue;
		}

			//TEST decision propagtion
		const size_t& decisionIndex = decisionsSelf.right.at(key);
		llvm::Value* decision = builder.CreateExtractValue(this->raw, llvm::ArrayRef<unsigned>{decisionIndex});
		res = builder.CreateInsertElement(res, llvm::ConstantInt::get(ty32, i), decision);
	}

	return res;
}

size_t
LateContextCompiler2::getFunctionVariantsSize() const {
	ContextQuery* context = pass->queryContext;

	return context->getFunctionDomain(function->function->getName()).size();
}

size_t
LateContextCompiler2::getFunctionDemandSize() const {
	ContextQuery* context = pass->queryContext;

	return context->getFunctionDemand(function->function->getName()).size();
}

} /* namespace xreate */
