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
58using namespace llvm ;
69
@@ -11,13 +14,35 @@ struct LLVMPass : public PassInfoMixin<LLVMPass> {
1114PreservedAnalyses 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