'【SOLVED】LLVM DILocation: extract information from metadata

I wanna get value and 861 from a return instruction, for example ret i32 %3, !dbg !861 and it's metadata !861 = !DILocation(line: 8, column: 5, scope: !857). But it didn't work.

version of clang and llvm is 13.0.0

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";
      }  
    }
  }
}

and the result:

!!!return inst:   ret i32 %3
   0x0.
   void.
   val name: .

I nearly got nothing! Problems:

1. DILocation return 0x0, why? I wanna get information of !861 = !DILocation(line: 8, column: 5, scope: !857)

Actually, now 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!

2. return type is void, why? I thought it should be ret.

Nick Lewycky said: The return instruction, locally to the current function, is void, it does not produce a value that subsequent instructions in the same function can consume. > %a = add i32 %b, %c makes sense, but %a = ret i32 %b does not. A ret instruction itself always has void type, no matter what type the function is returning. If you want the type of the returned value you could ask inst->getReturnValue()->getType(). Thanks Nick Lewycky!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source