Generic RISC-V ISS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

336 lines
15 KiB

  1. ////////////////////////////////////////////////////////////////////////////////
  2. // Copyright (C) 2017, MINRES Technologies GmbH
  3. // All rights reserved.
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. //
  8. // 1. Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. //
  11. // 2. Redistributions in binary form must reproduce the above copyright notice,
  12. // this list of conditions and the following disclaimer in the documentation
  13. // and/or other materials provided with the distribution.
  14. //
  15. // 3. Neither the name of the copyright holder nor the names of its contributors
  16. // may be used to endorse or promote products derived from this software
  17. // without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  23. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  24. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  25. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  27. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  28. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  29. // POSSIBILITY OF SUCH DAMAGE.
  30. //
  31. // Contributors:
  32. // eyck@minres.com - initial API and implementation
  33. //
  34. //
  35. ////////////////////////////////////////////////////////////////////////////////
  36. #include <iss/arch/${coreDef.name.toLowerCase()}.h>
  37. #include <iss/arch/riscv_hart_msu_vp.h>
  38. #include <iss/debugger/gdb_session.h>
  39. #include <iss/debugger/server.h>
  40. #include <iss/iss.h>
  41. #include <iss/vm_base.h>
  42. #include <util/logging.h>
  43. #include <boost/format.hpp>
  44. #include <iss/debugger/riscv_target_adapter.h>
  45. #include <array>
  46. namespace iss {
  47. namespace vm {
  48. namespace fp_impl{
  49. void add_fp_functions_2_module(llvm::Module *, unsigned);
  50. }
  51. }
  52. namespace ${coreDef.name.toLowerCase()} {
  53. using namespace iss::arch;
  54. using namespace llvm;
  55. using namespace iss::debugger;
  56. template <typename ARCH> class vm_impl : public vm::vm_base<ARCH> {
  57. public:
  58. using super = typename vm::vm_base<ARCH>;
  59. using virt_addr_t = typename super::virt_addr_t;
  60. using phys_addr_t = typename super::phys_addr_t;
  61. using code_word_t = typename super::code_word_t;
  62. using addr_t = typename super::addr_t;
  63. vm_impl();
  64. vm_impl(ARCH &core, unsigned core_id = 0, unsigned cluster_id = 0);
  65. void enableDebug(bool enable) { super::sync_exec = super::ALL_SYNC; }
  66. target_adapter_if *accquire_target_adapter(server_if *srv) {
  67. debugger_if::dbg_enabled = true;
  68. if (vm::vm_base<ARCH>::tgt_adapter == nullptr)
  69. vm::vm_base<ARCH>::tgt_adapter = new riscv_target_adapter<ARCH>(srv, this->get_arch());
  70. return vm::vm_base<ARCH>::tgt_adapter;
  71. }
  72. protected:
  73. using vm::vm_base<ARCH>::get_reg_ptr;
  74. template <typename T> inline llvm::ConstantInt *size(T type) {
  75. return llvm::ConstantInt::get(getContext(), llvm::APInt(32, type->getType()->getScalarSizeInBits()));
  76. }
  77. void setup_module(llvm::Module* m) override {
  78. super::setup_module(m);
  79. vm::fp_impl::add_fp_functions_2_module(m, traits<ARCH>::FP_REGS_SIZE);
  80. }
  81. inline llvm::Value *gen_choose(llvm::Value *cond, llvm::Value *trueVal, llvm::Value *falseVal, unsigned size) {
  82. return super::gen_cond_assign(cond, this->gen_ext(trueVal, size), this->gen_ext(falseVal, size));
  83. }
  84. std::tuple<vm::continuation_e, llvm::BasicBlock *> gen_single_inst_behavior(virt_addr_t &, unsigned int &,
  85. llvm::BasicBlock *) override;
  86. void gen_leave_behavior(llvm::BasicBlock *leave_blk) override;
  87. void gen_raise_trap(uint16_t trap_id, uint16_t cause);
  88. void gen_leave_trap(unsigned lvl);
  89. void gen_wait(unsigned type);
  90. void gen_trap_behavior(llvm::BasicBlock *) override;
  91. void gen_trap_check(llvm::BasicBlock *bb);
  92. inline llvm::Value *gen_reg_load(unsigned i, unsigned level = 0) {
  93. return this->builder.CreateLoad(get_reg_ptr(i), false);
  94. }
  95. inline void gen_set_pc(virt_addr_t pc, unsigned reg_num) {
  96. llvm::Value *next_pc_v = this->builder.CreateSExtOrTrunc(this->gen_const(traits<ARCH>::XLEN, pc.val),
  97. this->get_type(traits<ARCH>::XLEN));
  98. this->builder.CreateStore(next_pc_v, get_reg_ptr(reg_num), true);
  99. }
  100. // some compile time constants
  101. // enum { MASK16 = 0b1111110001100011, MASK32 = 0b11111111111100000111000001111111 };
  102. enum { MASK16 = 0b1111111111111111, MASK32 = 0b11111111111100000111000001111111 };
  103. enum { EXTR_MASK16 = MASK16 >> 2, EXTR_MASK32 = MASK32 >> 2 };
  104. enum { LUT_SIZE = 1 << util::bit_count(EXTR_MASK32), LUT_SIZE_C = 1 << util::bit_count(EXTR_MASK16) };
  105. using this_class = vm_impl<ARCH>;
  106. using compile_func = std::tuple<vm::continuation_e, llvm::BasicBlock *> (this_class::*)(virt_addr_t &pc,
  107. code_word_t instr,
  108. llvm::BasicBlock *bb);
  109. std::array<compile_func, LUT_SIZE> lut;
  110. std::array<compile_func, LUT_SIZE_C> lut_00, lut_01, lut_10;
  111. std::array<compile_func, LUT_SIZE> lut_11;
  112. std::array<compile_func*, 4> qlut;
  113. std::array<const uint32_t, 4> lutmasks = { { EXTR_MASK16, EXTR_MASK16, EXTR_MASK16, EXTR_MASK32 } };
  114. void expand_bit_mask(int pos, uint32_t mask, uint32_t value, uint32_t valid, uint32_t idx, compile_func lut[],
  115. compile_func f) {
  116. if (pos < 0) {
  117. lut[idx] = f;
  118. } else {
  119. auto bitmask = 1UL << pos;
  120. if ((mask & bitmask) == 0) {
  121. expand_bit_mask(pos - 1, mask, value, valid, idx, lut, f);
  122. } else {
  123. if ((valid & bitmask) == 0) {
  124. expand_bit_mask(pos - 1, mask, value, valid, (idx << 1), lut, f);
  125. expand_bit_mask(pos - 1, mask, value, valid, (idx << 1) + 1, lut, f);
  126. } else {
  127. auto new_val = idx << 1;
  128. if ((value & bitmask) != 0) new_val++;
  129. expand_bit_mask(pos - 1, mask, value, valid, new_val, lut, f);
  130. }
  131. }
  132. }
  133. }
  134. inline uint32_t extract_fields(uint32_t val) { return extract_fields(29, val >> 2, lutmasks[val & 0x3], 0); }
  135. uint32_t extract_fields(int pos, uint32_t val, uint32_t mask, uint32_t lut_val) {
  136. if (pos >= 0) {
  137. auto bitmask = 1UL << pos;
  138. if ((mask & bitmask) == 0) {
  139. lut_val = extract_fields(pos - 1, val, mask, lut_val);
  140. } else {
  141. auto new_val = lut_val << 1;
  142. if ((val & bitmask) != 0) new_val++;
  143. lut_val = extract_fields(pos - 1, val, mask, new_val);
  144. }
  145. }
  146. return lut_val;
  147. }
  148. private:
  149. /****************************************************************************
  150. * start opcode definitions
  151. ****************************************************************************/
  152. struct InstructionDesriptor {
  153. size_t length;
  154. uint32_t value;
  155. uint32_t mask;
  156. compile_func op;
  157. };
  158. const std::array<InstructionDesriptor, ${instructions.size}> instr_descr = {{
  159. /* entries are: size, valid value, valid mask, function ptr */<%instructions.each{instr -> %>
  160. /* instruction ${instr.instruction.name} */
  161. {${instr.length}, ${instr.value}, ${instr.mask}, &this_class::__${generator.functionName(instr.name)}},<%}%>
  162. }};
  163. /* instruction definitions */<%instructions.eachWithIndex{instr, idx -> %>
  164. /* instruction ${idx}: ${instr.name} */
  165. std::tuple<vm::continuation_e, llvm::BasicBlock*> __${generator.functionName(instr.name)}(virt_addr_t& pc, code_word_t instr, llvm::BasicBlock* bb){<%instr.code.eachLine{%>
  166. ${it}<%}%>
  167. }
  168. <%}%>
  169. /****************************************************************************
  170. * end opcode definitions
  171. ****************************************************************************/
  172. std::tuple<vm::continuation_e, llvm::BasicBlock *> illegal_intruction(virt_addr_t &pc, code_word_t instr,
  173. llvm::BasicBlock *bb) {
  174. this->gen_sync(iss::PRE_SYNC, instr_descr.size());
  175. this->builder.CreateStore(this->builder.CreateLoad(get_reg_ptr(traits<ARCH>::NEXT_PC), true),
  176. get_reg_ptr(traits<ARCH>::PC), true);
  177. this->builder.CreateStore(
  178. this->builder.CreateAdd(this->builder.CreateLoad(get_reg_ptr(traits<ARCH>::ICOUNT), true),
  179. this->gen_const(64U, 1)),
  180. get_reg_ptr(traits<ARCH>::ICOUNT), true);
  181. pc = pc + ((instr & 3) == 3 ? 4 : 2);
  182. this->gen_raise_trap(0, 2); // illegal instruction trap
  183. this->gen_sync(iss::POST_SYNC, instr_descr.size());
  184. this->gen_trap_check(this->leave_blk);
  185. return std::make_tuple(iss::vm::BRANCH, nullptr);
  186. }
  187. };
  188. template <typename CODE_WORD> void debug_fn(CODE_WORD insn) {
  189. volatile CODE_WORD x = insn;
  190. insn = 2 * x;
  191. }
  192. template <typename ARCH> vm_impl<ARCH>::vm_impl() { this(new ARCH()); }
  193. template <typename ARCH>
  194. vm_impl<ARCH>::vm_impl(ARCH &core, unsigned core_id, unsigned cluster_id)
  195. : vm::vm_base<ARCH>(core, core_id, cluster_id) {
  196. qlut[0] = lut_00.data();
  197. qlut[1] = lut_01.data();
  198. qlut[2] = lut_10.data();
  199. qlut[3] = lut_11.data();
  200. for (auto instr : instr_descr) {
  201. auto quantrant = instr.value & 0x3;
  202. expand_bit_mask(29, lutmasks[quantrant], instr.value >> 2, instr.mask >> 2, 0, qlut[quantrant], instr.op);
  203. }
  204. }
  205. template <typename ARCH>
  206. std::tuple<vm::continuation_e, llvm::BasicBlock *>
  207. vm_impl<ARCH>::gen_single_inst_behavior(virt_addr_t &pc, unsigned int &inst_cnt, llvm::BasicBlock *this_block) {
  208. // we fetch at max 4 byte, alignment is 2
  209. code_word_t insn = 0;
  210. const typename traits<ARCH>::addr_t upper_bits = ~traits<ARCH>::PGMASK;
  211. phys_addr_t paddr(pc);
  212. try {
  213. uint8_t *const data = (uint8_t *)&insn;
  214. paddr = this->core.v2p(pc);
  215. if ((pc.val & upper_bits) != ((pc.val + 2) & upper_bits)) { // we may cross a page boundary
  216. auto res = this->core.read(paddr, 2, data);
  217. if (res != iss::Ok) throw trap_access(1, pc.val);
  218. if ((insn & 0x3) == 0x3) { // this is a 32bit instruction
  219. res = this->core.read(this->core.v2p(pc + 2), 2, data + 2);
  220. }
  221. } else {
  222. auto res = this->core.read(paddr, 4, data);
  223. if (res != iss::Ok) throw trap_access(1, pc.val);
  224. }
  225. } catch (trap_access &ta) {
  226. throw trap_access(ta.id, pc.val);
  227. }
  228. if (insn == 0x0000006f || (insn&0xffff)==0xa001) throw simulation_stopped(0); // 'J 0' or 'C.J 0'
  229. // curr pc on stack
  230. ++inst_cnt;
  231. auto lut_val = extract_fields(insn);
  232. auto f = qlut[insn & 0x3][lut_val];
  233. if (f == nullptr) {
  234. f = &this_class::illegal_intruction;
  235. }
  236. return (this->*f)(pc, insn, this_block);
  237. }
  238. template <typename ARCH> void vm_impl<ARCH>::gen_leave_behavior(llvm::BasicBlock *leave_blk) {
  239. this->builder.SetInsertPoint(leave_blk);
  240. this->builder.CreateRet(this->builder.CreateLoad(get_reg_ptr(arch::traits<ARCH>::NEXT_PC), false));
  241. }
  242. template <typename ARCH> void vm_impl<ARCH>::gen_raise_trap(uint16_t trap_id, uint16_t cause) {
  243. auto *TRAP_val = this->gen_const(32, 0x80 << 24 | (cause << 16) | trap_id);
  244. this->builder.CreateStore(TRAP_val, get_reg_ptr(traits<ARCH>::TRAP_STATE), true);
  245. this->builder.CreateStore(this->gen_const(32U, std::numeric_limits<uint32_t>::max()), get_reg_ptr(traits<ARCH>::LAST_BRANCH), false);
  246. }
  247. template <typename ARCH> void vm_impl<ARCH>::gen_leave_trap(unsigned lvl) {
  248. std::vector<llvm::Value *> args{
  249. this->core_ptr, llvm::ConstantInt::get(getContext(), llvm::APInt(64, lvl)),
  250. };
  251. this->builder.CreateCall(this->mod->getFunction("leave_trap"), args);
  252. auto *PC_val = this->gen_read_mem(traits<ARCH>::CSR, (lvl << 8) + 0x41, traits<ARCH>::XLEN / 8);
  253. this->builder.CreateStore(PC_val, get_reg_ptr(traits<ARCH>::NEXT_PC), false);
  254. this->builder.CreateStore(this->gen_const(32U, std::numeric_limits<uint32_t>::max()), get_reg_ptr(traits<ARCH>::LAST_BRANCH), false);
  255. }
  256. template <typename ARCH> void vm_impl<ARCH>::gen_wait(unsigned type) {
  257. std::vector<llvm::Value *> args{
  258. this->core_ptr, llvm::ConstantInt::get(getContext(), llvm::APInt(64, type)),
  259. };
  260. this->builder.CreateCall(this->mod->getFunction("wait"), args);
  261. }
  262. template <typename ARCH> void vm_impl<ARCH>::gen_trap_behavior(llvm::BasicBlock *trap_blk) {
  263. this->builder.SetInsertPoint(trap_blk);
  264. auto *trap_state_val = this->builder.CreateLoad(get_reg_ptr(traits<ARCH>::TRAP_STATE), true);
  265. this->builder.CreateStore(this->gen_const(32U, std::numeric_limits<uint32_t>::max()), get_reg_ptr(traits<ARCH>::LAST_BRANCH), false);
  266. std::vector<llvm::Value *> args{
  267. this->core_ptr,
  268. this->adj_to64(trap_state_val),
  269. this->adj_to64(this->builder.CreateLoad(get_reg_ptr(traits<ARCH>::PC), false))};
  270. this->builder.CreateCall(this->mod->getFunction("enter_trap"), args);
  271. auto *trap_addr_val = this->builder.CreateLoad(get_reg_ptr(traits<ARCH>::NEXT_PC), false);
  272. this->builder.CreateRet(trap_addr_val);
  273. }
  274. template <typename ARCH> inline void vm_impl<ARCH>::gen_trap_check(llvm::BasicBlock *bb) {
  275. auto *v = this->builder.CreateLoad(get_reg_ptr(arch::traits<ARCH>::TRAP_STATE), true);
  276. this->gen_cond_branch(this->builder.CreateICmp(
  277. ICmpInst::ICMP_EQ, v,
  278. llvm::ConstantInt::get(getContext(), llvm::APInt(v->getType()->getIntegerBitWidth(), 0))),
  279. bb, this->trap_blk, 1);
  280. }
  281. } // namespace ${coreDef.name.toLowerCase()}
  282. template <>
  283. std::unique_ptr<vm_if> create<arch::${coreDef.name.toLowerCase()}>(arch::${coreDef.name.toLowerCase()} *core, unsigned short port, bool dump) {
  284. std::unique_ptr<${coreDef.name.toLowerCase()}::vm_impl<arch::${coreDef.name.toLowerCase()}>> ret =
  285. std::make_unique<${coreDef.name.toLowerCase()}::vm_impl<arch::${coreDef.name.toLowerCase()}>>(*core, dump);
  286. if (port != 0) debugger::server<debugger::gdb_session>::run_server(ret.get(), port);
  287. return ret;
  288. }
  289. } // namespace iss