1 //===- FlattenCFGPass.cpp - CFG Flatten Pass ----------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements flattening of CFG.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Analysis/AliasAnalysis.h"
14 #include "llvm/IR/CFG.h"
15 #include "llvm/IR/ValueHandle.h"
16 #include "llvm/InitializePasses.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/Transforms/Utils/Local.h"
23 #define DEBUG_TYPE "flattencfg"
26 struct FlattenCFGPass : public FunctionPass {
27 static char ID; // Pass identification, replacement for typeid
29 FlattenCFGPass() : FunctionPass(ID) {
30 initializeFlattenCFGPassPass(*PassRegistry::getPassRegistry());
32 bool runOnFunction(Function &F) override;
34 void getAnalysisUsage(AnalysisUsage &AU) const override {
35 AU.addRequired<AAResultsWrapperPass>();
43 char FlattenCFGPass::ID = 0;
44 INITIALIZE_PASS_BEGIN(FlattenCFGPass, "flattencfg", "Flatten the CFG", false,
46 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
47 INITIALIZE_PASS_END(FlattenCFGPass, "flattencfg", "Flatten the CFG", false,
50 // Public interface to the FlattenCFG pass
51 FunctionPass *llvm::createFlattenCFGPass() { return new FlattenCFGPass(); }
53 /// iterativelyFlattenCFG - Call FlattenCFG on all the blocks in the function,
54 /// iterating until no more changes are made.
55 static bool iterativelyFlattenCFG(Function &F, AliasAnalysis *AA) {
57 bool LocalChange = true;
59 // Use block handles instead of iterating over function blocks directly
60 // to avoid using iterators invalidated by erasing blocks.
61 std::vector<WeakVH> Blocks;
62 Blocks.reserve(F.size());
64 Blocks.push_back(&BB);
69 // Loop over all of the basic blocks and try to flatten them.
70 for (WeakVH &BlockHandle : Blocks) {
71 // Skip blocks erased by FlattenCFG.
72 if (auto *BB = cast_or_null<BasicBlock>(BlockHandle))
73 if (FlattenCFG(BB, AA))
76 Changed |= LocalChange;
81 bool FlattenCFGPass::runOnFunction(Function &F) {
82 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
83 bool EverChanged = false;
84 // iterativelyFlattenCFG can make some blocks dead.
85 while (iterativelyFlattenCFG(F, AA)) {
86 removeUnreachableBlocks(F);