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.

67 lines
2.0 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
#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("Assign 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);
// 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);
// b = 1.8
auto bAlloca = builder->create_alloca(FloatType);
builder->create_store(CONST_FP(1.8), bAlloca);
// a[2] = {2}
auto arrayType_a = ArrayType::get(Int32Type, 2);
auto aAlloca = builder->create_alloca(arrayType_a);
auto a0Gep = builder->create_gep(aAlloca, {CONST_INT(0), CONST_INT(0)});
builder->create_store(CONST_INT(2), a0Gep);
// a[0] * b
auto a0Load = builder->create_load(a0Gep);
auto a0Float = builder->create_sitofp(a0Load, FloatType);
auto bLoad = builder->create_load(FloatType, bAlloca);
auto a1res = builder->create_fmul(a0Float, bLoad);
// store to a[1]
auto a1res_int = builder->create_fptosi(a1res, Int32Type);
auto a1Gep = builder->create_gep(aAlloca, {CONST_INT(0), CONST_INT(1)});
builder->create_store(a1res_int, a1Gep);
// ret
builder->create_store(a1res_int, retAlloca);
auto retLoad = builder->create_load(retAlloca);
builder->create_ret(retLoad);
std::cout << module->print();
return 0;
}