Commit 1a5e808c authored by 艾琮焜's avatar 艾琮焜

lab3

parent 8ca8504d
......@@ -39,6 +39,7 @@ INCLUDE_DIRECTORIES(
include/cminusfc
include/common
include/lightir
include/codegen
${LLVM_INCLUDE_DIRS}
)
......
#pragma once
#include <cassert>
#include <string>
struct ASMInstruction {
enum InstType { Instruction, Atrribute, Label, Comment } type;
std::string content;
explicit ASMInstruction(std::string s, InstType ty = Instruction)
: type(ty), content(s) {}
std::string format() const {
switch (type) {
case ASMInstruction::Instruction:
case ASMInstruction::Atrribute:
return "\t" + content + "\n";
case ASMInstruction::Label:
return content + ":\n";
case ASMInstruction::Comment:
return "# " + content + "\n";
}
assert(false && "unreachable");
}
};
#pragma once
#include "ASMInstruction.hpp"
#include "Module.hpp"
#include "Register.hpp"
class CodeGen {
public:
explicit CodeGen(Module *module) : m(module) {}
std::string print() const;
void run();
template <class... Args> void append_inst(Args... arg) {
output.emplace_back(arg...);
}
void
append_inst(const char *inst, std::initializer_list<std::string> args,
ASMInstruction::InstType ty = ASMInstruction::Instruction) {
auto content = std::string(inst) + " ";
for (const auto &arg : args) {
content += arg + ", ";
}
content.pop_back();
content.pop_back();
output.emplace_back(content, ty);
}
private:
void allocate();
void copy_stmt(); // for phi copy
// 向寄存器中装载数据
void load_to_greg(Value *, const Reg &);
void load_to_freg(Value *, const FReg &);
void load_from_stack_to_greg(Value *, const Reg &);
// 向寄存器中加载立即数
void load_large_int32(int32_t, const Reg &);
void load_large_int64(int64_t, const Reg &);
void load_float_imm(float, const FReg &);
// 将寄存器中的数据保存回栈上
void store_from_greg(Value *, const Reg &);
void store_from_freg(Value *, const FReg &);
void gen_prologue();
void gen_ret();
void gen_br();
void gen_binary();
void gen_float_binary();
void gen_alloca();
void gen_load();
void gen_store();
void gen_icmp();
void gen_fcmp();
void gen_zext();
void gen_call();
void gen_gep();
void gen_sitofp();
void gen_fptosi();
void gen_epilogue();
static std::string label_name(BasicBlock *bb) {
return "." + bb->get_parent()->get_name() + "_" + bb->get_name();
}
static std::string func_exit_label_name(Function *func) {
return func->get_name() + "_exit";
}
static std::string fcmp_label_name(BasicBlock *bb, unsigned cnt) {
return label_name(bb) + "_fcmp_" + std::to_string(cnt);
}
struct {
/* 随着ir遍历设置 */
Function *func{nullptr}; // 当前函数
BasicBlock *bb{nullptr}; // 当前基本块
Instruction *inst{nullptr}; // 当前指令
/* 在allocate()中设置 */
unsigned frame_size{0}; // 当前函数的栈帧大小
std::unordered_map<Value *, int> offset_map{}; // 指针相对 fp 的偏移
unsigned fcmp_cnt{0}; // fcmp 的计数器, 用于创建 fcmp 需要的 label
void clear() {
func = nullptr;
bb = nullptr;
inst = nullptr;
frame_size = 0;
fcmp_cnt = 0;
offset_map.clear();
}
} context;
Module *m;
std::list<ASMInstruction> output;
};
#pragma once
#include <stdexcept>
/* 关于位宽 */
#define IMM_12_MAX 0x7FF
#define IMM_12_MIN -0x800
#define LOW_12_MASK 0x00000FFF
#define LOW_20_MASK 0x000FFFFF
#define LOW_32_MASK 0xFFFFFFFF
inline unsigned ALIGN(unsigned x, unsigned alignment) {
return ((x + (alignment - 1)) & ~(alignment - 1));
}
inline bool IS_IMM_12(int x) { return x <= IMM_12_MAX and x >= IMM_12_MIN; }
/* 栈帧相关 */
#define PROLOGUE_OFFSET_BASE 16 // $ra $fp
#define PROLOGUE_ALIGN 16
/* 龙芯指令 */
// Arithmetic
#define ADD "add"
#define SUB "sub"
#define MUL "mul"
#define DIV "div"
#define ADDI "addi"
#define FADD "fadd"
#define FSUB "fsub"
#define FMUL "fmul"
#define FDIV "fdiv"
#define ORI "ori"
#define LU12I_W "lu12i.w"
#define LU32I_D "lu32i.d"
#define LU52I_D "lu52i.d"
// Data transfer (greg <-> freg)
#define GR2FR "movgr2fr"
#define FR2GR "movfr2gr"
// Memory access
#define LOAD "ld"
#define STORE "st"
#define FLOAD "fld"
#define FSTORE "fst"
#define BYTE ".b"
#define HALF_WORD ".h"
#define WORD ".w"
#define DOUBLE ".d"
#define SINGLE ".s" // float
#define LONG ".l"
// ASM syntax sugar
#define LOAD_ADDR "la.local"
// errors
class not_implemented_error : public std::logic_error {
public:
explicit not_implemented_error(std::string &&err_msg = "")
: std::logic_error(err_msg){};
};
class unreachable_error : public std::logic_error {
public:
explicit unreachable_error(std::string &&err_msg = "")
: std::logic_error(err_msg){};
};
#pragma once
#include <cassert>
#include <string>
/* General-purpose Register Convention:
* Name Alias Meaning
* $r0 $zero constant 0
* $r1 $ra return address
* $r2 $tp thread pointer
* $r3 $sp stack pointer
* $r4 - $r5 $a0 - $a1 argument, return value
* $r6 - $r11 $a2 - $a7 argument
* $r12 - $r20 $t0 - $t8 temporary
* $r21 saved
* $r22 $fp / $s9 frame pointer
* $r23 - $r31 $s0 - $s8 static
*
* Floating-point Register Convention
* Name Alias Meaning
* $f0-$f1 $fa0-$fa1 argument/return value
* $f2-$f7 $fa2-$fa7 argument
* $f8-$f23 $ft0-$ft15 temporary
* $f24-$f31 $fs0-$fs7 static
*/
struct Reg {
unsigned id;
explicit Reg(unsigned i) : id(i) { assert(i <= 31); }
bool operator==(const Reg &other) { return id == other.id; }
std::string print() const;
static Reg zero() { return Reg(0); }
static Reg ra() { return Reg(1); }
static Reg sp() { return Reg(3); }
static Reg fp() { return Reg(22); }
static Reg a(unsigned i) {
assert(0 <= i and i <= 7);
return Reg(i + 4);
}
static Reg t(unsigned i) {
assert(0 <= i and i <= 8);
return Reg(i + 12);
}
static Reg s(unsigned i) {
assert(0 <= i and i <= 9);
if (i == 9)
return Reg(22);
else
return Reg(i + 23);
}
};
struct FReg {
unsigned id;
explicit FReg(unsigned i) : id(i) { assert(i <= 31); }
bool operator==(const FReg &other) { return id == other.id; }
std::string print() const;
static FReg fa(unsigned i) {
assert(0 <= i and i <= 7);
return FReg(i);
}
static FReg ft(unsigned i) {
assert(0 <= i and i <= 15);
return FReg(i + 8);
}
static FReg fs(unsigned i) {
assert(0 <= i and i <= 7);
return FReg(i + 24);
}
};
struct CFReg {
unsigned id;
explicit CFReg(unsigned i) : id(i) { assert(i <= 7); }
bool operator==(const CFReg &other) { return id == other.id; }
std::string print() const { return "$fcc" + std::to_string(id); }
};
......@@ -3,4 +3,5 @@ add_subdirectory(common)
add_subdirectory(logging)
add_subdirectory(cminusfc)
add_subdirectory(lightir)
add_subdirectory(io)
\ No newline at end of file
add_subdirectory(io)
add_subdirectory(codegen)
......@@ -8,6 +8,7 @@ target_link_libraries(
cminusfc
IR_lib
common
codegen
syntax
stdc++fs
)
......
#include "Module.hpp"
#include "ast.hpp"
#include "cminusf_builder.hpp"
#include "CodeGen.hpp"
#include <filesystem>
#include <fstream>
......@@ -16,6 +17,7 @@ struct Config {
std::filesystem::path output_file;
bool emitast{false};
bool emitasm{false};
bool emitllvm{false};
Config(int argc, char **argv) : argc(argc), argv(argv) {
......@@ -55,9 +57,13 @@ int main(int argc, char **argv) {
output_stream << "; ModuleID = 'cminus'\n";
output_stream << "source_filename = " << abs_path << "\n\n";
output_stream << m->print();
} else if (config.emitasm) {
CodeGen codegen(m.get());
codegen.run();
output_stream << codegen.print();
}
// TODO: lab3 lab4 (IR optimization or codegen)
// TODO: lab4 (IR optimization)
}
return 0;
......@@ -79,6 +85,8 @@ void Config::parse_cmd_line() {
emitast = true;
} else if (argv[i] == "-emit-llvm"s) {
emitllvm = true;
} else if (argv[i] == "-S"s) {
emitasm = true;
} else {
if (input_file.empty()) {
input_file = argv[i];
......@@ -102,6 +110,8 @@ void Config::check() {
*/
if (output_file.empty()) {
output_file = input_file.stem();
if (emitasm && !emitllvm && !emitast)
output_file += ".s";
}
}
......
add_library(
codegen STATIC
CodeGen.cpp
Register.cpp
)
target_link_libraries(codegen common IR_lib)
This diff is collapsed.
#include "Register.hpp"
#include <string>
std::string Reg::print() const {
if (id == 0) {
return "$zero";
}
if (id == 1) {
return "$ra";
}
if (id == 2) {
return "$tp";
}
if (id == 3) {
return "$sp";
}
if (4 <= id and id <= 11) {
return "$a" + std::to_string(id - 4);
}
if (12 <= id and id <= 20) {
return "$t" + std::to_string(id - 12);
}
if (id == 22) {
return "$fp";
}
assert(false);
}
std::string FReg::print() const {
if (0 <= id and id <= 7) {
return "$fa" + std::to_string(id);
}
if (8 <= id and id <= 23) {
return "$ft" + std::to_string(id - 8);
}
if (24 <= id and id <= 31) {
return "$fs" + std::to_string(id - 24);
}
assert(false);
}
# 2026 实验三:LoongArch64 代码生成
本目录提供实验三的框架、热身练习及自动测试。实验三以完成实验一的解析器和实验二的 IR 生成为前提。
## 需要完成的内容
- `warmup/stu_cpp/`:按照注释完成 6 个热身程序,输入 IR 见 `warmup/ll_cases/`。
- `../../src/codegen/CodeGen.cpp`:补全标有 TODO 的指令翻译和函数调用、返回等逻辑。
- `../../include/codegen/`:汇编输出、寄存器和辅助接口。
热身程序保留了待填空的代码。完成前置实验和热身程序后,在仓库根目录默认构建即可生成六个热身可执行文件,例如:
```bash
cmake -S . -B build
cmake --build build
./build/stu_assign_codegen > assign.s
```
其他热身目标为 `stu_function_codegen`、`stu_icmp_codegen`、`stu_fcmp_codegen`、`stu_float_codegen` 和 `stu_global_codegen`。
## 编译器入口
完成前置实验后,在仓库根目录构建编译器:
```bash
cmake -S . -B build
cmake --build build --target cminusfc
./build/cminusfc -S input.cminus -o output.s
```
省略 `-o` 时,`./build/cminusfc -S input.cminus` 默认生成 `input.s`。
`-emit-ast` 和 `-emit-llvm` 的现有入口保留。后端框架尚未实现的部分会抛出 `not_implemented_error`,需要完成 TODO 后才能运行相关程序。
## 自动测试
需要安装 `loongarch64-unknown-linux-gnu-gcc` 和 `qemu-loongarch64`。在以下目录运行测试脚本:
```bash
cd tests/3-codegen/autogen
./eval_lab3.sh ./testcases debug
# 也可以运行通用测试集
./eval_lab3.sh ../../testcases_general test
```
`debug` 模式额外保存 LLVM IR。脚本生成 LoongArch64 汇编,交叉编译并使用 QEMU 执行,将标准输出和退出码与 `.out` 文件比较。生成文件在 `output/`,详细日志为 `log.txt`。
```bash
./cleanup.sh
```
#!/bin/bash
rm -rf output log.txt
#!/bin/bash
project_dir=$(realpath ../../../)
io_dir=$(realpath "$project_dir"/src/io)
output_dir=output
suffix=cminus
LOG=log.txt
usage() {
cat <<JIANMU
Usage: $0 [path-to-testcases] [type]
path-to-testcases: './testcases' or '../../testcases_general' or 'self made cases'
type: 'debug' or 'test', debug will output .ll file
JIANMU
exit 0
}
check_return_value() {
rv=$1
expected_rv=$2
fail_msg=$3
detail=$4
if [ "$rv" -eq "$expected_rv" ]; then
return 0
else
printf "\033[1;31m%s: \033[0m%s\n" "$fail_msg" "$detail"
return 1
fi
}
# check arguments
[ $# -lt 2 ] && usage
if [ "$2" == "debug" ]; then
debug_mode=true
elif [ "$2" == "test" ]; then
debug_mode=false
else
usage
fi
test_dir=$1
testcases=$(ls "$test_dir"/*."$suffix" | sort -V)
check_return_value $? 0 "PATH" "unable to access to '$test_dir'" || exit 1
# hide stderr in the script
# exec 2>/dev/null
mkdir -p $output_dir
truncate -s 0 $LOG
if [ $debug_mode = false ]; then
exec 3>/dev/null 4>&1 5>&2 1>&3 2>&3
else
exec 3>&1
fi
if [ $debug_mode = false ]; then
exec 1>&4 2>&5
fi
echo "[info] Start testing, using testcase dir: $test_dir"
# asm
for case in $testcases; do
echo "==========$case==========" >>$LOG
case_base_name=$(basename -s .$suffix "$case")
std_out_file=$test_dir/$case_base_name.out
in_file=$test_dir/$case_base_name.in
asm_file=$output_dir/$case_base_name.s
exe_file=$output_dir/$case_base_name
out_file=$output_dir/$case_base_name.out
ll_file=$output_dir/$case_base_name.ll
echo -n "$case_base_name..."
# if debug mode on, generate .ll also
if [ $debug_mode = true ]; then
bash -c "${project_dir}/build/cminusfc -emit-llvm $case -o $ll_file" >>$LOG 2>&1
fi
# cminusfc compile to .s
bash -c "${project_dir}/build/cminusfc -S $case -o $asm_file" >>$LOG 2>&1
check_return_value $? 0 "CE" "cminusfc compiler error" || continue
# gcc compile asm to executable
loongarch64-unknown-linux-gnu-gcc -static \
"$asm_file" "$io_dir"/io.c -o "$exe_file" \
>>$LOG
check_return_value $? 0 "CE" "gcc compiler error" || continue
# qemu run
if [ -e "$in_file" ]; then
exec_cmd="qemu-loongarch64 $exe_file >$out_file <$in_file"
else
exec_cmd="qemu-loongarch64 $exe_file >$out_file"
fi
bash -c "$exec_cmd"
ret=$?
# remove trailing null byte in the end line
sed -i "\$s/\x00*$//" "$out_file"
# append return value
echo $ret >>"$out_file"
# compare output
diff --strip-trailing-cr "$std_out_file" "$out_file" -y >>$LOG
check_return_value $? 0 "WA" "output differ, check $std_out_file and $out_file" || continue
# ok
printf "\033[1;32mOK\033[0m\n"
done
int main(void) {
output(input());
return 0;
}
int main(void) {
output(111);
return 111;
}
int main(void) {
float a;
float b;
float c;
a = 1.1;
b = 1.5;
c = 1.2;
outputFloat(a * b + c);
return 0;
}
/*
用 gcc 编译此文件生成汇编代码时,命令为 gcc -include io.h -S 10-float.c
其中 io.h 位于 src/io/io.h,
也可以在本文件开头加上 void outputFloat(float x);
*/
/* float function call */
float mod(float x, float y) {
int div;
div = x / y;
return x - div * y;
}
int main(void) {
float a;
float b;
a = 11.2;
b = 2.2;
outputFloat(mod(a, b));
return 0;
}
int seed;
int randomLCG(void) {
seed = seed * 1103515245 + 12345;
return seed;
}
int randBin(void) {
if (randomLCG() > 0)
return 1;
else
return 0;
}
/* random walk */
int returnToZeroSteps(void) {
int x;
int steps;
x = 0;
steps = 0;
while (steps < 20) {
if (randBin())
x = x + 1;
else
x = x - 1;
steps = steps + 1;
if (x == 0)
return steps;
}
return 20;
}
int main(void) {
int i;
i = 0;
seed = 3407;
while (i < 20) {
output(returnToZeroSteps());
i = i + 1;
}
return 0;
}
4
2
2
4
8
2
2
2
2
2
6
2
10
8
4
2
20
2
2
8
0
/* 01 背包问题 */
int n;
int m;
int w[5];
int v[5];
int dp[66]; /* dp[n * 11 + size] 表示前 n 个物品放入容量为 size 的背包中的最大价值,初始化为 -1 */
int max(int a, int b) {
if (a > b)
return a;
else
return b;
}
/* 状态转移方程:
dp[n][size] = max(dp[n - 1][size], dp[n - 1][size - w[n]] + v[n])
边界条件:
dp[n][size <= 0] = 0
dp[0][size] = 0 */
int knapsack(int n, int size) {
int result;
if (size <= 0)
return 0;
if (n == 0)
return 0;
if (dp[n * 11 + size] >= 0)
return dp[n * 11 + size];
if (size < w[n - 1])
result = knapsack(n - 1, size);
else
result = max(knapsack(n - 1, size), knapsack(n - 1, size - w[n - 1]) + v[n - 1]);
dp[n * 11 + size] = result;
return result;
}
int main(void) {
int i;
i = 0;
n = 5;
m = 10;
w[0] = 2;
w[1] = 2;
w[2] = 6;
w[3] = 5;
w[4] = 4;
v[0] = 6;
v[1] = 3;
v[2] = 5;
v[3] = 4;
v[4] = 6;
while (i < 66) {
dp[i] = 0 - 1;
i = i + 1;
}
output(knapsack(n, m));
return 0;
}
int main(void) {
int a;
int b;
int c;
a = 23;
b = 25;
c = 4;
return a + b * c;
}
int main(void) {
output(11);
output(22222);
return 0;
}
int main(void) {
int a;
int b;
int c;
a = 11;
b = 22;
c = 33;
/* max value */
if (a > b) {
if (a > c)
output(a);
else
output(c);
} else {
if (c < b)
output(b);
else
output(c);
}
return 0;
}
int main(void) {
int n;
int i;
n = 10;
i = 0;
while (i < n) {
output(i);
i = i + 1;
}
return 0;
}
int main(void) {
int a[10];
int i;
i = 0;
a[0] = 11;
a[4] = 22;
a[9] = 33;
output(a[0]);
output(a[4]);
output(a[9]);
return 0;
}
int min(int a, int b) {
if (a <= b)
return a;
else
return b;
}
int main(void) {
int a;
int b;
int c;
a = 11;
b = 22;
c = 33;
output(min(a, b));
output(min(b, c));
output(min(c, a));
return 0;
}
int store(int arr[], int index, int value) {
arr[index] = value;
return value;
}
int main(void) {
int a[10];
int i;
int sum;
i = 0;
while (i < 10) {
store(a, i, i * 2);
i = i + 1;
}
sum = 0;
i = 0;
while (i < 10) {
sum = sum + a[i];
i = i + 1;
}
output(sum);
return 0;
}
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main(void) {
int n;
int i;
n = 10;
i = 0;
while (i < n) {
output(fibonacci(i));
i = i + 1;
}
return 0;
}
add_executable(
stu_assign_codegen
stu_cpp/assign_codegen.cpp
)
target_link_libraries(
stu_assign_codegen
IR_lib
codegen
)
add_executable(
stu_function_codegen
stu_cpp/function_codegen.cpp
)
target_link_libraries(
stu_function_codegen
IR_lib
codegen
)
add_executable(
stu_icmp_codegen
stu_cpp/icmp_codegen.cpp
)
target_link_libraries(
stu_icmp_codegen
IR_lib
codegen
)
add_executable(
stu_fcmp_codegen
stu_cpp/fcmp_codegen.cpp
)
target_link_libraries(
stu_fcmp_codegen
IR_lib
codegen
)
add_executable(
stu_float_codegen
stu_cpp/float_codegen.cpp
)
target_link_libraries(
stu_float_codegen
IR_lib
codegen
)
add_executable(
stu_global_codegen
stu_cpp/global_codegen.cpp
)
target_link_libraries(
stu_global_codegen
IR_lib
codegen
)
define i32 @main() {
label_entry:
%op0 = alloca [10 x i32]
%op1 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 0
store i32 10, i32* %op1
%op2 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 1
%op3 = load i32, i32* %op1
%op4 = mul i32 %op3, 3
store i32 %op4, i32* %op2
%op5 = load i32, i32* %op2
ret i32 %op5
}
define i32 @main() {
label_entry:
; 5.5 (0x40b00000) > 1.0 (0x3f800000)
%op0 = fcmp ugt float 0x4016000000000000, 0x3ff0000000000000
%op1 = zext i1 %op0 to i32
%op2 = icmp ne i32 %op1, 0
br i1 %op2, label %label3, label %label4
label3: ; preds = %label_entry
ret i32 233
label4: ; preds = %label_entry
ret i32 0
}
define i32 @main() {
label_entry:
%op0 = alloca float
store float 0x40091eb860000000, float* %op0 ; 3.14, FP32 0x4048f5c3
%op1 = load float, float* %op0
%op2 = fptosi float %op1 to i32
ret i32 %op2
}
define i32 @callee(i32 %arg0) {
label_entry:
%op1 = alloca i32
store i32 %arg0, i32* %op1
%op2 = load i32, i32* %op1
%op3 = mul i32 3, %op2
ret i32 %op3
}
define i32 @main() {
label_entry:
%op0 = call i32 @callee(i32 110)
ret i32 %op0
}
@a = global i32 zeroinitializer
define i32 @main() {
label_entry:
store i32 10, i32* @a
%op0 = load i32, i32* @a
ret i32 %op0
}
define i32 @main() {
label_entry:
%op0 = icmp sgt i32 5, 1
%op1 = zext i1 %op0 to i32
%op2 = icmp ne i32 %op1, 0
br i1 %op2, label %label3, label %label4
label3: ; preds = %label_entry
ret i32 233
label4: ; preds = %label_entry
ret i32 0
}
#include "ASMInstruction.hpp"
#include "CodeGen.hpp"
#include "Module.hpp"
#include <iostream>
#include <memory>
#include <unordered_map>
void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码
int main() {
auto *module = new Module();
auto *codegen = new CodeGen(module);
// 告诉汇编器将汇编放到代码段
codegen->append_inst(".text", ASMInstruction::Atrribute);
translate_main(codegen);
std::cout << codegen->print();
delete codegen;
delete module;
return 0;
}
// TODO: 按照提示补全
void translate_main(CodeGen *codegen) {
std::unordered_map<std::string, int> offset_map;
/* 声明 main 函数 */
codegen->append_inst(".globl main", ASMInstruction::Atrribute);
codegen->append_inst(".type main, @function", ASMInstruction::Atrribute);
/* main 函数开始 */
codegen->append_inst("main", ASMInstruction::Label); // main 函数标签
/* main 函数的 Prologue (序言) */
// 保存返回地址
codegen->append_inst("st.d $ra, $sp, -8");
// 保存老的 fp
codegen->append_inst("st.d $fp, $sp, -16");
// 设置新的 fp
codegen->append_inst("addi.d $fp, $sp, 0");
// 为栈帧分配空间. 思考: 为什么是 96 字节?
codegen->append_inst("addi.d $sp, $sp, -96");
/* main 函数的 label_entry */
codegen->append_inst(".main_label_entry", ASMInstruction::Label);
/* %op0 = alloca [10 x i32] */
// 在汇编中写入注释, 方便 debug
codegen->append_inst("%op0 = alloca [10 x i32]", ASMInstruction::Comment);
// 将数组的地址写入 %op0 对应的内存空间中
// 首先计算数组的地址对应的偏移量, 按照我们在栈式分配中介绍的规则, 数组的空
// 间紧挨着 %op0 的空间, 数组的地址为这段空间的最小值.
// 然后将数组的地址写入 %op0 对应的内存空间中.
// 你需要思考:
// - %op0 的大小是多少字节?
// - %op0 的偏移量是多少字节?
// - 数组的大小是多少字节?
// - 数组的偏移量是多少字节?
offset_map["%op0"] = ; // TODO: 请填空
offset_map["array"] = ; // TODO: 请填空
codegen->append_inst("addi.d",
{"$t0", "$fp", std::to_string(offset_map["array"])});
codegen->append_inst("st.d",
{"$t0", "$fp", std::to_string(offset_map["%op0"])});
/* %op1 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 0 */
codegen->append_inst(
"%op1 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 0",
ASMInstruction::Comment);
// 将 gep 的值写入 %op1 对应的内存空间中
// 你可以手动计算 gep 的值, 或者使用指令计算 gep 的值
// 你需要思考 %op1 的偏移量是多少字节
offset_map["%op1"] = ; // TODO: 请填空
// 获得数组的地址, 将其写入 $t0 中
codegen->append_inst("ld.d",
{"$t0", "$fp", std::to_string(offset_map["%op0"])});
// TODO: 计算 %op1 的值, 并将其写入 %op1 对应的内存空间中
codegen->append_inst("");
/* store i32 10, i32* %op1 */
codegen->append_inst("store i32 10, i32* %op1", ASMInstruction::Comment);
// 将 10 写入数组 (%op1 指向的空间) 中, 需要先获得 %op1 的值
codegen->append_inst("ld.d",
{"$t0", "$fp", std::to_string(offset_map["%op1"])});
codegen->append_inst("addi.w $t1, $zero, 10");
codegen->append_inst("st.w $t1, $t0, 0");
/* %op2 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 1 */
codegen->append_inst(
"%op2 = getelementptr [10 x i32], [10 x i32]* %op0, i32 0, i32 1",
ASMInstruction::Comment);
// 将 gep 的值写入 %op2 对应的内存空间中
// 你可以手动计算 gep 的值, 或者使用指令计算 gep 的值
// 你需要思考 %op2 的偏移量是多少字节
offset_map["%op2"] = ; // TODO: 请填空
// 获得数组的地址, 将其写入 $t0 中
codegen->append_inst("ld.d",
{"$t0", "$fp", std::to_string(offset_map["%op0"])});
// TODO: 计算 gep 的值, 并将其写入 %op2 对应的内存空间中
codegen->append_inst("");
/* %op3 = load i32, i32* %op1 */
codegen->append_inst("%op3 = load i32, i32* %op1", ASMInstruction::Comment);
// 将 %op1 指向的空间中存储的值写入 %op3 对应的内存空间中
offset_map["%op3"] = ; // TODO: 请填空
// TODO: 先获得 %op1 的值, 然后获得 %op1 指向的空间的值, 最后将这个值写入
// %op3 对应的内存空间中
codegen->append_inst("");
/* %op4 = mul i32 %op3, 3 */
codegen->append_inst("%op4 = mul i32 %op3, 3", ASMInstruction::Comment);
offset_map["%op4"] = ; // TODO: 请填空
// TODO: 先获得 %op3 的值, 然后将其乘以 3, 最后将结果写入 %op4 对应的内存空
// 间中
codegen->append_inst("");
/* store i32 %op4, i32* %op2 */
codegen->append_inst("store i32 %op4, i32* %op2", ASMInstruction::Comment);
// 将 %op4 的值写入 %op2 指向的空间中
// TODO: 先获得 %op4 的值, 然后将其写入 %op2 指向的空间中
codegen->append_inst("");
/* %op5 = load i32, i32* %op2 */
// 将 %op2 指向的空间中存储的值写入 %op5 对应的内存空间中
offset_map["%op5"] = ; // TODO: 请填空
// TODO: 先获得 %op2 的值, 然后获得 %op2 指向的空间的值, 最后将这个值写入
// %op5 对应的内存空间中
codegen->append_inst("");
/* ret i32 %op5 */
codegen->append_inst("ret i32 %op5", ASMInstruction::Comment);
// TODO: 将 %op5 的值写入 $a0 中
codegen->append_inst("");
// 思考: 为什么不在这里 jr $ra, 而是跳转到 main_exit?
codegen->append_inst("b main_exit");
/* main 函数的 Epilogue (收尾) */
codegen->append_inst("main_exit", ASMInstruction::Label);
// 释放栈帧空间
codegen->append_inst("addi.d $sp, $sp, 96");
// 恢复 ra
codegen->append_inst("ld.d $ra, $sp, -8");
// 恢复 fp
codegen->append_inst("ld.d $fp, $sp, -16");
// 返回
codegen->append_inst("jr $ra");
}
#include "ASMInstruction.hpp"
#include "CodeGen.hpp"
#include "Module.hpp"
#include <iostream>
#include <memory>
#include <unordered_map>
void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码
int main() {
auto *module = new Module();
auto *codegen = new CodeGen(module);
// 告诉汇编器将汇编放到代码段
codegen->append_inst(".text", ASMInstruction::Atrribute);
translate_main(codegen);
std::cout << codegen->print();
delete codegen;
delete module;
return 0;
}
// TODO: 按照提示补全
void translate_main(CodeGen *codegen) {
std::unordered_map<std::string, int> offset_map;
/* 声明 main 函数 */
codegen->append_inst(".globl main", ASMInstruction::Atrribute);
codegen->append_inst(".type main, @function", ASMInstruction::Atrribute);
/* main 函数开始 */
codegen->append_inst("main", ASMInstruction::Label); // main 函数标签
/* main 函数的 Prologue (序言) */
// 保存返回地址
codegen->append_inst("st.d $ra, $sp, -8");
// 保存老的 fp
codegen->append_inst("st.d $fp, $sp, -16");
// 设置新的 fp
codegen->append_inst("addi.d $fp, $sp, 0");
// 为栈帧分配空间. 思考: 为什么是 32 字节?
codegen->append_inst("addi.d $sp, $sp, -32");
/* main 函数的 label_entry */
codegen->append_inst(".main_label_entry", ASMInstruction::Label);
/* %op0 = fcmp ugt float 0x4016000000000000, 0x3ff0000000000000 */
// 在汇编中写入注释, 方便 debug
codegen->append_inst(
"%op0 = fcmp ugt float 0x4016000000000000, 0x3ff0000000000000",
ASMInstruction::Comment);
// 将比较结果写入 %op0 对应的内存空间中
offset_map["%op0"] = ; // TODO: 请填空
// TODO: 将 5.5 (0x40b00000) 加载到浮点寄存器中
codegen->append_inst("");
// TODO: 将 1.0 (0x3f800000) 加载到浮点寄存器中
codegen->append_inst("");
// TODO: 使用 fcmp.slt.s 进行比较, 比较结果在浮点标志寄存器中, 你需要思考
// 如何将浮点标志寄存器中的值写入内存. 提示: 尝试使用 bcnez 指令
codegen->append_inst("");
/* %op1 = zext i1 %op0 to i32 */
codegen->append_inst("%op1 = zext i1 %op0 to i32", ASMInstruction::Comment);
// 将 %op0 的值从 i1 类型转换为 i32 类型, 并将结果写入到 %op1 对应的内存空
// 间中
offset_map["%op1"] = ; // TODO: 请填空
// TODO: 获得 %op0 的值, 然后进行转换, 最后将结果写入 %op1
// 思考: 怎么转换? 需不需要显式地使用某些指令转换?
codegen->append_inst("");
/* %op2 = icmp ne i32 %op1, 0 */
codegen->append_inst("%op2 = icmp ne i32 %op1, 0", ASMInstruction::Comment);
// 比较 %op1 和 0, 并将结果写入 %op2 对应的内存空间中
offset_map["%op2"] = ; // TODO: 请填空
// TODO: 获得 %op1 的值, 然后进行比较, 最后将结果写入 %op2
// 思考: 如何比较? 能否不使用跳转指令计算结果?
// 提示: 尝试使用 xor/xori 和 slt/sltu/slti/sltui 计算比较结果
codegen->append_inst("");
/* br i1 %op2, label %label3, label %label4 */
codegen->append_inst("br i1 %op2, label %label3, label %label4",
ASMInstruction::Comment);
// TODO: 获得 %op2 的值, 并根据 %op2 的值跳转到 label3 或者 label4
// 提示: 汇编中对应的标签分别为 .main_label3 和 .main_label4
codegen->append_inst("");
/* label3: */
codegen->append_inst(".main_label3", ASMInstruction::Label);
/* ret i32 233 */
codegen->append_inst("ret i32 233", ASMInstruction::Comment);
// 将 233 写入 $a0 中
codegen->append_inst("addi.w $a0, $zero, 233");
codegen->append_inst("b main_exit");
/* label4: */
codegen->append_inst(".main_label4", ASMInstruction::Label);
/* ret i32 0 */
codegen->append_inst("ret i32 0", ASMInstruction::Comment);
// 将 0 写入 $a0 中
codegen->append_inst("addi.w $a0, $zero, 0");
codegen->append_inst("b main_exit");
/* main 函数的 Epilogue (收尾) */
codegen->append_inst("main_exit", ASMInstruction::Label);
// 释放栈帧空间
codegen->append_inst("addi.d $sp, $sp, 32");
// 恢复 ra
codegen->append_inst("ld.d $ra, $sp, -8");
// 恢复 fp
codegen->append_inst("ld.d $fp, $sp, -16");
// 返回
codegen->append_inst("jr $ra");
}
#include "ASMInstruction.hpp"
#include "CodeGen.hpp"
#include "Module.hpp"
#include <iostream>
#include <memory>
#include <unordered_map>
void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码
int main() {
auto *module = new Module();
auto *codegen = new CodeGen(module);
// 告诉汇编器将汇编放到代码段
codegen->append_inst(".text", ASMInstruction::Atrribute);
translate_main(codegen);
std::cout << codegen->print();
delete codegen;
delete module;
return 0;
}
// TODO: 按照提示补全
void translate_main(CodeGen *codegen) {
std::unordered_map<std::string, int> offset_map;
/* 声明 main 函数 */
codegen->append_inst(".globl main", ASMInstruction::Atrribute);
codegen->append_inst(".type main, @function", ASMInstruction::Atrribute);
/* main 函数开始 */
codegen->append_inst("main", ASMInstruction::Label); // main 函数标签
/* main 函数的 Prologue (序言) */
// 保存返回地址
codegen->append_inst("st.d $ra, $sp, -8");
// 保存老的 fp
codegen->append_inst("st.d $fp, $sp, -16");
// 设置新的 fp
codegen->append_inst("addi.d $fp, $sp, 0");
// 为栈帧分配空间. 思考: 为什么是 48 字节?
codegen->append_inst("addi.d $sp, $sp, -48");
/* main 函数的 label_entry */
codegen->append_inst(".main_label_entry", ASMInstruction::Label);
/* %op0 = alloca float */
// 在汇编中写入注释, 方便 debug
codegen->append_inst("%op0 = alloca float", ASMInstruction::Comment);
// 将浮点数的地址写入 %op0 对应的内存空间中
offset_map["%op0"] = ; // TODO: 请填空
offset_map["*%op0"] = ; // TODO: 请填空
codegen->append_inst("addi.d",
{"$t0", "$fp", std::to_string(offset_map["*%op0"])});
codegen->append_inst("st.d",
{"$t0", "$fp", std::to_string(offset_map["%op0"])});
/* store float 0x40091eb860000000, float* %op0 */
codegen->append_inst("store float 0x40091eb860000000, float* %op0",
ASMInstruction::Comment);
// 将 3.14 (0x4048f5c3) 写入 %op0 指向的内存空间中
// 获得 %op0 的值
codegen->append_inst("ld.d",
{"$t0", "$fp", std::to_string(offset_map["%op0"])});
// TODO: 将 0x4048f5c3 加载到通用寄存器或者浮点寄存器中
codegen->append_inst("");
// TODO: 将通用寄存器或者浮点寄存器中的值写入 %op0 对应的内存空间中
codegen->append_inst("");
/* %op1 = load float, float* %op0 */
codegen->append_inst("%op1 = load float, float* %op0",
ASMInstruction::Comment);
// TODO: 先获得 %op0 的值, 然后获得 %op0 指向的空间的值, 最后将这个值写入
// %op1 对应的内存空间中
offset_map["%op1"] = ; // TODO: 请填空
codegen->append_inst("");
/* %op2 = fptosi float %op1 to i32 */
codegen->append_inst("%op2 = fptosi float %op1 to i32",
ASMInstruction::Comment);
// TODO: 使用 ftintrz.w.s 指令进行转换, 并将结果写入 %op2 对应的内存空间中
offset_map["%op2"] = ; // TODO: 请填空
codegen->append_inst("");
/* ret i32 %op2 */
codegen->append_inst("ret i32 %op2", ASMInstruction::Comment);
// TODO: 将 %op2 的值写入 $a0 中
codegen->append_inst("");
codegen->append_inst("b main_exit");
/* main 函数的 Epilogue (收尾) */
codegen->append_inst("main_exit", ASMInstruction::Label);
// 释放栈帧空间
codegen->append_inst("addi.d $sp, $sp, 48");
// 恢复 ra
codegen->append_inst("ld.d $ra, $sp, -8");
// 恢复 fp
codegen->append_inst("ld.d $fp, $sp, -16");
// 返回
codegen->append_inst("jr $ra");
}
#include "ASMInstruction.hpp"
#include "CodeGen.hpp"
#include "Module.hpp"
#include <iostream>
#include <memory>
#include <unordered_map>
void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码
void translate_callee(CodeGen *codegen); // 将 callee 函数翻译为汇编代码
int main() {
auto *module = new Module();
auto *codegen = new CodeGen(module);
// 告诉汇编器将汇编放到代码段
codegen->append_inst(".text", ASMInstruction::Atrribute);
translate_callee(codegen);
translate_main(codegen);
std::cout << codegen->print();
delete codegen;
delete module;
return 0;
}
// TODO: 按照提示补全
void translate_callee(CodeGen *codegen) {
std::unordered_map<std::string, int> offset_map;
/* 声明 callee 函数 */
codegen->append_inst(".globl callee", ASMInstruction::Atrribute);
codegen->append_inst(".type callee, @function", ASMInstruction::Atrribute);
/* callee 函数开始 */
codegen->append_inst("callee", ASMInstruction::Label); // main 函数标签
/* callee 函数的 Prologue (序言) */
// 保存返回地址
codegen->append_inst("st.d $ra, $sp, -8");
// 保存老的 fp
codegen->append_inst("st.d $fp, $sp, -16");
// 设置新的 fp
codegen->append_inst("addi.d $fp, $sp, 0");
// 为栈帧分配空间. 思考: 为什么是 48 字节?
codegen->append_inst("addi.d $sp, $sp, -48");
// 为参数分配空间
offset_map["%arg0"] = ; // TODO: 请填空
codegen->append_inst("st.w",
{"$a0", "$fp", std::to_string(offset_map["%arg0"])});
/* callee 函数的 label_entry */
codegen->append_inst(".callee_label_entry", ASMInstruction::Label);
/* %op1 = alloca i32 */
// 在汇编中写入注释, 方便 debug
codegen->append_inst("%op1 = alloca i32", ASMInstruction::Comment);
// 将 alloca 的地址写入 %op1 对应的内存空间中
offset_map["%op1"] = ; // TODO: 请填空
offset_map["*%op1"] = ; // TODO: 请填空
codegen->append_inst("addi.d",
{"$t0", "$fp", std::to_string(offset_map["*%op1"])});
codegen->append_inst("st.d",
{"$t0", "$fp", std::to_string(offset_map["%op1"])});
/* store i32 %arg0, i32* %op1 */
codegen->append_inst("store i32 %arg0, i32* %op1", ASMInstruction::Comment);
// 将 %arg0 的值写入 %op1 对应的内存空间中
codegen->append_inst("ld.d",
{"$t0", "$fp", std::to_string(offset_map["%op1"])});
codegen->append_inst("ld.w",
{"$t1", "$fp", std::to_string(offset_map["%arg0"])});
codegen->append_inst("st.w $t1, $t0, 0");
/* %op2 = load i32, i32* %op1 */
codegen->append_inst("%op2 = load i32, i32* %op1", ASMInstruction::Comment);
// 将 %op1 对应的内存空间的值写入 %op2 对应的内存空间中
offset_map["%op2"] = ; // TODO: 请填空
codegen->append_inst("ld.d",
{"$t0", "$fp", std::to_string(offset_map["%op1"])});
codegen->append_inst("ld.w $t1, $t0, 0");
codegen->append_inst("st.w",
{"$t1", "$fp", std::to_string(offset_map["%op2"])});
/* %op3 = mul i32 3, %op2 */
codegen->append_inst("%op3 = mul i32 3, %op2", ASMInstruction::Comment);
// 将 %op2 的值乘以 3, 并将结果写入 %op3 对应的内存空间中
offset_map["%op3"] = ; // TODO: 请填空
codegen->append_inst("ld.w",
{"$t0", "$fp", std::to_string(offset_map["%op2"])});
codegen->append_inst("addi.w $t1, $zero, 3");
codegen->append_inst("mul.w $t0, $t0, $t1");
codegen->append_inst("st.w",
{"$t0", "$fp", std::to_string(offset_map["%op3"])});
/* ret i32 %op3 */
codegen->append_inst("ret i32 %op3", ASMInstruction::Comment);
// 将 %op3 的值写入 $a0 中
codegen->append_inst("ld.w",
{"$a0", "$fp", std::to_string(offset_map["%op3"])});
codegen->append_inst("b callee_exit");
/* callee 函数的 Epilogue (收尾) */
codegen->append_inst("callee_exit", ASMInstruction::Label);
// 释放栈帧空间
codegen->append_inst("addi.d $sp, $sp, 48");
// 恢复 ra
codegen->append_inst("ld.d $ra, $sp, -8");
// 恢复 fp
codegen->append_inst("ld.d $fp, $sp, -16");
// 返回
codegen->append_inst("jr $ra");
}
// TODO: 按照提示补全
void translate_main(CodeGen *codegen) {
std::unordered_map<std::string, int> offset_map;
/* 声明 main 函数 */
codegen->append_inst(".globl main", ASMInstruction::Atrribute);
codegen->append_inst(".type main, @function", ASMInstruction::Atrribute);
/* main 函数开始 */
codegen->append_inst("main", ASMInstruction::Label); // main 函数标签
/* main 函数的 Prologue (序言) */
// 保存返回地址
codegen->append_inst("st.d $ra, $sp, -8");
// 保存老的 fp
codegen->append_inst("st.d $fp, $sp, -16");
// 设置新的 fp
codegen->append_inst("addi.d $fp, $sp, 0");
// 为栈帧分配空间. 思考: 为什么是 32 字节?
codegen->append_inst("addi.d $sp, $sp, -32");
/* main 函数的 label_entry */
codegen->append_inst(".main_label_entry", ASMInstruction::Label);
/* %op0 = call i32 @callee(i32 110) */
// 在汇编中写入注释, 方便 debug
codegen->append_inst("%op0 = call i32 @callee(i32 110)",
ASMInstruction::Comment);
offset_map["%op0"] = ; // TODO: 请填空
// TODO: 将参数写入参数寄存器
codegen->append_inst("");
// TODO: 调用 callee 函数
codegen->append_inst("");
// 将返回值写入 %op0 对应的内存空间中
codegen->append_inst("st.w",
{"$a0", "$fp", std::to_string(offset_map["%op0"])});
/* ret i32 %op0 */
codegen->append_inst("ret i32 %op0", ASMInstruction::Comment);
codegen->append_inst("ld.w",
{"$a0", "$fp", std::to_string(offset_map["%op0"])});
codegen->append_inst("b main_exit");
/* main 函数的 Epilogue (收尾) */
codegen->append_inst("main_exit", ASMInstruction::Label);
// 释放栈帧空间
codegen->append_inst("addi.d $sp, $sp, 32");
// 恢复 ra
codegen->append_inst("ld.d $ra, $sp, -8");
// 恢复 fp
codegen->append_inst("ld.d $fp, $sp, -16");
// 返回
codegen->append_inst("jr $ra");
}
#include "ASMInstruction.hpp"
#include "CodeGen.hpp"
#include "Module.hpp"
#include <iostream>
#include <memory>
#include <unordered_map>
void declare_global(CodeGen *codegen); // 声明全局变量 a
void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码
int main() {
auto *module = new Module();
auto *codegen = new CodeGen(module);
// 告诉汇编器将汇编放到代码段
codegen->append_inst(".text", ASMInstruction::Atrribute);
declare_global(codegen);
codegen->append_inst(".text", ASMInstruction::Atrribute);
translate_main(codegen);
std::cout << codegen->print();
delete codegen;
delete module;
return 0;
}
void declare_global(CodeGen *codegen) {
// 声明全局变量 a
// 将 a 放到 .bss 段中
codegen->append_inst(".section .bss, \"aw\", @nobits",
ASMInstruction::Atrribute);
// 标记 a 为全局变量
codegen->append_inst(".globl a", ASMInstruction::Atrribute);
// 标记 a 为数据对象 (变量)
codegen->append_inst(".type a, @object", ASMInstruction::Atrribute);
// 标记 a 的大小为 4 字节
codegen->append_inst(".size a, 4", ASMInstruction::Atrribute);
// a 的标签
codegen->append_inst("a", ASMInstruction::Label);
// 为 a 分配空间
codegen->append_inst(".space 4");
}
// TODO: 按照提示补全
void translate_main(CodeGen *codegen) {
std::unordered_map<std::string, int> offset_map;
/* 声明 main 函数 */
codegen->append_inst(".globl main", ASMInstruction::Atrribute);
codegen->append_inst(".type main, @function", ASMInstruction::Atrribute);
/* main 函数开始 */
codegen->append_inst("main", ASMInstruction::Label); // main 函数标签
/* main 函数的 Prologue (序言) */
// 保存返回地址
codegen->append_inst("st.d $ra, $sp, -8");
// 保存老的 fp
codegen->append_inst("st.d $fp, $sp, -16");
// 设置新的 fp
codegen->append_inst("addi.d $fp, $sp, 0");
// 为栈帧分配空间. 思考: 为什么是 32 字节?
codegen->append_inst("addi.d $sp, $sp, -32");
/* main 函数的 label_entry */
codegen->append_inst(".main_label_entry", ASMInstruction::Label);
/* store i32 10, i32* @a */
// 在汇编中写入注释, 方便 debug
codegen->append_inst("store i32 10, i32* @a", ASMInstruction::Comment);
// 将 10 写入 a 对应的内存空间中
// TODO: 获得 a 的地址
codegen->append_inst("");
// TODO: 将 10 写入 a 对应的内存空间中
codegen->append_inst("");
/* %op0 = load i32, i32* @a */
codegen->append_inst("%op0 = load i32, i32* @a", ASMInstruction::Comment);
// 将 a 的值写入 %op0 对应的内存空间中
offset_map["%op0"] = ; // TODO: 请填空
// TODO: 获得 a 的地址, 并存储在 $t0 中
codegen->append_inst("");
// 将 a 的值写入 %op0 对应的内存空间中
codegen->append_inst("ld.w $t1, $t0, 0");
codegen->append_inst("st.w",
{"$t1", "$fp", std::to_string(offset_map["%op0"])});
/* ret i32 %op0 */
codegen->append_inst("ret i32 %op0", ASMInstruction::Comment);
// 将 %op0 的值写入 $a0
codegen->append_inst("ld.w",
{"$a0", "$fp", std::to_string(offset_map["%op0"])});
codegen->append_inst("b main_exit");
/* main 函数的 Epilogue (收尾) */
codegen->append_inst("main_exit", ASMInstruction::Label);
// 释放栈帧空间
codegen->append_inst("addi.d $sp, $sp, 32");
// 恢复 ra
codegen->append_inst("ld.d $ra, $sp, -8");
// 恢复 fp
codegen->append_inst("ld.d $fp, $sp, -16");
// 返回
codegen->append_inst("jr $ra");
}
#include "ASMInstruction.hpp"
#include "CodeGen.hpp"
#include "Module.hpp"
#include <iostream>
#include <memory>
#include <unordered_map>
void translate_main(CodeGen *codegen); // 将 main 函数翻译为汇编代码
int main() {
auto *module = new Module();
auto *codegen = new CodeGen(module);
// 告诉汇编器将汇编放到代码段
codegen->append_inst(".text", ASMInstruction::Atrribute);
translate_main(codegen);
std::cout << codegen->print();
delete codegen;
delete module;
return 0;
}
// TODO: 按照提示补全
void translate_main(CodeGen *codegen) {
std::unordered_map<std::string, int> offset_map;
/* 声明 main 函数 */
codegen->append_inst(".globl main", ASMInstruction::Atrribute);
codegen->append_inst(".type main, @function", ASMInstruction::Atrribute);
/* main 函数开始 */
codegen->append_inst("main", ASMInstruction::Label); // main 函数标签
/* main 函数的 Prologue (序言) */
// 保存返回地址
codegen->append_inst("st.d $ra, $sp, -8");
// 保存老的 fp
codegen->append_inst("st.d $fp, $sp, -16");
// 设置新的 fp
codegen->append_inst("addi.d $fp, $sp, 0");
// 为栈帧分配空间. 思考: 为什么是 32 字节?
codegen->append_inst("addi.d $sp, $sp, -32");
/* main 函数的 label_entry */
codegen->append_inst(".main_label_entry", ASMInstruction::Label);
/* %op0 = icmp sgt i32 5, 1 */
// 在汇编中写入注释, 方便 debug
codegen->append_inst("%op0 = icmp sgt i32 5, 1", ASMInstruction::Comment);
// 将比较结果写入 %op0 对应的内存空间中
offset_map["%op0"] = ; // TODO: 请填空
codegen->append_inst("addi.w $t0, $zero, 5");
codegen->append_inst("addi.w $t1, $zero, 1");
// TODO: 使用 slt 指令比较, 并将结果写入 %op0 对应的内存空间中
codegen->append_inst("");
codegen->append_inst("");
/* %op1 = zext i1 %op0 to i32 */
codegen->append_inst("%op1 = zext i1 %op0 to i32", ASMInstruction::Comment);
// 将 %op0 的值从 i1 类型转换为 i32 类型, 并将结果写入到 %op1 对应的内存空
// 间中
offset_map["%op1"] = ; // TODO: 请填空
// TODO: 获得 %op0 的值, 然后进行转换, 最后将结果写入 %op1
// 思考: 怎么转换? 需不需要显式地使用某些指令转换?
codegen->append_inst("");
/* %op2 = icmp ne i32 %op1, 0 */
codegen->append_inst("%op2 = icmp ne i32 %op1, 0", ASMInstruction::Comment);
// 比较 %op1 和 0, 并将结果写入 %op2 对应的内存空间中
offset_map["%op2"] = ; // TODO: 请填空
// TODO: 获得 %op1 的值, 然后进行比较, 最后将结果写入 %op2
// 思考: 如何比较? 能否不使用跳转指令计算结果?
// 提示: 尝试使用 xor/xori 和 slt/sltu/slti/sltui 计算比较结果
codegen->append_inst("");
/* br i1 %op2, label %label3, label %label4 */
codegen->append_inst("br i1 %op2, label %label3, label %label4",
ASMInstruction::Comment);
// TODO: 获得 %op2 的值, 并根据 %op2 的值跳转到 label3 或者 label4
// 提示: 汇编中对应的标签分别为 .main_label3 和 .main_label4
codegen->append_inst("");
/* label3: */
codegen->append_inst(".main_label3", ASMInstruction::Label);
/* ret i32 233 */
codegen->append_inst("ret i32 233", ASMInstruction::Comment);
// 将 233 写入 $a0 中
codegen->append_inst("addi.w $a0, $zero, 233");
codegen->append_inst("b main_exit");
/* label4: */
codegen->append_inst(".main_label4", ASMInstruction::Label);
/* ret i32 0 */
codegen->append_inst("ret i32 0", ASMInstruction::Comment);
// 将 0 写入 $a0 中
codegen->append_inst("addi.w $a0, $zero, 0");
codegen->append_inst("b main_exit");
/* main 函数的 Epilogue (收尾) */
codegen->append_inst("main_exit", ASMInstruction::Label);
// 释放栈帧空间
codegen->append_inst("addi.d $sp, $sp, 32");
// 恢复 ra
codegen->append_inst("ld.d $ra, $sp, -8");
// 恢复 fp
codegen->append_inst("ld.d $fp, $sp, -16");
// 返回
codegen->append_inst("jr $ra");
}
add_subdirectory("2-ir-gen/warmup")
\ No newline at end of file
add_subdirectory("2-ir-gen/warmup")
add_subdirectory("3-codegen/warmup")
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment