Skip to content

Commit 6e9f6a3

Browse files
authored
Update llvm-pass.so.cc
1 parent c6406a3 commit 6e9f6a3

1 file changed

Lines changed: 28 additions & 4 deletions

File tree

lab6/llvm-pass.so.cc

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
#include "llvm/Passes/PassPlugin.h"
22
#include "llvm/Passes/PassBuilder.h"
33
#include "llvm/IR/IRBuilder.h"
4+
#include "llvm/IR/Constants.h"
5+
#include "llvm/IR/Module.h"
6+
#include "llvm/IR/Instructions.h"
47

58
using namespace llvm;
69

@@ -11,13 +14,35 @@ struct LLVMPass : public PassInfoMixin<LLVMPass> {
1114
PreservedAnalyses LLVMPass::run(Module &M, ModuleAnalysisManager &MAM) {
1215
LLVMContext &Ctx = M.getContext();
1316
IntegerType *Int32Ty = IntegerType::getInt32Ty(Ctx);
14-
FunctionCallee debug_func = M.getOrInsertFunction("debug", Int32Ty);
17+
PointerType *Int8PtrTy = Type::getInt8PtrTy(Ctx);
18+
19+
// 宣告 debug(int) 函式
20+
FunctionType *DebugFuncTy = FunctionType::get(Type::getVoidTy(Ctx), {Int32Ty}, false);
21+
FunctionCallee debug_func = M.getOrInsertFunction("debug", DebugFuncTy);
1522
ConstantInt *debug_arg = ConstantInt::get(Int32Ty, 48763);
1623

17-
for (auto &F : M) {
18-
errs() << "func: " << F.getName() << "\n";
24+
for (Function &F : M) {
25+
if (F.getName() != "main") continue;
26+
27+
// 取得 main 的參數 argc, argv
28+
Argument *argc = F.getArg(0);
29+
Argument *argv = F.getArg(1);
30+
31+
// 插入點:main 的開頭
32+
IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
33+
34+
// 1️⃣ 呼叫 debug(48763)
35+
IRB.CreateCall(debug_func, debug_arg);
1936

37+
// 2️⃣ 將 argc 的所有用途替換為常數 48763
38+
argc->replaceAllUsesWith(debug_arg);
39+
40+
// 3️⃣ 將 argv[1] 設為 "hayaku... motohayaku!"
41+
Value *argv1_ptr = IRB.CreateGEP(argv->getType()->getPointerElementType(), argv, ConstantInt::get(Int32Ty, 1));
42+
Value *str_val = IRB.CreateGlobalStringPtr("hayaku... motohayaku!");
43+
IRB.CreateStore(str_val, argv1_ptr);
2044
}
45+
2146
return PreservedAnalyses::none();
2247
}
2348

@@ -31,4 +56,3 @@ llvmGetPassPluginInfo() {
3156
});
3257
}};
3358
}
34-

0 commit comments

Comments
 (0)