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