Vortex Exercise 5

Vortex Exercise 5

本练习将添加一条新的RISC-V自定义指令VX_DOT8来计算8位整数点积, 并将在SimX周期级模拟器中实现该指令
把这个 patch 打到 9cd0e1bb 分支上即可

Exercise5_9cd0e_83fe7.patch

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
diff --git a/kernel/include/vx_intrinsics.h b/kernel/include/vx_intrinsics.h
index 71d4cd5b..da9cf0e2 100644
--- a/kernel/include/vx_intrinsics.h
─+++ b/kernel/include/vx_intrinsics.h
@@ -281,6 +281,19 @@ inline __attribute__((const)) int vx_shfl_idx(size_t value, int bval, int cval,
     return ret;
 }
 
+// DOT8 funct7 设为9 避免以后项目添加新指令产生冲突
+// R type: .insn r opcode7, funct3, funct7, rd, rs1, rs2
+/* +--------+-----+-----+--------+----+---------+ */
+/* | funct7 | rs2 | rs1 | funct3 | rd | opcode7 | */
+/* +--------+-----+-----+--------+----+---------+ */
+/* 31       25    20    15       12   7         0 */
+
+inline int vx_dot8(int a, int b) {
+  size_t ret;
+  asm volatile (".insn r %1, 0, 9, %0, %2, %3" : "=r"(ret) : "i"(RISCV_CUSTOM0), "r"(a), "r"(b));
+  return ret;
+}
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/sim/simx/decode.cpp b/sim/simx/decode.cpp
index f2d6cc35..9cb1157e 100644
--- a/sim/simx/decode.cpp
─+++ b/sim/simx/decode.cpp
@@ -112,6 +112,7 @@ static op_string_t op_string(const Instr &instr) {
         }
       }
       case AluType::CZERO: return {aluArgs.imm ? "CZERO.NEZ":"CZERO.EQZ", ""};
+      case AluType::DOT8: return {"DOT8", ""};
       default:
         std::abort();
       }
@@ -1118,6 +1119,22 @@ void Emulator::decode(uint32_t code, uint32_t wid, uint64_t uuid) {
       }
     } break;
   #endif
+    case 9: {
+      switch (funct3) {
+      case 0: { // DOT8
+        auto instr = std::allocate_shared<Instr>(instr_pool_, uuid, FUType::ALU);
+        instr->setDestReg(rd, RegType::Integer);
+        instr->setSrcReg(0, rs1, RegType::Integer);
+        instr->setSrcReg(1, rs2, RegType::Integer);
+        instr->setOpType(AluType::DOT8);
+        ibuffer.push_back(instr);
+      } break;
+
+      default:
+        std::abort();
+      }
+    } break;
+
     default:
       std::abort();
     }
diff --git a/sim/simx/execute.cpp b/sim/simx/execute.cpp
index 25ee6850..9f75c039 100644
--- a/sim/simx/execute.cpp
─+++ b/sim/simx/execute.cpp
@@ -300,6 +300,28 @@ instr_trace_t* Emulator::execute(const Instr &instr, uint32_t wid) {
           rd_data[t].i = cond ? 0 : rs1_data[t].i;
         }
       } break;
+      case AluType::DOT8: {
+          // DOT8
+          for (uint32_t t = thread_start; t < num_threads; ++t) {
+            if (!warp.tmask.test(t))
+              continue;
+            // 实现 8-bit 点积运算逻辑
+            // 假设是两个 32-bit 寄存器,每个包含 4 个 8-bit 值
+            uint32_t src0_val = rs1_data[t].u32;
+            uint32_t src1_val = rs2_data[t].u32;
+
+            int32_t result = 0;
+            for (int i = 0; i < 4; ++i) {
+              int8_t a = (src0_val >> (i * 8)) & 0xFF;
+              int8_t b = (src1_val >> (i * 8)) & 0xFF;
+              result += a * b;
+            }
+
+            rd_data[t].i = result;
+          }
+          rd_write = true;
+      } break;
+
       default:
         std::abort();
       }
