如何找到在LLVM IR级别的两个特定基本块之间出现的所有基本块?

时间:2019-06-04 07:30:52

标签: c++ graph llvm

我正在LLVM中进行一些分析,由于某些原因,我想找到可以在两个特定基本块之间执行的所有基本块。

例如,假设我们有两个名为AB的基本块。现在,我想知道在执行基本块A之后且在基本块B之前可以出现哪些基本块。

一种可能的解决方案是使用控制辉光图的可达性分析。例如,如果可以从C到达基本块A,并且也可以从B到达基本块C,那么可以说C可以在之后执行AB之前。

我在LLVM中唯一能找到的就是llvm/analysis/CFG.h中的该函数:

/// Determine whether instruction 'To' is reachable from 'From', without passing
/// through any blocks in ExclusionSet, returning true if uncertain.
///
/// Determine whether there is a path from From to To within a single function.
/// Returns false only if we can prove that once 'From' has been executed then
/// 'To' can not be executed. Conservatively returns true.
///
/// This function is linear with respect to the number of blocks in the CFG,
/// walking down successors from From to reach To, with a fixed threshold.
/// Using DT or LI allows us to answer more quickly. LI reduces the cost of
/// an entire loop of any number of blocks to be the same as the cost of a
/// single block. DT reduces the cost by allowing the search to terminate when
/// we find a block that dominates the block containing 'To'. DT is most useful
/// on branchy code but not loops, and LI is most useful on code with loops but
/// does not help on branchy code outside loops.
bool isPotentiallyReachable(
     const Instruction *From, const Instruction *To,
     const SmallPtrSetImpl<BasicBlock *> *ExclusionSet = nullptr,
     const DominatorTree *DT = nullptr, const LoopInfo *LI = nullptr);

但是问题是此功能过于保守,答案不确定。我想知道某些答案。

1 个答案:

答案 0 :(得分:0)

您要寻找的概念称为统治。您想要由A主导并由B主导的块。为此,您获得或获得了DominatorTreePostDominatorTree,并查看了A和B下方的树的各个部分。如果您要编写通行证,则可以从通行证管理器中获取一个。

但是,请注意LLVM的代码是保守的,因为这种事情会很快变得复杂。在A之后执行(即由A主导)但返回或引发异常而不是分支到B的块呢?你想要那些吗?如果存在无限循环该怎么办?这些可能是故意的。如果可能引发异常并且处理程序未由B主导怎么办?这类事情充满了您必须考虑的情况。