【基于legacy pass manager的pass编写】1.在github页面下载最新的llvm工程,现在最新的版本应该对应着是llvm13
2.在llvm-project/llvm/lib/Transforms文件夹新建自定义的pass文件夹
cd llvm-project/llvm/lib/Transformsmkdir MyPass
在MyPass文件夹下新建一个CMakeLists.txt
文章图片
写入
add_llvm_library( MYPass MODULE
MYPass.cppDEPENDS
intrinsics_gen
PLUGIN_TOOL
opt
)
3.在llvm-project/llvm/lib/Transforms/CmakeLists.txt中添加文件夹目录
add_subdirectory(MYPass)
文章图片
4.编写Pass
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"using namespace llvm;
#define DEBUG_TYPE "hello"STATISTIC(HelloCounter, "Counts number of functions greeted");
namespace {
// Hello - The first implementation, without getAnalysisUsage.
struct Hello : public FunctionPass {
static char ID;
// Pass identification, replacement for typeid
Hello() : FunctionPass(ID) {}bool runOnFunction(Function &F) override {
++HelloCounter;
errs() << "Hello: ";
errs().write_escaped(F.getName()) << '\n';
return false;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
}void releaseMemory() override {
errs() << "releaseMemory";
}};
}char Hello::ID = 0;
static RegisterPass X("hello", "Hello World Pass",false,false);
static RegisterStandardPasses Y2(PassManagerBuilder::EP_EarlyAsPossible,[](const PassManagerBuilder &Builder,legacy::PassManagerBase &PM) {
PM.add(new Hello());
});
5.构建和编译pass
cd /yourPath/llvm-projectcmake -S llvm -B build -G Xcode -DLLVM_ENABLE_PROJECTS="clang;
libcxx;
libcxxabi"
在xcode里选择sechme:MYPass,开始编译
编译完成后,可在llvm-project/build/Debug/bin目录下找到编译后的可执行文件,以及llvm-project/build/Debug/lib目录下找到LLVM pass的动态库
5.opt使用MYPass.dylib,这里官方文档有误,需要通过-enable-new-pm=0指定用legacy pass manager
./opt -load ../lib/LLVMHello.dylib -hello -enable-new-pm=0 < hello.bc >/dev/null
6.clang使用MYPass.dylib,这里官方文档有误,需要通过-flegacy-pass-manager指定用legacy pass manager
./clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.2.sdk -Xclang -load -Xclang ../lib/LLVMHello.dylib -flegacy-pass-manager hello.mm
-isysroot指定系统sdk版本