Skip to content

Commit f8591cf

Browse files
committed
fix arg3
1 parent 6b73a0a commit f8591cf

File tree

1 file changed

+22
-19
lines changed

1 file changed

+22
-19
lines changed

lab6/llvm-pass.so.cc

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
#include "llvm/Passes/PassPlugin.h"
22
#include "llvm/Passes/PassBuilder.h"
33
#include "llvm/IR/IRBuilder.h"
4+
#include "llvm/IR/Instructions.h"
5+
#include "llvm/IR/Module.h"
6+
#include "llvm/IR/Function.h"
7+
#include "llvm/IR/Constants.h"
8+
#include "llvm/IR/GlobalVariable.h"
9+
#include "llvm/IR/Type.h"
410

511
using namespace llvm;
612

@@ -10,16 +16,19 @@ struct LLVMPass : public PassInfoMixin<LLVMPass> {
1016

1117
PreservedAnalyses LLVMPass::run(Module &M, ModuleAnalysisManager &MAM) {
1218
LLVMContext &Ctx = M.getContext();
13-
IntegerType *Int32Ty = IntegerType::getInt32Ty(Ctx);
14-
FunctionCallee debug_func = M.getOrInsertFunction("debug", Int32Ty);
15-
ConstantInt *debug_arg = ConstantInt::get(Int32Ty, 48763);
19+
IntegerType *Int32Ty = Type::getInt32Ty(Ctx);
20+
PointerType *Int8PtrTy = Type::getInt8PtrTy(Ctx);
1621

17-
for (auto &F : M) {
22+
// 取得 debug 函數
23+
FunctionCallee debugFunc = M.getOrInsertFunction("debug", Int32Ty, Int32Ty);
24+
ConstantInt *debugArg = ConstantInt::get(Int32Ty, 48763);
25+
26+
for (Function &F : M) {
1827
if (F.getName() == "main") {
1928
IRBuilder<> Builder(&*F.getEntryBlock().getFirstInsertionPt());
2029

2130
// 1. 插入 debug(48763);
22-
Builder.CreateCall(debug_func, debug_arg);
31+
Builder.CreateCall(debugFunc, debugArg);
2332

2433
// 2. 將 argv[1] = "hayaku... motohayaku!"
2534
// 建立常數字串
@@ -30,23 +39,18 @@ PreservedAnalyses LLVMPass::run(Module &M, ModuleAnalysisManager &MAM) {
3039
Value *argcArg = &*args++;
3140
Value *argvArg = &*args;
3241

33-
// 正確計算 argv[1] 的位址並存入字串
34-
Value *argv1Ptr = Builder.CreateInBoundsGEP(
35-
PointerType::getUnqual(Type::getInt8PtrTy(Ctx)),
36-
argvArg,
37-
{ConstantInt::get(Int32Ty, 1)},
38-
"argv1_ptr"
39-
);
42+
// argv[1] = "hayaku... motohayaku!"
43+
Value *idxs[] = {
44+
ConstantInt::get(Int32Ty, 1)
45+
};
46+
Value *argv1Ptr = Builder.CreateInBoundsGEP(argvArg, idxs, "argv1_ptr");
4047
Builder.CreateStore(StrConstant, argv1Ptr);
4148

42-
// 3. 將所有 argc 的用法替換為常數 48763
43-
for (auto it = argcArg->use_begin(), et = argcArg->use_end(); it != et;) {
44-
Use &use = *it++;
45-
use.set(debug_arg);
46-
}
49+
// 3. 將 argc 改為 48763
50+
argcArg->replaceAllUsesWith(debugArg); // 把 argc 的所有使用都替換成 48763
4751
}
48-
4952
}
53+
5054
return PreservedAnalyses::none();
5155
}
5256

@@ -60,4 +64,3 @@ llvmGetPassPluginInfo() {
6064
});
6165
}};
6266
}
63-

0 commit comments

Comments
 (0)