Skip to content

Commit 1446acd

Browse files
AdUhTkJmmengzhuo
authored andcommitted
Add primitive add_string
1 parent 441b774 commit 1446acd

File tree

4 files changed

+45
-1
lines changed

4 files changed

+45
-1
lines changed

src/riscv_generate.ml

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,6 +449,50 @@ let deal_with_prim tac rd (prim: Primitive.prim) args =
449449
(* Load from the offset plus 4 for the tag *)
450450
Vec.push tac (Load { rd; rs = arg; offset = offset + 4; byte = size })
451451

452+
(* There is a bunch of `Pccall`s used in primitive.ml *)
453+
(* We'll match each function name separately *)
454+
| Pccall { func_name = "add_string" } ->
455+
let s1 = List.nth args 0 in
456+
let s2 = List.nth args 1 in
457+
458+
(* First load their lengths *)
459+
let l1 = new_temp Mtype.T_int in
460+
let l2 = new_temp Mtype.T_int in
461+
Vec.push tac (Load { rd = l1; rs = s1; offset = -4; byte = 4 });
462+
Vec.push tac (Load { rd = l2; rs = s2; offset = -4; byte = 4 });
463+
464+
(* Multiply them by sizeof(char) *)
465+
let char_size = new_temp Mtype.T_int in
466+
let new_len = new_temp Mtype.T_int in
467+
Vec.push tac (AssignInt { rd = char_size; imm = sizeof Mtype.T_char });
468+
Vec.push tac (Add { rd = new_len; rs1 = l2; rs2 = l1 });
469+
470+
(* Calculate the new length *)
471+
let space_size = new_temp Mtype.T_int in
472+
Vec.push tac (Mul { rd = space_size; rs1 = new_len; rs2 = char_size });
473+
Vec.push tac (Addi { rd = space_size; rs = space_size; imm = sizeof Mtype.T_int });
474+
475+
(* Then allocate the correct amount of space *)
476+
let space = new_temp Mtype.T_bytes in
477+
Vec.push tac (CallExtern { rd = space; fn = "malloc"; args = [space_size] });
478+
479+
(* Store the length and add the offset *)
480+
Vec.push tac (Store { rd = new_len; rs = space; offset = 0; byte = 4 });
481+
Vec.push tac (Addi { rd = space; rs = space; imm = 4 });
482+
483+
(* Now copy the values into it *)
484+
Vec.push tac (Mul { rd = l1; rs1 = l1; rs2 = char_size });
485+
Vec.push tac (Mul { rd = l2; rs1 = l2; rs2 = char_size });
486+
487+
Vec.push tac (CallExtern { rd = unit; fn = "memcpy"; args = [space; s1; l1] });
488+
489+
let ptr = new_temp Mtype.T_bytes in
490+
Vec.push tac (Add { rd = ptr; rs1 = space; rs2 = l1 });
491+
Vec.push tac (CallExtern { rd = unit; fn = "memcpy"; args = [ptr; s2; l2] });
492+
493+
(* Store the space into rd *)
494+
Vec.push tac (Assign { rd; rs = space })
495+
452496
| Pignore ->
453497
Vec.push tac (Assign { rd; rs = unit })
454498

test/src/match01/match01.ans

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ one or two
33
one or two
44
three
55
four
6-
other: 4
6+
other: 5

0 commit comments

Comments
 (0)