为何LLVM Pass无法获取精确的行/列调试信息?
The root cause here is straightforward: you didn't generate debug metadata when compiling your C code to LLVM IR. Without that metadata embedded in the .ll file, your Pass has no DebugLoc data to read.
What's Missing?
By default, clang doesn't emit debug information unless explicitly told to. Your initial compilation command:
clang -emit-llvm -S -fno-discard-value-names -c hello.c
produces LLVM IR with no debug metadata attached to instructions. That's why every getDebugLoc() call returns an empty result.
Fix Steps
Add debug flags to your compilation command
Modify theclangcommand to include the-gflag (or-gline-tables-onlyif you only need line/column info without full debug symbols):clang -g -emit-llvm -S -fno-discard-value-names -c hello.cThe
-gflag instructs clang to embed complete debug metadata (source file paths, line numbers, column positions, etc.) into the LLVM IR.Verify the debug metadata exists
Open the generatedhello.llfile—you should now see!dbgmetadata entries at the bottom, and individual instructions will have a!dbgattachment pointing to those entries, like:%retval = alloca i32, align 4, !dbg !7Re-run your Pass pipeline
Use your existingoptandclangcommands as before, but now the DebugLoc checks in your Pass will correctly retrieve line and column information.
Minor Suggestion for Your Pass Code
While not related to the DebugLoc issue, in LLVM Passes it's better practice to use llvm::errs() instead of std::cout for output—this aligns with LLVM's standard logging system and avoids potential conflicts with other output streams. For example:
if (location) errs() << " see line: " << location.getLine() << ", col " << location.getCol() << " \n"; else errs() << "no debugloc information detected\n";
内容的提问来源于stack exchange,提问作者Rookie