diff --git a/sim/simx/func_unit.cpp b/sim/simx/func_unit.cpp
index 42cbeb9a..ef6d65fc 100644
--- a/sim/simx/func_unit.cpp
+++ b/sim/simx/func_unit.cpp
@@ -51,6 +51,7 @@ void AluUnit::tick() {
             case AluType::AND:
             case AluType::OR:
             case AluType::CZERO:
+            case AluType::DOT8:
                 delay = 2;
                 break;
             default:
diff --git a/sim/simx/types.h b/sim/simx/types.h
index d069bdae..3182c33c 100644
--- a/sim/simx/types.h
+++ b/sim/simx/types.h
@@ -169,7 +169,8 @@ enum class AluType {
   AND,
   OR,
   XOR,
-  CZERO
+  CZERO,
+  DOT8
 };
 
 struct IntrAluArgs {
@@ -193,6 +194,7 @@ inline std::ostream &operator<<(std::ostream &os, const AluType& type) {
   case AluType::OR:      os << "OR"; break;
   case AluType::XOR:     os << "XOR"; break;
   case AluType::CZERO:   os << "CZERO"; break;
+  case AluType::DOT8:    os << "DOT8"; break;
   default:
     assert(false);
   }
diff --git a/tests/regression/Makefile b/tests/regression/Makefile
index be3ccc96..8db25319 100644
--- a/tests/regression/Makefile
+++ b/tests/regression/Makefile
@@ -21,6 +21,7 @@ all:
 	$(MAKE) -C sgemm2
 	$(MAKE) -C madmax
 	$(MAKE) -C stencil3d
+	$(MAKE) -C dot8
 
 run-simx:
 	$(MAKE) -C basic run-simx
@@ -42,6 +43,7 @@ run-simx:
 	$(MAKE) -C sgemm2 run-simx
 	$(MAKE) -C madmax run-simx
 	$(MAKE) -C stencil3d run-simx
+	$(MAKE) -C dot8 run-simx
 
 run-rtlsim:
 	$(MAKE) -C basic run-rtlsim
@@ -63,6 +65,7 @@ run-rtlsim:
 	$(MAKE) -C sgemm2 run-rtlsim
 	$(MAKE) -C madmax run-rtlsim
 	$(MAKE) -C stencil3d run-rtlsim
+	$(MAKE) -C dot8 run-rtlsim
 
 clean:
 	$(MAKE) -C basic clean
@@ -84,3 +87,4 @@ clean:
 	$(MAKE) -C sgemm2 clean
 	$(MAKE) -C madmax clean
 	$(MAKE) -C stencil3d clean
+	$(MAKE) -C dot8 clean
diff --git a/tests/regression/dot8/Makefile b/tests/regression/dot8/Makefile
new file mode 100644
index 00000000..f8e9ec9b
--- /dev/null
+++ b/tests/regression/dot8/Makefile
@@ -0,0 +1,14 @@
+ROOT_DIR := $(realpath ../../..)
+include $(ROOT_DIR)/config.mk
+
+PROJECT := dot8
+
+SRC_DIR := $(VORTEX_HOME)/tests/regression/$(PROJECT)
+
+SRCS := $(SRC_DIR)/main.cpp
+
+VX_SRCS := $(SRC_DIR)/kernel.cpp
+
+OPTS ?= -n32
+
+include ../common.mk
diff --git a/tests/regression/dot8/common.h b/tests/regression/dot8/common.h
new file mode 100644
index 00000000..db203b91
--- /dev/null
+++ b/tests/regression/dot8/common.h
@@ -0,0 +1,16 @@
+#ifndef _COMMON_H_
+#define _COMMON_H_
+
+#ifndef TYPE
+#define TYPE int8_t
+#endif
+
+typedef struct {
+  uint32_t grid_dim[2];
+  uint32_t size;
+  uint64_t A_addr;
+  uint64_t B_addr;
+  uint64_t C_addr;
+} kernel_arg_t;
+
+#endif
diff --git a/tests/regression/dot8/kernel.cpp b/tests/regression/dot8/kernel.cpp
new file mode 100644
index 00000000..1fce2dec
--- /dev/null
+++ b/tests/regression/dot8/kernel.cpp
@@ -0,0 +1,58 @@
+#include <cstdint>
+#include <vx_spawn.h>
+#include "common.h"
+#include <stdio.h>
+#include <vx_print.h>
+
+void MatrixMultiply(TYPE *A, TYPE *B, int32_t *C, int N) {
+    vx_printf("MatrixMultiply start (N=%d)\n", N);
+    // auto C = reinterpret_cast<uint32_t *>(C);
+    vx_printf("C point addr: 0x%x\n", C);
+    
+    int32_t sum(0);
+    for (int i = 0; i < N; i+=4) {
+        // Pack A elements
+        uint32_t packedA = *((uint32_t *)&A[i]);
+        vx_printf("    packedA=0x%08x\n", packedA);
+
+        // Pack B elements
+        uint32_t packedB = (uint8_t)B[(i + 0) * N]
+                        | ((uint8_t)B[(i + 1) * N] << 8)
+                        | ((uint8_t)B[(i + 2) * N] << 16)
+                        | ((uint8_t)B[(i + 3) * N] << 24);
+        vx_printf("    packedB=0x%08x (bytes: %x,%x,%x,%x)\n", 
+                packedB,
+                (uint8_t)B[(i + 0) * N],
+                (uint8_t)B[(i + 1) * N],
+                (uint8_t)B[(i + 2) * N],
+                (uint8_t)B[(i + 3) * N]);
+
+        int32_t dot = vx_dot8(packedA, packedB);
+        // int32_t dot = packedA * packedB;    // debug
+        vx_printf("    dot product=0x%08x (%d) C point: 0x%x\n", dot, dot, C);
+        sum += dot;
+    }
+    C[0] = sum;
+    vx_printf("  Final C = %d (0x%08x)\n", C[0], C[0]);
+    
+    vx_printf("MatrixMultiply completed\n");
+}
+
+
+void kernel_body(kernel_arg_t* __UNIFORM__ arg) {
+    auto A = reinterpret_cast<TYPE*>(arg->A_addr);
+    auto B = reinterpret_cast<TYPE*>(arg->B_addr);
+    auto C = reinterpret_cast<int32_t*>(arg->C_addr);
+    auto size = arg->size;
+
+    int col = blockIdx.x;
+    int row = blockIdx.y;
+    vx_printf("row: %d, col: %d\n", row, col);
+    MatrixMultiply(&A[row*size], &B[col], &C[row * size + col], size);
+}
+
+
+int main() {
+    kernel_arg_t* arg = (kernel_arg_t*)csr_read(VX_CSR_MSCRATCH);
+    return vx_spawn_threads(2, arg->grid_dim, nullptr, (vx_kernel_func_cb)kernel_body, arg);
+}
diff --git a/tests/regression/dot8/main.cpp b/tests/regression/dot8/main.cpp
new file mode 100644
index 00000000..b4d9f135
--- /dev/null
+++ b/tests/regression/dot8/main.cpp
@@ -0,0 +1,301 @@
+#include <cstdint>
+#include <cstdio>
+#include <endian.h>
+#include <iostream>
+#include <unistd.h>
+#include <string.h>
+#include <vector>
+#include <chrono>
+#include <vortex.h>
+#include <cmath>
+#include "common.h"
+#include <iomanip>
+
+#define FLOAT_ULP 6
+
+#define RT_CHECK(_expr)                                         \
+   do {                                                         \
+     int _ret = _expr;                                          \
+     if (0 == _ret)                                             \
+       break;                                                   \
+     printf("Error: '%s' returned %d!\n", #_expr, (int)_ret);   \
+     cleanup();                                                          \
+     exit(-1);                                                  \
+   } while (false)
+
+///////////////////////////////////////////////////////////////////////////////
+
+template <typename Type>
+class Comparator {};
+
+template <>
+class Comparator<int> {
+public:
+  static const char* type_str() {
+    return "integer";
+  }
+  static int generate() {
+    return rand();
+  }
+  static bool compare(int a, int b, int index, int errors) {
+    if (a != b) {
+      if (errors < 100) {
+        printf("*** error: [%d] expected=%d, actual=%d\n", index, b, a);
+      }
+      return false;
+    }
+    return true;
+  }
+};
+
+template <>
+class Comparator<float> {
+public:
+  static const char* type_str() {
+    return "float";
+  }
+  static int generate() {
+    return static_cast<float>(rand()) / RAND_MAX;
+  }
+  static bool compare(float a, float b, int index, int errors) {
+    union fi_t { float f; int32_t i; };
+    fi_t fa, fb;
+    fa.f = a;
+    fb.f = b;
+    auto d = std::abs(fa.i - fb.i);
+    if (d > FLOAT_ULP) {
+      if (errors < 100) {
+        printf("*** error: [%d] expected=%f, actual=%f\n", index, b, a);
+      }
+      return false;
+    }
+    return true;
+  }
+};
+
+template <>
+class Comparator<int8_t> {
+public:
+  static const char* type_str() {
+    return "int8_t";
+  }
+  static int8_t generate() {
+    return static_cast<int8_t>(rand() % 256);  // Generate value between 0-255
+  }
+  static bool compare(int a, int b, int index, int errors) {
+    if (a != b) {
+      if (errors < 100) {
+        printf("*** error: [%d] expected=0x%x, actual=0x%x\n", index, b, a);
+      }
+      return false;
+    }
+    return true;
+  }
+};
+
+static void matmul_cpu(int32_t *out, const TYPE *A, const TYPE *B, uint32_t size) {
+  printf("matmul_cpu Starting matrix multiplication (size: %u)\n", size);
+  for (uint32_t row = 0; row < size; ++row) {
+    printf("Processing row %u\n", row);
+    for (uint32_t col = 0; col < size; ++col) {
+      int32_t sum(0);
+      printf("  Calculating element [%u][%u]\n", row, col);
+      for (uint32_t i = 0; i < size; i++) {
+        TYPE a = A[row * size + i];
+        TYPE b = B[i * size + col];
+        printf("    A[%u][%u]=%d (0x%x), B[%u][%u]=%d (0x%x)\n", row, i, a, a, i, col, b, b);
+        sum += a * b;
+      }
+      out[row * size + col] = sum;
+      printf("  Result[%u][%u] =%d (0x%x)\n", row, col, sum, sum);
+    }
+  }
+  printf("Matrix multiplication completed\n");
+}
+
+
+const char* kernel_file = "kernel.vxbin";
+uint32_t size = 32;
+
+vx_device_h device = nullptr;
+vx_buffer_h A_buffer = nullptr;
+vx_buffer_h B_buffer = nullptr;
+vx_buffer_h C_buffer = nullptr;
+vx_buffer_h krnl_buffer = nullptr;
+vx_buffer_h args_buffer = nullptr;
+kernel_arg_t kernel_arg = {};
+
+static void show_usage() {
+   std::cout << "Vortex Test." << std::endl;
+   std::cout << "Usage: [-k: kernel] [-n size] [-h: help]" << std::endl;
+}
+
+static void parse_args(int argc, char **argv) {
+  int c;
+  while ((c = getopt(argc, argv, "n:k:h")) != -1) {
+    switch (c) {
+    case 'n':
+      size = atoi(optarg);
+      break;
+    case 'k':
+      kernel_file = optarg;
+      break;
+    case 'h':
+      show_usage();
+      exit(0);
+      break;
+    default:
+      show_usage();
+      exit(-1);
+    }
+  }
+}
+
+void cleanup() {
+  if (device) {
+    vx_mem_free(A_buffer);
+    vx_mem_free(B_buffer);
+    vx_mem_free(C_buffer);
+    vx_mem_free(krnl_buffer);
+    vx_mem_free(args_buffer);
+    vx_dev_close(device);
+  }
+}
+
+int main(int argc, char *argv[]) {
+  // parse command arguments
+  parse_args(argc, argv);
+
+  std::srand(50);
+
+  // open device connection
+  std::cout << "open device connection" << std::endl;
+  RT_CHECK(vx_dev_open(&device));
+
+  uint32_t size_sq = size * size;
+  uint32_t buf_size = size_sq * sizeof(TYPE);
+  uint32_t C_buf_size = buf_size * 4;
+
+  std::cout << "data type: " << Comparator<TYPE>::type_str() << std::endl;
+  std::cout << "matrix size: " << size << "x" << size << std::endl;
+
+  kernel_arg.grid_dim[0] = size;
+  kernel_arg.grid_dim[1] = size;
+  kernel_arg.size = size;
+
+  // allocate device memory
+  std::cout << "allocate device memory" << std::endl;
+  RT_CHECK(vx_mem_alloc(device, buf_size, VX_MEM_READ, &A_buffer));
+  RT_CHECK(vx_mem_address(A_buffer, &kernel_arg.A_addr));
+  RT_CHECK(vx_mem_alloc(device, buf_size, VX_MEM_READ, &B_buffer));
+  RT_CHECK(vx_mem_address(B_buffer, &kernel_arg.B_addr));
+  RT_CHECK(vx_mem_alloc(device, C_buf_size, VX_MEM_WRITE, &C_buffer));
+  RT_CHECK(vx_mem_address(C_buffer, &kernel_arg.C_addr));
+
+  std::cout << "A_addr=0x" << std::hex << kernel_arg.A_addr << std::endl;
+  std::cout << "B_addr=0x" << std::hex << kernel_arg.B_addr << std::endl;
+  std::cout << "C_addr=0x" << std::hex << kernel_arg.C_addr << std::endl;
+
+  // generate source data
+  std::vector<TYPE> h_A(size_sq);
+  std::vector<TYPE> h_B(size_sq);
+  std::vector<int32_t> h_C(size_sq);
+  for (uint32_t i = 0; i < size_sq; ++i) {
+    h_A[i] = Comparator<TYPE>::generate();
+    h_B[i] = Comparator<TYPE>::generate();
+  }
+
+  // 打印矩阵 h_A
+  std::cout << "Matrix A (" << size << "x" << size << "):\n";
+  for (uint32_t row = 0; row < size; ++row) {
+      for (uint32_t col = 0; col < size; ++col) {
+          std::cout << "0x" 
+                    << std::hex << std::setw(2) << std::setfill('0')
+                    << static_cast<int>(static_cast<uint8_t>(h_A[row * size + col])) << " ";
+      }
+      std::cout << "\n";
+  }
+
+  // 打印矩阵 h_B
+  std::cout << "\nMatrix B (" << size << "x" << size << "):\n";
+  for (uint32_t row = 0; row < size; ++row) {
+      for (uint32_t col = 0; col < size; ++col) {
+          std::cout << "0x"
+                    << std::hex << std::setw(2) << std::setfill('0')
+                    << static_cast<int>(static_cast<uint8_t>(h_B[row * size + col])) << " ";
+      }
+      std::cout << "\n";
+  }
+  std::cout << std::dec << std::endl;  // 恢复十进制输出
+
+
+
+  // upload matrix A buffer
+  {
+    std::cout << "upload matrix A buffer" << std::endl;
+    RT_CHECK(vx_copy_to_dev(A_buffer, h_A.data(), 0, buf_size));
+  }
+
+  // upload matrix B buffer
+  {
+    std::cout << "upload matrix B buffer" << std::endl;
+    RT_CHECK(vx_copy_to_dev(B_buffer, h_B.data(), 0, buf_size));
+  }
+
+  // upload program
+  std::cout << "upload program" << std::endl;
+  RT_CHECK(vx_upload_kernel_file(device, kernel_file, &krnl_buffer));
+
+  // upload kernel argument
+  std::cout << "upload kernel argument" << std::endl;
+  RT_CHECK(vx_upload_bytes(device, &kernel_arg, sizeof(kernel_arg_t), &args_buffer));
+
+  auto time_start = std::chrono::high_resolution_clock::now();
+
+  // start device
+  std::cout << "start device" << std::endl;
+  RT_CHECK(vx_start(device, krnl_buffer, args_buffer));
+
+  // wait for completion
+  std::cout << "wait for completion" << std::endl;
+  RT_CHECK(vx_ready_wait(device, VX_MAX_TIMEOUT));
+
+  auto time_end = std::chrono::high_resolution_clock::now();
+  double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(time_end - time_start).count();
+  printf("Elapsed time: %lg ms\n", elapsed);
+
+  // download destination buffer
+  std::cout << "download destination buffer" << std::endl;
+  RT_CHECK(vx_copy_from_dev(h_C.data(), C_buffer, 0, C_buf_size));
+
+  // verify result
+  std::cout << "verify result" << std::endl;
+  int errors = 0;
+  {
+    std::vector<int32_t> h_ref(size_sq);
+    matmul_cpu(h_ref.data(), h_A.data(), h_B.data(), size);
+    uint32_t int_size = (int32_t)(h_ref.size() / 4);
+
+    auto int_h_C = reinterpret_cast<int32_t *>(h_C.data());
+    auto int_h_ref = reinterpret_cast<int32_t *>(h_ref.data());
+
+    for (uint32_t i = 0; i < int_size; ++i) {
+      if (!Comparator<TYPE>::compare(int_h_C[i], int_h_ref[i], i, errors)) {
+        ++errors;
+      }
+    }
+  }
+
+  // cleanup
+  std::cout << "cleanup" << std::endl;
+  cleanup();
+
+  if (errors != 0) {
+    std::cout << "Found " << std::dec << errors << " errors!" << std::endl;
+    std::cout << "FAILED!" << std::endl;
+    return errors;
+  }
+
+  std::cout << "PASSED!" << std::endl;
+  return 0;
+}

解题步骤

添加新的RISC-V 指令

由于我们要新增的命令, 是把两个8 位数相乘把结果存给rd, 类似于汇编 ( mul rd, s0, s1 )
我们要需要两个源寄存器来存储源数据, 以及一个 rd 寄存器来存储结果
参考: RISC_002dV_002dFormats 可知, 我们的自定义指令使用 R 型指令格式
R type: .insn r opcode7, funct3, funct7, rd, rs1, rs2

 funct7   rs2   rs1   funct3   rd   opcode7 

31 25 20 15 12 7 0

在 kernel/include/vx_intrinsics.h 添加以下代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// DOT8 funct7 设为9 避免以后项目添加新指令产生冲突
// R type: .insn r opcode7, funct3, funct7, rd, rs1, rs2
/* +--------+-----+-----+--------+----+---------+ */
/* | funct7 | rs2 | rs1 | funct3 | rd | opcode7 | */
/* +--------+-----+-----+--------+----+---------+ */
/* 31       25    20    15       12   7         0 */

inline int vx_dot8(int a, int b) {
  size_t ret;
  asm volatile (".insn r %1, 0, 9, %0, %2, %3" : "=r"(ret) : "i"(RISCV_CUSTOM0), "r"(a), "r"(b));
  // asm volatile (".insn r %0, 0, 9, %1, %2, %3" :: "i"(RISCV_CUSTOM0), "=r"(ret) , "r"(a), "r"(b));  // 或者这样
  return ret;
}

👿注意:
上面的两条内嵌汇编语句, 最终效果都是一样的, 如果是使用 :: 则后面跟着的以逗号分隔的项会按顺序( 从左到右 )填充到前面的占位符
如果是使用 : 来分隔后面的待填充项的话, 第一个 : 后面的项会填充到 %0, 第二个: 后面的项会填充到 %1, 依次类推 ( 使用 : 来分隔多用于前面的占位符没有按顺序排放)

添加新的运算类型( DOT8 )代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
diff --git a/sim/simx/types.h b/sim/simx/types.h
index d069bdae..3182c33c 100644
--- a/sim/simx/types.h
─+++ b/sim/simx/types.h
@@ -169,7 +169,8 @@ enum class AluType {
   AND,
   OR,
   XOR,
-  CZERO
+  CZERO,
+  DOT8
 };
 
 struct IntrAluArgs {
@@ -193,6 +194,7 @@ inline std::ostream &operator<<(std::ostream &os, const AluType& type) {
   case AluType::OR:      os << "OR"; break;
   case AluType::XOR:     os << "XOR"; break;
   case AluType::CZERO:   os << "CZERO"; break;
+  case AluType::DOT8:    os << "DOT8"; break;
   default:
     assert(false);
   }

types.h 中有很多 operator, 这些operator, 使用了多态的特性, 由于我们是在 AluType 结构体中添加的DOT8, 我们选择在输入参数类型为 AluType 的 operator 中添加 DOT8 的返回字符串

添加解码相关的代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
diff --git a/sim/simx/decode.cpp b/sim/simx/decode.cpp
index f2d6cc35..9cb1157e 100644
--- a/sim/simx/decode.cpp
─+++ b/sim/simx/decode.cpp
@@ -112,6 +112,7 @@ static op_string_t op_string(const Instr &instr) {
         }
       }
       case AluType::CZERO: return {aluArgs.imm ? "CZERO.NEZ":"CZERO.EQZ", ""};
+      case AluType::DOT8: return {"DOT8", ""};
       default:
         std::abort();
       }
@@ -1118,6 +1119,22 @@ void Emulator::decode(uint32_t code, uint32_t wid, uint64_t uuid) {
       }
     } break;
   #endif
+    case 9: {
+      switch (funct3) {
+      case 0: { // DOT8
+        auto instr = std::allocate_shared<Instr>(instr_pool_, uuid, FUType::ALU);
+        instr->setDestReg(rd, RegType::Integer);
+        instr->setSrcReg(0, rs1, RegType::Integer);
+        instr->setSrcReg(1, rs2, RegType::Integer);
+        instr->setOpType(AluType::DOT8);
+        ibuffer.push_back(instr);
+      } break;
+
+      default:
+        std::abort();
+      }
+    } break;
+
     default:
       std::abort();
     }

