编写LLVM Pass
在上一篇的基础上,编写一个简单的LLVM Pass。
在
llvm-project-17.0.6.src/llvm/lib/Transforms/
目录下,新建一个文件夹SweetWound
:
在在
llvm-project-17.0.6.src/llvm/include/llvm/Transforms/
目录下,新建一个文件夹SweetWound
:
在
Transforms
目录下的CMakeLists.txt
文件末尾,增加如下代码:
...
add_subdirectory(SweetWound)
在
llvm-project-17.0.6.src/llvm/include/llvm/Transforms/SweetWound/
目录下,新建ModuleTest.h
文件,并写入如下代码:
// ModuleTest.h
#ifndef _LLVM_TRANSFORMS_SWEETWOUND_H_
#define _LLVM_TRANSFORMS_SWEETWOUND_H_
#include "llvm/Pass.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Module.h"
namespace llvm {
class ModuleTestPass : public PassInfoMixin {
public:
bool flag;
ModuleTestPass(bool flag) {
this->flag = flag;
}
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
static bool isRequired() {
return true;
}
};
}
#endif
在
llvm-project-17.0.6.src/llvm/lib/Transforms/SweetWound/
目录下,创建ModuleTest.cpp
文件,并写入如下代码:
// ModuleTest.cpp
#include "llvm/Transforms/SweetWound/ModuleTest.h"
using namespace llvm;
PreservedAnalyses ModuleTestPass::run(Module &M, ModuleAnalysisManager &AM) {
if (this->flag == true) {
outs() << "[SW]:" << M.getName() << "\n";
return PreservedAnalyses::none();
}
return PreservedAnalyses::all();
}
在
llvm-project-17.0.6.src/llvm/lib/Transforms/SweetWound/
目录下,创建CMakeLists.txt
文件,并写入如下代码:
add_llvm_component_library(LLVMSweetWound
ModuleTest.cpp
LINK_COMPONENTS
Analysis
Core
Support
TransformUtils
)
修改
llvm-project-17.0.6.src/llvm/lib/Passes/PassBuilder.cpp
文件:
......
#include
//======================导入头文件======================//
#include "llvm/Transforms/SweetWound/ModuleTest.h"
......
// ======================增加编译参数 begin ======================//
static cl::opt s_sw_test("test", cl::init(false), cl::desc("test module pass."));
// ======================增加编译参数 end ========================//
PassBuilder::PassBuilder(TargetMachine *TM, PipelineTuningOptions PTO,
std::optional PGOOpt,
PassInstrumentationCallbacks *PIC)
: TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC) {
......
// 注册Pass
this->registerPipelineStartEPCallback(
[](llvm::ModulePassManager &MPM, llvm::OptimizationLevel Level) {
MPM.addPass(ModuleTestPass(s_sw_test));
}
);
}
重新执行编译脚本,成功后,替换
LLVM17.0.6.xctoolchain
文件。在Xcode的
Build Settings-->Other C Flags
中,设置编译参数:-mllvm -test
:
Command + B
编译(或Command + R
运行):
可以看到每个编译单元都有对应的输出,即代表编写的LLVM Pass加载成功!!!