10b57cec5SDimitry Andric //===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This family of functions perform manipulations on basic blocks, and
100b57cec5SDimitry Andric // instructions contained within basic blocks.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
150b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
180b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/MemoryDependenceAnalysis.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
240b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
250b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
260b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
27bdd1243dSDimitry Andric #include "llvm/IR/DebugInfo.h"
280b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
290b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
300b57cec5SDimitry Andric #include "llvm/IR/Function.h"
310b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
320b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
330b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
340b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
35fe013be4SDimitry Andric #include "llvm/IR/IRBuilder.h"
360b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
370b57cec5SDimitry Andric #include "llvm/IR/Type.h"
380b57cec5SDimitry Andric #include "llvm/IR/User.h"
390b57cec5SDimitry Andric #include "llvm/IR/Value.h"
400b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
410b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
42349cc55cSDimitry Andric #include "llvm/Support/CommandLine.h"
430b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
440b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
450b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
460b57cec5SDimitry Andric #include <cassert>
470b57cec5SDimitry Andric #include <cstdint>
480b57cec5SDimitry Andric #include <string>
490b57cec5SDimitry Andric #include <utility>
500b57cec5SDimitry Andric #include <vector>
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric using namespace llvm;
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric #define DEBUG_TYPE "basicblock-utils"
550b57cec5SDimitry Andric 
56349cc55cSDimitry Andric static cl::opt<unsigned> MaxDeoptOrUnreachableSuccessorCheckDepth(
57349cc55cSDimitry Andric     "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
58349cc55cSDimitry Andric     cl::desc("Set the maximum path length when checking whether a basic block "
59349cc55cSDimitry Andric              "is followed by a block that either has a terminating "
60349cc55cSDimitry Andric              "deoptimizing call or is terminated with an unreachable"));
61349cc55cSDimitry Andric 
detachDeadBlocks(ArrayRef<BasicBlock * > BBs,SmallVectorImpl<DominatorTree::UpdateType> * Updates,bool KeepOneInputPHIs)621fd87a68SDimitry Andric void llvm::detachDeadBlocks(
630b57cec5SDimitry Andric     ArrayRef<BasicBlock *> BBs,
640b57cec5SDimitry Andric     SmallVectorImpl<DominatorTree::UpdateType> *Updates,
650b57cec5SDimitry Andric     bool KeepOneInputPHIs) {
660b57cec5SDimitry Andric   for (auto *BB : BBs) {
670b57cec5SDimitry Andric     // Loop through all of our successors and make sure they know that one
680b57cec5SDimitry Andric     // of their predecessors is going away.
690b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
700b57cec5SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
710b57cec5SDimitry Andric       Succ->removePredecessor(BB, KeepOneInputPHIs);
720b57cec5SDimitry Andric       if (Updates && UniqueSuccessors.insert(Succ).second)
730b57cec5SDimitry Andric         Updates->push_back({DominatorTree::Delete, BB, Succ});
740b57cec5SDimitry Andric     }
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric     // Zap all the instructions in the block.
770b57cec5SDimitry Andric     while (!BB->empty()) {
780b57cec5SDimitry Andric       Instruction &I = BB->back();
790b57cec5SDimitry Andric       // If this instruction is used, replace uses with an arbitrary value.
800b57cec5SDimitry Andric       // Because control flow can't get here, we don't care what we replace the
810b57cec5SDimitry Andric       // value with.  Note that since this block is unreachable, and all values
820b57cec5SDimitry Andric       // contained within it must dominate their uses, that all uses will
830b57cec5SDimitry Andric       // eventually be removed (they are themselves dead).
840b57cec5SDimitry Andric       if (!I.use_empty())
85fcaf7f86SDimitry Andric         I.replaceAllUsesWith(PoisonValue::get(I.getType()));
86bdd1243dSDimitry Andric       BB->back().eraseFromParent();
870b57cec5SDimitry Andric     }
880b57cec5SDimitry Andric     new UnreachableInst(BB->getContext(), BB);
89bdd1243dSDimitry Andric     assert(BB->size() == 1 &&
900b57cec5SDimitry Andric            isa<UnreachableInst>(BB->getTerminator()) &&
910b57cec5SDimitry Andric            "The successor list of BB isn't empty before "
920b57cec5SDimitry Andric            "applying corresponding DTU updates.");
930b57cec5SDimitry Andric   }
940b57cec5SDimitry Andric }
950b57cec5SDimitry Andric 
DeleteDeadBlock(BasicBlock * BB,DomTreeUpdater * DTU,bool KeepOneInputPHIs)960b57cec5SDimitry Andric void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
970b57cec5SDimitry Andric                            bool KeepOneInputPHIs) {
980b57cec5SDimitry Andric   DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
990b57cec5SDimitry Andric }
1000b57cec5SDimitry Andric 
DeleteDeadBlocks(ArrayRef<BasicBlock * > BBs,DomTreeUpdater * DTU,bool KeepOneInputPHIs)1010b57cec5SDimitry Andric void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
1020b57cec5SDimitry Andric                             bool KeepOneInputPHIs) {
1030b57cec5SDimitry Andric #ifndef NDEBUG
1040b57cec5SDimitry Andric   // Make sure that all predecessors of each dead block is also dead.
1050b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
1060b57cec5SDimitry Andric   assert(Dead.size() == BBs.size() && "Duplicating blocks?");
1070b57cec5SDimitry Andric   for (auto *BB : Dead)
1080b57cec5SDimitry Andric     for (BasicBlock *Pred : predecessors(BB))
1090b57cec5SDimitry Andric       assert(Dead.count(Pred) && "All predecessors must be dead!");
1100b57cec5SDimitry Andric #endif
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> Updates;
1131fd87a68SDimitry Andric   detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric   if (DTU)
116e8d8bef9SDimitry Andric     DTU->applyUpdates(Updates);
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   for (BasicBlock *BB : BBs)
1190b57cec5SDimitry Andric     if (DTU)
1200b57cec5SDimitry Andric       DTU->deleteBB(BB);
1210b57cec5SDimitry Andric     else
1220b57cec5SDimitry Andric       BB->eraseFromParent();
1230b57cec5SDimitry Andric }
1240b57cec5SDimitry Andric 
EliminateUnreachableBlocks(Function & F,DomTreeUpdater * DTU,bool KeepOneInputPHIs)1250b57cec5SDimitry Andric bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
1260b57cec5SDimitry Andric                                       bool KeepOneInputPHIs) {
1270b57cec5SDimitry Andric   df_iterator_default_set<BasicBlock*> Reachable;
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   // Mark all reachable blocks.
1300b57cec5SDimitry Andric   for (BasicBlock *BB : depth_first_ext(&F, Reachable))
1310b57cec5SDimitry Andric     (void)BB/* Mark all reachable blocks */;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   // Collect all dead blocks.
1340b57cec5SDimitry Andric   std::vector<BasicBlock*> DeadBlocks;
135fe6060f1SDimitry Andric   for (BasicBlock &BB : F)
136fe6060f1SDimitry Andric     if (!Reachable.count(&BB))
137fe6060f1SDimitry Andric       DeadBlocks.push_back(&BB);
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   // Delete the dead blocks.
1400b57cec5SDimitry Andric   DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   return !DeadBlocks.empty();
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
FoldSingleEntryPHINodes(BasicBlock * BB,MemoryDependenceResults * MemDep)145e8d8bef9SDimitry Andric bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
1460b57cec5SDimitry Andric                                    MemoryDependenceResults *MemDep) {
147e8d8bef9SDimitry Andric   if (!isa<PHINode>(BB->begin()))
148e8d8bef9SDimitry Andric     return false;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1510b57cec5SDimitry Andric     if (PN->getIncomingValue(0) != PN)
1520b57cec5SDimitry Andric       PN->replaceAllUsesWith(PN->getIncomingValue(0));
1530b57cec5SDimitry Andric     else
154bdd1243dSDimitry Andric       PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric     if (MemDep)
1570b57cec5SDimitry Andric       MemDep->removeInstruction(PN);  // Memdep updates AA itself.
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric     PN->eraseFromParent();
1600b57cec5SDimitry Andric   }
161e8d8bef9SDimitry Andric   return true;
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric 
DeleteDeadPHIs(BasicBlock * BB,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU)1645ffd83dbSDimitry Andric bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI,
1655ffd83dbSDimitry Andric                           MemorySSAUpdater *MSSAU) {
1660b57cec5SDimitry Andric   // Recursively deleting a PHI may cause multiple PHIs to be deleted
1670b57cec5SDimitry Andric   // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
1680b57cec5SDimitry Andric   SmallVector<WeakTrackingVH, 8> PHIs;
1690b57cec5SDimitry Andric   for (PHINode &PN : BB->phis())
1700b57cec5SDimitry Andric     PHIs.push_back(&PN);
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   bool Changed = false;
1730b57cec5SDimitry Andric   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
1740b57cec5SDimitry Andric     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
1755ffd83dbSDimitry Andric       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   return Changed;
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric 
MergeBlockIntoPredecessor(BasicBlock * BB,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,MemoryDependenceResults * MemDep,bool PredecessorWithTwoSuccessors,DominatorTree * DT)1800b57cec5SDimitry Andric bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
1810b57cec5SDimitry Andric                                      LoopInfo *LI, MemorySSAUpdater *MSSAU,
1828bcb0991SDimitry Andric                                      MemoryDependenceResults *MemDep,
183bdd1243dSDimitry Andric                                      bool PredecessorWithTwoSuccessors,
184bdd1243dSDimitry Andric                                      DominatorTree *DT) {
1850b57cec5SDimitry Andric   if (BB->hasAddressTaken())
1860b57cec5SDimitry Andric     return false;
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   // Can't merge if there are multiple predecessors, or no predecessors.
1890b57cec5SDimitry Andric   BasicBlock *PredBB = BB->getUniquePredecessor();
1900b57cec5SDimitry Andric   if (!PredBB) return false;
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   // Don't break self-loops.
1930b57cec5SDimitry Andric   if (PredBB == BB) return false;
194fcaf7f86SDimitry Andric 
195fcaf7f86SDimitry Andric   // Don't break unwinding instructions or terminators with other side-effects.
196fcaf7f86SDimitry Andric   Instruction *PTI = PredBB->getTerminator();
197c9157d92SDimitry Andric   if (PTI->isSpecialTerminator() || PTI->mayHaveSideEffects())
1980b57cec5SDimitry Andric     return false;
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   // Can't merge if there are multiple distinct successors.
2018bcb0991SDimitry Andric   if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
2020b57cec5SDimitry Andric     return false;
2030b57cec5SDimitry Andric 
2048bcb0991SDimitry Andric   // Currently only allow PredBB to have two predecessors, one being BB.
2058bcb0991SDimitry Andric   // Update BI to branch to BB's only successor instead of BB.
2068bcb0991SDimitry Andric   BranchInst *PredBB_BI;
2078bcb0991SDimitry Andric   BasicBlock *NewSucc = nullptr;
2088bcb0991SDimitry Andric   unsigned FallThruPath;
2098bcb0991SDimitry Andric   if (PredecessorWithTwoSuccessors) {
210fcaf7f86SDimitry Andric     if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
2118bcb0991SDimitry Andric       return false;
2128bcb0991SDimitry Andric     BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
2138bcb0991SDimitry Andric     if (!BB_JmpI || !BB_JmpI->isUnconditional())
2148bcb0991SDimitry Andric       return false;
2158bcb0991SDimitry Andric     NewSucc = BB_JmpI->getSuccessor(0);
2168bcb0991SDimitry Andric     FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
2178bcb0991SDimitry Andric   }
2188bcb0991SDimitry Andric 
2190b57cec5SDimitry Andric   // Can't merge if there is PHI loop.
2200b57cec5SDimitry Andric   for (PHINode &PN : BB->phis())
221fe6060f1SDimitry Andric     if (llvm::is_contained(PN.incoming_values(), &PN))
2220b57cec5SDimitry Andric       return false;
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
2250b57cec5SDimitry Andric                     << PredBB->getName() << "\n");
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   // Begin by getting rid of unneeded PHIs.
2280b57cec5SDimitry Andric   SmallVector<AssertingVH<Value>, 4> IncomingValues;
2290b57cec5SDimitry Andric   if (isa<PHINode>(BB->front())) {
2300b57cec5SDimitry Andric     for (PHINode &PN : BB->phis())
2310b57cec5SDimitry Andric       if (!isa<PHINode>(PN.getIncomingValue(0)) ||
2320b57cec5SDimitry Andric           cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
2330b57cec5SDimitry Andric         IncomingValues.push_back(PN.getIncomingValue(0));
2340b57cec5SDimitry Andric     FoldSingleEntryPHINodes(BB, MemDep);
2350b57cec5SDimitry Andric   }
2360b57cec5SDimitry Andric 
237bdd1243dSDimitry Andric   if (DT) {
238bdd1243dSDimitry Andric     assert(!DTU && "cannot use both DT and DTU for updates");
239bdd1243dSDimitry Andric     DomTreeNode *PredNode = DT->getNode(PredBB);
240bdd1243dSDimitry Andric     DomTreeNode *BBNode = DT->getNode(BB);
241bdd1243dSDimitry Andric     if (PredNode) {
242bdd1243dSDimitry Andric       assert(BBNode && "PredNode unreachable but BBNode reachable?");
243bdd1243dSDimitry Andric       for (DomTreeNode *C : to_vector(BBNode->children()))
244bdd1243dSDimitry Andric         C->setIDom(PredNode);
245bdd1243dSDimitry Andric     }
246bdd1243dSDimitry Andric   }
2470b57cec5SDimitry Andric   // DTU update: Collect all the edges that exit BB.
2480b57cec5SDimitry Andric   // These dominator edges will be redirected from Pred.
2490b57cec5SDimitry Andric   std::vector<DominatorTree::UpdateType> Updates;
2500b57cec5SDimitry Andric   if (DTU) {
251bdd1243dSDimitry Andric     assert(!DT && "cannot use both DT and DTU for updates");
2524824e7fdSDimitry Andric     // To avoid processing the same predecessor more than once.
2534824e7fdSDimitry Andric     SmallPtrSet<BasicBlock *, 8> SeenSuccs;
254fe6060f1SDimitry Andric     SmallPtrSet<BasicBlock *, 2> SuccsOfPredBB(succ_begin(PredBB),
255349cc55cSDimitry Andric                                                succ_end(PredBB));
2564824e7fdSDimitry Andric     Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
2570b57cec5SDimitry Andric     // Add insert edges first. Experimentally, for the particular case of two
2580b57cec5SDimitry Andric     // blocks that can be merged, with a single successor and single predecessor
2590b57cec5SDimitry Andric     // respectively, it is beneficial to have all insert updates first. Deleting
2600b57cec5SDimitry Andric     // edges first may lead to unreachable blocks, followed by inserting edges
2610b57cec5SDimitry Andric     // making the blocks reachable again. Such DT updates lead to high compile
2620b57cec5SDimitry Andric     // times. We add inserts before deletes here to reduce compile time.
2634824e7fdSDimitry Andric     for (BasicBlock *SuccOfBB : successors(BB))
264fe6060f1SDimitry Andric       // This successor of BB may already be a PredBB's successor.
265fe6060f1SDimitry Andric       if (!SuccsOfPredBB.contains(SuccOfBB))
2664824e7fdSDimitry Andric         if (SeenSuccs.insert(SuccOfBB).second)
267fe6060f1SDimitry Andric           Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
2684824e7fdSDimitry Andric     SeenSuccs.clear();
2694824e7fdSDimitry Andric     for (BasicBlock *SuccOfBB : successors(BB))
2704824e7fdSDimitry Andric       if (SeenSuccs.insert(SuccOfBB).second)
271fe6060f1SDimitry Andric         Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
2720b57cec5SDimitry Andric     Updates.push_back({DominatorTree::Delete, PredBB, BB});
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric 
2758bcb0991SDimitry Andric   Instruction *STI = BB->getTerminator();
2768bcb0991SDimitry Andric   Instruction *Start = &*BB->begin();
2778bcb0991SDimitry Andric   // If there's nothing to move, mark the starting instruction as the last
278480093f4SDimitry Andric   // instruction in the block. Terminator instruction is handled separately.
2798bcb0991SDimitry Andric   if (Start == STI)
2808bcb0991SDimitry Andric     Start = PTI;
2810b57cec5SDimitry Andric 
2828bcb0991SDimitry Andric   // Move all definitions in the successor to the predecessor...
283bdd1243dSDimitry Andric   PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
2848bcb0991SDimitry Andric 
2858bcb0991SDimitry Andric   if (MSSAU)
2868bcb0991SDimitry Andric     MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   // Make all PHI nodes that referred to BB now refer to Pred as their
2890b57cec5SDimitry Andric   // source...
2900b57cec5SDimitry Andric   BB->replaceAllUsesWith(PredBB);
2910b57cec5SDimitry Andric 
2928bcb0991SDimitry Andric   if (PredecessorWithTwoSuccessors) {
2938bcb0991SDimitry Andric     // Delete the unconditional branch from BB.
294bdd1243dSDimitry Andric     BB->back().eraseFromParent();
2958bcb0991SDimitry Andric 
2968bcb0991SDimitry Andric     // Update branch in the predecessor.
2978bcb0991SDimitry Andric     PredBB_BI->setSuccessor(FallThruPath, NewSucc);
2988bcb0991SDimitry Andric   } else {
2998bcb0991SDimitry Andric     // Delete the unconditional branch from the predecessor.
300bdd1243dSDimitry Andric     PredBB->back().eraseFromParent();
3018bcb0991SDimitry Andric 
3028bcb0991SDimitry Andric     // Move terminator instruction.
303c9157d92SDimitry Andric     BB->back().moveBeforePreserving(*PredBB, PredBB->end());
304480093f4SDimitry Andric 
305480093f4SDimitry Andric     // Terminator may be a memory accessing instruction too.
306480093f4SDimitry Andric     if (MSSAU)
307480093f4SDimitry Andric       if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
308480093f4SDimitry Andric               MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
309480093f4SDimitry Andric         MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
3108bcb0991SDimitry Andric   }
3118bcb0991SDimitry Andric   // Add unreachable to now empty BB.
3120b57cec5SDimitry Andric   new UnreachableInst(BB->getContext(), BB);
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   // Inherit predecessors name if it exists.
3150b57cec5SDimitry Andric   if (!PredBB->hasName())
3160b57cec5SDimitry Andric     PredBB->takeName(BB);
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   if (LI)
3190b57cec5SDimitry Andric     LI->removeBlock(BB);
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   if (MemDep)
3220b57cec5SDimitry Andric     MemDep->invalidateCachedPredecessors();
3230b57cec5SDimitry Andric 
324fe6060f1SDimitry Andric   if (DTU)
325e8d8bef9SDimitry Andric     DTU->applyUpdates(Updates);
326fe6060f1SDimitry Andric 
327bdd1243dSDimitry Andric   if (DT) {
328bdd1243dSDimitry Andric     assert(succ_empty(BB) &&
329bdd1243dSDimitry Andric            "successors should have been transferred to PredBB");
330bdd1243dSDimitry Andric     DT->eraseNode(BB);
331bdd1243dSDimitry Andric   }
332bdd1243dSDimitry Andric 
333fe6060f1SDimitry Andric   // Finally, erase the old block and update dominator info.
334fe6060f1SDimitry Andric   DeleteDeadBlock(BB, DTU);
3358bcb0991SDimitry Andric 
3360b57cec5SDimitry Andric   return true;
3370b57cec5SDimitry Andric }
3380b57cec5SDimitry Andric 
MergeBlockSuccessorsIntoGivenBlocks(SmallPtrSetImpl<BasicBlock * > & MergeBlocks,Loop * L,DomTreeUpdater * DTU,LoopInfo * LI)3395ffd83dbSDimitry Andric bool llvm::MergeBlockSuccessorsIntoGivenBlocks(
3405ffd83dbSDimitry Andric     SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU,
3415ffd83dbSDimitry Andric     LoopInfo *LI) {
3425ffd83dbSDimitry Andric   assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
3435ffd83dbSDimitry Andric 
3445ffd83dbSDimitry Andric   bool BlocksHaveBeenMerged = false;
3455ffd83dbSDimitry Andric   while (!MergeBlocks.empty()) {
3465ffd83dbSDimitry Andric     BasicBlock *BB = *MergeBlocks.begin();
3475ffd83dbSDimitry Andric     BasicBlock *Dest = BB->getSingleSuccessor();
3485ffd83dbSDimitry Andric     if (Dest && (!L || L->contains(Dest))) {
3495ffd83dbSDimitry Andric       BasicBlock *Fold = Dest->getUniquePredecessor();
3505ffd83dbSDimitry Andric       (void)Fold;
3515ffd83dbSDimitry Andric       if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
3525ffd83dbSDimitry Andric         assert(Fold == BB &&
3535ffd83dbSDimitry Andric                "Expecting BB to be unique predecessor of the Dest block");
3545ffd83dbSDimitry Andric         MergeBlocks.erase(Dest);
3555ffd83dbSDimitry Andric         BlocksHaveBeenMerged = true;
3565ffd83dbSDimitry Andric       } else
3575ffd83dbSDimitry Andric         MergeBlocks.erase(BB);
3585ffd83dbSDimitry Andric     } else
3595ffd83dbSDimitry Andric       MergeBlocks.erase(BB);
3605ffd83dbSDimitry Andric   }
3615ffd83dbSDimitry Andric   return BlocksHaveBeenMerged;
3625ffd83dbSDimitry Andric }
3635ffd83dbSDimitry Andric 
364480093f4SDimitry Andric /// Remove redundant instructions within sequences of consecutive dbg.value
365480093f4SDimitry Andric /// instructions. This is done using a backward scan to keep the last dbg.value
366480093f4SDimitry Andric /// describing a specific variable/fragment.
367480093f4SDimitry Andric ///
368480093f4SDimitry Andric /// BackwardScan strategy:
369480093f4SDimitry Andric /// ----------------------
370480093f4SDimitry Andric /// Given a sequence of consecutive DbgValueInst like this
371480093f4SDimitry Andric ///
372480093f4SDimitry Andric ///   dbg.value ..., "x", FragmentX1  (*)
373480093f4SDimitry Andric ///   dbg.value ..., "y", FragmentY1
374480093f4SDimitry Andric ///   dbg.value ..., "x", FragmentX2
375480093f4SDimitry Andric ///   dbg.value ..., "x", FragmentX1  (**)
376480093f4SDimitry Andric ///
377480093f4SDimitry Andric /// then the instruction marked with (*) can be removed (it is guaranteed to be
378480093f4SDimitry Andric /// obsoleted by the instruction marked with (**) as the latter instruction is
379480093f4SDimitry Andric /// describing the same variable using the same fragment info).
380480093f4SDimitry Andric ///
381480093f4SDimitry Andric /// Possible improvements:
382480093f4SDimitry Andric /// - Check fully overlapping fragments and not only identical fragments.
383fe013be4SDimitry Andric /// - Support dbg.declare. dbg.label, and possibly other meta instructions being
384fe013be4SDimitry Andric ///   part of the sequence of consecutive instructions.
DPValuesRemoveRedundantDbgInstrsUsingBackwardScan(BasicBlock * BB)385c9157d92SDimitry Andric static bool DPValuesRemoveRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
386c9157d92SDimitry Andric   SmallVector<DPValue *, 8> ToBeRemoved;
387c9157d92SDimitry Andric   SmallDenseSet<DebugVariable> VariableSet;
388c9157d92SDimitry Andric   for (auto &I : reverse(*BB)) {
389c9157d92SDimitry Andric     for (DPValue &DPV : reverse(I.getDbgValueRange())) {
390c9157d92SDimitry Andric       // Skip declare-type records, as the debug intrinsic method only works
391c9157d92SDimitry Andric       // on dbg.value intrinsics.
392c9157d92SDimitry Andric       if (DPV.getType() == DPValue::LocationType::Declare) {
393c9157d92SDimitry Andric         // The debug intrinsic method treats dbg.declares are "non-debug"
394c9157d92SDimitry Andric         // instructions (i.e., a break in a consecutive range of debug
395c9157d92SDimitry Andric         // intrinsics). Emulate that to create identical outputs. See
396c9157d92SDimitry Andric         // "Possible improvements" above.
397c9157d92SDimitry Andric         // FIXME: Delete the line below.
398c9157d92SDimitry Andric         VariableSet.clear();
399c9157d92SDimitry Andric         continue;
400c9157d92SDimitry Andric       }
401c9157d92SDimitry Andric 
402c9157d92SDimitry Andric       DebugVariable Key(DPV.getVariable(), DPV.getExpression(),
403c9157d92SDimitry Andric                         DPV.getDebugLoc()->getInlinedAt());
404c9157d92SDimitry Andric       auto R = VariableSet.insert(Key);
405c9157d92SDimitry Andric       // If the same variable fragment is described more than once it is enough
406c9157d92SDimitry Andric       // to keep the last one (i.e. the first found since we for reverse
407c9157d92SDimitry Andric       // iteration).
408*a58f00eaSDimitry Andric       if (R.second)
409*a58f00eaSDimitry Andric         continue;
410*a58f00eaSDimitry Andric 
411*a58f00eaSDimitry Andric       if (DPV.isDbgAssign()) {
412*a58f00eaSDimitry Andric         // Don't delete dbg.assign intrinsics that are linked to instructions.
413*a58f00eaSDimitry Andric         if (!at::getAssignmentInsts(&DPV).empty())
414*a58f00eaSDimitry Andric           continue;
415*a58f00eaSDimitry Andric         // Unlinked dbg.assign intrinsics can be treated like dbg.values.
416*a58f00eaSDimitry Andric       }
417*a58f00eaSDimitry Andric 
418c9157d92SDimitry Andric       ToBeRemoved.push_back(&DPV);
419c9157d92SDimitry Andric       continue;
420c9157d92SDimitry Andric     }
421c9157d92SDimitry Andric     // Sequence with consecutive dbg.value instrs ended. Clear the map to
422c9157d92SDimitry Andric     // restart identifying redundant instructions if case we find another
423c9157d92SDimitry Andric     // dbg.value sequence.
424c9157d92SDimitry Andric     VariableSet.clear();
425c9157d92SDimitry Andric   }
426c9157d92SDimitry Andric 
427c9157d92SDimitry Andric   for (auto &DPV : ToBeRemoved)
428c9157d92SDimitry Andric     DPV->eraseFromParent();
429c9157d92SDimitry Andric 
430c9157d92SDimitry Andric   return !ToBeRemoved.empty();
431c9157d92SDimitry Andric }
432c9157d92SDimitry Andric 
removeRedundantDbgInstrsUsingBackwardScan(BasicBlock * BB)433480093f4SDimitry Andric static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
434c9157d92SDimitry Andric   if (BB->IsNewDbgInfoFormat)
435c9157d92SDimitry Andric     return DPValuesRemoveRedundantDbgInstrsUsingBackwardScan(BB);
436c9157d92SDimitry Andric 
437480093f4SDimitry Andric   SmallVector<DbgValueInst *, 8> ToBeRemoved;
438480093f4SDimitry Andric   SmallDenseSet<DebugVariable> VariableSet;
439480093f4SDimitry Andric   for (auto &I : reverse(*BB)) {
440480093f4SDimitry Andric     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
441480093f4SDimitry Andric       DebugVariable Key(DVI->getVariable(),
442480093f4SDimitry Andric                         DVI->getExpression(),
443480093f4SDimitry Andric                         DVI->getDebugLoc()->getInlinedAt());
444480093f4SDimitry Andric       auto R = VariableSet.insert(Key);
445bdd1243dSDimitry Andric       // If the variable fragment hasn't been seen before then we don't want
446bdd1243dSDimitry Andric       // to remove this dbg intrinsic.
447bdd1243dSDimitry Andric       if (R.second)
448bdd1243dSDimitry Andric         continue;
449bdd1243dSDimitry Andric 
450bdd1243dSDimitry Andric       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI)) {
451bdd1243dSDimitry Andric         // Don't delete dbg.assign intrinsics that are linked to instructions.
452bdd1243dSDimitry Andric         if (!at::getAssignmentInsts(DAI).empty())
453bdd1243dSDimitry Andric           continue;
454bdd1243dSDimitry Andric         // Unlinked dbg.assign intrinsics can be treated like dbg.values.
455bdd1243dSDimitry Andric       }
456bdd1243dSDimitry Andric 
457480093f4SDimitry Andric       // If the same variable fragment is described more than once it is enough
458480093f4SDimitry Andric       // to keep the last one (i.e. the first found since we for reverse
459480093f4SDimitry Andric       // iteration).
460480093f4SDimitry Andric       ToBeRemoved.push_back(DVI);
461480093f4SDimitry Andric       continue;
462480093f4SDimitry Andric     }
463480093f4SDimitry Andric     // Sequence with consecutive dbg.value instrs ended. Clear the map to
464480093f4SDimitry Andric     // restart identifying redundant instructions if case we find another
465480093f4SDimitry Andric     // dbg.value sequence.
466480093f4SDimitry Andric     VariableSet.clear();
467480093f4SDimitry Andric   }
468480093f4SDimitry Andric 
469480093f4SDimitry Andric   for (auto &Instr : ToBeRemoved)
470480093f4SDimitry Andric     Instr->eraseFromParent();
471480093f4SDimitry Andric 
472480093f4SDimitry Andric   return !ToBeRemoved.empty();
473480093f4SDimitry Andric }
474480093f4SDimitry Andric 
475480093f4SDimitry Andric /// Remove redundant dbg.value instructions using a forward scan. This can
476480093f4SDimitry Andric /// remove a dbg.value instruction that is redundant due to indicating that a
477480093f4SDimitry Andric /// variable has the same value as already being indicated by an earlier
478480093f4SDimitry Andric /// dbg.value.
479480093f4SDimitry Andric ///
480480093f4SDimitry Andric /// ForwardScan strategy:
481480093f4SDimitry Andric /// ---------------------
482480093f4SDimitry Andric /// Given two identical dbg.value instructions, separated by a block of
483480093f4SDimitry Andric /// instructions that isn't describing the same variable, like this
484480093f4SDimitry Andric ///
485480093f4SDimitry Andric ///   dbg.value X1, "x", FragmentX1  (**)
486480093f4SDimitry Andric ///   <block of instructions, none being "dbg.value ..., "x", ...">
487480093f4SDimitry Andric ///   dbg.value X1, "x", FragmentX1  (*)
488480093f4SDimitry Andric ///
489480093f4SDimitry Andric /// then the instruction marked with (*) can be removed. Variable "x" is already
490480093f4SDimitry Andric /// described as being mapped to the SSA value X1.
491480093f4SDimitry Andric ///
492480093f4SDimitry Andric /// Possible improvements:
493480093f4SDimitry Andric /// - Keep track of non-overlapping fragments.
DPValuesRemoveRedundantDbgInstrsUsingForwardScan(BasicBlock * BB)494c9157d92SDimitry Andric static bool DPValuesRemoveRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
495c9157d92SDimitry Andric   SmallVector<DPValue *, 8> ToBeRemoved;
496c9157d92SDimitry Andric   DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
497c9157d92SDimitry Andric       VariableMap;
498c9157d92SDimitry Andric   for (auto &I : *BB) {
499c9157d92SDimitry Andric     for (DPValue &DPV : I.getDbgValueRange()) {
500c9157d92SDimitry Andric       if (DPV.getType() == DPValue::LocationType::Declare)
501c9157d92SDimitry Andric         continue;
502c9157d92SDimitry Andric       DebugVariable Key(DPV.getVariable(), std::nullopt,
503c9157d92SDimitry Andric                         DPV.getDebugLoc()->getInlinedAt());
504c9157d92SDimitry Andric       auto VMI = VariableMap.find(Key);
505*a58f00eaSDimitry Andric       // A dbg.assign with no linked instructions can be treated like a
506*a58f00eaSDimitry Andric       // dbg.value (i.e. can be deleted).
507*a58f00eaSDimitry Andric       bool IsDbgValueKind =
508*a58f00eaSDimitry Andric           (!DPV.isDbgAssign() || at::getAssignmentInsts(&DPV).empty());
509*a58f00eaSDimitry Andric 
510c9157d92SDimitry Andric       // Update the map if we found a new value/expression describing the
511c9157d92SDimitry Andric       // variable, or if the variable wasn't mapped already.
512c9157d92SDimitry Andric       SmallVector<Value *, 4> Values(DPV.location_ops());
513c9157d92SDimitry Andric       if (VMI == VariableMap.end() || VMI->second.first != Values ||
514c9157d92SDimitry Andric           VMI->second.second != DPV.getExpression()) {
515*a58f00eaSDimitry Andric         if (IsDbgValueKind)
516c9157d92SDimitry Andric           VariableMap[Key] = {Values, DPV.getExpression()};
517*a58f00eaSDimitry Andric         else
518*a58f00eaSDimitry Andric           VariableMap[Key] = {Values, nullptr};
519c9157d92SDimitry Andric         continue;
520c9157d92SDimitry Andric       }
521*a58f00eaSDimitry Andric       // Don't delete dbg.assign intrinsics that are linked to instructions.
522*a58f00eaSDimitry Andric       if (!IsDbgValueKind)
523*a58f00eaSDimitry Andric         continue;
524c9157d92SDimitry Andric       // Found an identical mapping. Remember the instruction for later removal.
525c9157d92SDimitry Andric       ToBeRemoved.push_back(&DPV);
526c9157d92SDimitry Andric     }
527c9157d92SDimitry Andric   }
528c9157d92SDimitry Andric 
529c9157d92SDimitry Andric   for (auto *DPV : ToBeRemoved)
530c9157d92SDimitry Andric     DPV->eraseFromParent();
531c9157d92SDimitry Andric 
532c9157d92SDimitry Andric   return !ToBeRemoved.empty();
533c9157d92SDimitry Andric }
534c9157d92SDimitry Andric 
DPValuesRemoveUndefDbgAssignsFromEntryBlock(BasicBlock * BB)535*a58f00eaSDimitry Andric static bool DPValuesRemoveUndefDbgAssignsFromEntryBlock(BasicBlock *BB) {
536*a58f00eaSDimitry Andric   assert(BB->isEntryBlock() && "expected entry block");
537*a58f00eaSDimitry Andric   SmallVector<DPValue *, 8> ToBeRemoved;
538*a58f00eaSDimitry Andric   DenseSet<DebugVariable> SeenDefForAggregate;
539*a58f00eaSDimitry Andric   // Returns the DebugVariable for DVI with no fragment info.
540*a58f00eaSDimitry Andric   auto GetAggregateVariable = [](const DPValue &DPV) {
541*a58f00eaSDimitry Andric     return DebugVariable(DPV.getVariable(), std::nullopt,
542*a58f00eaSDimitry Andric                          DPV.getDebugLoc().getInlinedAt());
543*a58f00eaSDimitry Andric   };
544*a58f00eaSDimitry Andric 
545*a58f00eaSDimitry Andric   // Remove undef dbg.assign intrinsics that are encountered before
546*a58f00eaSDimitry Andric   // any non-undef intrinsics from the entry block.
547*a58f00eaSDimitry Andric   for (auto &I : *BB) {
548*a58f00eaSDimitry Andric     for (DPValue &DPV : I.getDbgValueRange()) {
549*a58f00eaSDimitry Andric       if (!DPV.isDbgValue() && !DPV.isDbgAssign())
550*a58f00eaSDimitry Andric         continue;
551*a58f00eaSDimitry Andric       bool IsDbgValueKind =
552*a58f00eaSDimitry Andric           (DPV.isDbgValue() || at::getAssignmentInsts(&DPV).empty());
553*a58f00eaSDimitry Andric       DebugVariable Aggregate = GetAggregateVariable(DPV);
554*a58f00eaSDimitry Andric       if (!SeenDefForAggregate.contains(Aggregate)) {
555*a58f00eaSDimitry Andric         bool IsKill = DPV.isKillLocation() && IsDbgValueKind;
556*a58f00eaSDimitry Andric         if (!IsKill) {
557*a58f00eaSDimitry Andric           SeenDefForAggregate.insert(Aggregate);
558*a58f00eaSDimitry Andric         } else if (DPV.isDbgAssign()) {
559*a58f00eaSDimitry Andric           ToBeRemoved.push_back(&DPV);
560*a58f00eaSDimitry Andric         }
561*a58f00eaSDimitry Andric       }
562*a58f00eaSDimitry Andric     }
563*a58f00eaSDimitry Andric   }
564*a58f00eaSDimitry Andric 
565*a58f00eaSDimitry Andric   for (DPValue *DPV : ToBeRemoved)
566*a58f00eaSDimitry Andric     DPV->eraseFromParent();
567*a58f00eaSDimitry Andric 
568*a58f00eaSDimitry Andric   return !ToBeRemoved.empty();
569*a58f00eaSDimitry Andric }
570*a58f00eaSDimitry Andric 
removeRedundantDbgInstrsUsingForwardScan(BasicBlock * BB)571480093f4SDimitry Andric static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
572c9157d92SDimitry Andric   if (BB->IsNewDbgInfoFormat)
573c9157d92SDimitry Andric     return DPValuesRemoveRedundantDbgInstrsUsingForwardScan(BB);
574c9157d92SDimitry Andric 
575480093f4SDimitry Andric   SmallVector<DbgValueInst *, 8> ToBeRemoved;
576fe6060f1SDimitry Andric   DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
577fe6060f1SDimitry Andric       VariableMap;
578480093f4SDimitry Andric   for (auto &I : *BB) {
579480093f4SDimitry Andric     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
580bdd1243dSDimitry Andric       DebugVariable Key(DVI->getVariable(), std::nullopt,
581480093f4SDimitry Andric                         DVI->getDebugLoc()->getInlinedAt());
582480093f4SDimitry Andric       auto VMI = VariableMap.find(Key);
583bdd1243dSDimitry Andric       auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
584bdd1243dSDimitry Andric       // A dbg.assign with no linked instructions can be treated like a
585bdd1243dSDimitry Andric       // dbg.value (i.e. can be deleted).
586bdd1243dSDimitry Andric       bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
587bdd1243dSDimitry Andric 
588480093f4SDimitry Andric       // Update the map if we found a new value/expression describing the
589480093f4SDimitry Andric       // variable, or if the variable wasn't mapped already.
590fe6060f1SDimitry Andric       SmallVector<Value *, 4> Values(DVI->getValues());
591fe6060f1SDimitry Andric       if (VMI == VariableMap.end() || VMI->second.first != Values ||
592480093f4SDimitry Andric           VMI->second.second != DVI->getExpression()) {
593*a58f00eaSDimitry Andric         // Use a sentinel value (nullptr) for the DIExpression when we see a
594bdd1243dSDimitry Andric         // linked dbg.assign so that the next debug intrinsic will never match
595bdd1243dSDimitry Andric         // it (i.e. always treat linked dbg.assigns as if they're unique).
596bdd1243dSDimitry Andric         if (IsDbgValueKind)
597fe6060f1SDimitry Andric           VariableMap[Key] = {Values, DVI->getExpression()};
598bdd1243dSDimitry Andric         else
599bdd1243dSDimitry Andric           VariableMap[Key] = {Values, nullptr};
600480093f4SDimitry Andric         continue;
601480093f4SDimitry Andric       }
602bdd1243dSDimitry Andric 
603bdd1243dSDimitry Andric       // Don't delete dbg.assign intrinsics that are linked to instructions.
604bdd1243dSDimitry Andric       if (!IsDbgValueKind)
605bdd1243dSDimitry Andric         continue;
606480093f4SDimitry Andric       ToBeRemoved.push_back(DVI);
607480093f4SDimitry Andric     }
608480093f4SDimitry Andric   }
609480093f4SDimitry Andric 
610480093f4SDimitry Andric   for (auto &Instr : ToBeRemoved)
611480093f4SDimitry Andric     Instr->eraseFromParent();
612480093f4SDimitry Andric 
613480093f4SDimitry Andric   return !ToBeRemoved.empty();
614480093f4SDimitry Andric }
615480093f4SDimitry Andric 
616bdd1243dSDimitry Andric /// Remove redundant undef dbg.assign intrinsic from an entry block using a
617bdd1243dSDimitry Andric /// forward scan.
618bdd1243dSDimitry Andric /// Strategy:
619bdd1243dSDimitry Andric /// ---------------------
620bdd1243dSDimitry Andric /// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
621bdd1243dSDimitry Andric /// linked to an intrinsic, and don't share an aggregate variable with a debug
622bdd1243dSDimitry Andric /// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
623bdd1243dSDimitry Andric /// that come before non-undef debug intrinsics for the variable are
624bdd1243dSDimitry Andric /// deleted. Given:
625bdd1243dSDimitry Andric ///
626bdd1243dSDimitry Andric ///   dbg.assign undef, "x", FragmentX1 (*)
627bdd1243dSDimitry Andric ///   <block of instructions, none being "dbg.value ..., "x", ...">
628bdd1243dSDimitry Andric ///   dbg.value %V, "x", FragmentX2
629bdd1243dSDimitry Andric ///   <block of instructions, none being "dbg.value ..., "x", ...">
630bdd1243dSDimitry Andric ///   dbg.assign undef, "x", FragmentX1
631bdd1243dSDimitry Andric ///
632bdd1243dSDimitry Andric /// then (only) the instruction marked with (*) can be removed.
633bdd1243dSDimitry Andric /// Possible improvements:
634bdd1243dSDimitry Andric /// - Keep track of non-overlapping fragments.
removeUndefDbgAssignsFromEntryBlock(BasicBlock * BB)635*a58f00eaSDimitry Andric static bool removeUndefDbgAssignsFromEntryBlock(BasicBlock *BB) {
636*a58f00eaSDimitry Andric   if (BB->IsNewDbgInfoFormat)
637*a58f00eaSDimitry Andric     return DPValuesRemoveUndefDbgAssignsFromEntryBlock(BB);
638*a58f00eaSDimitry Andric 
639bdd1243dSDimitry Andric   assert(BB->isEntryBlock() && "expected entry block");
640bdd1243dSDimitry Andric   SmallVector<DbgAssignIntrinsic *, 8> ToBeRemoved;
641bdd1243dSDimitry Andric   DenseSet<DebugVariable> SeenDefForAggregate;
642bdd1243dSDimitry Andric   // Returns the DebugVariable for DVI with no fragment info.
643bdd1243dSDimitry Andric   auto GetAggregateVariable = [](DbgValueInst *DVI) {
644bdd1243dSDimitry Andric     return DebugVariable(DVI->getVariable(), std::nullopt,
645bdd1243dSDimitry Andric                          DVI->getDebugLoc()->getInlinedAt());
646bdd1243dSDimitry Andric   };
647bdd1243dSDimitry Andric 
648bdd1243dSDimitry Andric   // Remove undef dbg.assign intrinsics that are encountered before
649bdd1243dSDimitry Andric   // any non-undef intrinsics from the entry block.
650bdd1243dSDimitry Andric   for (auto &I : *BB) {
651bdd1243dSDimitry Andric     DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I);
652bdd1243dSDimitry Andric     if (!DVI)
653bdd1243dSDimitry Andric       continue;
654bdd1243dSDimitry Andric     auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
655bdd1243dSDimitry Andric     bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
656bdd1243dSDimitry Andric     DebugVariable Aggregate = GetAggregateVariable(DVI);
657bdd1243dSDimitry Andric     if (!SeenDefForAggregate.contains(Aggregate)) {
658bdd1243dSDimitry Andric       bool IsKill = DVI->isKillLocation() && IsDbgValueKind;
659bdd1243dSDimitry Andric       if (!IsKill) {
660bdd1243dSDimitry Andric         SeenDefForAggregate.insert(Aggregate);
661bdd1243dSDimitry Andric       } else if (DAI) {
662bdd1243dSDimitry Andric         ToBeRemoved.push_back(DAI);
663bdd1243dSDimitry Andric       }
664bdd1243dSDimitry Andric     }
665bdd1243dSDimitry Andric   }
666bdd1243dSDimitry Andric 
667bdd1243dSDimitry Andric   for (DbgAssignIntrinsic *DAI : ToBeRemoved)
668bdd1243dSDimitry Andric     DAI->eraseFromParent();
669bdd1243dSDimitry Andric 
670bdd1243dSDimitry Andric   return !ToBeRemoved.empty();
671bdd1243dSDimitry Andric }
672bdd1243dSDimitry Andric 
RemoveRedundantDbgInstrs(BasicBlock * BB)673480093f4SDimitry Andric bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) {
674480093f4SDimitry Andric   bool MadeChanges = false;
675480093f4SDimitry Andric   // By using the "backward scan" strategy before the "forward scan" strategy we
676480093f4SDimitry Andric   // can remove both dbg.value (2) and (3) in a situation like this:
677480093f4SDimitry Andric   //
678480093f4SDimitry Andric   //   (1) dbg.value V1, "x", DIExpression()
679480093f4SDimitry Andric   //       ...
680480093f4SDimitry Andric   //   (2) dbg.value V2, "x", DIExpression()
681480093f4SDimitry Andric   //   (3) dbg.value V1, "x", DIExpression()
682480093f4SDimitry Andric   //
683480093f4SDimitry Andric   // The backward scan will remove (2), it is made obsolete by (3). After
684480093f4SDimitry Andric   // getting (2) out of the way, the foward scan will remove (3) since "x"
685480093f4SDimitry Andric   // already is described as having the value V1 at (1).
686480093f4SDimitry Andric   MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB);
687bdd1243dSDimitry Andric   if (BB->isEntryBlock() &&
688bdd1243dSDimitry Andric       isAssignmentTrackingEnabled(*BB->getParent()->getParent()))
689*a58f00eaSDimitry Andric     MadeChanges |= removeUndefDbgAssignsFromEntryBlock(BB);
690480093f4SDimitry Andric   MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB);
691480093f4SDimitry Andric 
692480093f4SDimitry Andric   if (MadeChanges)
693480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
694480093f4SDimitry Andric                       << BB->getName() << "\n");
695480093f4SDimitry Andric   return MadeChanges;
696480093f4SDimitry Andric }
697480093f4SDimitry Andric 
ReplaceInstWithValue(BasicBlock::iterator & BI,Value * V)698bdd1243dSDimitry Andric void llvm::ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V) {
6990b57cec5SDimitry Andric   Instruction &I = *BI;
7000b57cec5SDimitry Andric   // Replaces all of the uses of the instruction with uses of the value
7010b57cec5SDimitry Andric   I.replaceAllUsesWith(V);
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   // Make sure to propagate a name if there is one already.
7040b57cec5SDimitry Andric   if (I.hasName() && !V->hasName())
7050b57cec5SDimitry Andric     V->takeName(&I);
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric   // Delete the unnecessary instruction now...
708bdd1243dSDimitry Andric   BI = BI->eraseFromParent();
7090b57cec5SDimitry Andric }
7100b57cec5SDimitry Andric 
ReplaceInstWithInst(BasicBlock * BB,BasicBlock::iterator & BI,Instruction * I)711bdd1243dSDimitry Andric void llvm::ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI,
712bdd1243dSDimitry Andric                                Instruction *I) {
7130b57cec5SDimitry Andric   assert(I->getParent() == nullptr &&
7140b57cec5SDimitry Andric          "ReplaceInstWithInst: Instruction already inserted into basic block!");
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   // Copy debug location to newly added instruction, if it wasn't already set
7170b57cec5SDimitry Andric   // by the caller.
7180b57cec5SDimitry Andric   if (!I->getDebugLoc())
7190b57cec5SDimitry Andric     I->setDebugLoc(BI->getDebugLoc());
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   // Insert the new instruction into the basic block...
722bdd1243dSDimitry Andric   BasicBlock::iterator New = I->insertInto(BB, BI);
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric   // Replace all uses of the old instruction, and delete it.
725bdd1243dSDimitry Andric   ReplaceInstWithValue(BI, I);
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric   // Move BI back to point to the newly inserted instruction
7280b57cec5SDimitry Andric   BI = New;
7290b57cec5SDimitry Andric }
7300b57cec5SDimitry Andric 
IsBlockFollowedByDeoptOrUnreachable(const BasicBlock * BB)731349cc55cSDimitry Andric bool llvm::IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB) {
732349cc55cSDimitry Andric   // Remember visited blocks to avoid infinite loop
733349cc55cSDimitry Andric   SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
734349cc55cSDimitry Andric   unsigned Depth = 0;
735349cc55cSDimitry Andric   while (BB && Depth++ < MaxDeoptOrUnreachableSuccessorCheckDepth &&
736349cc55cSDimitry Andric          VisitedBlocks.insert(BB).second) {
737fe013be4SDimitry Andric     if (isa<UnreachableInst>(BB->getTerminator()) ||
738fe013be4SDimitry Andric         BB->getTerminatingDeoptimizeCall())
739349cc55cSDimitry Andric       return true;
740349cc55cSDimitry Andric     BB = BB->getUniqueSuccessor();
741349cc55cSDimitry Andric   }
742349cc55cSDimitry Andric   return false;
743349cc55cSDimitry Andric }
744349cc55cSDimitry Andric 
ReplaceInstWithInst(Instruction * From,Instruction * To)7450b57cec5SDimitry Andric void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
7460b57cec5SDimitry Andric   BasicBlock::iterator BI(From);
747bdd1243dSDimitry Andric   ReplaceInstWithInst(From->getParent(), BI, To);
7480b57cec5SDimitry Andric }
7490b57cec5SDimitry Andric 
SplitEdge(BasicBlock * BB,BasicBlock * Succ,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName)7500b57cec5SDimitry Andric BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
751e8d8bef9SDimitry Andric                             LoopInfo *LI, MemorySSAUpdater *MSSAU,
752e8d8bef9SDimitry Andric                             const Twine &BBName) {
7530b57cec5SDimitry Andric   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   Instruction *LatchTerm = BB->getTerminator();
756fe6060f1SDimitry Andric 
757fe6060f1SDimitry Andric   CriticalEdgeSplittingOptions Options =
758fe6060f1SDimitry Andric       CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA();
759fe6060f1SDimitry Andric 
760fe6060f1SDimitry Andric   if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
761fe6060f1SDimitry Andric     // If it is a critical edge, and the succesor is an exception block, handle
762fe6060f1SDimitry Andric     // the split edge logic in this specific function
763fe6060f1SDimitry Andric     if (Succ->isEHPad())
764fe6060f1SDimitry Andric       return ehAwareSplitEdge(BB, Succ, nullptr, nullptr, Options, BBName);
765fe6060f1SDimitry Andric 
766fe6060f1SDimitry Andric     // If this is a critical edge, let SplitKnownCriticalEdge do it.
767fe6060f1SDimitry Andric     return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
768fe6060f1SDimitry Andric   }
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric   // If the edge isn't critical, then BB has a single successor or Succ has a
7710b57cec5SDimitry Andric   // single pred.  Split the block.
7720b57cec5SDimitry Andric   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
7730b57cec5SDimitry Andric     // If the successor only has a single pred, split the top of the successor
7740b57cec5SDimitry Andric     // block.
7750b57cec5SDimitry Andric     assert(SP == BB && "CFG broken");
7760b57cec5SDimitry Andric     SP = nullptr;
777e8d8bef9SDimitry Andric     return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
778e8d8bef9SDimitry Andric                       /*Before=*/true);
7790b57cec5SDimitry Andric   }
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   // Otherwise, if BB has a single successor, split it at the bottom of the
7820b57cec5SDimitry Andric   // block.
7830b57cec5SDimitry Andric   assert(BB->getTerminator()->getNumSuccessors() == 1 &&
7840b57cec5SDimitry Andric          "Should have a single succ!");
785e8d8bef9SDimitry Andric   return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
7860b57cec5SDimitry Andric }
7870b57cec5SDimitry Andric 
setUnwindEdgeTo(Instruction * TI,BasicBlock * Succ)788fe6060f1SDimitry Andric void llvm::setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
789fe6060f1SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI))
790fe6060f1SDimitry Andric     II->setUnwindDest(Succ);
791fe6060f1SDimitry Andric   else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
792fe6060f1SDimitry Andric     CS->setUnwindDest(Succ);
793fe6060f1SDimitry Andric   else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
794fe6060f1SDimitry Andric     CR->setUnwindDest(Succ);
795fe6060f1SDimitry Andric   else
796fe6060f1SDimitry Andric     llvm_unreachable("unexpected terminator instruction");
797fe6060f1SDimitry Andric }
798fe6060f1SDimitry Andric 
updatePhiNodes(BasicBlock * DestBB,BasicBlock * OldPred,BasicBlock * NewPred,PHINode * Until)799fe6060f1SDimitry Andric void llvm::updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
800fe6060f1SDimitry Andric                           BasicBlock *NewPred, PHINode *Until) {
801fe6060f1SDimitry Andric   int BBIdx = 0;
802fe6060f1SDimitry Andric   for (PHINode &PN : DestBB->phis()) {
803fe6060f1SDimitry Andric     // We manually update the LandingPadReplacement PHINode and it is the last
804fe6060f1SDimitry Andric     // PHI Node. So, if we find it, we are done.
805fe6060f1SDimitry Andric     if (Until == &PN)
806fe6060f1SDimitry Andric       break;
807fe6060f1SDimitry Andric 
808fe6060f1SDimitry Andric     // Reuse the previous value of BBIdx if it lines up.  In cases where we
809fe6060f1SDimitry Andric     // have multiple phi nodes with *lots* of predecessors, this is a speed
810fe6060f1SDimitry Andric     // win because we don't have to scan the PHI looking for TIBB.  This
811fe6060f1SDimitry Andric     // happens because the BB list of PHI nodes are usually in the same
812fe6060f1SDimitry Andric     // order.
813fe6060f1SDimitry Andric     if (PN.getIncomingBlock(BBIdx) != OldPred)
814fe6060f1SDimitry Andric       BBIdx = PN.getBasicBlockIndex(OldPred);
815fe6060f1SDimitry Andric 
816fe6060f1SDimitry Andric     assert(BBIdx != -1 && "Invalid PHI Index!");
817fe6060f1SDimitry Andric     PN.setIncomingBlock(BBIdx, NewPred);
818fe6060f1SDimitry Andric   }
819fe6060f1SDimitry Andric }
820fe6060f1SDimitry Andric 
ehAwareSplitEdge(BasicBlock * BB,BasicBlock * Succ,LandingPadInst * OriginalPad,PHINode * LandingPadReplacement,const CriticalEdgeSplittingOptions & Options,const Twine & BBName)821fe6060f1SDimitry Andric BasicBlock *llvm::ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
822fe6060f1SDimitry Andric                                    LandingPadInst *OriginalPad,
823fe6060f1SDimitry Andric                                    PHINode *LandingPadReplacement,
824fe6060f1SDimitry Andric                                    const CriticalEdgeSplittingOptions &Options,
825fe6060f1SDimitry Andric                                    const Twine &BBName) {
826fe6060f1SDimitry Andric 
827fe6060f1SDimitry Andric   auto *PadInst = Succ->getFirstNonPHI();
828fe6060f1SDimitry Andric   if (!LandingPadReplacement && !PadInst->isEHPad())
829fe6060f1SDimitry Andric     return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
830fe6060f1SDimitry Andric 
831fe6060f1SDimitry Andric   auto *LI = Options.LI;
832fe6060f1SDimitry Andric   SmallVector<BasicBlock *, 4> LoopPreds;
833fe6060f1SDimitry Andric   // Check if extra modifications will be required to preserve loop-simplify
834fe6060f1SDimitry Andric   // form after splitting. If it would require splitting blocks with IndirectBr
835fe6060f1SDimitry Andric   // terminators, bail out if preserving loop-simplify form is requested.
836fe6060f1SDimitry Andric   if (Options.PreserveLoopSimplify && LI) {
837fe6060f1SDimitry Andric     if (Loop *BBLoop = LI->getLoopFor(BB)) {
838fe6060f1SDimitry Andric 
839fe6060f1SDimitry Andric       // The only way that we can break LoopSimplify form by splitting a
840fe6060f1SDimitry Andric       // critical edge is when there exists some edge from BBLoop to Succ *and*
841fe6060f1SDimitry Andric       // the only edge into Succ from outside of BBLoop is that of NewBB after
842fe6060f1SDimitry Andric       // the split. If the first isn't true, then LoopSimplify still holds,
843fe6060f1SDimitry Andric       // NewBB is the new exit block and it has no non-loop predecessors. If the
844fe6060f1SDimitry Andric       // second isn't true, then Succ was not in LoopSimplify form prior to
845fe6060f1SDimitry Andric       // the split as it had a non-loop predecessor. In both of these cases,
846fe6060f1SDimitry Andric       // the predecessor must be directly in BBLoop, not in a subloop, or again
847fe6060f1SDimitry Andric       // LoopSimplify doesn't hold.
848fe6060f1SDimitry Andric       for (BasicBlock *P : predecessors(Succ)) {
849fe6060f1SDimitry Andric         if (P == BB)
850fe6060f1SDimitry Andric           continue; // The new block is known.
851fe6060f1SDimitry Andric         if (LI->getLoopFor(P) != BBLoop) {
852fe6060f1SDimitry Andric           // Loop is not in LoopSimplify form, no need to re simplify after
853fe6060f1SDimitry Andric           // splitting edge.
854fe6060f1SDimitry Andric           LoopPreds.clear();
855fe6060f1SDimitry Andric           break;
856fe6060f1SDimitry Andric         }
857fe6060f1SDimitry Andric         LoopPreds.push_back(P);
858fe6060f1SDimitry Andric       }
859fe6060f1SDimitry Andric       // Loop-simplify form can be preserved, if we can split all in-loop
860fe6060f1SDimitry Andric       // predecessors.
861fe6060f1SDimitry Andric       if (any_of(LoopPreds, [](BasicBlock *Pred) {
862fe6060f1SDimitry Andric             return isa<IndirectBrInst>(Pred->getTerminator());
863fe6060f1SDimitry Andric           })) {
864fe6060f1SDimitry Andric         return nullptr;
865fe6060f1SDimitry Andric       }
866fe6060f1SDimitry Andric     }
867fe6060f1SDimitry Andric   }
868fe6060f1SDimitry Andric 
869fe6060f1SDimitry Andric   auto *NewBB =
870fe6060f1SDimitry Andric       BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
871fe6060f1SDimitry Andric   setUnwindEdgeTo(BB->getTerminator(), NewBB);
872fe6060f1SDimitry Andric   updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
873fe6060f1SDimitry Andric 
874fe6060f1SDimitry Andric   if (LandingPadReplacement) {
875fe6060f1SDimitry Andric     auto *NewLP = OriginalPad->clone();
876fe6060f1SDimitry Andric     auto *Terminator = BranchInst::Create(Succ, NewBB);
877fe6060f1SDimitry Andric     NewLP->insertBefore(Terminator);
878fe6060f1SDimitry Andric     LandingPadReplacement->addIncoming(NewLP, NewBB);
879fe6060f1SDimitry Andric   } else {
880fe6060f1SDimitry Andric     Value *ParentPad = nullptr;
881fe6060f1SDimitry Andric     if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
882fe6060f1SDimitry Andric       ParentPad = FuncletPad->getParentPad();
883fe6060f1SDimitry Andric     else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
884fe6060f1SDimitry Andric       ParentPad = CatchSwitch->getParentPad();
885fe6060f1SDimitry Andric     else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
886fe6060f1SDimitry Andric       ParentPad = CleanupPad->getParentPad();
887fe6060f1SDimitry Andric     else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
888fe6060f1SDimitry Andric       ParentPad = LandingPad->getParent();
889fe6060f1SDimitry Andric     else
890fe6060f1SDimitry Andric       llvm_unreachable("handling for other EHPads not implemented yet");
891fe6060f1SDimitry Andric 
892fe6060f1SDimitry Andric     auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
893fe6060f1SDimitry Andric     CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
894fe6060f1SDimitry Andric   }
895fe6060f1SDimitry Andric 
896fe6060f1SDimitry Andric   auto *DT = Options.DT;
897fe6060f1SDimitry Andric   auto *MSSAU = Options.MSSAU;
898fe6060f1SDimitry Andric   if (!DT && !LI)
899fe6060f1SDimitry Andric     return NewBB;
900fe6060f1SDimitry Andric 
901fe6060f1SDimitry Andric   if (DT) {
902fe6060f1SDimitry Andric     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
903fe6060f1SDimitry Andric     SmallVector<DominatorTree::UpdateType, 3> Updates;
904fe6060f1SDimitry Andric 
905fe6060f1SDimitry Andric     Updates.push_back({DominatorTree::Insert, BB, NewBB});
906fe6060f1SDimitry Andric     Updates.push_back({DominatorTree::Insert, NewBB, Succ});
907fe6060f1SDimitry Andric     Updates.push_back({DominatorTree::Delete, BB, Succ});
908fe6060f1SDimitry Andric 
909fe6060f1SDimitry Andric     DTU.applyUpdates(Updates);
910fe6060f1SDimitry Andric     DTU.flush();
911fe6060f1SDimitry Andric 
912fe6060f1SDimitry Andric     if (MSSAU) {
913fe6060f1SDimitry Andric       MSSAU->applyUpdates(Updates, *DT);
914fe6060f1SDimitry Andric       if (VerifyMemorySSA)
915fe6060f1SDimitry Andric         MSSAU->getMemorySSA()->verifyMemorySSA();
916fe6060f1SDimitry Andric     }
917fe6060f1SDimitry Andric   }
918fe6060f1SDimitry Andric 
919fe6060f1SDimitry Andric   if (LI) {
920fe6060f1SDimitry Andric     if (Loop *BBLoop = LI->getLoopFor(BB)) {
921fe6060f1SDimitry Andric       // If one or the other blocks were not in a loop, the new block is not
922fe6060f1SDimitry Andric       // either, and thus LI doesn't need to be updated.
923fe6060f1SDimitry Andric       if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
924fe6060f1SDimitry Andric         if (BBLoop == SuccLoop) {
925fe6060f1SDimitry Andric           // Both in the same loop, the NewBB joins loop.
926fe6060f1SDimitry Andric           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
927fe6060f1SDimitry Andric         } else if (BBLoop->contains(SuccLoop)) {
928fe6060f1SDimitry Andric           // Edge from an outer loop to an inner loop.  Add to the outer loop.
929fe6060f1SDimitry Andric           BBLoop->addBasicBlockToLoop(NewBB, *LI);
930fe6060f1SDimitry Andric         } else if (SuccLoop->contains(BBLoop)) {
931fe6060f1SDimitry Andric           // Edge from an inner loop to an outer loop.  Add to the outer loop.
932fe6060f1SDimitry Andric           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
933fe6060f1SDimitry Andric         } else {
934fe6060f1SDimitry Andric           // Edge from two loops with no containment relation.  Because these
935fe6060f1SDimitry Andric           // are natural loops, we know that the destination block must be the
936fe6060f1SDimitry Andric           // header of its loop (adding a branch into a loop elsewhere would
937fe6060f1SDimitry Andric           // create an irreducible loop).
938fe6060f1SDimitry Andric           assert(SuccLoop->getHeader() == Succ &&
939fe6060f1SDimitry Andric                  "Should not create irreducible loops!");
940fe6060f1SDimitry Andric           if (Loop *P = SuccLoop->getParentLoop())
941fe6060f1SDimitry Andric             P->addBasicBlockToLoop(NewBB, *LI);
942fe6060f1SDimitry Andric         }
943fe6060f1SDimitry Andric       }
944fe6060f1SDimitry Andric 
945fe6060f1SDimitry Andric       // If BB is in a loop and Succ is outside of that loop, we may need to
946fe6060f1SDimitry Andric       // update LoopSimplify form and LCSSA form.
947fe6060f1SDimitry Andric       if (!BBLoop->contains(Succ)) {
948fe6060f1SDimitry Andric         assert(!BBLoop->contains(NewBB) &&
949fe6060f1SDimitry Andric                "Split point for loop exit is contained in loop!");
950fe6060f1SDimitry Andric 
951fe6060f1SDimitry Andric         // Update LCSSA form in the newly created exit block.
952fe6060f1SDimitry Andric         if (Options.PreserveLCSSA) {
953fe6060f1SDimitry Andric           createPHIsForSplitLoopExit(BB, NewBB, Succ);
954fe6060f1SDimitry Andric         }
955fe6060f1SDimitry Andric 
956fe6060f1SDimitry Andric         if (!LoopPreds.empty()) {
957fe6060f1SDimitry Andric           BasicBlock *NewExitBB = SplitBlockPredecessors(
958fe6060f1SDimitry Andric               Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
959fe6060f1SDimitry Andric           if (Options.PreserveLCSSA)
960fe6060f1SDimitry Andric             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
961fe6060f1SDimitry Andric         }
962fe6060f1SDimitry Andric       }
963fe6060f1SDimitry Andric     }
964fe6060f1SDimitry Andric   }
965fe6060f1SDimitry Andric 
966fe6060f1SDimitry Andric   return NewBB;
967fe6060f1SDimitry Andric }
968fe6060f1SDimitry Andric 
createPHIsForSplitLoopExit(ArrayRef<BasicBlock * > Preds,BasicBlock * SplitBB,BasicBlock * DestBB)969fe6060f1SDimitry Andric void llvm::createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
970fe6060f1SDimitry Andric                                       BasicBlock *SplitBB, BasicBlock *DestBB) {
971fe6060f1SDimitry Andric   // SplitBB shouldn't have anything non-trivial in it yet.
972fe6060f1SDimitry Andric   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
973fe6060f1SDimitry Andric           SplitBB->isLandingPad()) &&
974fe6060f1SDimitry Andric          "SplitBB has non-PHI nodes!");
975fe6060f1SDimitry Andric 
976fe6060f1SDimitry Andric   // For each PHI in the destination block.
977fe6060f1SDimitry Andric   for (PHINode &PN : DestBB->phis()) {
978fe6060f1SDimitry Andric     int Idx = PN.getBasicBlockIndex(SplitBB);
979fe6060f1SDimitry Andric     assert(Idx >= 0 && "Invalid Block Index");
980fe6060f1SDimitry Andric     Value *V = PN.getIncomingValue(Idx);
981fe6060f1SDimitry Andric 
982fe6060f1SDimitry Andric     // If the input is a PHI which already satisfies LCSSA, don't create
983fe6060f1SDimitry Andric     // a new one.
984fe6060f1SDimitry Andric     if (const PHINode *VP = dyn_cast<PHINode>(V))
985fe6060f1SDimitry Andric       if (VP->getParent() == SplitBB)
986fe6060f1SDimitry Andric         continue;
987fe6060f1SDimitry Andric 
988fe6060f1SDimitry Andric     // Otherwise a new PHI is needed. Create one and populate it.
989c9157d92SDimitry Andric     PHINode *NewPN = PHINode::Create(PN.getType(), Preds.size(), "split");
990c9157d92SDimitry Andric     BasicBlock::iterator InsertPos =
991c9157d92SDimitry Andric         SplitBB->isLandingPad() ? SplitBB->begin()
992c9157d92SDimitry Andric                                 : SplitBB->getTerminator()->getIterator();
993c9157d92SDimitry Andric     NewPN->insertBefore(InsertPos);
994fe6060f1SDimitry Andric     for (BasicBlock *BB : Preds)
995fe6060f1SDimitry Andric       NewPN->addIncoming(V, BB);
996fe6060f1SDimitry Andric 
997fe6060f1SDimitry Andric     // Update the original PHI.
998fe6060f1SDimitry Andric     PN.setIncomingValue(Idx, NewPN);
999fe6060f1SDimitry Andric   }
1000fe6060f1SDimitry Andric }
1001fe6060f1SDimitry Andric 
10020b57cec5SDimitry Andric unsigned
SplitAllCriticalEdges(Function & F,const CriticalEdgeSplittingOptions & Options)10030b57cec5SDimitry Andric llvm::SplitAllCriticalEdges(Function &F,
10040b57cec5SDimitry Andric                             const CriticalEdgeSplittingOptions &Options) {
10050b57cec5SDimitry Andric   unsigned NumBroken = 0;
10060b57cec5SDimitry Andric   for (BasicBlock &BB : F) {
10070b57cec5SDimitry Andric     Instruction *TI = BB.getTerminator();
1008753f127fSDimitry Andric     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
10090b57cec5SDimitry Andric       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10100b57cec5SDimitry Andric         if (SplitCriticalEdge(TI, i, Options))
10110b57cec5SDimitry Andric           ++NumBroken;
10120b57cec5SDimitry Andric   }
10130b57cec5SDimitry Andric   return NumBroken;
10140b57cec5SDimitry Andric }
10150b57cec5SDimitry Andric 
SplitBlockImpl(BasicBlock * Old,BasicBlock::iterator SplitPt,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)1016c9157d92SDimitry Andric static BasicBlock *SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt,
1017e8d8bef9SDimitry Andric                                   DomTreeUpdater *DTU, DominatorTree *DT,
1018e8d8bef9SDimitry Andric                                   LoopInfo *LI, MemorySSAUpdater *MSSAU,
1019e8d8bef9SDimitry Andric                                   const Twine &BBName, bool Before) {
1020e8d8bef9SDimitry Andric   if (Before) {
1021e8d8bef9SDimitry Andric     DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1022e8d8bef9SDimitry Andric     return splitBlockBefore(Old, SplitPt,
1023e8d8bef9SDimitry Andric                             DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
1024e8d8bef9SDimitry Andric                             BBName);
1025e8d8bef9SDimitry Andric   }
1026c9157d92SDimitry Andric   BasicBlock::iterator SplitIt = SplitPt;
1027fe6060f1SDimitry Andric   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
10280b57cec5SDimitry Andric     ++SplitIt;
1029fe6060f1SDimitry Andric     assert(SplitIt != SplitPt->getParent()->end());
1030fe6060f1SDimitry Andric   }
10318bcb0991SDimitry Andric   std::string Name = BBName.str();
10328bcb0991SDimitry Andric   BasicBlock *New = Old->splitBasicBlock(
10338bcb0991SDimitry Andric       SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric   // The new block lives in whichever loop the old one did. This preserves
10360b57cec5SDimitry Andric   // LCSSA as well, because we force the split point to be after any PHI nodes.
10370b57cec5SDimitry Andric   if (LI)
10380b57cec5SDimitry Andric     if (Loop *L = LI->getLoopFor(Old))
10390b57cec5SDimitry Andric       L->addBasicBlockToLoop(New, *LI);
10400b57cec5SDimitry Andric 
1041e8d8bef9SDimitry Andric   if (DTU) {
1042e8d8bef9SDimitry Andric     SmallVector<DominatorTree::UpdateType, 8> Updates;
1043e8d8bef9SDimitry Andric     // Old dominates New. New node dominates all other nodes dominated by Old.
10444824e7fdSDimitry Andric     SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
1045e8d8bef9SDimitry Andric     Updates.push_back({DominatorTree::Insert, Old, New});
10464824e7fdSDimitry Andric     Updates.reserve(Updates.size() + 2 * succ_size(New));
10474824e7fdSDimitry Andric     for (BasicBlock *SuccessorOfOld : successors(New))
10484824e7fdSDimitry Andric       if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
10494824e7fdSDimitry Andric         Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
10504824e7fdSDimitry Andric         Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
1051e8d8bef9SDimitry Andric       }
1052e8d8bef9SDimitry Andric 
1053e8d8bef9SDimitry Andric     DTU->applyUpdates(Updates);
1054e8d8bef9SDimitry Andric   } else if (DT)
10550b57cec5SDimitry Andric     // Old dominates New. New node dominates all other nodes dominated by Old.
10560b57cec5SDimitry Andric     if (DomTreeNode *OldNode = DT->getNode(Old)) {
10570b57cec5SDimitry Andric       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric       DomTreeNode *NewNode = DT->addNewBlock(New, Old);
10600b57cec5SDimitry Andric       for (DomTreeNode *I : Children)
10610b57cec5SDimitry Andric         DT->changeImmediateDominator(I, NewNode);
10620b57cec5SDimitry Andric     }
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   // Move MemoryAccesses still tracked in Old, but part of New now.
10650b57cec5SDimitry Andric   // Update accesses in successor blocks accordingly.
10660b57cec5SDimitry Andric   if (MSSAU)
10670b57cec5SDimitry Andric     MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric   return New;
10700b57cec5SDimitry Andric }
10710b57cec5SDimitry Andric 
SplitBlock(BasicBlock * Old,BasicBlock::iterator SplitPt,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)1072c9157d92SDimitry Andric BasicBlock *llvm::SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
1073e8d8bef9SDimitry Andric                              DominatorTree *DT, LoopInfo *LI,
1074e8d8bef9SDimitry Andric                              MemorySSAUpdater *MSSAU, const Twine &BBName,
1075e8d8bef9SDimitry Andric                              bool Before) {
1076e8d8bef9SDimitry Andric   return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
1077e8d8bef9SDimitry Andric                         Before);
1078e8d8bef9SDimitry Andric }
SplitBlock(BasicBlock * Old,BasicBlock::iterator SplitPt,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)1079c9157d92SDimitry Andric BasicBlock *llvm::SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
1080e8d8bef9SDimitry Andric                              DomTreeUpdater *DTU, LoopInfo *LI,
1081e8d8bef9SDimitry Andric                              MemorySSAUpdater *MSSAU, const Twine &BBName,
1082e8d8bef9SDimitry Andric                              bool Before) {
1083e8d8bef9SDimitry Andric   return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
1084e8d8bef9SDimitry Andric                         Before);
1085e8d8bef9SDimitry Andric }
1086e8d8bef9SDimitry Andric 
splitBlockBefore(BasicBlock * Old,BasicBlock::iterator SplitPt,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName)1087c9157d92SDimitry Andric BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt,
1088e8d8bef9SDimitry Andric                                    DomTreeUpdater *DTU, LoopInfo *LI,
1089e8d8bef9SDimitry Andric                                    MemorySSAUpdater *MSSAU,
1090e8d8bef9SDimitry Andric                                    const Twine &BBName) {
1091e8d8bef9SDimitry Andric 
1092c9157d92SDimitry Andric   BasicBlock::iterator SplitIt = SplitPt;
1093e8d8bef9SDimitry Andric   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
1094e8d8bef9SDimitry Andric     ++SplitIt;
1095e8d8bef9SDimitry Andric   std::string Name = BBName.str();
1096e8d8bef9SDimitry Andric   BasicBlock *New = Old->splitBasicBlock(
1097e8d8bef9SDimitry Andric       SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
1098e8d8bef9SDimitry Andric       /* Before=*/true);
1099e8d8bef9SDimitry Andric 
1100e8d8bef9SDimitry Andric   // The new block lives in whichever loop the old one did. This preserves
1101e8d8bef9SDimitry Andric   // LCSSA as well, because we force the split point to be after any PHI nodes.
1102e8d8bef9SDimitry Andric   if (LI)
1103e8d8bef9SDimitry Andric     if (Loop *L = LI->getLoopFor(Old))
1104e8d8bef9SDimitry Andric       L->addBasicBlockToLoop(New, *LI);
1105e8d8bef9SDimitry Andric 
1106e8d8bef9SDimitry Andric   if (DTU) {
1107e8d8bef9SDimitry Andric     SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1108e8d8bef9SDimitry Andric     // New dominates Old. The predecessor nodes of the Old node dominate
1109e8d8bef9SDimitry Andric     // New node.
11104824e7fdSDimitry Andric     SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
1111e8d8bef9SDimitry Andric     DTUpdates.push_back({DominatorTree::Insert, New, Old});
11124824e7fdSDimitry Andric     DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
11134824e7fdSDimitry Andric     for (BasicBlock *PredecessorOfOld : predecessors(New))
11144824e7fdSDimitry Andric       if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
11154824e7fdSDimitry Andric         DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
11164824e7fdSDimitry Andric         DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
1117e8d8bef9SDimitry Andric       }
1118e8d8bef9SDimitry Andric 
1119e8d8bef9SDimitry Andric     DTU->applyUpdates(DTUpdates);
1120e8d8bef9SDimitry Andric 
1121e8d8bef9SDimitry Andric     // Move MemoryAccesses still tracked in Old, but part of New now.
1122e8d8bef9SDimitry Andric     // Update accesses in successor blocks accordingly.
1123e8d8bef9SDimitry Andric     if (MSSAU) {
1124e8d8bef9SDimitry Andric       MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
1125e8d8bef9SDimitry Andric       if (VerifyMemorySSA)
1126e8d8bef9SDimitry Andric         MSSAU->getMemorySSA()->verifyMemorySSA();
1127e8d8bef9SDimitry Andric     }
1128e8d8bef9SDimitry Andric   }
1129e8d8bef9SDimitry Andric   return New;
1130e8d8bef9SDimitry Andric }
1131e8d8bef9SDimitry Andric 
11320b57cec5SDimitry Andric /// 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)11330b57cec5SDimitry Andric static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
11340b57cec5SDimitry Andric                                       ArrayRef<BasicBlock *> Preds,
1135e8d8bef9SDimitry Andric                                       DomTreeUpdater *DTU, DominatorTree *DT,
1136e8d8bef9SDimitry Andric                                       LoopInfo *LI, MemorySSAUpdater *MSSAU,
11370b57cec5SDimitry Andric                                       bool PreserveLCSSA, bool &HasLoopExit) {
11380b57cec5SDimitry Andric   // Update dominator tree if available.
1139e8d8bef9SDimitry Andric   if (DTU) {
1140e8d8bef9SDimitry Andric     // Recalculation of DomTree is needed when updating a forward DomTree and
1141e8d8bef9SDimitry Andric     // the Entry BB is replaced.
1142fe6060f1SDimitry Andric     if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
1143e8d8bef9SDimitry Andric       // The entry block was removed and there is no external interface for
1144e8d8bef9SDimitry Andric       // the dominator tree to be notified of this change. In this corner-case
1145e8d8bef9SDimitry Andric       // we recalculate the entire tree.
1146e8d8bef9SDimitry Andric       DTU->recalculate(*NewBB->getParent());
1147e8d8bef9SDimitry Andric     } else {
1148e8d8bef9SDimitry Andric       // Split block expects NewBB to have a non-empty set of predecessors.
1149e8d8bef9SDimitry Andric       SmallVector<DominatorTree::UpdateType, 8> Updates;
11504824e7fdSDimitry Andric       SmallPtrSet<BasicBlock *, 8> UniquePreds;
1151e8d8bef9SDimitry Andric       Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
11524824e7fdSDimitry Andric       Updates.reserve(Updates.size() + 2 * Preds.size());
11534824e7fdSDimitry Andric       for (auto *Pred : Preds)
11544824e7fdSDimitry Andric         if (UniquePreds.insert(Pred).second) {
11554824e7fdSDimitry Andric           Updates.push_back({DominatorTree::Insert, Pred, NewBB});
11564824e7fdSDimitry Andric           Updates.push_back({DominatorTree::Delete, Pred, OldBB});
1157e8d8bef9SDimitry Andric         }
1158e8d8bef9SDimitry Andric       DTU->applyUpdates(Updates);
1159e8d8bef9SDimitry Andric     }
1160e8d8bef9SDimitry Andric   } else if (DT) {
11610b57cec5SDimitry Andric     if (OldBB == DT->getRootNode()->getBlock()) {
1162fe6060f1SDimitry Andric       assert(NewBB->isEntryBlock());
11630b57cec5SDimitry Andric       DT->setNewRoot(NewBB);
11640b57cec5SDimitry Andric     } else {
11650b57cec5SDimitry Andric       // Split block expects NewBB to have a non-empty set of predecessors.
11660b57cec5SDimitry Andric       DT->splitBlock(NewBB);
11670b57cec5SDimitry Andric     }
11680b57cec5SDimitry Andric   }
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   // Update MemoryPhis after split if MemorySSA is available
11710b57cec5SDimitry Andric   if (MSSAU)
11720b57cec5SDimitry Andric     MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric   // The rest of the logic is only relevant for updating the loop structures.
11750b57cec5SDimitry Andric   if (!LI)
11760b57cec5SDimitry Andric     return;
11770b57cec5SDimitry Andric 
1178e8d8bef9SDimitry Andric   if (DTU && DTU->hasDomTree())
1179e8d8bef9SDimitry Andric     DT = &DTU->getDomTree();
11800b57cec5SDimitry Andric   assert(DT && "DT should be available to update LoopInfo!");
11810b57cec5SDimitry Andric   Loop *L = LI->getLoopFor(OldBB);
11820b57cec5SDimitry Andric 
11830b57cec5SDimitry Andric   // If we need to preserve loop analyses, collect some information about how
11840b57cec5SDimitry Andric   // this split will affect loops.
11850b57cec5SDimitry Andric   bool IsLoopEntry = !!L;
11860b57cec5SDimitry Andric   bool SplitMakesNewLoopHeader = false;
11870b57cec5SDimitry Andric   for (BasicBlock *Pred : Preds) {
11880b57cec5SDimitry Andric     // Preds that are not reachable from entry should not be used to identify if
11890b57cec5SDimitry Andric     // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
11900b57cec5SDimitry Andric     // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
11910b57cec5SDimitry Andric     // as true and make the NewBB the header of some loop. This breaks LI.
11920b57cec5SDimitry Andric     if (!DT->isReachableFromEntry(Pred))
11930b57cec5SDimitry Andric       continue;
11940b57cec5SDimitry Andric     // If we need to preserve LCSSA, determine if any of the preds is a loop
11950b57cec5SDimitry Andric     // exit.
11960b57cec5SDimitry Andric     if (PreserveLCSSA)
11970b57cec5SDimitry Andric       if (Loop *PL = LI->getLoopFor(Pred))
11980b57cec5SDimitry Andric         if (!PL->contains(OldBB))
11990b57cec5SDimitry Andric           HasLoopExit = true;
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric     // If we need to preserve LoopInfo, note whether any of the preds crosses
12020b57cec5SDimitry Andric     // an interesting loop boundary.
12030b57cec5SDimitry Andric     if (!L)
12040b57cec5SDimitry Andric       continue;
12050b57cec5SDimitry Andric     if (L->contains(Pred))
12060b57cec5SDimitry Andric       IsLoopEntry = false;
12070b57cec5SDimitry Andric     else
12080b57cec5SDimitry Andric       SplitMakesNewLoopHeader = true;
12090b57cec5SDimitry Andric   }
12100b57cec5SDimitry Andric 
12110b57cec5SDimitry Andric   // Unless we have a loop for OldBB, nothing else to do here.
12120b57cec5SDimitry Andric   if (!L)
12130b57cec5SDimitry Andric     return;
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric   if (IsLoopEntry) {
12160b57cec5SDimitry Andric     // Add the new block to the nearest enclosing loop (and not an adjacent
12170b57cec5SDimitry Andric     // loop). To find this, examine each of the predecessors and determine which
12180b57cec5SDimitry Andric     // loops enclose them, and select the most-nested loop which contains the
12190b57cec5SDimitry Andric     // loop containing the block being split.
12200b57cec5SDimitry Andric     Loop *InnermostPredLoop = nullptr;
12210b57cec5SDimitry Andric     for (BasicBlock *Pred : Preds) {
12220b57cec5SDimitry Andric       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
12230b57cec5SDimitry Andric         // Seek a loop which actually contains the block being split (to avoid
12240b57cec5SDimitry Andric         // adjacent loops).
12250b57cec5SDimitry Andric         while (PredLoop && !PredLoop->contains(OldBB))
12260b57cec5SDimitry Andric           PredLoop = PredLoop->getParentLoop();
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric         // Select the most-nested of these loops which contains the block.
12290b57cec5SDimitry Andric         if (PredLoop && PredLoop->contains(OldBB) &&
12300b57cec5SDimitry Andric             (!InnermostPredLoop ||
12310b57cec5SDimitry Andric              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
12320b57cec5SDimitry Andric           InnermostPredLoop = PredLoop;
12330b57cec5SDimitry Andric       }
12340b57cec5SDimitry Andric     }
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric     if (InnermostPredLoop)
12370b57cec5SDimitry Andric       InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
12380b57cec5SDimitry Andric   } else {
12390b57cec5SDimitry Andric     L->addBasicBlockToLoop(NewBB, *LI);
12400b57cec5SDimitry Andric     if (SplitMakesNewLoopHeader)
12410b57cec5SDimitry Andric       L->moveToHeader(NewBB);
12420b57cec5SDimitry Andric   }
12430b57cec5SDimitry Andric }
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
12460b57cec5SDimitry Andric /// This also updates AliasAnalysis, if available.
UpdatePHINodes(BasicBlock * OrigBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,BranchInst * BI,bool HasLoopExit)12470b57cec5SDimitry Andric static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
12480b57cec5SDimitry Andric                            ArrayRef<BasicBlock *> Preds, BranchInst *BI,
12490b57cec5SDimitry Andric                            bool HasLoopExit) {
12500b57cec5SDimitry Andric   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
12510b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
12520b57cec5SDimitry Andric   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
12530b57cec5SDimitry Andric     PHINode *PN = cast<PHINode>(I++);
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric     // Check to see if all of the values coming in are the same.  If so, we
12560b57cec5SDimitry Andric     // don't need to create a new PHI node, unless it's needed for LCSSA.
12570b57cec5SDimitry Andric     Value *InVal = nullptr;
12580b57cec5SDimitry Andric     if (!HasLoopExit) {
12590b57cec5SDimitry Andric       InVal = PN->getIncomingValueForBlock(Preds[0]);
12600b57cec5SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
12610b57cec5SDimitry Andric         if (!PredSet.count(PN->getIncomingBlock(i)))
12620b57cec5SDimitry Andric           continue;
12630b57cec5SDimitry Andric         if (!InVal)
12640b57cec5SDimitry Andric           InVal = PN->getIncomingValue(i);
12650b57cec5SDimitry Andric         else if (InVal != PN->getIncomingValue(i)) {
12660b57cec5SDimitry Andric           InVal = nullptr;
12670b57cec5SDimitry Andric           break;
12680b57cec5SDimitry Andric         }
12690b57cec5SDimitry Andric       }
12700b57cec5SDimitry Andric     }
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric     if (InVal) {
12730b57cec5SDimitry Andric       // If all incoming values for the new PHI would be the same, just don't
12740b57cec5SDimitry Andric       // make a new PHI.  Instead, just remove the incoming values from the old
12750b57cec5SDimitry Andric       // PHI.
1276c9157d92SDimitry Andric       PN->removeIncomingValueIf(
1277c9157d92SDimitry Andric           [&](unsigned Idx) {
1278c9157d92SDimitry Andric             return PredSet.contains(PN->getIncomingBlock(Idx));
1279c9157d92SDimitry Andric           },
1280c9157d92SDimitry Andric           /* DeletePHIIfEmpty */ false);
12810b57cec5SDimitry Andric 
12820b57cec5SDimitry Andric       // Add an incoming value to the PHI node in the loop for the preheader
12830b57cec5SDimitry Andric       // edge.
12840b57cec5SDimitry Andric       PN->addIncoming(InVal, NewBB);
12850b57cec5SDimitry Andric       continue;
12860b57cec5SDimitry Andric     }
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric     // If the values coming into the block are not the same, we need a new
12890b57cec5SDimitry Andric     // PHI.
12900b57cec5SDimitry Andric     // Create the new PHI node, insert it into NewBB at the end of the block
12910b57cec5SDimitry Andric     PHINode *NewPHI =
12920b57cec5SDimitry Andric         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric     // NOTE! This loop walks backwards for a reason! First off, this minimizes
12950b57cec5SDimitry Andric     // the cost of removal if we end up removing a large number of values, and
12960b57cec5SDimitry Andric     // second off, this ensures that the indices for the incoming values aren't
12970b57cec5SDimitry Andric     // invalidated when we remove one.
12980b57cec5SDimitry Andric     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
12990b57cec5SDimitry Andric       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
13000b57cec5SDimitry Andric       if (PredSet.count(IncomingBB)) {
13010b57cec5SDimitry Andric         Value *V = PN->removeIncomingValue(i, false);
13020b57cec5SDimitry Andric         NewPHI->addIncoming(V, IncomingBB);
13030b57cec5SDimitry Andric       }
13040b57cec5SDimitry Andric     }
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric     PN->addIncoming(NewPHI, NewBB);
13070b57cec5SDimitry Andric   }
13080b57cec5SDimitry Andric }
13090b57cec5SDimitry Andric 
1310e8d8bef9SDimitry Andric static void SplitLandingPadPredecessorsImpl(
1311e8d8bef9SDimitry Andric     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1312e8d8bef9SDimitry Andric     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1313e8d8bef9SDimitry Andric     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1314e8d8bef9SDimitry Andric     MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1315e8d8bef9SDimitry Andric 
1316e8d8bef9SDimitry Andric static BasicBlock *
SplitBlockPredecessorsImpl(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1317e8d8bef9SDimitry Andric SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
1318e8d8bef9SDimitry Andric                            const char *Suffix, DomTreeUpdater *DTU,
1319e8d8bef9SDimitry Andric                            DominatorTree *DT, LoopInfo *LI,
1320e8d8bef9SDimitry Andric                            MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
13210b57cec5SDimitry Andric   // Do not attempt to split that which cannot be split.
13220b57cec5SDimitry Andric   if (!BB->canSplitPredecessors())
13230b57cec5SDimitry Andric     return nullptr;
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   // For the landingpads we need to act a bit differently.
13260b57cec5SDimitry Andric   // Delegate this work to the SplitLandingPadPredecessors.
13270b57cec5SDimitry Andric   if (BB->isLandingPad()) {
13280b57cec5SDimitry Andric     SmallVector<BasicBlock*, 2> NewBBs;
13290b57cec5SDimitry Andric     std::string NewName = std::string(Suffix) + ".split-lp";
13300b57cec5SDimitry Andric 
1331e8d8bef9SDimitry Andric     SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1332e8d8bef9SDimitry Andric                                     DTU, DT, LI, MSSAU, PreserveLCSSA);
13330b57cec5SDimitry Andric     return NewBBs[0];
13340b57cec5SDimitry Andric   }
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric   // Create new basic block, insert right before the original block.
13370b57cec5SDimitry Andric   BasicBlock *NewBB = BasicBlock::Create(
13380b57cec5SDimitry Andric       BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric   // The new block unconditionally branches to the old block.
13410b57cec5SDimitry Andric   BranchInst *BI = BranchInst::Create(BB, NewBB);
1342e8d8bef9SDimitry Andric 
1343e8d8bef9SDimitry Andric   Loop *L = nullptr;
1344e8d8bef9SDimitry Andric   BasicBlock *OldLatch = nullptr;
13450b57cec5SDimitry Andric   // Splitting the predecessors of a loop header creates a preheader block.
1346e8d8bef9SDimitry Andric   if (LI && LI->isLoopHeader(BB)) {
1347e8d8bef9SDimitry Andric     L = LI->getLoopFor(BB);
13480b57cec5SDimitry Andric     // Using the loop start line number prevents debuggers stepping into the
13490b57cec5SDimitry Andric     // loop body for this instruction.
1350e8d8bef9SDimitry Andric     BI->setDebugLoc(L->getStartLoc());
1351e8d8bef9SDimitry Andric 
1352e8d8bef9SDimitry Andric     // If BB is the header of the Loop, it is possible that the loop is
1353e8d8bef9SDimitry Andric     // modified, such that the current latch does not remain the latch of the
1354e8d8bef9SDimitry Andric     // loop. If that is the case, the loop metadata from the current latch needs
1355e8d8bef9SDimitry Andric     // to be applied to the new latch.
1356e8d8bef9SDimitry Andric     OldLatch = L->getLoopLatch();
1357e8d8bef9SDimitry Andric   } else
13580b57cec5SDimitry Andric     BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric   // Move the edges from Preds to point to NewBB instead of BB.
1361bdd1243dSDimitry Andric   for (BasicBlock *Pred : Preds) {
13620b57cec5SDimitry Andric     // This is slightly more strict than necessary; the minimum requirement
13630b57cec5SDimitry Andric     // is that there be no more than one indirectbr branching to BB. And
13640b57cec5SDimitry Andric     // all BlockAddress uses would need to be updated.
1365bdd1243dSDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
13660b57cec5SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
1367bdd1243dSDimitry Andric     Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
13680b57cec5SDimitry Andric   }
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
13710b57cec5SDimitry Andric   // node becomes an incoming value for BB's phi node.  However, if the Preds
13720b57cec5SDimitry Andric   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
13730b57cec5SDimitry Andric   // account for the newly created predecessor.
13740b57cec5SDimitry Andric   if (Preds.empty()) {
13750b57cec5SDimitry Andric     // Insert dummy values as the incoming value.
13760b57cec5SDimitry Andric     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
1377fcaf7f86SDimitry Andric       cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
13780b57cec5SDimitry Andric   }
13790b57cec5SDimitry Andric 
13800b57cec5SDimitry Andric   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
13810b57cec5SDimitry Andric   bool HasLoopExit = false;
1382e8d8bef9SDimitry Andric   UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
13830b57cec5SDimitry Andric                             HasLoopExit);
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric   if (!Preds.empty()) {
13860b57cec5SDimitry Andric     // Update the PHI nodes in BB with the values coming from NewBB.
13870b57cec5SDimitry Andric     UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
13880b57cec5SDimitry Andric   }
13890b57cec5SDimitry Andric 
1390e8d8bef9SDimitry Andric   if (OldLatch) {
1391e8d8bef9SDimitry Andric     BasicBlock *NewLatch = L->getLoopLatch();
1392e8d8bef9SDimitry Andric     if (NewLatch != OldLatch) {
1393e8d8bef9SDimitry Andric       MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop");
1394e8d8bef9SDimitry Andric       NewLatch->getTerminator()->setMetadata("llvm.loop", MD);
139581ad6265SDimitry Andric       // It's still possible that OldLatch is the latch of another inner loop,
139681ad6265SDimitry Andric       // in which case we do not remove the metadata.
139781ad6265SDimitry Andric       Loop *IL = LI->getLoopFor(OldLatch);
139881ad6265SDimitry Andric       if (IL && IL->getLoopLatch() != OldLatch)
1399e8d8bef9SDimitry Andric         OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr);
1400e8d8bef9SDimitry Andric     }
1401e8d8bef9SDimitry Andric   }
1402e8d8bef9SDimitry Andric 
14030b57cec5SDimitry Andric   return NewBB;
14040b57cec5SDimitry Andric }
14050b57cec5SDimitry Andric 
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1406e8d8bef9SDimitry Andric BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
14070b57cec5SDimitry Andric                                          ArrayRef<BasicBlock *> Preds,
1408e8d8bef9SDimitry Andric                                          const char *Suffix, DominatorTree *DT,
1409e8d8bef9SDimitry Andric                                          LoopInfo *LI, MemorySSAUpdater *MSSAU,
1410e8d8bef9SDimitry Andric                                          bool PreserveLCSSA) {
1411e8d8bef9SDimitry Andric   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1412e8d8bef9SDimitry Andric                                     MSSAU, PreserveLCSSA);
1413e8d8bef9SDimitry Andric }
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1414e8d8bef9SDimitry Andric BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
1415e8d8bef9SDimitry Andric                                          ArrayRef<BasicBlock *> Preds,
1416e8d8bef9SDimitry Andric                                          const char *Suffix,
1417e8d8bef9SDimitry Andric                                          DomTreeUpdater *DTU, LoopInfo *LI,
14180b57cec5SDimitry Andric                                          MemorySSAUpdater *MSSAU,
14190b57cec5SDimitry Andric                                          bool PreserveLCSSA) {
1420e8d8bef9SDimitry Andric   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1421e8d8bef9SDimitry Andric                                     /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1422e8d8bef9SDimitry Andric }
1423e8d8bef9SDimitry Andric 
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)1424e8d8bef9SDimitry Andric static void SplitLandingPadPredecessorsImpl(
1425e8d8bef9SDimitry Andric     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1426e8d8bef9SDimitry Andric     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1427e8d8bef9SDimitry Andric     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1428e8d8bef9SDimitry Andric     MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
14290b57cec5SDimitry Andric   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
14320b57cec5SDimitry Andric   // it right before the original block.
14330b57cec5SDimitry Andric   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
14340b57cec5SDimitry Andric                                           OrigBB->getName() + Suffix1,
14350b57cec5SDimitry Andric                                           OrigBB->getParent(), OrigBB);
14360b57cec5SDimitry Andric   NewBBs.push_back(NewBB1);
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   // The new block unconditionally branches to the old block.
14390b57cec5SDimitry Andric   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
14400b57cec5SDimitry Andric   BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1443bdd1243dSDimitry Andric   for (BasicBlock *Pred : Preds) {
14440b57cec5SDimitry Andric     // This is slightly more strict than necessary; the minimum requirement
14450b57cec5SDimitry Andric     // is that there be no more than one indirectbr branching to BB. And
14460b57cec5SDimitry Andric     // all BlockAddress uses would need to be updated.
1447bdd1243dSDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
14480b57cec5SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
1449bdd1243dSDimitry Andric     Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
14500b57cec5SDimitry Andric   }
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric   bool HasLoopExit = false;
1453e8d8bef9SDimitry Andric   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1454e8d8bef9SDimitry Andric                             PreserveLCSSA, HasLoopExit);
14550b57cec5SDimitry Andric 
14560b57cec5SDimitry Andric   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
14570b57cec5SDimitry Andric   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric   // Move the remaining edges from OrigBB to point to NewBB2.
14600b57cec5SDimitry Andric   SmallVector<BasicBlock*, 8> NewBB2Preds;
14610b57cec5SDimitry Andric   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
14620b57cec5SDimitry Andric        i != e; ) {
14630b57cec5SDimitry Andric     BasicBlock *Pred = *i++;
14640b57cec5SDimitry Andric     if (Pred == NewBB1) continue;
14650b57cec5SDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
14660b57cec5SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
14670b57cec5SDimitry Andric     NewBB2Preds.push_back(Pred);
14680b57cec5SDimitry Andric     e = pred_end(OrigBB);
14690b57cec5SDimitry Andric   }
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric   BasicBlock *NewBB2 = nullptr;
14720b57cec5SDimitry Andric   if (!NewBB2Preds.empty()) {
14730b57cec5SDimitry Andric     // Create another basic block for the rest of OrigBB's predecessors.
14740b57cec5SDimitry Andric     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
14750b57cec5SDimitry Andric                                 OrigBB->getName() + Suffix2,
14760b57cec5SDimitry Andric                                 OrigBB->getParent(), OrigBB);
14770b57cec5SDimitry Andric     NewBBs.push_back(NewBB2);
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric     // The new block unconditionally branches to the old block.
14800b57cec5SDimitry Andric     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
14810b57cec5SDimitry Andric     BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric     // Move the remaining edges from OrigBB to point to NewBB2.
14840b57cec5SDimitry Andric     for (BasicBlock *NewBB2Pred : NewBB2Preds)
14850b57cec5SDimitry Andric       NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
14880b57cec5SDimitry Andric     HasLoopExit = false;
1489e8d8bef9SDimitry Andric     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
14900b57cec5SDimitry Andric                               PreserveLCSSA, HasLoopExit);
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
14930b57cec5SDimitry Andric     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
14940b57cec5SDimitry Andric   }
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric   LandingPadInst *LPad = OrigBB->getLandingPadInst();
14970b57cec5SDimitry Andric   Instruction *Clone1 = LPad->clone();
14980b57cec5SDimitry Andric   Clone1->setName(Twine("lpad") + Suffix1);
1499bdd1243dSDimitry Andric   Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric   if (NewBB2) {
15020b57cec5SDimitry Andric     Instruction *Clone2 = LPad->clone();
15030b57cec5SDimitry Andric     Clone2->setName(Twine("lpad") + Suffix2);
1504bdd1243dSDimitry Andric     Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric     // Create a PHI node for the two cloned landingpad instructions only
15070b57cec5SDimitry Andric     // if the original landingpad instruction has some uses.
15080b57cec5SDimitry Andric     if (!LPad->use_empty()) {
15090b57cec5SDimitry Andric       assert(!LPad->getType()->isTokenTy() &&
15100b57cec5SDimitry Andric              "Split cannot be applied if LPad is token type. Otherwise an "
15110b57cec5SDimitry Andric              "invalid PHINode of token type would be created.");
15120b57cec5SDimitry Andric       PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
15130b57cec5SDimitry Andric       PN->addIncoming(Clone1, NewBB1);
15140b57cec5SDimitry Andric       PN->addIncoming(Clone2, NewBB2);
15150b57cec5SDimitry Andric       LPad->replaceAllUsesWith(PN);
15160b57cec5SDimitry Andric     }
15170b57cec5SDimitry Andric     LPad->eraseFromParent();
15180b57cec5SDimitry Andric   } else {
15190b57cec5SDimitry Andric     // There is no second clone. Just replace the landing pad with the first
15200b57cec5SDimitry Andric     // clone.
15210b57cec5SDimitry Andric     LPad->replaceAllUsesWith(Clone1);
15220b57cec5SDimitry Andric     LPad->eraseFromParent();
15230b57cec5SDimitry Andric   }
15240b57cec5SDimitry Andric }
15250b57cec5SDimitry Andric 
SplitLandingPadPredecessors(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1526e8d8bef9SDimitry Andric void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
1527e8d8bef9SDimitry Andric                                        ArrayRef<BasicBlock *> Preds,
1528e8d8bef9SDimitry Andric                                        const char *Suffix1, const char *Suffix2,
1529e8d8bef9SDimitry Andric                                        SmallVectorImpl<BasicBlock *> &NewBBs,
1530e8d8bef9SDimitry Andric                                        DomTreeUpdater *DTU, LoopInfo *LI,
1531e8d8bef9SDimitry Andric                                        MemorySSAUpdater *MSSAU,
1532e8d8bef9SDimitry Andric                                        bool PreserveLCSSA) {
1533e8d8bef9SDimitry Andric   return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1534e8d8bef9SDimitry Andric                                          NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1535e8d8bef9SDimitry Andric                                          PreserveLCSSA);
1536e8d8bef9SDimitry Andric }
1537e8d8bef9SDimitry Andric 
FoldReturnIntoUncondBranch(ReturnInst * RI,BasicBlock * BB,BasicBlock * Pred,DomTreeUpdater * DTU)15380b57cec5SDimitry Andric ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
15390b57cec5SDimitry Andric                                              BasicBlock *Pred,
15400b57cec5SDimitry Andric                                              DomTreeUpdater *DTU) {
15410b57cec5SDimitry Andric   Instruction *UncondBranch = Pred->getTerminator();
15420b57cec5SDimitry Andric   // Clone the return and add it to the end of the predecessor.
15430b57cec5SDimitry Andric   Instruction *NewRet = RI->clone();
1544bdd1243dSDimitry Andric   NewRet->insertInto(Pred, Pred->end());
15450b57cec5SDimitry Andric 
15460b57cec5SDimitry Andric   // If the return instruction returns a value, and if the value was a
15470b57cec5SDimitry Andric   // PHI node in "BB", propagate the right value into the return.
1548fe6060f1SDimitry Andric   for (Use &Op : NewRet->operands()) {
1549fe6060f1SDimitry Andric     Value *V = Op;
15500b57cec5SDimitry Andric     Instruction *NewBC = nullptr;
15510b57cec5SDimitry Andric     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
15520b57cec5SDimitry Andric       // Return value might be bitcasted. Clone and insert it before the
15530b57cec5SDimitry Andric       // return instruction.
15540b57cec5SDimitry Andric       V = BCI->getOperand(0);
15550b57cec5SDimitry Andric       NewBC = BCI->clone();
1556bdd1243dSDimitry Andric       NewBC->insertInto(Pred, NewRet->getIterator());
1557fe6060f1SDimitry Andric       Op = NewBC;
15580b57cec5SDimitry Andric     }
15595ffd83dbSDimitry Andric 
15605ffd83dbSDimitry Andric     Instruction *NewEV = nullptr;
15615ffd83dbSDimitry Andric     if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
15625ffd83dbSDimitry Andric       V = EVI->getOperand(0);
15635ffd83dbSDimitry Andric       NewEV = EVI->clone();
15645ffd83dbSDimitry Andric       if (NewBC) {
15655ffd83dbSDimitry Andric         NewBC->setOperand(0, NewEV);
1566bdd1243dSDimitry Andric         NewEV->insertInto(Pred, NewBC->getIterator());
15675ffd83dbSDimitry Andric       } else {
1568bdd1243dSDimitry Andric         NewEV->insertInto(Pred, NewRet->getIterator());
1569fe6060f1SDimitry Andric         Op = NewEV;
15705ffd83dbSDimitry Andric       }
15715ffd83dbSDimitry Andric     }
15725ffd83dbSDimitry Andric 
15730b57cec5SDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(V)) {
15740b57cec5SDimitry Andric       if (PN->getParent() == BB) {
15755ffd83dbSDimitry Andric         if (NewEV) {
15765ffd83dbSDimitry Andric           NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
15775ffd83dbSDimitry Andric         } else if (NewBC)
15780b57cec5SDimitry Andric           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
15790b57cec5SDimitry Andric         else
1580fe6060f1SDimitry Andric           Op = PN->getIncomingValueForBlock(Pred);
15810b57cec5SDimitry Andric       }
15820b57cec5SDimitry Andric     }
15830b57cec5SDimitry Andric   }
15840b57cec5SDimitry Andric 
15850b57cec5SDimitry Andric   // Update any PHI nodes in the returning block to realize that we no
15860b57cec5SDimitry Andric   // longer branch to them.
15870b57cec5SDimitry Andric   BB->removePredecessor(Pred);
15880b57cec5SDimitry Andric   UncondBranch->eraseFromParent();
15890b57cec5SDimitry Andric 
15900b57cec5SDimitry Andric   if (DTU)
15910b57cec5SDimitry Andric     DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
15920b57cec5SDimitry Andric 
15930b57cec5SDimitry Andric   return cast<ReturnInst>(NewRet);
15940b57cec5SDimitry Andric }
15950b57cec5SDimitry Andric 
SplitBlockAndInsertIfThen(Value * Cond,BasicBlock::iterator SplitBefore,bool Unreachable,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI,BasicBlock * ThenBlock)1596e8d8bef9SDimitry Andric Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
1597c9157d92SDimitry Andric                                              BasicBlock::iterator SplitBefore,
1598e8d8bef9SDimitry Andric                                              bool Unreachable,
1599e8d8bef9SDimitry Andric                                              MDNode *BranchWeights,
1600e8d8bef9SDimitry Andric                                              DomTreeUpdater *DTU, LoopInfo *LI,
1601e8d8bef9SDimitry Andric                                              BasicBlock *ThenBlock) {
1602fe013be4SDimitry Andric   SplitBlockAndInsertIfThenElse(
1603fe013be4SDimitry Andric       Cond, SplitBefore, &ThenBlock, /* ElseBlock */ nullptr,
1604fe013be4SDimitry Andric       /* UnreachableThen */ Unreachable,
1605fe013be4SDimitry Andric       /* UnreachableElse */ false, BranchWeights, DTU, LI);
1606fe013be4SDimitry Andric   return ThenBlock->getTerminator();
1607fe013be4SDimitry Andric }
1608fe013be4SDimitry Andric 
SplitBlockAndInsertIfElse(Value * Cond,BasicBlock::iterator SplitBefore,bool Unreachable,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI,BasicBlock * ElseBlock)1609fe013be4SDimitry Andric Instruction *llvm::SplitBlockAndInsertIfElse(Value *Cond,
1610c9157d92SDimitry Andric                                              BasicBlock::iterator SplitBefore,
1611fe013be4SDimitry Andric                                              bool Unreachable,
1612fe013be4SDimitry Andric                                              MDNode *BranchWeights,
1613fe013be4SDimitry Andric                                              DomTreeUpdater *DTU, LoopInfo *LI,
1614fe013be4SDimitry Andric                                              BasicBlock *ElseBlock) {
1615fe013be4SDimitry Andric   SplitBlockAndInsertIfThenElse(
1616fe013be4SDimitry Andric       Cond, SplitBefore, /* ThenBlock */ nullptr, &ElseBlock,
1617fe013be4SDimitry Andric       /* UnreachableThen */ false,
1618fe013be4SDimitry Andric       /* UnreachableElse */ Unreachable, BranchWeights, DTU, LI);
1619fe013be4SDimitry Andric   return ElseBlock->getTerminator();
1620e8d8bef9SDimitry Andric }
1621e8d8bef9SDimitry Andric 
SplitBlockAndInsertIfThenElse(Value * Cond,BasicBlock::iterator SplitBefore,Instruction ** ThenTerm,Instruction ** ElseTerm,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI)1622c9157d92SDimitry Andric void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore,
16230b57cec5SDimitry Andric                                          Instruction **ThenTerm,
16240b57cec5SDimitry Andric                                          Instruction **ElseTerm,
1625bdd1243dSDimitry Andric                                          MDNode *BranchWeights,
1626fe013be4SDimitry Andric                                          DomTreeUpdater *DTU, LoopInfo *LI) {
1627fe013be4SDimitry Andric   BasicBlock *ThenBlock = nullptr;
1628fe013be4SDimitry Andric   BasicBlock *ElseBlock = nullptr;
1629fe013be4SDimitry Andric   SplitBlockAndInsertIfThenElse(
1630fe013be4SDimitry Andric       Cond, SplitBefore, &ThenBlock, &ElseBlock, /* UnreachableThen */ false,
1631fe013be4SDimitry Andric       /* UnreachableElse */ false, BranchWeights, DTU, LI);
1632bdd1243dSDimitry Andric 
1633fe013be4SDimitry Andric   *ThenTerm = ThenBlock->getTerminator();
1634fe013be4SDimitry Andric   *ElseTerm = ElseBlock->getTerminator();
1635fe013be4SDimitry Andric }
1636fe013be4SDimitry Andric 
SplitBlockAndInsertIfThenElse(Value * Cond,BasicBlock::iterator SplitBefore,BasicBlock ** ThenBlock,BasicBlock ** ElseBlock,bool UnreachableThen,bool UnreachableElse,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI)1637fe013be4SDimitry Andric void llvm::SplitBlockAndInsertIfThenElse(
1638c9157d92SDimitry Andric     Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
1639fe013be4SDimitry Andric     BasicBlock **ElseBlock, bool UnreachableThen, bool UnreachableElse,
1640fe013be4SDimitry Andric     MDNode *BranchWeights, DomTreeUpdater *DTU, LoopInfo *LI) {
1641fe013be4SDimitry Andric   assert((ThenBlock || ElseBlock) &&
1642fe013be4SDimitry Andric          "At least one branch block must be created");
1643fe013be4SDimitry Andric   assert((!UnreachableThen || !UnreachableElse) &&
1644fe013be4SDimitry Andric          "Split block tail must be reachable");
1645fe013be4SDimitry Andric 
1646fe013be4SDimitry Andric   SmallVector<DominatorTree::UpdateType, 8> Updates;
1647bdd1243dSDimitry Andric   SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
1648fe013be4SDimitry Andric   BasicBlock *Head = SplitBefore->getParent();
1649fe013be4SDimitry Andric   if (DTU) {
1650bdd1243dSDimitry Andric     UniqueOrigSuccessors.insert(succ_begin(Head), succ_end(Head));
1651fe013be4SDimitry Andric     Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
1652fe013be4SDimitry Andric   }
1653bdd1243dSDimitry Andric 
16540b57cec5SDimitry Andric   LLVMContext &C = Head->getContext();
1655c9157d92SDimitry Andric   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
1656fe013be4SDimitry Andric   BasicBlock *TrueBlock = Tail;
1657fe013be4SDimitry Andric   BasicBlock *FalseBlock = Tail;
1658fe013be4SDimitry Andric   bool ThenToTailEdge = false;
1659fe013be4SDimitry Andric   bool ElseToTailEdge = false;
1660fe013be4SDimitry Andric 
1661fe013be4SDimitry Andric   // Encapsulate the logic around creation/insertion/etc of a new block.
1662fe013be4SDimitry Andric   auto handleBlock = [&](BasicBlock **PBB, bool Unreachable, BasicBlock *&BB,
1663fe013be4SDimitry Andric                          bool &ToTailEdge) {
1664fe013be4SDimitry Andric     if (PBB == nullptr)
1665fe013be4SDimitry Andric       return; // Do not create/insert a block.
1666fe013be4SDimitry Andric 
1667fe013be4SDimitry Andric     if (*PBB)
1668fe013be4SDimitry Andric       BB = *PBB; // Caller supplied block, use it.
1669fe013be4SDimitry Andric     else {
1670fe013be4SDimitry Andric       // Create a new block.
1671fe013be4SDimitry Andric       BB = BasicBlock::Create(C, "", Head->getParent(), Tail);
1672fe013be4SDimitry Andric       if (Unreachable)
1673fe013be4SDimitry Andric         (void)new UnreachableInst(C, BB);
1674fe013be4SDimitry Andric       else {
1675fe013be4SDimitry Andric         (void)BranchInst::Create(Tail, BB);
1676fe013be4SDimitry Andric         ToTailEdge = true;
1677fe013be4SDimitry Andric       }
1678fe013be4SDimitry Andric       BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
1679fe013be4SDimitry Andric       // Pass the new block back to the caller.
1680fe013be4SDimitry Andric       *PBB = BB;
1681fe013be4SDimitry Andric     }
1682fe013be4SDimitry Andric   };
1683fe013be4SDimitry Andric 
1684fe013be4SDimitry Andric   handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
1685fe013be4SDimitry Andric   handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
1686fe013be4SDimitry Andric 
1687fe013be4SDimitry Andric   Instruction *HeadOldTerm = Head->getTerminator();
16880b57cec5SDimitry Andric   BranchInst *HeadNewTerm =
1689fe013be4SDimitry Andric       BranchInst::Create(/*ifTrue*/ TrueBlock, /*ifFalse*/ FalseBlock, Cond);
16900b57cec5SDimitry Andric   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
16910b57cec5SDimitry Andric   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
1692fe013be4SDimitry Andric 
1693bdd1243dSDimitry Andric   if (DTU) {
1694fe013be4SDimitry Andric     Updates.emplace_back(DominatorTree::Insert, Head, TrueBlock);
1695fe013be4SDimitry Andric     Updates.emplace_back(DominatorTree::Insert, Head, FalseBlock);
1696fe013be4SDimitry Andric     if (ThenToTailEdge)
1697fe013be4SDimitry Andric       Updates.emplace_back(DominatorTree::Insert, TrueBlock, Tail);
1698fe013be4SDimitry Andric     if (ElseToTailEdge)
1699fe013be4SDimitry Andric       Updates.emplace_back(DominatorTree::Insert, FalseBlock, Tail);
1700bdd1243dSDimitry Andric     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1701fe013be4SDimitry Andric       Updates.emplace_back(DominatorTree::Insert, Tail, UniqueOrigSuccessor);
1702bdd1243dSDimitry Andric     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1703fe013be4SDimitry Andric       Updates.emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1704bdd1243dSDimitry Andric     DTU->applyUpdates(Updates);
1705bdd1243dSDimitry Andric   }
1706fe013be4SDimitry Andric 
1707fe013be4SDimitry Andric   if (LI) {
1708fe013be4SDimitry Andric     if (Loop *L = LI->getLoopFor(Head); L) {
1709fe013be4SDimitry Andric       if (ThenToTailEdge)
1710fe013be4SDimitry Andric         L->addBasicBlockToLoop(TrueBlock, *LI);
1711fe013be4SDimitry Andric       if (ElseToTailEdge)
1712fe013be4SDimitry Andric         L->addBasicBlockToLoop(FalseBlock, *LI);
1713fe013be4SDimitry Andric       L->addBasicBlockToLoop(Tail, *LI);
1714fe013be4SDimitry Andric     }
1715fe013be4SDimitry Andric   }
1716fe013be4SDimitry Andric }
1717fe013be4SDimitry Andric 
1718fe013be4SDimitry Andric std::pair<Instruction*, Value*>
SplitBlockAndInsertSimpleForLoop(Value * End,Instruction * SplitBefore)1719fe013be4SDimitry Andric llvm::SplitBlockAndInsertSimpleForLoop(Value *End, Instruction *SplitBefore) {
1720fe013be4SDimitry Andric   BasicBlock *LoopPred = SplitBefore->getParent();
1721fe013be4SDimitry Andric   BasicBlock *LoopBody = SplitBlock(SplitBefore->getParent(), SplitBefore);
1722fe013be4SDimitry Andric   BasicBlock *LoopExit = SplitBlock(SplitBefore->getParent(), SplitBefore);
1723fe013be4SDimitry Andric 
1724fe013be4SDimitry Andric   auto *Ty = End->getType();
1725fe013be4SDimitry Andric   auto &DL = SplitBefore->getModule()->getDataLayout();
1726fe013be4SDimitry Andric   const unsigned Bitwidth = DL.getTypeSizeInBits(Ty);
1727fe013be4SDimitry Andric 
1728fe013be4SDimitry Andric   IRBuilder<> Builder(LoopBody->getTerminator());
1729fe013be4SDimitry Andric   auto *IV = Builder.CreatePHI(Ty, 2, "iv");
1730fe013be4SDimitry Andric   auto *IVNext =
1731fe013be4SDimitry Andric     Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
1732fe013be4SDimitry Andric                       /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
1733fe013be4SDimitry Andric   auto *IVCheck = Builder.CreateICmpEQ(IVNext, End,
1734fe013be4SDimitry Andric                                        IV->getName() + ".check");
1735fe013be4SDimitry Andric   Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
1736fe013be4SDimitry Andric   LoopBody->getTerminator()->eraseFromParent();
1737fe013be4SDimitry Andric 
1738fe013be4SDimitry Andric   // Populate the IV PHI.
1739fe013be4SDimitry Andric   IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
1740fe013be4SDimitry Andric   IV->addIncoming(IVNext, LoopBody);
1741fe013be4SDimitry Andric 
1742fe013be4SDimitry Andric   return std::make_pair(LoopBody->getFirstNonPHI(), IV);
1743fe013be4SDimitry Andric }
1744fe013be4SDimitry Andric 
SplitBlockAndInsertForEachLane(ElementCount EC,Type * IndexTy,Instruction * InsertBefore,std::function<void (IRBuilderBase &,Value *)> Func)1745fe013be4SDimitry Andric void llvm::SplitBlockAndInsertForEachLane(ElementCount EC,
1746fe013be4SDimitry Andric      Type *IndexTy, Instruction *InsertBefore,
1747fe013be4SDimitry Andric      std::function<void(IRBuilderBase&, Value*)> Func) {
1748fe013be4SDimitry Andric 
1749fe013be4SDimitry Andric   IRBuilder<> IRB(InsertBefore);
1750fe013be4SDimitry Andric 
1751fe013be4SDimitry Andric   if (EC.isScalable()) {
1752fe013be4SDimitry Andric     Value *NumElements = IRB.CreateElementCount(IndexTy, EC);
1753fe013be4SDimitry Andric 
1754fe013be4SDimitry Andric     auto [BodyIP, Index] =
1755fe013be4SDimitry Andric       SplitBlockAndInsertSimpleForLoop(NumElements, InsertBefore);
1756fe013be4SDimitry Andric 
1757fe013be4SDimitry Andric     IRB.SetInsertPoint(BodyIP);
1758fe013be4SDimitry Andric     Func(IRB, Index);
1759fe013be4SDimitry Andric     return;
1760fe013be4SDimitry Andric   }
1761fe013be4SDimitry Andric 
1762fe013be4SDimitry Andric   unsigned Num = EC.getFixedValue();
1763fe013be4SDimitry Andric   for (unsigned Idx = 0; Idx < Num; ++Idx) {
1764fe013be4SDimitry Andric     IRB.SetInsertPoint(InsertBefore);
1765fe013be4SDimitry Andric     Func(IRB, ConstantInt::get(IndexTy, Idx));
1766fe013be4SDimitry Andric   }
1767fe013be4SDimitry Andric }
1768fe013be4SDimitry Andric 
SplitBlockAndInsertForEachLane(Value * EVL,Instruction * InsertBefore,std::function<void (IRBuilderBase &,Value *)> Func)1769fe013be4SDimitry Andric void llvm::SplitBlockAndInsertForEachLane(
1770fe013be4SDimitry Andric     Value *EVL, Instruction *InsertBefore,
1771fe013be4SDimitry Andric     std::function<void(IRBuilderBase &, Value *)> Func) {
1772fe013be4SDimitry Andric 
1773fe013be4SDimitry Andric   IRBuilder<> IRB(InsertBefore);
1774fe013be4SDimitry Andric   Type *Ty = EVL->getType();
1775fe013be4SDimitry Andric 
1776fe013be4SDimitry Andric   if (!isa<ConstantInt>(EVL)) {
1777fe013be4SDimitry Andric     auto [BodyIP, Index] = SplitBlockAndInsertSimpleForLoop(EVL, InsertBefore);
1778fe013be4SDimitry Andric     IRB.SetInsertPoint(BodyIP);
1779fe013be4SDimitry Andric     Func(IRB, Index);
1780fe013be4SDimitry Andric     return;
1781fe013be4SDimitry Andric   }
1782fe013be4SDimitry Andric 
1783fe013be4SDimitry Andric   unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
1784fe013be4SDimitry Andric   for (unsigned Idx = 0; Idx < Num; ++Idx) {
1785fe013be4SDimitry Andric     IRB.SetInsertPoint(InsertBefore);
1786fe013be4SDimitry Andric     Func(IRB, ConstantInt::get(Ty, Idx));
1787fe013be4SDimitry Andric   }
17880b57cec5SDimitry Andric }
17890b57cec5SDimitry Andric 
GetIfCondition(BasicBlock * BB,BasicBlock * & IfTrue,BasicBlock * & IfFalse)1790fe6060f1SDimitry Andric BranchInst *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
17910b57cec5SDimitry Andric                                  BasicBlock *&IfFalse) {
17920b57cec5SDimitry Andric   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
17930b57cec5SDimitry Andric   BasicBlock *Pred1 = nullptr;
17940b57cec5SDimitry Andric   BasicBlock *Pred2 = nullptr;
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric   if (SomePHI) {
17970b57cec5SDimitry Andric     if (SomePHI->getNumIncomingValues() != 2)
17980b57cec5SDimitry Andric       return nullptr;
17990b57cec5SDimitry Andric     Pred1 = SomePHI->getIncomingBlock(0);
18000b57cec5SDimitry Andric     Pred2 = SomePHI->getIncomingBlock(1);
18010b57cec5SDimitry Andric   } else {
18020b57cec5SDimitry Andric     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
18030b57cec5SDimitry Andric     if (PI == PE) // No predecessor
18040b57cec5SDimitry Andric       return nullptr;
18050b57cec5SDimitry Andric     Pred1 = *PI++;
18060b57cec5SDimitry Andric     if (PI == PE) // Only one predecessor
18070b57cec5SDimitry Andric       return nullptr;
18080b57cec5SDimitry Andric     Pred2 = *PI++;
18090b57cec5SDimitry Andric     if (PI != PE) // More than two predecessors
18100b57cec5SDimitry Andric       return nullptr;
18110b57cec5SDimitry Andric   }
18120b57cec5SDimitry Andric 
18130b57cec5SDimitry Andric   // We can only handle branches.  Other control flow will be lowered to
18140b57cec5SDimitry Andric   // branches if possible anyway.
18150b57cec5SDimitry Andric   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
18160b57cec5SDimitry Andric   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
18170b57cec5SDimitry Andric   if (!Pred1Br || !Pred2Br)
18180b57cec5SDimitry Andric     return nullptr;
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   // Eliminate code duplication by ensuring that Pred1Br is conditional if
18210b57cec5SDimitry Andric   // either are.
18220b57cec5SDimitry Andric   if (Pred2Br->isConditional()) {
18230b57cec5SDimitry Andric     // If both branches are conditional, we don't have an "if statement".  In
18240b57cec5SDimitry Andric     // reality, we could transform this case, but since the condition will be
18250b57cec5SDimitry Andric     // required anyway, we stand no chance of eliminating it, so the xform is
18260b57cec5SDimitry Andric     // probably not profitable.
18270b57cec5SDimitry Andric     if (Pred1Br->isConditional())
18280b57cec5SDimitry Andric       return nullptr;
18290b57cec5SDimitry Andric 
18300b57cec5SDimitry Andric     std::swap(Pred1, Pred2);
18310b57cec5SDimitry Andric     std::swap(Pred1Br, Pred2Br);
18320b57cec5SDimitry Andric   }
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   if (Pred1Br->isConditional()) {
18350b57cec5SDimitry Andric     // The only thing we have to watch out for here is to make sure that Pred2
18360b57cec5SDimitry Andric     // doesn't have incoming edges from other blocks.  If it does, the condition
18370b57cec5SDimitry Andric     // doesn't dominate BB.
18380b57cec5SDimitry Andric     if (!Pred2->getSinglePredecessor())
18390b57cec5SDimitry Andric       return nullptr;
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric     // If we found a conditional branch predecessor, make sure that it branches
18420b57cec5SDimitry Andric     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
18430b57cec5SDimitry Andric     if (Pred1Br->getSuccessor(0) == BB &&
18440b57cec5SDimitry Andric         Pred1Br->getSuccessor(1) == Pred2) {
18450b57cec5SDimitry Andric       IfTrue = Pred1;
18460b57cec5SDimitry Andric       IfFalse = Pred2;
18470b57cec5SDimitry Andric     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
18480b57cec5SDimitry Andric                Pred1Br->getSuccessor(1) == BB) {
18490b57cec5SDimitry Andric       IfTrue = Pred2;
18500b57cec5SDimitry Andric       IfFalse = Pred1;
18510b57cec5SDimitry Andric     } else {
18520b57cec5SDimitry Andric       // We know that one arm of the conditional goes to BB, so the other must
18530b57cec5SDimitry Andric       // go somewhere unrelated, and this must not be an "if statement".
18540b57cec5SDimitry Andric       return nullptr;
18550b57cec5SDimitry Andric     }
18560b57cec5SDimitry Andric 
1857fe6060f1SDimitry Andric     return Pred1Br;
18580b57cec5SDimitry Andric   }
18590b57cec5SDimitry Andric 
18600b57cec5SDimitry Andric   // Ok, if we got here, both predecessors end with an unconditional branch to
18610b57cec5SDimitry Andric   // BB.  Don't panic!  If both blocks only have a single (identical)
18620b57cec5SDimitry Andric   // predecessor, and THAT is a conditional branch, then we're all ok!
18630b57cec5SDimitry Andric   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
18640b57cec5SDimitry Andric   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
18650b57cec5SDimitry Andric     return nullptr;
18660b57cec5SDimitry Andric 
18670b57cec5SDimitry Andric   // Otherwise, if this is a conditional branch, then we can use it!
18680b57cec5SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
18690b57cec5SDimitry Andric   if (!BI) return nullptr;
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   assert(BI->isConditional() && "Two successors but not conditional?");
18720b57cec5SDimitry Andric   if (BI->getSuccessor(0) == Pred1) {
18730b57cec5SDimitry Andric     IfTrue = Pred1;
18740b57cec5SDimitry Andric     IfFalse = Pred2;
18750b57cec5SDimitry Andric   } else {
18760b57cec5SDimitry Andric     IfTrue = Pred2;
18770b57cec5SDimitry Andric     IfFalse = Pred1;
18780b57cec5SDimitry Andric   }
1879fe6060f1SDimitry Andric   return BI;
18800b57cec5SDimitry Andric }
18815ffd83dbSDimitry Andric 
18825ffd83dbSDimitry Andric // After creating a control flow hub, the operands of PHINodes in an outgoing
18835ffd83dbSDimitry Andric // block Out no longer match the predecessors of that block. Predecessors of Out
18845ffd83dbSDimitry Andric // that are incoming blocks to the hub are now replaced by just one edge from
18855ffd83dbSDimitry Andric // the hub. To match this new control flow, the corresponding values from each
18865ffd83dbSDimitry Andric // PHINode must now be moved a new PHINode in the first guard block of the hub.
18875ffd83dbSDimitry Andric //
18885ffd83dbSDimitry Andric // This operation cannot be performed with SSAUpdater, because it involves one
18895ffd83dbSDimitry Andric // new use: If the block Out is in the list of Incoming blocks, then the newly
18905ffd83dbSDimitry Andric // 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)18915ffd83dbSDimitry Andric static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock,
18925ffd83dbSDimitry Andric                           const SetVector<BasicBlock *> &Incoming,
18935ffd83dbSDimitry Andric                           BasicBlock *FirstGuardBlock) {
18945ffd83dbSDimitry Andric   auto I = Out->begin();
18955ffd83dbSDimitry Andric   while (I != Out->end() && isa<PHINode>(I)) {
18965ffd83dbSDimitry Andric     auto Phi = cast<PHINode>(I);
18975ffd83dbSDimitry Andric     auto NewPhi =
18985ffd83dbSDimitry Andric         PHINode::Create(Phi->getType(), Incoming.size(),
1899bdd1243dSDimitry Andric                         Phi->getName() + ".moved", &FirstGuardBlock->front());
1900bdd1243dSDimitry Andric     for (auto *In : Incoming) {
19015ffd83dbSDimitry Andric       Value *V = UndefValue::get(Phi->getType());
19025ffd83dbSDimitry Andric       if (In == Out) {
19035ffd83dbSDimitry Andric         V = NewPhi;
19045ffd83dbSDimitry Andric       } else if (Phi->getBasicBlockIndex(In) != -1) {
19055ffd83dbSDimitry Andric         V = Phi->removeIncomingValue(In, false);
19065ffd83dbSDimitry Andric       }
19075ffd83dbSDimitry Andric       NewPhi->addIncoming(V, In);
19085ffd83dbSDimitry Andric     }
19095ffd83dbSDimitry Andric     assert(NewPhi->getNumIncomingValues() == Incoming.size());
19105ffd83dbSDimitry Andric     if (Phi->getNumOperands() == 0) {
19115ffd83dbSDimitry Andric       Phi->replaceAllUsesWith(NewPhi);
19125ffd83dbSDimitry Andric       I = Phi->eraseFromParent();
19135ffd83dbSDimitry Andric       continue;
19145ffd83dbSDimitry Andric     }
19155ffd83dbSDimitry Andric     Phi->addIncoming(NewPhi, GuardBlock);
19165ffd83dbSDimitry Andric     ++I;
19175ffd83dbSDimitry Andric   }
19185ffd83dbSDimitry Andric }
19195ffd83dbSDimitry Andric 
1920bdd1243dSDimitry Andric using BBPredicates = DenseMap<BasicBlock *, Instruction *>;
19215ffd83dbSDimitry Andric using BBSetVector = SetVector<BasicBlock *>;
19225ffd83dbSDimitry Andric 
19235ffd83dbSDimitry Andric // Redirects the terminator of the incoming block to the first guard
19245ffd83dbSDimitry Andric // block in the hub. The condition of the original terminator (if it
19255ffd83dbSDimitry Andric // was conditional) and its original successors are returned as a
19265ffd83dbSDimitry Andric // tuple <condition, succ0, succ1>. The function additionally filters
19275ffd83dbSDimitry Andric // out successors that are not in the set of outgoing blocks.
19285ffd83dbSDimitry Andric //
19295ffd83dbSDimitry Andric // - condition is non-null iff the branch is conditional.
19305ffd83dbSDimitry Andric // - Succ1 is non-null iff the sole/taken target is an outgoing block.
19315ffd83dbSDimitry Andric // - Succ2 is non-null iff condition is non-null and the fallthrough
19325ffd83dbSDimitry Andric //         target is an outgoing block.
19335ffd83dbSDimitry Andric static std::tuple<Value *, BasicBlock *, BasicBlock *>
redirectToHub(BasicBlock * BB,BasicBlock * FirstGuardBlock,const BBSetVector & Outgoing)19345ffd83dbSDimitry Andric redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock,
19355ffd83dbSDimitry Andric               const BBSetVector &Outgoing) {
1936bdd1243dSDimitry Andric   assert(isa<BranchInst>(BB->getTerminator()) &&
1937bdd1243dSDimitry Andric          "Only support branch terminator.");
19385ffd83dbSDimitry Andric   auto Branch = cast<BranchInst>(BB->getTerminator());
19395ffd83dbSDimitry Andric   auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
19405ffd83dbSDimitry Andric 
19415ffd83dbSDimitry Andric   BasicBlock *Succ0 = Branch->getSuccessor(0);
19425ffd83dbSDimitry Andric   BasicBlock *Succ1 = nullptr;
19435ffd83dbSDimitry Andric   Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr;
19445ffd83dbSDimitry Andric 
19455ffd83dbSDimitry Andric   if (Branch->isUnconditional()) {
19465ffd83dbSDimitry Andric     Branch->setSuccessor(0, FirstGuardBlock);
19475ffd83dbSDimitry Andric     assert(Succ0);
19485ffd83dbSDimitry Andric   } else {
19495ffd83dbSDimitry Andric     Succ1 = Branch->getSuccessor(1);
19505ffd83dbSDimitry Andric     Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr;
19515ffd83dbSDimitry Andric     assert(Succ0 || Succ1);
19525ffd83dbSDimitry Andric     if (Succ0 && !Succ1) {
19535ffd83dbSDimitry Andric       Branch->setSuccessor(0, FirstGuardBlock);
19545ffd83dbSDimitry Andric     } else if (Succ1 && !Succ0) {
19555ffd83dbSDimitry Andric       Branch->setSuccessor(1, FirstGuardBlock);
19565ffd83dbSDimitry Andric     } else {
19575ffd83dbSDimitry Andric       Branch->eraseFromParent();
19585ffd83dbSDimitry Andric       BranchInst::Create(FirstGuardBlock, BB);
19595ffd83dbSDimitry Andric     }
19605ffd83dbSDimitry Andric   }
19615ffd83dbSDimitry Andric 
19625ffd83dbSDimitry Andric   assert(Succ0 || Succ1);
19635ffd83dbSDimitry Andric   return std::make_tuple(Condition, Succ0, Succ1);
19645ffd83dbSDimitry Andric }
1965bdd1243dSDimitry Andric // Setup the branch instructions for guard blocks.
19665ffd83dbSDimitry Andric //
19675ffd83dbSDimitry Andric // Each guard block terminates in a conditional branch that transfers
19685ffd83dbSDimitry Andric // control to the corresponding outgoing block or the next guard
19695ffd83dbSDimitry Andric // block. The last guard block has two outgoing blocks as successors
19705ffd83dbSDimitry Andric // since the condition for the final outgoing block is trivially
19715ffd83dbSDimitry Andric // true. So we create one less block (including the first guard block)
19725ffd83dbSDimitry Andric // than the number of outgoing blocks.
setupBranchForGuard(SmallVectorImpl<BasicBlock * > & GuardBlocks,const BBSetVector & Outgoing,BBPredicates & GuardPredicates)1973bdd1243dSDimitry Andric static void setupBranchForGuard(SmallVectorImpl<BasicBlock *> &GuardBlocks,
1974bdd1243dSDimitry Andric                                 const BBSetVector &Outgoing,
1975bdd1243dSDimitry Andric                                 BBPredicates &GuardPredicates) {
19765ffd83dbSDimitry Andric   // To help keep the loop simple, temporarily append the last
19775ffd83dbSDimitry Andric   // outgoing block to the list of guard blocks.
19785ffd83dbSDimitry Andric   GuardBlocks.push_back(Outgoing.back());
19795ffd83dbSDimitry Andric 
19805ffd83dbSDimitry Andric   for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) {
19815ffd83dbSDimitry Andric     auto Out = Outgoing[i];
19825ffd83dbSDimitry Andric     assert(GuardPredicates.count(Out));
19835ffd83dbSDimitry Andric     BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out],
19845ffd83dbSDimitry Andric                        GuardBlocks[i]);
19855ffd83dbSDimitry Andric   }
19865ffd83dbSDimitry Andric 
19875ffd83dbSDimitry Andric   // Remove the last block from the guard list.
19885ffd83dbSDimitry Andric   GuardBlocks.pop_back();
19895ffd83dbSDimitry Andric }
19905ffd83dbSDimitry Andric 
1991bdd1243dSDimitry Andric /// We are using one integer to represent the block we are branching to. Then at
1992bdd1243dSDimitry Andric /// each guard block, the predicate was calcuated using a simple `icmp eq`.
calcPredicateUsingInteger(const BBSetVector & Incoming,const BBSetVector & Outgoing,SmallVectorImpl<BasicBlock * > & GuardBlocks,BBPredicates & GuardPredicates)1993bdd1243dSDimitry Andric static void calcPredicateUsingInteger(
1994bdd1243dSDimitry Andric     const BBSetVector &Incoming, const BBSetVector &Outgoing,
1995bdd1243dSDimitry Andric     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates) {
1996bdd1243dSDimitry Andric   auto &Context = Incoming.front()->getContext();
1997bdd1243dSDimitry Andric   auto FirstGuardBlock = GuardBlocks.front();
1998bdd1243dSDimitry Andric 
1999bdd1243dSDimitry Andric   auto Phi = PHINode::Create(Type::getInt32Ty(Context), Incoming.size(),
2000bdd1243dSDimitry Andric                              "merged.bb.idx", FirstGuardBlock);
2001bdd1243dSDimitry Andric 
2002bdd1243dSDimitry Andric   for (auto In : Incoming) {
2003bdd1243dSDimitry Andric     Value *Condition;
2004bdd1243dSDimitry Andric     BasicBlock *Succ0;
2005bdd1243dSDimitry Andric     BasicBlock *Succ1;
2006bdd1243dSDimitry Andric     std::tie(Condition, Succ0, Succ1) =
2007bdd1243dSDimitry Andric         redirectToHub(In, FirstGuardBlock, Outgoing);
2008bdd1243dSDimitry Andric     Value *IncomingId = nullptr;
2009bdd1243dSDimitry Andric     if (Succ0 && Succ1) {
2010bdd1243dSDimitry Andric       // target_bb_index = Condition ? index_of_succ0 : index_of_succ1.
2011bdd1243dSDimitry Andric       auto Succ0Iter = find(Outgoing, Succ0);
2012bdd1243dSDimitry Andric       auto Succ1Iter = find(Outgoing, Succ1);
2013bdd1243dSDimitry Andric       Value *Id0 = ConstantInt::get(Type::getInt32Ty(Context),
2014bdd1243dSDimitry Andric                                     std::distance(Outgoing.begin(), Succ0Iter));
2015bdd1243dSDimitry Andric       Value *Id1 = ConstantInt::get(Type::getInt32Ty(Context),
2016bdd1243dSDimitry Andric                                     std::distance(Outgoing.begin(), Succ1Iter));
2017bdd1243dSDimitry Andric       IncomingId = SelectInst::Create(Condition, Id0, Id1, "target.bb.idx",
2018bdd1243dSDimitry Andric                                       In->getTerminator());
2019bdd1243dSDimitry Andric     } else {
2020bdd1243dSDimitry Andric       // Get the index of the non-null successor.
2021bdd1243dSDimitry Andric       auto SuccIter = Succ0 ? find(Outgoing, Succ0) : find(Outgoing, Succ1);
2022bdd1243dSDimitry Andric       IncomingId = ConstantInt::get(Type::getInt32Ty(Context),
2023bdd1243dSDimitry Andric                                     std::distance(Outgoing.begin(), SuccIter));
2024bdd1243dSDimitry Andric     }
2025bdd1243dSDimitry Andric     Phi->addIncoming(IncomingId, In);
2026bdd1243dSDimitry Andric   }
2027bdd1243dSDimitry Andric 
2028bdd1243dSDimitry Andric   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2029bdd1243dSDimitry Andric     auto Out = Outgoing[i];
2030bdd1243dSDimitry Andric     auto Cmp = ICmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, Phi,
2031bdd1243dSDimitry Andric                                 ConstantInt::get(Type::getInt32Ty(Context), i),
2032bdd1243dSDimitry Andric                                 Out->getName() + ".predicate", GuardBlocks[i]);
2033bdd1243dSDimitry Andric     GuardPredicates[Out] = Cmp;
2034bdd1243dSDimitry Andric   }
2035bdd1243dSDimitry Andric }
2036bdd1243dSDimitry Andric 
2037bdd1243dSDimitry Andric /// 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)2038bdd1243dSDimitry Andric static void calcPredicateUsingBooleans(
2039bdd1243dSDimitry Andric     const BBSetVector &Incoming, const BBSetVector &Outgoing,
2040bdd1243dSDimitry Andric     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates,
2041bdd1243dSDimitry Andric     SmallVectorImpl<WeakVH> &DeletionCandidates) {
2042bdd1243dSDimitry Andric   auto &Context = Incoming.front()->getContext();
2043bdd1243dSDimitry Andric   auto BoolTrue = ConstantInt::getTrue(Context);
2044bdd1243dSDimitry Andric   auto BoolFalse = ConstantInt::getFalse(Context);
2045bdd1243dSDimitry Andric   auto FirstGuardBlock = GuardBlocks.front();
2046bdd1243dSDimitry Andric 
2047bdd1243dSDimitry Andric   // The predicate for the last outgoing is trivially true, and so we
2048bdd1243dSDimitry Andric   // process only the first N-1 successors.
2049bdd1243dSDimitry Andric   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2050bdd1243dSDimitry Andric     auto Out = Outgoing[i];
2051bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n");
2052bdd1243dSDimitry Andric 
2053bdd1243dSDimitry Andric     auto Phi =
2054bdd1243dSDimitry Andric         PHINode::Create(Type::getInt1Ty(Context), Incoming.size(),
2055bdd1243dSDimitry Andric                         StringRef("Guard.") + Out->getName(), FirstGuardBlock);
2056bdd1243dSDimitry Andric     GuardPredicates[Out] = Phi;
2057bdd1243dSDimitry Andric   }
2058bdd1243dSDimitry Andric 
2059bdd1243dSDimitry Andric   for (auto *In : Incoming) {
2060bdd1243dSDimitry Andric     Value *Condition;
2061bdd1243dSDimitry Andric     BasicBlock *Succ0;
2062bdd1243dSDimitry Andric     BasicBlock *Succ1;
2063bdd1243dSDimitry Andric     std::tie(Condition, Succ0, Succ1) =
2064bdd1243dSDimitry Andric         redirectToHub(In, FirstGuardBlock, Outgoing);
2065bdd1243dSDimitry Andric 
2066bdd1243dSDimitry Andric     // Optimization: Consider an incoming block A with both successors
2067bdd1243dSDimitry Andric     // Succ0 and Succ1 in the set of outgoing blocks. The predicates
2068bdd1243dSDimitry Andric     // for Succ0 and Succ1 complement each other. If Succ0 is visited
2069bdd1243dSDimitry Andric     // first in the loop below, control will branch to Succ0 using the
2070bdd1243dSDimitry Andric     // corresponding predicate. But if that branch is not taken, then
2071bdd1243dSDimitry Andric     // control must reach Succ1, which means that the incoming value of
2072bdd1243dSDimitry Andric     // the predicate from `In` is true for Succ1.
2073bdd1243dSDimitry Andric     bool OneSuccessorDone = false;
2074bdd1243dSDimitry Andric     for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2075bdd1243dSDimitry Andric       auto Out = Outgoing[i];
2076bdd1243dSDimitry Andric       PHINode *Phi = cast<PHINode>(GuardPredicates[Out]);
2077bdd1243dSDimitry Andric       if (Out != Succ0 && Out != Succ1) {
2078bdd1243dSDimitry Andric         Phi->addIncoming(BoolFalse, In);
2079bdd1243dSDimitry Andric       } else if (!Succ0 || !Succ1 || OneSuccessorDone) {
2080bdd1243dSDimitry Andric         // Optimization: When only one successor is an outgoing block,
2081bdd1243dSDimitry Andric         // the incoming predicate from `In` is always true.
2082bdd1243dSDimitry Andric         Phi->addIncoming(BoolTrue, In);
2083bdd1243dSDimitry Andric       } else {
2084bdd1243dSDimitry Andric         assert(Succ0 && Succ1);
2085bdd1243dSDimitry Andric         if (Out == Succ0) {
2086bdd1243dSDimitry Andric           Phi->addIncoming(Condition, In);
2087bdd1243dSDimitry Andric         } else {
2088bdd1243dSDimitry Andric           auto Inverted = invertCondition(Condition);
2089bdd1243dSDimitry Andric           DeletionCandidates.push_back(Condition);
2090bdd1243dSDimitry Andric           Phi->addIncoming(Inverted, In);
2091bdd1243dSDimitry Andric         }
2092bdd1243dSDimitry Andric         OneSuccessorDone = true;
2093bdd1243dSDimitry Andric       }
2094bdd1243dSDimitry Andric     }
2095bdd1243dSDimitry Andric   }
2096bdd1243dSDimitry Andric }
2097bdd1243dSDimitry Andric 
2098bdd1243dSDimitry Andric // Capture the existing control flow as guard predicates, and redirect
2099bdd1243dSDimitry Andric // control flow from \p Incoming block through the \p GuardBlocks to the
2100bdd1243dSDimitry Andric // \p Outgoing blocks.
2101bdd1243dSDimitry Andric //
2102bdd1243dSDimitry Andric // There is one guard predicate for each outgoing block OutBB. The
2103bdd1243dSDimitry Andric // predicate represents whether the hub should transfer control flow
2104bdd1243dSDimitry Andric // to OutBB. These predicates are NOT ORTHOGONAL. The Hub evaluates
2105bdd1243dSDimitry Andric // them in the same order as the Outgoing set-vector, and control
2106bdd1243dSDimitry Andric // branches to the first outgoing block whose predicate evaluates to true.
2107bdd1243dSDimitry Andric static void
convertToGuardPredicates(SmallVectorImpl<BasicBlock * > & GuardBlocks,SmallVectorImpl<WeakVH> & DeletionCandidates,const BBSetVector & Incoming,const BBSetVector & Outgoing,const StringRef Prefix,std::optional<unsigned> MaxControlFlowBooleans)2108bdd1243dSDimitry Andric convertToGuardPredicates(SmallVectorImpl<BasicBlock *> &GuardBlocks,
2109bdd1243dSDimitry Andric                          SmallVectorImpl<WeakVH> &DeletionCandidates,
2110bdd1243dSDimitry Andric                          const BBSetVector &Incoming,
2111bdd1243dSDimitry Andric                          const BBSetVector &Outgoing, const StringRef Prefix,
2112bdd1243dSDimitry Andric                          std::optional<unsigned> MaxControlFlowBooleans) {
2113bdd1243dSDimitry Andric   BBPredicates GuardPredicates;
2114bdd1243dSDimitry Andric   auto F = Incoming.front()->getParent();
2115bdd1243dSDimitry Andric 
2116bdd1243dSDimitry Andric   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i)
2117bdd1243dSDimitry Andric     GuardBlocks.push_back(
2118bdd1243dSDimitry Andric         BasicBlock::Create(F->getContext(), Prefix + ".guard", F));
2119bdd1243dSDimitry Andric 
2120bdd1243dSDimitry Andric   // When we are using an integer to record which target block to jump to, we
2121bdd1243dSDimitry Andric   // are creating less live values, actually we are using one single integer to
2122bdd1243dSDimitry Andric   // store the index of the target block. When we are using booleans to store
2123bdd1243dSDimitry Andric   // the branching information, we need (N-1) boolean values, where N is the
2124bdd1243dSDimitry Andric   // number of outgoing block.
2125bdd1243dSDimitry Andric   if (!MaxControlFlowBooleans || Outgoing.size() <= *MaxControlFlowBooleans)
2126bdd1243dSDimitry Andric     calcPredicateUsingBooleans(Incoming, Outgoing, GuardBlocks, GuardPredicates,
2127bdd1243dSDimitry Andric                                DeletionCandidates);
2128bdd1243dSDimitry Andric   else
2129bdd1243dSDimitry Andric     calcPredicateUsingInteger(Incoming, Outgoing, GuardBlocks, GuardPredicates);
2130bdd1243dSDimitry Andric 
2131bdd1243dSDimitry Andric   setupBranchForGuard(GuardBlocks, Outgoing, GuardPredicates);
2132bdd1243dSDimitry Andric }
2133bdd1243dSDimitry Andric 
CreateControlFlowHub(DomTreeUpdater * DTU,SmallVectorImpl<BasicBlock * > & GuardBlocks,const BBSetVector & Incoming,const BBSetVector & Outgoing,const StringRef Prefix,std::optional<unsigned> MaxControlFlowBooleans)21345ffd83dbSDimitry Andric BasicBlock *llvm::CreateControlFlowHub(
21355ffd83dbSDimitry Andric     DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
21365ffd83dbSDimitry Andric     const BBSetVector &Incoming, const BBSetVector &Outgoing,
2137bdd1243dSDimitry Andric     const StringRef Prefix, std::optional<unsigned> MaxControlFlowBooleans) {
2138bdd1243dSDimitry Andric   if (Outgoing.size() < 2)
2139bdd1243dSDimitry Andric     return Outgoing.front();
21405ffd83dbSDimitry Andric 
21415ffd83dbSDimitry Andric   SmallVector<DominatorTree::UpdateType, 16> Updates;
21425ffd83dbSDimitry Andric   if (DTU) {
2143bdd1243dSDimitry Andric     for (auto *In : Incoming) {
2144bdd1243dSDimitry Andric       for (auto Succ : successors(In))
21455ffd83dbSDimitry Andric         if (Outgoing.count(Succ))
21465ffd83dbSDimitry Andric           Updates.push_back({DominatorTree::Delete, In, Succ});
21475ffd83dbSDimitry Andric     }
21485ffd83dbSDimitry Andric   }
21495ffd83dbSDimitry Andric 
21505ffd83dbSDimitry Andric   SmallVector<WeakVH, 8> DeletionCandidates;
2151bdd1243dSDimitry Andric   convertToGuardPredicates(GuardBlocks, DeletionCandidates, Incoming, Outgoing,
2152bdd1243dSDimitry Andric                            Prefix, MaxControlFlowBooleans);
2153bdd1243dSDimitry Andric   auto FirstGuardBlock = GuardBlocks.front();
21545ffd83dbSDimitry Andric 
21555ffd83dbSDimitry Andric   // Update the PHINodes in each outgoing block to match the new control flow.
2156bdd1243dSDimitry Andric   for (int i = 0, e = GuardBlocks.size(); i != e; ++i)
21575ffd83dbSDimitry Andric     reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock);
2158bdd1243dSDimitry Andric 
21595ffd83dbSDimitry Andric   reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock);
21605ffd83dbSDimitry Andric 
21615ffd83dbSDimitry Andric   if (DTU) {
21625ffd83dbSDimitry Andric     int NumGuards = GuardBlocks.size();
21635ffd83dbSDimitry Andric     assert((int)Outgoing.size() == NumGuards + 1);
2164bdd1243dSDimitry Andric 
2165bdd1243dSDimitry Andric     for (auto In : Incoming)
2166bdd1243dSDimitry Andric       Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock});
2167bdd1243dSDimitry Andric 
21685ffd83dbSDimitry Andric     for (int i = 0; i != NumGuards - 1; ++i) {
21695ffd83dbSDimitry Andric       Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]});
21705ffd83dbSDimitry Andric       Updates.push_back(
21715ffd83dbSDimitry Andric           {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]});
21725ffd83dbSDimitry Andric     }
21735ffd83dbSDimitry Andric     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
21745ffd83dbSDimitry Andric                        Outgoing[NumGuards - 1]});
21755ffd83dbSDimitry Andric     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
21765ffd83dbSDimitry Andric                        Outgoing[NumGuards]});
21775ffd83dbSDimitry Andric     DTU->applyUpdates(Updates);
21785ffd83dbSDimitry Andric   }
21795ffd83dbSDimitry Andric 
21805ffd83dbSDimitry Andric   for (auto I : DeletionCandidates) {
21815ffd83dbSDimitry Andric     if (I->use_empty())
21825ffd83dbSDimitry Andric       if (auto Inst = dyn_cast_or_null<Instruction>(I))
21835ffd83dbSDimitry Andric         Inst->eraseFromParent();
21845ffd83dbSDimitry Andric   }
21855ffd83dbSDimitry Andric 
21865ffd83dbSDimitry Andric   return FirstGuardBlock;
21875ffd83dbSDimitry Andric }
2188fe013be4SDimitry Andric 
InvertBranch(BranchInst * PBI,IRBuilderBase & Builder)2189fe013be4SDimitry Andric void llvm::InvertBranch(BranchInst *PBI, IRBuilderBase &Builder) {
2190fe013be4SDimitry Andric   Value *NewCond = PBI->getCondition();
2191fe013be4SDimitry Andric   // If this is a "cmp" instruction, only used for branching (and nowhere
2192fe013be4SDimitry Andric   // else), then we can simply invert the predicate.
2193fe013be4SDimitry Andric   if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2194fe013be4SDimitry Andric     CmpInst *CI = cast<CmpInst>(NewCond);
2195fe013be4SDimitry Andric     CI->setPredicate(CI->getInversePredicate());
2196fe013be4SDimitry Andric   } else
2197fe013be4SDimitry Andric     NewCond = Builder.CreateNot(NewCond, NewCond->getName() + ".not");
2198fe013be4SDimitry Andric 
2199fe013be4SDimitry Andric   PBI->setCondition(NewCond);
2200fe013be4SDimitry Andric   PBI->swapSuccessors();
2201fe013be4SDimitry Andric }
2202c9157d92SDimitry Andric 
hasOnlySimpleTerminator(const Function & F)2203c9157d92SDimitry Andric bool llvm::hasOnlySimpleTerminator(const Function &F) {
2204c9157d92SDimitry Andric   for (auto &BB : F) {
2205c9157d92SDimitry Andric     auto *Term = BB.getTerminator();
2206c9157d92SDimitry Andric     if (!(isa<ReturnInst>(Term) || isa<UnreachableInst>(Term) ||
2207c9157d92SDimitry Andric           isa<BranchInst>(Term)))
2208c9157d92SDimitry Andric       return false;
2209c9157d92SDimitry Andric   }
2210c9157d92SDimitry Andric   return true;
2211c9157d92SDimitry Andric }
2212c9157d92SDimitry Andric 
isPresplitCoroSuspendExitEdge(const BasicBlock & Src,const BasicBlock & Dest)2213c9157d92SDimitry Andric bool llvm::isPresplitCoroSuspendExitEdge(const BasicBlock &Src,
2214c9157d92SDimitry Andric                                          const BasicBlock &Dest) {
2215c9157d92SDimitry Andric   assert(Src.getParent() == Dest.getParent());
2216c9157d92SDimitry Andric   if (!Src.getParent()->isPresplitCoroutine())
2217c9157d92SDimitry Andric     return false;
2218c9157d92SDimitry Andric   if (auto *SW = dyn_cast<SwitchInst>(Src.getTerminator()))
2219c9157d92SDimitry Andric     if (auto *Intr = dyn_cast<IntrinsicInst>(SW->getCondition()))
2220c9157d92SDimitry Andric       return Intr->getIntrinsicID() == Intrinsic::coro_suspend &&
2221c9157d92SDimitry Andric              SW->getDefaultDest() == &Dest;
2222c9157d92SDimitry Andric   return false;
2223c9157d92SDimitry Andric }
2224