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