因为我们在定义 dot8 指令的时候把 funt7 设为9, funt3 设为0, 这里直接在对应位置添加一个 case9 分支
rs1, rs2 的值已经在上面就计算好了, 这里只需要调用 setSrcReg 把rs1设置成第0 个源寄存器, 把rs2 设置成第1 个源寄存器即可
再把OpType 设置成 AluType::DOT8 类型, 这样在execute 模块就可以根据指令类型来直接具体的运算了

添加运行时的执行 dot8 命令的操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
diff --git a/sim/simx/execute.cpp b/sim/simx/execute.cpp
index 25ee6850..9f75c039 100644
--- a/sim/simx/execute.cpp
─+++ b/sim/simx/execute.cpp
@@ -300,6 +300,28 @@ instr_trace_t* Emulator::execute(const Instr &instr, uint32_t wid) {
           rd_data[t].i = cond ? 0 : rs1_data[t].i;
         }
       } break;
+      case AluType::DOT8: {
+          // DOT8
+          for (uint32_t t = thread_start; t < num_threads; ++t) {
+            if (!warp.tmask.test(t))
+              continue;
+            // 实现 8-bit 点积运算逻辑
+            // 假设是两个 32-bit 寄存器,每个包含 4 个 8-bit 值
+            uint32_t src0_val = rs1_data[t].u32;
+            uint32_t src1_val = rs2_data[t].u32;
+
+            int32_t result = 0;
+            for (int i = 0; i < 4; ++i) {
+              int8_t a = (src0_val >> (i * 8)) & 0xFF;
+              int8_t b = (src1_val >> (i * 8)) & 0xFF;
+              result += a * b;
+            }
+
+            rd_data[t].i = result;
+          }
+          rd_write = true;
+      } break;
+
       default:
         std::abort();
       }

