llvm line number of an instruction

Hello everybody,

I want to get the line number of an instruction (and also of a variable declaration - alloca and global). The instruction is saved in an array of instructions. I have the function:

Constant* metadata::getLineNumber(Instruction* I){
if (MDNode *N = I->getMetadata(“dbg”)) { // this if is never executed
DILocation Loc(N);
unsigned Line = Loc.getLineNumber();
return ConstantInt::get(Type::getInt32Ty(I->getContext()), Line);
} // else {
// return NULL; }

and in my main() I have :

errs()<<"\nLine number is "<<*metadata::getLineNumber(allocas[p]);

the result is NULL since I->getMetadata("dbg") is false.

Is there a possibility to enable dbg flags in LLVM without rebuilding the LLVM framework, like using a flag when compiling the target program or when running my pass (I used -debug) ?

Compiling a program with “-O3 -g” should give full debug information, but I still have the same result. I am aware of http://llvm.org/docs/SourceLevelDebugging.html , from where I can see that is quite easy to take the source line number from a metadata field.

PS: for Allocas, it seems that I have to use findDbgDeclare method from DbgInfoPrinter.cpp.

Thank you in advance !

The line numbers there aren’t the line numbers of the instructions in the .ll file, they’re metadata attached to llvm instructions describing the original source program (e.g. C++). So you’d need to have a front end attaching line information to instructions and other debug information in the module (very little if all you want is line numbers) to get the line numbers.