1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect the sequence of machine instructions for a basic block.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/MachineBasicBlock.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/CodeGen/LiveIntervals.h"
17 #include "llvm/CodeGen/LiveVariables.h"
18 #include "llvm/CodeGen/MachineDominators.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/SlotIndexes.h"
24 #include "llvm/CodeGen/TargetInstrInfo.h"
25 #include "llvm/CodeGen/TargetRegisterInfo.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/ModuleSlotTracker.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/Support/DataTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include <algorithm>
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "codegen"
41 
42 MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
43     : BB(B), Number(-1), xParent(&MF) {
44   Insts.Parent = this;
45   if (B)
46     IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
47 }
48 
49 MachineBasicBlock::~MachineBasicBlock() {
50 }
51 
52 /// Return the MCSymbol for this basic block.
53 MCSymbol *MachineBasicBlock::getSymbol() const {
54   if (!CachedMCSymbol) {
55     const MachineFunction *MF = getParent();
56     MCContext &Ctx = MF->getContext();
57     auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
58     assert(getNumber() >= 0 && "cannot get label for unreachable MBB");
59     CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
60                                            Twine(MF->getFunctionNumber()) +
61                                            "_" + Twine(getNumber()));
62   }
63 
64   return CachedMCSymbol;
65 }
66 
67 
68 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
69   MBB.print(OS);
70   return OS;
71 }
72 
73 Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
74   return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
75 }
76 
77 /// When an MBB is added to an MF, we need to update the parent pointer of the
78 /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
79 /// operand list for registers.
80 ///
81 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
82 /// gets the next available unique MBB number. If it is removed from a
83 /// MachineFunction, it goes back to being #-1.
84 void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
85     MachineBasicBlock *N) {
86   MachineFunction &MF = *N->getParent();
87   N->Number = MF.addToMBBNumbering(N);
88 
89   // Make sure the instructions have their operands in the reginfo lists.
90   MachineRegisterInfo &RegInfo = MF.getRegInfo();
91   for (MachineBasicBlock::instr_iterator
92          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
93     I->AddRegOperandsToUseLists(RegInfo);
94 }
95 
96 void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
97     MachineBasicBlock *N) {
98   N->getParent()->removeFromMBBNumbering(N->Number);
99   N->Number = -1;
100 }
101 
102 /// When we add an instruction to a basic block list, we update its parent
103 /// pointer and add its operands from reg use/def lists if appropriate.
104 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
105   assert(!N->getParent() && "machine instruction already in a basic block");
106   N->setParent(Parent);
107 
108   // Add the instruction's register operands to their corresponding
109   // use/def lists.
110   MachineFunction *MF = Parent->getParent();
111   N->AddRegOperandsToUseLists(MF->getRegInfo());
112 }
113 
114 /// When we remove an instruction from a basic block list, we update its parent
115 /// pointer and remove its operands from reg use/def lists if appropriate.
116 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
117   assert(N->getParent() && "machine instruction not in a basic block");
118 
119   // Remove from the use/def lists.
120   if (MachineFunction *MF = N->getMF())
121     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
122 
123   N->setParent(nullptr);
124 }
125 
126 /// When moving a range of instructions from one MBB list to another, we need to
127 /// update the parent pointers and the use/def lists.
128 void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
129                                                        instr_iterator First,
130                                                        instr_iterator Last) {
131   assert(Parent->getParent() == FromList.Parent->getParent() &&
132         "MachineInstr parent mismatch!");
133   assert(this != &FromList && "Called without a real transfer...");
134   assert(Parent != FromList.Parent && "Two lists have the same parent?");
135 
136   // If splicing between two blocks within the same function, just update the
137   // parent pointers.
138   for (; First != Last; ++First)
139     First->setParent(Parent);
140 }
141 
142 void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
143   assert(!MI->getParent() && "MI is still in a block!");
144   Parent->getParent()->DeleteMachineInstr(MI);
145 }
146 
147 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
148   instr_iterator I = instr_begin(), E = instr_end();
149   while (I != E && I->isPHI())
150     ++I;
151   assert((I == E || !I->isInsideBundle()) &&
152          "First non-phi MI cannot be inside a bundle!");
153   return I;
154 }
155 
156 MachineBasicBlock::iterator
157 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
158   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
159 
160   iterator E = end();
161   while (I != E && (I->isPHI() || I->isPosition() ||
162                     TII->isBasicBlockPrologue(*I)))
163     ++I;
164   // FIXME: This needs to change if we wish to bundle labels
165   // inside the bundle.
166   assert((I == E || !I->isInsideBundle()) &&
167          "First non-phi / non-label instruction is inside a bundle!");
168   return I;
169 }
170 
171 MachineBasicBlock::iterator
172 MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I) {
173   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
174 
175   iterator E = end();
176   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue() ||
177                     TII->isBasicBlockPrologue(*I)))
178     ++I;
179   // FIXME: This needs to change if we wish to bundle labels / dbg_values
180   // inside the bundle.
181   assert((I == E || !I->isInsideBundle()) &&
182          "First non-phi / non-label / non-debug "
183          "instruction is inside a bundle!");
184   return I;
185 }
186 
187 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
188   iterator B = begin(), E = end(), I = E;
189   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
190     ; /*noop */
191   while (I != E && !I->isTerminator())
192     ++I;
193   return I;
194 }
195 
196 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
197   instr_iterator B = instr_begin(), E = instr_end(), I = E;
198   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
199     ; /*noop */
200   while (I != E && !I->isTerminator())
201     ++I;
202   return I;
203 }
204 
205 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
206   // Skip over begin-of-block dbg_value instructions.
207   return skipDebugInstructionsForward(begin(), end());
208 }
209 
210 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
211   // Skip over end-of-block dbg_value instructions.
212   instr_iterator B = instr_begin(), I = instr_end();
213   while (I != B) {
214     --I;
215     // Return instruction that starts a bundle.
216     if (I->isDebugValue() || I->isInsideBundle())
217       continue;
218     return I;
219   }
220   // The block is all debug values.
221   return end();
222 }
223 
224 bool MachineBasicBlock::hasEHPadSuccessor() const {
225   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
226     if ((*I)->isEHPad())
227       return true;
228   return false;
229 }
230 
231 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
232 LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
233   print(dbgs());
234 }
235 #endif
236 
237 bool MachineBasicBlock::isLegalToHoistInto() const {
238   if (isReturnBlock() || hasEHPadSuccessor())
239     return false;
240   return true;
241 }
242 
243 StringRef MachineBasicBlock::getName() const {
244   if (const BasicBlock *LBB = getBasicBlock())
245     return LBB->getName();
246   else
247     return StringRef("", 0);
248 }
249 
250 /// Return a hopefully unique identifier for this block.
251 std::string MachineBasicBlock::getFullName() const {
252   std::string Name;
253   if (getParent())
254     Name = (getParent()->getName() + ":").str();
255   if (getBasicBlock())
256     Name += getBasicBlock()->getName();
257   else
258     Name += ("BB" + Twine(getNumber())).str();
259   return Name;
260 }
261 
262 void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
263                               bool IsStandalone) const {
264   const MachineFunction *MF = getParent();
265   if (!MF) {
266     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
267        << " is null\n";
268     return;
269   }
270   const Function &F = MF->getFunction();
271   const Module *M = F.getParent();
272   ModuleSlotTracker MST(M);
273   MST.incorporateFunction(F);
274   print(OS, MST, Indexes, IsStandalone);
275 }
276 
277 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
278                               const SlotIndexes *Indexes,
279                               bool IsStandalone) const {
280   const MachineFunction *MF = getParent();
281   if (!MF) {
282     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
283        << " is null\n";
284     return;
285   }
286 
287   if (Indexes)
288     OS << Indexes->getMBBStartIdx(this) << '\t';
289 
290   OS << "bb." << getNumber();
291   bool HasAttributes = false;
292   if (const auto *BB = getBasicBlock()) {
293     if (BB->hasName()) {
294       OS << "." << BB->getName();
295     } else {
296       HasAttributes = true;
297       OS << " (";
298       int Slot = MST.getLocalSlot(BB);
299       if (Slot == -1)
300         OS << "<ir-block badref>";
301       else
302         OS << (Twine("%ir-block.") + Twine(Slot)).str();
303     }
304   }
305 
306   if (hasAddressTaken()) {
307     OS << (HasAttributes ? ", " : " (");
308     OS << "address-taken";
309     HasAttributes = true;
310   }
311   if (isEHPad()) {
312     OS << (HasAttributes ? ", " : " (");
313     OS << "landing-pad";
314     HasAttributes = true;
315   }
316   if (getAlignment()) {
317     OS << (HasAttributes ? ", " : " (");
318     OS << "align " << getAlignment();
319     HasAttributes = true;
320   }
321   if (HasAttributes)
322     OS << ")";
323   OS << ":\n";
324 
325   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
326   if (!livein_empty()) {
327     if (Indexes) OS << '\t';
328     OS << "    Live Ins:";
329     for (const auto &LI : LiveIns) {
330       OS << ' ' << printReg(LI.PhysReg, TRI);
331       if (!LI.LaneMask.all())
332         OS << ':' << PrintLaneMask(LI.LaneMask);
333     }
334     OS << '\n';
335   }
336   // Print the preds of this block according to the CFG.
337   if (!pred_empty()) {
338     if (Indexes) OS << '\t';
339     OS << "    Predecessors according to CFG:";
340     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
341       OS << " " << printMBBReference(*(*PI));
342     OS << '\n';
343   }
344 
345   for (auto &I : instrs()) {
346     if (Indexes) {
347       if (Indexes->hasIndex(I))
348         OS << Indexes->getInstructionIndex(I);
349       OS << '\t';
350     }
351     OS << '\t';
352     if (I.isInsideBundle())
353       OS << "  * ";
354     I.print(OS, MST, IsStandalone);
355   }
356 
357   // Print the successors of this block according to the CFG.
358   if (!succ_empty()) {
359     if (Indexes) OS << '\t';
360     OS << "    Successors according to CFG:";
361     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
362       OS << " " << printMBBReference(*(*SI));
363       if (!Probs.empty())
364         OS << '(' << *getProbabilityIterator(SI) << ')';
365     }
366     OS << '\n';
367   }
368   if (IrrLoopHeaderWeight) {
369     if (Indexes) OS << '\t';
370     OS << "    Irreducible loop header weight: "
371        << IrrLoopHeaderWeight.getValue();
372     OS << '\n';
373   }
374 }
375 
376 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
377                                        bool /*PrintType*/) const {
378   OS << "%bb." << getNumber();
379 }
380 
381 void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
382   LiveInVector::iterator I = find_if(
383       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
384   if (I == LiveIns.end())
385     return;
386 
387   I->LaneMask &= ~LaneMask;
388   if (I->LaneMask.none())
389     LiveIns.erase(I);
390 }
391 
392 MachineBasicBlock::livein_iterator
393 MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
394   // Get non-const version of iterator.
395   LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
396   return LiveIns.erase(LI);
397 }
398 
399 bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
400   livein_iterator I = find_if(
401       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
402   return I != livein_end() && (I->LaneMask & LaneMask).any();
403 }
404 
405 void MachineBasicBlock::sortUniqueLiveIns() {
406   std::sort(LiveIns.begin(), LiveIns.end(),
407             [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
408               return LI0.PhysReg < LI1.PhysReg;
409             });
410   // Liveins are sorted by physreg now we can merge their lanemasks.
411   LiveInVector::const_iterator I = LiveIns.begin();
412   LiveInVector::const_iterator J;
413   LiveInVector::iterator Out = LiveIns.begin();
414   for (; I != LiveIns.end(); ++Out, I = J) {
415     unsigned PhysReg = I->PhysReg;
416     LaneBitmask LaneMask = I->LaneMask;
417     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
418       LaneMask |= J->LaneMask;
419     Out->PhysReg = PhysReg;
420     Out->LaneMask = LaneMask;
421   }
422   LiveIns.erase(Out, LiveIns.end());
423 }
424 
425 unsigned
426 MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
427   assert(getParent() && "MBB must be inserted in function");
428   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
429   assert(RC && "Register class is required");
430   assert((isEHPad() || this == &getParent()->front()) &&
431          "Only the entry block and landing pads can have physreg live ins");
432 
433   bool LiveIn = isLiveIn(PhysReg);
434   iterator I = SkipPHIsAndLabels(begin()), E = end();
435   MachineRegisterInfo &MRI = getParent()->getRegInfo();
436   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
437 
438   // Look for an existing copy.
439   if (LiveIn)
440     for (;I != E && I->isCopy(); ++I)
441       if (I->getOperand(1).getReg() == PhysReg) {
442         unsigned VirtReg = I->getOperand(0).getReg();
443         if (!MRI.constrainRegClass(VirtReg, RC))
444           llvm_unreachable("Incompatible live-in register class.");
445         return VirtReg;
446       }
447 
448   // No luck, create a virtual register.
449   unsigned VirtReg = MRI.createVirtualRegister(RC);
450   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
451     .addReg(PhysReg, RegState::Kill);
452   if (!LiveIn)
453     addLiveIn(PhysReg);
454   return VirtReg;
455 }
456 
457 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
458   getParent()->splice(NewAfter->getIterator(), getIterator());
459 }
460 
461 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
462   getParent()->splice(++NewBefore->getIterator(), getIterator());
463 }
464 
465 void MachineBasicBlock::updateTerminator() {
466   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
467   // A block with no successors has no concerns with fall-through edges.
468   if (this->succ_empty())
469     return;
470 
471   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
472   SmallVector<MachineOperand, 4> Cond;
473   DebugLoc DL = findBranchDebugLoc();
474   bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
475   (void) B;
476   assert(!B && "UpdateTerminators requires analyzable predecessors!");
477   if (Cond.empty()) {
478     if (TBB) {
479       // The block has an unconditional branch. If its successor is now its
480       // layout successor, delete the branch.
481       if (isLayoutSuccessor(TBB))
482         TII->removeBranch(*this);
483     } else {
484       // The block has an unconditional fallthrough. If its successor is not its
485       // layout successor, insert a branch. First we have to locate the only
486       // non-landing-pad successor, as that is the fallthrough block.
487       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
488         if ((*SI)->isEHPad())
489           continue;
490         assert(!TBB && "Found more than one non-landing-pad successor!");
491         TBB = *SI;
492       }
493 
494       // If there is no non-landing-pad successor, the block has no fall-through
495       // edges to be concerned with.
496       if (!TBB)
497         return;
498 
499       // Finally update the unconditional successor to be reached via a branch
500       // if it would not be reached by fallthrough.
501       if (!isLayoutSuccessor(TBB))
502         TII->insertBranch(*this, TBB, nullptr, Cond, DL);
503     }
504     return;
505   }
506 
507   if (FBB) {
508     // The block has a non-fallthrough conditional branch. If one of its
509     // successors is its layout successor, rewrite it to a fallthrough
510     // conditional branch.
511     if (isLayoutSuccessor(TBB)) {
512       if (TII->reverseBranchCondition(Cond))
513         return;
514       TII->removeBranch(*this);
515       TII->insertBranch(*this, FBB, nullptr, Cond, DL);
516     } else if (isLayoutSuccessor(FBB)) {
517       TII->removeBranch(*this);
518       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
519     }
520     return;
521   }
522 
523   // Walk through the successors and find the successor which is not a landing
524   // pad and is not the conditional branch destination (in TBB) as the
525   // fallthrough successor.
526   MachineBasicBlock *FallthroughBB = nullptr;
527   for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
528     if ((*SI)->isEHPad() || *SI == TBB)
529       continue;
530     assert(!FallthroughBB && "Found more than one fallthrough successor.");
531     FallthroughBB = *SI;
532   }
533 
534   if (!FallthroughBB) {
535     if (canFallThrough()) {
536       // We fallthrough to the same basic block as the conditional jump targets.
537       // Remove the conditional jump, leaving unconditional fallthrough.
538       // FIXME: This does not seem like a reasonable pattern to support, but it
539       // has been seen in the wild coming out of degenerate ARM test cases.
540       TII->removeBranch(*this);
541 
542       // Finally update the unconditional successor to be reached via a branch if
543       // it would not be reached by fallthrough.
544       if (!isLayoutSuccessor(TBB))
545         TII->insertBranch(*this, TBB, nullptr, Cond, DL);
546       return;
547     }
548 
549     // We enter here iff exactly one successor is TBB which cannot fallthrough
550     // and the rest successors if any are EHPads.  In this case, we need to
551     // change the conditional branch into unconditional branch.
552     TII->removeBranch(*this);
553     Cond.clear();
554     TII->insertBranch(*this, TBB, nullptr, Cond, DL);
555     return;
556   }
557 
558   // The block has a fallthrough conditional branch.
559   if (isLayoutSuccessor(TBB)) {
560     if (TII->reverseBranchCondition(Cond)) {
561       // We can't reverse the condition, add an unconditional branch.
562       Cond.clear();
563       TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
564       return;
565     }
566     TII->removeBranch(*this);
567     TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
568   } else if (!isLayoutSuccessor(FallthroughBB)) {
569     TII->removeBranch(*this);
570     TII->insertBranch(*this, TBB, FallthroughBB, Cond, DL);
571   }
572 }
573 
574 void MachineBasicBlock::validateSuccProbs() const {
575 #ifndef NDEBUG
576   int64_t Sum = 0;
577   for (auto Prob : Probs)
578     Sum += Prob.getNumerator();
579   // Due to precision issue, we assume that the sum of probabilities is one if
580   // the difference between the sum of their numerators and the denominator is
581   // no greater than the number of successors.
582   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
583              Probs.size() &&
584          "The sum of successors's probabilities exceeds one.");
585 #endif // NDEBUG
586 }
587 
588 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
589                                      BranchProbability Prob) {
590   // Probability list is either empty (if successor list isn't empty, this means
591   // disabled optimization) or has the same size as successor list.
592   if (!(Probs.empty() && !Successors.empty()))
593     Probs.push_back(Prob);
594   Successors.push_back(Succ);
595   Succ->addPredecessor(this);
596 }
597 
598 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
599   // We need to make sure probability list is either empty or has the same size
600   // of successor list. When this function is called, we can safely delete all
601   // probability in the list.
602   Probs.clear();
603   Successors.push_back(Succ);
604   Succ->addPredecessor(this);
605 }
606 
607 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
608                                         bool NormalizeSuccProbs) {
609   succ_iterator I = find(Successors, Succ);
610   removeSuccessor(I, NormalizeSuccProbs);
611 }
612 
613 MachineBasicBlock::succ_iterator
614 MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
615   assert(I != Successors.end() && "Not a current successor!");
616 
617   // If probability list is empty it means we don't use it (disabled
618   // optimization).
619   if (!Probs.empty()) {
620     probability_iterator WI = getProbabilityIterator(I);
621     Probs.erase(WI);
622     if (NormalizeSuccProbs)
623       normalizeSuccProbs();
624   }
625 
626   (*I)->removePredecessor(this);
627   return Successors.erase(I);
628 }
629 
630 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
631                                          MachineBasicBlock *New) {
632   if (Old == New)
633     return;
634 
635   succ_iterator E = succ_end();
636   succ_iterator NewI = E;
637   succ_iterator OldI = E;
638   for (succ_iterator I = succ_begin(); I != E; ++I) {
639     if (*I == Old) {
640       OldI = I;
641       if (NewI != E)
642         break;
643     }
644     if (*I == New) {
645       NewI = I;
646       if (OldI != E)
647         break;
648     }
649   }
650   assert(OldI != E && "Old is not a successor of this block");
651 
652   // If New isn't already a successor, let it take Old's place.
653   if (NewI == E) {
654     Old->removePredecessor(this);
655     New->addPredecessor(this);
656     *OldI = New;
657     return;
658   }
659 
660   // New is already a successor.
661   // Update its probability instead of adding a duplicate edge.
662   if (!Probs.empty()) {
663     auto ProbIter = getProbabilityIterator(NewI);
664     if (!ProbIter->isUnknown())
665       *ProbIter += *getProbabilityIterator(OldI);
666   }
667   removeSuccessor(OldI);
668 }
669 
670 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
671   Predecessors.push_back(Pred);
672 }
673 
674 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
675   pred_iterator I = find(Predecessors, Pred);
676   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
677   Predecessors.erase(I);
678 }
679 
680 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
681   if (this == FromMBB)
682     return;
683 
684   while (!FromMBB->succ_empty()) {
685     MachineBasicBlock *Succ = *FromMBB->succ_begin();
686 
687     // If probability list is empty it means we don't use it (disabled optimization).
688     if (!FromMBB->Probs.empty()) {
689       auto Prob = *FromMBB->Probs.begin();
690       addSuccessor(Succ, Prob);
691     } else
692       addSuccessorWithoutProb(Succ);
693 
694     FromMBB->removeSuccessor(Succ);
695   }
696 }
697 
698 void
699 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
700   if (this == FromMBB)
701     return;
702 
703   while (!FromMBB->succ_empty()) {
704     MachineBasicBlock *Succ = *FromMBB->succ_begin();
705     if (!FromMBB->Probs.empty()) {
706       auto Prob = *FromMBB->Probs.begin();
707       addSuccessor(Succ, Prob);
708     } else
709       addSuccessorWithoutProb(Succ);
710     FromMBB->removeSuccessor(Succ);
711 
712     // Fix up any PHI nodes in the successor.
713     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
714            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
715       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
716         MachineOperand &MO = MI->getOperand(i);
717         if (MO.getMBB() == FromMBB)
718           MO.setMBB(this);
719       }
720   }
721   normalizeSuccProbs();
722 }
723 
724 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
725   return is_contained(predecessors(), MBB);
726 }
727 
728 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
729   return is_contained(successors(), MBB);
730 }
731 
732 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
733   MachineFunction::const_iterator I(this);
734   return std::next(I) == MachineFunction::const_iterator(MBB);
735 }
736 
737 MachineBasicBlock *MachineBasicBlock::getFallThrough() {
738   MachineFunction::iterator Fallthrough = getIterator();
739   ++Fallthrough;
740   // If FallthroughBlock is off the end of the function, it can't fall through.
741   if (Fallthrough == getParent()->end())
742     return nullptr;
743 
744   // If FallthroughBlock isn't a successor, no fallthrough is possible.
745   if (!isSuccessor(&*Fallthrough))
746     return nullptr;
747 
748   // Analyze the branches, if any, at the end of the block.
749   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
750   SmallVector<MachineOperand, 4> Cond;
751   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
752   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
753     // If we couldn't analyze the branch, examine the last instruction.
754     // If the block doesn't end in a known control barrier, assume fallthrough
755     // is possible. The isPredicated check is needed because this code can be
756     // called during IfConversion, where an instruction which is normally a
757     // Barrier is predicated and thus no longer an actual control barrier.
758     return (empty() || !back().isBarrier() || TII->isPredicated(back()))
759                ? &*Fallthrough
760                : nullptr;
761   }
762 
763   // If there is no branch, control always falls through.
764   if (!TBB) return &*Fallthrough;
765 
766   // If there is some explicit branch to the fallthrough block, it can obviously
767   // reach, even though the branch should get folded to fall through implicitly.
768   if (MachineFunction::iterator(TBB) == Fallthrough ||
769       MachineFunction::iterator(FBB) == Fallthrough)
770     return &*Fallthrough;
771 
772   // If it's an unconditional branch to some block not the fall through, it
773   // doesn't fall through.
774   if (Cond.empty()) return nullptr;
775 
776   // Otherwise, if it is conditional and has no explicit false block, it falls
777   // through.
778   return (FBB == nullptr) ? &*Fallthrough : nullptr;
779 }
780 
781 bool MachineBasicBlock::canFallThrough() {
782   return getFallThrough() != nullptr;
783 }
784 
785 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ,
786                                                         Pass &P) {
787   if (!canSplitCriticalEdge(Succ))
788     return nullptr;
789 
790   MachineFunction *MF = getParent();
791   DebugLoc DL;  // FIXME: this is nowhere
792 
793   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
794   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
795   DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
796                << " -- " << printMBBReference(*NMBB) << " -- "
797                << printMBBReference(*Succ) << '\n');
798 
799   LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
800   SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
801   if (LIS)
802     LIS->insertMBBInMaps(NMBB);
803   else if (Indexes)
804     Indexes->insertMBBInMaps(NMBB);
805 
806   // On some targets like Mips, branches may kill virtual registers. Make sure
807   // that LiveVariables is properly updated after updateTerminator replaces the
808   // terminators.
809   LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
810 
811   // Collect a list of virtual registers killed by the terminators.
812   SmallVector<unsigned, 4> KilledRegs;
813   if (LV)
814     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
815          I != E; ++I) {
816       MachineInstr *MI = &*I;
817       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
818            OE = MI->operands_end(); OI != OE; ++OI) {
819         if (!OI->isReg() || OI->getReg() == 0 ||
820             !OI->isUse() || !OI->isKill() || OI->isUndef())
821           continue;
822         unsigned Reg = OI->getReg();
823         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
824             LV->getVarInfo(Reg).removeKill(*MI)) {
825           KilledRegs.push_back(Reg);
826           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
827           OI->setIsKill(false);
828         }
829       }
830     }
831 
832   SmallVector<unsigned, 4> UsedRegs;
833   if (LIS) {
834     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
835          I != E; ++I) {
836       MachineInstr *MI = &*I;
837 
838       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
839            OE = MI->operands_end(); OI != OE; ++OI) {
840         if (!OI->isReg() || OI->getReg() == 0)
841           continue;
842 
843         unsigned Reg = OI->getReg();
844         if (!is_contained(UsedRegs, Reg))
845           UsedRegs.push_back(Reg);
846       }
847     }
848   }
849 
850   ReplaceUsesOfBlockWith(Succ, NMBB);
851 
852   // If updateTerminator() removes instructions, we need to remove them from
853   // SlotIndexes.
854   SmallVector<MachineInstr*, 4> Terminators;
855   if (Indexes) {
856     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
857          I != E; ++I)
858       Terminators.push_back(&*I);
859   }
860 
861   updateTerminator();
862 
863   if (Indexes) {
864     SmallVector<MachineInstr*, 4> NewTerminators;
865     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
866          I != E; ++I)
867       NewTerminators.push_back(&*I);
868 
869     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
870         E = Terminators.end(); I != E; ++I) {
871       if (!is_contained(NewTerminators, *I))
872         Indexes->removeMachineInstrFromMaps(**I);
873     }
874   }
875 
876   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
877   NMBB->addSuccessor(Succ);
878   if (!NMBB->isLayoutSuccessor(Succ)) {
879     SmallVector<MachineOperand, 4> Cond;
880     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
881     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
882 
883     if (Indexes) {
884       for (MachineInstr &MI : NMBB->instrs()) {
885         // Some instructions may have been moved to NMBB by updateTerminator(),
886         // so we first remove any instruction that already has an index.
887         if (Indexes->hasIndex(MI))
888           Indexes->removeMachineInstrFromMaps(MI);
889         Indexes->insertMachineInstrInMaps(MI);
890       }
891     }
892   }
893 
894   // Fix PHI nodes in Succ so they refer to NMBB instead of this
895   for (MachineBasicBlock::instr_iterator
896          i = Succ->instr_begin(),e = Succ->instr_end();
897        i != e && i->isPHI(); ++i)
898     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
899       if (i->getOperand(ni+1).getMBB() == this)
900         i->getOperand(ni+1).setMBB(NMBB);
901 
902   // Inherit live-ins from the successor
903   for (const auto &LI : Succ->liveins())
904     NMBB->addLiveIn(LI);
905 
906   // Update LiveVariables.
907   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
908   if (LV) {
909     // Restore kills of virtual registers that were killed by the terminators.
910     while (!KilledRegs.empty()) {
911       unsigned Reg = KilledRegs.pop_back_val();
912       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
913         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
914           continue;
915         if (TargetRegisterInfo::isVirtualRegister(Reg))
916           LV->getVarInfo(Reg).Kills.push_back(&*I);
917         DEBUG(dbgs() << "Restored terminator kill: " << *I);
918         break;
919       }
920     }
921     // Update relevant live-through information.
922     LV->addNewBlock(NMBB, this, Succ);
923   }
924 
925   if (LIS) {
926     // After splitting the edge and updating SlotIndexes, live intervals may be
927     // in one of two situations, depending on whether this block was the last in
928     // the function. If the original block was the last in the function, all
929     // live intervals will end prior to the beginning of the new split block. If
930     // the original block was not at the end of the function, all live intervals
931     // will extend to the end of the new split block.
932 
933     bool isLastMBB =
934       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
935 
936     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
937     SlotIndex PrevIndex = StartIndex.getPrevSlot();
938     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
939 
940     // Find the registers used from NMBB in PHIs in Succ.
941     SmallSet<unsigned, 8> PHISrcRegs;
942     for (MachineBasicBlock::instr_iterator
943          I = Succ->instr_begin(), E = Succ->instr_end();
944          I != E && I->isPHI(); ++I) {
945       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
946         if (I->getOperand(ni+1).getMBB() == NMBB) {
947           MachineOperand &MO = I->getOperand(ni);
948           unsigned Reg = MO.getReg();
949           PHISrcRegs.insert(Reg);
950           if (MO.isUndef())
951             continue;
952 
953           LiveInterval &LI = LIS->getInterval(Reg);
954           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
955           assert(VNI &&
956                  "PHI sources should be live out of their predecessors.");
957           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
958         }
959       }
960     }
961 
962     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
963     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
964       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
965       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
966         continue;
967 
968       LiveInterval &LI = LIS->getInterval(Reg);
969       if (!LI.liveAt(PrevIndex))
970         continue;
971 
972       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
973       if (isLiveOut && isLastMBB) {
974         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
975         assert(VNI && "LiveInterval should have VNInfo where it is live.");
976         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
977       } else if (!isLiveOut && !isLastMBB) {
978         LI.removeSegment(StartIndex, EndIndex);
979       }
980     }
981 
982     // Update all intervals for registers whose uses may have been modified by
983     // updateTerminator().
984     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
985   }
986 
987   if (MachineDominatorTree *MDT =
988           P.getAnalysisIfAvailable<MachineDominatorTree>())
989     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
990 
991   if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
992     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
993       // If one or the other blocks were not in a loop, the new block is not
994       // either, and thus LI doesn't need to be updated.
995       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
996         if (TIL == DestLoop) {
997           // Both in the same loop, the NMBB joins loop.
998           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
999         } else if (TIL->contains(DestLoop)) {
1000           // Edge from an outer loop to an inner loop.  Add to the outer loop.
1001           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
1002         } else if (DestLoop->contains(TIL)) {
1003           // Edge from an inner loop to an outer loop.  Add to the outer loop.
1004           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1005         } else {
1006           // Edge from two loops with no containment relation.  Because these
1007           // are natural loops, we know that the destination block must be the
1008           // header of its loop (adding a branch into a loop elsewhere would
1009           // create an irreducible loop).
1010           assert(DestLoop->getHeader() == Succ &&
1011                  "Should not create irreducible loops!");
1012           if (MachineLoop *P = DestLoop->getParentLoop())
1013             P->addBasicBlockToLoop(NMBB, MLI->getBase());
1014         }
1015       }
1016     }
1017 
1018   return NMBB;
1019 }
1020 
1021 bool MachineBasicBlock::canSplitCriticalEdge(
1022     const MachineBasicBlock *Succ) const {
1023   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1024   // it in this generic function.
1025   if (Succ->isEHPad())
1026     return false;
1027 
1028   const MachineFunction *MF = getParent();
1029 
1030   // Performance might be harmed on HW that implements branching using exec mask
1031   // where both sides of the branches are always executed.
1032   if (MF->getTarget().requiresStructuredCFG())
1033     return false;
1034 
1035   // We may need to update this's terminator, but we can't do that if
1036   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
1037   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1038   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1039   SmallVector<MachineOperand, 4> Cond;
1040   // AnalyzeBanch should modify this, since we did not allow modification.
1041   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1042                          /*AllowModify*/ false))
1043     return false;
1044 
1045   // Avoid bugpoint weirdness: A block may end with a conditional branch but
1046   // jumps to the same MBB is either case. We have duplicate CFG edges in that
1047   // case that we can't handle. Since this never happens in properly optimized
1048   // code, just skip those edges.
1049   if (TBB && TBB == FBB) {
1050     DEBUG(dbgs() << "Won't split critical edge after degenerate "
1051                  << printMBBReference(*this) << '\n');
1052     return false;
1053   }
1054   return true;
1055 }
1056 
1057 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1058 /// neighboring instructions so the bundle won't be broken by removing MI.
1059 static void unbundleSingleMI(MachineInstr *MI) {
1060   // Removing the first instruction in a bundle.
1061   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1062     MI->unbundleFromSucc();
1063   // Removing the last instruction in a bundle.
1064   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1065     MI->unbundleFromPred();
1066   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1067   // are already fine.
1068 }
1069 
1070 MachineBasicBlock::instr_iterator
1071 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1072   unbundleSingleMI(&*I);
1073   return Insts.erase(I);
1074 }
1075 
1076 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1077   unbundleSingleMI(MI);
1078   MI->clearFlag(MachineInstr::BundledPred);
1079   MI->clearFlag(MachineInstr::BundledSucc);
1080   return Insts.remove(MI);
1081 }
1082 
1083 MachineBasicBlock::instr_iterator
1084 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1085   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1086          "Cannot insert instruction with bundle flags");
1087   // Set the bundle flags when inserting inside a bundle.
1088   if (I != instr_end() && I->isBundledWithPred()) {
1089     MI->setFlag(MachineInstr::BundledPred);
1090     MI->setFlag(MachineInstr::BundledSucc);
1091   }
1092   return Insts.insert(I, MI);
1093 }
1094 
1095 /// This method unlinks 'this' from the containing function, and returns it, but
1096 /// does not delete it.
1097 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1098   assert(getParent() && "Not embedded in a function!");
1099   getParent()->remove(this);
1100   return this;
1101 }
1102 
1103 /// This method unlinks 'this' from the containing function, and deletes it.
1104 void MachineBasicBlock::eraseFromParent() {
1105   assert(getParent() && "Not embedded in a function!");
1106   getParent()->erase(this);
1107 }
1108 
1109 /// Given a machine basic block that branched to 'Old', change the code and CFG
1110 /// so that it branches to 'New' instead.
1111 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1112                                                MachineBasicBlock *New) {
1113   assert(Old != New && "Cannot replace self with self!");
1114 
1115   MachineBasicBlock::instr_iterator I = instr_end();
1116   while (I != instr_begin()) {
1117     --I;
1118     if (!I->isTerminator()) break;
1119 
1120     // Scan the operands of this machine instruction, replacing any uses of Old
1121     // with New.
1122     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1123       if (I->getOperand(i).isMBB() &&
1124           I->getOperand(i).getMBB() == Old)
1125         I->getOperand(i).setMBB(New);
1126   }
1127 
1128   // Update the successor information.
1129   replaceSuccessor(Old, New);
1130 }
1131 
1132 /// Various pieces of code can cause excess edges in the CFG to be inserted.  If
1133 /// we have proven that MBB can only branch to DestA and DestB, remove any other
1134 /// MBB successors from the CFG.  DestA and DestB can be null.
1135 ///
1136 /// Besides DestA and DestB, retain other edges leading to LandingPads
1137 /// (currently there can be only one; we don't check or require that here).
1138 /// Note it is possible that DestA and/or DestB are LandingPads.
1139 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1140                                              MachineBasicBlock *DestB,
1141                                              bool IsCond) {
1142   // The values of DestA and DestB frequently come from a call to the
1143   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1144   // values from there.
1145   //
1146   // 1. If both DestA and DestB are null, then the block ends with no branches
1147   //    (it falls through to its successor).
1148   // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
1149   //    with only an unconditional branch.
1150   // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
1151   //    with a conditional branch that falls through to a successor (DestB).
1152   // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
1153   //    conditional branch followed by an unconditional branch. DestA is the
1154   //    'true' destination and DestB is the 'false' destination.
1155 
1156   bool Changed = false;
1157 
1158   MachineBasicBlock *FallThru = getNextNode();
1159 
1160   if (!DestA && !DestB) {
1161     // Block falls through to successor.
1162     DestA = FallThru;
1163     DestB = FallThru;
1164   } else if (DestA && !DestB) {
1165     if (IsCond)
1166       // Block ends in conditional jump that falls through to successor.
1167       DestB = FallThru;
1168   } else {
1169     assert(DestA && DestB && IsCond &&
1170            "CFG in a bad state. Cannot correct CFG edges");
1171   }
1172 
1173   // Remove superfluous edges. I.e., those which aren't destinations of this
1174   // basic block, duplicate edges, or landing pads.
1175   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1176   MachineBasicBlock::succ_iterator SI = succ_begin();
1177   while (SI != succ_end()) {
1178     const MachineBasicBlock *MBB = *SI;
1179     if (!SeenMBBs.insert(MBB).second ||
1180         (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
1181       // This is a superfluous edge, remove it.
1182       SI = removeSuccessor(SI);
1183       Changed = true;
1184     } else {
1185       ++SI;
1186     }
1187   }
1188 
1189   if (Changed)
1190     normalizeSuccProbs();
1191   return Changed;
1192 }
1193 
1194 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1195 /// instructions.  Return UnknownLoc if there is none.
1196 DebugLoc
1197 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1198   // Skip debug declarations, we don't want a DebugLoc from them.
1199   MBBI = skipDebugInstructionsForward(MBBI, instr_end());
1200   if (MBBI != instr_end())
1201     return MBBI->getDebugLoc();
1202   return {};
1203 }
1204 
1205 /// Find and return the merged DebugLoc of the branch instructions of the block.
1206 /// Return UnknownLoc if there is none.
1207 DebugLoc
1208 MachineBasicBlock::findBranchDebugLoc() {
1209   DebugLoc DL;
1210   auto TI = getFirstTerminator();
1211   while (TI != end() && !TI->isBranch())
1212     ++TI;
1213 
1214   if (TI != end()) {
1215     DL = TI->getDebugLoc();
1216     for (++TI ; TI != end() ; ++TI)
1217       if (TI->isBranch())
1218         DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
1219   }
1220   return DL;
1221 }
1222 
1223 /// Return probability of the edge from this block to MBB.
1224 BranchProbability
1225 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1226   if (Probs.empty())
1227     return BranchProbability(1, succ_size());
1228 
1229   const auto &Prob = *getProbabilityIterator(Succ);
1230   if (Prob.isUnknown()) {
1231     // For unknown probabilities, collect the sum of all known ones, and evenly
1232     // ditribute the complemental of the sum to each unknown probability.
1233     unsigned KnownProbNum = 0;
1234     auto Sum = BranchProbability::getZero();
1235     for (auto &P : Probs) {
1236       if (!P.isUnknown()) {
1237         Sum += P;
1238         KnownProbNum++;
1239       }
1240     }
1241     return Sum.getCompl() / (Probs.size() - KnownProbNum);
1242   } else
1243     return Prob;
1244 }
1245 
1246 /// Set successor probability of a given iterator.
1247 void MachineBasicBlock::setSuccProbability(succ_iterator I,
1248                                            BranchProbability Prob) {
1249   assert(!Prob.isUnknown());
1250   if (Probs.empty())
1251     return;
1252   *getProbabilityIterator(I) = Prob;
1253 }
1254 
1255 /// Return probability iterator corresonding to the I successor iterator
1256 MachineBasicBlock::const_probability_iterator
1257 MachineBasicBlock::getProbabilityIterator(
1258     MachineBasicBlock::const_succ_iterator I) const {
1259   assert(Probs.size() == Successors.size() && "Async probability list!");
1260   const size_t index = std::distance(Successors.begin(), I);
1261   assert(index < Probs.size() && "Not a current successor!");
1262   return Probs.begin() + index;
1263 }
1264 
1265 /// Return probability iterator corresonding to the I successor iterator.
1266 MachineBasicBlock::probability_iterator
1267 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1268   assert(Probs.size() == Successors.size() && "Async probability list!");
1269   const size_t index = std::distance(Successors.begin(), I);
1270   assert(index < Probs.size() && "Not a current successor!");
1271   return Probs.begin() + index;
1272 }
1273 
1274 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1275 /// as of just before "MI".
1276 ///
1277 /// Search is localised to a neighborhood of
1278 /// Neighborhood instructions before (searching for defs or kills) and N
1279 /// instructions after (searching just for defs) MI.
1280 MachineBasicBlock::LivenessQueryResult
1281 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1282                                            unsigned Reg, const_iterator Before,
1283                                            unsigned Neighborhood) const {
1284   unsigned N = Neighborhood;
1285 
1286   // Start by searching backwards from Before, looking for kills, reads or defs.
1287   const_iterator I(Before);
1288   // If this is the first insn in the block, don't search backwards.
1289   if (I != begin()) {
1290     do {
1291       --I;
1292 
1293       MachineOperandIteratorBase::PhysRegInfo Info =
1294           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
1295 
1296       // Defs happen after uses so they take precedence if both are present.
1297 
1298       // Register is dead after a dead def of the full register.
1299       if (Info.DeadDef)
1300         return LQR_Dead;
1301       // Register is (at least partially) live after a def.
1302       if (Info.Defined) {
1303         if (!Info.PartialDeadDef)
1304           return LQR_Live;
1305         // As soon as we saw a partial definition (dead or not),
1306         // we cannot tell if the value is partial live without
1307         // tracking the lanemasks. We are not going to do this,
1308         // so fall back on the remaining of the analysis.
1309         break;
1310       }
1311       // Register is dead after a full kill or clobber and no def.
1312       if (Info.Killed || Info.Clobbered)
1313         return LQR_Dead;
1314       // Register must be live if we read it.
1315       if (Info.Read)
1316         return LQR_Live;
1317     } while (I != begin() && --N > 0);
1318   }
1319 
1320   // Did we get to the start of the block?
1321   if (I == begin()) {
1322     // If so, the register's state is definitely defined by the live-in state.
1323     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); RAI.isValid();
1324          ++RAI)
1325       if (isLiveIn(*RAI))
1326         return LQR_Live;
1327 
1328     return LQR_Dead;
1329   }
1330 
1331   N = Neighborhood;
1332 
1333   // Try searching forwards from Before, looking for reads or defs.
1334   I = const_iterator(Before);
1335   // If this is the last insn in the block, don't search forwards.
1336   if (I != end()) {
1337     for (++I; I != end() && N > 0; ++I, --N) {
1338       MachineOperandIteratorBase::PhysRegInfo Info =
1339           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
1340 
1341       // Register is live when we read it here.
1342       if (Info.Read)
1343         return LQR_Live;
1344       // Register is dead if we can fully overwrite or clobber it here.
1345       if (Info.FullyDefined || Info.Clobbered)
1346         return LQR_Dead;
1347     }
1348   }
1349 
1350   // At this point we have no idea of the liveness of the register.
1351   return LQR_Unknown;
1352 }
1353 
1354 const uint32_t *
1355 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1356   // EH funclet entry does not preserve any registers.
1357   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1358 }
1359 
1360 const uint32_t *
1361 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1362   // If we see a return block with successors, this must be a funclet return,
1363   // which does not preserve any registers. If there are no successors, we don't
1364   // care what kind of return it is, putting a mask after it is a no-op.
1365   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1366 }
1367 
1368 void MachineBasicBlock::clearLiveIns() {
1369   LiveIns.clear();
1370 }
1371 
1372 MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
1373   assert(getParent()->getProperties().hasProperty(
1374       MachineFunctionProperties::Property::TracksLiveness) &&
1375       "Liveness information is accurate");
1376   return LiveIns.begin();
1377 }
1378