@@ -252,3 +252,108 @@ typedef enum {
OPC_FENCE_R_RW = 0x0230000f,
OPC_FENCE_RW_W = 0x0310000f,
} RISCVInsn;
+
+/*
+ * RISC-V immediate and instruction encoders (excludes 16-bit RVC)
+ */
+
+/* Type-R */
+
+static int32_t encode_r(RISCVInsn opc, TCGReg rd, TCGReg rs1, TCGReg rs2)
+{
+ return opc | (rd & 0x1f) << 7 | (rs1 & 0x1f) << 15 | (rs2 & 0x1f) << 20;
+}
+
+/* Type-I */
+
+static int32_t encode_imm12(uint32_t imm)
+{
+ return (imm & 0xfff) << 20;
+}
+
+static int32_t encode_i(RISCVInsn opc, TCGReg rd, TCGReg rs1, uint32_t imm)
+{
+ return opc | (rd & 0x1f) << 7 | (rs1 & 0x1f) << 15 | encode_imm12(imm);
+}
+
+/* Type-S */
+
+static int32_t encode_simm12(uint32_t imm)
+{
+ int32_t ret = 0;
+
+ ret |= (imm & 0xFE0) << 20;
+ ret |= (imm & 0x1F) << 7;
+
+ return ret;
+}
+
+static int32_t encode_s(RISCVInsn opc, TCGReg rs1, TCGReg rs2, uint32_t imm)
+{
+ return opc | (rs1 & 0x1f) << 15 | (rs2 & 0x1f) << 20 | encode_simm12(imm);
+}
+
+/* Type-SB */
+
+static int32_t encode_sbimm12(uint32_t imm)
+{
+ int32_t ret = 0;
+
+ ret |= (imm & 0x1000) << 19;
+ ret |= (imm & 0x7e0) << 20;
+ ret |= (imm & 0x1e) << 7;
+ ret |= (imm & 0x800) >> 4;
+
+ return ret;
+}
+
+static int32_t encode_sb(RISCVInsn opc, TCGReg rs1, TCGReg rs2, uint32_t imm)
+{
+ return opc | (rs1 & 0x1f) << 15 | (rs2 & 0x1f) << 20 | encode_sbimm12(imm);
+}
+
+/* Type-U */
+
+static int32_t encode_uimm20(uint32_t imm)
+{
+ return imm & 0xfffff000;
+}
+
+static int32_t encode_u(RISCVInsn opc, TCGReg rd, uint32_t imm)
+{
+ return opc | (rd & 0x1f) << 7 | encode_uimm20(imm);
+}
+
+/* Type-UJ */
+
+static int32_t encode_ujimm12(uint32_t imm)
+{
+ int32_t ret = 0;
+
+ ret |= (imm & 0x100000) << 11;
+ ret |= (imm & 0xffe) << 20;
+ ret |= (imm & 0x800) << 9;
+ ret |= imm & 0xff000;
+
+ return ret;
+}
+
+static int32_t encode_uj(RISCVInsn opc, TCGReg rd, uint32_t imm)
+{
+ return opc | (rd & 0x1f) << 7 | encode_ujimm12(imm);
+}
+
+void tb_target_set_jmp_target(uintptr_t tc_ptr, uintptr_t jmp_addr,
+ uintptr_t addr)
+{
+ intptr_t offset = (intptr_t)addr - (intptr_t)jmp_addr;
+ tcg_debug_assert(offset == (int32_t)offset);
+
+ int32_t hi20 = ((offset + 0x800) >> 12) << 12;
+ int32_t lo12 = offset - hi20;
+
+ atomic_set((uint32_t *)jmp_addr, encode_uimm20(hi20));
+ atomic_set((uint32_t *)jmp_addr + 4, encode_imm12(lo12));
+
+ flush_icache_range(jmp_addr, jmp_addr + 8);
+}