How to get DISubprogram of a Function

IR: metadata of main function:

!857 = distinct !DISubprogram(name: "main", scope: !8, file: !8, line: 11, type: !539, scopeLine: 11, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !7, retainedNodes: !9)

I wanna get DISubprogram. I wrote 2 versions. But both versions failed to get DISubprogram.

First wrong solution

virtual bool runOnFunction(Function &F) {
  SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  F.getAllMetadata(MDs);  // the size of MDs is always 0.
  errs() << "F METADATA node size is " << (MDs.size()) << " .\n";
  for (auto &MD : MDs) {
    if (MDNode *N = MD.second) {
      if (auto *subProgram = dyn_cast<DISubprogram>(N)) {
        errs() << subProgram->getLine();
      }
    }
  }
  return false;
}

Second wrong solution

if (auto *subprogram = F.getSubprogram())
  errs() << subprogram->getLine() << "\n";
else
  errs() << "has no subprogram" << "\n";

Third wrong solution

Here is to read metadata of an instruction. It failed again! Desperate…

auto alloca = dyn_cast<AllocaInst>(arg2);  // metadata of second operand's name

if (alloca->hasMetadata()) {
  errs() << "...has md...";
}
unsigned mk = alloca->getContext().getMDKindID("dbg");
if (MDNode *mdn = alloca->getMetadata(mk)) {
  Metadata *mds = mdn->getOperand(0);

  StringRef str;
  if (MDString::classof(mds)) {
    str = (cast<MDString>(*mds)).getString();
    errs() << str;
  }
} else {
  errs() << "no mk!\n";
}

The solution cannot get subprogram of main function. WHY and HOW?

Thanks!

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.

I just know little about -O0 -g. They will generate metadata…

-g gets you debug info, without -g you get no debug info. -O0 is the default and gets you unoptimised, ie relatively trivial to map back to C, output IR. DISubprogram is debug info (the DI), so if you want it you need to ask for it.

1 Like