Skip to content

Commit c60999b

Browse files
authored
Merge pull request #474 from skysoul1024/lab6
[LAB6] 313551109
2 parents aebbb60 + 62f2afe commit c60999b

1 file changed

Lines changed: 32 additions & 6 deletions

File tree

lab6/llvm-pass.so.cc

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include "llvm/Passes/PassPlugin.h"
22
#include "llvm/Passes/PassBuilder.h"
33
#include "llvm/IR/IRBuilder.h"
4+
#include "llvm/IR/Constants.h"
45

56
using namespace llvm;
67

@@ -11,13 +12,39 @@ struct LLVMPass : public PassInfoMixin<LLVMPass> {
1112
PreservedAnalyses LLVMPass::run(Module &M, ModuleAnalysisManager &MAM) {
1213
LLVMContext &Ctx = M.getContext();
1314
IntegerType *Int32Ty = IntegerType::getInt32Ty(Ctx);
14-
FunctionCallee debug_func = M.getOrInsertFunction("debug", Int32Ty);
15+
PointerType *CharPtrTy = Type::getInt8PtrTy(Ctx);
16+
17+
// Get or create debug function declaration
18+
FunctionCallee debug_func = M.getOrInsertFunction("debug",
19+
FunctionType::get(Type::getVoidTy(Ctx), {Int32Ty}, false));
20+
21+
// Create constant value for debug function argument and argc
1522
ConstantInt *debug_arg = ConstantInt::get(Int32Ty, 48763);
16-
23+
1724
for (auto &F : M) {
18-
errs() << "func: " << F.getName() << "\n";
19-
25+
// Find main function
26+
if (F.getName() == "main") {
27+
// Create IRBuilder at the beginning of the entry block
28+
IRBuilder<> Builder(&*F.getEntryBlock().getFirstInsertionPt());
29+
30+
// a. Call debug function with argument 48763
31+
Builder.CreateCall(debug_func, {debug_arg});
32+
33+
// Get function arguments
34+
Argument *argcArg = F.getArg(0);
35+
Argument *argvArg = F.getArg(1);
36+
37+
// b. Set argv[1] = "hayaku... motohayaku!"
38+
Value *index1 = ConstantInt::get(Int32Ty, 1);
39+
Value *argv1_ptr = Builder.CreateInBoundsGEP(CharPtrTy, argvArg, index1);
40+
Value *hayakuStr = Builder.CreateGlobalStringPtr("hayaku... motohayaku!");
41+
Builder.CreateStore(hayakuStr, argv1_ptr);
42+
43+
// c. Replace all uses of argc with 48763
44+
argcArg->replaceAllUsesWith(debug_arg);
45+
}
2046
}
47+
2148
return PreservedAnalyses::none();
2249
}
2350

@@ -30,5 +57,4 @@ llvmGetPassPluginInfo() {
3057
MPM.addPass(LLVMPass());
3158
});
3259
}};
33-
}
34-
60+
}

0 commit comments

Comments
 (0)