xref: /openbsd-src/gnu/llvm/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This family of functions perform manipulations on basic blocks, and
1009467b48Spatrick // instructions contained within basic blocks.
1109467b48Spatrick //
1209467b48Spatrick //===----------------------------------------------------------------------===//
1309467b48Spatrick 
1409467b48Spatrick #include "llvm/Transforms/Utils/BasicBlockUtils.h"
1509467b48Spatrick #include "llvm/ADT/ArrayRef.h"
1609467b48Spatrick #include "llvm/ADT/SmallPtrSet.h"
1709467b48Spatrick #include "llvm/ADT/SmallVector.h"
1809467b48Spatrick #include "llvm/ADT/Twine.h"
1909467b48Spatrick #include "llvm/Analysis/CFG.h"
2009467b48Spatrick #include "llvm/Analysis/DomTreeUpdater.h"
2109467b48Spatrick #include "llvm/Analysis/LoopInfo.h"
2209467b48Spatrick #include "llvm/Analysis/MemoryDependenceAnalysis.h"
2309467b48Spatrick #include "llvm/Analysis/MemorySSAUpdater.h"
2409467b48Spatrick #include "llvm/IR/BasicBlock.h"
2509467b48Spatrick #include "llvm/IR/CFG.h"
2609467b48Spatrick #include "llvm/IR/Constants.h"
27*d415bd75Srobert #include "llvm/IR/DebugInfo.h"
2809467b48Spatrick #include "llvm/IR/DebugInfoMetadata.h"
2909467b48Spatrick #include "llvm/IR/Dominators.h"
3009467b48Spatrick #include "llvm/IR/Function.h"
3109467b48Spatrick #include "llvm/IR/InstrTypes.h"
3209467b48Spatrick #include "llvm/IR/Instruction.h"
3309467b48Spatrick #include "llvm/IR/Instructions.h"
3409467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
3509467b48Spatrick #include "llvm/IR/LLVMContext.h"
3609467b48Spatrick #include "llvm/IR/Type.h"
3709467b48Spatrick #include "llvm/IR/User.h"
3809467b48Spatrick #include "llvm/IR/Value.h"
3909467b48Spatrick #include "llvm/IR/ValueHandle.h"
4009467b48Spatrick #include "llvm/Support/Casting.h"
41*d415bd75Srobert #include "llvm/Support/CommandLine.h"
4209467b48Spatrick #include "llvm/Support/Debug.h"
4309467b48Spatrick #include "llvm/Support/raw_ostream.h"
4409467b48Spatrick #include "llvm/Transforms/Utils/Local.h"
4509467b48Spatrick #include <cassert>
4609467b48Spatrick #include <cstdint>
4709467b48Spatrick #include <string>
4809467b48Spatrick #include <utility>
4909467b48Spatrick #include <vector>
5009467b48Spatrick 
5109467b48Spatrick using namespace llvm;
5209467b48Spatrick 
5309467b48Spatrick #define DEBUG_TYPE "basicblock-utils"
5409467b48Spatrick 
55*d415bd75Srobert static cl::opt<unsigned> MaxDeoptOrUnreachableSuccessorCheckDepth(
56*d415bd75Srobert     "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
57*d415bd75Srobert     cl::desc("Set the maximum path length when checking whether a basic block "
58*d415bd75Srobert              "is followed by a block that either has a terminating "
59*d415bd75Srobert              "deoptimizing call or is terminated with an unreachable"));
60*d415bd75Srobert 
detachDeadBlocks(ArrayRef<BasicBlock * > BBs,SmallVectorImpl<DominatorTree::UpdateType> * Updates,bool KeepOneInputPHIs)61*d415bd75Srobert void llvm::detachDeadBlocks(
6209467b48Spatrick     ArrayRef<BasicBlock *> BBs,
6309467b48Spatrick     SmallVectorImpl<DominatorTree::UpdateType> *Updates,
6409467b48Spatrick     bool KeepOneInputPHIs) {
6509467b48Spatrick   for (auto *BB : BBs) {
6609467b48Spatrick     // Loop through all of our successors and make sure they know that one
6709467b48Spatrick     // of their predecessors is going away.
6809467b48Spatrick     SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
6909467b48Spatrick     for (BasicBlock *Succ : successors(BB)) {
7009467b48Spatrick       Succ->removePredecessor(BB, KeepOneInputPHIs);
7109467b48Spatrick       if (Updates && UniqueSuccessors.insert(Succ).second)
7209467b48Spatrick         Updates->push_back({DominatorTree::Delete, BB, Succ});
7309467b48Spatrick     }
7409467b48Spatrick 
7509467b48Spatrick     // Zap all the instructions in the block.
7609467b48Spatrick     while (!BB->empty()) {
7709467b48Spatrick       Instruction &I = BB->back();
7809467b48Spatrick       // If this instruction is used, replace uses with an arbitrary value.
7909467b48Spatrick       // Because control flow can't get here, we don't care what we replace the
8009467b48Spatrick       // value with.  Note that since this block is unreachable, and all values
8109467b48Spatrick       // contained within it must dominate their uses, that all uses will
8209467b48Spatrick       // eventually be removed (they are themselves dead).
8309467b48Spatrick       if (!I.use_empty())
84*d415bd75Srobert         I.replaceAllUsesWith(PoisonValue::get(I.getType()));
85*d415bd75Srobert       BB->back().eraseFromParent();
8609467b48Spatrick     }
8709467b48Spatrick     new UnreachableInst(BB->getContext(), BB);
88*d415bd75Srobert     assert(BB->size() == 1 &&
8909467b48Spatrick            isa<UnreachableInst>(BB->getTerminator()) &&
9009467b48Spatrick            "The successor list of BB isn't empty before "
9109467b48Spatrick            "applying corresponding DTU updates.");
9209467b48Spatrick   }
9309467b48Spatrick }
9409467b48Spatrick 
DeleteDeadBlock(BasicBlock * BB,DomTreeUpdater * DTU,bool KeepOneInputPHIs)9509467b48Spatrick void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
9609467b48Spatrick                            bool KeepOneInputPHIs) {
9709467b48Spatrick   DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
9809467b48Spatrick }
9909467b48Spatrick 
DeleteDeadBlocks(ArrayRef<BasicBlock * > BBs,DomTreeUpdater * DTU,bool KeepOneInputPHIs)10009467b48Spatrick void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
10109467b48Spatrick                             bool KeepOneInputPHIs) {
10209467b48Spatrick #ifndef NDEBUG
10309467b48Spatrick   // Make sure that all predecessors of each dead block is also dead.
10409467b48Spatrick   SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
10509467b48Spatrick   assert(Dead.size() == BBs.size() && "Duplicating blocks?");
10609467b48Spatrick   for (auto *BB : Dead)
10709467b48Spatrick     for (BasicBlock *Pred : predecessors(BB))
10809467b48Spatrick       assert(Dead.count(Pred) && "All predecessors must be dead!");
10909467b48Spatrick #endif
11009467b48Spatrick 
11109467b48Spatrick   SmallVector<DominatorTree::UpdateType, 4> Updates;
112*d415bd75Srobert   detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
11309467b48Spatrick 
11409467b48Spatrick   if (DTU)
11573471bf0Spatrick     DTU->applyUpdates(Updates);
11609467b48Spatrick 
11709467b48Spatrick   for (BasicBlock *BB : BBs)
11809467b48Spatrick     if (DTU)
11909467b48Spatrick       DTU->deleteBB(BB);
12009467b48Spatrick     else
12109467b48Spatrick       BB->eraseFromParent();
12209467b48Spatrick }
12309467b48Spatrick 
EliminateUnreachableBlocks(Function & F,DomTreeUpdater * DTU,bool KeepOneInputPHIs)12409467b48Spatrick bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
12509467b48Spatrick                                       bool KeepOneInputPHIs) {
12609467b48Spatrick   df_iterator_default_set<BasicBlock*> Reachable;
12709467b48Spatrick 
12809467b48Spatrick   // Mark all reachable blocks.
12909467b48Spatrick   for (BasicBlock *BB : depth_first_ext(&F, Reachable))
13009467b48Spatrick     (void)BB/* Mark all reachable blocks */;
13109467b48Spatrick 
13209467b48Spatrick   // Collect all dead blocks.
13309467b48Spatrick   std::vector<BasicBlock*> DeadBlocks;
13473471bf0Spatrick   for (BasicBlock &BB : F)
13573471bf0Spatrick     if (!Reachable.count(&BB))
13673471bf0Spatrick       DeadBlocks.push_back(&BB);
13709467b48Spatrick 
13809467b48Spatrick   // Delete the dead blocks.
13909467b48Spatrick   DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
14009467b48Spatrick 
14109467b48Spatrick   return !DeadBlocks.empty();
14209467b48Spatrick }
14309467b48Spatrick 
FoldSingleEntryPHINodes(BasicBlock * BB,MemoryDependenceResults * MemDep)14473471bf0Spatrick bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
14509467b48Spatrick                                    MemoryDependenceResults *MemDep) {
14673471bf0Spatrick   if (!isa<PHINode>(BB->begin()))
14773471bf0Spatrick     return false;
14809467b48Spatrick 
14909467b48Spatrick   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
15009467b48Spatrick     if (PN->getIncomingValue(0) != PN)
15109467b48Spatrick       PN->replaceAllUsesWith(PN->getIncomingValue(0));
15209467b48Spatrick     else
153*d415bd75Srobert       PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
15409467b48Spatrick 
15509467b48Spatrick     if (MemDep)
15609467b48Spatrick       MemDep->removeInstruction(PN);  // Memdep updates AA itself.
15709467b48Spatrick 
15809467b48Spatrick     PN->eraseFromParent();
15909467b48Spatrick   }
16073471bf0Spatrick   return true;
16109467b48Spatrick }
16209467b48Spatrick 
DeleteDeadPHIs(BasicBlock * BB,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU)163097a140dSpatrick bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI,
164097a140dSpatrick                           MemorySSAUpdater *MSSAU) {
16509467b48Spatrick   // Recursively deleting a PHI may cause multiple PHIs to be deleted
16609467b48Spatrick   // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
16709467b48Spatrick   SmallVector<WeakTrackingVH, 8> PHIs;
16809467b48Spatrick   for (PHINode &PN : BB->phis())
16909467b48Spatrick     PHIs.push_back(&PN);
17009467b48Spatrick 
17109467b48Spatrick   bool Changed = false;
17209467b48Spatrick   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
17309467b48Spatrick     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
174097a140dSpatrick       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
17509467b48Spatrick 
17609467b48Spatrick   return Changed;
17709467b48Spatrick }
17809467b48Spatrick 
MergeBlockIntoPredecessor(BasicBlock * BB,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,MemoryDependenceResults * MemDep,bool PredecessorWithTwoSuccessors,DominatorTree * DT)17909467b48Spatrick bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
18009467b48Spatrick                                      LoopInfo *LI, MemorySSAUpdater *MSSAU,
18109467b48Spatrick                                      MemoryDependenceResults *MemDep,
182*d415bd75Srobert                                      bool PredecessorWithTwoSuccessors,
183*d415bd75Srobert                                      DominatorTree *DT) {
18409467b48Spatrick   if (BB->hasAddressTaken())
18509467b48Spatrick     return false;
18609467b48Spatrick 
18709467b48Spatrick   // Can't merge if there are multiple predecessors, or no predecessors.
18809467b48Spatrick   BasicBlock *PredBB = BB->getUniquePredecessor();
18909467b48Spatrick   if (!PredBB) return false;
19009467b48Spatrick 
19109467b48Spatrick   // Don't break self-loops.
19209467b48Spatrick   if (PredBB == BB) return false;
193*d415bd75Srobert 
194*d415bd75Srobert   // Don't break unwinding instructions or terminators with other side-effects.
195*d415bd75Srobert   Instruction *PTI = PredBB->getTerminator();
196*d415bd75Srobert   if (PTI->isExceptionalTerminator() || PTI->mayHaveSideEffects())
19709467b48Spatrick     return false;
19809467b48Spatrick 
19909467b48Spatrick   // Can't merge if there are multiple distinct successors.
20009467b48Spatrick   if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
20109467b48Spatrick     return false;
20209467b48Spatrick 
20309467b48Spatrick   // Currently only allow PredBB to have two predecessors, one being BB.
20409467b48Spatrick   // Update BI to branch to BB's only successor instead of BB.
20509467b48Spatrick   BranchInst *PredBB_BI;
20609467b48Spatrick   BasicBlock *NewSucc = nullptr;
20709467b48Spatrick   unsigned FallThruPath;
20809467b48Spatrick   if (PredecessorWithTwoSuccessors) {
209*d415bd75Srobert     if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
21009467b48Spatrick       return false;
21109467b48Spatrick     BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
21209467b48Spatrick     if (!BB_JmpI || !BB_JmpI->isUnconditional())
21309467b48Spatrick       return false;
21409467b48Spatrick     NewSucc = BB_JmpI->getSuccessor(0);
21509467b48Spatrick     FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
21609467b48Spatrick   }
21709467b48Spatrick 
21809467b48Spatrick   // Can't merge if there is PHI loop.
21909467b48Spatrick   for (PHINode &PN : BB->phis())
22073471bf0Spatrick     if (llvm::is_contained(PN.incoming_values(), &PN))
22109467b48Spatrick       return false;
22209467b48Spatrick 
22309467b48Spatrick   LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
22409467b48Spatrick                     << PredBB->getName() << "\n");
22509467b48Spatrick 
22609467b48Spatrick   // Begin by getting rid of unneeded PHIs.
22709467b48Spatrick   SmallVector<AssertingVH<Value>, 4> IncomingValues;
22809467b48Spatrick   if (isa<PHINode>(BB->front())) {
22909467b48Spatrick     for (PHINode &PN : BB->phis())
23009467b48Spatrick       if (!isa<PHINode>(PN.getIncomingValue(0)) ||
23109467b48Spatrick           cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
23209467b48Spatrick         IncomingValues.push_back(PN.getIncomingValue(0));
23309467b48Spatrick     FoldSingleEntryPHINodes(BB, MemDep);
23409467b48Spatrick   }
23509467b48Spatrick 
236*d415bd75Srobert   if (DT) {
237*d415bd75Srobert     assert(!DTU && "cannot use both DT and DTU for updates");
238*d415bd75Srobert     DomTreeNode *PredNode = DT->getNode(PredBB);
239*d415bd75Srobert     DomTreeNode *BBNode = DT->getNode(BB);
240*d415bd75Srobert     if (PredNode) {
241*d415bd75Srobert       assert(BBNode && "PredNode unreachable but BBNode reachable?");
242*d415bd75Srobert       for (DomTreeNode *C : to_vector(BBNode->children()))
243*d415bd75Srobert         C->setIDom(PredNode);
244*d415bd75Srobert     }
245*d415bd75Srobert   }
24609467b48Spatrick   // DTU update: Collect all the edges that exit BB.
24709467b48Spatrick   // These dominator edges will be redirected from Pred.
24809467b48Spatrick   std::vector<DominatorTree::UpdateType> Updates;
24909467b48Spatrick   if (DTU) {
250*d415bd75Srobert     assert(!DT && "cannot use both DT and DTU for updates");
251*d415bd75Srobert     // To avoid processing the same predecessor more than once.
252*d415bd75Srobert     SmallPtrSet<BasicBlock *, 8> SeenSuccs;
25373471bf0Spatrick     SmallPtrSet<BasicBlock *, 2> SuccsOfPredBB(succ_begin(PredBB),
254*d415bd75Srobert                                                succ_end(PredBB));
255*d415bd75Srobert     Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
25609467b48Spatrick     // Add insert edges first. Experimentally, for the particular case of two
25709467b48Spatrick     // blocks that can be merged, with a single successor and single predecessor
25809467b48Spatrick     // respectively, it is beneficial to have all insert updates first. Deleting
25909467b48Spatrick     // edges first may lead to unreachable blocks, followed by inserting edges
26009467b48Spatrick     // making the blocks reachable again. Such DT updates lead to high compile
26109467b48Spatrick     // times. We add inserts before deletes here to reduce compile time.
262*d415bd75Srobert     for (BasicBlock *SuccOfBB : successors(BB))
26373471bf0Spatrick       // This successor of BB may already be a PredBB's successor.
26473471bf0Spatrick       if (!SuccsOfPredBB.contains(SuccOfBB))
265*d415bd75Srobert         if (SeenSuccs.insert(SuccOfBB).second)
26673471bf0Spatrick           Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
267*d415bd75Srobert     SeenSuccs.clear();
268*d415bd75Srobert     for (BasicBlock *SuccOfBB : successors(BB))
269*d415bd75Srobert       if (SeenSuccs.insert(SuccOfBB).second)
27073471bf0Spatrick         Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
27109467b48Spatrick     Updates.push_back({DominatorTree::Delete, PredBB, BB});
27209467b48Spatrick   }
27309467b48Spatrick 
27409467b48Spatrick   Instruction *STI = BB->getTerminator();
27509467b48Spatrick   Instruction *Start = &*BB->begin();
27609467b48Spatrick   // If there's nothing to move, mark the starting instruction as the last
27709467b48Spatrick   // instruction in the block. Terminator instruction is handled separately.
27809467b48Spatrick   if (Start == STI)
27909467b48Spatrick     Start = PTI;
28009467b48Spatrick 
28109467b48Spatrick   // Move all definitions in the successor to the predecessor...
282*d415bd75Srobert   PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
28309467b48Spatrick 
28409467b48Spatrick   if (MSSAU)
28509467b48Spatrick     MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
28609467b48Spatrick 
28709467b48Spatrick   // Make all PHI nodes that referred to BB now refer to Pred as their
28809467b48Spatrick   // source...
28909467b48Spatrick   BB->replaceAllUsesWith(PredBB);
29009467b48Spatrick 
29109467b48Spatrick   if (PredecessorWithTwoSuccessors) {
29209467b48Spatrick     // Delete the unconditional branch from BB.
293*d415bd75Srobert     BB->back().eraseFromParent();
29409467b48Spatrick 
29509467b48Spatrick     // Update branch in the predecessor.
29609467b48Spatrick     PredBB_BI->setSuccessor(FallThruPath, NewSucc);
29709467b48Spatrick   } else {
29809467b48Spatrick     // Delete the unconditional branch from the predecessor.
299*d415bd75Srobert     PredBB->back().eraseFromParent();
30009467b48Spatrick 
30109467b48Spatrick     // Move terminator instruction.
302*d415bd75Srobert     PredBB->splice(PredBB->end(), BB);
30309467b48Spatrick 
30409467b48Spatrick     // Terminator may be a memory accessing instruction too.
30509467b48Spatrick     if (MSSAU)
30609467b48Spatrick       if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
30709467b48Spatrick               MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
30809467b48Spatrick         MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
30909467b48Spatrick   }
31009467b48Spatrick   // Add unreachable to now empty BB.
31109467b48Spatrick   new UnreachableInst(BB->getContext(), BB);
31209467b48Spatrick 
31309467b48Spatrick   // Inherit predecessors name if it exists.
31409467b48Spatrick   if (!PredBB->hasName())
31509467b48Spatrick     PredBB->takeName(BB);
31609467b48Spatrick 
31709467b48Spatrick   if (LI)
31809467b48Spatrick     LI->removeBlock(BB);
31909467b48Spatrick 
32009467b48Spatrick   if (MemDep)
32109467b48Spatrick     MemDep->invalidateCachedPredecessors();
32209467b48Spatrick 
32373471bf0Spatrick   if (DTU)
32473471bf0Spatrick     DTU->applyUpdates(Updates);
32573471bf0Spatrick 
326*d415bd75Srobert   if (DT) {
327*d415bd75Srobert     assert(succ_empty(BB) &&
328*d415bd75Srobert            "successors should have been transferred to PredBB");
329*d415bd75Srobert     DT->eraseNode(BB);
330*d415bd75Srobert   }
331*d415bd75Srobert 
33209467b48Spatrick   // Finally, erase the old block and update dominator info.
33373471bf0Spatrick   DeleteDeadBlock(BB, DTU);
33409467b48Spatrick 
33509467b48Spatrick   return true;
33609467b48Spatrick }
33709467b48Spatrick 
MergeBlockSuccessorsIntoGivenBlocks(SmallPtrSetImpl<BasicBlock * > & MergeBlocks,Loop * L,DomTreeUpdater * DTU,LoopInfo * LI)338097a140dSpatrick bool llvm::MergeBlockSuccessorsIntoGivenBlocks(
339097a140dSpatrick     SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU,
340097a140dSpatrick     LoopInfo *LI) {
341097a140dSpatrick   assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
342097a140dSpatrick 
343097a140dSpatrick   bool BlocksHaveBeenMerged = false;
344097a140dSpatrick   while (!MergeBlocks.empty()) {
345097a140dSpatrick     BasicBlock *BB = *MergeBlocks.begin();
346097a140dSpatrick     BasicBlock *Dest = BB->getSingleSuccessor();
347097a140dSpatrick     if (Dest && (!L || L->contains(Dest))) {
348097a140dSpatrick       BasicBlock *Fold = Dest->getUniquePredecessor();
349097a140dSpatrick       (void)Fold;
350097a140dSpatrick       if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
351097a140dSpatrick         assert(Fold == BB &&
352097a140dSpatrick                "Expecting BB to be unique predecessor of the Dest block");
353097a140dSpatrick         MergeBlocks.erase(Dest);
354097a140dSpatrick         BlocksHaveBeenMerged = true;
355097a140dSpatrick       } else
356097a140dSpatrick         MergeBlocks.erase(BB);
357097a140dSpatrick     } else
358097a140dSpatrick       MergeBlocks.erase(BB);
359097a140dSpatrick   }
360097a140dSpatrick   return BlocksHaveBeenMerged;
361097a140dSpatrick }
362097a140dSpatrick 
36309467b48Spatrick /// Remove redundant instructions within sequences of consecutive dbg.value
36409467b48Spatrick /// instructions. This is done using a backward scan to keep the last dbg.value
36509467b48Spatrick /// describing a specific variable/fragment.
36609467b48Spatrick ///
36709467b48Spatrick /// BackwardScan strategy:
36809467b48Spatrick /// ----------------------
36909467b48Spatrick /// Given a sequence of consecutive DbgValueInst like this
37009467b48Spatrick ///
37109467b48Spatrick ///   dbg.value ..., "x", FragmentX1  (*)
37209467b48Spatrick ///   dbg.value ..., "y", FragmentY1
37309467b48Spatrick ///   dbg.value ..., "x", FragmentX2
37409467b48Spatrick ///   dbg.value ..., "x", FragmentX1  (**)
37509467b48Spatrick ///
37609467b48Spatrick /// then the instruction marked with (*) can be removed (it is guaranteed to be
37709467b48Spatrick /// obsoleted by the instruction marked with (**) as the latter instruction is
37809467b48Spatrick /// describing the same variable using the same fragment info).
37909467b48Spatrick ///
38009467b48Spatrick /// Possible improvements:
38109467b48Spatrick /// - Check fully overlapping fragments and not only identical fragments.
38209467b48Spatrick /// - Support dbg.addr, dbg.declare. dbg.label, and possibly other meta
38309467b48Spatrick ///   instructions being part of the sequence of consecutive instructions.
removeRedundantDbgInstrsUsingBackwardScan(BasicBlock * BB)38409467b48Spatrick static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
38509467b48Spatrick   SmallVector<DbgValueInst *, 8> ToBeRemoved;
38609467b48Spatrick   SmallDenseSet<DebugVariable> VariableSet;
38709467b48Spatrick   for (auto &I : reverse(*BB)) {
38809467b48Spatrick     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
38909467b48Spatrick       DebugVariable Key(DVI->getVariable(),
39009467b48Spatrick                         DVI->getExpression(),
39109467b48Spatrick                         DVI->getDebugLoc()->getInlinedAt());
39209467b48Spatrick       auto R = VariableSet.insert(Key);
393*d415bd75Srobert       // If the variable fragment hasn't been seen before then we don't want
394*d415bd75Srobert       // to remove this dbg intrinsic.
395*d415bd75Srobert       if (R.second)
396*d415bd75Srobert         continue;
397*d415bd75Srobert 
398*d415bd75Srobert       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI)) {
399*d415bd75Srobert         // Don't delete dbg.assign intrinsics that are linked to instructions.
400*d415bd75Srobert         if (!at::getAssignmentInsts(DAI).empty())
401*d415bd75Srobert           continue;
402*d415bd75Srobert         // Unlinked dbg.assign intrinsics can be treated like dbg.values.
403*d415bd75Srobert       }
404*d415bd75Srobert 
40509467b48Spatrick       // If the same variable fragment is described more than once it is enough
40609467b48Spatrick       // to keep the last one (i.e. the first found since we for reverse
40709467b48Spatrick       // iteration).
40809467b48Spatrick       ToBeRemoved.push_back(DVI);
40909467b48Spatrick       continue;
41009467b48Spatrick     }
41109467b48Spatrick     // Sequence with consecutive dbg.value instrs ended. Clear the map to
41209467b48Spatrick     // restart identifying redundant instructions if case we find another
41309467b48Spatrick     // dbg.value sequence.
41409467b48Spatrick     VariableSet.clear();
41509467b48Spatrick   }
41609467b48Spatrick 
41709467b48Spatrick   for (auto &Instr : ToBeRemoved)
41809467b48Spatrick     Instr->eraseFromParent();
41909467b48Spatrick 
42009467b48Spatrick   return !ToBeRemoved.empty();
42109467b48Spatrick }
42209467b48Spatrick 
42309467b48Spatrick /// Remove redundant dbg.value instructions using a forward scan. This can
42409467b48Spatrick /// remove a dbg.value instruction that is redundant due to indicating that a
42509467b48Spatrick /// variable has the same value as already being indicated by an earlier
42609467b48Spatrick /// dbg.value.
42709467b48Spatrick ///
42809467b48Spatrick /// ForwardScan strategy:
42909467b48Spatrick /// ---------------------
43009467b48Spatrick /// Given two identical dbg.value instructions, separated by a block of
43109467b48Spatrick /// instructions that isn't describing the same variable, like this
43209467b48Spatrick ///
43309467b48Spatrick ///   dbg.value X1, "x", FragmentX1  (**)
43409467b48Spatrick ///   <block of instructions, none being "dbg.value ..., "x", ...">
43509467b48Spatrick ///   dbg.value X1, "x", FragmentX1  (*)
43609467b48Spatrick ///
43709467b48Spatrick /// then the instruction marked with (*) can be removed. Variable "x" is already
43809467b48Spatrick /// described as being mapped to the SSA value X1.
43909467b48Spatrick ///
44009467b48Spatrick /// Possible improvements:
44109467b48Spatrick /// - Keep track of non-overlapping fragments.
removeRedundantDbgInstrsUsingForwardScan(BasicBlock * BB)44209467b48Spatrick static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
44309467b48Spatrick   SmallVector<DbgValueInst *, 8> ToBeRemoved;
44473471bf0Spatrick   DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
44573471bf0Spatrick       VariableMap;
44609467b48Spatrick   for (auto &I : *BB) {
44709467b48Spatrick     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
448*d415bd75Srobert       DebugVariable Key(DVI->getVariable(), std::nullopt,
44909467b48Spatrick                         DVI->getDebugLoc()->getInlinedAt());
45009467b48Spatrick       auto VMI = VariableMap.find(Key);
451*d415bd75Srobert       auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
452*d415bd75Srobert       // A dbg.assign with no linked instructions can be treated like a
453*d415bd75Srobert       // dbg.value (i.e. can be deleted).
454*d415bd75Srobert       bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
455*d415bd75Srobert 
45609467b48Spatrick       // Update the map if we found a new value/expression describing the
45709467b48Spatrick       // variable, or if the variable wasn't mapped already.
45873471bf0Spatrick       SmallVector<Value *, 4> Values(DVI->getValues());
45973471bf0Spatrick       if (VMI == VariableMap.end() || VMI->second.first != Values ||
46009467b48Spatrick           VMI->second.second != DVI->getExpression()) {
461*d415bd75Srobert         // Use a sentinal value (nullptr) for the DIExpression when we see a
462*d415bd75Srobert         // linked dbg.assign so that the next debug intrinsic will never match
463*d415bd75Srobert         // it (i.e. always treat linked dbg.assigns as if they're unique).
464*d415bd75Srobert         if (IsDbgValueKind)
46573471bf0Spatrick           VariableMap[Key] = {Values, DVI->getExpression()};
466*d415bd75Srobert         else
467*d415bd75Srobert           VariableMap[Key] = {Values, nullptr};
46809467b48Spatrick         continue;
46909467b48Spatrick       }
470*d415bd75Srobert 
471*d415bd75Srobert       // Don't delete dbg.assign intrinsics that are linked to instructions.
472*d415bd75Srobert       if (!IsDbgValueKind)
473*d415bd75Srobert         continue;
47409467b48Spatrick       ToBeRemoved.push_back(DVI);
47509467b48Spatrick     }
47609467b48Spatrick   }
47709467b48Spatrick 
47809467b48Spatrick   for (auto &Instr : ToBeRemoved)
47909467b48Spatrick     Instr->eraseFromParent();
48009467b48Spatrick 
48109467b48Spatrick   return !ToBeRemoved.empty();
48209467b48Spatrick }
48309467b48Spatrick 
484*d415bd75Srobert /// Remove redundant undef dbg.assign intrinsic from an entry block using a
485*d415bd75Srobert /// forward scan.
486*d415bd75Srobert /// Strategy:
487*d415bd75Srobert /// ---------------------
488*d415bd75Srobert /// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
489*d415bd75Srobert /// linked to an intrinsic, and don't share an aggregate variable with a debug
490*d415bd75Srobert /// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
491*d415bd75Srobert /// that come before non-undef debug intrinsics for the variable are
492*d415bd75Srobert /// deleted. Given:
493*d415bd75Srobert ///
494*d415bd75Srobert ///   dbg.assign undef, "x", FragmentX1 (*)
495*d415bd75Srobert ///   <block of instructions, none being "dbg.value ..., "x", ...">
496*d415bd75Srobert ///   dbg.value %V, "x", FragmentX2
497*d415bd75Srobert ///   <block of instructions, none being "dbg.value ..., "x", ...">
498*d415bd75Srobert ///   dbg.assign undef, "x", FragmentX1
499*d415bd75Srobert ///
500*d415bd75Srobert /// then (only) the instruction marked with (*) can be removed.
501*d415bd75Srobert /// Possible improvements:
502*d415bd75Srobert /// - Keep track of non-overlapping fragments.
remomveUndefDbgAssignsFromEntryBlock(BasicBlock * BB)503*d415bd75Srobert static bool remomveUndefDbgAssignsFromEntryBlock(BasicBlock *BB) {
504*d415bd75Srobert   assert(BB->isEntryBlock() && "expected entry block");
505*d415bd75Srobert   SmallVector<DbgAssignIntrinsic *, 8> ToBeRemoved;
506*d415bd75Srobert   DenseSet<DebugVariable> SeenDefForAggregate;
507*d415bd75Srobert   // Returns the DebugVariable for DVI with no fragment info.
508*d415bd75Srobert   auto GetAggregateVariable = [](DbgValueInst *DVI) {
509*d415bd75Srobert     return DebugVariable(DVI->getVariable(), std::nullopt,
510*d415bd75Srobert                          DVI->getDebugLoc()->getInlinedAt());
511*d415bd75Srobert   };
512*d415bd75Srobert 
513*d415bd75Srobert   // Remove undef dbg.assign intrinsics that are encountered before
514*d415bd75Srobert   // any non-undef intrinsics from the entry block.
515*d415bd75Srobert   for (auto &I : *BB) {
516*d415bd75Srobert     DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I);
517*d415bd75Srobert     if (!DVI)
518*d415bd75Srobert       continue;
519*d415bd75Srobert     auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
520*d415bd75Srobert     bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
521*d415bd75Srobert     DebugVariable Aggregate = GetAggregateVariable(DVI);
522*d415bd75Srobert     if (!SeenDefForAggregate.contains(Aggregate)) {
523*d415bd75Srobert       bool IsKill = DVI->isKillLocation() && IsDbgValueKind;
524*d415bd75Srobert       if (!IsKill) {
525*d415bd75Srobert         SeenDefForAggregate.insert(Aggregate);
526*d415bd75Srobert       } else if (DAI) {
527*d415bd75Srobert         ToBeRemoved.push_back(DAI);
528*d415bd75Srobert       }
529*d415bd75Srobert     }
530*d415bd75Srobert   }
531*d415bd75Srobert 
532*d415bd75Srobert   for (DbgAssignIntrinsic *DAI : ToBeRemoved)
533*d415bd75Srobert     DAI->eraseFromParent();
534*d415bd75Srobert 
535*d415bd75Srobert   return !ToBeRemoved.empty();
536*d415bd75Srobert }
537*d415bd75Srobert 
RemoveRedundantDbgInstrs(BasicBlock * BB)53809467b48Spatrick bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) {
53909467b48Spatrick   bool MadeChanges = false;
54009467b48Spatrick   // By using the "backward scan" strategy before the "forward scan" strategy we
54109467b48Spatrick   // can remove both dbg.value (2) and (3) in a situation like this:
54209467b48Spatrick   //
54309467b48Spatrick   //   (1) dbg.value V1, "x", DIExpression()
54409467b48Spatrick   //       ...
54509467b48Spatrick   //   (2) dbg.value V2, "x", DIExpression()
54609467b48Spatrick   //   (3) dbg.value V1, "x", DIExpression()
54709467b48Spatrick   //
54809467b48Spatrick   // The backward scan will remove (2), it is made obsolete by (3). After
54909467b48Spatrick   // getting (2) out of the way, the foward scan will remove (3) since "x"
55009467b48Spatrick   // already is described as having the value V1 at (1).
55109467b48Spatrick   MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB);
552*d415bd75Srobert   if (BB->isEntryBlock() &&
553*d415bd75Srobert       isAssignmentTrackingEnabled(*BB->getParent()->getParent()))
554*d415bd75Srobert     MadeChanges |= remomveUndefDbgAssignsFromEntryBlock(BB);
55509467b48Spatrick   MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB);
55609467b48Spatrick 
55709467b48Spatrick   if (MadeChanges)
55809467b48Spatrick     LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
55909467b48Spatrick                       << BB->getName() << "\n");
56009467b48Spatrick   return MadeChanges;
56109467b48Spatrick }
56209467b48Spatrick 
ReplaceInstWithValue(BasicBlock::iterator & BI,Value * V)563*d415bd75Srobert void llvm::ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V) {
56409467b48Spatrick   Instruction &I = *BI;
56509467b48Spatrick   // Replaces all of the uses of the instruction with uses of the value
56609467b48Spatrick   I.replaceAllUsesWith(V);
56709467b48Spatrick 
56809467b48Spatrick   // Make sure to propagate a name if there is one already.
56909467b48Spatrick   if (I.hasName() && !V->hasName())
57009467b48Spatrick     V->takeName(&I);
57109467b48Spatrick 
57209467b48Spatrick   // Delete the unnecessary instruction now...
573*d415bd75Srobert   BI = BI->eraseFromParent();
57409467b48Spatrick }
57509467b48Spatrick 
ReplaceInstWithInst(BasicBlock * BB,BasicBlock::iterator & BI,Instruction * I)576*d415bd75Srobert void llvm::ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI,
577*d415bd75Srobert                                Instruction *I) {
57809467b48Spatrick   assert(I->getParent() == nullptr &&
57909467b48Spatrick          "ReplaceInstWithInst: Instruction already inserted into basic block!");
58009467b48Spatrick 
58109467b48Spatrick   // Copy debug location to newly added instruction, if it wasn't already set
58209467b48Spatrick   // by the caller.
58309467b48Spatrick   if (!I->getDebugLoc())
58409467b48Spatrick     I->setDebugLoc(BI->getDebugLoc());
58509467b48Spatrick 
58609467b48Spatrick   // Insert the new instruction into the basic block...
587*d415bd75Srobert   BasicBlock::iterator New = I->insertInto(BB, BI);
58809467b48Spatrick 
58909467b48Spatrick   // Replace all uses of the old instruction, and delete it.
590*d415bd75Srobert   ReplaceInstWithValue(BI, I);
59109467b48Spatrick 
59209467b48Spatrick   // Move BI back to point to the newly inserted instruction
59309467b48Spatrick   BI = New;
59409467b48Spatrick }
59509467b48Spatrick 
IsBlockFollowedByDeoptOrUnreachable(const BasicBlock * BB)596*d415bd75Srobert bool llvm::IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB) {
597*d415bd75Srobert   // Remember visited blocks to avoid infinite loop
598*d415bd75Srobert   SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
599*d415bd75Srobert   unsigned Depth = 0;
600*d415bd75Srobert   while (BB && Depth++ < MaxDeoptOrUnreachableSuccessorCheckDepth &&
601*d415bd75Srobert          VisitedBlocks.insert(BB).second) {
602*d415bd75Srobert     if (BB->getTerminatingDeoptimizeCall() ||
603*d415bd75Srobert         isa<UnreachableInst>(BB->getTerminator()))
604*d415bd75Srobert       return true;
605*d415bd75Srobert     BB = BB->getUniqueSuccessor();
606*d415bd75Srobert   }
607*d415bd75Srobert   return false;
608*d415bd75Srobert }
609*d415bd75Srobert 
ReplaceInstWithInst(Instruction * From,Instruction * To)61009467b48Spatrick void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
61109467b48Spatrick   BasicBlock::iterator BI(From);
612*d415bd75Srobert   ReplaceInstWithInst(From->getParent(), BI, To);
61309467b48Spatrick }
61409467b48Spatrick 
SplitEdge(BasicBlock * BB,BasicBlock * Succ,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName)61509467b48Spatrick BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
61673471bf0Spatrick                             LoopInfo *LI, MemorySSAUpdater *MSSAU,
61773471bf0Spatrick                             const Twine &BBName) {
61809467b48Spatrick   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
61909467b48Spatrick 
62009467b48Spatrick   Instruction *LatchTerm = BB->getTerminator();
62173471bf0Spatrick 
62273471bf0Spatrick   CriticalEdgeSplittingOptions Options =
62373471bf0Spatrick       CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA();
62473471bf0Spatrick 
62573471bf0Spatrick   if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
62673471bf0Spatrick     // If it is a critical edge, and the succesor is an exception block, handle
62773471bf0Spatrick     // the split edge logic in this specific function
62873471bf0Spatrick     if (Succ->isEHPad())
62973471bf0Spatrick       return ehAwareSplitEdge(BB, Succ, nullptr, nullptr, Options, BBName);
63073471bf0Spatrick 
63173471bf0Spatrick     // If this is a critical edge, let SplitKnownCriticalEdge do it.
63273471bf0Spatrick     return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
63373471bf0Spatrick   }
63409467b48Spatrick 
63509467b48Spatrick   // If the edge isn't critical, then BB has a single successor or Succ has a
63609467b48Spatrick   // single pred.  Split the block.
63709467b48Spatrick   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
63809467b48Spatrick     // If the successor only has a single pred, split the top of the successor
63909467b48Spatrick     // block.
64009467b48Spatrick     assert(SP == BB && "CFG broken");
64109467b48Spatrick     SP = nullptr;
64273471bf0Spatrick     return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
64373471bf0Spatrick                       /*Before=*/true);
64409467b48Spatrick   }
64509467b48Spatrick 
64609467b48Spatrick   // Otherwise, if BB has a single successor, split it at the bottom of the
64709467b48Spatrick   // block.
64809467b48Spatrick   assert(BB->getTerminator()->getNumSuccessors() == 1 &&
64909467b48Spatrick          "Should have a single succ!");
65073471bf0Spatrick   return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
65173471bf0Spatrick }
65273471bf0Spatrick 
setUnwindEdgeTo(Instruction * TI,BasicBlock * Succ)65373471bf0Spatrick void llvm::setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
65473471bf0Spatrick   if (auto *II = dyn_cast<InvokeInst>(TI))
65573471bf0Spatrick     II->setUnwindDest(Succ);
65673471bf0Spatrick   else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
65773471bf0Spatrick     CS->setUnwindDest(Succ);
65873471bf0Spatrick   else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
65973471bf0Spatrick     CR->setUnwindDest(Succ);
66073471bf0Spatrick   else
66173471bf0Spatrick     llvm_unreachable("unexpected terminator instruction");
66273471bf0Spatrick }
66373471bf0Spatrick 
updatePhiNodes(BasicBlock * DestBB,BasicBlock * OldPred,BasicBlock * NewPred,PHINode * Until)66473471bf0Spatrick void llvm::updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
66573471bf0Spatrick                           BasicBlock *NewPred, PHINode *Until) {
66673471bf0Spatrick   int BBIdx = 0;
66773471bf0Spatrick   for (PHINode &PN : DestBB->phis()) {
66873471bf0Spatrick     // We manually update the LandingPadReplacement PHINode and it is the last
66973471bf0Spatrick     // PHI Node. So, if we find it, we are done.
67073471bf0Spatrick     if (Until == &PN)
67173471bf0Spatrick       break;
67273471bf0Spatrick 
67373471bf0Spatrick     // Reuse the previous value of BBIdx if it lines up.  In cases where we
67473471bf0Spatrick     // have multiple phi nodes with *lots* of predecessors, this is a speed
67573471bf0Spatrick     // win because we don't have to scan the PHI looking for TIBB.  This
67673471bf0Spatrick     // happens because the BB list of PHI nodes are usually in the same
67773471bf0Spatrick     // order.
67873471bf0Spatrick     if (PN.getIncomingBlock(BBIdx) != OldPred)
67973471bf0Spatrick       BBIdx = PN.getBasicBlockIndex(OldPred);
68073471bf0Spatrick 
68173471bf0Spatrick     assert(BBIdx != -1 && "Invalid PHI Index!");
68273471bf0Spatrick     PN.setIncomingBlock(BBIdx, NewPred);
68373471bf0Spatrick   }
68473471bf0Spatrick }
68573471bf0Spatrick 
ehAwareSplitEdge(BasicBlock * BB,BasicBlock * Succ,LandingPadInst * OriginalPad,PHINode * LandingPadReplacement,const CriticalEdgeSplittingOptions & Options,const Twine & BBName)68673471bf0Spatrick BasicBlock *llvm::ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
68773471bf0Spatrick                                    LandingPadInst *OriginalPad,
68873471bf0Spatrick                                    PHINode *LandingPadReplacement,
68973471bf0Spatrick                                    const CriticalEdgeSplittingOptions &Options,
69073471bf0Spatrick                                    const Twine &BBName) {
69173471bf0Spatrick 
69273471bf0Spatrick   auto *PadInst = Succ->getFirstNonPHI();
69373471bf0Spatrick   if (!LandingPadReplacement && !PadInst->isEHPad())
69473471bf0Spatrick     return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
69573471bf0Spatrick 
69673471bf0Spatrick   auto *LI = Options.LI;
69773471bf0Spatrick   SmallVector<BasicBlock *, 4> LoopPreds;
69873471bf0Spatrick   // Check if extra modifications will be required to preserve loop-simplify
69973471bf0Spatrick   // form after splitting. If it would require splitting blocks with IndirectBr
70073471bf0Spatrick   // terminators, bail out if preserving loop-simplify form is requested.
70173471bf0Spatrick   if (Options.PreserveLoopSimplify && LI) {
70273471bf0Spatrick     if (Loop *BBLoop = LI->getLoopFor(BB)) {
70373471bf0Spatrick 
70473471bf0Spatrick       // The only way that we can break LoopSimplify form by splitting a
70573471bf0Spatrick       // critical edge is when there exists some edge from BBLoop to Succ *and*
70673471bf0Spatrick       // the only edge into Succ from outside of BBLoop is that of NewBB after
70773471bf0Spatrick       // the split. If the first isn't true, then LoopSimplify still holds,
70873471bf0Spatrick       // NewBB is the new exit block and it has no non-loop predecessors. If the
70973471bf0Spatrick       // second isn't true, then Succ was not in LoopSimplify form prior to
71073471bf0Spatrick       // the split as it had a non-loop predecessor. In both of these cases,
71173471bf0Spatrick       // the predecessor must be directly in BBLoop, not in a subloop, or again
71273471bf0Spatrick       // LoopSimplify doesn't hold.
71373471bf0Spatrick       for (BasicBlock *P : predecessors(Succ)) {
71473471bf0Spatrick         if (P == BB)
71573471bf0Spatrick           continue; // The new block is known.
71673471bf0Spatrick         if (LI->getLoopFor(P) != BBLoop) {
71773471bf0Spatrick           // Loop is not in LoopSimplify form, no need to re simplify after
71873471bf0Spatrick           // splitting edge.
71973471bf0Spatrick           LoopPreds.clear();
72073471bf0Spatrick           break;
72173471bf0Spatrick         }
72273471bf0Spatrick         LoopPreds.push_back(P);
72373471bf0Spatrick       }
72473471bf0Spatrick       // Loop-simplify form can be preserved, if we can split all in-loop
72573471bf0Spatrick       // predecessors.
72673471bf0Spatrick       if (any_of(LoopPreds, [](BasicBlock *Pred) {
72773471bf0Spatrick             return isa<IndirectBrInst>(Pred->getTerminator());
72873471bf0Spatrick           })) {
72973471bf0Spatrick         return nullptr;
73073471bf0Spatrick       }
73173471bf0Spatrick     }
73273471bf0Spatrick   }
73373471bf0Spatrick 
73473471bf0Spatrick   auto *NewBB =
73573471bf0Spatrick       BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
73673471bf0Spatrick   setUnwindEdgeTo(BB->getTerminator(), NewBB);
73773471bf0Spatrick   updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
73873471bf0Spatrick 
73973471bf0Spatrick   if (LandingPadReplacement) {
74073471bf0Spatrick     auto *NewLP = OriginalPad->clone();
74173471bf0Spatrick     auto *Terminator = BranchInst::Create(Succ, NewBB);
74273471bf0Spatrick     NewLP->insertBefore(Terminator);
74373471bf0Spatrick     LandingPadReplacement->addIncoming(NewLP, NewBB);
74473471bf0Spatrick   } else {
74573471bf0Spatrick     Value *ParentPad = nullptr;
74673471bf0Spatrick     if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
74773471bf0Spatrick       ParentPad = FuncletPad->getParentPad();
74873471bf0Spatrick     else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
74973471bf0Spatrick       ParentPad = CatchSwitch->getParentPad();
75073471bf0Spatrick     else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
75173471bf0Spatrick       ParentPad = CleanupPad->getParentPad();
75273471bf0Spatrick     else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
75373471bf0Spatrick       ParentPad = LandingPad->getParent();
75473471bf0Spatrick     else
75573471bf0Spatrick       llvm_unreachable("handling for other EHPads not implemented yet");
75673471bf0Spatrick 
75773471bf0Spatrick     auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
75873471bf0Spatrick     CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
75973471bf0Spatrick   }
76073471bf0Spatrick 
76173471bf0Spatrick   auto *DT = Options.DT;
76273471bf0Spatrick   auto *MSSAU = Options.MSSAU;
76373471bf0Spatrick   if (!DT && !LI)
76473471bf0Spatrick     return NewBB;
76573471bf0Spatrick 
76673471bf0Spatrick   if (DT) {
76773471bf0Spatrick     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
76873471bf0Spatrick     SmallVector<DominatorTree::UpdateType, 3> Updates;
76973471bf0Spatrick 
77073471bf0Spatrick     Updates.push_back({DominatorTree::Insert, BB, NewBB});
77173471bf0Spatrick     Updates.push_back({DominatorTree::Insert, NewBB, Succ});
77273471bf0Spatrick     Updates.push_back({DominatorTree::Delete, BB, Succ});
77373471bf0Spatrick 
77473471bf0Spatrick     DTU.applyUpdates(Updates);
77573471bf0Spatrick     DTU.flush();
77673471bf0Spatrick 
77773471bf0Spatrick     if (MSSAU) {
77873471bf0Spatrick       MSSAU->applyUpdates(Updates, *DT);
77973471bf0Spatrick       if (VerifyMemorySSA)
78073471bf0Spatrick         MSSAU->getMemorySSA()->verifyMemorySSA();
78173471bf0Spatrick     }
78273471bf0Spatrick   }
78373471bf0Spatrick 
78473471bf0Spatrick   if (LI) {
78573471bf0Spatrick     if (Loop *BBLoop = LI->getLoopFor(BB)) {
78673471bf0Spatrick       // If one or the other blocks were not in a loop, the new block is not
78773471bf0Spatrick       // either, and thus LI doesn't need to be updated.
78873471bf0Spatrick       if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
78973471bf0Spatrick         if (BBLoop == SuccLoop) {
79073471bf0Spatrick           // Both in the same loop, the NewBB joins loop.
79173471bf0Spatrick           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
79273471bf0Spatrick         } else if (BBLoop->contains(SuccLoop)) {
79373471bf0Spatrick           // Edge from an outer loop to an inner loop.  Add to the outer loop.
79473471bf0Spatrick           BBLoop->addBasicBlockToLoop(NewBB, *LI);
79573471bf0Spatrick         } else if (SuccLoop->contains(BBLoop)) {
79673471bf0Spatrick           // Edge from an inner loop to an outer loop.  Add to the outer loop.
79773471bf0Spatrick           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
79873471bf0Spatrick         } else {
79973471bf0Spatrick           // Edge from two loops with no containment relation.  Because these
80073471bf0Spatrick           // are natural loops, we know that the destination block must be the
80173471bf0Spatrick           // header of its loop (adding a branch into a loop elsewhere would
80273471bf0Spatrick           // create an irreducible loop).
80373471bf0Spatrick           assert(SuccLoop->getHeader() == Succ &&
80473471bf0Spatrick                  "Should not create irreducible loops!");
80573471bf0Spatrick           if (Loop *P = SuccLoop->getParentLoop())
80673471bf0Spatrick             P->addBasicBlockToLoop(NewBB, *LI);
80773471bf0Spatrick         }
80873471bf0Spatrick       }
80973471bf0Spatrick 
81073471bf0Spatrick       // If BB is in a loop and Succ is outside of that loop, we may need to
81173471bf0Spatrick       // update LoopSimplify form and LCSSA form.
81273471bf0Spatrick       if (!BBLoop->contains(Succ)) {
81373471bf0Spatrick         assert(!BBLoop->contains(NewBB) &&
81473471bf0Spatrick                "Split point for loop exit is contained in loop!");
81573471bf0Spatrick 
81673471bf0Spatrick         // Update LCSSA form in the newly created exit block.
81773471bf0Spatrick         if (Options.PreserveLCSSA) {
81873471bf0Spatrick           createPHIsForSplitLoopExit(BB, NewBB, Succ);
81973471bf0Spatrick         }
82073471bf0Spatrick 
82173471bf0Spatrick         if (!LoopPreds.empty()) {
82273471bf0Spatrick           BasicBlock *NewExitBB = SplitBlockPredecessors(
82373471bf0Spatrick               Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
82473471bf0Spatrick           if (Options.PreserveLCSSA)
82573471bf0Spatrick             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
82673471bf0Spatrick         }
82773471bf0Spatrick       }
82873471bf0Spatrick     }
82973471bf0Spatrick   }
83073471bf0Spatrick 
83173471bf0Spatrick   return NewBB;
83273471bf0Spatrick }
83373471bf0Spatrick 
createPHIsForSplitLoopExit(ArrayRef<BasicBlock * > Preds,BasicBlock * SplitBB,BasicBlock * DestBB)83473471bf0Spatrick void llvm::createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
83573471bf0Spatrick                                       BasicBlock *SplitBB, BasicBlock *DestBB) {
83673471bf0Spatrick   // SplitBB shouldn't have anything non-trivial in it yet.
83773471bf0Spatrick   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
83873471bf0Spatrick           SplitBB->isLandingPad()) &&
83973471bf0Spatrick          "SplitBB has non-PHI nodes!");
84073471bf0Spatrick 
84173471bf0Spatrick   // For each PHI in the destination block.
84273471bf0Spatrick   for (PHINode &PN : DestBB->phis()) {
84373471bf0Spatrick     int Idx = PN.getBasicBlockIndex(SplitBB);
84473471bf0Spatrick     assert(Idx >= 0 && "Invalid Block Index");
84573471bf0Spatrick     Value *V = PN.getIncomingValue(Idx);
84673471bf0Spatrick 
84773471bf0Spatrick     // If the input is a PHI which already satisfies LCSSA, don't create
84873471bf0Spatrick     // a new one.
84973471bf0Spatrick     if (const PHINode *VP = dyn_cast<PHINode>(V))
85073471bf0Spatrick       if (VP->getParent() == SplitBB)
85173471bf0Spatrick         continue;
85273471bf0Spatrick 
85373471bf0Spatrick     // Otherwise a new PHI is needed. Create one and populate it.
85473471bf0Spatrick     PHINode *NewPN = PHINode::Create(
85573471bf0Spatrick         PN.getType(), Preds.size(), "split",
85673471bf0Spatrick         SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
85773471bf0Spatrick     for (BasicBlock *BB : Preds)
85873471bf0Spatrick       NewPN->addIncoming(V, BB);
85973471bf0Spatrick 
86073471bf0Spatrick     // Update the original PHI.
86173471bf0Spatrick     PN.setIncomingValue(Idx, NewPN);
86273471bf0Spatrick   }
86309467b48Spatrick }
86409467b48Spatrick 
86509467b48Spatrick unsigned
SplitAllCriticalEdges(Function & F,const CriticalEdgeSplittingOptions & Options)86609467b48Spatrick llvm::SplitAllCriticalEdges(Function &F,
86709467b48Spatrick                             const CriticalEdgeSplittingOptions &Options) {
86809467b48Spatrick   unsigned NumBroken = 0;
86909467b48Spatrick   for (BasicBlock &BB : F) {
87009467b48Spatrick     Instruction *TI = BB.getTerminator();
871*d415bd75Srobert     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
87209467b48Spatrick       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
87309467b48Spatrick         if (SplitCriticalEdge(TI, i, Options))
87409467b48Spatrick           ++NumBroken;
87509467b48Spatrick   }
87609467b48Spatrick   return NumBroken;
87709467b48Spatrick }
87809467b48Spatrick 
SplitBlockImpl(BasicBlock * Old,Instruction * SplitPt,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)87973471bf0Spatrick static BasicBlock *SplitBlockImpl(BasicBlock *Old, Instruction *SplitPt,
88073471bf0Spatrick                                   DomTreeUpdater *DTU, DominatorTree *DT,
88173471bf0Spatrick                                   LoopInfo *LI, MemorySSAUpdater *MSSAU,
88273471bf0Spatrick                                   const Twine &BBName, bool Before) {
88373471bf0Spatrick   if (Before) {
88473471bf0Spatrick     DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
88573471bf0Spatrick     return splitBlockBefore(Old, SplitPt,
88673471bf0Spatrick                             DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
88773471bf0Spatrick                             BBName);
88873471bf0Spatrick   }
88909467b48Spatrick   BasicBlock::iterator SplitIt = SplitPt->getIterator();
89073471bf0Spatrick   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
89109467b48Spatrick     ++SplitIt;
89273471bf0Spatrick     assert(SplitIt != SplitPt->getParent()->end());
89373471bf0Spatrick   }
89409467b48Spatrick   std::string Name = BBName.str();
89509467b48Spatrick   BasicBlock *New = Old->splitBasicBlock(
89609467b48Spatrick       SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
89709467b48Spatrick 
89809467b48Spatrick   // The new block lives in whichever loop the old one did. This preserves
89909467b48Spatrick   // LCSSA as well, because we force the split point to be after any PHI nodes.
90009467b48Spatrick   if (LI)
90109467b48Spatrick     if (Loop *L = LI->getLoopFor(Old))
90209467b48Spatrick       L->addBasicBlockToLoop(New, *LI);
90309467b48Spatrick 
90473471bf0Spatrick   if (DTU) {
90573471bf0Spatrick     SmallVector<DominatorTree::UpdateType, 8> Updates;
90673471bf0Spatrick     // Old dominates New. New node dominates all other nodes dominated by Old.
907*d415bd75Srobert     SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
90873471bf0Spatrick     Updates.push_back({DominatorTree::Insert, Old, New});
909*d415bd75Srobert     Updates.reserve(Updates.size() + 2 * succ_size(New));
910*d415bd75Srobert     for (BasicBlock *SuccessorOfOld : successors(New))
911*d415bd75Srobert       if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
912*d415bd75Srobert         Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
913*d415bd75Srobert         Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
91473471bf0Spatrick       }
91573471bf0Spatrick 
91673471bf0Spatrick     DTU->applyUpdates(Updates);
91773471bf0Spatrick   } else if (DT)
91809467b48Spatrick     // Old dominates New. New node dominates all other nodes dominated by Old.
91909467b48Spatrick     if (DomTreeNode *OldNode = DT->getNode(Old)) {
92009467b48Spatrick       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
92109467b48Spatrick 
92209467b48Spatrick       DomTreeNode *NewNode = DT->addNewBlock(New, Old);
92309467b48Spatrick       for (DomTreeNode *I : Children)
92409467b48Spatrick         DT->changeImmediateDominator(I, NewNode);
92509467b48Spatrick     }
92609467b48Spatrick 
92709467b48Spatrick   // Move MemoryAccesses still tracked in Old, but part of New now.
92809467b48Spatrick   // Update accesses in successor blocks accordingly.
92909467b48Spatrick   if (MSSAU)
93009467b48Spatrick     MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
93109467b48Spatrick 
93209467b48Spatrick   return New;
93309467b48Spatrick }
93409467b48Spatrick 
SplitBlock(BasicBlock * Old,Instruction * SplitPt,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)93573471bf0Spatrick BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
93673471bf0Spatrick                              DominatorTree *DT, LoopInfo *LI,
93773471bf0Spatrick                              MemorySSAUpdater *MSSAU, const Twine &BBName,
93873471bf0Spatrick                              bool Before) {
93973471bf0Spatrick   return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
94073471bf0Spatrick                         Before);
94173471bf0Spatrick }
SplitBlock(BasicBlock * Old,Instruction * SplitPt,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)94273471bf0Spatrick BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
94373471bf0Spatrick                              DomTreeUpdater *DTU, LoopInfo *LI,
94473471bf0Spatrick                              MemorySSAUpdater *MSSAU, const Twine &BBName,
94573471bf0Spatrick                              bool Before) {
94673471bf0Spatrick   return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
94773471bf0Spatrick                         Before);
94873471bf0Spatrick }
94973471bf0Spatrick 
splitBlockBefore(BasicBlock * Old,Instruction * SplitPt,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName)95073471bf0Spatrick BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, Instruction *SplitPt,
95173471bf0Spatrick                                    DomTreeUpdater *DTU, LoopInfo *LI,
95273471bf0Spatrick                                    MemorySSAUpdater *MSSAU,
95373471bf0Spatrick                                    const Twine &BBName) {
95473471bf0Spatrick 
95573471bf0Spatrick   BasicBlock::iterator SplitIt = SplitPt->getIterator();
95673471bf0Spatrick   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
95773471bf0Spatrick     ++SplitIt;
95873471bf0Spatrick   std::string Name = BBName.str();
95973471bf0Spatrick   BasicBlock *New = Old->splitBasicBlock(
96073471bf0Spatrick       SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
96173471bf0Spatrick       /* Before=*/true);
96273471bf0Spatrick 
96373471bf0Spatrick   // The new block lives in whichever loop the old one did. This preserves
96473471bf0Spatrick   // LCSSA as well, because we force the split point to be after any PHI nodes.
96573471bf0Spatrick   if (LI)
96673471bf0Spatrick     if (Loop *L = LI->getLoopFor(Old))
96773471bf0Spatrick       L->addBasicBlockToLoop(New, *LI);
96873471bf0Spatrick 
96973471bf0Spatrick   if (DTU) {
97073471bf0Spatrick     SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
97173471bf0Spatrick     // New dominates Old. The predecessor nodes of the Old node dominate
97273471bf0Spatrick     // New node.
973*d415bd75Srobert     SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
97473471bf0Spatrick     DTUpdates.push_back({DominatorTree::Insert, New, Old});
975*d415bd75Srobert     DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
976*d415bd75Srobert     for (BasicBlock *PredecessorOfOld : predecessors(New))
977*d415bd75Srobert       if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
978*d415bd75Srobert         DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
979*d415bd75Srobert         DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
98073471bf0Spatrick       }
98173471bf0Spatrick 
98273471bf0Spatrick     DTU->applyUpdates(DTUpdates);
98373471bf0Spatrick 
98473471bf0Spatrick     // Move MemoryAccesses still tracked in Old, but part of New now.
98573471bf0Spatrick     // Update accesses in successor blocks accordingly.
98673471bf0Spatrick     if (MSSAU) {
98773471bf0Spatrick       MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
98873471bf0Spatrick       if (VerifyMemorySSA)
98973471bf0Spatrick         MSSAU->getMemorySSA()->verifyMemorySSA();
99073471bf0Spatrick     }
99173471bf0Spatrick   }
99273471bf0Spatrick   return New;
99373471bf0Spatrick }
99473471bf0Spatrick 
99509467b48Spatrick /// Update DominatorTree, LoopInfo, and LCCSA analysis information.
UpdateAnalysisInformation(BasicBlock * OldBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA,bool & HasLoopExit)99609467b48Spatrick static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
99709467b48Spatrick                                       ArrayRef<BasicBlock *> Preds,
99873471bf0Spatrick                                       DomTreeUpdater *DTU, DominatorTree *DT,
99973471bf0Spatrick                                       LoopInfo *LI, MemorySSAUpdater *MSSAU,
100009467b48Spatrick                                       bool PreserveLCSSA, bool &HasLoopExit) {
100109467b48Spatrick   // Update dominator tree if available.
100273471bf0Spatrick   if (DTU) {
100373471bf0Spatrick     // Recalculation of DomTree is needed when updating a forward DomTree and
100473471bf0Spatrick     // the Entry BB is replaced.
100573471bf0Spatrick     if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
100673471bf0Spatrick       // The entry block was removed and there is no external interface for
100773471bf0Spatrick       // the dominator tree to be notified of this change. In this corner-case
100873471bf0Spatrick       // we recalculate the entire tree.
100973471bf0Spatrick       DTU->recalculate(*NewBB->getParent());
101073471bf0Spatrick     } else {
101173471bf0Spatrick       // Split block expects NewBB to have a non-empty set of predecessors.
101273471bf0Spatrick       SmallVector<DominatorTree::UpdateType, 8> Updates;
1013*d415bd75Srobert       SmallPtrSet<BasicBlock *, 8> UniquePreds;
101473471bf0Spatrick       Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
1015*d415bd75Srobert       Updates.reserve(Updates.size() + 2 * Preds.size());
1016*d415bd75Srobert       for (auto *Pred : Preds)
1017*d415bd75Srobert         if (UniquePreds.insert(Pred).second) {
1018*d415bd75Srobert           Updates.push_back({DominatorTree::Insert, Pred, NewBB});
1019*d415bd75Srobert           Updates.push_back({DominatorTree::Delete, Pred, OldBB});
102073471bf0Spatrick         }
102173471bf0Spatrick       DTU->applyUpdates(Updates);
102273471bf0Spatrick     }
102373471bf0Spatrick   } else if (DT) {
102409467b48Spatrick     if (OldBB == DT->getRootNode()->getBlock()) {
102573471bf0Spatrick       assert(NewBB->isEntryBlock());
102609467b48Spatrick       DT->setNewRoot(NewBB);
102709467b48Spatrick     } else {
102809467b48Spatrick       // Split block expects NewBB to have a non-empty set of predecessors.
102909467b48Spatrick       DT->splitBlock(NewBB);
103009467b48Spatrick     }
103109467b48Spatrick   }
103209467b48Spatrick 
103309467b48Spatrick   // Update MemoryPhis after split if MemorySSA is available
103409467b48Spatrick   if (MSSAU)
103509467b48Spatrick     MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
103609467b48Spatrick 
103709467b48Spatrick   // The rest of the logic is only relevant for updating the loop structures.
103809467b48Spatrick   if (!LI)
103909467b48Spatrick     return;
104009467b48Spatrick 
104173471bf0Spatrick   if (DTU && DTU->hasDomTree())
104273471bf0Spatrick     DT = &DTU->getDomTree();
104309467b48Spatrick   assert(DT && "DT should be available to update LoopInfo!");
104409467b48Spatrick   Loop *L = LI->getLoopFor(OldBB);
104509467b48Spatrick 
104609467b48Spatrick   // If we need to preserve loop analyses, collect some information about how
104709467b48Spatrick   // this split will affect loops.
104809467b48Spatrick   bool IsLoopEntry = !!L;
104909467b48Spatrick   bool SplitMakesNewLoopHeader = false;
105009467b48Spatrick   for (BasicBlock *Pred : Preds) {
105109467b48Spatrick     // Preds that are not reachable from entry should not be used to identify if
105209467b48Spatrick     // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
105309467b48Spatrick     // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
105409467b48Spatrick     // as true and make the NewBB the header of some loop. This breaks LI.
105509467b48Spatrick     if (!DT->isReachableFromEntry(Pred))
105609467b48Spatrick       continue;
105709467b48Spatrick     // If we need to preserve LCSSA, determine if any of the preds is a loop
105809467b48Spatrick     // exit.
105909467b48Spatrick     if (PreserveLCSSA)
106009467b48Spatrick       if (Loop *PL = LI->getLoopFor(Pred))
106109467b48Spatrick         if (!PL->contains(OldBB))
106209467b48Spatrick           HasLoopExit = true;
106309467b48Spatrick 
106409467b48Spatrick     // If we need to preserve LoopInfo, note whether any of the preds crosses
106509467b48Spatrick     // an interesting loop boundary.
106609467b48Spatrick     if (!L)
106709467b48Spatrick       continue;
106809467b48Spatrick     if (L->contains(Pred))
106909467b48Spatrick       IsLoopEntry = false;
107009467b48Spatrick     else
107109467b48Spatrick       SplitMakesNewLoopHeader = true;
107209467b48Spatrick   }
107309467b48Spatrick 
107409467b48Spatrick   // Unless we have a loop for OldBB, nothing else to do here.
107509467b48Spatrick   if (!L)
107609467b48Spatrick     return;
107709467b48Spatrick 
107809467b48Spatrick   if (IsLoopEntry) {
107909467b48Spatrick     // Add the new block to the nearest enclosing loop (and not an adjacent
108009467b48Spatrick     // loop). To find this, examine each of the predecessors and determine which
108109467b48Spatrick     // loops enclose them, and select the most-nested loop which contains the
108209467b48Spatrick     // loop containing the block being split.
108309467b48Spatrick     Loop *InnermostPredLoop = nullptr;
108409467b48Spatrick     for (BasicBlock *Pred : Preds) {
108509467b48Spatrick       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
108609467b48Spatrick         // Seek a loop which actually contains the block being split (to avoid
108709467b48Spatrick         // adjacent loops).
108809467b48Spatrick         while (PredLoop && !PredLoop->contains(OldBB))
108909467b48Spatrick           PredLoop = PredLoop->getParentLoop();
109009467b48Spatrick 
109109467b48Spatrick         // Select the most-nested of these loops which contains the block.
109209467b48Spatrick         if (PredLoop && PredLoop->contains(OldBB) &&
109309467b48Spatrick             (!InnermostPredLoop ||
109409467b48Spatrick              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
109509467b48Spatrick           InnermostPredLoop = PredLoop;
109609467b48Spatrick       }
109709467b48Spatrick     }
109809467b48Spatrick 
109909467b48Spatrick     if (InnermostPredLoop)
110009467b48Spatrick       InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
110109467b48Spatrick   } else {
110209467b48Spatrick     L->addBasicBlockToLoop(NewBB, *LI);
110309467b48Spatrick     if (SplitMakesNewLoopHeader)
110409467b48Spatrick       L->moveToHeader(NewBB);
110509467b48Spatrick   }
110609467b48Spatrick }
110709467b48Spatrick 
110809467b48Spatrick /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
110909467b48Spatrick /// This also updates AliasAnalysis, if available.
UpdatePHINodes(BasicBlock * OrigBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,BranchInst * BI,bool HasLoopExit)111009467b48Spatrick static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
111109467b48Spatrick                            ArrayRef<BasicBlock *> Preds, BranchInst *BI,
111209467b48Spatrick                            bool HasLoopExit) {
111309467b48Spatrick   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
111409467b48Spatrick   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
111509467b48Spatrick   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
111609467b48Spatrick     PHINode *PN = cast<PHINode>(I++);
111709467b48Spatrick 
111809467b48Spatrick     // Check to see if all of the values coming in are the same.  If so, we
111909467b48Spatrick     // don't need to create a new PHI node, unless it's needed for LCSSA.
112009467b48Spatrick     Value *InVal = nullptr;
112109467b48Spatrick     if (!HasLoopExit) {
112209467b48Spatrick       InVal = PN->getIncomingValueForBlock(Preds[0]);
112309467b48Spatrick       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
112409467b48Spatrick         if (!PredSet.count(PN->getIncomingBlock(i)))
112509467b48Spatrick           continue;
112609467b48Spatrick         if (!InVal)
112709467b48Spatrick           InVal = PN->getIncomingValue(i);
112809467b48Spatrick         else if (InVal != PN->getIncomingValue(i)) {
112909467b48Spatrick           InVal = nullptr;
113009467b48Spatrick           break;
113109467b48Spatrick         }
113209467b48Spatrick       }
113309467b48Spatrick     }
113409467b48Spatrick 
113509467b48Spatrick     if (InVal) {
113609467b48Spatrick       // If all incoming values for the new PHI would be the same, just don't
113709467b48Spatrick       // make a new PHI.  Instead, just remove the incoming values from the old
113809467b48Spatrick       // PHI.
113909467b48Spatrick 
114009467b48Spatrick       // NOTE! This loop walks backwards for a reason! First off, this minimizes
114109467b48Spatrick       // the cost of removal if we end up removing a large number of values, and
114209467b48Spatrick       // second off, this ensures that the indices for the incoming values
114309467b48Spatrick       // aren't invalidated when we remove one.
114409467b48Spatrick       for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
114509467b48Spatrick         if (PredSet.count(PN->getIncomingBlock(i)))
114609467b48Spatrick           PN->removeIncomingValue(i, false);
114709467b48Spatrick 
114809467b48Spatrick       // Add an incoming value to the PHI node in the loop for the preheader
114909467b48Spatrick       // edge.
115009467b48Spatrick       PN->addIncoming(InVal, NewBB);
115109467b48Spatrick       continue;
115209467b48Spatrick     }
115309467b48Spatrick 
115409467b48Spatrick     // If the values coming into the block are not the same, we need a new
115509467b48Spatrick     // PHI.
115609467b48Spatrick     // Create the new PHI node, insert it into NewBB at the end of the block
115709467b48Spatrick     PHINode *NewPHI =
115809467b48Spatrick         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
115909467b48Spatrick 
116009467b48Spatrick     // NOTE! This loop walks backwards for a reason! First off, this minimizes
116109467b48Spatrick     // the cost of removal if we end up removing a large number of values, and
116209467b48Spatrick     // second off, this ensures that the indices for the incoming values aren't
116309467b48Spatrick     // invalidated when we remove one.
116409467b48Spatrick     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
116509467b48Spatrick       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
116609467b48Spatrick       if (PredSet.count(IncomingBB)) {
116709467b48Spatrick         Value *V = PN->removeIncomingValue(i, false);
116809467b48Spatrick         NewPHI->addIncoming(V, IncomingBB);
116909467b48Spatrick       }
117009467b48Spatrick     }
117109467b48Spatrick 
117209467b48Spatrick     PN->addIncoming(NewPHI, NewBB);
117309467b48Spatrick   }
117409467b48Spatrick }
117509467b48Spatrick 
117673471bf0Spatrick static void SplitLandingPadPredecessorsImpl(
117773471bf0Spatrick     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
117873471bf0Spatrick     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
117973471bf0Spatrick     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
118073471bf0Spatrick     MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
118173471bf0Spatrick 
118273471bf0Spatrick static BasicBlock *
SplitBlockPredecessorsImpl(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)118373471bf0Spatrick SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
118473471bf0Spatrick                            const char *Suffix, DomTreeUpdater *DTU,
118573471bf0Spatrick                            DominatorTree *DT, LoopInfo *LI,
118673471bf0Spatrick                            MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
118709467b48Spatrick   // Do not attempt to split that which cannot be split.
118809467b48Spatrick   if (!BB->canSplitPredecessors())
118909467b48Spatrick     return nullptr;
119009467b48Spatrick 
119109467b48Spatrick   // For the landingpads we need to act a bit differently.
119209467b48Spatrick   // Delegate this work to the SplitLandingPadPredecessors.
119309467b48Spatrick   if (BB->isLandingPad()) {
119409467b48Spatrick     SmallVector<BasicBlock*, 2> NewBBs;
119509467b48Spatrick     std::string NewName = std::string(Suffix) + ".split-lp";
119609467b48Spatrick 
119773471bf0Spatrick     SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
119873471bf0Spatrick                                     DTU, DT, LI, MSSAU, PreserveLCSSA);
119909467b48Spatrick     return NewBBs[0];
120009467b48Spatrick   }
120109467b48Spatrick 
120209467b48Spatrick   // Create new basic block, insert right before the original block.
120309467b48Spatrick   BasicBlock *NewBB = BasicBlock::Create(
120409467b48Spatrick       BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
120509467b48Spatrick 
120609467b48Spatrick   // The new block unconditionally branches to the old block.
120709467b48Spatrick   BranchInst *BI = BranchInst::Create(BB, NewBB);
120873471bf0Spatrick 
120973471bf0Spatrick   Loop *L = nullptr;
121073471bf0Spatrick   BasicBlock *OldLatch = nullptr;
121109467b48Spatrick   // Splitting the predecessors of a loop header creates a preheader block.
121273471bf0Spatrick   if (LI && LI->isLoopHeader(BB)) {
121373471bf0Spatrick     L = LI->getLoopFor(BB);
121409467b48Spatrick     // Using the loop start line number prevents debuggers stepping into the
121509467b48Spatrick     // loop body for this instruction.
121673471bf0Spatrick     BI->setDebugLoc(L->getStartLoc());
121773471bf0Spatrick 
121873471bf0Spatrick     // If BB is the header of the Loop, it is possible that the loop is
121973471bf0Spatrick     // modified, such that the current latch does not remain the latch of the
122073471bf0Spatrick     // loop. If that is the case, the loop metadata from the current latch needs
122173471bf0Spatrick     // to be applied to the new latch.
122273471bf0Spatrick     OldLatch = L->getLoopLatch();
122373471bf0Spatrick   } else
122409467b48Spatrick     BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
122509467b48Spatrick 
122609467b48Spatrick   // Move the edges from Preds to point to NewBB instead of BB.
1227*d415bd75Srobert   for (BasicBlock *Pred : Preds) {
122809467b48Spatrick     // This is slightly more strict than necessary; the minimum requirement
122909467b48Spatrick     // is that there be no more than one indirectbr branching to BB. And
123009467b48Spatrick     // all BlockAddress uses would need to be updated.
1231*d415bd75Srobert     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
123209467b48Spatrick            "Cannot split an edge from an IndirectBrInst");
1233*d415bd75Srobert     Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
123409467b48Spatrick   }
123509467b48Spatrick 
123609467b48Spatrick   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
123709467b48Spatrick   // node becomes an incoming value for BB's phi node.  However, if the Preds
123809467b48Spatrick   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
123909467b48Spatrick   // account for the newly created predecessor.
124009467b48Spatrick   if (Preds.empty()) {
124109467b48Spatrick     // Insert dummy values as the incoming value.
124209467b48Spatrick     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
1243*d415bd75Srobert       cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
124409467b48Spatrick   }
124509467b48Spatrick 
124609467b48Spatrick   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
124709467b48Spatrick   bool HasLoopExit = false;
124873471bf0Spatrick   UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
124909467b48Spatrick                             HasLoopExit);
125009467b48Spatrick 
125109467b48Spatrick   if (!Preds.empty()) {
125209467b48Spatrick     // Update the PHI nodes in BB with the values coming from NewBB.
125309467b48Spatrick     UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
125409467b48Spatrick   }
125509467b48Spatrick 
125673471bf0Spatrick   if (OldLatch) {
125773471bf0Spatrick     BasicBlock *NewLatch = L->getLoopLatch();
125873471bf0Spatrick     if (NewLatch != OldLatch) {
125973471bf0Spatrick       MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop");
126073471bf0Spatrick       NewLatch->getTerminator()->setMetadata("llvm.loop", MD);
1261*d415bd75Srobert       // It's still possible that OldLatch is the latch of another inner loop,
1262*d415bd75Srobert       // in which case we do not remove the metadata.
1263*d415bd75Srobert       Loop *IL = LI->getLoopFor(OldLatch);
1264*d415bd75Srobert       if (IL && IL->getLoopLatch() != OldLatch)
126573471bf0Spatrick         OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr);
126673471bf0Spatrick     }
126773471bf0Spatrick   }
126873471bf0Spatrick 
126909467b48Spatrick   return NewBB;
127009467b48Spatrick }
127109467b48Spatrick 
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)127273471bf0Spatrick BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
127309467b48Spatrick                                          ArrayRef<BasicBlock *> Preds,
127473471bf0Spatrick                                          const char *Suffix, DominatorTree *DT,
127573471bf0Spatrick                                          LoopInfo *LI, MemorySSAUpdater *MSSAU,
127673471bf0Spatrick                                          bool PreserveLCSSA) {
127773471bf0Spatrick   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
127873471bf0Spatrick                                     MSSAU, PreserveLCSSA);
127973471bf0Spatrick }
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)128073471bf0Spatrick BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
128173471bf0Spatrick                                          ArrayRef<BasicBlock *> Preds,
128273471bf0Spatrick                                          const char *Suffix,
128373471bf0Spatrick                                          DomTreeUpdater *DTU, LoopInfo *LI,
128409467b48Spatrick                                          MemorySSAUpdater *MSSAU,
128509467b48Spatrick                                          bool PreserveLCSSA) {
128673471bf0Spatrick   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
128773471bf0Spatrick                                     /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
128873471bf0Spatrick }
128973471bf0Spatrick 
SplitLandingPadPredecessorsImpl(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)129073471bf0Spatrick static void SplitLandingPadPredecessorsImpl(
129173471bf0Spatrick     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
129273471bf0Spatrick     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
129373471bf0Spatrick     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
129473471bf0Spatrick     MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
129509467b48Spatrick   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
129609467b48Spatrick 
129709467b48Spatrick   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
129809467b48Spatrick   // it right before the original block.
129909467b48Spatrick   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
130009467b48Spatrick                                           OrigBB->getName() + Suffix1,
130109467b48Spatrick                                           OrigBB->getParent(), OrigBB);
130209467b48Spatrick   NewBBs.push_back(NewBB1);
130309467b48Spatrick 
130409467b48Spatrick   // The new block unconditionally branches to the old block.
130509467b48Spatrick   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
130609467b48Spatrick   BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
130709467b48Spatrick 
130809467b48Spatrick   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1309*d415bd75Srobert   for (BasicBlock *Pred : Preds) {
131009467b48Spatrick     // This is slightly more strict than necessary; the minimum requirement
131109467b48Spatrick     // is that there be no more than one indirectbr branching to BB. And
131209467b48Spatrick     // all BlockAddress uses would need to be updated.
1313*d415bd75Srobert     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
131409467b48Spatrick            "Cannot split an edge from an IndirectBrInst");
1315*d415bd75Srobert     Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
131609467b48Spatrick   }
131709467b48Spatrick 
131809467b48Spatrick   bool HasLoopExit = false;
131973471bf0Spatrick   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
132073471bf0Spatrick                             PreserveLCSSA, HasLoopExit);
132109467b48Spatrick 
132209467b48Spatrick   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
132309467b48Spatrick   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
132409467b48Spatrick 
132509467b48Spatrick   // Move the remaining edges from OrigBB to point to NewBB2.
132609467b48Spatrick   SmallVector<BasicBlock*, 8> NewBB2Preds;
132709467b48Spatrick   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
132809467b48Spatrick        i != e; ) {
132909467b48Spatrick     BasicBlock *Pred = *i++;
133009467b48Spatrick     if (Pred == NewBB1) continue;
133109467b48Spatrick     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
133209467b48Spatrick            "Cannot split an edge from an IndirectBrInst");
133309467b48Spatrick     NewBB2Preds.push_back(Pred);
133409467b48Spatrick     e = pred_end(OrigBB);
133509467b48Spatrick   }
133609467b48Spatrick 
133709467b48Spatrick   BasicBlock *NewBB2 = nullptr;
133809467b48Spatrick   if (!NewBB2Preds.empty()) {
133909467b48Spatrick     // Create another basic block for the rest of OrigBB's predecessors.
134009467b48Spatrick     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
134109467b48Spatrick                                 OrigBB->getName() + Suffix2,
134209467b48Spatrick                                 OrigBB->getParent(), OrigBB);
134309467b48Spatrick     NewBBs.push_back(NewBB2);
134409467b48Spatrick 
134509467b48Spatrick     // The new block unconditionally branches to the old block.
134609467b48Spatrick     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
134709467b48Spatrick     BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
134809467b48Spatrick 
134909467b48Spatrick     // Move the remaining edges from OrigBB to point to NewBB2.
135009467b48Spatrick     for (BasicBlock *NewBB2Pred : NewBB2Preds)
135109467b48Spatrick       NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
135209467b48Spatrick 
135309467b48Spatrick     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
135409467b48Spatrick     HasLoopExit = false;
135573471bf0Spatrick     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
135609467b48Spatrick                               PreserveLCSSA, HasLoopExit);
135709467b48Spatrick 
135809467b48Spatrick     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
135909467b48Spatrick     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
136009467b48Spatrick   }
136109467b48Spatrick 
136209467b48Spatrick   LandingPadInst *LPad = OrigBB->getLandingPadInst();
136309467b48Spatrick   Instruction *Clone1 = LPad->clone();
136409467b48Spatrick   Clone1->setName(Twine("lpad") + Suffix1);
1365*d415bd75Srobert   Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
136609467b48Spatrick 
136709467b48Spatrick   if (NewBB2) {
136809467b48Spatrick     Instruction *Clone2 = LPad->clone();
136909467b48Spatrick     Clone2->setName(Twine("lpad") + Suffix2);
1370*d415bd75Srobert     Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
137109467b48Spatrick 
137209467b48Spatrick     // Create a PHI node for the two cloned landingpad instructions only
137309467b48Spatrick     // if the original landingpad instruction has some uses.
137409467b48Spatrick     if (!LPad->use_empty()) {
137509467b48Spatrick       assert(!LPad->getType()->isTokenTy() &&
137609467b48Spatrick              "Split cannot be applied if LPad is token type. Otherwise an "
137709467b48Spatrick              "invalid PHINode of token type would be created.");
137809467b48Spatrick       PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
137909467b48Spatrick       PN->addIncoming(Clone1, NewBB1);
138009467b48Spatrick       PN->addIncoming(Clone2, NewBB2);
138109467b48Spatrick       LPad->replaceAllUsesWith(PN);
138209467b48Spatrick     }
138309467b48Spatrick     LPad->eraseFromParent();
138409467b48Spatrick   } else {
138509467b48Spatrick     // There is no second clone. Just replace the landing pad with the first
138609467b48Spatrick     // clone.
138709467b48Spatrick     LPad->replaceAllUsesWith(Clone1);
138809467b48Spatrick     LPad->eraseFromParent();
138909467b48Spatrick   }
139009467b48Spatrick }
139109467b48Spatrick 
SplitLandingPadPredecessors(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)139273471bf0Spatrick void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
139373471bf0Spatrick                                        ArrayRef<BasicBlock *> Preds,
139473471bf0Spatrick                                        const char *Suffix1, const char *Suffix2,
139573471bf0Spatrick                                        SmallVectorImpl<BasicBlock *> &NewBBs,
139673471bf0Spatrick                                        DominatorTree *DT, LoopInfo *LI,
139773471bf0Spatrick                                        MemorySSAUpdater *MSSAU,
139873471bf0Spatrick                                        bool PreserveLCSSA) {
139973471bf0Spatrick   return SplitLandingPadPredecessorsImpl(
140073471bf0Spatrick       OrigBB, Preds, Suffix1, Suffix2, NewBBs,
140173471bf0Spatrick       /*DTU=*/nullptr, DT, LI, MSSAU, PreserveLCSSA);
140273471bf0Spatrick }
SplitLandingPadPredecessors(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)140373471bf0Spatrick void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
140473471bf0Spatrick                                        ArrayRef<BasicBlock *> Preds,
140573471bf0Spatrick                                        const char *Suffix1, const char *Suffix2,
140673471bf0Spatrick                                        SmallVectorImpl<BasicBlock *> &NewBBs,
140773471bf0Spatrick                                        DomTreeUpdater *DTU, LoopInfo *LI,
140873471bf0Spatrick                                        MemorySSAUpdater *MSSAU,
140973471bf0Spatrick                                        bool PreserveLCSSA) {
141073471bf0Spatrick   return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
141173471bf0Spatrick                                          NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
141273471bf0Spatrick                                          PreserveLCSSA);
141373471bf0Spatrick }
141473471bf0Spatrick 
FoldReturnIntoUncondBranch(ReturnInst * RI,BasicBlock * BB,BasicBlock * Pred,DomTreeUpdater * DTU)141509467b48Spatrick ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
141609467b48Spatrick                                              BasicBlock *Pred,
141709467b48Spatrick                                              DomTreeUpdater *DTU) {
141809467b48Spatrick   Instruction *UncondBranch = Pred->getTerminator();
141909467b48Spatrick   // Clone the return and add it to the end of the predecessor.
142009467b48Spatrick   Instruction *NewRet = RI->clone();
1421*d415bd75Srobert   NewRet->insertInto(Pred, Pred->end());
142209467b48Spatrick 
142309467b48Spatrick   // If the return instruction returns a value, and if the value was a
142409467b48Spatrick   // PHI node in "BB", propagate the right value into the return.
142573471bf0Spatrick   for (Use &Op : NewRet->operands()) {
142673471bf0Spatrick     Value *V = Op;
142709467b48Spatrick     Instruction *NewBC = nullptr;
142809467b48Spatrick     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
142909467b48Spatrick       // Return value might be bitcasted. Clone and insert it before the
143009467b48Spatrick       // return instruction.
143109467b48Spatrick       V = BCI->getOperand(0);
143209467b48Spatrick       NewBC = BCI->clone();
1433*d415bd75Srobert       NewBC->insertInto(Pred, NewRet->getIterator());
143473471bf0Spatrick       Op = NewBC;
143509467b48Spatrick     }
1436097a140dSpatrick 
1437097a140dSpatrick     Instruction *NewEV = nullptr;
1438097a140dSpatrick     if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
1439097a140dSpatrick       V = EVI->getOperand(0);
1440097a140dSpatrick       NewEV = EVI->clone();
1441097a140dSpatrick       if (NewBC) {
1442097a140dSpatrick         NewBC->setOperand(0, NewEV);
1443*d415bd75Srobert         NewEV->insertInto(Pred, NewBC->getIterator());
1444097a140dSpatrick       } else {
1445*d415bd75Srobert         NewEV->insertInto(Pred, NewRet->getIterator());
144673471bf0Spatrick         Op = NewEV;
1447097a140dSpatrick       }
1448097a140dSpatrick     }
1449097a140dSpatrick 
145009467b48Spatrick     if (PHINode *PN = dyn_cast<PHINode>(V)) {
145109467b48Spatrick       if (PN->getParent() == BB) {
1452097a140dSpatrick         if (NewEV) {
1453097a140dSpatrick           NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
1454097a140dSpatrick         } else if (NewBC)
145509467b48Spatrick           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
145609467b48Spatrick         else
145773471bf0Spatrick           Op = PN->getIncomingValueForBlock(Pred);
145809467b48Spatrick       }
145909467b48Spatrick     }
146009467b48Spatrick   }
146109467b48Spatrick 
146209467b48Spatrick   // Update any PHI nodes in the returning block to realize that we no
146309467b48Spatrick   // longer branch to them.
146409467b48Spatrick   BB->removePredecessor(Pred);
146509467b48Spatrick   UncondBranch->eraseFromParent();
146609467b48Spatrick 
146709467b48Spatrick   if (DTU)
146809467b48Spatrick     DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
146909467b48Spatrick 
147009467b48Spatrick   return cast<ReturnInst>(NewRet);
147109467b48Spatrick }
147209467b48Spatrick 
147373471bf0Spatrick static Instruction *
SplitBlockAndInsertIfThenImpl(Value * Cond,Instruction * SplitBefore,bool Unreachable,MDNode * BranchWeights,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,BasicBlock * ThenBlock)147473471bf0Spatrick SplitBlockAndInsertIfThenImpl(Value *Cond, Instruction *SplitBefore,
147573471bf0Spatrick                               bool Unreachable, MDNode *BranchWeights,
147673471bf0Spatrick                               DomTreeUpdater *DTU, DominatorTree *DT,
147773471bf0Spatrick                               LoopInfo *LI, BasicBlock *ThenBlock) {
147873471bf0Spatrick   SmallVector<DominatorTree::UpdateType, 8> Updates;
147909467b48Spatrick   BasicBlock *Head = SplitBefore->getParent();
148009467b48Spatrick   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
148173471bf0Spatrick   if (DTU) {
1482*d415bd75Srobert     SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfHead;
148373471bf0Spatrick     Updates.push_back({DominatorTree::Insert, Head, Tail});
1484*d415bd75Srobert     Updates.reserve(Updates.size() + 2 * succ_size(Tail));
1485*d415bd75Srobert     for (BasicBlock *SuccessorOfHead : successors(Tail))
1486*d415bd75Srobert       if (UniqueSuccessorsOfHead.insert(SuccessorOfHead).second) {
1487*d415bd75Srobert         Updates.push_back({DominatorTree::Insert, Tail, SuccessorOfHead});
1488*d415bd75Srobert         Updates.push_back({DominatorTree::Delete, Head, SuccessorOfHead});
148973471bf0Spatrick       }
149073471bf0Spatrick   }
149109467b48Spatrick   Instruction *HeadOldTerm = Head->getTerminator();
149209467b48Spatrick   LLVMContext &C = Head->getContext();
149309467b48Spatrick   Instruction *CheckTerm;
149409467b48Spatrick   bool CreateThenBlock = (ThenBlock == nullptr);
149509467b48Spatrick   if (CreateThenBlock) {
149609467b48Spatrick     ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
149709467b48Spatrick     if (Unreachable)
149809467b48Spatrick       CheckTerm = new UnreachableInst(C, ThenBlock);
149973471bf0Spatrick     else {
150009467b48Spatrick       CheckTerm = BranchInst::Create(Tail, ThenBlock);
150173471bf0Spatrick       if (DTU)
150273471bf0Spatrick         Updates.push_back({DominatorTree::Insert, ThenBlock, Tail});
150373471bf0Spatrick     }
150409467b48Spatrick     CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
150509467b48Spatrick   } else
150609467b48Spatrick     CheckTerm = ThenBlock->getTerminator();
150709467b48Spatrick   BranchInst *HeadNewTerm =
150809467b48Spatrick       BranchInst::Create(/*ifTrue*/ ThenBlock, /*ifFalse*/ Tail, Cond);
150973471bf0Spatrick   if (DTU)
151073471bf0Spatrick     Updates.push_back({DominatorTree::Insert, Head, ThenBlock});
151109467b48Spatrick   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
151209467b48Spatrick   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
151309467b48Spatrick 
151473471bf0Spatrick   if (DTU)
151573471bf0Spatrick     DTU->applyUpdates(Updates);
151673471bf0Spatrick   else if (DT) {
151709467b48Spatrick     if (DomTreeNode *OldNode = DT->getNode(Head)) {
151809467b48Spatrick       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
151909467b48Spatrick 
152009467b48Spatrick       DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
152109467b48Spatrick       for (DomTreeNode *Child : Children)
152209467b48Spatrick         DT->changeImmediateDominator(Child, NewNode);
152309467b48Spatrick 
152409467b48Spatrick       // Head dominates ThenBlock.
152509467b48Spatrick       if (CreateThenBlock)
152609467b48Spatrick         DT->addNewBlock(ThenBlock, Head);
152709467b48Spatrick       else
152809467b48Spatrick         DT->changeImmediateDominator(ThenBlock, Head);
152909467b48Spatrick     }
153009467b48Spatrick   }
153109467b48Spatrick 
153209467b48Spatrick   if (LI) {
153309467b48Spatrick     if (Loop *L = LI->getLoopFor(Head)) {
153409467b48Spatrick       L->addBasicBlockToLoop(ThenBlock, *LI);
153509467b48Spatrick       L->addBasicBlockToLoop(Tail, *LI);
153609467b48Spatrick     }
153709467b48Spatrick   }
153809467b48Spatrick 
153909467b48Spatrick   return CheckTerm;
154009467b48Spatrick }
154109467b48Spatrick 
SplitBlockAndInsertIfThen(Value * Cond,Instruction * SplitBefore,bool Unreachable,MDNode * BranchWeights,DominatorTree * DT,LoopInfo * LI,BasicBlock * ThenBlock)154273471bf0Spatrick Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
154373471bf0Spatrick                                              Instruction *SplitBefore,
154473471bf0Spatrick                                              bool Unreachable,
154573471bf0Spatrick                                              MDNode *BranchWeights,
154673471bf0Spatrick                                              DominatorTree *DT, LoopInfo *LI,
154773471bf0Spatrick                                              BasicBlock *ThenBlock) {
154873471bf0Spatrick   return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable,
154973471bf0Spatrick                                        BranchWeights,
155073471bf0Spatrick                                        /*DTU=*/nullptr, DT, LI, ThenBlock);
155173471bf0Spatrick }
SplitBlockAndInsertIfThen(Value * Cond,Instruction * SplitBefore,bool Unreachable,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI,BasicBlock * ThenBlock)155273471bf0Spatrick Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
155373471bf0Spatrick                                              Instruction *SplitBefore,
155473471bf0Spatrick                                              bool Unreachable,
155573471bf0Spatrick                                              MDNode *BranchWeights,
155673471bf0Spatrick                                              DomTreeUpdater *DTU, LoopInfo *LI,
155773471bf0Spatrick                                              BasicBlock *ThenBlock) {
155873471bf0Spatrick   return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable,
155973471bf0Spatrick                                        BranchWeights, DTU, /*DT=*/nullptr, LI,
156073471bf0Spatrick                                        ThenBlock);
156173471bf0Spatrick }
156273471bf0Spatrick 
SplitBlockAndInsertIfThenElse(Value * Cond,Instruction * SplitBefore,Instruction ** ThenTerm,Instruction ** ElseTerm,MDNode * BranchWeights,DomTreeUpdater * DTU)156309467b48Spatrick void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
156409467b48Spatrick                                          Instruction **ThenTerm,
156509467b48Spatrick                                          Instruction **ElseTerm,
1566*d415bd75Srobert                                          MDNode *BranchWeights,
1567*d415bd75Srobert                                          DomTreeUpdater *DTU) {
156809467b48Spatrick   BasicBlock *Head = SplitBefore->getParent();
1569*d415bd75Srobert 
1570*d415bd75Srobert   SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
1571*d415bd75Srobert   if (DTU)
1572*d415bd75Srobert     UniqueOrigSuccessors.insert(succ_begin(Head), succ_end(Head));
1573*d415bd75Srobert 
157409467b48Spatrick   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
157509467b48Spatrick   Instruction *HeadOldTerm = Head->getTerminator();
157609467b48Spatrick   LLVMContext &C = Head->getContext();
157709467b48Spatrick   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
157809467b48Spatrick   BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
157909467b48Spatrick   *ThenTerm = BranchInst::Create(Tail, ThenBlock);
158009467b48Spatrick   (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
158109467b48Spatrick   *ElseTerm = BranchInst::Create(Tail, ElseBlock);
158209467b48Spatrick   (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
158309467b48Spatrick   BranchInst *HeadNewTerm =
158409467b48Spatrick     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
158509467b48Spatrick   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
158609467b48Spatrick   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
1587*d415bd75Srobert   if (DTU) {
1588*d415bd75Srobert     SmallVector<DominatorTree::UpdateType, 8> Updates;
1589*d415bd75Srobert     Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
1590*d415bd75Srobert     for (BasicBlock *Succ : successors(Head)) {
1591*d415bd75Srobert       Updates.push_back({DominatorTree::Insert, Head, Succ});
1592*d415bd75Srobert       Updates.push_back({DominatorTree::Insert, Succ, Tail});
1593*d415bd75Srobert     }
1594*d415bd75Srobert     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1595*d415bd75Srobert       Updates.push_back({DominatorTree::Insert, Tail, UniqueOrigSuccessor});
1596*d415bd75Srobert     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1597*d415bd75Srobert       Updates.push_back({DominatorTree::Delete, Head, UniqueOrigSuccessor});
1598*d415bd75Srobert     DTU->applyUpdates(Updates);
1599*d415bd75Srobert   }
160009467b48Spatrick }
160109467b48Spatrick 
GetIfCondition(BasicBlock * BB,BasicBlock * & IfTrue,BasicBlock * & IfFalse)160273471bf0Spatrick BranchInst *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
160309467b48Spatrick                                  BasicBlock *&IfFalse) {
160409467b48Spatrick   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
160509467b48Spatrick   BasicBlock *Pred1 = nullptr;
160609467b48Spatrick   BasicBlock *Pred2 = nullptr;
160709467b48Spatrick 
160809467b48Spatrick   if (SomePHI) {
160909467b48Spatrick     if (SomePHI->getNumIncomingValues() != 2)
161009467b48Spatrick       return nullptr;
161109467b48Spatrick     Pred1 = SomePHI->getIncomingBlock(0);
161209467b48Spatrick     Pred2 = SomePHI->getIncomingBlock(1);
161309467b48Spatrick   } else {
161409467b48Spatrick     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
161509467b48Spatrick     if (PI == PE) // No predecessor
161609467b48Spatrick       return nullptr;
161709467b48Spatrick     Pred1 = *PI++;
161809467b48Spatrick     if (PI == PE) // Only one predecessor
161909467b48Spatrick       return nullptr;
162009467b48Spatrick     Pred2 = *PI++;
162109467b48Spatrick     if (PI != PE) // More than two predecessors
162209467b48Spatrick       return nullptr;
162309467b48Spatrick   }
162409467b48Spatrick 
162509467b48Spatrick   // We can only handle branches.  Other control flow will be lowered to
162609467b48Spatrick   // branches if possible anyway.
162709467b48Spatrick   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
162809467b48Spatrick   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
162909467b48Spatrick   if (!Pred1Br || !Pred2Br)
163009467b48Spatrick     return nullptr;
163109467b48Spatrick 
163209467b48Spatrick   // Eliminate code duplication by ensuring that Pred1Br is conditional if
163309467b48Spatrick   // either are.
163409467b48Spatrick   if (Pred2Br->isConditional()) {
163509467b48Spatrick     // If both branches are conditional, we don't have an "if statement".  In
163609467b48Spatrick     // reality, we could transform this case, but since the condition will be
163709467b48Spatrick     // required anyway, we stand no chance of eliminating it, so the xform is
163809467b48Spatrick     // probably not profitable.
163909467b48Spatrick     if (Pred1Br->isConditional())
164009467b48Spatrick       return nullptr;
164109467b48Spatrick 
164209467b48Spatrick     std::swap(Pred1, Pred2);
164309467b48Spatrick     std::swap(Pred1Br, Pred2Br);
164409467b48Spatrick   }
164509467b48Spatrick 
164609467b48Spatrick   if (Pred1Br->isConditional()) {
164709467b48Spatrick     // The only thing we have to watch out for here is to make sure that Pred2
164809467b48Spatrick     // doesn't have incoming edges from other blocks.  If it does, the condition
164909467b48Spatrick     // doesn't dominate BB.
165009467b48Spatrick     if (!Pred2->getSinglePredecessor())
165109467b48Spatrick       return nullptr;
165209467b48Spatrick 
165309467b48Spatrick     // If we found a conditional branch predecessor, make sure that it branches
165409467b48Spatrick     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
165509467b48Spatrick     if (Pred1Br->getSuccessor(0) == BB &&
165609467b48Spatrick         Pred1Br->getSuccessor(1) == Pred2) {
165709467b48Spatrick       IfTrue = Pred1;
165809467b48Spatrick       IfFalse = Pred2;
165909467b48Spatrick     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
166009467b48Spatrick                Pred1Br->getSuccessor(1) == BB) {
166109467b48Spatrick       IfTrue = Pred2;
166209467b48Spatrick       IfFalse = Pred1;
166309467b48Spatrick     } else {
166409467b48Spatrick       // We know that one arm of the conditional goes to BB, so the other must
166509467b48Spatrick       // go somewhere unrelated, and this must not be an "if statement".
166609467b48Spatrick       return nullptr;
166709467b48Spatrick     }
166809467b48Spatrick 
166973471bf0Spatrick     return Pred1Br;
167009467b48Spatrick   }
167109467b48Spatrick 
167209467b48Spatrick   // Ok, if we got here, both predecessors end with an unconditional branch to
167309467b48Spatrick   // BB.  Don't panic!  If both blocks only have a single (identical)
167409467b48Spatrick   // predecessor, and THAT is a conditional branch, then we're all ok!
167509467b48Spatrick   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
167609467b48Spatrick   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
167709467b48Spatrick     return nullptr;
167809467b48Spatrick 
167909467b48Spatrick   // Otherwise, if this is a conditional branch, then we can use it!
168009467b48Spatrick   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
168109467b48Spatrick   if (!BI) return nullptr;
168209467b48Spatrick 
168309467b48Spatrick   assert(BI->isConditional() && "Two successors but not conditional?");
168409467b48Spatrick   if (BI->getSuccessor(0) == Pred1) {
168509467b48Spatrick     IfTrue = Pred1;
168609467b48Spatrick     IfFalse = Pred2;
168709467b48Spatrick   } else {
168809467b48Spatrick     IfTrue = Pred2;
168909467b48Spatrick     IfFalse = Pred1;
169009467b48Spatrick   }
169173471bf0Spatrick   return BI;
169209467b48Spatrick }
1693097a140dSpatrick 
1694097a140dSpatrick // After creating a control flow hub, the operands of PHINodes in an outgoing
1695097a140dSpatrick // block Out no longer match the predecessors of that block. Predecessors of Out
1696097a140dSpatrick // that are incoming blocks to the hub are now replaced by just one edge from
1697097a140dSpatrick // the hub. To match this new control flow, the corresponding values from each
1698097a140dSpatrick // PHINode must now be moved a new PHINode in the first guard block of the hub.
1699097a140dSpatrick //
1700097a140dSpatrick // This operation cannot be performed with SSAUpdater, because it involves one
1701097a140dSpatrick // new use: If the block Out is in the list of Incoming blocks, then the newly
1702097a140dSpatrick // created PHI in the Hub will use itself along that edge from Out to Hub.
reconnectPhis(BasicBlock * Out,BasicBlock * GuardBlock,const SetVector<BasicBlock * > & Incoming,BasicBlock * FirstGuardBlock)1703097a140dSpatrick static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock,
1704097a140dSpatrick                           const SetVector<BasicBlock *> &Incoming,
1705097a140dSpatrick                           BasicBlock *FirstGuardBlock) {
1706097a140dSpatrick   auto I = Out->begin();
1707097a140dSpatrick   while (I != Out->end() && isa<PHINode>(I)) {
1708097a140dSpatrick     auto Phi = cast<PHINode>(I);
1709097a140dSpatrick     auto NewPhi =
1710097a140dSpatrick         PHINode::Create(Phi->getType(), Incoming.size(),
1711*d415bd75Srobert                         Phi->getName() + ".moved", &FirstGuardBlock->front());
1712*d415bd75Srobert     for (auto *In : Incoming) {
1713097a140dSpatrick       Value *V = UndefValue::get(Phi->getType());
1714097a140dSpatrick       if (In == Out) {
1715097a140dSpatrick         V = NewPhi;
1716097a140dSpatrick       } else if (Phi->getBasicBlockIndex(In) != -1) {
1717097a140dSpatrick         V = Phi->removeIncomingValue(In, false);
1718097a140dSpatrick       }
1719097a140dSpatrick       NewPhi->addIncoming(V, In);
1720097a140dSpatrick     }
1721097a140dSpatrick     assert(NewPhi->getNumIncomingValues() == Incoming.size());
1722097a140dSpatrick     if (Phi->getNumOperands() == 0) {
1723097a140dSpatrick       Phi->replaceAllUsesWith(NewPhi);
1724097a140dSpatrick       I = Phi->eraseFromParent();
1725097a140dSpatrick       continue;
1726097a140dSpatrick     }
1727097a140dSpatrick     Phi->addIncoming(NewPhi, GuardBlock);
1728097a140dSpatrick     ++I;
1729097a140dSpatrick   }
1730097a140dSpatrick }
1731097a140dSpatrick 
1732*d415bd75Srobert using BBPredicates = DenseMap<BasicBlock *, Instruction *>;
1733097a140dSpatrick using BBSetVector = SetVector<BasicBlock *>;
1734097a140dSpatrick 
1735097a140dSpatrick // Redirects the terminator of the incoming block to the first guard
1736097a140dSpatrick // block in the hub. The condition of the original terminator (if it
1737097a140dSpatrick // was conditional) and its original successors are returned as a
1738097a140dSpatrick // tuple <condition, succ0, succ1>. The function additionally filters
1739097a140dSpatrick // out successors that are not in the set of outgoing blocks.
1740097a140dSpatrick //
1741097a140dSpatrick // - condition is non-null iff the branch is conditional.
1742097a140dSpatrick // - Succ1 is non-null iff the sole/taken target is an outgoing block.
1743097a140dSpatrick // - Succ2 is non-null iff condition is non-null and the fallthrough
1744097a140dSpatrick //         target is an outgoing block.
1745097a140dSpatrick static std::tuple<Value *, BasicBlock *, BasicBlock *>
redirectToHub(BasicBlock * BB,BasicBlock * FirstGuardBlock,const BBSetVector & Outgoing)1746097a140dSpatrick redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock,
1747097a140dSpatrick               const BBSetVector &Outgoing) {
1748*d415bd75Srobert   assert(isa<BranchInst>(BB->getTerminator()) &&
1749*d415bd75Srobert          "Only support branch terminator.");
1750097a140dSpatrick   auto Branch = cast<BranchInst>(BB->getTerminator());
1751097a140dSpatrick   auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
1752097a140dSpatrick 
1753097a140dSpatrick   BasicBlock *Succ0 = Branch->getSuccessor(0);
1754097a140dSpatrick   BasicBlock *Succ1 = nullptr;
1755097a140dSpatrick   Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr;
1756097a140dSpatrick 
1757097a140dSpatrick   if (Branch->isUnconditional()) {
1758097a140dSpatrick     Branch->setSuccessor(0, FirstGuardBlock);
1759097a140dSpatrick     assert(Succ0);
1760097a140dSpatrick   } else {
1761097a140dSpatrick     Succ1 = Branch->getSuccessor(1);
1762097a140dSpatrick     Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr;
1763097a140dSpatrick     assert(Succ0 || Succ1);
1764097a140dSpatrick     if (Succ0 && !Succ1) {
1765097a140dSpatrick       Branch->setSuccessor(0, FirstGuardBlock);
1766097a140dSpatrick     } else if (Succ1 && !Succ0) {
1767097a140dSpatrick       Branch->setSuccessor(1, FirstGuardBlock);
1768097a140dSpatrick     } else {
1769097a140dSpatrick       Branch->eraseFromParent();
1770097a140dSpatrick       BranchInst::Create(FirstGuardBlock, BB);
1771097a140dSpatrick     }
1772097a140dSpatrick   }
1773097a140dSpatrick 
1774097a140dSpatrick   assert(Succ0 || Succ1);
1775097a140dSpatrick   return std::make_tuple(Condition, Succ0, Succ1);
1776097a140dSpatrick }
1777*d415bd75Srobert // Setup the branch instructions for guard blocks.
1778097a140dSpatrick //
1779097a140dSpatrick // Each guard block terminates in a conditional branch that transfers
1780097a140dSpatrick // control to the corresponding outgoing block or the next guard
1781097a140dSpatrick // block. The last guard block has two outgoing blocks as successors
1782097a140dSpatrick // since the condition for the final outgoing block is trivially
1783097a140dSpatrick // true. So we create one less block (including the first guard block)
1784097a140dSpatrick // than the number of outgoing blocks.
setupBranchForGuard(SmallVectorImpl<BasicBlock * > & GuardBlocks,const BBSetVector & Outgoing,BBPredicates & GuardPredicates)1785*d415bd75Srobert static void setupBranchForGuard(SmallVectorImpl<BasicBlock *> &GuardBlocks,
1786*d415bd75Srobert                                 const BBSetVector &Outgoing,
1787*d415bd75Srobert                                 BBPredicates &GuardPredicates) {
1788097a140dSpatrick   // To help keep the loop simple, temporarily append the last
1789097a140dSpatrick   // outgoing block to the list of guard blocks.
1790097a140dSpatrick   GuardBlocks.push_back(Outgoing.back());
1791097a140dSpatrick 
1792097a140dSpatrick   for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) {
1793097a140dSpatrick     auto Out = Outgoing[i];
1794097a140dSpatrick     assert(GuardPredicates.count(Out));
1795097a140dSpatrick     BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out],
1796097a140dSpatrick                        GuardBlocks[i]);
1797097a140dSpatrick   }
1798097a140dSpatrick 
1799097a140dSpatrick   // Remove the last block from the guard list.
1800097a140dSpatrick   GuardBlocks.pop_back();
1801097a140dSpatrick }
1802097a140dSpatrick 
1803*d415bd75Srobert /// We are using one integer to represent the block we are branching to. Then at
1804*d415bd75Srobert /// each guard block, the predicate was calcuated using a simple `icmp eq`.
calcPredicateUsingInteger(const BBSetVector & Incoming,const BBSetVector & Outgoing,SmallVectorImpl<BasicBlock * > & GuardBlocks,BBPredicates & GuardPredicates)1805*d415bd75Srobert static void calcPredicateUsingInteger(
1806*d415bd75Srobert     const BBSetVector &Incoming, const BBSetVector &Outgoing,
1807*d415bd75Srobert     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates) {
1808*d415bd75Srobert   auto &Context = Incoming.front()->getContext();
1809*d415bd75Srobert   auto FirstGuardBlock = GuardBlocks.front();
1810*d415bd75Srobert 
1811*d415bd75Srobert   auto Phi = PHINode::Create(Type::getInt32Ty(Context), Incoming.size(),
1812*d415bd75Srobert                              "merged.bb.idx", FirstGuardBlock);
1813*d415bd75Srobert 
1814*d415bd75Srobert   for (auto In : Incoming) {
1815*d415bd75Srobert     Value *Condition;
1816*d415bd75Srobert     BasicBlock *Succ0;
1817*d415bd75Srobert     BasicBlock *Succ1;
1818*d415bd75Srobert     std::tie(Condition, Succ0, Succ1) =
1819*d415bd75Srobert         redirectToHub(In, FirstGuardBlock, Outgoing);
1820*d415bd75Srobert     Value *IncomingId = nullptr;
1821*d415bd75Srobert     if (Succ0 && Succ1) {
1822*d415bd75Srobert       // target_bb_index = Condition ? index_of_succ0 : index_of_succ1.
1823*d415bd75Srobert       auto Succ0Iter = find(Outgoing, Succ0);
1824*d415bd75Srobert       auto Succ1Iter = find(Outgoing, Succ1);
1825*d415bd75Srobert       Value *Id0 = ConstantInt::get(Type::getInt32Ty(Context),
1826*d415bd75Srobert                                     std::distance(Outgoing.begin(), Succ0Iter));
1827*d415bd75Srobert       Value *Id1 = ConstantInt::get(Type::getInt32Ty(Context),
1828*d415bd75Srobert                                     std::distance(Outgoing.begin(), Succ1Iter));
1829*d415bd75Srobert       IncomingId = SelectInst::Create(Condition, Id0, Id1, "target.bb.idx",
1830*d415bd75Srobert                                       In->getTerminator());
1831*d415bd75Srobert     } else {
1832*d415bd75Srobert       // Get the index of the non-null successor.
1833*d415bd75Srobert       auto SuccIter = Succ0 ? find(Outgoing, Succ0) : find(Outgoing, Succ1);
1834*d415bd75Srobert       IncomingId = ConstantInt::get(Type::getInt32Ty(Context),
1835*d415bd75Srobert                                     std::distance(Outgoing.begin(), SuccIter));
1836*d415bd75Srobert     }
1837*d415bd75Srobert     Phi->addIncoming(IncomingId, In);
1838*d415bd75Srobert   }
1839*d415bd75Srobert 
1840*d415bd75Srobert   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
1841*d415bd75Srobert     auto Out = Outgoing[i];
1842*d415bd75Srobert     auto Cmp = ICmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, Phi,
1843*d415bd75Srobert                                 ConstantInt::get(Type::getInt32Ty(Context), i),
1844*d415bd75Srobert                                 Out->getName() + ".predicate", GuardBlocks[i]);
1845*d415bd75Srobert     GuardPredicates[Out] = Cmp;
1846*d415bd75Srobert   }
1847*d415bd75Srobert }
1848*d415bd75Srobert 
1849*d415bd75Srobert /// We record the predicate of each outgoing block using a phi of boolean.
calcPredicateUsingBooleans(const BBSetVector & Incoming,const BBSetVector & Outgoing,SmallVectorImpl<BasicBlock * > & GuardBlocks,BBPredicates & GuardPredicates,SmallVectorImpl<WeakVH> & DeletionCandidates)1850*d415bd75Srobert static void calcPredicateUsingBooleans(
1851*d415bd75Srobert     const BBSetVector &Incoming, const BBSetVector &Outgoing,
1852*d415bd75Srobert     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates,
1853*d415bd75Srobert     SmallVectorImpl<WeakVH> &DeletionCandidates) {
1854*d415bd75Srobert   auto &Context = Incoming.front()->getContext();
1855*d415bd75Srobert   auto BoolTrue = ConstantInt::getTrue(Context);
1856*d415bd75Srobert   auto BoolFalse = ConstantInt::getFalse(Context);
1857*d415bd75Srobert   auto FirstGuardBlock = GuardBlocks.front();
1858*d415bd75Srobert 
1859*d415bd75Srobert   // The predicate for the last outgoing is trivially true, and so we
1860*d415bd75Srobert   // process only the first N-1 successors.
1861*d415bd75Srobert   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
1862*d415bd75Srobert     auto Out = Outgoing[i];
1863*d415bd75Srobert     LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n");
1864*d415bd75Srobert 
1865*d415bd75Srobert     auto Phi =
1866*d415bd75Srobert         PHINode::Create(Type::getInt1Ty(Context), Incoming.size(),
1867*d415bd75Srobert                         StringRef("Guard.") + Out->getName(), FirstGuardBlock);
1868*d415bd75Srobert     GuardPredicates[Out] = Phi;
1869*d415bd75Srobert   }
1870*d415bd75Srobert 
1871*d415bd75Srobert   for (auto *In : Incoming) {
1872*d415bd75Srobert     Value *Condition;
1873*d415bd75Srobert     BasicBlock *Succ0;
1874*d415bd75Srobert     BasicBlock *Succ1;
1875*d415bd75Srobert     std::tie(Condition, Succ0, Succ1) =
1876*d415bd75Srobert         redirectToHub(In, FirstGuardBlock, Outgoing);
1877*d415bd75Srobert 
1878*d415bd75Srobert     // Optimization: Consider an incoming block A with both successors
1879*d415bd75Srobert     // Succ0 and Succ1 in the set of outgoing blocks. The predicates
1880*d415bd75Srobert     // for Succ0 and Succ1 complement each other. If Succ0 is visited
1881*d415bd75Srobert     // first in the loop below, control will branch to Succ0 using the
1882*d415bd75Srobert     // corresponding predicate. But if that branch is not taken, then
1883*d415bd75Srobert     // control must reach Succ1, which means that the incoming value of
1884*d415bd75Srobert     // the predicate from `In` is true for Succ1.
1885*d415bd75Srobert     bool OneSuccessorDone = false;
1886*d415bd75Srobert     for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
1887*d415bd75Srobert       auto Out = Outgoing[i];
1888*d415bd75Srobert       PHINode *Phi = cast<PHINode>(GuardPredicates[Out]);
1889*d415bd75Srobert       if (Out != Succ0 && Out != Succ1) {
1890*d415bd75Srobert         Phi->addIncoming(BoolFalse, In);
1891*d415bd75Srobert       } else if (!Succ0 || !Succ1 || OneSuccessorDone) {
1892*d415bd75Srobert         // Optimization: When only one successor is an outgoing block,
1893*d415bd75Srobert         // the incoming predicate from `In` is always true.
1894*d415bd75Srobert         Phi->addIncoming(BoolTrue, In);
1895*d415bd75Srobert       } else {
1896*d415bd75Srobert         assert(Succ0 && Succ1);
1897*d415bd75Srobert         if (Out == Succ0) {
1898*d415bd75Srobert           Phi->addIncoming(Condition, In);
1899*d415bd75Srobert         } else {
1900*d415bd75Srobert           auto Inverted = invertCondition(Condition);
1901*d415bd75Srobert           DeletionCandidates.push_back(Condition);
1902*d415bd75Srobert           Phi->addIncoming(Inverted, In);
1903*d415bd75Srobert         }
1904*d415bd75Srobert         OneSuccessorDone = true;
1905*d415bd75Srobert       }
1906*d415bd75Srobert     }
1907*d415bd75Srobert   }
1908*d415bd75Srobert }
1909*d415bd75Srobert 
1910*d415bd75Srobert // Capture the existing control flow as guard predicates, and redirect
1911*d415bd75Srobert // control flow from \p Incoming block through the \p GuardBlocks to the
1912*d415bd75Srobert // \p Outgoing blocks.
1913*d415bd75Srobert //
1914*d415bd75Srobert // There is one guard predicate for each outgoing block OutBB. The
1915*d415bd75Srobert // predicate represents whether the hub should transfer control flow
1916*d415bd75Srobert // to OutBB. These predicates are NOT ORTHOGONAL. The Hub evaluates
1917*d415bd75Srobert // them in the same order as the Outgoing set-vector, and control
1918*d415bd75Srobert // branches to the first outgoing block whose predicate evaluates to true.
1919*d415bd75Srobert static void
convertToGuardPredicates(SmallVectorImpl<BasicBlock * > & GuardBlocks,SmallVectorImpl<WeakVH> & DeletionCandidates,const BBSetVector & Incoming,const BBSetVector & Outgoing,const StringRef Prefix,std::optional<unsigned> MaxControlFlowBooleans)1920*d415bd75Srobert convertToGuardPredicates(SmallVectorImpl<BasicBlock *> &GuardBlocks,
1921*d415bd75Srobert                          SmallVectorImpl<WeakVH> &DeletionCandidates,
1922*d415bd75Srobert                          const BBSetVector &Incoming,
1923*d415bd75Srobert                          const BBSetVector &Outgoing, const StringRef Prefix,
1924*d415bd75Srobert                          std::optional<unsigned> MaxControlFlowBooleans) {
1925*d415bd75Srobert   BBPredicates GuardPredicates;
1926*d415bd75Srobert   auto F = Incoming.front()->getParent();
1927*d415bd75Srobert 
1928*d415bd75Srobert   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i)
1929*d415bd75Srobert     GuardBlocks.push_back(
1930*d415bd75Srobert         BasicBlock::Create(F->getContext(), Prefix + ".guard", F));
1931*d415bd75Srobert 
1932*d415bd75Srobert   // When we are using an integer to record which target block to jump to, we
1933*d415bd75Srobert   // are creating less live values, actually we are using one single integer to
1934*d415bd75Srobert   // store the index of the target block. When we are using booleans to store
1935*d415bd75Srobert   // the branching information, we need (N-1) boolean values, where N is the
1936*d415bd75Srobert   // number of outgoing block.
1937*d415bd75Srobert   if (!MaxControlFlowBooleans || Outgoing.size() <= *MaxControlFlowBooleans)
1938*d415bd75Srobert     calcPredicateUsingBooleans(Incoming, Outgoing, GuardBlocks, GuardPredicates,
1939*d415bd75Srobert                                DeletionCandidates);
1940*d415bd75Srobert   else
1941*d415bd75Srobert     calcPredicateUsingInteger(Incoming, Outgoing, GuardBlocks, GuardPredicates);
1942*d415bd75Srobert 
1943*d415bd75Srobert   setupBranchForGuard(GuardBlocks, Outgoing, GuardPredicates);
1944*d415bd75Srobert }
1945*d415bd75Srobert 
CreateControlFlowHub(DomTreeUpdater * DTU,SmallVectorImpl<BasicBlock * > & GuardBlocks,const BBSetVector & Incoming,const BBSetVector & Outgoing,const StringRef Prefix,std::optional<unsigned> MaxControlFlowBooleans)1946097a140dSpatrick BasicBlock *llvm::CreateControlFlowHub(
1947097a140dSpatrick     DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
1948097a140dSpatrick     const BBSetVector &Incoming, const BBSetVector &Outgoing,
1949*d415bd75Srobert     const StringRef Prefix, std::optional<unsigned> MaxControlFlowBooleans) {
1950*d415bd75Srobert   if (Outgoing.size() < 2)
1951*d415bd75Srobert     return Outgoing.front();
1952097a140dSpatrick 
1953097a140dSpatrick   SmallVector<DominatorTree::UpdateType, 16> Updates;
1954097a140dSpatrick   if (DTU) {
1955*d415bd75Srobert     for (auto *In : Incoming) {
1956*d415bd75Srobert       for (auto Succ : successors(In))
1957097a140dSpatrick         if (Outgoing.count(Succ))
1958097a140dSpatrick           Updates.push_back({DominatorTree::Delete, In, Succ});
1959097a140dSpatrick     }
1960097a140dSpatrick   }
1961097a140dSpatrick 
1962097a140dSpatrick   SmallVector<WeakVH, 8> DeletionCandidates;
1963*d415bd75Srobert   convertToGuardPredicates(GuardBlocks, DeletionCandidates, Incoming, Outgoing,
1964*d415bd75Srobert                            Prefix, MaxControlFlowBooleans);
1965*d415bd75Srobert   auto FirstGuardBlock = GuardBlocks.front();
1966097a140dSpatrick 
1967097a140dSpatrick   // Update the PHINodes in each outgoing block to match the new control flow.
1968*d415bd75Srobert   for (int i = 0, e = GuardBlocks.size(); i != e; ++i)
1969097a140dSpatrick     reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock);
1970*d415bd75Srobert 
1971097a140dSpatrick   reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock);
1972097a140dSpatrick 
1973097a140dSpatrick   if (DTU) {
1974097a140dSpatrick     int NumGuards = GuardBlocks.size();
1975097a140dSpatrick     assert((int)Outgoing.size() == NumGuards + 1);
1976*d415bd75Srobert 
1977*d415bd75Srobert     for (auto In : Incoming)
1978*d415bd75Srobert       Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock});
1979*d415bd75Srobert 
1980097a140dSpatrick     for (int i = 0; i != NumGuards - 1; ++i) {
1981097a140dSpatrick       Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]});
1982097a140dSpatrick       Updates.push_back(
1983097a140dSpatrick           {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]});
1984097a140dSpatrick     }
1985097a140dSpatrick     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
1986097a140dSpatrick                        Outgoing[NumGuards - 1]});
1987097a140dSpatrick     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
1988097a140dSpatrick                        Outgoing[NumGuards]});
1989097a140dSpatrick     DTU->applyUpdates(Updates);
1990097a140dSpatrick   }
1991097a140dSpatrick 
1992097a140dSpatrick   for (auto I : DeletionCandidates) {
1993097a140dSpatrick     if (I->use_empty())
1994097a140dSpatrick       if (auto Inst = dyn_cast_or_null<Instruction>(I))
1995097a140dSpatrick         Inst->eraseFromParent();
1996097a140dSpatrick   }
1997097a140dSpatrick 
1998097a140dSpatrick   return FirstGuardBlock;
1999097a140dSpatrick }
2000