Home | History | Annotate | Download | only in Utils
      1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This family of functions perform manipulations on basic blocks, and
     11 // instructions contained within basic blocks.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     16 #include "llvm/Analysis/AliasAnalysis.h"
     17 #include "llvm/Analysis/CFG.h"
     18 #include "llvm/Analysis/LoopInfo.h"
     19 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
     20 #include "llvm/IR/Constant.h"
     21 #include "llvm/IR/DataLayout.h"
     22 #include "llvm/IR/Dominators.h"
     23 #include "llvm/IR/Function.h"
     24 #include "llvm/IR/Instructions.h"
     25 #include "llvm/IR/IntrinsicInst.h"
     26 #include "llvm/IR/Type.h"
     27 #include "llvm/IR/ValueHandle.h"
     28 #include "llvm/Support/ErrorHandling.h"
     29 #include "llvm/Transforms/Scalar.h"
     30 #include "llvm/Transforms/Utils/Local.h"
     31 #include <algorithm>
     32 using namespace llvm;
     33 
     34 /// DeleteDeadBlock - Delete the specified block, which must have no
     35 /// predecessors.
     36 void llvm::DeleteDeadBlock(BasicBlock *BB) {
     37   assert((pred_begin(BB) == pred_end(BB) ||
     38          // Can delete self loop.
     39          BB->getSinglePredecessor() == BB) && "Block is not dead!");
     40   TerminatorInst *BBTerm = BB->getTerminator();
     41 
     42   // Loop through all of our successors and make sure they know that one
     43   // of their predecessors is going away.
     44   for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
     45     BBTerm->getSuccessor(i)->removePredecessor(BB);
     46 
     47   // Zap all the instructions in the block.
     48   while (!BB->empty()) {
     49     Instruction &I = BB->back();
     50     // If this instruction is used, replace uses with an arbitrary value.
     51     // Because control flow can't get here, we don't care what we replace the
     52     // value with.  Note that since this block is unreachable, and all values
     53     // contained within it must dominate their uses, that all uses will
     54     // eventually be removed (they are themselves dead).
     55     if (!I.use_empty())
     56       I.replaceAllUsesWith(UndefValue::get(I.getType()));
     57     BB->getInstList().pop_back();
     58   }
     59 
     60   // Zap the block!
     61   BB->eraseFromParent();
     62 }
     63 
     64 /// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
     65 /// any single-entry PHI nodes in it, fold them away.  This handles the case
     66 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
     67 /// when the block has exactly one predecessor.
     68 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P) {
     69   if (!isa<PHINode>(BB->begin())) return;
     70 
     71   AliasAnalysis *AA = nullptr;
     72   MemoryDependenceAnalysis *MemDep = nullptr;
     73   if (P) {
     74     AA = P->getAnalysisIfAvailable<AliasAnalysis>();
     75     MemDep = P->getAnalysisIfAvailable<MemoryDependenceAnalysis>();
     76   }
     77 
     78   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
     79     if (PN->getIncomingValue(0) != PN)
     80       PN->replaceAllUsesWith(PN->getIncomingValue(0));
     81     else
     82       PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
     83 
     84     if (MemDep)
     85       MemDep->removeInstruction(PN);  // Memdep updates AA itself.
     86     else if (AA && isa<PointerType>(PN->getType()))
     87       AA->deleteValue(PN);
     88 
     89     PN->eraseFromParent();
     90   }
     91 }
     92 
     93 
     94 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
     95 /// is dead. Also recursively delete any operands that become dead as
     96 /// a result. This includes tracing the def-use list from the PHI to see if
     97 /// it is ultimately unused or if it reaches an unused cycle.
     98 bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
     99   // Recursively deleting a PHI may cause multiple PHIs to be deleted
    100   // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
    101   SmallVector<WeakVH, 8> PHIs;
    102   for (BasicBlock::iterator I = BB->begin();
    103        PHINode *PN = dyn_cast<PHINode>(I); ++I)
    104     PHIs.push_back(PN);
    105 
    106   bool Changed = false;
    107   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
    108     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
    109       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
    110 
    111   return Changed;
    112 }
    113 
    114 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
    115 /// if possible.  The return value indicates success or failure.
    116 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
    117   // Don't merge away blocks who have their address taken.
    118   if (BB->hasAddressTaken()) return false;
    119 
    120   // Can't merge if there are multiple predecessors, or no predecessors.
    121   BasicBlock *PredBB = BB->getUniquePredecessor();
    122   if (!PredBB) return false;
    123 
    124   // Don't break self-loops.
    125   if (PredBB == BB) return false;
    126   // Don't break invokes.
    127   if (isa<InvokeInst>(PredBB->getTerminator())) return false;
    128 
    129   succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
    130   BasicBlock *OnlySucc = BB;
    131   for (; SI != SE; ++SI)
    132     if (*SI != OnlySucc) {
    133       OnlySucc = nullptr;     // There are multiple distinct successors!
    134       break;
    135     }
    136 
    137   // Can't merge if there are multiple successors.
    138   if (!OnlySucc) return false;
    139 
    140   // Can't merge if there is PHI loop.
    141   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
    142     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
    143       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    144         if (PN->getIncomingValue(i) == PN)
    145           return false;
    146     } else
    147       break;
    148   }
    149 
    150   // Begin by getting rid of unneeded PHIs.
    151   if (isa<PHINode>(BB->front()))
    152     FoldSingleEntryPHINodes(BB, P);
    153 
    154   // Delete the unconditional branch from the predecessor...
    155   PredBB->getInstList().pop_back();
    156 
    157   // Make all PHI nodes that referred to BB now refer to Pred as their
    158   // source...
    159   BB->replaceAllUsesWith(PredBB);
    160 
    161   // Move all definitions in the successor to the predecessor...
    162   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
    163 
    164   // Inherit predecessors name if it exists.
    165   if (!PredBB->hasName())
    166     PredBB->takeName(BB);
    167 
    168   // Finally, erase the old block and update dominator info.
    169   if (P) {
    170     if (DominatorTreeWrapperPass *DTWP =
    171             P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
    172       DominatorTree &DT = DTWP->getDomTree();
    173       if (DomTreeNode *DTN = DT.getNode(BB)) {
    174         DomTreeNode *PredDTN = DT.getNode(PredBB);
    175         SmallVector<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
    176         for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
    177              DE = Children.end(); DI != DE; ++DI)
    178           DT.changeImmediateDominator(*DI, PredDTN);
    179 
    180         DT.eraseNode(BB);
    181       }
    182 
    183       if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
    184         LI->removeBlock(BB);
    185 
    186       if (MemoryDependenceAnalysis *MD =
    187             P->getAnalysisIfAvailable<MemoryDependenceAnalysis>())
    188         MD->invalidateCachedPredecessors();
    189     }
    190   }
    191 
    192   BB->eraseFromParent();
    193   return true;
    194 }
    195 
    196 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
    197 /// with a value, then remove and delete the original instruction.
    198 ///
    199 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
    200                                 BasicBlock::iterator &BI, Value *V) {
    201   Instruction &I = *BI;
    202   // Replaces all of the uses of the instruction with uses of the value
    203   I.replaceAllUsesWith(V);
    204 
    205   // Make sure to propagate a name if there is one already.
    206   if (I.hasName() && !V->hasName())
    207     V->takeName(&I);
    208 
    209   // Delete the unnecessary instruction now...
    210   BI = BIL.erase(BI);
    211 }
    212 
    213 
    214 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
    215 /// instruction specified by I.  The original instruction is deleted and BI is
    216 /// updated to point to the new instruction.
    217 ///
    218 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
    219                                BasicBlock::iterator &BI, Instruction *I) {
    220   assert(I->getParent() == nullptr &&
    221          "ReplaceInstWithInst: Instruction already inserted into basic block!");
    222 
    223   // Insert the new instruction into the basic block...
    224   BasicBlock::iterator New = BIL.insert(BI, I);
    225 
    226   // Replace all uses of the old instruction, and delete it.
    227   ReplaceInstWithValue(BIL, BI, I);
    228 
    229   // Move BI back to point to the newly inserted instruction
    230   BI = New;
    231 }
    232 
    233 /// ReplaceInstWithInst - Replace the instruction specified by From with the
    234 /// instruction specified by To.
    235 ///
    236 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
    237   BasicBlock::iterator BI(From);
    238   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
    239 }
    240 
    241 /// SplitEdge -  Split the edge connecting specified block. Pass P must
    242 /// not be NULL.
    243 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
    244   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
    245 
    246   // If this is a critical edge, let SplitCriticalEdge do it.
    247   TerminatorInst *LatchTerm = BB->getTerminator();
    248   if (SplitCriticalEdge(LatchTerm, SuccNum, P))
    249     return LatchTerm->getSuccessor(SuccNum);
    250 
    251   // If the edge isn't critical, then BB has a single successor or Succ has a
    252   // single pred.  Split the block.
    253   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
    254     // If the successor only has a single pred, split the top of the successor
    255     // block.
    256     assert(SP == BB && "CFG broken");
    257     SP = nullptr;
    258     return SplitBlock(Succ, Succ->begin(), P);
    259   }
    260 
    261   // Otherwise, if BB has a single successor, split it at the bottom of the
    262   // block.
    263   assert(BB->getTerminator()->getNumSuccessors() == 1 &&
    264          "Should have a single succ!");
    265   return SplitBlock(BB, BB->getTerminator(), P);
    266 }
    267 
    268 /// SplitBlock - Split the specified block at the specified instruction - every
    269 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
    270 /// to a new block.  The two blocks are joined by an unconditional branch and
    271 /// the loop info is updated.
    272 ///
    273 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
    274   BasicBlock::iterator SplitIt = SplitPt;
    275   while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
    276     ++SplitIt;
    277   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
    278 
    279   // The new block lives in whichever loop the old one did. This preserves
    280   // LCSSA as well, because we force the split point to be after any PHI nodes.
    281   if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
    282     if (Loop *L = LI->getLoopFor(Old))
    283       L->addBasicBlockToLoop(New, LI->getBase());
    284 
    285   if (DominatorTreeWrapperPass *DTWP =
    286           P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
    287     DominatorTree &DT = DTWP->getDomTree();
    288     // Old dominates New. New node dominates all other nodes dominated by Old.
    289     if (DomTreeNode *OldNode = DT.getNode(Old)) {
    290       std::vector<DomTreeNode *> Children;
    291       for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
    292            I != E; ++I)
    293         Children.push_back(*I);
    294 
    295       DomTreeNode *NewNode = DT.addNewBlock(New, Old);
    296       for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
    297              E = Children.end(); I != E; ++I)
    298         DT.changeImmediateDominator(*I, NewNode);
    299     }
    300   }
    301 
    302   return New;
    303 }
    304 
    305 /// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
    306 /// analysis information.
    307 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
    308                                       ArrayRef<BasicBlock *> Preds,
    309                                       Pass *P, bool &HasLoopExit) {
    310   if (!P) return;
    311 
    312   LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
    313   Loop *L = LI ? LI->getLoopFor(OldBB) : nullptr;
    314 
    315   // If we need to preserve loop analyses, collect some information about how
    316   // this split will affect loops.
    317   bool IsLoopEntry = !!L;
    318   bool SplitMakesNewLoopHeader = false;
    319   if (LI) {
    320     bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
    321     for (ArrayRef<BasicBlock*>::iterator
    322            i = Preds.begin(), e = Preds.end(); i != e; ++i) {
    323       BasicBlock *Pred = *i;
    324 
    325       // If we need to preserve LCSSA, determine if any of the preds is a loop
    326       // exit.
    327       if (PreserveLCSSA)
    328         if (Loop *PL = LI->getLoopFor(Pred))
    329           if (!PL->contains(OldBB))
    330             HasLoopExit = true;
    331 
    332       // If we need to preserve LoopInfo, note whether any of the preds crosses
    333       // an interesting loop boundary.
    334       if (!L) continue;
    335       if (L->contains(Pred))
    336         IsLoopEntry = false;
    337       else
    338         SplitMakesNewLoopHeader = true;
    339     }
    340   }
    341 
    342   // Update dominator tree if available.
    343   if (DominatorTreeWrapperPass *DTWP =
    344           P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
    345     DTWP->getDomTree().splitBlock(NewBB);
    346 
    347   if (!L) return;
    348 
    349   if (IsLoopEntry) {
    350     // Add the new block to the nearest enclosing loop (and not an adjacent
    351     // loop). To find this, examine each of the predecessors and determine which
    352     // loops enclose them, and select the most-nested loop which contains the
    353     // loop containing the block being split.
    354     Loop *InnermostPredLoop = nullptr;
    355     for (ArrayRef<BasicBlock*>::iterator
    356            i = Preds.begin(), e = Preds.end(); i != e; ++i) {
    357       BasicBlock *Pred = *i;
    358       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
    359         // Seek a loop which actually contains the block being split (to avoid
    360         // adjacent loops).
    361         while (PredLoop && !PredLoop->contains(OldBB))
    362           PredLoop = PredLoop->getParentLoop();
    363 
    364         // Select the most-nested of these loops which contains the block.
    365         if (PredLoop && PredLoop->contains(OldBB) &&
    366             (!InnermostPredLoop ||
    367              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
    368           InnermostPredLoop = PredLoop;
    369       }
    370     }
    371 
    372     if (InnermostPredLoop)
    373       InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
    374   } else {
    375     L->addBasicBlockToLoop(NewBB, LI->getBase());
    376     if (SplitMakesNewLoopHeader)
    377       L->moveToHeader(NewBB);
    378   }
    379 }
    380 
    381 /// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
    382 /// from NewBB. This also updates AliasAnalysis, if available.
    383 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
    384                            ArrayRef<BasicBlock*> Preds, BranchInst *BI,
    385                            Pass *P, bool HasLoopExit) {
    386   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
    387   AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : nullptr;
    388   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
    389   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
    390     PHINode *PN = cast<PHINode>(I++);
    391 
    392     // Check to see if all of the values coming in are the same.  If so, we
    393     // don't need to create a new PHI node, unless it's needed for LCSSA.
    394     Value *InVal = nullptr;
    395     if (!HasLoopExit) {
    396       InVal = PN->getIncomingValueForBlock(Preds[0]);
    397       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
    398         if (!PredSet.count(PN->getIncomingBlock(i)))
    399           continue;
    400         if (!InVal)
    401           InVal = PN->getIncomingValue(i);
    402         else if (InVal != PN->getIncomingValue(i)) {
    403           InVal = nullptr;
    404           break;
    405         }
    406       }
    407     }
    408 
    409     if (InVal) {
    410       // If all incoming values for the new PHI would be the same, just don't
    411       // make a new PHI.  Instead, just remove the incoming values from the old
    412       // PHI.
    413 
    414       // NOTE! This loop walks backwards for a reason! First off, this minimizes
    415       // the cost of removal if we end up removing a large number of values, and
    416       // second off, this ensures that the indices for the incoming values
    417       // aren't invalidated when we remove one.
    418       for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
    419         if (PredSet.count(PN->getIncomingBlock(i)))
    420           PN->removeIncomingValue(i, false);
    421 
    422       // Add an incoming value to the PHI node in the loop for the preheader
    423       // edge.
    424       PN->addIncoming(InVal, NewBB);
    425       continue;
    426     }
    427 
    428     // If the values coming into the block are not the same, we need a new
    429     // PHI.
    430     // Create the new PHI node, insert it into NewBB at the end of the block
    431     PHINode *NewPHI =
    432         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
    433     if (AA)
    434       AA->copyValue(PN, NewPHI);
    435 
    436     // NOTE! This loop walks backwards for a reason! First off, this minimizes
    437     // the cost of removal if we end up removing a large number of values, and
    438     // second off, this ensures that the indices for the incoming values aren't
    439     // invalidated when we remove one.
    440     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
    441       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
    442       if (PredSet.count(IncomingBB)) {
    443         Value *V = PN->removeIncomingValue(i, false);
    444         NewPHI->addIncoming(V, IncomingBB);
    445       }
    446     }
    447 
    448     PN->addIncoming(NewPHI, NewBB);
    449   }
    450 }
    451 
    452 /// SplitBlockPredecessors - This method transforms BB by introducing a new
    453 /// basic block into the function, and moving some of the predecessors of BB to
    454 /// be predecessors of the new block.  The new predecessors are indicated by the
    455 /// Preds array, which has NumPreds elements in it.  The new block is given a
    456 /// suffix of 'Suffix'.
    457 ///
    458 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
    459 /// LoopInfo, and LCCSA but no other analyses. In particular, it does not
    460 /// preserve LoopSimplify (because it's complicated to handle the case where one
    461 /// of the edges being split is an exit of a loop with other exits).
    462 ///
    463 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
    464                                          ArrayRef<BasicBlock*> Preds,
    465                                          const char *Suffix, Pass *P) {
    466   // Create new basic block, insert right before the original block.
    467   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
    468                                          BB->getParent(), BB);
    469 
    470   // The new block unconditionally branches to the old block.
    471   BranchInst *BI = BranchInst::Create(BB, NewBB);
    472 
    473   // Move the edges from Preds to point to NewBB instead of BB.
    474   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
    475     // This is slightly more strict than necessary; the minimum requirement
    476     // is that there be no more than one indirectbr branching to BB. And
    477     // all BlockAddress uses would need to be updated.
    478     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
    479            "Cannot split an edge from an IndirectBrInst");
    480     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
    481   }
    482 
    483   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
    484   // node becomes an incoming value for BB's phi node.  However, if the Preds
    485   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
    486   // account for the newly created predecessor.
    487   if (Preds.size() == 0) {
    488     // Insert dummy values as the incoming value.
    489     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
    490       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
    491     return NewBB;
    492   }
    493 
    494   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
    495   bool HasLoopExit = false;
    496   UpdateAnalysisInformation(BB, NewBB, Preds, P, HasLoopExit);
    497 
    498   // Update the PHI nodes in BB with the values coming from NewBB.
    499   UpdatePHINodes(BB, NewBB, Preds, BI, P, HasLoopExit);
    500   return NewBB;
    501 }
    502 
    503 /// SplitLandingPadPredecessors - This method transforms the landing pad,
    504 /// OrigBB, by introducing two new basic blocks into the function. One of those
    505 /// new basic blocks gets the predecessors listed in Preds. The other basic
    506 /// block gets the remaining predecessors of OrigBB. The landingpad instruction
    507 /// OrigBB is clone into both of the new basic blocks. The new blocks are given
    508 /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
    509 ///
    510 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
    511 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
    512 /// it does not preserve LoopSimplify (because it's complicated to handle the
    513 /// case where one of the edges being split is an exit of a loop with other
    514 /// exits).
    515 ///
    516 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
    517                                        ArrayRef<BasicBlock*> Preds,
    518                                        const char *Suffix1, const char *Suffix2,
    519                                        Pass *P,
    520                                        SmallVectorImpl<BasicBlock*> &NewBBs) {
    521   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
    522 
    523   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
    524   // it right before the original block.
    525   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
    526                                           OrigBB->getName() + Suffix1,
    527                                           OrigBB->getParent(), OrigBB);
    528   NewBBs.push_back(NewBB1);
    529 
    530   // The new block unconditionally branches to the old block.
    531   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
    532 
    533   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
    534   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
    535     // This is slightly more strict than necessary; the minimum requirement
    536     // is that there be no more than one indirectbr branching to BB. And
    537     // all BlockAddress uses would need to be updated.
    538     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
    539            "Cannot split an edge from an IndirectBrInst");
    540     Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
    541   }
    542 
    543   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
    544   bool HasLoopExit = false;
    545   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, P, HasLoopExit);
    546 
    547   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
    548   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, P, HasLoopExit);
    549 
    550   // Move the remaining edges from OrigBB to point to NewBB2.
    551   SmallVector<BasicBlock*, 8> NewBB2Preds;
    552   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
    553        i != e; ) {
    554     BasicBlock *Pred = *i++;
    555     if (Pred == NewBB1) continue;
    556     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
    557            "Cannot split an edge from an IndirectBrInst");
    558     NewBB2Preds.push_back(Pred);
    559     e = pred_end(OrigBB);
    560   }
    561 
    562   BasicBlock *NewBB2 = nullptr;
    563   if (!NewBB2Preds.empty()) {
    564     // Create another basic block for the rest of OrigBB's predecessors.
    565     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
    566                                 OrigBB->getName() + Suffix2,
    567                                 OrigBB->getParent(), OrigBB);
    568     NewBBs.push_back(NewBB2);
    569 
    570     // The new block unconditionally branches to the old block.
    571     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
    572 
    573     // Move the remaining edges from OrigBB to point to NewBB2.
    574     for (SmallVectorImpl<BasicBlock*>::iterator
    575            i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
    576       (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
    577 
    578     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
    579     HasLoopExit = false;
    580     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, P, HasLoopExit);
    581 
    582     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
    583     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, P, HasLoopExit);
    584   }
    585 
    586   LandingPadInst *LPad = OrigBB->getLandingPadInst();
    587   Instruction *Clone1 = LPad->clone();
    588   Clone1->setName(Twine("lpad") + Suffix1);
    589   NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
    590 
    591   if (NewBB2) {
    592     Instruction *Clone2 = LPad->clone();
    593     Clone2->setName(Twine("lpad") + Suffix2);
    594     NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
    595 
    596     // Create a PHI node for the two cloned landingpad instructions.
    597     PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
    598     PN->addIncoming(Clone1, NewBB1);
    599     PN->addIncoming(Clone2, NewBB2);
    600     LPad->replaceAllUsesWith(PN);
    601     LPad->eraseFromParent();
    602   } else {
    603     // There is no second clone. Just replace the landing pad with the first
    604     // clone.
    605     LPad->replaceAllUsesWith(Clone1);
    606     LPad->eraseFromParent();
    607   }
    608 }
    609 
    610 /// FoldReturnIntoUncondBranch - This method duplicates the specified return
    611 /// instruction into a predecessor which ends in an unconditional branch. If
    612 /// the return instruction returns a value defined by a PHI, propagate the
    613 /// right value into the return. It returns the new return instruction in the
    614 /// predecessor.
    615 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
    616                                              BasicBlock *Pred) {
    617   Instruction *UncondBranch = Pred->getTerminator();
    618   // Clone the return and add it to the end of the predecessor.
    619   Instruction *NewRet = RI->clone();
    620   Pred->getInstList().push_back(NewRet);
    621 
    622   // If the return instruction returns a value, and if the value was a
    623   // PHI node in "BB", propagate the right value into the return.
    624   for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
    625        i != e; ++i) {
    626     Value *V = *i;
    627     Instruction *NewBC = nullptr;
    628     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
    629       // Return value might be bitcasted. Clone and insert it before the
    630       // return instruction.
    631       V = BCI->getOperand(0);
    632       NewBC = BCI->clone();
    633       Pred->getInstList().insert(NewRet, NewBC);
    634       *i = NewBC;
    635     }
    636     if (PHINode *PN = dyn_cast<PHINode>(V)) {
    637       if (PN->getParent() == BB) {
    638         if (NewBC)
    639           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
    640         else
    641           *i = PN->getIncomingValueForBlock(Pred);
    642       }
    643     }
    644   }
    645 
    646   // Update any PHI nodes in the returning block to realize that we no
    647   // longer branch to them.
    648   BB->removePredecessor(Pred);
    649   UncondBranch->eraseFromParent();
    650   return cast<ReturnInst>(NewRet);
    651 }
    652 
    653 /// SplitBlockAndInsertIfThen - Split the containing block at the
    654 /// specified instruction - everything before and including SplitBefore stays
    655 /// in the old basic block, and everything after SplitBefore is moved to a
    656 /// new block. The two blocks are connected by a conditional branch
    657 /// (with value of Cmp being the condition).
    658 /// Before:
    659 ///   Head
    660 ///   SplitBefore
    661 ///   Tail
    662 /// After:
    663 ///   Head
    664 ///   if (Cond)
    665 ///     ThenBlock
    666 ///   SplitBefore
    667 ///   Tail
    668 ///
    669 /// If Unreachable is true, then ThenBlock ends with
    670 /// UnreachableInst, otherwise it branches to Tail.
    671 /// Returns the NewBasicBlock's terminator.
    672 
    673 TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
    674                                                 Instruction *SplitBefore,
    675                                                 bool Unreachable,
    676                                                 MDNode *BranchWeights) {
    677   BasicBlock *Head = SplitBefore->getParent();
    678   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
    679   TerminatorInst *HeadOldTerm = Head->getTerminator();
    680   LLVMContext &C = Head->getContext();
    681   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
    682   TerminatorInst *CheckTerm;
    683   if (Unreachable)
    684     CheckTerm = new UnreachableInst(C, ThenBlock);
    685   else
    686     CheckTerm = BranchInst::Create(Tail, ThenBlock);
    687   CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
    688   BranchInst *HeadNewTerm =
    689     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
    690   HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
    691   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
    692   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
    693   return CheckTerm;
    694 }
    695 
    696 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
    697 /// but also creates the ElseBlock.
    698 /// Before:
    699 ///   Head
    700 ///   SplitBefore
    701 ///   Tail
    702 /// After:
    703 ///   Head
    704 ///   if (Cond)
    705 ///     ThenBlock
    706 ///   else
    707 ///     ElseBlock
    708 ///   SplitBefore
    709 ///   Tail
    710 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
    711                                          TerminatorInst **ThenTerm,
    712                                          TerminatorInst **ElseTerm,
    713                                          MDNode *BranchWeights) {
    714   BasicBlock *Head = SplitBefore->getParent();
    715   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
    716   TerminatorInst *HeadOldTerm = Head->getTerminator();
    717   LLVMContext &C = Head->getContext();
    718   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
    719   BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
    720   *ThenTerm = BranchInst::Create(Tail, ThenBlock);
    721   (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
    722   *ElseTerm = BranchInst::Create(Tail, ElseBlock);
    723   (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
    724   BranchInst *HeadNewTerm =
    725     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
    726   HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
    727   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
    728   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
    729 }
    730 
    731 
    732 /// GetIfCondition - Given a basic block (BB) with two predecessors,
    733 /// check to see if the merge at this block is due
    734 /// to an "if condition".  If so, return the boolean condition that determines
    735 /// which entry into BB will be taken.  Also, return by references the block
    736 /// that will be entered from if the condition is true, and the block that will
    737 /// be entered if the condition is false.
    738 ///
    739 /// This does no checking to see if the true/false blocks have large or unsavory
    740 /// instructions in them.
    741 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
    742                              BasicBlock *&IfFalse) {
    743   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
    744   BasicBlock *Pred1 = nullptr;
    745   BasicBlock *Pred2 = nullptr;
    746 
    747   if (SomePHI) {
    748     if (SomePHI->getNumIncomingValues() != 2)
    749       return nullptr;
    750     Pred1 = SomePHI->getIncomingBlock(0);
    751     Pred2 = SomePHI->getIncomingBlock(1);
    752   } else {
    753     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
    754     if (PI == PE) // No predecessor
    755       return nullptr;
    756     Pred1 = *PI++;
    757     if (PI == PE) // Only one predecessor
    758       return nullptr;
    759     Pred2 = *PI++;
    760     if (PI != PE) // More than two predecessors
    761       return nullptr;
    762   }
    763 
    764   // We can only handle branches.  Other control flow will be lowered to
    765   // branches if possible anyway.
    766   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
    767   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
    768   if (!Pred1Br || !Pred2Br)
    769     return nullptr;
    770 
    771   // Eliminate code duplication by ensuring that Pred1Br is conditional if
    772   // either are.
    773   if (Pred2Br->isConditional()) {
    774     // If both branches are conditional, we don't have an "if statement".  In
    775     // reality, we could transform this case, but since the condition will be
    776     // required anyway, we stand no chance of eliminating it, so the xform is
    777     // probably not profitable.
    778     if (Pred1Br->isConditional())
    779       return nullptr;
    780 
    781     std::swap(Pred1, Pred2);
    782     std::swap(Pred1Br, Pred2Br);
    783   }
    784 
    785   if (Pred1Br->isConditional()) {
    786     // The only thing we have to watch out for here is to make sure that Pred2
    787     // doesn't have incoming edges from other blocks.  If it does, the condition
    788     // doesn't dominate BB.
    789     if (!Pred2->getSinglePredecessor())
    790       return nullptr;
    791 
    792     // If we found a conditional branch predecessor, make sure that it branches
    793     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
    794     if (Pred1Br->getSuccessor(0) == BB &&
    795         Pred1Br->getSuccessor(1) == Pred2) {
    796       IfTrue = Pred1;
    797       IfFalse = Pred2;
    798     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
    799                Pred1Br->getSuccessor(1) == BB) {
    800       IfTrue = Pred2;
    801       IfFalse = Pred1;
    802     } else {
    803       // We know that one arm of the conditional goes to BB, so the other must
    804       // go somewhere unrelated, and this must not be an "if statement".
    805       return nullptr;
    806     }
    807 
    808     return Pred1Br->getCondition();
    809   }
    810 
    811   // Ok, if we got here, both predecessors end with an unconditional branch to
    812   // BB.  Don't panic!  If both blocks only have a single (identical)
    813   // predecessor, and THAT is a conditional branch, then we're all ok!
    814   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
    815   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
    816     return nullptr;
    817 
    818   // Otherwise, if this is a conditional branch, then we can use it!
    819   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
    820   if (!BI) return nullptr;
    821 
    822   assert(BI->isConditional() && "Two successors but not conditional?");
    823   if (BI->getSuccessor(0) == Pred1) {
    824     IfTrue = Pred1;
    825     IfFalse = Pred2;
    826   } else {
    827     IfTrue = Pred2;
    828     IfFalse = Pred1;
    829   }
    830   return BI->getCondition();
    831 }
    832