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.

83 lines
2.5 KiB

#include "BasicBlock.h"
#include "Constant.h"
#include "Function.h"
#include "IRStmtBuilder.h"
#include "Module.h"
#include "Type.h"
#include <iostream>
#include <memory>
#ifdef DEBUG // 用于调试信息,大家可以在编译过程中通过" -DDEBUG"来开启这一选项
#define DEBUG_OUTPUT std::cout << __LINE__ << std::endl; // 输出行号的简单示例
#else
#define DEBUG_OUTPUT
#endif
#define CONST_INT(num) \
ConstantInt::create(num, module)
#define CONST_FP(num) \
ConstantFloat::create(num, module) // 得到常数值的表示,方便后面多次用到
using namespace SysYF::IR;
int main() {
auto module = Module::create("SysYF code"); // module name是什么无关紧要
auto builder = IRStmtBuilder::create(nullptr, module);
SysYF::Ptr<Type> Int32Type = Type::get_int32_type(module);
// int a;
auto a = GlobalVariable::create("a", module, Int32Type, false, CONST_INT(0));
// int b;
auto b = GlobalVariable::create("b", module, Int32Type, false, CONST_INT(0));
// main函数
auto mainFun = Function::create(FunctionType::create(Int32Type, {}),
"main", module);
auto bb = BasicBlock::create(module, "entry", mainFun);
// BasicBlock的名字在生成中无所谓,但是可以方便阅读
builder->set_insert_point(bb);
auto retAlloca = builder->create_alloca(Int32Type);
// b=0;
builder->create_store(CONST_INT(0), b);
// a = 3;
builder->create_store(CONST_INT(3), a);
// whileBBs
auto condBB = BasicBlock::create(module, "condBB_while", mainFun);
auto trueBB = BasicBlock::create(module, "trueBB_while", mainFun);
auto falseBB = BasicBlock::create(module, "falseBB_while", mainFun);
builder->create_br(condBB);
// condBB
builder->set_insert_point(condBB);
auto aLoad = builder->create_load(a);
auto icmp = builder->create_icmp_gt(aLoad, CONST_INT(0));
builder->create_cond_br(icmp, trueBB, falseBB);
// trueBB
builder->set_insert_point(trueBB);
aLoad = builder->create_load(a);
auto bLoad = builder->create_load(b);
auto add = builder->create_iadd(bLoad, aLoad);
builder->create_store(add, b);
auto sub = builder->create_isub(aLoad, CONST_INT(1));
builder->create_store(sub, a);
builder->create_br(condBB);
// falseBB
builder->set_insert_point(falseBB);
bLoad = builder->create_load(b);
builder->create_store(bLoad, retAlloca);
auto retLoad = builder->create_load(retAlloca);
builder->create_ret(retLoad);
std::cout << module->print();
1 year ago
return 0;
}