|
|
|
#include "BasicBlock.h"
|
|
|
|
#include "Constant.h"
|
|
|
|
#include "Function.h"
|
|
|
|
#include "IRStmtBuilder.h"
|
|
|
|
#include "Module.h"
|
|
|
|
#include "Type.h"
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
#include <memory>
|
|
|
|
|
|
|
|
#ifdef DEBUG
|
|
|
|
#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("If code");
|
|
|
|
auto builder = IRStmtBuilder::create(nullptr, module);
|
|
|
|
SysYF::Ptr<Type> Int32Type = Type::get_int32_type(module);
|
|
|
|
SysYF::Ptr<Type> FloatType = Type::get_float_type(module);
|
|
|
|
|
|
|
|
auto zero_initializer = ConstantZero::create(Int32Type, module);
|
|
|
|
auto a = GlobalVariable::create("a", module, Int32Type, false, zero_initializer);
|
|
|
|
|
|
|
|
// main function
|
|
|
|
auto mainFun = Function::create(FunctionType::create(Int32Type, {}),
|
|
|
|
"main", module);
|
|
|
|
auto bb = BasicBlock::create(module, "entry", mainFun);
|
|
|
|
builder->set_insert_point(bb);
|
|
|
|
auto retAlloca = builder->create_alloca(Int32Type);
|
|
|
|
|
|
|
|
// store 10 to a
|
|
|
|
builder->create_store(CONST_INT(10), a);
|
|
|
|
auto aValue = builder->create_load(a);
|
|
|
|
|
|
|
|
// if(a > 0)
|
|
|
|
auto icmp = builder->create_icmp_gt(aValue, CONST_INT(0));
|
|
|
|
auto trueBB = BasicBlock::create(module, "trueBB_if", mainFun); // true分支
|
|
|
|
auto falseBB = BasicBlock::create(module, "falseBB_if", mainFun); // false分支
|
|
|
|
builder->create_cond_br(icmp, trueBB, falseBB); // 条件BR
|
|
|
|
|
|
|
|
// if true return a
|
|
|
|
builder->set_insert_point(trueBB);
|
|
|
|
builder->create_ret(aValue);
|
|
|
|
|
|
|
|
// if false return 0
|
|
|
|
builder->set_insert_point(falseBB);
|
|
|
|
builder->create_ret(CONST_INT(0));
|
|
|
|
|
|
|
|
std::cout << module->print();
|
|
|
|
return 0;
|
|
|
|
}
|