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/GlobalVariable.h"
46
57using namespace llvm ;
68
@@ -11,13 +13,38 @@ struct LLVMPass : public PassInfoMixin<LLVMPass> {
1113PreservedAnalyses LLVMPass::run (Module &M, ModuleAnalysisManager &MAM ) {
1214 LLVMContext &Ctx = M.getContext ();
1315 IntegerType *Int32Ty = IntegerType::getInt32Ty (Ctx);
14- FunctionCallee debug_func = M.getOrInsertFunction (" debug" , Int32Ty);
16+ PointerType *Int8PtrTy = Type::getInt8PtrTy (Ctx);
17+
18+ FunctionType *DebugTy = FunctionType::get (Type::getVoidTy (Ctx), {Int32Ty}, false );
19+ FunctionCallee debug_func = M.getOrInsertFunction (" debug" , DebugTy);
1520 ConstantInt *debug_arg = ConstantInt::get (Int32Ty, 48763 );
1621
22+ Constant *StrConstant = ConstantDataArray::getString (Ctx, " hayaku... motohayaku!" , true );
23+ GlobalVariable *StrVar = new GlobalVariable (M, StrConstant->getType (), true ,
24+ GlobalValue::PrivateLinkage, StrConstant, " .str.hayaku" );
25+ Constant *Zero = ConstantInt::get (Int32Ty, 0 );
26+ Constant *Indices[] = {Zero, Zero};
27+ Constant *StrPtr = ConstantExpr::getGetElementPtr (StrConstant->getType (), StrVar, Indices);
28+
1729 for (auto &F : M) {
18- errs () << " func: " << F.getName () << " \n " ;
30+ if (F.getName () != " main" )
31+ continue ;
32+
33+ errs () << " Instrumenting function: " << F.getName () << " \n " ;
34+ IRBuilder<> Builder (&*F.getEntryBlock ().getFirstInsertionPt ());
35+
36+ Builder.CreateCall (debug_func, {debug_arg});
1937
38+ auto ArgIter = F.arg_begin ();
39+ Argument *argcArg = ArgIter++;
40+ Argument *argvArg = ArgIter;
41+
42+ Value *Argv1Ptr = Builder.CreateGEP (Int8PtrTy, argvArg, ConstantInt::get (Int32Ty, 1 ));
43+ Builder.CreateStore (StrPtr, Argv1Ptr);
44+
45+ argcArg->replaceAllUsesWith (debug_arg);
2046 }
47+
2148 return PreservedAnalyses::none ();
2249}
2350
@@ -31,4 +58,3 @@ llvmGetPassPluginInfo() {
3158 });
3259 }};
3360}
34-
0 commit comments