llvm: How to get the label of Basic Blocks

Values in LLVM IR are not required to have a name; and indeed, those basic blocks don't have names, which is why you get an empty string from currBB->getName().

The reason that they have names in the LLVM IR printout is because when you print to the textual format of LLVM IR (as it appears in .ll files), you have to assign a name to them to make them referable, so the printer assigns sequential numeric names to basic blocks (and other values). Those numeric names are only created by the printer, though, and don't actually exist in the module.


I think the behavior of LLVM now is different. I use similar lines of code and can get the label's name on LLVM-4.0

for (auto &funct : m) {
            for (auto &basic_block : funct) {
            StringRef bbName(basic_block.getName());
                errs() << "BasicBlock: "  << bbName << "\n";
            }
}

While compiling source code to bitcode using clang use the below flag

-fno-discard-value-names

You will get the name of basic block as a unique string


While BasicBlocks may be with no name (as indicated by hasName() method) one may print unique BasicBlock identifier by using currBB->printAsOperand(errs(), false) instead of streaming into errs() the value of currBB->getName(). For unnamed BasicBlock this would provide the numerical basic block representation, such as %68 .