当前位置:网站首页>Llvm - generate for loop
Llvm - generate for loop
2022-04-23 15:04:00 【Mrpre】
1、 Generating function
2、 Use Phi Expression implementation for loop
3、 In this case ,KaleidoscopeJIT The source code is located in ./llvm-8.0.1.src/examples/Kaleidoscope/include/KaleidoscopeJIT.h
Phi The concept of can be referred to https://stackoverflow.com/questions/11485531/what-exactly-phi-instruction-does-and-how-to-use-it-in-llvm
In this case , Generated llvm ir as follows :
define double @myfor(double %a) {
myentry:
br label %loop
loop: ; preds = %loop, %myentry
%i = phi double [ 0.000000e+00, %myentry ], [ %nextvar, %loop ]
%a1 = fadd double %a, 2.000000e+00
%nextvar = fadd double 1.000000e+00, %i
%cmptmp = fcmp ult double %i, 1.000000e+01
br i1 %cmptmp, label %loop, label %afterloop
afterloop: ; preds = %loop
ret double %a1
}
phi The logic of , If from myentry Come on ( Like just coming in ), be %i Namely 0, otherwise %i The value is %nextvar( For example, after a cycle )
Code :
#include "./llvm-8.0.1.src/examples/Kaleidoscope/include/KaleidoscopeJIT.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
using namespace llvm;
using namespace llvm::orc;
//LLVM items
static LLVMContext TheContext;
static IRBuilder<> Builder(TheContext);
static std::unique_ptr<Module> TheModule;
//JIT
static std::unique_ptr<KaleidoscopeJIT> TheJIT;
/* *double myfor(double a) *{ * for(i = 0; i < a; i++) { * a = a + 1 * } * return a *} * */
int main()
{
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
//init module
TheModule = llvm::make_unique<Module>("myjit", TheContext);
//used to be runned by jit later
TheJIT = llvm::make_unique<KaleidoscopeJIT>();
TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
//define the args
vector<std::string> ArgNames;
//myfor has 1 args
ArgNames.push_back(string("a"));
//make the 1 args attach to LLVM Type::double
std::vector<Type *> Doubles(ArgNames.size(), Type::getDoubleTy(TheContext));
//generate llvm function type
FunctionType *FT = FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
//Create function whose FunctionType is FT
Function *TheFunction = Function::Create(FT, Function::ExternalLinkage, "myfor", TheModule.get());
//give the name of Function args and save the args as innerargs
unsigned Idx = 0;
std::vector<Value *>innerargs;
for (auto &Arg : TheFunction->args()) {
Arg.setName(ArgNames[Idx++]);
innerargs.push_back(&Arg);
}
//this function's basic block
BasicBlock *BB = BasicBlock::Create(TheContext, "myentry", TheFunction);
//create the loop BasicBlock
BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
//exit the block
BasicBlock *AfterBB = BasicBlock::Create(TheContext, "afterloop", TheFunction);
Builder.SetInsertPoint(BB);
//add goto LoopBB in BB
Builder.CreateBr(LoopBB);
//start with LoopBB
Builder.SetInsertPoint(LoopBB);
//start with 0
Value *StartVal = ConstantFP::get(TheContext, APFloat(0.0));
//step is 1
Value *StepVal = ConstantFP::get(TheContext, APFloat(1.0));
//local Variable which name is a
PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(TheContext), 1, "i");
//if it's from start block, set Variable 0
Variable->addIncoming(StartVal, BB);
//do the body then do cond
//emit loop body in LoopBB
//body: arg_a += 1
Value *ret = Builder.CreateFAdd(innerargs[0], ConstantFP::get(TheContext, APFloat(2.0)), "a");
//do the cond,if Variable >= 2 then break(goto AfterBB)
Value *NextVar = Builder.CreateFAdd(StepVal, Variable, "nextvar");
//if Variable < 10 then goto LoopBB or gotot AfterBB
Value *cond = Builder.CreateFCmpULT(Variable, ConstantFP::get(TheContext, APFloat(10.0)), "cmptmp");
Builder.CreateCondBr(cond, LoopBB, AfterBB);
Builder.SetInsertPoint(AfterBB);
Variable->addIncoming(NextVar, LoopBB);
Builder.CreateRet(ret);
TheFunction->print(errs());
//using jit to run this code
auto H = TheJIT->addModule(std::move(TheModule));
auto ExprSymbol = TheJIT->findSymbol("myfor");
double (*myfor)(double) = (double (*)(double))(intptr_t)cantFail(ExprSymbol.getAddress());
cout <<myfor(40)<<endl;
}
版权声明
本文为[Mrpre]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231409588105.html
边栏推荐
- 2-Go变量操作
- Sword finger offer II 019 Delete at most one character to get palindrome (simple)
- How does eolink help telecommuting
- ffmpeg安装遇错:nasm/yasm not found or too old. Use --disable-x86asm for a crippled build.
- 3、 Gradient descent solution θ
- Ffmpeg installation error: NASM / yasm not found or too old Use --disable-x86asm for a clipped build
- The difference between having and where in SQL
- Set up an AI team in the game world and start the super parametric multi-agent "chaos fight"
- 1990年1月1日是星期一,定义函数date_to_week(year,month,day),实现功能输入年月日后返回星期几,例如date_to_week(2020,11,1),返回:星期日。 提示:
- Introduction to dirty reading, unrepeatable reading and phantom reading
猜你喜欢
冰冰学习笔记:一步一步带你实现顺序表
Svn detailed use tutorial
How does eolink help telecommuting
Leetcode149 - maximum number of points on a line - Math - hash table
Five data types of redis
Swift - literal, literal protocol, conversion between basic data types and dictionary / array
1-初识Go语言
Don't you know the usage scenario of the responsibility chain model?
每日一题-LeetCode396-旋转函数-递推
win10 任务栏通知区图标不见了
随机推荐
Realization of four data flow modes of grpc based on Multilingual Communication
How to upload large files quickly?
Introduction to distributed transaction Seata
JUC learning record (2022.4.22)
Epoll's et, lt working mode -- example program
Vscode Chinese plug-in doesn't work. Problem solving
Flink datastream type system typeinformation
The difference between having and where in SQL
Tencent has written a few words, Ali has written them all for a month
Chapter 7 of JVM series -- bytecode execution engine
OC to swift conditional compilation, marking, macro, log, version detection, expiration prompt
Do (local scope), initializer, memory conflict, swift pointer, inout, unsafepointer, unsafebitcast, success
How to design a good API interface?
Detailed explanation of C language knowledge points - data types and variables [2] - integer variables and constants [1]
Achievements in science and Technology (21)
How do I open the win10 startup folder?
Swift - literal, literal protocol, conversion between basic data types and dictionary / array
LeetCode167-两数之和II-双指针-二分-数组-查找
The win10 taskbar notification area icon is missing
What is the main purpose of PCIe X1 slot?