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