Question

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.

Was it helpful?

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

OTHER TIPS

A simpler way to iterate through the predecessors or successors is shown by using a for-each loop in the Programmer's Manual:

Iterating over the predecessors and successors of a block is quite easy with the routines defined in llvm/IR/CFG.h. Just use code like this to iterate over all predecessors of BB:

#include "llvm/IR/CFG.h"
BasicBlock *BB = ...; 
for (BasicBlock *Pred : predecessors(BB)) {
  // ...
}

Similarly, to iterate over successors use successors.

This is a lot cleaner than using explicit iteration with pred_begin and pred_end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top