xref: /llvm-project/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp (revision 6d23aaad4ffdcdda56845e4ca392f09c5795630a)
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/IR/BasicBlock.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfo.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/IRBuilder.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/User.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include <cassert>
47 #include <cstdint>
48 #include <string>
49 #include <utility>
50 #include <vector>
51 
52 using namespace llvm;
53 
54 #define DEBUG_TYPE "basicblock-utils"
55 
56 static cl::opt<unsigned> MaxDeoptOrUnreachableSuccessorCheckDepth(
57     "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
58     cl::desc("Set the maximum path length when checking whether a basic block "
59              "is followed by a block that either has a terminating "
60              "deoptimizing call or is terminated with an unreachable"));
61 
62 void llvm::detachDeadBlocks(
63     ArrayRef<BasicBlock *> BBs,
64     SmallVectorImpl<DominatorTree::UpdateType> *Updates,
65     bool KeepOneInputPHIs) {
66   for (auto *BB : BBs) {
67     // Loop through all of our successors and make sure they know that one
68     // of their predecessors is going away.
69     SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
70     for (BasicBlock *Succ : successors(BB)) {
71       Succ->removePredecessor(BB, KeepOneInputPHIs);
72       if (Updates && UniqueSuccessors.insert(Succ).second)
73         Updates->push_back({DominatorTree::Delete, BB, Succ});
74     }
75 
76     // Zap all the instructions in the block.
77     while (!BB->empty()) {
78       Instruction &I = BB->back();
79       // If this instruction is used, replace uses with an arbitrary value.
80       // Because control flow can't get here, we don't care what we replace the
81       // value with.  Note that since this block is unreachable, and all values
82       // contained within it must dominate their uses, that all uses will
83       // eventually be removed (they are themselves dead).
84       if (!I.use_empty())
85         I.replaceAllUsesWith(PoisonValue::get(I.getType()));
86       BB->back().eraseFromParent();
87     }
88     new UnreachableInst(BB->getContext(), BB);
89     assert(BB->size() == 1 &&
90            isa<UnreachableInst>(BB->getTerminator()) &&
91            "The successor list of BB isn't empty before "
92            "applying corresponding DTU updates.");
93   }
94 }
95 
96 void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
97                            bool KeepOneInputPHIs) {
98   DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
99 }
100 
101 void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
102                             bool KeepOneInputPHIs) {
103 #ifndef NDEBUG
104   // Make sure that all predecessors of each dead block is also dead.
105   SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
106   assert(Dead.size() == BBs.size() && "Duplicating blocks?");
107   for (auto *BB : Dead)
108     for (BasicBlock *Pred : predecessors(BB))
109       assert(Dead.count(Pred) && "All predecessors must be dead!");
110 #endif
111 
112   SmallVector<DominatorTree::UpdateType, 4> Updates;
113   detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
114 
115   if (DTU)
116     DTU->applyUpdates(Updates);
117 
118   for (BasicBlock *BB : BBs)
119     if (DTU)
120       DTU->deleteBB(BB);
121     else
122       BB->eraseFromParent();
123 }
124 
125 bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
126                                       bool KeepOneInputPHIs) {
127   df_iterator_default_set<BasicBlock*> Reachable;
128 
129   // Mark all reachable blocks.
130   for (BasicBlock *BB : depth_first_ext(&F, Reachable))
131     (void)BB/* Mark all reachable blocks */;
132 
133   // Collect all dead blocks.
134   std::vector<BasicBlock*> DeadBlocks;
135   for (BasicBlock &BB : F)
136     if (!Reachable.count(&BB))
137       DeadBlocks.push_back(&BB);
138 
139   // Delete the dead blocks.
140   DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
141 
142   return !DeadBlocks.empty();
143 }
144 
145 bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
146                                    MemoryDependenceResults *MemDep) {
147   if (!isa<PHINode>(BB->begin()))
148     return false;
149 
150   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
151     if (PN->getIncomingValue(0) != PN)
152       PN->replaceAllUsesWith(PN->getIncomingValue(0));
153     else
154       PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
155 
156     if (MemDep)
157       MemDep->removeInstruction(PN);  // Memdep updates AA itself.
158 
159     PN->eraseFromParent();
160   }
161   return true;
162 }
163 
164 bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI,
165                           MemorySSAUpdater *MSSAU) {
166   // Recursively deleting a PHI may cause multiple PHIs to be deleted
167   // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
168   SmallVector<WeakTrackingVH, 8> PHIs;
169   for (PHINode &PN : BB->phis())
170     PHIs.push_back(&PN);
171 
172   bool Changed = false;
173   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
174     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
175       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
176 
177   return Changed;
178 }
179 
180 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
181                                      LoopInfo *LI, MemorySSAUpdater *MSSAU,
182                                      MemoryDependenceResults *MemDep,
183                                      bool PredecessorWithTwoSuccessors,
184                                      DominatorTree *DT) {
185   if (BB->hasAddressTaken())
186     return false;
187 
188   // Can't merge if there are multiple predecessors, or no predecessors.
189   BasicBlock *PredBB = BB->getUniquePredecessor();
190   if (!PredBB) return false;
191 
192   // Don't break self-loops.
193   if (PredBB == BB) return false;
194 
195   // Don't break unwinding instructions or terminators with other side-effects.
196   Instruction *PTI = PredBB->getTerminator();
197   if (PTI->isSpecialTerminator() || PTI->mayHaveSideEffects())
198     return false;
199 
200   // Can't merge if there are multiple distinct successors.
201   if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
202     return false;
203 
204   // Currently only allow PredBB to have two predecessors, one being BB.
205   // Update BI to branch to BB's only successor instead of BB.
206   BranchInst *PredBB_BI;
207   BasicBlock *NewSucc = nullptr;
208   unsigned FallThruPath;
209   if (PredecessorWithTwoSuccessors) {
210     if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
211       return false;
212     BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
213     if (!BB_JmpI || !BB_JmpI->isUnconditional())
214       return false;
215     NewSucc = BB_JmpI->getSuccessor(0);
216     FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
217   }
218 
219   // Can't merge if there is PHI loop.
220   for (PHINode &PN : BB->phis())
221     if (llvm::is_contained(PN.incoming_values(), &PN))
222       return false;
223 
224   LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
225                     << PredBB->getName() << "\n");
226 
227   // Begin by getting rid of unneeded PHIs.
228   SmallVector<AssertingVH<Value>, 4> IncomingValues;
229   if (isa<PHINode>(BB->front())) {
230     for (PHINode &PN : BB->phis())
231       if (!isa<PHINode>(PN.getIncomingValue(0)) ||
232           cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
233         IncomingValues.push_back(PN.getIncomingValue(0));
234     FoldSingleEntryPHINodes(BB, MemDep);
235   }
236 
237   if (DT) {
238     assert(!DTU && "cannot use both DT and DTU for updates");
239     DomTreeNode *PredNode = DT->getNode(PredBB);
240     DomTreeNode *BBNode = DT->getNode(BB);
241     if (PredNode) {
242       assert(BBNode && "PredNode unreachable but BBNode reachable?");
243       for (DomTreeNode *C : to_vector(BBNode->children()))
244         C->setIDom(PredNode);
245     }
246   }
247   // DTU update: Collect all the edges that exit BB.
248   // These dominator edges will be redirected from Pred.
249   std::vector<DominatorTree::UpdateType> Updates;
250   if (DTU) {
251     assert(!DT && "cannot use both DT and DTU for updates");
252     // To avoid processing the same predecessor more than once.
253     SmallPtrSet<BasicBlock *, 8> SeenSuccs;
254     SmallPtrSet<BasicBlock *, 2> SuccsOfPredBB(succ_begin(PredBB),
255                                                succ_end(PredBB));
256     Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
257     // Add insert edges first. Experimentally, for the particular case of two
258     // blocks that can be merged, with a single successor and single predecessor
259     // respectively, it is beneficial to have all insert updates first. Deleting
260     // edges first may lead to unreachable blocks, followed by inserting edges
261     // making the blocks reachable again. Such DT updates lead to high compile
262     // times. We add inserts before deletes here to reduce compile time.
263     for (BasicBlock *SuccOfBB : successors(BB))
264       // This successor of BB may already be a PredBB's successor.
265       if (!SuccsOfPredBB.contains(SuccOfBB))
266         if (SeenSuccs.insert(SuccOfBB).second)
267           Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
268     SeenSuccs.clear();
269     for (BasicBlock *SuccOfBB : successors(BB))
270       if (SeenSuccs.insert(SuccOfBB).second)
271         Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
272     Updates.push_back({DominatorTree::Delete, PredBB, BB});
273   }
274 
275   Instruction *STI = BB->getTerminator();
276   Instruction *Start = &*BB->begin();
277   // If there's nothing to move, mark the starting instruction as the last
278   // instruction in the block. Terminator instruction is handled separately.
279   if (Start == STI)
280     Start = PTI;
281 
282   // Move all definitions in the successor to the predecessor...
283   PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
284 
285   if (MSSAU)
286     MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
287 
288   // Make all PHI nodes that referred to BB now refer to Pred as their
289   // source...
290   BB->replaceAllUsesWith(PredBB);
291 
292   if (PredecessorWithTwoSuccessors) {
293     // Delete the unconditional branch from BB.
294     BB->back().eraseFromParent();
295 
296     // Update branch in the predecessor.
297     PredBB_BI->setSuccessor(FallThruPath, NewSucc);
298   } else {
299     // Delete the unconditional branch from the predecessor.
300     PredBB->back().eraseFromParent();
301 
302     // Move terminator instruction.
303     BB->back().moveBeforePreserving(*PredBB, PredBB->end());
304 
305     // Terminator may be a memory accessing instruction too.
306     if (MSSAU)
307       if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
308               MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
309         MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
310   }
311   // Add unreachable to now empty BB.
312   new UnreachableInst(BB->getContext(), BB);
313 
314   // Inherit predecessors name if it exists.
315   if (!PredBB->hasName())
316     PredBB->takeName(BB);
317 
318   if (LI)
319     LI->removeBlock(BB);
320 
321   if (MemDep)
322     MemDep->invalidateCachedPredecessors();
323 
324   if (DTU)
325     DTU->applyUpdates(Updates);
326 
327   if (DT) {
328     assert(succ_empty(BB) &&
329            "successors should have been transferred to PredBB");
330     DT->eraseNode(BB);
331   }
332 
333   // Finally, erase the old block and update dominator info.
334   DeleteDeadBlock(BB, DTU);
335 
336   return true;
337 }
338 
339 bool llvm::MergeBlockSuccessorsIntoGivenBlocks(
340     SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU,
341     LoopInfo *LI) {
342   assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
343 
344   bool BlocksHaveBeenMerged = false;
345   while (!MergeBlocks.empty()) {
346     BasicBlock *BB = *MergeBlocks.begin();
347     BasicBlock *Dest = BB->getSingleSuccessor();
348     if (Dest && (!L || L->contains(Dest))) {
349       BasicBlock *Fold = Dest->getUniquePredecessor();
350       (void)Fold;
351       if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
352         assert(Fold == BB &&
353                "Expecting BB to be unique predecessor of the Dest block");
354         MergeBlocks.erase(Dest);
355         BlocksHaveBeenMerged = true;
356       } else
357         MergeBlocks.erase(BB);
358     } else
359       MergeBlocks.erase(BB);
360   }
361   return BlocksHaveBeenMerged;
362 }
363 
364 /// Remove redundant instructions within sequences of consecutive dbg.value
365 /// instructions. This is done using a backward scan to keep the last dbg.value
366 /// describing a specific variable/fragment.
367 ///
368 /// BackwardScan strategy:
369 /// ----------------------
370 /// Given a sequence of consecutive DbgValueInst like this
371 ///
372 ///   dbg.value ..., "x", FragmentX1  (*)
373 ///   dbg.value ..., "y", FragmentY1
374 ///   dbg.value ..., "x", FragmentX2
375 ///   dbg.value ..., "x", FragmentX1  (**)
376 ///
377 /// then the instruction marked with (*) can be removed (it is guaranteed to be
378 /// obsoleted by the instruction marked with (**) as the latter instruction is
379 /// describing the same variable using the same fragment info).
380 ///
381 /// Possible improvements:
382 /// - Check fully overlapping fragments and not only identical fragments.
383 /// - Support dbg.declare. dbg.label, and possibly other meta instructions being
384 ///   part of the sequence of consecutive instructions.
385 static bool DPValuesRemoveRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
386   SmallVector<DPValue *, 8> ToBeRemoved;
387   SmallDenseSet<DebugVariable> VariableSet;
388   for (auto &I : reverse(*BB)) {
389     for (DPValue &DPV : reverse(I.getDbgValueRange())) {
390       DebugVariable Key(DPV.getVariable(), DPV.getExpression(),
391                         DPV.getDebugLoc()->getInlinedAt());
392       auto R = VariableSet.insert(Key);
393       // If the same variable fragment is described more than once it is enough
394       // to keep the last one (i.e. the first found since we for reverse
395       // iteration).
396       // FIXME: add assignment tracking support (see parallel implementation
397       // below).
398       if (!R.second)
399         ToBeRemoved.push_back(&DPV);
400       continue;
401     }
402     // Sequence with consecutive dbg.value instrs ended. Clear the map to
403     // restart identifying redundant instructions if case we find another
404     // dbg.value sequence.
405     VariableSet.clear();
406   }
407 
408   for (auto &DPV : ToBeRemoved)
409     DPV->eraseFromParent();
410 
411   return !ToBeRemoved.empty();
412 }
413 
414 static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
415   if (BB->IsNewDbgInfoFormat)
416     return DPValuesRemoveRedundantDbgInstrsUsingBackwardScan(BB);
417 
418   SmallVector<DbgValueInst *, 8> ToBeRemoved;
419   SmallDenseSet<DebugVariable> VariableSet;
420   for (auto &I : reverse(*BB)) {
421     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
422       DebugVariable Key(DVI->getVariable(),
423                         DVI->getExpression(),
424                         DVI->getDebugLoc()->getInlinedAt());
425       auto R = VariableSet.insert(Key);
426       // If the variable fragment hasn't been seen before then we don't want
427       // to remove this dbg intrinsic.
428       if (R.second)
429         continue;
430 
431       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI)) {
432         // Don't delete dbg.assign intrinsics that are linked to instructions.
433         if (!at::getAssignmentInsts(DAI).empty())
434           continue;
435         // Unlinked dbg.assign intrinsics can be treated like dbg.values.
436       }
437 
438       // If the same variable fragment is described more than once it is enough
439       // to keep the last one (i.e. the first found since we for reverse
440       // iteration).
441       ToBeRemoved.push_back(DVI);
442       continue;
443     }
444     // Sequence with consecutive dbg.value instrs ended. Clear the map to
445     // restart identifying redundant instructions if case we find another
446     // dbg.value sequence.
447     VariableSet.clear();
448   }
449 
450   for (auto &Instr : ToBeRemoved)
451     Instr->eraseFromParent();
452 
453   return !ToBeRemoved.empty();
454 }
455 
456 /// Remove redundant dbg.value instructions using a forward scan. This can
457 /// remove a dbg.value instruction that is redundant due to indicating that a
458 /// variable has the same value as already being indicated by an earlier
459 /// dbg.value.
460 ///
461 /// ForwardScan strategy:
462 /// ---------------------
463 /// Given two identical dbg.value instructions, separated by a block of
464 /// instructions that isn't describing the same variable, like this
465 ///
466 ///   dbg.value X1, "x", FragmentX1  (**)
467 ///   <block of instructions, none being "dbg.value ..., "x", ...">
468 ///   dbg.value X1, "x", FragmentX1  (*)
469 ///
470 /// then the instruction marked with (*) can be removed. Variable "x" is already
471 /// described as being mapped to the SSA value X1.
472 ///
473 /// Possible improvements:
474 /// - Keep track of non-overlapping fragments.
475 static bool DPValuesRemoveRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
476   SmallVector<DPValue *, 8> ToBeRemoved;
477   DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
478       VariableMap;
479   for (auto &I : *BB) {
480     for (DPValue &DPV : I.getDbgValueRange()) {
481       DebugVariable Key(DPV.getVariable(), std::nullopt,
482                         DPV.getDebugLoc()->getInlinedAt());
483       auto VMI = VariableMap.find(Key);
484       // Update the map if we found a new value/expression describing the
485       // variable, or if the variable wasn't mapped already.
486       SmallVector<Value *, 4> Values(DPV.location_ops());
487       if (VMI == VariableMap.end() || VMI->second.first != Values ||
488           VMI->second.second != DPV.getExpression()) {
489         VariableMap[Key] = {Values, DPV.getExpression()};
490         continue;
491       }
492       // Found an identical mapping. Remember the instruction for later removal.
493       ToBeRemoved.push_back(&DPV);
494     }
495   }
496 
497   for (auto *DPV : ToBeRemoved)
498     DPV->eraseFromParent();
499 
500   return !ToBeRemoved.empty();
501 }
502 
503 static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
504   if (BB->IsNewDbgInfoFormat)
505     return DPValuesRemoveRedundantDbgInstrsUsingForwardScan(BB);
506 
507   SmallVector<DbgValueInst *, 8> ToBeRemoved;
508   DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
509       VariableMap;
510   for (auto &I : *BB) {
511     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
512       DebugVariable Key(DVI->getVariable(), std::nullopt,
513                         DVI->getDebugLoc()->getInlinedAt());
514       auto VMI = VariableMap.find(Key);
515       auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
516       // A dbg.assign with no linked instructions can be treated like a
517       // dbg.value (i.e. can be deleted).
518       bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
519 
520       // Update the map if we found a new value/expression describing the
521       // variable, or if the variable wasn't mapped already.
522       SmallVector<Value *, 4> Values(DVI->getValues());
523       if (VMI == VariableMap.end() || VMI->second.first != Values ||
524           VMI->second.second != DVI->getExpression()) {
525         // Use a sentinal value (nullptr) for the DIExpression when we see a
526         // linked dbg.assign so that the next debug intrinsic will never match
527         // it (i.e. always treat linked dbg.assigns as if they're unique).
528         if (IsDbgValueKind)
529           VariableMap[Key] = {Values, DVI->getExpression()};
530         else
531           VariableMap[Key] = {Values, nullptr};
532         continue;
533       }
534 
535       // Don't delete dbg.assign intrinsics that are linked to instructions.
536       if (!IsDbgValueKind)
537         continue;
538       ToBeRemoved.push_back(DVI);
539     }
540   }
541 
542   for (auto &Instr : ToBeRemoved)
543     Instr->eraseFromParent();
544 
545   return !ToBeRemoved.empty();
546 }
547 
548 /// Remove redundant undef dbg.assign intrinsic from an entry block using a
549 /// forward scan.
550 /// Strategy:
551 /// ---------------------
552 /// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
553 /// linked to an intrinsic, and don't share an aggregate variable with a debug
554 /// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
555 /// that come before non-undef debug intrinsics for the variable are
556 /// deleted. Given:
557 ///
558 ///   dbg.assign undef, "x", FragmentX1 (*)
559 ///   <block of instructions, none being "dbg.value ..., "x", ...">
560 ///   dbg.value %V, "x", FragmentX2
561 ///   <block of instructions, none being "dbg.value ..., "x", ...">
562 ///   dbg.assign undef, "x", FragmentX1
563 ///
564 /// then (only) the instruction marked with (*) can be removed.
565 /// Possible improvements:
566 /// - Keep track of non-overlapping fragments.
567 static bool remomveUndefDbgAssignsFromEntryBlock(BasicBlock *BB) {
568   assert(BB->isEntryBlock() && "expected entry block");
569   SmallVector<DbgAssignIntrinsic *, 8> ToBeRemoved;
570   DenseSet<DebugVariable> SeenDefForAggregate;
571   // Returns the DebugVariable for DVI with no fragment info.
572   auto GetAggregateVariable = [](DbgValueInst *DVI) {
573     return DebugVariable(DVI->getVariable(), std::nullopt,
574                          DVI->getDebugLoc()->getInlinedAt());
575   };
576 
577   // Remove undef dbg.assign intrinsics that are encountered before
578   // any non-undef intrinsics from the entry block.
579   for (auto &I : *BB) {
580     DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I);
581     if (!DVI)
582       continue;
583     auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
584     bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
585     DebugVariable Aggregate = GetAggregateVariable(DVI);
586     if (!SeenDefForAggregate.contains(Aggregate)) {
587       bool IsKill = DVI->isKillLocation() && IsDbgValueKind;
588       if (!IsKill) {
589         SeenDefForAggregate.insert(Aggregate);
590       } else if (DAI) {
591         ToBeRemoved.push_back(DAI);
592       }
593     }
594   }
595 
596   for (DbgAssignIntrinsic *DAI : ToBeRemoved)
597     DAI->eraseFromParent();
598 
599   return !ToBeRemoved.empty();
600 }
601 
602 bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) {
603   bool MadeChanges = false;
604   // By using the "backward scan" strategy before the "forward scan" strategy we
605   // can remove both dbg.value (2) and (3) in a situation like this:
606   //
607   //   (1) dbg.value V1, "x", DIExpression()
608   //       ...
609   //   (2) dbg.value V2, "x", DIExpression()
610   //   (3) dbg.value V1, "x", DIExpression()
611   //
612   // The backward scan will remove (2), it is made obsolete by (3). After
613   // getting (2) out of the way, the foward scan will remove (3) since "x"
614   // already is described as having the value V1 at (1).
615   MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB);
616   if (BB->isEntryBlock() &&
617       isAssignmentTrackingEnabled(*BB->getParent()->getParent()))
618     MadeChanges |= remomveUndefDbgAssignsFromEntryBlock(BB);
619   MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB);
620 
621   if (MadeChanges)
622     LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
623                       << BB->getName() << "\n");
624   return MadeChanges;
625 }
626 
627 void llvm::ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V) {
628   Instruction &I = *BI;
629   // Replaces all of the uses of the instruction with uses of the value
630   I.replaceAllUsesWith(V);
631 
632   // Make sure to propagate a name if there is one already.
633   if (I.hasName() && !V->hasName())
634     V->takeName(&I);
635 
636   // Delete the unnecessary instruction now...
637   BI = BI->eraseFromParent();
638 }
639 
640 void llvm::ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI,
641                                Instruction *I) {
642   assert(I->getParent() == nullptr &&
643          "ReplaceInstWithInst: Instruction already inserted into basic block!");
644 
645   // Copy debug location to newly added instruction, if it wasn't already set
646   // by the caller.
647   if (!I->getDebugLoc())
648     I->setDebugLoc(BI->getDebugLoc());
649 
650   // Insert the new instruction into the basic block...
651   BasicBlock::iterator New = I->insertInto(BB, BI);
652 
653   // Replace all uses of the old instruction, and delete it.
654   ReplaceInstWithValue(BI, I);
655 
656   // Move BI back to point to the newly inserted instruction
657   BI = New;
658 }
659 
660 bool llvm::IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB) {
661   // Remember visited blocks to avoid infinite loop
662   SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
663   unsigned Depth = 0;
664   while (BB && Depth++ < MaxDeoptOrUnreachableSuccessorCheckDepth &&
665          VisitedBlocks.insert(BB).second) {
666     if (isa<UnreachableInst>(BB->getTerminator()) ||
667         BB->getTerminatingDeoptimizeCall())
668       return true;
669     BB = BB->getUniqueSuccessor();
670   }
671   return false;
672 }
673 
674 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
675   BasicBlock::iterator BI(From);
676   ReplaceInstWithInst(From->getParent(), BI, To);
677 }
678 
679 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
680                             LoopInfo *LI, MemorySSAUpdater *MSSAU,
681                             const Twine &BBName) {
682   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
683 
684   Instruction *LatchTerm = BB->getTerminator();
685 
686   CriticalEdgeSplittingOptions Options =
687       CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA();
688 
689   if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
690     // If it is a critical edge, and the succesor is an exception block, handle
691     // the split edge logic in this specific function
692     if (Succ->isEHPad())
693       return ehAwareSplitEdge(BB, Succ, nullptr, nullptr, Options, BBName);
694 
695     // If this is a critical edge, let SplitKnownCriticalEdge do it.
696     return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
697   }
698 
699   // If the edge isn't critical, then BB has a single successor or Succ has a
700   // single pred.  Split the block.
701   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
702     // If the successor only has a single pred, split the top of the successor
703     // block.
704     assert(SP == BB && "CFG broken");
705     SP = nullptr;
706     return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
707                       /*Before=*/true);
708   }
709 
710   // Otherwise, if BB has a single successor, split it at the bottom of the
711   // block.
712   assert(BB->getTerminator()->getNumSuccessors() == 1 &&
713          "Should have a single succ!");
714   return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
715 }
716 
717 void llvm::setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
718   if (auto *II = dyn_cast<InvokeInst>(TI))
719     II->setUnwindDest(Succ);
720   else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
721     CS->setUnwindDest(Succ);
722   else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
723     CR->setUnwindDest(Succ);
724   else
725     llvm_unreachable("unexpected terminator instruction");
726 }
727 
728 void llvm::updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
729                           BasicBlock *NewPred, PHINode *Until) {
730   int BBIdx = 0;
731   for (PHINode &PN : DestBB->phis()) {
732     // We manually update the LandingPadReplacement PHINode and it is the last
733     // PHI Node. So, if we find it, we are done.
734     if (Until == &PN)
735       break;
736 
737     // Reuse the previous value of BBIdx if it lines up.  In cases where we
738     // have multiple phi nodes with *lots* of predecessors, this is a speed
739     // win because we don't have to scan the PHI looking for TIBB.  This
740     // happens because the BB list of PHI nodes are usually in the same
741     // order.
742     if (PN.getIncomingBlock(BBIdx) != OldPred)
743       BBIdx = PN.getBasicBlockIndex(OldPred);
744 
745     assert(BBIdx != -1 && "Invalid PHI Index!");
746     PN.setIncomingBlock(BBIdx, NewPred);
747   }
748 }
749 
750 BasicBlock *llvm::ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
751                                    LandingPadInst *OriginalPad,
752                                    PHINode *LandingPadReplacement,
753                                    const CriticalEdgeSplittingOptions &Options,
754                                    const Twine &BBName) {
755 
756   auto *PadInst = Succ->getFirstNonPHI();
757   if (!LandingPadReplacement && !PadInst->isEHPad())
758     return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
759 
760   auto *LI = Options.LI;
761   SmallVector<BasicBlock *, 4> LoopPreds;
762   // Check if extra modifications will be required to preserve loop-simplify
763   // form after splitting. If it would require splitting blocks with IndirectBr
764   // terminators, bail out if preserving loop-simplify form is requested.
765   if (Options.PreserveLoopSimplify && LI) {
766     if (Loop *BBLoop = LI->getLoopFor(BB)) {
767 
768       // The only way that we can break LoopSimplify form by splitting a
769       // critical edge is when there exists some edge from BBLoop to Succ *and*
770       // the only edge into Succ from outside of BBLoop is that of NewBB after
771       // the split. If the first isn't true, then LoopSimplify still holds,
772       // NewBB is the new exit block and it has no non-loop predecessors. If the
773       // second isn't true, then Succ was not in LoopSimplify form prior to
774       // the split as it had a non-loop predecessor. In both of these cases,
775       // the predecessor must be directly in BBLoop, not in a subloop, or again
776       // LoopSimplify doesn't hold.
777       for (BasicBlock *P : predecessors(Succ)) {
778         if (P == BB)
779           continue; // The new block is known.
780         if (LI->getLoopFor(P) != BBLoop) {
781           // Loop is not in LoopSimplify form, no need to re simplify after
782           // splitting edge.
783           LoopPreds.clear();
784           break;
785         }
786         LoopPreds.push_back(P);
787       }
788       // Loop-simplify form can be preserved, if we can split all in-loop
789       // predecessors.
790       if (any_of(LoopPreds, [](BasicBlock *Pred) {
791             return isa<IndirectBrInst>(Pred->getTerminator());
792           })) {
793         return nullptr;
794       }
795     }
796   }
797 
798   auto *NewBB =
799       BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
800   setUnwindEdgeTo(BB->getTerminator(), NewBB);
801   updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
802 
803   if (LandingPadReplacement) {
804     auto *NewLP = OriginalPad->clone();
805     auto *Terminator = BranchInst::Create(Succ, NewBB);
806     NewLP->insertBefore(Terminator);
807     LandingPadReplacement->addIncoming(NewLP, NewBB);
808   } else {
809     Value *ParentPad = nullptr;
810     if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
811       ParentPad = FuncletPad->getParentPad();
812     else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
813       ParentPad = CatchSwitch->getParentPad();
814     else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
815       ParentPad = CleanupPad->getParentPad();
816     else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
817       ParentPad = LandingPad->getParent();
818     else
819       llvm_unreachable("handling for other EHPads not implemented yet");
820 
821     auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
822     CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
823   }
824 
825   auto *DT = Options.DT;
826   auto *MSSAU = Options.MSSAU;
827   if (!DT && !LI)
828     return NewBB;
829 
830   if (DT) {
831     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
832     SmallVector<DominatorTree::UpdateType, 3> Updates;
833 
834     Updates.push_back({DominatorTree::Insert, BB, NewBB});
835     Updates.push_back({DominatorTree::Insert, NewBB, Succ});
836     Updates.push_back({DominatorTree::Delete, BB, Succ});
837 
838     DTU.applyUpdates(Updates);
839     DTU.flush();
840 
841     if (MSSAU) {
842       MSSAU->applyUpdates(Updates, *DT);
843       if (VerifyMemorySSA)
844         MSSAU->getMemorySSA()->verifyMemorySSA();
845     }
846   }
847 
848   if (LI) {
849     if (Loop *BBLoop = LI->getLoopFor(BB)) {
850       // If one or the other blocks were not in a loop, the new block is not
851       // either, and thus LI doesn't need to be updated.
852       if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
853         if (BBLoop == SuccLoop) {
854           // Both in the same loop, the NewBB joins loop.
855           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
856         } else if (BBLoop->contains(SuccLoop)) {
857           // Edge from an outer loop to an inner loop.  Add to the outer loop.
858           BBLoop->addBasicBlockToLoop(NewBB, *LI);
859         } else if (SuccLoop->contains(BBLoop)) {
860           // Edge from an inner loop to an outer loop.  Add to the outer loop.
861           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
862         } else {
863           // Edge from two loops with no containment relation.  Because these
864           // are natural loops, we know that the destination block must be the
865           // header of its loop (adding a branch into a loop elsewhere would
866           // create an irreducible loop).
867           assert(SuccLoop->getHeader() == Succ &&
868                  "Should not create irreducible loops!");
869           if (Loop *P = SuccLoop->getParentLoop())
870             P->addBasicBlockToLoop(NewBB, *LI);
871         }
872       }
873 
874       // If BB is in a loop and Succ is outside of that loop, we may need to
875       // update LoopSimplify form and LCSSA form.
876       if (!BBLoop->contains(Succ)) {
877         assert(!BBLoop->contains(NewBB) &&
878                "Split point for loop exit is contained in loop!");
879 
880         // Update LCSSA form in the newly created exit block.
881         if (Options.PreserveLCSSA) {
882           createPHIsForSplitLoopExit(BB, NewBB, Succ);
883         }
884 
885         if (!LoopPreds.empty()) {
886           BasicBlock *NewExitBB = SplitBlockPredecessors(
887               Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
888           if (Options.PreserveLCSSA)
889             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
890         }
891       }
892     }
893   }
894 
895   return NewBB;
896 }
897 
898 void llvm::createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
899                                       BasicBlock *SplitBB, BasicBlock *DestBB) {
900   // SplitBB shouldn't have anything non-trivial in it yet.
901   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
902           SplitBB->isLandingPad()) &&
903          "SplitBB has non-PHI nodes!");
904 
905   // For each PHI in the destination block.
906   for (PHINode &PN : DestBB->phis()) {
907     int Idx = PN.getBasicBlockIndex(SplitBB);
908     assert(Idx >= 0 && "Invalid Block Index");
909     Value *V = PN.getIncomingValue(Idx);
910 
911     // If the input is a PHI which already satisfies LCSSA, don't create
912     // a new one.
913     if (const PHINode *VP = dyn_cast<PHINode>(V))
914       if (VP->getParent() == SplitBB)
915         continue;
916 
917     // Otherwise a new PHI is needed. Create one and populate it.
918     PHINode *NewPN = PHINode::Create(PN.getType(), Preds.size(), "split");
919     BasicBlock::iterator InsertPos =
920         SplitBB->isLandingPad() ? SplitBB->begin()
921                                 : SplitBB->getTerminator()->getIterator();
922     NewPN->insertBefore(InsertPos);
923     for (BasicBlock *BB : Preds)
924       NewPN->addIncoming(V, BB);
925 
926     // Update the original PHI.
927     PN.setIncomingValue(Idx, NewPN);
928   }
929 }
930 
931 unsigned
932 llvm::SplitAllCriticalEdges(Function &F,
933                             const CriticalEdgeSplittingOptions &Options) {
934   unsigned NumBroken = 0;
935   for (BasicBlock &BB : F) {
936     Instruction *TI = BB.getTerminator();
937     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
938       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
939         if (SplitCriticalEdge(TI, i, Options))
940           ++NumBroken;
941   }
942   return NumBroken;
943 }
944 
945 static BasicBlock *SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt,
946                                   DomTreeUpdater *DTU, DominatorTree *DT,
947                                   LoopInfo *LI, MemorySSAUpdater *MSSAU,
948                                   const Twine &BBName, bool Before) {
949   if (Before) {
950     DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
951     return splitBlockBefore(Old, SplitPt,
952                             DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
953                             BBName);
954   }
955   BasicBlock::iterator SplitIt = SplitPt;
956   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
957     ++SplitIt;
958     assert(SplitIt != SplitPt->getParent()->end());
959   }
960   std::string Name = BBName.str();
961   BasicBlock *New = Old->splitBasicBlock(
962       SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
963 
964   // The new block lives in whichever loop the old one did. This preserves
965   // LCSSA as well, because we force the split point to be after any PHI nodes.
966   if (LI)
967     if (Loop *L = LI->getLoopFor(Old))
968       L->addBasicBlockToLoop(New, *LI);
969 
970   if (DTU) {
971     SmallVector<DominatorTree::UpdateType, 8> Updates;
972     // Old dominates New. New node dominates all other nodes dominated by Old.
973     SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
974     Updates.push_back({DominatorTree::Insert, Old, New});
975     Updates.reserve(Updates.size() + 2 * succ_size(New));
976     for (BasicBlock *SuccessorOfOld : successors(New))
977       if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
978         Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
979         Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
980       }
981 
982     DTU->applyUpdates(Updates);
983   } else if (DT)
984     // Old dominates New. New node dominates all other nodes dominated by Old.
985     if (DomTreeNode *OldNode = DT->getNode(Old)) {
986       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
987 
988       DomTreeNode *NewNode = DT->addNewBlock(New, Old);
989       for (DomTreeNode *I : Children)
990         DT->changeImmediateDominator(I, NewNode);
991     }
992 
993   // Move MemoryAccesses still tracked in Old, but part of New now.
994   // Update accesses in successor blocks accordingly.
995   if (MSSAU)
996     MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
997 
998   return New;
999 }
1000 
1001 BasicBlock *llvm::SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
1002                              DominatorTree *DT, LoopInfo *LI,
1003                              MemorySSAUpdater *MSSAU, const Twine &BBName,
1004                              bool Before) {
1005   return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
1006                         Before);
1007 }
1008 BasicBlock *llvm::SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
1009                              DomTreeUpdater *DTU, LoopInfo *LI,
1010                              MemorySSAUpdater *MSSAU, const Twine &BBName,
1011                              bool Before) {
1012   return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
1013                         Before);
1014 }
1015 
1016 BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt,
1017                                    DomTreeUpdater *DTU, LoopInfo *LI,
1018                                    MemorySSAUpdater *MSSAU,
1019                                    const Twine &BBName) {
1020 
1021   BasicBlock::iterator SplitIt = SplitPt;
1022   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
1023     ++SplitIt;
1024   std::string Name = BBName.str();
1025   BasicBlock *New = Old->splitBasicBlock(
1026       SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
1027       /* Before=*/true);
1028 
1029   // The new block lives in whichever loop the old one did. This preserves
1030   // LCSSA as well, because we force the split point to be after any PHI nodes.
1031   if (LI)
1032     if (Loop *L = LI->getLoopFor(Old))
1033       L->addBasicBlockToLoop(New, *LI);
1034 
1035   if (DTU) {
1036     SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1037     // New dominates Old. The predecessor nodes of the Old node dominate
1038     // New node.
1039     SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
1040     DTUpdates.push_back({DominatorTree::Insert, New, Old});
1041     DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
1042     for (BasicBlock *PredecessorOfOld : predecessors(New))
1043       if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
1044         DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
1045         DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
1046       }
1047 
1048     DTU->applyUpdates(DTUpdates);
1049 
1050     // Move MemoryAccesses still tracked in Old, but part of New now.
1051     // Update accesses in successor blocks accordingly.
1052     if (MSSAU) {
1053       MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
1054       if (VerifyMemorySSA)
1055         MSSAU->getMemorySSA()->verifyMemorySSA();
1056     }
1057   }
1058   return New;
1059 }
1060 
1061 /// Update DominatorTree, LoopInfo, and LCCSA analysis information.
1062 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
1063                                       ArrayRef<BasicBlock *> Preds,
1064                                       DomTreeUpdater *DTU, DominatorTree *DT,
1065                                       LoopInfo *LI, MemorySSAUpdater *MSSAU,
1066                                       bool PreserveLCSSA, bool &HasLoopExit) {
1067   // Update dominator tree if available.
1068   if (DTU) {
1069     // Recalculation of DomTree is needed when updating a forward DomTree and
1070     // the Entry BB is replaced.
1071     if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
1072       // The entry block was removed and there is no external interface for
1073       // the dominator tree to be notified of this change. In this corner-case
1074       // we recalculate the entire tree.
1075       DTU->recalculate(*NewBB->getParent());
1076     } else {
1077       // Split block expects NewBB to have a non-empty set of predecessors.
1078       SmallVector<DominatorTree::UpdateType, 8> Updates;
1079       SmallPtrSet<BasicBlock *, 8> UniquePreds;
1080       Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
1081       Updates.reserve(Updates.size() + 2 * Preds.size());
1082       for (auto *Pred : Preds)
1083         if (UniquePreds.insert(Pred).second) {
1084           Updates.push_back({DominatorTree::Insert, Pred, NewBB});
1085           Updates.push_back({DominatorTree::Delete, Pred, OldBB});
1086         }
1087       DTU->applyUpdates(Updates);
1088     }
1089   } else if (DT) {
1090     if (OldBB == DT->getRootNode()->getBlock()) {
1091       assert(NewBB->isEntryBlock());
1092       DT->setNewRoot(NewBB);
1093     } else {
1094       // Split block expects NewBB to have a non-empty set of predecessors.
1095       DT->splitBlock(NewBB);
1096     }
1097   }
1098 
1099   // Update MemoryPhis after split if MemorySSA is available
1100   if (MSSAU)
1101     MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
1102 
1103   // The rest of the logic is only relevant for updating the loop structures.
1104   if (!LI)
1105     return;
1106 
1107   if (DTU && DTU->hasDomTree())
1108     DT = &DTU->getDomTree();
1109   assert(DT && "DT should be available to update LoopInfo!");
1110   Loop *L = LI->getLoopFor(OldBB);
1111 
1112   // If we need to preserve loop analyses, collect some information about how
1113   // this split will affect loops.
1114   bool IsLoopEntry = !!L;
1115   bool SplitMakesNewLoopHeader = false;
1116   for (BasicBlock *Pred : Preds) {
1117     // Preds that are not reachable from entry should not be used to identify if
1118     // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
1119     // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
1120     // as true and make the NewBB the header of some loop. This breaks LI.
1121     if (!DT->isReachableFromEntry(Pred))
1122       continue;
1123     // If we need to preserve LCSSA, determine if any of the preds is a loop
1124     // exit.
1125     if (PreserveLCSSA)
1126       if (Loop *PL = LI->getLoopFor(Pred))
1127         if (!PL->contains(OldBB))
1128           HasLoopExit = true;
1129 
1130     // If we need to preserve LoopInfo, note whether any of the preds crosses
1131     // an interesting loop boundary.
1132     if (!L)
1133       continue;
1134     if (L->contains(Pred))
1135       IsLoopEntry = false;
1136     else
1137       SplitMakesNewLoopHeader = true;
1138   }
1139 
1140   // Unless we have a loop for OldBB, nothing else to do here.
1141   if (!L)
1142     return;
1143 
1144   if (IsLoopEntry) {
1145     // Add the new block to the nearest enclosing loop (and not an adjacent
1146     // loop). To find this, examine each of the predecessors and determine which
1147     // loops enclose them, and select the most-nested loop which contains the
1148     // loop containing the block being split.
1149     Loop *InnermostPredLoop = nullptr;
1150     for (BasicBlock *Pred : Preds) {
1151       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
1152         // Seek a loop which actually contains the block being split (to avoid
1153         // adjacent loops).
1154         while (PredLoop && !PredLoop->contains(OldBB))
1155           PredLoop = PredLoop->getParentLoop();
1156 
1157         // Select the most-nested of these loops which contains the block.
1158         if (PredLoop && PredLoop->contains(OldBB) &&
1159             (!InnermostPredLoop ||
1160              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
1161           InnermostPredLoop = PredLoop;
1162       }
1163     }
1164 
1165     if (InnermostPredLoop)
1166       InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
1167   } else {
1168     L->addBasicBlockToLoop(NewBB, *LI);
1169     if (SplitMakesNewLoopHeader)
1170       L->moveToHeader(NewBB);
1171   }
1172 }
1173 
1174 /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
1175 /// This also updates AliasAnalysis, if available.
1176 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
1177                            ArrayRef<BasicBlock *> Preds, BranchInst *BI,
1178                            bool HasLoopExit) {
1179   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
1180   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
1181   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
1182     PHINode *PN = cast<PHINode>(I++);
1183 
1184     // Check to see if all of the values coming in are the same.  If so, we
1185     // don't need to create a new PHI node, unless it's needed for LCSSA.
1186     Value *InVal = nullptr;
1187     if (!HasLoopExit) {
1188       InVal = PN->getIncomingValueForBlock(Preds[0]);
1189       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1190         if (!PredSet.count(PN->getIncomingBlock(i)))
1191           continue;
1192         if (!InVal)
1193           InVal = PN->getIncomingValue(i);
1194         else if (InVal != PN->getIncomingValue(i)) {
1195           InVal = nullptr;
1196           break;
1197         }
1198       }
1199     }
1200 
1201     if (InVal) {
1202       // If all incoming values for the new PHI would be the same, just don't
1203       // make a new PHI.  Instead, just remove the incoming values from the old
1204       // PHI.
1205       PN->removeIncomingValueIf(
1206           [&](unsigned Idx) {
1207             return PredSet.contains(PN->getIncomingBlock(Idx));
1208           },
1209           /* DeletePHIIfEmpty */ false);
1210 
1211       // Add an incoming value to the PHI node in the loop for the preheader
1212       // edge.
1213       PN->addIncoming(InVal, NewBB);
1214       continue;
1215     }
1216 
1217     // If the values coming into the block are not the same, we need a new
1218     // PHI.
1219     // Create the new PHI node, insert it into NewBB at the end of the block
1220     PHINode *NewPHI =
1221         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
1222 
1223     // NOTE! This loop walks backwards for a reason! First off, this minimizes
1224     // the cost of removal if we end up removing a large number of values, and
1225     // second off, this ensures that the indices for the incoming values aren't
1226     // invalidated when we remove one.
1227     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
1228       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
1229       if (PredSet.count(IncomingBB)) {
1230         Value *V = PN->removeIncomingValue(i, false);
1231         NewPHI->addIncoming(V, IncomingBB);
1232       }
1233     }
1234 
1235     PN->addIncoming(NewPHI, NewBB);
1236   }
1237 }
1238 
1239 static void SplitLandingPadPredecessorsImpl(
1240     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1241     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1242     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1243     MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1244 
1245 static BasicBlock *
1246 SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
1247                            const char *Suffix, DomTreeUpdater *DTU,
1248                            DominatorTree *DT, LoopInfo *LI,
1249                            MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1250   // Do not attempt to split that which cannot be split.
1251   if (!BB->canSplitPredecessors())
1252     return nullptr;
1253 
1254   // For the landingpads we need to act a bit differently.
1255   // Delegate this work to the SplitLandingPadPredecessors.
1256   if (BB->isLandingPad()) {
1257     SmallVector<BasicBlock*, 2> NewBBs;
1258     std::string NewName = std::string(Suffix) + ".split-lp";
1259 
1260     SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1261                                     DTU, DT, LI, MSSAU, PreserveLCSSA);
1262     return NewBBs[0];
1263   }
1264 
1265   // Create new basic block, insert right before the original block.
1266   BasicBlock *NewBB = BasicBlock::Create(
1267       BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
1268 
1269   // The new block unconditionally branches to the old block.
1270   BranchInst *BI = BranchInst::Create(BB, NewBB);
1271 
1272   Loop *L = nullptr;
1273   BasicBlock *OldLatch = nullptr;
1274   // Splitting the predecessors of a loop header creates a preheader block.
1275   if (LI && LI->isLoopHeader(BB)) {
1276     L = LI->getLoopFor(BB);
1277     // Using the loop start line number prevents debuggers stepping into the
1278     // loop body for this instruction.
1279     BI->setDebugLoc(L->getStartLoc());
1280 
1281     // If BB is the header of the Loop, it is possible that the loop is
1282     // modified, such that the current latch does not remain the latch of the
1283     // loop. If that is the case, the loop metadata from the current latch needs
1284     // to be applied to the new latch.
1285     OldLatch = L->getLoopLatch();
1286   } else
1287     BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
1288 
1289   // Move the edges from Preds to point to NewBB instead of BB.
1290   for (BasicBlock *Pred : Preds) {
1291     // This is slightly more strict than necessary; the minimum requirement
1292     // is that there be no more than one indirectbr branching to BB. And
1293     // all BlockAddress uses would need to be updated.
1294     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1295            "Cannot split an edge from an IndirectBrInst");
1296     Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
1297   }
1298 
1299   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
1300   // node becomes an incoming value for BB's phi node.  However, if the Preds
1301   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
1302   // account for the newly created predecessor.
1303   if (Preds.empty()) {
1304     // Insert dummy values as the incoming value.
1305     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
1306       cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
1307   }
1308 
1309   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1310   bool HasLoopExit = false;
1311   UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
1312                             HasLoopExit);
1313 
1314   if (!Preds.empty()) {
1315     // Update the PHI nodes in BB with the values coming from NewBB.
1316     UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
1317   }
1318 
1319   if (OldLatch) {
1320     BasicBlock *NewLatch = L->getLoopLatch();
1321     if (NewLatch != OldLatch) {
1322       MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop");
1323       NewLatch->getTerminator()->setMetadata("llvm.loop", MD);
1324       // It's still possible that OldLatch is the latch of another inner loop,
1325       // in which case we do not remove the metadata.
1326       Loop *IL = LI->getLoopFor(OldLatch);
1327       if (IL && IL->getLoopLatch() != OldLatch)
1328         OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr);
1329     }
1330   }
1331 
1332   return NewBB;
1333 }
1334 
1335 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
1336                                          ArrayRef<BasicBlock *> Preds,
1337                                          const char *Suffix, DominatorTree *DT,
1338                                          LoopInfo *LI, MemorySSAUpdater *MSSAU,
1339                                          bool PreserveLCSSA) {
1340   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1341                                     MSSAU, PreserveLCSSA);
1342 }
1343 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
1344                                          ArrayRef<BasicBlock *> Preds,
1345                                          const char *Suffix,
1346                                          DomTreeUpdater *DTU, LoopInfo *LI,
1347                                          MemorySSAUpdater *MSSAU,
1348                                          bool PreserveLCSSA) {
1349   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1350                                     /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1351 }
1352 
1353 static void SplitLandingPadPredecessorsImpl(
1354     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1355     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1356     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1357     MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1358   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
1359 
1360   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
1361   // it right before the original block.
1362   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
1363                                           OrigBB->getName() + Suffix1,
1364                                           OrigBB->getParent(), OrigBB);
1365   NewBBs.push_back(NewBB1);
1366 
1367   // The new block unconditionally branches to the old block.
1368   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
1369   BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
1370 
1371   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1372   for (BasicBlock *Pred : Preds) {
1373     // This is slightly more strict than necessary; the minimum requirement
1374     // is that there be no more than one indirectbr branching to BB. And
1375     // all BlockAddress uses would need to be updated.
1376     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1377            "Cannot split an edge from an IndirectBrInst");
1378     Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
1379   }
1380 
1381   bool HasLoopExit = false;
1382   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1383                             PreserveLCSSA, HasLoopExit);
1384 
1385   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
1386   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
1387 
1388   // Move the remaining edges from OrigBB to point to NewBB2.
1389   SmallVector<BasicBlock*, 8> NewBB2Preds;
1390   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
1391        i != e; ) {
1392     BasicBlock *Pred = *i++;
1393     if (Pred == NewBB1) continue;
1394     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1395            "Cannot split an edge from an IndirectBrInst");
1396     NewBB2Preds.push_back(Pred);
1397     e = pred_end(OrigBB);
1398   }
1399 
1400   BasicBlock *NewBB2 = nullptr;
1401   if (!NewBB2Preds.empty()) {
1402     // Create another basic block for the rest of OrigBB's predecessors.
1403     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
1404                                 OrigBB->getName() + Suffix2,
1405                                 OrigBB->getParent(), OrigBB);
1406     NewBBs.push_back(NewBB2);
1407 
1408     // The new block unconditionally branches to the old block.
1409     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
1410     BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
1411 
1412     // Move the remaining edges from OrigBB to point to NewBB2.
1413     for (BasicBlock *NewBB2Pred : NewBB2Preds)
1414       NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
1415 
1416     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
1417     HasLoopExit = false;
1418     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
1419                               PreserveLCSSA, HasLoopExit);
1420 
1421     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
1422     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
1423   }
1424 
1425   LandingPadInst *LPad = OrigBB->getLandingPadInst();
1426   Instruction *Clone1 = LPad->clone();
1427   Clone1->setName(Twine("lpad") + Suffix1);
1428   Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
1429 
1430   if (NewBB2) {
1431     Instruction *Clone2 = LPad->clone();
1432     Clone2->setName(Twine("lpad") + Suffix2);
1433     Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
1434 
1435     // Create a PHI node for the two cloned landingpad instructions only
1436     // if the original landingpad instruction has some uses.
1437     if (!LPad->use_empty()) {
1438       assert(!LPad->getType()->isTokenTy() &&
1439              "Split cannot be applied if LPad is token type. Otherwise an "
1440              "invalid PHINode of token type would be created.");
1441       PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
1442       PN->addIncoming(Clone1, NewBB1);
1443       PN->addIncoming(Clone2, NewBB2);
1444       LPad->replaceAllUsesWith(PN);
1445     }
1446     LPad->eraseFromParent();
1447   } else {
1448     // There is no second clone. Just replace the landing pad with the first
1449     // clone.
1450     LPad->replaceAllUsesWith(Clone1);
1451     LPad->eraseFromParent();
1452   }
1453 }
1454 
1455 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
1456                                        ArrayRef<BasicBlock *> Preds,
1457                                        const char *Suffix1, const char *Suffix2,
1458                                        SmallVectorImpl<BasicBlock *> &NewBBs,
1459                                        DominatorTree *DT, LoopInfo *LI,
1460                                        MemorySSAUpdater *MSSAU,
1461                                        bool PreserveLCSSA) {
1462   return SplitLandingPadPredecessorsImpl(
1463       OrigBB, Preds, Suffix1, Suffix2, NewBBs,
1464       /*DTU=*/nullptr, DT, LI, MSSAU, PreserveLCSSA);
1465 }
1466 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
1467                                        ArrayRef<BasicBlock *> Preds,
1468                                        const char *Suffix1, const char *Suffix2,
1469                                        SmallVectorImpl<BasicBlock *> &NewBBs,
1470                                        DomTreeUpdater *DTU, LoopInfo *LI,
1471                                        MemorySSAUpdater *MSSAU,
1472                                        bool PreserveLCSSA) {
1473   return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1474                                          NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1475                                          PreserveLCSSA);
1476 }
1477 
1478 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
1479                                              BasicBlock *Pred,
1480                                              DomTreeUpdater *DTU) {
1481   Instruction *UncondBranch = Pred->getTerminator();
1482   // Clone the return and add it to the end of the predecessor.
1483   Instruction *NewRet = RI->clone();
1484   NewRet->insertInto(Pred, Pred->end());
1485 
1486   // If the return instruction returns a value, and if the value was a
1487   // PHI node in "BB", propagate the right value into the return.
1488   for (Use &Op : NewRet->operands()) {
1489     Value *V = Op;
1490     Instruction *NewBC = nullptr;
1491     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1492       // Return value might be bitcasted. Clone and insert it before the
1493       // return instruction.
1494       V = BCI->getOperand(0);
1495       NewBC = BCI->clone();
1496       NewBC->insertInto(Pred, NewRet->getIterator());
1497       Op = NewBC;
1498     }
1499 
1500     Instruction *NewEV = nullptr;
1501     if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
1502       V = EVI->getOperand(0);
1503       NewEV = EVI->clone();
1504       if (NewBC) {
1505         NewBC->setOperand(0, NewEV);
1506         NewEV->insertInto(Pred, NewBC->getIterator());
1507       } else {
1508         NewEV->insertInto(Pred, NewRet->getIterator());
1509         Op = NewEV;
1510       }
1511     }
1512 
1513     if (PHINode *PN = dyn_cast<PHINode>(V)) {
1514       if (PN->getParent() == BB) {
1515         if (NewEV) {
1516           NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
1517         } else if (NewBC)
1518           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
1519         else
1520           Op = PN->getIncomingValueForBlock(Pred);
1521       }
1522     }
1523   }
1524 
1525   // Update any PHI nodes in the returning block to realize that we no
1526   // longer branch to them.
1527   BB->removePredecessor(Pred);
1528   UncondBranch->eraseFromParent();
1529 
1530   if (DTU)
1531     DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
1532 
1533   return cast<ReturnInst>(NewRet);
1534 }
1535 
1536 Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
1537                                              BasicBlock::iterator SplitBefore,
1538                                              bool Unreachable,
1539                                              MDNode *BranchWeights,
1540                                              DomTreeUpdater *DTU, LoopInfo *LI,
1541                                              BasicBlock *ThenBlock) {
1542   SplitBlockAndInsertIfThenElse(
1543       Cond, SplitBefore, &ThenBlock, /* ElseBlock */ nullptr,
1544       /* UnreachableThen */ Unreachable,
1545       /* UnreachableElse */ false, BranchWeights, DTU, LI);
1546   return ThenBlock->getTerminator();
1547 }
1548 
1549 Instruction *llvm::SplitBlockAndInsertIfElse(Value *Cond,
1550                                              BasicBlock::iterator SplitBefore,
1551                                              bool Unreachable,
1552                                              MDNode *BranchWeights,
1553                                              DomTreeUpdater *DTU, LoopInfo *LI,
1554                                              BasicBlock *ElseBlock) {
1555   SplitBlockAndInsertIfThenElse(
1556       Cond, SplitBefore, /* ThenBlock */ nullptr, &ElseBlock,
1557       /* UnreachableThen */ false,
1558       /* UnreachableElse */ Unreachable, BranchWeights, DTU, LI);
1559   return ElseBlock->getTerminator();
1560 }
1561 
1562 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore,
1563                                          Instruction **ThenTerm,
1564                                          Instruction **ElseTerm,
1565                                          MDNode *BranchWeights,
1566                                          DomTreeUpdater *DTU, LoopInfo *LI) {
1567   BasicBlock *ThenBlock = nullptr;
1568   BasicBlock *ElseBlock = nullptr;
1569   SplitBlockAndInsertIfThenElse(
1570       Cond, SplitBefore, &ThenBlock, &ElseBlock, /* UnreachableThen */ false,
1571       /* UnreachableElse */ false, BranchWeights, DTU, LI);
1572 
1573   *ThenTerm = ThenBlock->getTerminator();
1574   *ElseTerm = ElseBlock->getTerminator();
1575 }
1576 
1577 void llvm::SplitBlockAndInsertIfThenElse(
1578     Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
1579     BasicBlock **ElseBlock, bool UnreachableThen, bool UnreachableElse,
1580     MDNode *BranchWeights, DomTreeUpdater *DTU, LoopInfo *LI) {
1581   assert((ThenBlock || ElseBlock) &&
1582          "At least one branch block must be created");
1583   assert((!UnreachableThen || !UnreachableElse) &&
1584          "Split block tail must be reachable");
1585 
1586   SmallVector<DominatorTree::UpdateType, 8> Updates;
1587   SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
1588   BasicBlock *Head = SplitBefore->getParent();
1589   if (DTU) {
1590     UniqueOrigSuccessors.insert(succ_begin(Head), succ_end(Head));
1591     Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
1592   }
1593 
1594   LLVMContext &C = Head->getContext();
1595   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
1596   BasicBlock *TrueBlock = Tail;
1597   BasicBlock *FalseBlock = Tail;
1598   bool ThenToTailEdge = false;
1599   bool ElseToTailEdge = false;
1600 
1601   // Encapsulate the logic around creation/insertion/etc of a new block.
1602   auto handleBlock = [&](BasicBlock **PBB, bool Unreachable, BasicBlock *&BB,
1603                          bool &ToTailEdge) {
1604     if (PBB == nullptr)
1605       return; // Do not create/insert a block.
1606 
1607     if (*PBB)
1608       BB = *PBB; // Caller supplied block, use it.
1609     else {
1610       // Create a new block.
1611       BB = BasicBlock::Create(C, "", Head->getParent(), Tail);
1612       if (Unreachable)
1613         (void)new UnreachableInst(C, BB);
1614       else {
1615         (void)BranchInst::Create(Tail, BB);
1616         ToTailEdge = true;
1617       }
1618       BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
1619       // Pass the new block back to the caller.
1620       *PBB = BB;
1621     }
1622   };
1623 
1624   handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
1625   handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
1626 
1627   Instruction *HeadOldTerm = Head->getTerminator();
1628   BranchInst *HeadNewTerm =
1629       BranchInst::Create(/*ifTrue*/ TrueBlock, /*ifFalse*/ FalseBlock, Cond);
1630   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1631   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
1632 
1633   if (DTU) {
1634     Updates.emplace_back(DominatorTree::Insert, Head, TrueBlock);
1635     Updates.emplace_back(DominatorTree::Insert, Head, FalseBlock);
1636     if (ThenToTailEdge)
1637       Updates.emplace_back(DominatorTree::Insert, TrueBlock, Tail);
1638     if (ElseToTailEdge)
1639       Updates.emplace_back(DominatorTree::Insert, FalseBlock, Tail);
1640     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1641       Updates.emplace_back(DominatorTree::Insert, Tail, UniqueOrigSuccessor);
1642     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1643       Updates.emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1644     DTU->applyUpdates(Updates);
1645   }
1646 
1647   if (LI) {
1648     if (Loop *L = LI->getLoopFor(Head); L) {
1649       if (ThenToTailEdge)
1650         L->addBasicBlockToLoop(TrueBlock, *LI);
1651       if (ElseToTailEdge)
1652         L->addBasicBlockToLoop(FalseBlock, *LI);
1653       L->addBasicBlockToLoop(Tail, *LI);
1654     }
1655   }
1656 }
1657 
1658 std::pair<Instruction*, Value*>
1659 llvm::SplitBlockAndInsertSimpleForLoop(Value *End, Instruction *SplitBefore) {
1660   BasicBlock *LoopPred = SplitBefore->getParent();
1661   BasicBlock *LoopBody = SplitBlock(SplitBefore->getParent(), SplitBefore);
1662   BasicBlock *LoopExit = SplitBlock(SplitBefore->getParent(), SplitBefore);
1663 
1664   auto *Ty = End->getType();
1665   auto &DL = SplitBefore->getModule()->getDataLayout();
1666   const unsigned Bitwidth = DL.getTypeSizeInBits(Ty);
1667 
1668   IRBuilder<> Builder(LoopBody->getTerminator());
1669   auto *IV = Builder.CreatePHI(Ty, 2, "iv");
1670   auto *IVNext =
1671     Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
1672                       /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
1673   auto *IVCheck = Builder.CreateICmpEQ(IVNext, End,
1674                                        IV->getName() + ".check");
1675   Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
1676   LoopBody->getTerminator()->eraseFromParent();
1677 
1678   // Populate the IV PHI.
1679   IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
1680   IV->addIncoming(IVNext, LoopBody);
1681 
1682   return std::make_pair(LoopBody->getFirstNonPHI(), IV);
1683 }
1684 
1685 void llvm::SplitBlockAndInsertForEachLane(ElementCount EC,
1686      Type *IndexTy, Instruction *InsertBefore,
1687      std::function<void(IRBuilderBase&, Value*)> Func) {
1688 
1689   IRBuilder<> IRB(InsertBefore);
1690 
1691   if (EC.isScalable()) {
1692     Value *NumElements = IRB.CreateElementCount(IndexTy, EC);
1693 
1694     auto [BodyIP, Index] =
1695       SplitBlockAndInsertSimpleForLoop(NumElements, InsertBefore);
1696 
1697     IRB.SetInsertPoint(BodyIP);
1698     Func(IRB, Index);
1699     return;
1700   }
1701 
1702   unsigned Num = EC.getFixedValue();
1703   for (unsigned Idx = 0; Idx < Num; ++Idx) {
1704     IRB.SetInsertPoint(InsertBefore);
1705     Func(IRB, ConstantInt::get(IndexTy, Idx));
1706   }
1707 }
1708 
1709 void llvm::SplitBlockAndInsertForEachLane(
1710     Value *EVL, Instruction *InsertBefore,
1711     std::function<void(IRBuilderBase &, Value *)> Func) {
1712 
1713   IRBuilder<> IRB(InsertBefore);
1714   Type *Ty = EVL->getType();
1715 
1716   if (!isa<ConstantInt>(EVL)) {
1717     auto [BodyIP, Index] = SplitBlockAndInsertSimpleForLoop(EVL, InsertBefore);
1718     IRB.SetInsertPoint(BodyIP);
1719     Func(IRB, Index);
1720     return;
1721   }
1722 
1723   unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
1724   for (unsigned Idx = 0; Idx < Num; ++Idx) {
1725     IRB.SetInsertPoint(InsertBefore);
1726     Func(IRB, ConstantInt::get(Ty, Idx));
1727   }
1728 }
1729 
1730 BranchInst *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
1731                                  BasicBlock *&IfFalse) {
1732   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
1733   BasicBlock *Pred1 = nullptr;
1734   BasicBlock *Pred2 = nullptr;
1735 
1736   if (SomePHI) {
1737     if (SomePHI->getNumIncomingValues() != 2)
1738       return nullptr;
1739     Pred1 = SomePHI->getIncomingBlock(0);
1740     Pred2 = SomePHI->getIncomingBlock(1);
1741   } else {
1742     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1743     if (PI == PE) // No predecessor
1744       return nullptr;
1745     Pred1 = *PI++;
1746     if (PI == PE) // Only one predecessor
1747       return nullptr;
1748     Pred2 = *PI++;
1749     if (PI != PE) // More than two predecessors
1750       return nullptr;
1751   }
1752 
1753   // We can only handle branches.  Other control flow will be lowered to
1754   // branches if possible anyway.
1755   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
1756   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
1757   if (!Pred1Br || !Pred2Br)
1758     return nullptr;
1759 
1760   // Eliminate code duplication by ensuring that Pred1Br is conditional if
1761   // either are.
1762   if (Pred2Br->isConditional()) {
1763     // If both branches are conditional, we don't have an "if statement".  In
1764     // reality, we could transform this case, but since the condition will be
1765     // required anyway, we stand no chance of eliminating it, so the xform is
1766     // probably not profitable.
1767     if (Pred1Br->isConditional())
1768       return nullptr;
1769 
1770     std::swap(Pred1, Pred2);
1771     std::swap(Pred1Br, Pred2Br);
1772   }
1773 
1774   if (Pred1Br->isConditional()) {
1775     // The only thing we have to watch out for here is to make sure that Pred2
1776     // doesn't have incoming edges from other blocks.  If it does, the condition
1777     // doesn't dominate BB.
1778     if (!Pred2->getSinglePredecessor())
1779       return nullptr;
1780 
1781     // If we found a conditional branch predecessor, make sure that it branches
1782     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
1783     if (Pred1Br->getSuccessor(0) == BB &&
1784         Pred1Br->getSuccessor(1) == Pred2) {
1785       IfTrue = Pred1;
1786       IfFalse = Pred2;
1787     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
1788                Pred1Br->getSuccessor(1) == BB) {
1789       IfTrue = Pred2;
1790       IfFalse = Pred1;
1791     } else {
1792       // We know that one arm of the conditional goes to BB, so the other must
1793       // go somewhere unrelated, and this must not be an "if statement".
1794       return nullptr;
1795     }
1796 
1797     return Pred1Br;
1798   }
1799 
1800   // Ok, if we got here, both predecessors end with an unconditional branch to
1801   // BB.  Don't panic!  If both blocks only have a single (identical)
1802   // predecessor, and THAT is a conditional branch, then we're all ok!
1803   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
1804   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
1805     return nullptr;
1806 
1807   // Otherwise, if this is a conditional branch, then we can use it!
1808   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
1809   if (!BI) return nullptr;
1810 
1811   assert(BI->isConditional() && "Two successors but not conditional?");
1812   if (BI->getSuccessor(0) == Pred1) {
1813     IfTrue = Pred1;
1814     IfFalse = Pred2;
1815   } else {
1816     IfTrue = Pred2;
1817     IfFalse = Pred1;
1818   }
1819   return BI;
1820 }
1821 
1822 // After creating a control flow hub, the operands of PHINodes in an outgoing
1823 // block Out no longer match the predecessors of that block. Predecessors of Out
1824 // that are incoming blocks to the hub are now replaced by just one edge from
1825 // the hub. To match this new control flow, the corresponding values from each
1826 // PHINode must now be moved a new PHINode in the first guard block of the hub.
1827 //
1828 // This operation cannot be performed with SSAUpdater, because it involves one
1829 // new use: If the block Out is in the list of Incoming blocks, then the newly
1830 // created PHI in the Hub will use itself along that edge from Out to Hub.
1831 static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock,
1832                           const SetVector<BasicBlock *> &Incoming,
1833                           BasicBlock *FirstGuardBlock) {
1834   auto I = Out->begin();
1835   while (I != Out->end() && isa<PHINode>(I)) {
1836     auto Phi = cast<PHINode>(I);
1837     auto NewPhi =
1838         PHINode::Create(Phi->getType(), Incoming.size(),
1839                         Phi->getName() + ".moved", &FirstGuardBlock->front());
1840     for (auto *In : Incoming) {
1841       Value *V = UndefValue::get(Phi->getType());
1842       if (In == Out) {
1843         V = NewPhi;
1844       } else if (Phi->getBasicBlockIndex(In) != -1) {
1845         V = Phi->removeIncomingValue(In, false);
1846       }
1847       NewPhi->addIncoming(V, In);
1848     }
1849     assert(NewPhi->getNumIncomingValues() == Incoming.size());
1850     if (Phi->getNumOperands() == 0) {
1851       Phi->replaceAllUsesWith(NewPhi);
1852       I = Phi->eraseFromParent();
1853       continue;
1854     }
1855     Phi->addIncoming(NewPhi, GuardBlock);
1856     ++I;
1857   }
1858 }
1859 
1860 using BBPredicates = DenseMap<BasicBlock *, Instruction *>;
1861 using BBSetVector = SetVector<BasicBlock *>;
1862 
1863 // Redirects the terminator of the incoming block to the first guard
1864 // block in the hub. The condition of the original terminator (if it
1865 // was conditional) and its original successors are returned as a
1866 // tuple <condition, succ0, succ1>. The function additionally filters
1867 // out successors that are not in the set of outgoing blocks.
1868 //
1869 // - condition is non-null iff the branch is conditional.
1870 // - Succ1 is non-null iff the sole/taken target is an outgoing block.
1871 // - Succ2 is non-null iff condition is non-null and the fallthrough
1872 //         target is an outgoing block.
1873 static std::tuple<Value *, BasicBlock *, BasicBlock *>
1874 redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock,
1875               const BBSetVector &Outgoing) {
1876   assert(isa<BranchInst>(BB->getTerminator()) &&
1877          "Only support branch terminator.");
1878   auto Branch = cast<BranchInst>(BB->getTerminator());
1879   auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
1880 
1881   BasicBlock *Succ0 = Branch->getSuccessor(0);
1882   BasicBlock *Succ1 = nullptr;
1883   Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr;
1884 
1885   if (Branch->isUnconditional()) {
1886     Branch->setSuccessor(0, FirstGuardBlock);
1887     assert(Succ0);
1888   } else {
1889     Succ1 = Branch->getSuccessor(1);
1890     Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr;
1891     assert(Succ0 || Succ1);
1892     if (Succ0 && !Succ1) {
1893       Branch->setSuccessor(0, FirstGuardBlock);
1894     } else if (Succ1 && !Succ0) {
1895       Branch->setSuccessor(1, FirstGuardBlock);
1896     } else {
1897       Branch->eraseFromParent();
1898       BranchInst::Create(FirstGuardBlock, BB);
1899     }
1900   }
1901 
1902   assert(Succ0 || Succ1);
1903   return std::make_tuple(Condition, Succ0, Succ1);
1904 }
1905 // Setup the branch instructions for guard blocks.
1906 //
1907 // Each guard block terminates in a conditional branch that transfers
1908 // control to the corresponding outgoing block or the next guard
1909 // block. The last guard block has two outgoing blocks as successors
1910 // since the condition for the final outgoing block is trivially
1911 // true. So we create one less block (including the first guard block)
1912 // than the number of outgoing blocks.
1913 static void setupBranchForGuard(SmallVectorImpl<BasicBlock *> &GuardBlocks,
1914                                 const BBSetVector &Outgoing,
1915                                 BBPredicates &GuardPredicates) {
1916   // To help keep the loop simple, temporarily append the last
1917   // outgoing block to the list of guard blocks.
1918   GuardBlocks.push_back(Outgoing.back());
1919 
1920   for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) {
1921     auto Out = Outgoing[i];
1922     assert(GuardPredicates.count(Out));
1923     BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out],
1924                        GuardBlocks[i]);
1925   }
1926 
1927   // Remove the last block from the guard list.
1928   GuardBlocks.pop_back();
1929 }
1930 
1931 /// We are using one integer to represent the block we are branching to. Then at
1932 /// each guard block, the predicate was calcuated using a simple `icmp eq`.
1933 static void calcPredicateUsingInteger(
1934     const BBSetVector &Incoming, const BBSetVector &Outgoing,
1935     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates) {
1936   auto &Context = Incoming.front()->getContext();
1937   auto FirstGuardBlock = GuardBlocks.front();
1938 
1939   auto Phi = PHINode::Create(Type::getInt32Ty(Context), Incoming.size(),
1940                              "merged.bb.idx", FirstGuardBlock);
1941 
1942   for (auto In : Incoming) {
1943     Value *Condition;
1944     BasicBlock *Succ0;
1945     BasicBlock *Succ1;
1946     std::tie(Condition, Succ0, Succ1) =
1947         redirectToHub(In, FirstGuardBlock, Outgoing);
1948     Value *IncomingId = nullptr;
1949     if (Succ0 && Succ1) {
1950       // target_bb_index = Condition ? index_of_succ0 : index_of_succ1.
1951       auto Succ0Iter = find(Outgoing, Succ0);
1952       auto Succ1Iter = find(Outgoing, Succ1);
1953       Value *Id0 = ConstantInt::get(Type::getInt32Ty(Context),
1954                                     std::distance(Outgoing.begin(), Succ0Iter));
1955       Value *Id1 = ConstantInt::get(Type::getInt32Ty(Context),
1956                                     std::distance(Outgoing.begin(), Succ1Iter));
1957       IncomingId = SelectInst::Create(Condition, Id0, Id1, "target.bb.idx",
1958                                       In->getTerminator());
1959     } else {
1960       // Get the index of the non-null successor.
1961       auto SuccIter = Succ0 ? find(Outgoing, Succ0) : find(Outgoing, Succ1);
1962       IncomingId = ConstantInt::get(Type::getInt32Ty(Context),
1963                                     std::distance(Outgoing.begin(), SuccIter));
1964     }
1965     Phi->addIncoming(IncomingId, In);
1966   }
1967 
1968   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
1969     auto Out = Outgoing[i];
1970     auto Cmp = ICmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, Phi,
1971                                 ConstantInt::get(Type::getInt32Ty(Context), i),
1972                                 Out->getName() + ".predicate", GuardBlocks[i]);
1973     GuardPredicates[Out] = Cmp;
1974   }
1975 }
1976 
1977 /// We record the predicate of each outgoing block using a phi of boolean.
1978 static void calcPredicateUsingBooleans(
1979     const BBSetVector &Incoming, const BBSetVector &Outgoing,
1980     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates,
1981     SmallVectorImpl<WeakVH> &DeletionCandidates) {
1982   auto &Context = Incoming.front()->getContext();
1983   auto BoolTrue = ConstantInt::getTrue(Context);
1984   auto BoolFalse = ConstantInt::getFalse(Context);
1985   auto FirstGuardBlock = GuardBlocks.front();
1986 
1987   // The predicate for the last outgoing is trivially true, and so we
1988   // process only the first N-1 successors.
1989   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
1990     auto Out = Outgoing[i];
1991     LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n");
1992 
1993     auto Phi =
1994         PHINode::Create(Type::getInt1Ty(Context), Incoming.size(),
1995                         StringRef("Guard.") + Out->getName(), FirstGuardBlock);
1996     GuardPredicates[Out] = Phi;
1997   }
1998 
1999   for (auto *In : Incoming) {
2000     Value *Condition;
2001     BasicBlock *Succ0;
2002     BasicBlock *Succ1;
2003     std::tie(Condition, Succ0, Succ1) =
2004         redirectToHub(In, FirstGuardBlock, Outgoing);
2005 
2006     // Optimization: Consider an incoming block A with both successors
2007     // Succ0 and Succ1 in the set of outgoing blocks. The predicates
2008     // for Succ0 and Succ1 complement each other. If Succ0 is visited
2009     // first in the loop below, control will branch to Succ0 using the
2010     // corresponding predicate. But if that branch is not taken, then
2011     // control must reach Succ1, which means that the incoming value of
2012     // the predicate from `In` is true for Succ1.
2013     bool OneSuccessorDone = false;
2014     for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2015       auto Out = Outgoing[i];
2016       PHINode *Phi = cast<PHINode>(GuardPredicates[Out]);
2017       if (Out != Succ0 && Out != Succ1) {
2018         Phi->addIncoming(BoolFalse, In);
2019       } else if (!Succ0 || !Succ1 || OneSuccessorDone) {
2020         // Optimization: When only one successor is an outgoing block,
2021         // the incoming predicate from `In` is always true.
2022         Phi->addIncoming(BoolTrue, In);
2023       } else {
2024         assert(Succ0 && Succ1);
2025         if (Out == Succ0) {
2026           Phi->addIncoming(Condition, In);
2027         } else {
2028           auto Inverted = invertCondition(Condition);
2029           DeletionCandidates.push_back(Condition);
2030           Phi->addIncoming(Inverted, In);
2031         }
2032         OneSuccessorDone = true;
2033       }
2034     }
2035   }
2036 }
2037 
2038 // Capture the existing control flow as guard predicates, and redirect
2039 // control flow from \p Incoming block through the \p GuardBlocks to the
2040 // \p Outgoing blocks.
2041 //
2042 // There is one guard predicate for each outgoing block OutBB. The
2043 // predicate represents whether the hub should transfer control flow
2044 // to OutBB. These predicates are NOT ORTHOGONAL. The Hub evaluates
2045 // them in the same order as the Outgoing set-vector, and control
2046 // branches to the first outgoing block whose predicate evaluates to true.
2047 static void
2048 convertToGuardPredicates(SmallVectorImpl<BasicBlock *> &GuardBlocks,
2049                          SmallVectorImpl<WeakVH> &DeletionCandidates,
2050                          const BBSetVector &Incoming,
2051                          const BBSetVector &Outgoing, const StringRef Prefix,
2052                          std::optional<unsigned> MaxControlFlowBooleans) {
2053   BBPredicates GuardPredicates;
2054   auto F = Incoming.front()->getParent();
2055 
2056   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i)
2057     GuardBlocks.push_back(
2058         BasicBlock::Create(F->getContext(), Prefix + ".guard", F));
2059 
2060   // When we are using an integer to record which target block to jump to, we
2061   // are creating less live values, actually we are using one single integer to
2062   // store the index of the target block. When we are using booleans to store
2063   // the branching information, we need (N-1) boolean values, where N is the
2064   // number of outgoing block.
2065   if (!MaxControlFlowBooleans || Outgoing.size() <= *MaxControlFlowBooleans)
2066     calcPredicateUsingBooleans(Incoming, Outgoing, GuardBlocks, GuardPredicates,
2067                                DeletionCandidates);
2068   else
2069     calcPredicateUsingInteger(Incoming, Outgoing, GuardBlocks, GuardPredicates);
2070 
2071   setupBranchForGuard(GuardBlocks, Outgoing, GuardPredicates);
2072 }
2073 
2074 BasicBlock *llvm::CreateControlFlowHub(
2075     DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
2076     const BBSetVector &Incoming, const BBSetVector &Outgoing,
2077     const StringRef Prefix, std::optional<unsigned> MaxControlFlowBooleans) {
2078   if (Outgoing.size() < 2)
2079     return Outgoing.front();
2080 
2081   SmallVector<DominatorTree::UpdateType, 16> Updates;
2082   if (DTU) {
2083     for (auto *In : Incoming) {
2084       for (auto Succ : successors(In))
2085         if (Outgoing.count(Succ))
2086           Updates.push_back({DominatorTree::Delete, In, Succ});
2087     }
2088   }
2089 
2090   SmallVector<WeakVH, 8> DeletionCandidates;
2091   convertToGuardPredicates(GuardBlocks, DeletionCandidates, Incoming, Outgoing,
2092                            Prefix, MaxControlFlowBooleans);
2093   auto FirstGuardBlock = GuardBlocks.front();
2094 
2095   // Update the PHINodes in each outgoing block to match the new control flow.
2096   for (int i = 0, e = GuardBlocks.size(); i != e; ++i)
2097     reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock);
2098 
2099   reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock);
2100 
2101   if (DTU) {
2102     int NumGuards = GuardBlocks.size();
2103     assert((int)Outgoing.size() == NumGuards + 1);
2104 
2105     for (auto In : Incoming)
2106       Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock});
2107 
2108     for (int i = 0; i != NumGuards - 1; ++i) {
2109       Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]});
2110       Updates.push_back(
2111           {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]});
2112     }
2113     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
2114                        Outgoing[NumGuards - 1]});
2115     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
2116                        Outgoing[NumGuards]});
2117     DTU->applyUpdates(Updates);
2118   }
2119 
2120   for (auto I : DeletionCandidates) {
2121     if (I->use_empty())
2122       if (auto Inst = dyn_cast_or_null<Instruction>(I))
2123         Inst->eraseFromParent();
2124   }
2125 
2126   return FirstGuardBlock;
2127 }
2128 
2129 void llvm::InvertBranch(BranchInst *PBI, IRBuilderBase &Builder) {
2130   Value *NewCond = PBI->getCondition();
2131   // If this is a "cmp" instruction, only used for branching (and nowhere
2132   // else), then we can simply invert the predicate.
2133   if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2134     CmpInst *CI = cast<CmpInst>(NewCond);
2135     CI->setPredicate(CI->getInversePredicate());
2136   } else
2137     NewCond = Builder.CreateNot(NewCond, NewCond->getName() + ".not");
2138 
2139   PBI->setCondition(NewCond);
2140   PBI->swapSuccessors();
2141 }
2142 
2143 bool llvm::hasOnlySimpleTerminator(const Function &F) {
2144   for (auto &BB : F) {
2145     auto *Term = BB.getTerminator();
2146     if (!(isa<ReturnInst>(Term) || isa<UnreachableInst>(Term) ||
2147           isa<BranchInst>(Term)))
2148       return false;
2149   }
2150   return true;
2151 }
2152