/*******************************************************************************
 * Copyright (C) 2017, 2018 MINRES Technologies GmbH
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *******************************************************************************/

<% 
import com.minres.coredsl.coreDsl.Register
import com.minres.coredsl.coreDsl.RegisterFile
import com.minres.coredsl.coreDsl.RegisterAlias
def getTypeSize(size){
	if(size > 32) 64 else if(size > 16) 32 else if(size > 8) 16 else 8
}
def getOriginalName(reg){
    if( reg.original instanceof RegisterFile) {
    	if( reg.index != null ) {
        	return reg.original.name+generator.generateHostCode(reg.index)
        } else {
        	return reg.original.name
        }
    } else if(reg.original instanceof Register){
        return reg.original.name
    }
}
def getRegisterNames(){
	def regNames = []
 	allRegs.each { reg -> 
		if( reg instanceof RegisterFile) {
			(reg.range.right..reg.range.left).each{
    			regNames+=reg.name.toLowerCase()+it
            }
        } else if(reg instanceof Register){
    		regNames+=reg.name.toLowerCase()
        }
    }
    return regNames
}
def getRegisterAliasNames(){
	def regMap = allRegs.findAll{it instanceof RegisterAlias }.collectEntries {[getOriginalName(it), it.name]}
 	return allRegs.findAll{it instanceof Register || it instanceof RegisterFile}.collect{reg ->
		if( reg instanceof RegisterFile) {
			return (reg.range.right..reg.range.left).collect{ (regMap[reg.name]?:regMap[reg.name+it]?:reg.name.toLowerCase()+it).toLowerCase() }
        } else if(reg instanceof Register){
    		regMap[reg.name]?:reg.name.toLowerCase()
        }
 	}.flatten()
}
%>
#ifndef _${coreDef.name.toUpperCase()}_H_
#define _${coreDef.name.toUpperCase()}_H_

#include <array>
#include <iss/arch/traits.h>
#include <iss/arch_if.h>
#include <iss/vm_if.h>

namespace iss {
namespace arch {

struct ${coreDef.name.toLowerCase()};

template <> struct traits<${coreDef.name.toLowerCase()}> {

	constexpr static char const* const core_type = "${coreDef.name}";
    
  	static constexpr std::array<const char*, ${getRegisterNames().size}> reg_names{
 		{"${getRegisterNames().join("\", \"")}"}};
 
  	static constexpr std::array<const char*, ${getRegisterAliasNames().size}> reg_aliases{
 		{"${getRegisterAliasNames().join("\", \"")}"}};

    enum constants {${coreDef.constants.collect{c -> c.name+"="+c.value}.join(', ')}};

    constexpr static unsigned FP_REGS_SIZE = ${coreDef.constants.find {it.name=='FLEN'}?.value?:0};

    enum reg_e {<%
     	allRegs.each { reg -> 
    		if( reg instanceof RegisterFile) {
    			(reg.range.right..reg.range.left).each{%>
        ${reg.name}${it},<%
                }
            } else if(reg instanceof Register){ %>
        ${reg.name},<%  
            }
        }%>
        NUM_REGS,
        NEXT_${pc.name}=NUM_REGS,
        TRAP_STATE,
        PENDING_TRAP,
        MACHINE_STATE,
        LAST_BRANCH,
        ICOUNT<% 
     	allRegs.each { reg -> 
    		if(reg instanceof RegisterAlias){ def aliasname=getOriginalName(reg)%>,
        ${reg.name} = ${aliasname}<%
            }
        }%>
    };

    using reg_t = uint${regDataWidth}_t;

    using addr_t = uint${addrDataWidth}_t;

    using code_word_t = uint${addrDataWidth}_t; //TODO: check removal

    using virt_addr_t = iss::typed_addr_t<iss::address_type::VIRTUAL>;

    using phys_addr_t = iss::typed_addr_t<iss::address_type::PHYSICAL>;

 	static constexpr std::array<const uint32_t, ${regSizes.size}> reg_bit_widths{
 		{${regSizes.join(",")}}};

    static constexpr std::array<const uint32_t, ${regOffsets.size}> reg_byte_offsets{
    	{${regOffsets.join(",")}}};

    static const uint64_t addr_mask = (reg_t(1) << (XLEN - 1)) | ((reg_t(1) << (XLEN - 1)) - 1);

    enum sreg_flag_e { FLAGS };

    enum mem_type_e { ${allSpaces.collect{s -> s.name}.join(', ')} };
};

struct ${coreDef.name.toLowerCase()}: public arch_if {

    using virt_addr_t = typename traits<${coreDef.name.toLowerCase()}>::virt_addr_t;
    using phys_addr_t = typename traits<${coreDef.name.toLowerCase()}>::phys_addr_t;
    using reg_t =  typename traits<${coreDef.name.toLowerCase()}>::reg_t;
    using addr_t = typename traits<${coreDef.name.toLowerCase()}>::addr_t;

    ${coreDef.name.toLowerCase()}();
    ~${coreDef.name.toLowerCase()}();

    void reset(uint64_t address=0) override;

    uint8_t* get_regs_base_ptr() override;
    /// deprecated
    void get_reg(short idx, std::vector<uint8_t>& value) override {}
    void set_reg(short idx, const std::vector<uint8_t>& value) override {}
    /// deprecated
    bool get_flag(int flag) override {return false;}
    void set_flag(int, bool value) override {};
    /// deprecated
    void update_flags(operations op, uint64_t opr1, uint64_t opr2) override {};

    inline uint64_t get_icount() { return reg.icount; }

    inline bool should_stop() { return interrupt_sim; }

    inline phys_addr_t v2p(const iss::addr_t& addr){
        if (addr.space != traits<${coreDef.name.toLowerCase()}>::MEM || addr.type == iss::address_type::PHYSICAL ||
                addr_mode[static_cast<uint16_t>(addr.access)&0x3]==address_type::PHYSICAL) {
            return phys_addr_t(addr.access, addr.space, addr.val&traits<${coreDef.name.toLowerCase()}>::addr_mask);
        } else
            return virt2phys(addr);
    }

    virtual phys_addr_t virt2phys(const iss::addr_t& addr);

    virtual iss::sync_type needed_sync() const { return iss::NO_SYNC; }

    inline uint32_t get_last_branch() { return reg.last_branch; }

protected:
    struct ${coreDef.name}_regs {<%
     	allRegs.each { reg -> 
    		if( reg instanceof RegisterFile) {
    			(reg.range.right..reg.range.left).each{%>
        uint${generator.getSize(reg)}_t ${reg.name}${it} = 0;<%
                }
            } else if(reg instanceof Register){ %>
        uint${generator.getSize(reg)}_t ${reg.name} = 0;<%
            }
        }%>
        uint${generator.getSize(pc)}_t NEXT_${pc.name} = 0;
        uint32_t trap_state = 0, pending_trap = 0, machine_state = 0, last_branch = 0;
        uint64_t icount = 0;
    } reg;

    std::array<address_type, 4> addr_mode;
    
    bool interrupt_sim=false;
<%
def fcsr = allRegs.find {it.name=='FCSR'}
if(fcsr != null) {%>
	uint${generator.getSize(fcsr)}_t get_fcsr(){return reg.FCSR;}
	void set_fcsr(uint${generator.getSize(fcsr)}_t val){reg.FCSR = val;}		
<%} else { %>
	uint32_t get_fcsr(){return 0;}
	void set_fcsr(uint32_t val){}
<%}%>
};

}
}            
#endif /* _${coreDef.name.toUpperCase()}_H_ */