添加运行 dot8 命令所需的延时信息

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
diff --git a/sim/simx/func_unit.cpp b/sim/simx/func_unit.cpp
index 42cbeb9a..ef6d65fc 100644
--- a/sim/simx/func_unit.cpp
─+++ b/sim/simx/func_unit.cpp
@@ -51,6 +51,7 @@ void AluUnit::tick() {
             case AluType::AND:
             case AluType::OR:
             case AluType::CZERO:
+            case AluType::DOT8:
                 delay = 2;
                 break;
             default:

修改 tests/regression/Makefile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
diff --git a/tests/regression/Makefile b/tests/regression/Makefile
index be3ccc96..8db25319 100644
--- a/tests/regression/Makefile
─+++ b/tests/regression/Makefile
@@ -21,6 +21,7 @@ all:
 	$(MAKE) -C sgemm2
 	$(MAKE) -C madmax
 	$(MAKE) -C stencil3d
+	$(MAKE) -C dot8
 
 run-simx:
 	$(MAKE) -C basic run-simx
@@ -42,6 +43,7 @@ run-simx:
 	$(MAKE) -C sgemm2 run-simx
 	$(MAKE) -C madmax run-simx
 	$(MAKE) -C stencil3d run-simx
+	$(MAKE) -C dot8 run-simx
 
 run-rtlsim:
 	$(MAKE) -C basic run-rtlsim
@@ -63,6 +65,7 @@ run-rtlsim:
 	$(MAKE) -C sgemm2 run-rtlsim
 	$(MAKE) -C madmax run-rtlsim
 	$(MAKE) -C stencil3d run-rtlsim
+	$(MAKE) -C dot8 run-rtlsim
 
 clean:
 	$(MAKE) -C basic clean
@@ -84,3 +87,4 @@ clean:
 	$(MAKE) -C sgemm2 clean
 	$(MAKE) -C madmax clean
 	$(MAKE) -C stencil3d clean
+	$(MAKE) -C dot8 clean

添加make dot8 的入口

添加 dot8 测试用例

参考: Exercise5_9cd0e_83fe7.patch 里的 regression/dot8 的改动
该 dot8 测试用例是参考 regression/sgemm 改的, 主要改动有以下几点:

  1. 在common.h 中把 TYPE 改为 int8_t
  2. 在main.cpp 中实现 类型为 int8_t 的 Comparator 类, 该类包含了产生int8_t 类型的随机数以及比较两个int 数据的方法
  3. 在main.cpp 中修改 matmul_cpu 函数, 计算参考结果用于对比 vx_dot8 命令计算出的结果
  4. 在 kernel.cpp 实现 MatrixMultiply 函数, 最终调用 vx_dot8 命令实现两个8 位数的相乘, 并在 kernel_body 中调用MatrixMultiply

调试技巧

如果 runtime/simx 目录下的代码有改动, 需要先进入 build/runtime/simx 执行 make clean 再 make 重新生成运行时的库
看日志文件可以使用 lnav, 看起来效率高一些

运行测试

1
2
3
4
cd build
../configure --xlen=32 --tooldir=$HOME/tools   # 构建 build 目录, 生成 makefile 等文件,把必要的文件拷贝到build目录
make -j32 -s
./ci/blackbox.sh --cores=1 --app=dot8 --driver=simx --args="-n4"

由于新加了 dot8 目录, 必须要先执行 configure 才可以在build 目录生成必要的文件

Licensed under CC BY-NC-SA 4.0