Get Predecessors for BasicBlock in LLVM

c++, graph-traversal, llvm

Solution

It isn't clear from the documentation, but the basic block class has support for a pred iterator, which gives the predecessors to the basic block. In C++11 style, one could loop through the predecessors of a block as follows:

BasicBlock* B = ...
for (auto it = pred_begin(B), et = pred_end(B); it != et; ++it)
{
  BasicBlock* predecessor = *it;
  ...
}

Problem

What is the easiest way to get the predecessors of a `BasicBlock` in the LLVM framework? I have taken a look at `DepthFirstIterator` and `idf_iterator<BasicBlock*>`, but I actually need to do a breadth-first search on the control flow graph. I feel like this should be easy, but it's not obvious from the documentation or the examples I have been exploring online.

Original source