Get Predecessors for BasicBlock in LLVM
Asked Answered
L

2

11

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.

Loriloria answered 11/2, 2014 at 17:1 Comment(0)
O
23

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;
  ...
}
Ortiz answered 11/2, 2014 at 17:28 Comment(1)
The BasicBlock docs are not helpful here. The logic lies in llvm/Support/CFG.h. I found the answer here: llvm.org/docs/…Loriloria
D
12

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.

Dribble answered 20/3, 2018 at 20:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.