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/Analysis/PostDominators.h"
250b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
260b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
270b57cec5SDimitry Andric #include "llvm/IR/Constants.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"
350b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
36*5f7ddb14SDimitry Andric #include "llvm/IR/PseudoProbe.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"
420b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
430b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
440b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
450b57cec5SDimitry Andric #include <cassert>
460b57cec5SDimitry Andric #include <cstdint>
470b57cec5SDimitry Andric #include <string>
480b57cec5SDimitry Andric #include <utility>
490b57cec5SDimitry Andric #include <vector>
500b57cec5SDimitry Andric
510b57cec5SDimitry Andric using namespace llvm;
520b57cec5SDimitry Andric
530b57cec5SDimitry Andric #define DEBUG_TYPE "basicblock-utils"
540b57cec5SDimitry Andric
DetatchDeadBlocks(ArrayRef<BasicBlock * > BBs,SmallVectorImpl<DominatorTree::UpdateType> * Updates,bool KeepOneInputPHIs)550b57cec5SDimitry Andric void llvm::DetatchDeadBlocks(
560b57cec5SDimitry Andric ArrayRef<BasicBlock *> BBs,
570b57cec5SDimitry Andric SmallVectorImpl<DominatorTree::UpdateType> *Updates,
580b57cec5SDimitry Andric bool KeepOneInputPHIs) {
590b57cec5SDimitry Andric for (auto *BB : BBs) {
600b57cec5SDimitry Andric // Loop through all of our successors and make sure they know that one
610b57cec5SDimitry Andric // of their predecessors is going away.
620b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
630b57cec5SDimitry Andric for (BasicBlock *Succ : successors(BB)) {
640b57cec5SDimitry Andric Succ->removePredecessor(BB, KeepOneInputPHIs);
650b57cec5SDimitry Andric if (Updates && UniqueSuccessors.insert(Succ).second)
660b57cec5SDimitry Andric Updates->push_back({DominatorTree::Delete, BB, Succ});
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric
690b57cec5SDimitry Andric // Zap all the instructions in the block.
700b57cec5SDimitry Andric while (!BB->empty()) {
710b57cec5SDimitry Andric Instruction &I = BB->back();
720b57cec5SDimitry Andric // If this instruction is used, replace uses with an arbitrary value.
730b57cec5SDimitry Andric // Because control flow can't get here, we don't care what we replace the
740b57cec5SDimitry Andric // value with. Note that since this block is unreachable, and all values
750b57cec5SDimitry Andric // contained within it must dominate their uses, that all uses will
760b57cec5SDimitry Andric // eventually be removed (they are themselves dead).
770b57cec5SDimitry Andric if (!I.use_empty())
780b57cec5SDimitry Andric I.replaceAllUsesWith(UndefValue::get(I.getType()));
790b57cec5SDimitry Andric BB->getInstList().pop_back();
800b57cec5SDimitry Andric }
810b57cec5SDimitry Andric new UnreachableInst(BB->getContext(), BB);
820b57cec5SDimitry Andric assert(BB->getInstList().size() == 1 &&
830b57cec5SDimitry Andric isa<UnreachableInst>(BB->getTerminator()) &&
840b57cec5SDimitry Andric "The successor list of BB isn't empty before "
850b57cec5SDimitry Andric "applying corresponding DTU updates.");
860b57cec5SDimitry Andric }
870b57cec5SDimitry Andric }
880b57cec5SDimitry Andric
DeleteDeadBlock(BasicBlock * BB,DomTreeUpdater * DTU,bool KeepOneInputPHIs)890b57cec5SDimitry Andric void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
900b57cec5SDimitry Andric bool KeepOneInputPHIs) {
910b57cec5SDimitry Andric DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric
DeleteDeadBlocks(ArrayRef<BasicBlock * > BBs,DomTreeUpdater * DTU,bool KeepOneInputPHIs)940b57cec5SDimitry Andric void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
950b57cec5SDimitry Andric bool KeepOneInputPHIs) {
960b57cec5SDimitry Andric #ifndef NDEBUG
970b57cec5SDimitry Andric // Make sure that all predecessors of each dead block is also dead.
980b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
990b57cec5SDimitry Andric assert(Dead.size() == BBs.size() && "Duplicating blocks?");
1000b57cec5SDimitry Andric for (auto *BB : Dead)
1010b57cec5SDimitry Andric for (BasicBlock *Pred : predecessors(BB))
1020b57cec5SDimitry Andric assert(Dead.count(Pred) && "All predecessors must be dead!");
1030b57cec5SDimitry Andric #endif
1040b57cec5SDimitry Andric
1050b57cec5SDimitry Andric SmallVector<DominatorTree::UpdateType, 4> Updates;
1060b57cec5SDimitry Andric DetatchDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
1070b57cec5SDimitry Andric
1080b57cec5SDimitry Andric if (DTU)
109af732203SDimitry Andric DTU->applyUpdates(Updates);
1100b57cec5SDimitry Andric
1110b57cec5SDimitry Andric for (BasicBlock *BB : BBs)
1120b57cec5SDimitry Andric if (DTU)
1130b57cec5SDimitry Andric DTU->deleteBB(BB);
1140b57cec5SDimitry Andric else
1150b57cec5SDimitry Andric BB->eraseFromParent();
1160b57cec5SDimitry Andric }
1170b57cec5SDimitry Andric
EliminateUnreachableBlocks(Function & F,DomTreeUpdater * DTU,bool KeepOneInputPHIs)1180b57cec5SDimitry Andric bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
1190b57cec5SDimitry Andric bool KeepOneInputPHIs) {
1200b57cec5SDimitry Andric df_iterator_default_set<BasicBlock*> Reachable;
1210b57cec5SDimitry Andric
1220b57cec5SDimitry Andric // Mark all reachable blocks.
1230b57cec5SDimitry Andric for (BasicBlock *BB : depth_first_ext(&F, Reachable))
1240b57cec5SDimitry Andric (void)BB/* Mark all reachable blocks */;
1250b57cec5SDimitry Andric
1260b57cec5SDimitry Andric // Collect all dead blocks.
1270b57cec5SDimitry Andric std::vector<BasicBlock*> DeadBlocks;
128*5f7ddb14SDimitry Andric for (BasicBlock &BB : F)
129*5f7ddb14SDimitry Andric if (!Reachable.count(&BB))
130*5f7ddb14SDimitry Andric DeadBlocks.push_back(&BB);
1310b57cec5SDimitry Andric
1320b57cec5SDimitry Andric // Delete the dead blocks.
1330b57cec5SDimitry Andric DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
1340b57cec5SDimitry Andric
1350b57cec5SDimitry Andric return !DeadBlocks.empty();
1360b57cec5SDimitry Andric }
1370b57cec5SDimitry Andric
FoldSingleEntryPHINodes(BasicBlock * BB,MemoryDependenceResults * MemDep)138af732203SDimitry Andric bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
1390b57cec5SDimitry Andric MemoryDependenceResults *MemDep) {
140af732203SDimitry Andric if (!isa<PHINode>(BB->begin()))
141af732203SDimitry Andric return false;
1420b57cec5SDimitry Andric
1430b57cec5SDimitry Andric while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1440b57cec5SDimitry Andric if (PN->getIncomingValue(0) != PN)
1450b57cec5SDimitry Andric PN->replaceAllUsesWith(PN->getIncomingValue(0));
1460b57cec5SDimitry Andric else
1470b57cec5SDimitry Andric PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1480b57cec5SDimitry Andric
1490b57cec5SDimitry Andric if (MemDep)
1500b57cec5SDimitry Andric MemDep->removeInstruction(PN); // Memdep updates AA itself.
1510b57cec5SDimitry Andric
1520b57cec5SDimitry Andric PN->eraseFromParent();
1530b57cec5SDimitry Andric }
154af732203SDimitry Andric return true;
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric
DeleteDeadPHIs(BasicBlock * BB,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU)1575ffd83dbSDimitry Andric bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI,
1585ffd83dbSDimitry Andric MemorySSAUpdater *MSSAU) {
1590b57cec5SDimitry Andric // Recursively deleting a PHI may cause multiple PHIs to be deleted
1600b57cec5SDimitry Andric // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
1610b57cec5SDimitry Andric SmallVector<WeakTrackingVH, 8> PHIs;
1620b57cec5SDimitry Andric for (PHINode &PN : BB->phis())
1630b57cec5SDimitry Andric PHIs.push_back(&PN);
1640b57cec5SDimitry Andric
1650b57cec5SDimitry Andric bool Changed = false;
1660b57cec5SDimitry Andric for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
1670b57cec5SDimitry Andric if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
1685ffd83dbSDimitry Andric Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
1690b57cec5SDimitry Andric
1700b57cec5SDimitry Andric return Changed;
1710b57cec5SDimitry Andric }
1720b57cec5SDimitry Andric
MergeBlockIntoPredecessor(BasicBlock * BB,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,MemoryDependenceResults * MemDep,bool PredecessorWithTwoSuccessors)1730b57cec5SDimitry Andric bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
1740b57cec5SDimitry Andric LoopInfo *LI, MemorySSAUpdater *MSSAU,
1758bcb0991SDimitry Andric MemoryDependenceResults *MemDep,
1768bcb0991SDimitry Andric bool PredecessorWithTwoSuccessors) {
1770b57cec5SDimitry Andric if (BB->hasAddressTaken())
1780b57cec5SDimitry Andric return false;
1790b57cec5SDimitry Andric
1800b57cec5SDimitry Andric // Can't merge if there are multiple predecessors, or no predecessors.
1810b57cec5SDimitry Andric BasicBlock *PredBB = BB->getUniquePredecessor();
1820b57cec5SDimitry Andric if (!PredBB) return false;
1830b57cec5SDimitry Andric
1840b57cec5SDimitry Andric // Don't break self-loops.
1850b57cec5SDimitry Andric if (PredBB == BB) return false;
1860b57cec5SDimitry Andric // Don't break unwinding instructions.
1870b57cec5SDimitry Andric if (PredBB->getTerminator()->isExceptionalTerminator())
1880b57cec5SDimitry Andric return false;
1890b57cec5SDimitry Andric
1900b57cec5SDimitry Andric // Can't merge if there are multiple distinct successors.
1918bcb0991SDimitry Andric if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
1920b57cec5SDimitry Andric return false;
1930b57cec5SDimitry Andric
1948bcb0991SDimitry Andric // Currently only allow PredBB to have two predecessors, one being BB.
1958bcb0991SDimitry Andric // Update BI to branch to BB's only successor instead of BB.
1968bcb0991SDimitry Andric BranchInst *PredBB_BI;
1978bcb0991SDimitry Andric BasicBlock *NewSucc = nullptr;
1988bcb0991SDimitry Andric unsigned FallThruPath;
1998bcb0991SDimitry Andric if (PredecessorWithTwoSuccessors) {
2008bcb0991SDimitry Andric if (!(PredBB_BI = dyn_cast<BranchInst>(PredBB->getTerminator())))
2018bcb0991SDimitry Andric return false;
2028bcb0991SDimitry Andric BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
2038bcb0991SDimitry Andric if (!BB_JmpI || !BB_JmpI->isUnconditional())
2048bcb0991SDimitry Andric return false;
2058bcb0991SDimitry Andric NewSucc = BB_JmpI->getSuccessor(0);
2068bcb0991SDimitry Andric FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
2078bcb0991SDimitry Andric }
2088bcb0991SDimitry Andric
2090b57cec5SDimitry Andric // Can't merge if there is PHI loop.
2100b57cec5SDimitry Andric for (PHINode &PN : BB->phis())
211*5f7ddb14SDimitry Andric if (llvm::is_contained(PN.incoming_values(), &PN))
2120b57cec5SDimitry Andric return false;
2130b57cec5SDimitry Andric
2140b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
2150b57cec5SDimitry Andric << PredBB->getName() << "\n");
2160b57cec5SDimitry Andric
2170b57cec5SDimitry Andric // Begin by getting rid of unneeded PHIs.
2180b57cec5SDimitry Andric SmallVector<AssertingVH<Value>, 4> IncomingValues;
2190b57cec5SDimitry Andric if (isa<PHINode>(BB->front())) {
2200b57cec5SDimitry Andric for (PHINode &PN : BB->phis())
2210b57cec5SDimitry Andric if (!isa<PHINode>(PN.getIncomingValue(0)) ||
2220b57cec5SDimitry Andric cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
2230b57cec5SDimitry Andric IncomingValues.push_back(PN.getIncomingValue(0));
2240b57cec5SDimitry Andric FoldSingleEntryPHINodes(BB, MemDep);
2250b57cec5SDimitry Andric }
2260b57cec5SDimitry Andric
2270b57cec5SDimitry Andric // DTU update: Collect all the edges that exit BB.
2280b57cec5SDimitry Andric // These dominator edges will be redirected from Pred.
2290b57cec5SDimitry Andric std::vector<DominatorTree::UpdateType> Updates;
2300b57cec5SDimitry Andric if (DTU) {
231*5f7ddb14SDimitry Andric SmallPtrSet<BasicBlock *, 2> SuccsOfBB(succ_begin(BB), succ_end(BB));
232*5f7ddb14SDimitry Andric SmallPtrSet<BasicBlock *, 2> SuccsOfPredBB(succ_begin(PredBB),
233*5f7ddb14SDimitry Andric succ_begin(PredBB));
234*5f7ddb14SDimitry Andric Updates.reserve(Updates.size() + 2 * SuccsOfBB.size() + 1);
2350b57cec5SDimitry Andric // Add insert edges first. Experimentally, for the particular case of two
2360b57cec5SDimitry Andric // blocks that can be merged, with a single successor and single predecessor
2370b57cec5SDimitry Andric // respectively, it is beneficial to have all insert updates first. Deleting
2380b57cec5SDimitry Andric // edges first may lead to unreachable blocks, followed by inserting edges
2390b57cec5SDimitry Andric // making the blocks reachable again. Such DT updates lead to high compile
2400b57cec5SDimitry Andric // times. We add inserts before deletes here to reduce compile time.
241*5f7ddb14SDimitry Andric for (BasicBlock *SuccOfBB : SuccsOfBB)
242*5f7ddb14SDimitry Andric // This successor of BB may already be a PredBB's successor.
243*5f7ddb14SDimitry Andric if (!SuccsOfPredBB.contains(SuccOfBB))
244*5f7ddb14SDimitry Andric Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
245*5f7ddb14SDimitry Andric for (BasicBlock *SuccOfBB : SuccsOfBB)
246*5f7ddb14SDimitry Andric Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
2470b57cec5SDimitry Andric Updates.push_back({DominatorTree::Delete, PredBB, BB});
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric
2508bcb0991SDimitry Andric Instruction *PTI = PredBB->getTerminator();
2518bcb0991SDimitry Andric Instruction *STI = BB->getTerminator();
2528bcb0991SDimitry Andric Instruction *Start = &*BB->begin();
2538bcb0991SDimitry Andric // If there's nothing to move, mark the starting instruction as the last
254480093f4SDimitry Andric // instruction in the block. Terminator instruction is handled separately.
2558bcb0991SDimitry Andric if (Start == STI)
2568bcb0991SDimitry Andric Start = PTI;
2570b57cec5SDimitry Andric
2588bcb0991SDimitry Andric // Move all definitions in the successor to the predecessor...
2598bcb0991SDimitry Andric PredBB->getInstList().splice(PTI->getIterator(), BB->getInstList(),
2608bcb0991SDimitry Andric BB->begin(), STI->getIterator());
2618bcb0991SDimitry Andric
2628bcb0991SDimitry Andric if (MSSAU)
2638bcb0991SDimitry Andric MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
2640b57cec5SDimitry Andric
2650b57cec5SDimitry Andric // Make all PHI nodes that referred to BB now refer to Pred as their
2660b57cec5SDimitry Andric // source...
2670b57cec5SDimitry Andric BB->replaceAllUsesWith(PredBB);
2680b57cec5SDimitry Andric
2698bcb0991SDimitry Andric if (PredecessorWithTwoSuccessors) {
2708bcb0991SDimitry Andric // Delete the unconditional branch from BB.
2718bcb0991SDimitry Andric BB->getInstList().pop_back();
2728bcb0991SDimitry Andric
2738bcb0991SDimitry Andric // Update branch in the predecessor.
2748bcb0991SDimitry Andric PredBB_BI->setSuccessor(FallThruPath, NewSucc);
2758bcb0991SDimitry Andric } else {
2768bcb0991SDimitry Andric // Delete the unconditional branch from the predecessor.
2778bcb0991SDimitry Andric PredBB->getInstList().pop_back();
2788bcb0991SDimitry Andric
2798bcb0991SDimitry Andric // Move terminator instruction.
2800b57cec5SDimitry Andric PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
281480093f4SDimitry Andric
282480093f4SDimitry Andric // Terminator may be a memory accessing instruction too.
283480093f4SDimitry Andric if (MSSAU)
284480093f4SDimitry Andric if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
285480093f4SDimitry Andric MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
286480093f4SDimitry Andric MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
2878bcb0991SDimitry Andric }
2888bcb0991SDimitry Andric // Add unreachable to now empty BB.
2890b57cec5SDimitry Andric new UnreachableInst(BB->getContext(), BB);
2900b57cec5SDimitry Andric
2910b57cec5SDimitry Andric // Inherit predecessors name if it exists.
2920b57cec5SDimitry Andric if (!PredBB->hasName())
2930b57cec5SDimitry Andric PredBB->takeName(BB);
2940b57cec5SDimitry Andric
2950b57cec5SDimitry Andric if (LI)
2960b57cec5SDimitry Andric LI->removeBlock(BB);
2970b57cec5SDimitry Andric
2980b57cec5SDimitry Andric if (MemDep)
2990b57cec5SDimitry Andric MemDep->invalidateCachedPredecessors();
3000b57cec5SDimitry Andric
301*5f7ddb14SDimitry Andric if (DTU)
302af732203SDimitry Andric DTU->applyUpdates(Updates);
303*5f7ddb14SDimitry Andric
304*5f7ddb14SDimitry Andric // Finally, erase the old block and update dominator info.
305*5f7ddb14SDimitry Andric DeleteDeadBlock(BB, DTU);
3068bcb0991SDimitry Andric
3070b57cec5SDimitry Andric return true;
3080b57cec5SDimitry Andric }
3090b57cec5SDimitry Andric
MergeBlockSuccessorsIntoGivenBlocks(SmallPtrSetImpl<BasicBlock * > & MergeBlocks,Loop * L,DomTreeUpdater * DTU,LoopInfo * LI)3105ffd83dbSDimitry Andric bool llvm::MergeBlockSuccessorsIntoGivenBlocks(
3115ffd83dbSDimitry Andric SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU,
3125ffd83dbSDimitry Andric LoopInfo *LI) {
3135ffd83dbSDimitry Andric assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
3145ffd83dbSDimitry Andric
3155ffd83dbSDimitry Andric bool BlocksHaveBeenMerged = false;
3165ffd83dbSDimitry Andric while (!MergeBlocks.empty()) {
3175ffd83dbSDimitry Andric BasicBlock *BB = *MergeBlocks.begin();
3185ffd83dbSDimitry Andric BasicBlock *Dest = BB->getSingleSuccessor();
3195ffd83dbSDimitry Andric if (Dest && (!L || L->contains(Dest))) {
3205ffd83dbSDimitry Andric BasicBlock *Fold = Dest->getUniquePredecessor();
3215ffd83dbSDimitry Andric (void)Fold;
3225ffd83dbSDimitry Andric if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
3235ffd83dbSDimitry Andric assert(Fold == BB &&
3245ffd83dbSDimitry Andric "Expecting BB to be unique predecessor of the Dest block");
3255ffd83dbSDimitry Andric MergeBlocks.erase(Dest);
3265ffd83dbSDimitry Andric BlocksHaveBeenMerged = true;
3275ffd83dbSDimitry Andric } else
3285ffd83dbSDimitry Andric MergeBlocks.erase(BB);
3295ffd83dbSDimitry Andric } else
3305ffd83dbSDimitry Andric MergeBlocks.erase(BB);
3315ffd83dbSDimitry Andric }
3325ffd83dbSDimitry Andric return BlocksHaveBeenMerged;
3335ffd83dbSDimitry Andric }
3345ffd83dbSDimitry Andric
335480093f4SDimitry Andric /// Remove redundant instructions within sequences of consecutive dbg.value
336480093f4SDimitry Andric /// instructions. This is done using a backward scan to keep the last dbg.value
337480093f4SDimitry Andric /// describing a specific variable/fragment.
338480093f4SDimitry Andric ///
339480093f4SDimitry Andric /// BackwardScan strategy:
340480093f4SDimitry Andric /// ----------------------
341480093f4SDimitry Andric /// Given a sequence of consecutive DbgValueInst like this
342480093f4SDimitry Andric ///
343480093f4SDimitry Andric /// dbg.value ..., "x", FragmentX1 (*)
344480093f4SDimitry Andric /// dbg.value ..., "y", FragmentY1
345480093f4SDimitry Andric /// dbg.value ..., "x", FragmentX2
346480093f4SDimitry Andric /// dbg.value ..., "x", FragmentX1 (**)
347480093f4SDimitry Andric ///
348480093f4SDimitry Andric /// then the instruction marked with (*) can be removed (it is guaranteed to be
349480093f4SDimitry Andric /// obsoleted by the instruction marked with (**) as the latter instruction is
350480093f4SDimitry Andric /// describing the same variable using the same fragment info).
351480093f4SDimitry Andric ///
352480093f4SDimitry Andric /// Possible improvements:
353480093f4SDimitry Andric /// - Check fully overlapping fragments and not only identical fragments.
354480093f4SDimitry Andric /// - Support dbg.addr, dbg.declare. dbg.label, and possibly other meta
355480093f4SDimitry Andric /// instructions being part of the sequence of consecutive instructions.
removeRedundantDbgInstrsUsingBackwardScan(BasicBlock * BB)356480093f4SDimitry Andric static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
357480093f4SDimitry Andric SmallVector<DbgValueInst *, 8> ToBeRemoved;
358480093f4SDimitry Andric SmallDenseSet<DebugVariable> VariableSet;
359480093f4SDimitry Andric for (auto &I : reverse(*BB)) {
360480093f4SDimitry Andric if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
361480093f4SDimitry Andric DebugVariable Key(DVI->getVariable(),
362480093f4SDimitry Andric DVI->getExpression(),
363480093f4SDimitry Andric DVI->getDebugLoc()->getInlinedAt());
364480093f4SDimitry Andric auto R = VariableSet.insert(Key);
365480093f4SDimitry Andric // If the same variable fragment is described more than once it is enough
366480093f4SDimitry Andric // to keep the last one (i.e. the first found since we for reverse
367480093f4SDimitry Andric // iteration).
368480093f4SDimitry Andric if (!R.second)
369480093f4SDimitry Andric ToBeRemoved.push_back(DVI);
370480093f4SDimitry Andric continue;
371480093f4SDimitry Andric }
372480093f4SDimitry Andric // Sequence with consecutive dbg.value instrs ended. Clear the map to
373480093f4SDimitry Andric // restart identifying redundant instructions if case we find another
374480093f4SDimitry Andric // dbg.value sequence.
375480093f4SDimitry Andric VariableSet.clear();
376480093f4SDimitry Andric }
377480093f4SDimitry Andric
378480093f4SDimitry Andric for (auto &Instr : ToBeRemoved)
379480093f4SDimitry Andric Instr->eraseFromParent();
380480093f4SDimitry Andric
381480093f4SDimitry Andric return !ToBeRemoved.empty();
382480093f4SDimitry Andric }
383480093f4SDimitry Andric
384480093f4SDimitry Andric /// Remove redundant dbg.value instructions using a forward scan. This can
385480093f4SDimitry Andric /// remove a dbg.value instruction that is redundant due to indicating that a
386480093f4SDimitry Andric /// variable has the same value as already being indicated by an earlier
387480093f4SDimitry Andric /// dbg.value.
388480093f4SDimitry Andric ///
389480093f4SDimitry Andric /// ForwardScan strategy:
390480093f4SDimitry Andric /// ---------------------
391480093f4SDimitry Andric /// Given two identical dbg.value instructions, separated by a block of
392480093f4SDimitry Andric /// instructions that isn't describing the same variable, like this
393480093f4SDimitry Andric ///
394480093f4SDimitry Andric /// dbg.value X1, "x", FragmentX1 (**)
395480093f4SDimitry Andric /// <block of instructions, none being "dbg.value ..., "x", ...">
396480093f4SDimitry Andric /// dbg.value X1, "x", FragmentX1 (*)
397480093f4SDimitry Andric ///
398480093f4SDimitry Andric /// then the instruction marked with (*) can be removed. Variable "x" is already
399480093f4SDimitry Andric /// described as being mapped to the SSA value X1.
400480093f4SDimitry Andric ///
401480093f4SDimitry Andric /// Possible improvements:
402480093f4SDimitry Andric /// - Keep track of non-overlapping fragments.
removeRedundantDbgInstrsUsingForwardScan(BasicBlock * BB)403480093f4SDimitry Andric static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
404480093f4SDimitry Andric SmallVector<DbgValueInst *, 8> ToBeRemoved;
405*5f7ddb14SDimitry Andric DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
406*5f7ddb14SDimitry Andric VariableMap;
407480093f4SDimitry Andric for (auto &I : *BB) {
408480093f4SDimitry Andric if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
409480093f4SDimitry Andric DebugVariable Key(DVI->getVariable(),
410480093f4SDimitry Andric NoneType(),
411480093f4SDimitry Andric DVI->getDebugLoc()->getInlinedAt());
412480093f4SDimitry Andric auto VMI = VariableMap.find(Key);
413480093f4SDimitry Andric // Update the map if we found a new value/expression describing the
414480093f4SDimitry Andric // variable, or if the variable wasn't mapped already.
415*5f7ddb14SDimitry Andric SmallVector<Value *, 4> Values(DVI->getValues());
416*5f7ddb14SDimitry Andric if (VMI == VariableMap.end() || VMI->second.first != Values ||
417480093f4SDimitry Andric VMI->second.second != DVI->getExpression()) {
418*5f7ddb14SDimitry Andric VariableMap[Key] = {Values, DVI->getExpression()};
419480093f4SDimitry Andric continue;
420480093f4SDimitry Andric }
421480093f4SDimitry Andric // Found an identical mapping. Remember the instruction for later removal.
422480093f4SDimitry Andric ToBeRemoved.push_back(DVI);
423480093f4SDimitry Andric }
424480093f4SDimitry Andric }
425480093f4SDimitry Andric
426480093f4SDimitry Andric for (auto &Instr : ToBeRemoved)
427480093f4SDimitry Andric Instr->eraseFromParent();
428480093f4SDimitry Andric
429480093f4SDimitry Andric return !ToBeRemoved.empty();
430480093f4SDimitry Andric }
431480093f4SDimitry Andric
RemoveRedundantDbgInstrs(BasicBlock * BB)432480093f4SDimitry Andric bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) {
433480093f4SDimitry Andric bool MadeChanges = false;
434480093f4SDimitry Andric // By using the "backward scan" strategy before the "forward scan" strategy we
435480093f4SDimitry Andric // can remove both dbg.value (2) and (3) in a situation like this:
436480093f4SDimitry Andric //
437480093f4SDimitry Andric // (1) dbg.value V1, "x", DIExpression()
438480093f4SDimitry Andric // ...
439480093f4SDimitry Andric // (2) dbg.value V2, "x", DIExpression()
440480093f4SDimitry Andric // (3) dbg.value V1, "x", DIExpression()
441480093f4SDimitry Andric //
442480093f4SDimitry Andric // The backward scan will remove (2), it is made obsolete by (3). After
443480093f4SDimitry Andric // getting (2) out of the way, the foward scan will remove (3) since "x"
444480093f4SDimitry Andric // already is described as having the value V1 at (1).
445480093f4SDimitry Andric MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB);
446480093f4SDimitry Andric MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB);
447480093f4SDimitry Andric
448480093f4SDimitry Andric if (MadeChanges)
449480093f4SDimitry Andric LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
450480093f4SDimitry Andric << BB->getName() << "\n");
451480093f4SDimitry Andric return MadeChanges;
452480093f4SDimitry Andric }
453480093f4SDimitry Andric
ReplaceInstWithValue(BasicBlock::InstListType & BIL,BasicBlock::iterator & BI,Value * V)4540b57cec5SDimitry Andric void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
4550b57cec5SDimitry Andric BasicBlock::iterator &BI, Value *V) {
4560b57cec5SDimitry Andric Instruction &I = *BI;
4570b57cec5SDimitry Andric // Replaces all of the uses of the instruction with uses of the value
4580b57cec5SDimitry Andric I.replaceAllUsesWith(V);
4590b57cec5SDimitry Andric
4600b57cec5SDimitry Andric // Make sure to propagate a name if there is one already.
4610b57cec5SDimitry Andric if (I.hasName() && !V->hasName())
4620b57cec5SDimitry Andric V->takeName(&I);
4630b57cec5SDimitry Andric
4640b57cec5SDimitry Andric // Delete the unnecessary instruction now...
4650b57cec5SDimitry Andric BI = BIL.erase(BI);
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric
ReplaceInstWithInst(BasicBlock::InstListType & BIL,BasicBlock::iterator & BI,Instruction * I)4680b57cec5SDimitry Andric void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
4690b57cec5SDimitry Andric BasicBlock::iterator &BI, Instruction *I) {
4700b57cec5SDimitry Andric assert(I->getParent() == nullptr &&
4710b57cec5SDimitry Andric "ReplaceInstWithInst: Instruction already inserted into basic block!");
4720b57cec5SDimitry Andric
4730b57cec5SDimitry Andric // Copy debug location to newly added instruction, if it wasn't already set
4740b57cec5SDimitry Andric // by the caller.
4750b57cec5SDimitry Andric if (!I->getDebugLoc())
4760b57cec5SDimitry Andric I->setDebugLoc(BI->getDebugLoc());
4770b57cec5SDimitry Andric
4780b57cec5SDimitry Andric // Insert the new instruction into the basic block...
4790b57cec5SDimitry Andric BasicBlock::iterator New = BIL.insert(BI, I);
4800b57cec5SDimitry Andric
4810b57cec5SDimitry Andric // Replace all uses of the old instruction, and delete it.
4820b57cec5SDimitry Andric ReplaceInstWithValue(BIL, BI, I);
4830b57cec5SDimitry Andric
4840b57cec5SDimitry Andric // Move BI back to point to the newly inserted instruction
4850b57cec5SDimitry Andric BI = New;
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric
ReplaceInstWithInst(Instruction * From,Instruction * To)4880b57cec5SDimitry Andric void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
4890b57cec5SDimitry Andric BasicBlock::iterator BI(From);
4900b57cec5SDimitry Andric ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
4910b57cec5SDimitry Andric }
4920b57cec5SDimitry Andric
SplitEdge(BasicBlock * BB,BasicBlock * Succ,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName)4930b57cec5SDimitry Andric BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
494af732203SDimitry Andric LoopInfo *LI, MemorySSAUpdater *MSSAU,
495af732203SDimitry Andric const Twine &BBName) {
4960b57cec5SDimitry Andric unsigned SuccNum = GetSuccessorNumber(BB, Succ);
4970b57cec5SDimitry Andric
4980b57cec5SDimitry Andric Instruction *LatchTerm = BB->getTerminator();
499*5f7ddb14SDimitry Andric
500*5f7ddb14SDimitry Andric CriticalEdgeSplittingOptions Options =
501*5f7ddb14SDimitry Andric CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA();
502*5f7ddb14SDimitry Andric
503*5f7ddb14SDimitry Andric if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
504*5f7ddb14SDimitry Andric // If it is a critical edge, and the succesor is an exception block, handle
505*5f7ddb14SDimitry Andric // the split edge logic in this specific function
506*5f7ddb14SDimitry Andric if (Succ->isEHPad())
507*5f7ddb14SDimitry Andric return ehAwareSplitEdge(BB, Succ, nullptr, nullptr, Options, BBName);
508*5f7ddb14SDimitry Andric
509*5f7ddb14SDimitry Andric // If this is a critical edge, let SplitKnownCriticalEdge do it.
510*5f7ddb14SDimitry Andric return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
511*5f7ddb14SDimitry Andric }
5120b57cec5SDimitry Andric
5130b57cec5SDimitry Andric // If the edge isn't critical, then BB has a single successor or Succ has a
5140b57cec5SDimitry Andric // single pred. Split the block.
5150b57cec5SDimitry Andric if (BasicBlock *SP = Succ->getSinglePredecessor()) {
5160b57cec5SDimitry Andric // If the successor only has a single pred, split the top of the successor
5170b57cec5SDimitry Andric // block.
5180b57cec5SDimitry Andric assert(SP == BB && "CFG broken");
5190b57cec5SDimitry Andric SP = nullptr;
520af732203SDimitry Andric return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
521af732203SDimitry Andric /*Before=*/true);
5220b57cec5SDimitry Andric }
5230b57cec5SDimitry Andric
5240b57cec5SDimitry Andric // Otherwise, if BB has a single successor, split it at the bottom of the
5250b57cec5SDimitry Andric // block.
5260b57cec5SDimitry Andric assert(BB->getTerminator()->getNumSuccessors() == 1 &&
5270b57cec5SDimitry Andric "Should have a single succ!");
528af732203SDimitry Andric return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
5290b57cec5SDimitry Andric }
5300b57cec5SDimitry Andric
setUnwindEdgeTo(Instruction * TI,BasicBlock * Succ)531*5f7ddb14SDimitry Andric void llvm::setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
532*5f7ddb14SDimitry Andric if (auto *II = dyn_cast<InvokeInst>(TI))
533*5f7ddb14SDimitry Andric II->setUnwindDest(Succ);
534*5f7ddb14SDimitry Andric else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
535*5f7ddb14SDimitry Andric CS->setUnwindDest(Succ);
536*5f7ddb14SDimitry Andric else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
537*5f7ddb14SDimitry Andric CR->setUnwindDest(Succ);
538*5f7ddb14SDimitry Andric else
539*5f7ddb14SDimitry Andric llvm_unreachable("unexpected terminator instruction");
540*5f7ddb14SDimitry Andric }
541*5f7ddb14SDimitry Andric
updatePhiNodes(BasicBlock * DestBB,BasicBlock * OldPred,BasicBlock * NewPred,PHINode * Until)542*5f7ddb14SDimitry Andric void llvm::updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
543*5f7ddb14SDimitry Andric BasicBlock *NewPred, PHINode *Until) {
544*5f7ddb14SDimitry Andric int BBIdx = 0;
545*5f7ddb14SDimitry Andric for (PHINode &PN : DestBB->phis()) {
546*5f7ddb14SDimitry Andric // We manually update the LandingPadReplacement PHINode and it is the last
547*5f7ddb14SDimitry Andric // PHI Node. So, if we find it, we are done.
548*5f7ddb14SDimitry Andric if (Until == &PN)
549*5f7ddb14SDimitry Andric break;
550*5f7ddb14SDimitry Andric
551*5f7ddb14SDimitry Andric // Reuse the previous value of BBIdx if it lines up. In cases where we
552*5f7ddb14SDimitry Andric // have multiple phi nodes with *lots* of predecessors, this is a speed
553*5f7ddb14SDimitry Andric // win because we don't have to scan the PHI looking for TIBB. This
554*5f7ddb14SDimitry Andric // happens because the BB list of PHI nodes are usually in the same
555*5f7ddb14SDimitry Andric // order.
556*5f7ddb14SDimitry Andric if (PN.getIncomingBlock(BBIdx) != OldPred)
557*5f7ddb14SDimitry Andric BBIdx = PN.getBasicBlockIndex(OldPred);
558*5f7ddb14SDimitry Andric
559*5f7ddb14SDimitry Andric assert(BBIdx != -1 && "Invalid PHI Index!");
560*5f7ddb14SDimitry Andric PN.setIncomingBlock(BBIdx, NewPred);
561*5f7ddb14SDimitry Andric }
562*5f7ddb14SDimitry Andric }
563*5f7ddb14SDimitry Andric
ehAwareSplitEdge(BasicBlock * BB,BasicBlock * Succ,LandingPadInst * OriginalPad,PHINode * LandingPadReplacement,const CriticalEdgeSplittingOptions & Options,const Twine & BBName)564*5f7ddb14SDimitry Andric BasicBlock *llvm::ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
565*5f7ddb14SDimitry Andric LandingPadInst *OriginalPad,
566*5f7ddb14SDimitry Andric PHINode *LandingPadReplacement,
567*5f7ddb14SDimitry Andric const CriticalEdgeSplittingOptions &Options,
568*5f7ddb14SDimitry Andric const Twine &BBName) {
569*5f7ddb14SDimitry Andric
570*5f7ddb14SDimitry Andric auto *PadInst = Succ->getFirstNonPHI();
571*5f7ddb14SDimitry Andric if (!LandingPadReplacement && !PadInst->isEHPad())
572*5f7ddb14SDimitry Andric return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
573*5f7ddb14SDimitry Andric
574*5f7ddb14SDimitry Andric auto *LI = Options.LI;
575*5f7ddb14SDimitry Andric SmallVector<BasicBlock *, 4> LoopPreds;
576*5f7ddb14SDimitry Andric // Check if extra modifications will be required to preserve loop-simplify
577*5f7ddb14SDimitry Andric // form after splitting. If it would require splitting blocks with IndirectBr
578*5f7ddb14SDimitry Andric // terminators, bail out if preserving loop-simplify form is requested.
579*5f7ddb14SDimitry Andric if (Options.PreserveLoopSimplify && LI) {
580*5f7ddb14SDimitry Andric if (Loop *BBLoop = LI->getLoopFor(BB)) {
581*5f7ddb14SDimitry Andric
582*5f7ddb14SDimitry Andric // The only way that we can break LoopSimplify form by splitting a
583*5f7ddb14SDimitry Andric // critical edge is when there exists some edge from BBLoop to Succ *and*
584*5f7ddb14SDimitry Andric // the only edge into Succ from outside of BBLoop is that of NewBB after
585*5f7ddb14SDimitry Andric // the split. If the first isn't true, then LoopSimplify still holds,
586*5f7ddb14SDimitry Andric // NewBB is the new exit block and it has no non-loop predecessors. If the
587*5f7ddb14SDimitry Andric // second isn't true, then Succ was not in LoopSimplify form prior to
588*5f7ddb14SDimitry Andric // the split as it had a non-loop predecessor. In both of these cases,
589*5f7ddb14SDimitry Andric // the predecessor must be directly in BBLoop, not in a subloop, or again
590*5f7ddb14SDimitry Andric // LoopSimplify doesn't hold.
591*5f7ddb14SDimitry Andric for (BasicBlock *P : predecessors(Succ)) {
592*5f7ddb14SDimitry Andric if (P == BB)
593*5f7ddb14SDimitry Andric continue; // The new block is known.
594*5f7ddb14SDimitry Andric if (LI->getLoopFor(P) != BBLoop) {
595*5f7ddb14SDimitry Andric // Loop is not in LoopSimplify form, no need to re simplify after
596*5f7ddb14SDimitry Andric // splitting edge.
597*5f7ddb14SDimitry Andric LoopPreds.clear();
598*5f7ddb14SDimitry Andric break;
599*5f7ddb14SDimitry Andric }
600*5f7ddb14SDimitry Andric LoopPreds.push_back(P);
601*5f7ddb14SDimitry Andric }
602*5f7ddb14SDimitry Andric // Loop-simplify form can be preserved, if we can split all in-loop
603*5f7ddb14SDimitry Andric // predecessors.
604*5f7ddb14SDimitry Andric if (any_of(LoopPreds, [](BasicBlock *Pred) {
605*5f7ddb14SDimitry Andric return isa<IndirectBrInst>(Pred->getTerminator());
606*5f7ddb14SDimitry Andric })) {
607*5f7ddb14SDimitry Andric return nullptr;
608*5f7ddb14SDimitry Andric }
609*5f7ddb14SDimitry Andric }
610*5f7ddb14SDimitry Andric }
611*5f7ddb14SDimitry Andric
612*5f7ddb14SDimitry Andric auto *NewBB =
613*5f7ddb14SDimitry Andric BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
614*5f7ddb14SDimitry Andric setUnwindEdgeTo(BB->getTerminator(), NewBB);
615*5f7ddb14SDimitry Andric updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
616*5f7ddb14SDimitry Andric
617*5f7ddb14SDimitry Andric if (LandingPadReplacement) {
618*5f7ddb14SDimitry Andric auto *NewLP = OriginalPad->clone();
619*5f7ddb14SDimitry Andric auto *Terminator = BranchInst::Create(Succ, NewBB);
620*5f7ddb14SDimitry Andric NewLP->insertBefore(Terminator);
621*5f7ddb14SDimitry Andric LandingPadReplacement->addIncoming(NewLP, NewBB);
622*5f7ddb14SDimitry Andric } else {
623*5f7ddb14SDimitry Andric Value *ParentPad = nullptr;
624*5f7ddb14SDimitry Andric if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
625*5f7ddb14SDimitry Andric ParentPad = FuncletPad->getParentPad();
626*5f7ddb14SDimitry Andric else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
627*5f7ddb14SDimitry Andric ParentPad = CatchSwitch->getParentPad();
628*5f7ddb14SDimitry Andric else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
629*5f7ddb14SDimitry Andric ParentPad = CleanupPad->getParentPad();
630*5f7ddb14SDimitry Andric else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
631*5f7ddb14SDimitry Andric ParentPad = LandingPad->getParent();
632*5f7ddb14SDimitry Andric else
633*5f7ddb14SDimitry Andric llvm_unreachable("handling for other EHPads not implemented yet");
634*5f7ddb14SDimitry Andric
635*5f7ddb14SDimitry Andric auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
636*5f7ddb14SDimitry Andric CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
637*5f7ddb14SDimitry Andric }
638*5f7ddb14SDimitry Andric
639*5f7ddb14SDimitry Andric auto *DT = Options.DT;
640*5f7ddb14SDimitry Andric auto *MSSAU = Options.MSSAU;
641*5f7ddb14SDimitry Andric if (!DT && !LI)
642*5f7ddb14SDimitry Andric return NewBB;
643*5f7ddb14SDimitry Andric
644*5f7ddb14SDimitry Andric if (DT) {
645*5f7ddb14SDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
646*5f7ddb14SDimitry Andric SmallVector<DominatorTree::UpdateType, 3> Updates;
647*5f7ddb14SDimitry Andric
648*5f7ddb14SDimitry Andric Updates.push_back({DominatorTree::Insert, BB, NewBB});
649*5f7ddb14SDimitry Andric Updates.push_back({DominatorTree::Insert, NewBB, Succ});
650*5f7ddb14SDimitry Andric Updates.push_back({DominatorTree::Delete, BB, Succ});
651*5f7ddb14SDimitry Andric
652*5f7ddb14SDimitry Andric DTU.applyUpdates(Updates);
653*5f7ddb14SDimitry Andric DTU.flush();
654*5f7ddb14SDimitry Andric
655*5f7ddb14SDimitry Andric if (MSSAU) {
656*5f7ddb14SDimitry Andric MSSAU->applyUpdates(Updates, *DT);
657*5f7ddb14SDimitry Andric if (VerifyMemorySSA)
658*5f7ddb14SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
659*5f7ddb14SDimitry Andric }
660*5f7ddb14SDimitry Andric }
661*5f7ddb14SDimitry Andric
662*5f7ddb14SDimitry Andric if (LI) {
663*5f7ddb14SDimitry Andric if (Loop *BBLoop = LI->getLoopFor(BB)) {
664*5f7ddb14SDimitry Andric // If one or the other blocks were not in a loop, the new block is not
665*5f7ddb14SDimitry Andric // either, and thus LI doesn't need to be updated.
666*5f7ddb14SDimitry Andric if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
667*5f7ddb14SDimitry Andric if (BBLoop == SuccLoop) {
668*5f7ddb14SDimitry Andric // Both in the same loop, the NewBB joins loop.
669*5f7ddb14SDimitry Andric SuccLoop->addBasicBlockToLoop(NewBB, *LI);
670*5f7ddb14SDimitry Andric } else if (BBLoop->contains(SuccLoop)) {
671*5f7ddb14SDimitry Andric // Edge from an outer loop to an inner loop. Add to the outer loop.
672*5f7ddb14SDimitry Andric BBLoop->addBasicBlockToLoop(NewBB, *LI);
673*5f7ddb14SDimitry Andric } else if (SuccLoop->contains(BBLoop)) {
674*5f7ddb14SDimitry Andric // Edge from an inner loop to an outer loop. Add to the outer loop.
675*5f7ddb14SDimitry Andric SuccLoop->addBasicBlockToLoop(NewBB, *LI);
676*5f7ddb14SDimitry Andric } else {
677*5f7ddb14SDimitry Andric // Edge from two loops with no containment relation. Because these
678*5f7ddb14SDimitry Andric // are natural loops, we know that the destination block must be the
679*5f7ddb14SDimitry Andric // header of its loop (adding a branch into a loop elsewhere would
680*5f7ddb14SDimitry Andric // create an irreducible loop).
681*5f7ddb14SDimitry Andric assert(SuccLoop->getHeader() == Succ &&
682*5f7ddb14SDimitry Andric "Should not create irreducible loops!");
683*5f7ddb14SDimitry Andric if (Loop *P = SuccLoop->getParentLoop())
684*5f7ddb14SDimitry Andric P->addBasicBlockToLoop(NewBB, *LI);
685*5f7ddb14SDimitry Andric }
686*5f7ddb14SDimitry Andric }
687*5f7ddb14SDimitry Andric
688*5f7ddb14SDimitry Andric // If BB is in a loop and Succ is outside of that loop, we may need to
689*5f7ddb14SDimitry Andric // update LoopSimplify form and LCSSA form.
690*5f7ddb14SDimitry Andric if (!BBLoop->contains(Succ)) {
691*5f7ddb14SDimitry Andric assert(!BBLoop->contains(NewBB) &&
692*5f7ddb14SDimitry Andric "Split point for loop exit is contained in loop!");
693*5f7ddb14SDimitry Andric
694*5f7ddb14SDimitry Andric // Update LCSSA form in the newly created exit block.
695*5f7ddb14SDimitry Andric if (Options.PreserveLCSSA) {
696*5f7ddb14SDimitry Andric createPHIsForSplitLoopExit(BB, NewBB, Succ);
697*5f7ddb14SDimitry Andric }
698*5f7ddb14SDimitry Andric
699*5f7ddb14SDimitry Andric if (!LoopPreds.empty()) {
700*5f7ddb14SDimitry Andric BasicBlock *NewExitBB = SplitBlockPredecessors(
701*5f7ddb14SDimitry Andric Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
702*5f7ddb14SDimitry Andric if (Options.PreserveLCSSA)
703*5f7ddb14SDimitry Andric createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
704*5f7ddb14SDimitry Andric }
705*5f7ddb14SDimitry Andric }
706*5f7ddb14SDimitry Andric }
707*5f7ddb14SDimitry Andric }
708*5f7ddb14SDimitry Andric
709*5f7ddb14SDimitry Andric return NewBB;
710*5f7ddb14SDimitry Andric }
711*5f7ddb14SDimitry Andric
createPHIsForSplitLoopExit(ArrayRef<BasicBlock * > Preds,BasicBlock * SplitBB,BasicBlock * DestBB)712*5f7ddb14SDimitry Andric void llvm::createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
713*5f7ddb14SDimitry Andric BasicBlock *SplitBB, BasicBlock *DestBB) {
714*5f7ddb14SDimitry Andric // SplitBB shouldn't have anything non-trivial in it yet.
715*5f7ddb14SDimitry Andric assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
716*5f7ddb14SDimitry Andric SplitBB->isLandingPad()) &&
717*5f7ddb14SDimitry Andric "SplitBB has non-PHI nodes!");
718*5f7ddb14SDimitry Andric
719*5f7ddb14SDimitry Andric // For each PHI in the destination block.
720*5f7ddb14SDimitry Andric for (PHINode &PN : DestBB->phis()) {
721*5f7ddb14SDimitry Andric int Idx = PN.getBasicBlockIndex(SplitBB);
722*5f7ddb14SDimitry Andric assert(Idx >= 0 && "Invalid Block Index");
723*5f7ddb14SDimitry Andric Value *V = PN.getIncomingValue(Idx);
724*5f7ddb14SDimitry Andric
725*5f7ddb14SDimitry Andric // If the input is a PHI which already satisfies LCSSA, don't create
726*5f7ddb14SDimitry Andric // a new one.
727*5f7ddb14SDimitry Andric if (const PHINode *VP = dyn_cast<PHINode>(V))
728*5f7ddb14SDimitry Andric if (VP->getParent() == SplitBB)
729*5f7ddb14SDimitry Andric continue;
730*5f7ddb14SDimitry Andric
731*5f7ddb14SDimitry Andric // Otherwise a new PHI is needed. Create one and populate it.
732*5f7ddb14SDimitry Andric PHINode *NewPN = PHINode::Create(
733*5f7ddb14SDimitry Andric PN.getType(), Preds.size(), "split",
734*5f7ddb14SDimitry Andric SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
735*5f7ddb14SDimitry Andric for (BasicBlock *BB : Preds)
736*5f7ddb14SDimitry Andric NewPN->addIncoming(V, BB);
737*5f7ddb14SDimitry Andric
738*5f7ddb14SDimitry Andric // Update the original PHI.
739*5f7ddb14SDimitry Andric PN.setIncomingValue(Idx, NewPN);
740*5f7ddb14SDimitry Andric }
741*5f7ddb14SDimitry Andric }
742*5f7ddb14SDimitry Andric
7430b57cec5SDimitry Andric unsigned
SplitAllCriticalEdges(Function & F,const CriticalEdgeSplittingOptions & Options)7440b57cec5SDimitry Andric llvm::SplitAllCriticalEdges(Function &F,
7450b57cec5SDimitry Andric const CriticalEdgeSplittingOptions &Options) {
7460b57cec5SDimitry Andric unsigned NumBroken = 0;
7470b57cec5SDimitry Andric for (BasicBlock &BB : F) {
7480b57cec5SDimitry Andric Instruction *TI = BB.getTerminator();
74947395794SDimitry Andric if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI) &&
75047395794SDimitry Andric !isa<CallBrInst>(TI))
7510b57cec5SDimitry Andric for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
7520b57cec5SDimitry Andric if (SplitCriticalEdge(TI, i, Options))
7530b57cec5SDimitry Andric ++NumBroken;
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric return NumBroken;
7560b57cec5SDimitry Andric }
7570b57cec5SDimitry Andric
SplitBlockImpl(BasicBlock * Old,Instruction * SplitPt,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)758af732203SDimitry Andric static BasicBlock *SplitBlockImpl(BasicBlock *Old, Instruction *SplitPt,
759af732203SDimitry Andric DomTreeUpdater *DTU, DominatorTree *DT,
760af732203SDimitry Andric LoopInfo *LI, MemorySSAUpdater *MSSAU,
761af732203SDimitry Andric const Twine &BBName, bool Before) {
762af732203SDimitry Andric if (Before) {
763af732203SDimitry Andric DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
764af732203SDimitry Andric return splitBlockBefore(Old, SplitPt,
765af732203SDimitry Andric DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
766af732203SDimitry Andric BBName);
767af732203SDimitry Andric }
7680b57cec5SDimitry Andric BasicBlock::iterator SplitIt = SplitPt->getIterator();
769*5f7ddb14SDimitry Andric while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
7700b57cec5SDimitry Andric ++SplitIt;
771*5f7ddb14SDimitry Andric assert(SplitIt != SplitPt->getParent()->end());
772*5f7ddb14SDimitry Andric }
7738bcb0991SDimitry Andric std::string Name = BBName.str();
7748bcb0991SDimitry Andric BasicBlock *New = Old->splitBasicBlock(
7758bcb0991SDimitry Andric SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
7760b57cec5SDimitry Andric
7770b57cec5SDimitry Andric // The new block lives in whichever loop the old one did. This preserves
7780b57cec5SDimitry Andric // LCSSA as well, because we force the split point to be after any PHI nodes.
7790b57cec5SDimitry Andric if (LI)
7800b57cec5SDimitry Andric if (Loop *L = LI->getLoopFor(Old))
7810b57cec5SDimitry Andric L->addBasicBlockToLoop(New, *LI);
7820b57cec5SDimitry Andric
783af732203SDimitry Andric if (DTU) {
784af732203SDimitry Andric SmallVector<DominatorTree::UpdateType, 8> Updates;
785af732203SDimitry Andric // Old dominates New. New node dominates all other nodes dominated by Old.
786*5f7ddb14SDimitry Andric SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld(succ_begin(New),
787af732203SDimitry Andric succ_end(New));
788af732203SDimitry Andric Updates.push_back({DominatorTree::Insert, Old, New});
789af732203SDimitry Andric Updates.reserve(Updates.size() + 2 * UniqueSuccessorsOfOld.size());
790af732203SDimitry Andric for (BasicBlock *UniqueSuccessorOfOld : UniqueSuccessorsOfOld) {
791af732203SDimitry Andric Updates.push_back({DominatorTree::Insert, New, UniqueSuccessorOfOld});
792af732203SDimitry Andric Updates.push_back({DominatorTree::Delete, Old, UniqueSuccessorOfOld});
793af732203SDimitry Andric }
794af732203SDimitry Andric
795af732203SDimitry Andric DTU->applyUpdates(Updates);
796af732203SDimitry Andric } else if (DT)
7970b57cec5SDimitry Andric // Old dominates New. New node dominates all other nodes dominated by Old.
7980b57cec5SDimitry Andric if (DomTreeNode *OldNode = DT->getNode(Old)) {
7990b57cec5SDimitry Andric std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
8000b57cec5SDimitry Andric
8010b57cec5SDimitry Andric DomTreeNode *NewNode = DT->addNewBlock(New, Old);
8020b57cec5SDimitry Andric for (DomTreeNode *I : Children)
8030b57cec5SDimitry Andric DT->changeImmediateDominator(I, NewNode);
8040b57cec5SDimitry Andric }
8050b57cec5SDimitry Andric
8060b57cec5SDimitry Andric // Move MemoryAccesses still tracked in Old, but part of New now.
8070b57cec5SDimitry Andric // Update accesses in successor blocks accordingly.
8080b57cec5SDimitry Andric if (MSSAU)
8090b57cec5SDimitry Andric MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
8100b57cec5SDimitry Andric
8110b57cec5SDimitry Andric return New;
8120b57cec5SDimitry Andric }
8130b57cec5SDimitry Andric
SplitBlock(BasicBlock * Old,Instruction * SplitPt,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)814af732203SDimitry Andric BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
815af732203SDimitry Andric DominatorTree *DT, LoopInfo *LI,
816af732203SDimitry Andric MemorySSAUpdater *MSSAU, const Twine &BBName,
817af732203SDimitry Andric bool Before) {
818af732203SDimitry Andric return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
819af732203SDimitry Andric Before);
820af732203SDimitry Andric }
SplitBlock(BasicBlock * Old,Instruction * SplitPt,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)821af732203SDimitry Andric BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
822af732203SDimitry Andric DomTreeUpdater *DTU, LoopInfo *LI,
823af732203SDimitry Andric MemorySSAUpdater *MSSAU, const Twine &BBName,
824af732203SDimitry Andric bool Before) {
825af732203SDimitry Andric return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
826af732203SDimitry Andric Before);
827af732203SDimitry Andric }
828af732203SDimitry Andric
splitBlockBefore(BasicBlock * Old,Instruction * SplitPt,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName)829af732203SDimitry Andric BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, Instruction *SplitPt,
830af732203SDimitry Andric DomTreeUpdater *DTU, LoopInfo *LI,
831af732203SDimitry Andric MemorySSAUpdater *MSSAU,
832af732203SDimitry Andric const Twine &BBName) {
833af732203SDimitry Andric
834af732203SDimitry Andric BasicBlock::iterator SplitIt = SplitPt->getIterator();
835af732203SDimitry Andric while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
836af732203SDimitry Andric ++SplitIt;
837af732203SDimitry Andric std::string Name = BBName.str();
838af732203SDimitry Andric BasicBlock *New = Old->splitBasicBlock(
839af732203SDimitry Andric SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
840af732203SDimitry Andric /* Before=*/true);
841af732203SDimitry Andric
842af732203SDimitry Andric // The new block lives in whichever loop the old one did. This preserves
843af732203SDimitry Andric // LCSSA as well, because we force the split point to be after any PHI nodes.
844af732203SDimitry Andric if (LI)
845af732203SDimitry Andric if (Loop *L = LI->getLoopFor(Old))
846af732203SDimitry Andric L->addBasicBlockToLoop(New, *LI);
847af732203SDimitry Andric
848af732203SDimitry Andric if (DTU) {
849af732203SDimitry Andric SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
850af732203SDimitry Andric // New dominates Old. The predecessor nodes of the Old node dominate
851af732203SDimitry Andric // New node.
852*5f7ddb14SDimitry Andric SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld(pred_begin(New),
853af732203SDimitry Andric pred_end(New));
854af732203SDimitry Andric DTUpdates.push_back({DominatorTree::Insert, New, Old});
855af732203SDimitry Andric DTUpdates.reserve(DTUpdates.size() + 2 * UniquePredecessorsOfOld.size());
856af732203SDimitry Andric for (BasicBlock *UniquePredecessorOfOld : UniquePredecessorsOfOld) {
857af732203SDimitry Andric DTUpdates.push_back({DominatorTree::Insert, UniquePredecessorOfOld, New});
858af732203SDimitry Andric DTUpdates.push_back({DominatorTree::Delete, UniquePredecessorOfOld, Old});
859af732203SDimitry Andric }
860af732203SDimitry Andric
861af732203SDimitry Andric DTU->applyUpdates(DTUpdates);
862af732203SDimitry Andric
863af732203SDimitry Andric // Move MemoryAccesses still tracked in Old, but part of New now.
864af732203SDimitry Andric // Update accesses in successor blocks accordingly.
865af732203SDimitry Andric if (MSSAU) {
866af732203SDimitry Andric MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
867af732203SDimitry Andric if (VerifyMemorySSA)
868af732203SDimitry Andric MSSAU->getMemorySSA()->verifyMemorySSA();
869af732203SDimitry Andric }
870af732203SDimitry Andric }
871af732203SDimitry Andric return New;
872af732203SDimitry Andric }
873af732203SDimitry Andric
8740b57cec5SDimitry 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)8750b57cec5SDimitry Andric static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
8760b57cec5SDimitry Andric ArrayRef<BasicBlock *> Preds,
877af732203SDimitry Andric DomTreeUpdater *DTU, DominatorTree *DT,
878af732203SDimitry Andric LoopInfo *LI, MemorySSAUpdater *MSSAU,
8790b57cec5SDimitry Andric bool PreserveLCSSA, bool &HasLoopExit) {
8800b57cec5SDimitry Andric // Update dominator tree if available.
881af732203SDimitry Andric if (DTU) {
882af732203SDimitry Andric // Recalculation of DomTree is needed when updating a forward DomTree and
883af732203SDimitry Andric // the Entry BB is replaced.
884*5f7ddb14SDimitry Andric if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
885af732203SDimitry Andric // The entry block was removed and there is no external interface for
886af732203SDimitry Andric // the dominator tree to be notified of this change. In this corner-case
887af732203SDimitry Andric // we recalculate the entire tree.
888af732203SDimitry Andric DTU->recalculate(*NewBB->getParent());
889af732203SDimitry Andric } else {
890af732203SDimitry Andric // Split block expects NewBB to have a non-empty set of predecessors.
891af732203SDimitry Andric SmallVector<DominatorTree::UpdateType, 8> Updates;
892*5f7ddb14SDimitry Andric SmallPtrSet<BasicBlock *, 8> UniquePreds(Preds.begin(), Preds.end());
893af732203SDimitry Andric Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
894af732203SDimitry Andric Updates.reserve(Updates.size() + 2 * UniquePreds.size());
895af732203SDimitry Andric for (auto *UniquePred : UniquePreds) {
896af732203SDimitry Andric Updates.push_back({DominatorTree::Insert, UniquePred, NewBB});
897af732203SDimitry Andric Updates.push_back({DominatorTree::Delete, UniquePred, OldBB});
898af732203SDimitry Andric }
899af732203SDimitry Andric DTU->applyUpdates(Updates);
900af732203SDimitry Andric }
901af732203SDimitry Andric } else if (DT) {
9020b57cec5SDimitry Andric if (OldBB == DT->getRootNode()->getBlock()) {
903*5f7ddb14SDimitry Andric assert(NewBB->isEntryBlock());
9040b57cec5SDimitry Andric DT->setNewRoot(NewBB);
9050b57cec5SDimitry Andric } else {
9060b57cec5SDimitry Andric // Split block expects NewBB to have a non-empty set of predecessors.
9070b57cec5SDimitry Andric DT->splitBlock(NewBB);
9080b57cec5SDimitry Andric }
9090b57cec5SDimitry Andric }
9100b57cec5SDimitry Andric
9110b57cec5SDimitry Andric // Update MemoryPhis after split if MemorySSA is available
9120b57cec5SDimitry Andric if (MSSAU)
9130b57cec5SDimitry Andric MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
9140b57cec5SDimitry Andric
9150b57cec5SDimitry Andric // The rest of the logic is only relevant for updating the loop structures.
9160b57cec5SDimitry Andric if (!LI)
9170b57cec5SDimitry Andric return;
9180b57cec5SDimitry Andric
919af732203SDimitry Andric if (DTU && DTU->hasDomTree())
920af732203SDimitry Andric DT = &DTU->getDomTree();
9210b57cec5SDimitry Andric assert(DT && "DT should be available to update LoopInfo!");
9220b57cec5SDimitry Andric Loop *L = LI->getLoopFor(OldBB);
9230b57cec5SDimitry Andric
9240b57cec5SDimitry Andric // If we need to preserve loop analyses, collect some information about how
9250b57cec5SDimitry Andric // this split will affect loops.
9260b57cec5SDimitry Andric bool IsLoopEntry = !!L;
9270b57cec5SDimitry Andric bool SplitMakesNewLoopHeader = false;
9280b57cec5SDimitry Andric for (BasicBlock *Pred : Preds) {
9290b57cec5SDimitry Andric // Preds that are not reachable from entry should not be used to identify if
9300b57cec5SDimitry Andric // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
9310b57cec5SDimitry Andric // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
9320b57cec5SDimitry Andric // as true and make the NewBB the header of some loop. This breaks LI.
9330b57cec5SDimitry Andric if (!DT->isReachableFromEntry(Pred))
9340b57cec5SDimitry Andric continue;
9350b57cec5SDimitry Andric // If we need to preserve LCSSA, determine if any of the preds is a loop
9360b57cec5SDimitry Andric // exit.
9370b57cec5SDimitry Andric if (PreserveLCSSA)
9380b57cec5SDimitry Andric if (Loop *PL = LI->getLoopFor(Pred))
9390b57cec5SDimitry Andric if (!PL->contains(OldBB))
9400b57cec5SDimitry Andric HasLoopExit = true;
9410b57cec5SDimitry Andric
9420b57cec5SDimitry Andric // If we need to preserve LoopInfo, note whether any of the preds crosses
9430b57cec5SDimitry Andric // an interesting loop boundary.
9440b57cec5SDimitry Andric if (!L)
9450b57cec5SDimitry Andric continue;
9460b57cec5SDimitry Andric if (L->contains(Pred))
9470b57cec5SDimitry Andric IsLoopEntry = false;
9480b57cec5SDimitry Andric else
9490b57cec5SDimitry Andric SplitMakesNewLoopHeader = true;
9500b57cec5SDimitry Andric }
9510b57cec5SDimitry Andric
9520b57cec5SDimitry Andric // Unless we have a loop for OldBB, nothing else to do here.
9530b57cec5SDimitry Andric if (!L)
9540b57cec5SDimitry Andric return;
9550b57cec5SDimitry Andric
9560b57cec5SDimitry Andric if (IsLoopEntry) {
9570b57cec5SDimitry Andric // Add the new block to the nearest enclosing loop (and not an adjacent
9580b57cec5SDimitry Andric // loop). To find this, examine each of the predecessors and determine which
9590b57cec5SDimitry Andric // loops enclose them, and select the most-nested loop which contains the
9600b57cec5SDimitry Andric // loop containing the block being split.
9610b57cec5SDimitry Andric Loop *InnermostPredLoop = nullptr;
9620b57cec5SDimitry Andric for (BasicBlock *Pred : Preds) {
9630b57cec5SDimitry Andric if (Loop *PredLoop = LI->getLoopFor(Pred)) {
9640b57cec5SDimitry Andric // Seek a loop which actually contains the block being split (to avoid
9650b57cec5SDimitry Andric // adjacent loops).
9660b57cec5SDimitry Andric while (PredLoop && !PredLoop->contains(OldBB))
9670b57cec5SDimitry Andric PredLoop = PredLoop->getParentLoop();
9680b57cec5SDimitry Andric
9690b57cec5SDimitry Andric // Select the most-nested of these loops which contains the block.
9700b57cec5SDimitry Andric if (PredLoop && PredLoop->contains(OldBB) &&
9710b57cec5SDimitry Andric (!InnermostPredLoop ||
9720b57cec5SDimitry Andric InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
9730b57cec5SDimitry Andric InnermostPredLoop = PredLoop;
9740b57cec5SDimitry Andric }
9750b57cec5SDimitry Andric }
9760b57cec5SDimitry Andric
9770b57cec5SDimitry Andric if (InnermostPredLoop)
9780b57cec5SDimitry Andric InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
9790b57cec5SDimitry Andric } else {
9800b57cec5SDimitry Andric L->addBasicBlockToLoop(NewBB, *LI);
9810b57cec5SDimitry Andric if (SplitMakesNewLoopHeader)
9820b57cec5SDimitry Andric L->moveToHeader(NewBB);
9830b57cec5SDimitry Andric }
9840b57cec5SDimitry Andric }
9850b57cec5SDimitry Andric
9860b57cec5SDimitry Andric /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
9870b57cec5SDimitry Andric /// This also updates AliasAnalysis, if available.
UpdatePHINodes(BasicBlock * OrigBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,BranchInst * BI,bool HasLoopExit)9880b57cec5SDimitry Andric static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
9890b57cec5SDimitry Andric ArrayRef<BasicBlock *> Preds, BranchInst *BI,
9900b57cec5SDimitry Andric bool HasLoopExit) {
9910b57cec5SDimitry Andric // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
9920b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
9930b57cec5SDimitry Andric for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
9940b57cec5SDimitry Andric PHINode *PN = cast<PHINode>(I++);
9950b57cec5SDimitry Andric
9960b57cec5SDimitry Andric // Check to see if all of the values coming in are the same. If so, we
9970b57cec5SDimitry Andric // don't need to create a new PHI node, unless it's needed for LCSSA.
9980b57cec5SDimitry Andric Value *InVal = nullptr;
9990b57cec5SDimitry Andric if (!HasLoopExit) {
10000b57cec5SDimitry Andric InVal = PN->getIncomingValueForBlock(Preds[0]);
10010b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10020b57cec5SDimitry Andric if (!PredSet.count(PN->getIncomingBlock(i)))
10030b57cec5SDimitry Andric continue;
10040b57cec5SDimitry Andric if (!InVal)
10050b57cec5SDimitry Andric InVal = PN->getIncomingValue(i);
10060b57cec5SDimitry Andric else if (InVal != PN->getIncomingValue(i)) {
10070b57cec5SDimitry Andric InVal = nullptr;
10080b57cec5SDimitry Andric break;
10090b57cec5SDimitry Andric }
10100b57cec5SDimitry Andric }
10110b57cec5SDimitry Andric }
10120b57cec5SDimitry Andric
10130b57cec5SDimitry Andric if (InVal) {
10140b57cec5SDimitry Andric // If all incoming values for the new PHI would be the same, just don't
10150b57cec5SDimitry Andric // make a new PHI. Instead, just remove the incoming values from the old
10160b57cec5SDimitry Andric // PHI.
10170b57cec5SDimitry Andric
10180b57cec5SDimitry Andric // NOTE! This loop walks backwards for a reason! First off, this minimizes
10190b57cec5SDimitry Andric // the cost of removal if we end up removing a large number of values, and
10200b57cec5SDimitry Andric // second off, this ensures that the indices for the incoming values
10210b57cec5SDimitry Andric // aren't invalidated when we remove one.
10220b57cec5SDimitry Andric for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
10230b57cec5SDimitry Andric if (PredSet.count(PN->getIncomingBlock(i)))
10240b57cec5SDimitry Andric PN->removeIncomingValue(i, false);
10250b57cec5SDimitry Andric
10260b57cec5SDimitry Andric // Add an incoming value to the PHI node in the loop for the preheader
10270b57cec5SDimitry Andric // edge.
10280b57cec5SDimitry Andric PN->addIncoming(InVal, NewBB);
10290b57cec5SDimitry Andric continue;
10300b57cec5SDimitry Andric }
10310b57cec5SDimitry Andric
10320b57cec5SDimitry Andric // If the values coming into the block are not the same, we need a new
10330b57cec5SDimitry Andric // PHI.
10340b57cec5SDimitry Andric // Create the new PHI node, insert it into NewBB at the end of the block
10350b57cec5SDimitry Andric PHINode *NewPHI =
10360b57cec5SDimitry Andric PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
10370b57cec5SDimitry Andric
10380b57cec5SDimitry Andric // NOTE! This loop walks backwards for a reason! First off, this minimizes
10390b57cec5SDimitry Andric // the cost of removal if we end up removing a large number of values, and
10400b57cec5SDimitry Andric // second off, this ensures that the indices for the incoming values aren't
10410b57cec5SDimitry Andric // invalidated when we remove one.
10420b57cec5SDimitry Andric for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
10430b57cec5SDimitry Andric BasicBlock *IncomingBB = PN->getIncomingBlock(i);
10440b57cec5SDimitry Andric if (PredSet.count(IncomingBB)) {
10450b57cec5SDimitry Andric Value *V = PN->removeIncomingValue(i, false);
10460b57cec5SDimitry Andric NewPHI->addIncoming(V, IncomingBB);
10470b57cec5SDimitry Andric }
10480b57cec5SDimitry Andric }
10490b57cec5SDimitry Andric
10500b57cec5SDimitry Andric PN->addIncoming(NewPHI, NewBB);
10510b57cec5SDimitry Andric }
10520b57cec5SDimitry Andric }
10530b57cec5SDimitry Andric
1054af732203SDimitry Andric static void SplitLandingPadPredecessorsImpl(
1055af732203SDimitry Andric BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1056af732203SDimitry Andric const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1057af732203SDimitry Andric DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1058af732203SDimitry Andric MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1059af732203SDimitry Andric
1060af732203SDimitry Andric static BasicBlock *
SplitBlockPredecessorsImpl(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1061af732203SDimitry Andric SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
1062af732203SDimitry Andric const char *Suffix, DomTreeUpdater *DTU,
1063af732203SDimitry Andric DominatorTree *DT, LoopInfo *LI,
1064af732203SDimitry Andric MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
10650b57cec5SDimitry Andric // Do not attempt to split that which cannot be split.
10660b57cec5SDimitry Andric if (!BB->canSplitPredecessors())
10670b57cec5SDimitry Andric return nullptr;
10680b57cec5SDimitry Andric
10690b57cec5SDimitry Andric // For the landingpads we need to act a bit differently.
10700b57cec5SDimitry Andric // Delegate this work to the SplitLandingPadPredecessors.
10710b57cec5SDimitry Andric if (BB->isLandingPad()) {
10720b57cec5SDimitry Andric SmallVector<BasicBlock*, 2> NewBBs;
10730b57cec5SDimitry Andric std::string NewName = std::string(Suffix) + ".split-lp";
10740b57cec5SDimitry Andric
1075af732203SDimitry Andric SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1076af732203SDimitry Andric DTU, DT, LI, MSSAU, PreserveLCSSA);
10770b57cec5SDimitry Andric return NewBBs[0];
10780b57cec5SDimitry Andric }
10790b57cec5SDimitry Andric
10800b57cec5SDimitry Andric // Create new basic block, insert right before the original block.
10810b57cec5SDimitry Andric BasicBlock *NewBB = BasicBlock::Create(
10820b57cec5SDimitry Andric BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
10830b57cec5SDimitry Andric
10840b57cec5SDimitry Andric // The new block unconditionally branches to the old block.
10850b57cec5SDimitry Andric BranchInst *BI = BranchInst::Create(BB, NewBB);
1086af732203SDimitry Andric
1087af732203SDimitry Andric Loop *L = nullptr;
1088af732203SDimitry Andric BasicBlock *OldLatch = nullptr;
10890b57cec5SDimitry Andric // Splitting the predecessors of a loop header creates a preheader block.
1090af732203SDimitry Andric if (LI && LI->isLoopHeader(BB)) {
1091af732203SDimitry Andric L = LI->getLoopFor(BB);
10920b57cec5SDimitry Andric // Using the loop start line number prevents debuggers stepping into the
10930b57cec5SDimitry Andric // loop body for this instruction.
1094af732203SDimitry Andric BI->setDebugLoc(L->getStartLoc());
1095af732203SDimitry Andric
1096af732203SDimitry Andric // If BB is the header of the Loop, it is possible that the loop is
1097af732203SDimitry Andric // modified, such that the current latch does not remain the latch of the
1098af732203SDimitry Andric // loop. If that is the case, the loop metadata from the current latch needs
1099af732203SDimitry Andric // to be applied to the new latch.
1100af732203SDimitry Andric OldLatch = L->getLoopLatch();
1101af732203SDimitry Andric } else
11020b57cec5SDimitry Andric BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
11030b57cec5SDimitry Andric
11040b57cec5SDimitry Andric // Move the edges from Preds to point to NewBB instead of BB.
11050b57cec5SDimitry Andric for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
11060b57cec5SDimitry Andric // This is slightly more strict than necessary; the minimum requirement
11070b57cec5SDimitry Andric // is that there be no more than one indirectbr branching to BB. And
11080b57cec5SDimitry Andric // all BlockAddress uses would need to be updated.
11090b57cec5SDimitry Andric assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
11100b57cec5SDimitry Andric "Cannot split an edge from an IndirectBrInst");
11110b57cec5SDimitry Andric assert(!isa<CallBrInst>(Preds[i]->getTerminator()) &&
11120b57cec5SDimitry Andric "Cannot split an edge from a CallBrInst");
11130b57cec5SDimitry Andric Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
11140b57cec5SDimitry Andric }
11150b57cec5SDimitry Andric
11160b57cec5SDimitry Andric // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
11170b57cec5SDimitry Andric // node becomes an incoming value for BB's phi node. However, if the Preds
11180b57cec5SDimitry Andric // list is empty, we need to insert dummy entries into the PHI nodes in BB to
11190b57cec5SDimitry Andric // account for the newly created predecessor.
11200b57cec5SDimitry Andric if (Preds.empty()) {
11210b57cec5SDimitry Andric // Insert dummy values as the incoming value.
11220b57cec5SDimitry Andric for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
11230b57cec5SDimitry Andric cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
11240b57cec5SDimitry Andric }
11250b57cec5SDimitry Andric
11260b57cec5SDimitry Andric // Update DominatorTree, LoopInfo, and LCCSA analysis information.
11270b57cec5SDimitry Andric bool HasLoopExit = false;
1128af732203SDimitry Andric UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
11290b57cec5SDimitry Andric HasLoopExit);
11300b57cec5SDimitry Andric
11310b57cec5SDimitry Andric if (!Preds.empty()) {
11320b57cec5SDimitry Andric // Update the PHI nodes in BB with the values coming from NewBB.
11330b57cec5SDimitry Andric UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
11340b57cec5SDimitry Andric }
11350b57cec5SDimitry Andric
1136af732203SDimitry Andric if (OldLatch) {
1137af732203SDimitry Andric BasicBlock *NewLatch = L->getLoopLatch();
1138af732203SDimitry Andric if (NewLatch != OldLatch) {
1139af732203SDimitry Andric MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop");
1140af732203SDimitry Andric NewLatch->getTerminator()->setMetadata("llvm.loop", MD);
1141af732203SDimitry Andric OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr);
1142af732203SDimitry Andric }
1143af732203SDimitry Andric }
1144af732203SDimitry Andric
11450b57cec5SDimitry Andric return NewBB;
11460b57cec5SDimitry Andric }
11470b57cec5SDimitry Andric
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1148af732203SDimitry Andric BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
11490b57cec5SDimitry Andric ArrayRef<BasicBlock *> Preds,
1150af732203SDimitry Andric const char *Suffix, DominatorTree *DT,
1151af732203SDimitry Andric LoopInfo *LI, MemorySSAUpdater *MSSAU,
1152af732203SDimitry Andric bool PreserveLCSSA) {
1153af732203SDimitry Andric return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1154af732203SDimitry Andric MSSAU, PreserveLCSSA);
1155af732203SDimitry Andric }
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1156af732203SDimitry Andric BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
1157af732203SDimitry Andric ArrayRef<BasicBlock *> Preds,
1158af732203SDimitry Andric const char *Suffix,
1159af732203SDimitry Andric DomTreeUpdater *DTU, LoopInfo *LI,
11600b57cec5SDimitry Andric MemorySSAUpdater *MSSAU,
11610b57cec5SDimitry Andric bool PreserveLCSSA) {
1162af732203SDimitry Andric return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1163af732203SDimitry Andric /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1164af732203SDimitry Andric }
1165af732203SDimitry 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)1166af732203SDimitry Andric static void SplitLandingPadPredecessorsImpl(
1167af732203SDimitry Andric BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1168af732203SDimitry Andric const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1169af732203SDimitry Andric DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1170af732203SDimitry Andric MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
11710b57cec5SDimitry Andric assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
11720b57cec5SDimitry Andric
11730b57cec5SDimitry Andric // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
11740b57cec5SDimitry Andric // it right before the original block.
11750b57cec5SDimitry Andric BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
11760b57cec5SDimitry Andric OrigBB->getName() + Suffix1,
11770b57cec5SDimitry Andric OrigBB->getParent(), OrigBB);
11780b57cec5SDimitry Andric NewBBs.push_back(NewBB1);
11790b57cec5SDimitry Andric
11800b57cec5SDimitry Andric // The new block unconditionally branches to the old block.
11810b57cec5SDimitry Andric BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
11820b57cec5SDimitry Andric BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
11830b57cec5SDimitry Andric
11840b57cec5SDimitry Andric // Move the edges from Preds to point to NewBB1 instead of OrigBB.
11850b57cec5SDimitry Andric for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
11860b57cec5SDimitry Andric // This is slightly more strict than necessary; the minimum requirement
11870b57cec5SDimitry Andric // is that there be no more than one indirectbr branching to BB. And
11880b57cec5SDimitry Andric // all BlockAddress uses would need to be updated.
11890b57cec5SDimitry Andric assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
11900b57cec5SDimitry Andric "Cannot split an edge from an IndirectBrInst");
11910b57cec5SDimitry Andric Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
11920b57cec5SDimitry Andric }
11930b57cec5SDimitry Andric
11940b57cec5SDimitry Andric bool HasLoopExit = false;
1195af732203SDimitry Andric UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1196af732203SDimitry Andric PreserveLCSSA, HasLoopExit);
11970b57cec5SDimitry Andric
11980b57cec5SDimitry Andric // Update the PHI nodes in OrigBB with the values coming from NewBB1.
11990b57cec5SDimitry Andric UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
12000b57cec5SDimitry Andric
12010b57cec5SDimitry Andric // Move the remaining edges from OrigBB to point to NewBB2.
12020b57cec5SDimitry Andric SmallVector<BasicBlock*, 8> NewBB2Preds;
12030b57cec5SDimitry Andric for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
12040b57cec5SDimitry Andric i != e; ) {
12050b57cec5SDimitry Andric BasicBlock *Pred = *i++;
12060b57cec5SDimitry Andric if (Pred == NewBB1) continue;
12070b57cec5SDimitry Andric assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
12080b57cec5SDimitry Andric "Cannot split an edge from an IndirectBrInst");
12090b57cec5SDimitry Andric NewBB2Preds.push_back(Pred);
12100b57cec5SDimitry Andric e = pred_end(OrigBB);
12110b57cec5SDimitry Andric }
12120b57cec5SDimitry Andric
12130b57cec5SDimitry Andric BasicBlock *NewBB2 = nullptr;
12140b57cec5SDimitry Andric if (!NewBB2Preds.empty()) {
12150b57cec5SDimitry Andric // Create another basic block for the rest of OrigBB's predecessors.
12160b57cec5SDimitry Andric NewBB2 = BasicBlock::Create(OrigBB->getContext(),
12170b57cec5SDimitry Andric OrigBB->getName() + Suffix2,
12180b57cec5SDimitry Andric OrigBB->getParent(), OrigBB);
12190b57cec5SDimitry Andric NewBBs.push_back(NewBB2);
12200b57cec5SDimitry Andric
12210b57cec5SDimitry Andric // The new block unconditionally branches to the old block.
12220b57cec5SDimitry Andric BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
12230b57cec5SDimitry Andric BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
12240b57cec5SDimitry Andric
12250b57cec5SDimitry Andric // Move the remaining edges from OrigBB to point to NewBB2.
12260b57cec5SDimitry Andric for (BasicBlock *NewBB2Pred : NewBB2Preds)
12270b57cec5SDimitry Andric NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
12280b57cec5SDimitry Andric
12290b57cec5SDimitry Andric // Update DominatorTree, LoopInfo, and LCCSA analysis information.
12300b57cec5SDimitry Andric HasLoopExit = false;
1231af732203SDimitry Andric UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
12320b57cec5SDimitry Andric PreserveLCSSA, HasLoopExit);
12330b57cec5SDimitry Andric
12340b57cec5SDimitry Andric // Update the PHI nodes in OrigBB with the values coming from NewBB2.
12350b57cec5SDimitry Andric UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
12360b57cec5SDimitry Andric }
12370b57cec5SDimitry Andric
12380b57cec5SDimitry Andric LandingPadInst *LPad = OrigBB->getLandingPadInst();
12390b57cec5SDimitry Andric Instruction *Clone1 = LPad->clone();
12400b57cec5SDimitry Andric Clone1->setName(Twine("lpad") + Suffix1);
12410b57cec5SDimitry Andric NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
12420b57cec5SDimitry Andric
12430b57cec5SDimitry Andric if (NewBB2) {
12440b57cec5SDimitry Andric Instruction *Clone2 = LPad->clone();
12450b57cec5SDimitry Andric Clone2->setName(Twine("lpad") + Suffix2);
12460b57cec5SDimitry Andric NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
12470b57cec5SDimitry Andric
12480b57cec5SDimitry Andric // Create a PHI node for the two cloned landingpad instructions only
12490b57cec5SDimitry Andric // if the original landingpad instruction has some uses.
12500b57cec5SDimitry Andric if (!LPad->use_empty()) {
12510b57cec5SDimitry Andric assert(!LPad->getType()->isTokenTy() &&
12520b57cec5SDimitry Andric "Split cannot be applied if LPad is token type. Otherwise an "
12530b57cec5SDimitry Andric "invalid PHINode of token type would be created.");
12540b57cec5SDimitry Andric PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
12550b57cec5SDimitry Andric PN->addIncoming(Clone1, NewBB1);
12560b57cec5SDimitry Andric PN->addIncoming(Clone2, NewBB2);
12570b57cec5SDimitry Andric LPad->replaceAllUsesWith(PN);
12580b57cec5SDimitry Andric }
12590b57cec5SDimitry Andric LPad->eraseFromParent();
12600b57cec5SDimitry Andric } else {
12610b57cec5SDimitry Andric // There is no second clone. Just replace the landing pad with the first
12620b57cec5SDimitry Andric // clone.
12630b57cec5SDimitry Andric LPad->replaceAllUsesWith(Clone1);
12640b57cec5SDimitry Andric LPad->eraseFromParent();
12650b57cec5SDimitry Andric }
12660b57cec5SDimitry Andric }
12670b57cec5SDimitry Andric
SplitLandingPadPredecessors(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1268af732203SDimitry Andric void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
1269af732203SDimitry Andric ArrayRef<BasicBlock *> Preds,
1270af732203SDimitry Andric const char *Suffix1, const char *Suffix2,
1271af732203SDimitry Andric SmallVectorImpl<BasicBlock *> &NewBBs,
1272af732203SDimitry Andric DominatorTree *DT, LoopInfo *LI,
1273af732203SDimitry Andric MemorySSAUpdater *MSSAU,
1274af732203SDimitry Andric bool PreserveLCSSA) {
1275af732203SDimitry Andric return SplitLandingPadPredecessorsImpl(
1276af732203SDimitry Andric OrigBB, Preds, Suffix1, Suffix2, NewBBs,
1277af732203SDimitry Andric /*DTU=*/nullptr, DT, LI, MSSAU, PreserveLCSSA);
1278af732203SDimitry Andric }
SplitLandingPadPredecessors(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1279af732203SDimitry Andric void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
1280af732203SDimitry Andric ArrayRef<BasicBlock *> Preds,
1281af732203SDimitry Andric const char *Suffix1, const char *Suffix2,
1282af732203SDimitry Andric SmallVectorImpl<BasicBlock *> &NewBBs,
1283af732203SDimitry Andric DomTreeUpdater *DTU, LoopInfo *LI,
1284af732203SDimitry Andric MemorySSAUpdater *MSSAU,
1285af732203SDimitry Andric bool PreserveLCSSA) {
1286af732203SDimitry Andric return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1287af732203SDimitry Andric NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1288af732203SDimitry Andric PreserveLCSSA);
1289af732203SDimitry Andric }
1290af732203SDimitry Andric
FoldReturnIntoUncondBranch(ReturnInst * RI,BasicBlock * BB,BasicBlock * Pred,DomTreeUpdater * DTU)12910b57cec5SDimitry Andric ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
12920b57cec5SDimitry Andric BasicBlock *Pred,
12930b57cec5SDimitry Andric DomTreeUpdater *DTU) {
12940b57cec5SDimitry Andric Instruction *UncondBranch = Pred->getTerminator();
12950b57cec5SDimitry Andric // Clone the return and add it to the end of the predecessor.
12960b57cec5SDimitry Andric Instruction *NewRet = RI->clone();
12970b57cec5SDimitry Andric Pred->getInstList().push_back(NewRet);
12980b57cec5SDimitry Andric
12990b57cec5SDimitry Andric // If the return instruction returns a value, and if the value was a
13000b57cec5SDimitry Andric // PHI node in "BB", propagate the right value into the return.
1301*5f7ddb14SDimitry Andric for (Use &Op : NewRet->operands()) {
1302*5f7ddb14SDimitry Andric Value *V = Op;
13030b57cec5SDimitry Andric Instruction *NewBC = nullptr;
13040b57cec5SDimitry Andric if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
13050b57cec5SDimitry Andric // Return value might be bitcasted. Clone and insert it before the
13060b57cec5SDimitry Andric // return instruction.
13070b57cec5SDimitry Andric V = BCI->getOperand(0);
13080b57cec5SDimitry Andric NewBC = BCI->clone();
13090b57cec5SDimitry Andric Pred->getInstList().insert(NewRet->getIterator(), NewBC);
1310*5f7ddb14SDimitry Andric Op = NewBC;
13110b57cec5SDimitry Andric }
13125ffd83dbSDimitry Andric
13135ffd83dbSDimitry Andric Instruction *NewEV = nullptr;
13145ffd83dbSDimitry Andric if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
13155ffd83dbSDimitry Andric V = EVI->getOperand(0);
13165ffd83dbSDimitry Andric NewEV = EVI->clone();
13175ffd83dbSDimitry Andric if (NewBC) {
13185ffd83dbSDimitry Andric NewBC->setOperand(0, NewEV);
13195ffd83dbSDimitry Andric Pred->getInstList().insert(NewBC->getIterator(), NewEV);
13205ffd83dbSDimitry Andric } else {
13215ffd83dbSDimitry Andric Pred->getInstList().insert(NewRet->getIterator(), NewEV);
1322*5f7ddb14SDimitry Andric Op = NewEV;
13235ffd83dbSDimitry Andric }
13245ffd83dbSDimitry Andric }
13255ffd83dbSDimitry Andric
13260b57cec5SDimitry Andric if (PHINode *PN = dyn_cast<PHINode>(V)) {
13270b57cec5SDimitry Andric if (PN->getParent() == BB) {
13285ffd83dbSDimitry Andric if (NewEV) {
13295ffd83dbSDimitry Andric NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
13305ffd83dbSDimitry Andric } else if (NewBC)
13310b57cec5SDimitry Andric NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
13320b57cec5SDimitry Andric else
1333*5f7ddb14SDimitry Andric Op = PN->getIncomingValueForBlock(Pred);
13340b57cec5SDimitry Andric }
13350b57cec5SDimitry Andric }
13360b57cec5SDimitry Andric }
13370b57cec5SDimitry Andric
13380b57cec5SDimitry Andric // Update any PHI nodes in the returning block to realize that we no
13390b57cec5SDimitry Andric // longer branch to them.
13400b57cec5SDimitry Andric BB->removePredecessor(Pred);
13410b57cec5SDimitry Andric UncondBranch->eraseFromParent();
13420b57cec5SDimitry Andric
13430b57cec5SDimitry Andric if (DTU)
13440b57cec5SDimitry Andric DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
13450b57cec5SDimitry Andric
13460b57cec5SDimitry Andric return cast<ReturnInst>(NewRet);
13470b57cec5SDimitry Andric }
13480b57cec5SDimitry Andric
1349af732203SDimitry Andric static Instruction *
SplitBlockAndInsertIfThenImpl(Value * Cond,Instruction * SplitBefore,bool Unreachable,MDNode * BranchWeights,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,BasicBlock * ThenBlock)1350af732203SDimitry Andric SplitBlockAndInsertIfThenImpl(Value *Cond, Instruction *SplitBefore,
1351af732203SDimitry Andric bool Unreachable, MDNode *BranchWeights,
1352af732203SDimitry Andric DomTreeUpdater *DTU, DominatorTree *DT,
1353af732203SDimitry Andric LoopInfo *LI, BasicBlock *ThenBlock) {
1354af732203SDimitry Andric SmallVector<DominatorTree::UpdateType, 8> Updates;
13550b57cec5SDimitry Andric BasicBlock *Head = SplitBefore->getParent();
13560b57cec5SDimitry Andric BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
1357af732203SDimitry Andric if (DTU) {
1358*5f7ddb14SDimitry Andric SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfHead(succ_begin(Tail),
1359af732203SDimitry Andric succ_end(Tail));
1360af732203SDimitry Andric Updates.push_back({DominatorTree::Insert, Head, Tail});
1361af732203SDimitry Andric Updates.reserve(Updates.size() + 2 * UniqueSuccessorsOfHead.size());
1362af732203SDimitry Andric for (BasicBlock *UniqueSuccessorOfHead : UniqueSuccessorsOfHead) {
1363af732203SDimitry Andric Updates.push_back({DominatorTree::Insert, Tail, UniqueSuccessorOfHead});
1364af732203SDimitry Andric Updates.push_back({DominatorTree::Delete, Head, UniqueSuccessorOfHead});
1365af732203SDimitry Andric }
1366af732203SDimitry Andric }
13670b57cec5SDimitry Andric Instruction *HeadOldTerm = Head->getTerminator();
13680b57cec5SDimitry Andric LLVMContext &C = Head->getContext();
13690b57cec5SDimitry Andric Instruction *CheckTerm;
13700b57cec5SDimitry Andric bool CreateThenBlock = (ThenBlock == nullptr);
13710b57cec5SDimitry Andric if (CreateThenBlock) {
13720b57cec5SDimitry Andric ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
13730b57cec5SDimitry Andric if (Unreachable)
13740b57cec5SDimitry Andric CheckTerm = new UnreachableInst(C, ThenBlock);
1375af732203SDimitry Andric else {
13760b57cec5SDimitry Andric CheckTerm = BranchInst::Create(Tail, ThenBlock);
1377af732203SDimitry Andric if (DTU)
1378af732203SDimitry Andric Updates.push_back({DominatorTree::Insert, ThenBlock, Tail});
1379af732203SDimitry Andric }
13800b57cec5SDimitry Andric CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
13810b57cec5SDimitry Andric } else
13820b57cec5SDimitry Andric CheckTerm = ThenBlock->getTerminator();
13830b57cec5SDimitry Andric BranchInst *HeadNewTerm =
13840b57cec5SDimitry Andric BranchInst::Create(/*ifTrue*/ ThenBlock, /*ifFalse*/ Tail, Cond);
1385af732203SDimitry Andric if (DTU)
1386af732203SDimitry Andric Updates.push_back({DominatorTree::Insert, Head, ThenBlock});
13870b57cec5SDimitry Andric HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
13880b57cec5SDimitry Andric ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
13890b57cec5SDimitry Andric
1390af732203SDimitry Andric if (DTU)
1391af732203SDimitry Andric DTU->applyUpdates(Updates);
1392af732203SDimitry Andric else if (DT) {
13930b57cec5SDimitry Andric if (DomTreeNode *OldNode = DT->getNode(Head)) {
13940b57cec5SDimitry Andric std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
13950b57cec5SDimitry Andric
13960b57cec5SDimitry Andric DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
13970b57cec5SDimitry Andric for (DomTreeNode *Child : Children)
13980b57cec5SDimitry Andric DT->changeImmediateDominator(Child, NewNode);
13990b57cec5SDimitry Andric
14000b57cec5SDimitry Andric // Head dominates ThenBlock.
14010b57cec5SDimitry Andric if (CreateThenBlock)
14020b57cec5SDimitry Andric DT->addNewBlock(ThenBlock, Head);
14030b57cec5SDimitry Andric else
14040b57cec5SDimitry Andric DT->changeImmediateDominator(ThenBlock, Head);
14050b57cec5SDimitry Andric }
14060b57cec5SDimitry Andric }
14070b57cec5SDimitry Andric
14080b57cec5SDimitry Andric if (LI) {
14090b57cec5SDimitry Andric if (Loop *L = LI->getLoopFor(Head)) {
14100b57cec5SDimitry Andric L->addBasicBlockToLoop(ThenBlock, *LI);
14110b57cec5SDimitry Andric L->addBasicBlockToLoop(Tail, *LI);
14120b57cec5SDimitry Andric }
14130b57cec5SDimitry Andric }
14140b57cec5SDimitry Andric
14150b57cec5SDimitry Andric return CheckTerm;
14160b57cec5SDimitry Andric }
14170b57cec5SDimitry Andric
SplitBlockAndInsertIfThen(Value * Cond,Instruction * SplitBefore,bool Unreachable,MDNode * BranchWeights,DominatorTree * DT,LoopInfo * LI,BasicBlock * ThenBlock)1418af732203SDimitry Andric Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
1419af732203SDimitry Andric Instruction *SplitBefore,
1420af732203SDimitry Andric bool Unreachable,
1421af732203SDimitry Andric MDNode *BranchWeights,
1422af732203SDimitry Andric DominatorTree *DT, LoopInfo *LI,
1423af732203SDimitry Andric BasicBlock *ThenBlock) {
1424af732203SDimitry Andric return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable,
1425af732203SDimitry Andric BranchWeights,
1426af732203SDimitry Andric /*DTU=*/nullptr, DT, LI, ThenBlock);
1427af732203SDimitry Andric }
SplitBlockAndInsertIfThen(Value * Cond,Instruction * SplitBefore,bool Unreachable,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI,BasicBlock * ThenBlock)1428af732203SDimitry Andric Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
1429af732203SDimitry Andric Instruction *SplitBefore,
1430af732203SDimitry Andric bool Unreachable,
1431af732203SDimitry Andric MDNode *BranchWeights,
1432af732203SDimitry Andric DomTreeUpdater *DTU, LoopInfo *LI,
1433af732203SDimitry Andric BasicBlock *ThenBlock) {
1434af732203SDimitry Andric return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable,
1435af732203SDimitry Andric BranchWeights, DTU, /*DT=*/nullptr, LI,
1436af732203SDimitry Andric ThenBlock);
1437af732203SDimitry Andric }
1438af732203SDimitry Andric
SplitBlockAndInsertIfThenElse(Value * Cond,Instruction * SplitBefore,Instruction ** ThenTerm,Instruction ** ElseTerm,MDNode * BranchWeights)14390b57cec5SDimitry Andric void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
14400b57cec5SDimitry Andric Instruction **ThenTerm,
14410b57cec5SDimitry Andric Instruction **ElseTerm,
14420b57cec5SDimitry Andric MDNode *BranchWeights) {
14430b57cec5SDimitry Andric BasicBlock *Head = SplitBefore->getParent();
14440b57cec5SDimitry Andric BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
14450b57cec5SDimitry Andric Instruction *HeadOldTerm = Head->getTerminator();
14460b57cec5SDimitry Andric LLVMContext &C = Head->getContext();
14470b57cec5SDimitry Andric BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
14480b57cec5SDimitry Andric BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
14490b57cec5SDimitry Andric *ThenTerm = BranchInst::Create(Tail, ThenBlock);
14500b57cec5SDimitry Andric (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
14510b57cec5SDimitry Andric *ElseTerm = BranchInst::Create(Tail, ElseBlock);
14520b57cec5SDimitry Andric (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
14530b57cec5SDimitry Andric BranchInst *HeadNewTerm =
14540b57cec5SDimitry Andric BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
14550b57cec5SDimitry Andric HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
14560b57cec5SDimitry Andric ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
14570b57cec5SDimitry Andric }
14580b57cec5SDimitry Andric
GetIfCondition(BasicBlock * BB,BasicBlock * & IfTrue,BasicBlock * & IfFalse)1459*5f7ddb14SDimitry Andric BranchInst *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
14600b57cec5SDimitry Andric BasicBlock *&IfFalse) {
14610b57cec5SDimitry Andric PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
14620b57cec5SDimitry Andric BasicBlock *Pred1 = nullptr;
14630b57cec5SDimitry Andric BasicBlock *Pred2 = nullptr;
14640b57cec5SDimitry Andric
14650b57cec5SDimitry Andric if (SomePHI) {
14660b57cec5SDimitry Andric if (SomePHI->getNumIncomingValues() != 2)
14670b57cec5SDimitry Andric return nullptr;
14680b57cec5SDimitry Andric Pred1 = SomePHI->getIncomingBlock(0);
14690b57cec5SDimitry Andric Pred2 = SomePHI->getIncomingBlock(1);
14700b57cec5SDimitry Andric } else {
14710b57cec5SDimitry Andric pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
14720b57cec5SDimitry Andric if (PI == PE) // No predecessor
14730b57cec5SDimitry Andric return nullptr;
14740b57cec5SDimitry Andric Pred1 = *PI++;
14750b57cec5SDimitry Andric if (PI == PE) // Only one predecessor
14760b57cec5SDimitry Andric return nullptr;
14770b57cec5SDimitry Andric Pred2 = *PI++;
14780b57cec5SDimitry Andric if (PI != PE) // More than two predecessors
14790b57cec5SDimitry Andric return nullptr;
14800b57cec5SDimitry Andric }
14810b57cec5SDimitry Andric
14820b57cec5SDimitry Andric // We can only handle branches. Other control flow will be lowered to
14830b57cec5SDimitry Andric // branches if possible anyway.
14840b57cec5SDimitry Andric BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
14850b57cec5SDimitry Andric BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
14860b57cec5SDimitry Andric if (!Pred1Br || !Pred2Br)
14870b57cec5SDimitry Andric return nullptr;
14880b57cec5SDimitry Andric
14890b57cec5SDimitry Andric // Eliminate code duplication by ensuring that Pred1Br is conditional if
14900b57cec5SDimitry Andric // either are.
14910b57cec5SDimitry Andric if (Pred2Br->isConditional()) {
14920b57cec5SDimitry Andric // If both branches are conditional, we don't have an "if statement". In
14930b57cec5SDimitry Andric // reality, we could transform this case, but since the condition will be
14940b57cec5SDimitry Andric // required anyway, we stand no chance of eliminating it, so the xform is
14950b57cec5SDimitry Andric // probably not profitable.
14960b57cec5SDimitry Andric if (Pred1Br->isConditional())
14970b57cec5SDimitry Andric return nullptr;
14980b57cec5SDimitry Andric
14990b57cec5SDimitry Andric std::swap(Pred1, Pred2);
15000b57cec5SDimitry Andric std::swap(Pred1Br, Pred2Br);
15010b57cec5SDimitry Andric }
15020b57cec5SDimitry Andric
15030b57cec5SDimitry Andric if (Pred1Br->isConditional()) {
15040b57cec5SDimitry Andric // The only thing we have to watch out for here is to make sure that Pred2
15050b57cec5SDimitry Andric // doesn't have incoming edges from other blocks. If it does, the condition
15060b57cec5SDimitry Andric // doesn't dominate BB.
15070b57cec5SDimitry Andric if (!Pred2->getSinglePredecessor())
15080b57cec5SDimitry Andric return nullptr;
15090b57cec5SDimitry Andric
15100b57cec5SDimitry Andric // If we found a conditional branch predecessor, make sure that it branches
15110b57cec5SDimitry Andric // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
15120b57cec5SDimitry Andric if (Pred1Br->getSuccessor(0) == BB &&
15130b57cec5SDimitry Andric Pred1Br->getSuccessor(1) == Pred2) {
15140b57cec5SDimitry Andric IfTrue = Pred1;
15150b57cec5SDimitry Andric IfFalse = Pred2;
15160b57cec5SDimitry Andric } else if (Pred1Br->getSuccessor(0) == Pred2 &&
15170b57cec5SDimitry Andric Pred1Br->getSuccessor(1) == BB) {
15180b57cec5SDimitry Andric IfTrue = Pred2;
15190b57cec5SDimitry Andric IfFalse = Pred1;
15200b57cec5SDimitry Andric } else {
15210b57cec5SDimitry Andric // We know that one arm of the conditional goes to BB, so the other must
15220b57cec5SDimitry Andric // go somewhere unrelated, and this must not be an "if statement".
15230b57cec5SDimitry Andric return nullptr;
15240b57cec5SDimitry Andric }
15250b57cec5SDimitry Andric
1526*5f7ddb14SDimitry Andric return Pred1Br;
15270b57cec5SDimitry Andric }
15280b57cec5SDimitry Andric
15290b57cec5SDimitry Andric // Ok, if we got here, both predecessors end with an unconditional branch to
15300b57cec5SDimitry Andric // BB. Don't panic! If both blocks only have a single (identical)
15310b57cec5SDimitry Andric // predecessor, and THAT is a conditional branch, then we're all ok!
15320b57cec5SDimitry Andric BasicBlock *CommonPred = Pred1->getSinglePredecessor();
15330b57cec5SDimitry Andric if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
15340b57cec5SDimitry Andric return nullptr;
15350b57cec5SDimitry Andric
15360b57cec5SDimitry Andric // Otherwise, if this is a conditional branch, then we can use it!
15370b57cec5SDimitry Andric BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
15380b57cec5SDimitry Andric if (!BI) return nullptr;
15390b57cec5SDimitry Andric
15400b57cec5SDimitry Andric assert(BI->isConditional() && "Two successors but not conditional?");
15410b57cec5SDimitry Andric if (BI->getSuccessor(0) == Pred1) {
15420b57cec5SDimitry Andric IfTrue = Pred1;
15430b57cec5SDimitry Andric IfFalse = Pred2;
15440b57cec5SDimitry Andric } else {
15450b57cec5SDimitry Andric IfTrue = Pred2;
15460b57cec5SDimitry Andric IfFalse = Pred1;
15470b57cec5SDimitry Andric }
1548*5f7ddb14SDimitry Andric return BI;
15490b57cec5SDimitry Andric }
15505ffd83dbSDimitry Andric
15515ffd83dbSDimitry Andric // After creating a control flow hub, the operands of PHINodes in an outgoing
15525ffd83dbSDimitry Andric // block Out no longer match the predecessors of that block. Predecessors of Out
15535ffd83dbSDimitry Andric // that are incoming blocks to the hub are now replaced by just one edge from
15545ffd83dbSDimitry Andric // the hub. To match this new control flow, the corresponding values from each
15555ffd83dbSDimitry Andric // PHINode must now be moved a new PHINode in the first guard block of the hub.
15565ffd83dbSDimitry Andric //
15575ffd83dbSDimitry Andric // This operation cannot be performed with SSAUpdater, because it involves one
15585ffd83dbSDimitry Andric // new use: If the block Out is in the list of Incoming blocks, then the newly
15595ffd83dbSDimitry 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)15605ffd83dbSDimitry Andric static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock,
15615ffd83dbSDimitry Andric const SetVector<BasicBlock *> &Incoming,
15625ffd83dbSDimitry Andric BasicBlock *FirstGuardBlock) {
15635ffd83dbSDimitry Andric auto I = Out->begin();
15645ffd83dbSDimitry Andric while (I != Out->end() && isa<PHINode>(I)) {
15655ffd83dbSDimitry Andric auto Phi = cast<PHINode>(I);
15665ffd83dbSDimitry Andric auto NewPhi =
15675ffd83dbSDimitry Andric PHINode::Create(Phi->getType(), Incoming.size(),
15685ffd83dbSDimitry Andric Phi->getName() + ".moved", &FirstGuardBlock->back());
15695ffd83dbSDimitry Andric for (auto In : Incoming) {
15705ffd83dbSDimitry Andric Value *V = UndefValue::get(Phi->getType());
15715ffd83dbSDimitry Andric if (In == Out) {
15725ffd83dbSDimitry Andric V = NewPhi;
15735ffd83dbSDimitry Andric } else if (Phi->getBasicBlockIndex(In) != -1) {
15745ffd83dbSDimitry Andric V = Phi->removeIncomingValue(In, false);
15755ffd83dbSDimitry Andric }
15765ffd83dbSDimitry Andric NewPhi->addIncoming(V, In);
15775ffd83dbSDimitry Andric }
15785ffd83dbSDimitry Andric assert(NewPhi->getNumIncomingValues() == Incoming.size());
15795ffd83dbSDimitry Andric if (Phi->getNumOperands() == 0) {
15805ffd83dbSDimitry Andric Phi->replaceAllUsesWith(NewPhi);
15815ffd83dbSDimitry Andric I = Phi->eraseFromParent();
15825ffd83dbSDimitry Andric continue;
15835ffd83dbSDimitry Andric }
15845ffd83dbSDimitry Andric Phi->addIncoming(NewPhi, GuardBlock);
15855ffd83dbSDimitry Andric ++I;
15865ffd83dbSDimitry Andric }
15875ffd83dbSDimitry Andric }
15885ffd83dbSDimitry Andric
15895ffd83dbSDimitry Andric using BBPredicates = DenseMap<BasicBlock *, PHINode *>;
15905ffd83dbSDimitry Andric using BBSetVector = SetVector<BasicBlock *>;
15915ffd83dbSDimitry Andric
15925ffd83dbSDimitry Andric // Redirects the terminator of the incoming block to the first guard
15935ffd83dbSDimitry Andric // block in the hub. The condition of the original terminator (if it
15945ffd83dbSDimitry Andric // was conditional) and its original successors are returned as a
15955ffd83dbSDimitry Andric // tuple <condition, succ0, succ1>. The function additionally filters
15965ffd83dbSDimitry Andric // out successors that are not in the set of outgoing blocks.
15975ffd83dbSDimitry Andric //
15985ffd83dbSDimitry Andric // - condition is non-null iff the branch is conditional.
15995ffd83dbSDimitry Andric // - Succ1 is non-null iff the sole/taken target is an outgoing block.
16005ffd83dbSDimitry Andric // - Succ2 is non-null iff condition is non-null and the fallthrough
16015ffd83dbSDimitry Andric // target is an outgoing block.
16025ffd83dbSDimitry Andric static std::tuple<Value *, BasicBlock *, BasicBlock *>
redirectToHub(BasicBlock * BB,BasicBlock * FirstGuardBlock,const BBSetVector & Outgoing)16035ffd83dbSDimitry Andric redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock,
16045ffd83dbSDimitry Andric const BBSetVector &Outgoing) {
16055ffd83dbSDimitry Andric auto Branch = cast<BranchInst>(BB->getTerminator());
16065ffd83dbSDimitry Andric auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
16075ffd83dbSDimitry Andric
16085ffd83dbSDimitry Andric BasicBlock *Succ0 = Branch->getSuccessor(0);
16095ffd83dbSDimitry Andric BasicBlock *Succ1 = nullptr;
16105ffd83dbSDimitry Andric Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr;
16115ffd83dbSDimitry Andric
16125ffd83dbSDimitry Andric if (Branch->isUnconditional()) {
16135ffd83dbSDimitry Andric Branch->setSuccessor(0, FirstGuardBlock);
16145ffd83dbSDimitry Andric assert(Succ0);
16155ffd83dbSDimitry Andric } else {
16165ffd83dbSDimitry Andric Succ1 = Branch->getSuccessor(1);
16175ffd83dbSDimitry Andric Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr;
16185ffd83dbSDimitry Andric assert(Succ0 || Succ1);
16195ffd83dbSDimitry Andric if (Succ0 && !Succ1) {
16205ffd83dbSDimitry Andric Branch->setSuccessor(0, FirstGuardBlock);
16215ffd83dbSDimitry Andric } else if (Succ1 && !Succ0) {
16225ffd83dbSDimitry Andric Branch->setSuccessor(1, FirstGuardBlock);
16235ffd83dbSDimitry Andric } else {
16245ffd83dbSDimitry Andric Branch->eraseFromParent();
16255ffd83dbSDimitry Andric BranchInst::Create(FirstGuardBlock, BB);
16265ffd83dbSDimitry Andric }
16275ffd83dbSDimitry Andric }
16285ffd83dbSDimitry Andric
16295ffd83dbSDimitry Andric assert(Succ0 || Succ1);
16305ffd83dbSDimitry Andric return std::make_tuple(Condition, Succ0, Succ1);
16315ffd83dbSDimitry Andric }
16325ffd83dbSDimitry Andric
16335ffd83dbSDimitry Andric // Capture the existing control flow as guard predicates, and redirect
16345ffd83dbSDimitry Andric // control flow from every incoming block to the first guard block in
16355ffd83dbSDimitry Andric // the hub.
16365ffd83dbSDimitry Andric //
16375ffd83dbSDimitry Andric // There is one guard predicate for each outgoing block OutBB. The
16385ffd83dbSDimitry Andric // predicate is a PHINode with one input for each InBB which
16395ffd83dbSDimitry Andric // represents whether the hub should transfer control flow to OutBB if
16405ffd83dbSDimitry Andric // it arrived from InBB. These predicates are NOT ORTHOGONAL. The Hub
16415ffd83dbSDimitry Andric // evaluates them in the same order as the Outgoing set-vector, and
16425ffd83dbSDimitry Andric // control branches to the first outgoing block whose predicate
16435ffd83dbSDimitry Andric // evaluates to true.
convertToGuardPredicates(BasicBlock * FirstGuardBlock,BBPredicates & GuardPredicates,SmallVectorImpl<WeakVH> & DeletionCandidates,const BBSetVector & Incoming,const BBSetVector & Outgoing)16445ffd83dbSDimitry Andric static void convertToGuardPredicates(
16455ffd83dbSDimitry Andric BasicBlock *FirstGuardBlock, BBPredicates &GuardPredicates,
16465ffd83dbSDimitry Andric SmallVectorImpl<WeakVH> &DeletionCandidates, const BBSetVector &Incoming,
16475ffd83dbSDimitry Andric const BBSetVector &Outgoing) {
16485ffd83dbSDimitry Andric auto &Context = Incoming.front()->getContext();
16495ffd83dbSDimitry Andric auto BoolTrue = ConstantInt::getTrue(Context);
16505ffd83dbSDimitry Andric auto BoolFalse = ConstantInt::getFalse(Context);
16515ffd83dbSDimitry Andric
16525ffd83dbSDimitry Andric // The predicate for the last outgoing is trivially true, and so we
16535ffd83dbSDimitry Andric // process only the first N-1 successors.
16545ffd83dbSDimitry Andric for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
16555ffd83dbSDimitry Andric auto Out = Outgoing[i];
16565ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n");
16575ffd83dbSDimitry Andric auto Phi =
16585ffd83dbSDimitry Andric PHINode::Create(Type::getInt1Ty(Context), Incoming.size(),
16595ffd83dbSDimitry Andric StringRef("Guard.") + Out->getName(), FirstGuardBlock);
16605ffd83dbSDimitry Andric GuardPredicates[Out] = Phi;
16615ffd83dbSDimitry Andric }
16625ffd83dbSDimitry Andric
16635ffd83dbSDimitry Andric for (auto In : Incoming) {
16645ffd83dbSDimitry Andric Value *Condition;
16655ffd83dbSDimitry Andric BasicBlock *Succ0;
16665ffd83dbSDimitry Andric BasicBlock *Succ1;
16675ffd83dbSDimitry Andric std::tie(Condition, Succ0, Succ1) =
16685ffd83dbSDimitry Andric redirectToHub(In, FirstGuardBlock, Outgoing);
16695ffd83dbSDimitry Andric
16705ffd83dbSDimitry Andric // Optimization: Consider an incoming block A with both successors
16715ffd83dbSDimitry Andric // Succ0 and Succ1 in the set of outgoing blocks. The predicates
16725ffd83dbSDimitry Andric // for Succ0 and Succ1 complement each other. If Succ0 is visited
16735ffd83dbSDimitry Andric // first in the loop below, control will branch to Succ0 using the
16745ffd83dbSDimitry Andric // corresponding predicate. But if that branch is not taken, then
16755ffd83dbSDimitry Andric // control must reach Succ1, which means that the predicate for
16765ffd83dbSDimitry Andric // Succ1 is always true.
16775ffd83dbSDimitry Andric bool OneSuccessorDone = false;
16785ffd83dbSDimitry Andric for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
16795ffd83dbSDimitry Andric auto Out = Outgoing[i];
16805ffd83dbSDimitry Andric auto Phi = GuardPredicates[Out];
16815ffd83dbSDimitry Andric if (Out != Succ0 && Out != Succ1) {
16825ffd83dbSDimitry Andric Phi->addIncoming(BoolFalse, In);
16835ffd83dbSDimitry Andric continue;
16845ffd83dbSDimitry Andric }
16855ffd83dbSDimitry Andric // Optimization: When only one successor is an outgoing block,
16865ffd83dbSDimitry Andric // the predicate is always true.
16875ffd83dbSDimitry Andric if (!Succ0 || !Succ1 || OneSuccessorDone) {
16885ffd83dbSDimitry Andric Phi->addIncoming(BoolTrue, In);
16895ffd83dbSDimitry Andric continue;
16905ffd83dbSDimitry Andric }
16915ffd83dbSDimitry Andric assert(Succ0 && Succ1);
16925ffd83dbSDimitry Andric OneSuccessorDone = true;
16935ffd83dbSDimitry Andric if (Out == Succ0) {
16945ffd83dbSDimitry Andric Phi->addIncoming(Condition, In);
16955ffd83dbSDimitry Andric continue;
16965ffd83dbSDimitry Andric }
16975ffd83dbSDimitry Andric auto Inverted = invertCondition(Condition);
16985ffd83dbSDimitry Andric DeletionCandidates.push_back(Condition);
16995ffd83dbSDimitry Andric Phi->addIncoming(Inverted, In);
17005ffd83dbSDimitry Andric }
17015ffd83dbSDimitry Andric }
17025ffd83dbSDimitry Andric }
17035ffd83dbSDimitry Andric
17045ffd83dbSDimitry Andric // For each outgoing block OutBB, create a guard block in the Hub. The
17055ffd83dbSDimitry Andric // first guard block was already created outside, and available as the
17065ffd83dbSDimitry Andric // first element in the vector of guard blocks.
17075ffd83dbSDimitry Andric //
17085ffd83dbSDimitry Andric // Each guard block terminates in a conditional branch that transfers
17095ffd83dbSDimitry Andric // control to the corresponding outgoing block or the next guard
17105ffd83dbSDimitry Andric // block. The last guard block has two outgoing blocks as successors
17115ffd83dbSDimitry Andric // since the condition for the final outgoing block is trivially
17125ffd83dbSDimitry Andric // true. So we create one less block (including the first guard block)
17135ffd83dbSDimitry Andric // than the number of outgoing blocks.
createGuardBlocks(SmallVectorImpl<BasicBlock * > & GuardBlocks,Function * F,const BBSetVector & Outgoing,BBPredicates & GuardPredicates,StringRef Prefix)17145ffd83dbSDimitry Andric static void createGuardBlocks(SmallVectorImpl<BasicBlock *> &GuardBlocks,
17155ffd83dbSDimitry Andric Function *F, const BBSetVector &Outgoing,
17165ffd83dbSDimitry Andric BBPredicates &GuardPredicates, StringRef Prefix) {
17175ffd83dbSDimitry Andric for (int i = 0, e = Outgoing.size() - 2; i != e; ++i) {
17185ffd83dbSDimitry Andric GuardBlocks.push_back(
17195ffd83dbSDimitry Andric BasicBlock::Create(F->getContext(), Prefix + ".guard", F));
17205ffd83dbSDimitry Andric }
17215ffd83dbSDimitry Andric assert(GuardBlocks.size() == GuardPredicates.size());
17225ffd83dbSDimitry Andric
17235ffd83dbSDimitry Andric // To help keep the loop simple, temporarily append the last
17245ffd83dbSDimitry Andric // outgoing block to the list of guard blocks.
17255ffd83dbSDimitry Andric GuardBlocks.push_back(Outgoing.back());
17265ffd83dbSDimitry Andric
17275ffd83dbSDimitry Andric for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) {
17285ffd83dbSDimitry Andric auto Out = Outgoing[i];
17295ffd83dbSDimitry Andric assert(GuardPredicates.count(Out));
17305ffd83dbSDimitry Andric BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out],
17315ffd83dbSDimitry Andric GuardBlocks[i]);
17325ffd83dbSDimitry Andric }
17335ffd83dbSDimitry Andric
17345ffd83dbSDimitry Andric // Remove the last block from the guard list.
17355ffd83dbSDimitry Andric GuardBlocks.pop_back();
17365ffd83dbSDimitry Andric }
17375ffd83dbSDimitry Andric
CreateControlFlowHub(DomTreeUpdater * DTU,SmallVectorImpl<BasicBlock * > & GuardBlocks,const BBSetVector & Incoming,const BBSetVector & Outgoing,const StringRef Prefix)17385ffd83dbSDimitry Andric BasicBlock *llvm::CreateControlFlowHub(
17395ffd83dbSDimitry Andric DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
17405ffd83dbSDimitry Andric const BBSetVector &Incoming, const BBSetVector &Outgoing,
17415ffd83dbSDimitry Andric const StringRef Prefix) {
17425ffd83dbSDimitry Andric auto F = Incoming.front()->getParent();
17435ffd83dbSDimitry Andric auto FirstGuardBlock =
17445ffd83dbSDimitry Andric BasicBlock::Create(F->getContext(), Prefix + ".guard", F);
17455ffd83dbSDimitry Andric
17465ffd83dbSDimitry Andric SmallVector<DominatorTree::UpdateType, 16> Updates;
17475ffd83dbSDimitry Andric if (DTU) {
17485ffd83dbSDimitry Andric for (auto In : Incoming) {
1749af732203SDimitry Andric Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock});
17505ffd83dbSDimitry Andric for (auto Succ : successors(In)) {
17515ffd83dbSDimitry Andric if (Outgoing.count(Succ))
17525ffd83dbSDimitry Andric Updates.push_back({DominatorTree::Delete, In, Succ});
17535ffd83dbSDimitry Andric }
17545ffd83dbSDimitry Andric }
17555ffd83dbSDimitry Andric }
17565ffd83dbSDimitry Andric
17575ffd83dbSDimitry Andric BBPredicates GuardPredicates;
17585ffd83dbSDimitry Andric SmallVector<WeakVH, 8> DeletionCandidates;
17595ffd83dbSDimitry Andric convertToGuardPredicates(FirstGuardBlock, GuardPredicates, DeletionCandidates,
17605ffd83dbSDimitry Andric Incoming, Outgoing);
17615ffd83dbSDimitry Andric
17625ffd83dbSDimitry Andric GuardBlocks.push_back(FirstGuardBlock);
17635ffd83dbSDimitry Andric createGuardBlocks(GuardBlocks, F, Outgoing, GuardPredicates, Prefix);
17645ffd83dbSDimitry Andric
17655ffd83dbSDimitry Andric // Update the PHINodes in each outgoing block to match the new control flow.
17665ffd83dbSDimitry Andric for (int i = 0, e = GuardBlocks.size(); i != e; ++i) {
17675ffd83dbSDimitry Andric reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock);
17685ffd83dbSDimitry Andric }
17695ffd83dbSDimitry Andric reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock);
17705ffd83dbSDimitry Andric
17715ffd83dbSDimitry Andric if (DTU) {
17725ffd83dbSDimitry Andric int NumGuards = GuardBlocks.size();
17735ffd83dbSDimitry Andric assert((int)Outgoing.size() == NumGuards + 1);
17745ffd83dbSDimitry Andric for (int i = 0; i != NumGuards - 1; ++i) {
17755ffd83dbSDimitry Andric Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]});
17765ffd83dbSDimitry Andric Updates.push_back(
17775ffd83dbSDimitry Andric {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]});
17785ffd83dbSDimitry Andric }
17795ffd83dbSDimitry Andric Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
17805ffd83dbSDimitry Andric Outgoing[NumGuards - 1]});
17815ffd83dbSDimitry Andric Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
17825ffd83dbSDimitry Andric Outgoing[NumGuards]});
17835ffd83dbSDimitry Andric DTU->applyUpdates(Updates);
17845ffd83dbSDimitry Andric }
17855ffd83dbSDimitry Andric
17865ffd83dbSDimitry Andric for (auto I : DeletionCandidates) {
17875ffd83dbSDimitry Andric if (I->use_empty())
17885ffd83dbSDimitry Andric if (auto Inst = dyn_cast_or_null<Instruction>(I))
17895ffd83dbSDimitry Andric Inst->eraseFromParent();
17905ffd83dbSDimitry Andric }
17915ffd83dbSDimitry Andric
17925ffd83dbSDimitry Andric return FirstGuardBlock;
17935ffd83dbSDimitry Andric }
1794