LLVM Pass插入printLoad/printStore调用的问题及递归死循环解决
Hey there, let's work through your two core problems step by step: grabbing dynamic store values and fixing that nasty infinite recursion segfault.
1. Extracting Values for All StoreInsts (Even Non-Constant Ones)
You noted you can pull constant values from StoreInsts but struggle with operation results—good news: this is totally doable. LLVM represents every value (constants, instruction outputs, etc.) as a Value*, so you don't need special handling for non-constant cases.
Here's how to reliably get the value being stored, no matter its origin:
// For a given StoreInst pointer SI Value* storedValue = SI->getOperand(0); // The first operand is always the value to store Value* storeAddr = SI->getPointerOperand(); // The memory address you already retrieve // Create the call to printStore, passing both address and value CallInst::Create(printStoreFunc, {storeAddr, storedValue}, "", SI->getNextNode());
This works even if storedValue is the result of an add, a load, or any other instruction—LLVM can pass it directly as an argument to your print function. Just double-check that printStore's signature matches the type of values you're storing (or use a generic type like i64 with casts if needed for consistency).
2. Fixing the Segmentation Fault from Infinite Recursion
The crash happens because your Pass is processing the load/store instructions inside your own printLoad and printStore functions, creating an endless loop of call insertion. The fix is simple: tell your Pass to skip these two functions entirely.
Add a check at the start of your Pass's runOnFunction method:
bool runOnFunction(Function &F) override { // Skip our print functions to break the recursion cycle if (F.getName() == "printLoad" || F.getName() == "printStore") { return false; } // Rest of your code to traverse instructions and insert print calls... }
Now when your Pass iterates over module functions, it ignores the print functions and won't inject calls inside them. Since printf is an external function (not defined in your module), your Pass won't process its internal instructions either—no extra work needed there.
Quick Verification Tip
After making these changes, dump the modified IR to confirm everything works as expected:
opt -load your-pass.so -your-pass -S input.ll > output.ll
Check output.ll to ensure calls to printLoad/printStore are inserted after every load/store in your target functions, and none appear inside the print functions themselves.
内容的提问来源于stack exchange,提问作者Mantas

