Get metadata DILocation

// cpp code
return 0;

// SSA instruction
ret i32 0, !dbg !865

// Metadata: DILocation
!865 = !DILocation(line: 16, column: 5, scope: !857)


Q1: dbg

How can I extract information dbg from instruction ret i32 0, !dbg !865? Why is it dbg rather than bdg or gdb or anything else? What does !dbg mean?

Q2: location of DILocation

How can I extract information 865 from IR ret i32 0, !dbg !865?

If I use inst->getDebugLoc() it always return 0x0
So I cannot use inst->getDebugLoc().getLine(), it will hava segmentation failure.
My version of clang and llvm is 13.0.0

Q3: content of DILocation

How can I extract information line: 16, column: 5, scope: !857 from IR !865 = !DILocation(line: 16, column: 5, scope: !857) ?

My current code and its result
for (auto &B : F) {
  for (auto &I : B) { 
    // get metadata
    if (auto *inst = dyn_cast<ReturnInst>(&I)) {
      // ret i32 %3, !dbg !861
      // !861 = !DILocation(line: 8, column: 5, scope: !857)

      errs() << "!!!return inst: " << *inst << "\n";

      DILocation *DILoc = inst->getDebugLoc().get();
      errs() << "   " << DILoc << "."<< "\n";

      Type *instTy = inst->getType();
      errs() << "   " << *instTy << "."<< "\n";
      Value* val = dyn_cast<Value>(inst);
      errs() << "   val name: " << val->getName().str() << ".\n";

      if (auto constant_int = dyn_cast<ConstantInt>(val)) {
        int number = constant_int->getSExtValue();
        errs() << "   val number: " << number << ".\n";


!!!return inst:   ret i32 %3
   val name: .

When metadata is attached to an instruction, you need to give a name to the metadata kind to let consumers know what the metadata is for; !dbg is the tag that indicates the presence of debug location information. The list of known metadata in the language ref here: LLVM Language Reference Manual — LLVM 16.0.0git documentation people may create their own metadata that’s not on this page.

Since you’re interested in debug location, what you’ll want to do is use the I->getDebugLoc() to get the debug location for the node (see LLVM: llvm::DebugLoc Class Reference for more information on what you can do with this class). In particular, the getScope, getLine, and getCol methods seem to be exactly what you want.

1 Like

Thanks for your reply!

Actually, I find my true problem.

  • I used clang++ -O0 -g -S -emit-llvm test1.cpp -o test.ll to get .ll file. So it generate the metadata.
  • When I used clang++, I didn’t use -O0 -g. So it didn’t generate the metadata.

So the function LLVM: llvm::DebugLoc didn’t work.
And now, after I added the two arguments, the code I wrote works!