xref: /llvm-project/llvm/lib/CodeGen/MachineBasicBlock.cpp (revision d65438d0ca7cf1e03a27767dbf2e455ac0b9b154)
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     OS << '\n';
356   }
357 
358   // Print the successors of this block according to the CFG.
359   if (!succ_empty()) {
360     if (Indexes) OS << '\t';
361     OS << "    Successors according to CFG:";
362     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
363       OS << " " << printMBBReference(*(*SI));
364       if (!Probs.empty())
365         OS << '(' << *getProbabilityIterator(SI) << ')';
366     }
367     OS << '\n';
368   }
369   if (IrrLoopHeaderWeight) {
370     if (Indexes) OS << '\t';
371     OS << "    Irreducible loop header weight: "
372        << IrrLoopHeaderWeight.getValue();
373     OS << '\n';
374   }
375 }
376 
377 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
378                                        bool /*PrintType*/) const {
379   OS << "%bb." << getNumber();
380 }
381 
382 void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
383   LiveInVector::iterator I = find_if(
384       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
385   if (I == LiveIns.end())
386     return;
387 
388   I->LaneMask &= ~LaneMask;
389   if (I->LaneMask.none())
390     LiveIns.erase(I);
391 }
392 
393 MachineBasicBlock::livein_iterator
394 MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
395   // Get non-const version of iterator.
396   LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
397   return LiveIns.erase(LI);
398 }
399 
400 bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
401   livein_iterator I = find_if(
402       LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
403   return I != livein_end() && (I->LaneMask & LaneMask).any();
404 }
405 
406 void MachineBasicBlock::sortUniqueLiveIns() {
407   std::sort(LiveIns.begin(), LiveIns.end(),
408             [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
409               return LI0.PhysReg < LI1.PhysReg;
410             });
411   // Liveins are sorted by physreg now we can merge their lanemasks.
412   LiveInVector::const_iterator I = LiveIns.begin();
413   LiveInVector::const_iterator J;
414   LiveInVector::iterator Out = LiveIns.begin();
415   for (; I != LiveIns.end(); ++Out, I = J) {
416     unsigned PhysReg = I->PhysReg;
417     LaneBitmask LaneMask = I->LaneMask;
418     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
419       LaneMask |= J->LaneMask;
420     Out->PhysReg = PhysReg;
421     Out->LaneMask = LaneMask;
422   }
423   LiveIns.erase(Out, LiveIns.end());
424 }
425 
426 unsigned
427 MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
428   assert(getParent() && "MBB must be inserted in function");
429   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
430   assert(RC && "Register class is required");
431   assert((isEHPad() || this == &getParent()->front()) &&
432          "Only the entry block and landing pads can have physreg live ins");
433 
434   bool LiveIn = isLiveIn(PhysReg);
435   iterator I = SkipPHIsAndLabels(begin()), E = end();
436   MachineRegisterInfo &MRI = getParent()->getRegInfo();
437   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
438 
439   // Look for an existing copy.
440   if (LiveIn)
441     for (;I != E && I->isCopy(); ++I)
442       if (I->getOperand(1).getReg() == PhysReg) {
443         unsigned VirtReg = I->getOperand(0).getReg();
444         if (!MRI.constrainRegClass(VirtReg, RC))
445           llvm_unreachable("Incompatible live-in register class.");
446         return VirtReg;
447       }
448 
449   // No luck, create a virtual register.
450   unsigned VirtReg = MRI.createVirtualRegister(RC);
451   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
452     .addReg(PhysReg, RegState::Kill);
453   if (!LiveIn)
454     addLiveIn(PhysReg);
455   return VirtReg;
456 }
457 
458 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
459   getParent()->splice(NewAfter->getIterator(), getIterator());
460 }
461 
462 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
463   getParent()->splice(++NewBefore->getIterator(), getIterator());
464 }
465 
466 void MachineBasicBlock::updateTerminator() {
467   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
468   // A block with no successors has no concerns with fall-through edges.
469   if (this->succ_empty())
470     return;
471 
472   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
473   SmallVector<MachineOperand, 4> Cond;
474   DebugLoc DL = findBranchDebugLoc();
475   bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
476   (void) B;
477   assert(!B && "UpdateTerminators requires analyzable predecessors!");
478   if (Cond.empty()) {
479     if (TBB) {
480       // The block has an unconditional branch. If its successor is now its
481       // layout successor, delete the branch.
482       if (isLayoutSuccessor(TBB))
483         TII->removeBranch(*this);
484     } else {
485       // The block has an unconditional fallthrough. If its successor is not its
486       // layout successor, insert a branch. First we have to locate the only
487       // non-landing-pad successor, as that is the fallthrough block.
488       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
489         if ((*SI)->isEHPad())
490           continue;
491         assert(!TBB && "Found more than one non-landing-pad successor!");
492         TBB = *SI;
493       }
494 
495       // If there is no non-landing-pad successor, the block has no fall-through
496       // edges to be concerned with.
497       if (!TBB)
498         return;
499 
500       // Finally update the unconditional successor to be reached via a branch
501       // if it would not be reached by fallthrough.
502       if (!isLayoutSuccessor(TBB))
503         TII->insertBranch(*this, TBB, nullptr, Cond, DL);
504     }
505     return;
506   }
507 
508   if (FBB) {
509     // The block has a non-fallthrough conditional branch. If one of its
510     // successors is its layout successor, rewrite it to a fallthrough
511     // conditional branch.
512     if (isLayoutSuccessor(TBB)) {
513       if (TII->reverseBranchCondition(Cond))
514         return;
515       TII->removeBranch(*this);
516       TII->insertBranch(*this, FBB, nullptr, Cond, DL);
517     } else if (isLayoutSuccessor(FBB)) {
518       TII->removeBranch(*this);
519       TII->insertBranch(*this, TBB, nullptr, Cond, DL);
520     }
521     return;
522   }
523 
524   // Walk through the successors and find the successor which is not a landing
525   // pad and is not the conditional branch destination (in TBB) as the
526   // fallthrough successor.
527   MachineBasicBlock *FallthroughBB = nullptr;
528   for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
529     if ((*SI)->isEHPad() || *SI == TBB)
530       continue;
531     assert(!FallthroughBB && "Found more than one fallthrough successor.");
532     FallthroughBB = *SI;
533   }
534 
535   if (!FallthroughBB) {
536     if (canFallThrough()) {
537       // We fallthrough to the same basic block as the conditional jump targets.
538       // Remove the conditional jump, leaving unconditional fallthrough.
539       // FIXME: This does not seem like a reasonable pattern to support, but it
540       // has been seen in the wild coming out of degenerate ARM test cases.
541       TII->removeBranch(*this);
542 
543       // Finally update the unconditional successor to be reached via a branch if
544       // it would not be reached by fallthrough.
545       if (!isLayoutSuccessor(TBB))
546         TII->insertBranch(*this, TBB, nullptr, Cond, DL);
547       return;
548     }
549 
550     // We enter here iff exactly one successor is TBB which cannot fallthrough
551     // and the rest successors if any are EHPads.  In this case, we need to
552     // change the conditional branch into unconditional branch.
553     TII->removeBranch(*this);
554     Cond.clear();
555     TII->insertBranch(*this, TBB, nullptr, Cond, DL);
556     return;
557   }
558 
559   // The block has a fallthrough conditional branch.
560   if (isLayoutSuccessor(TBB)) {
561     if (TII->reverseBranchCondition(Cond)) {
562       // We can't reverse the condition, add an unconditional branch.
563       Cond.clear();
564       TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
565       return;
566     }
567     TII->removeBranch(*this);
568     TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
569   } else if (!isLayoutSuccessor(FallthroughBB)) {
570     TII->removeBranch(*this);
571     TII->insertBranch(*this, TBB, FallthroughBB, Cond, DL);
572   }
573 }
574 
575 void MachineBasicBlock::validateSuccProbs() const {
576 #ifndef NDEBUG
577   int64_t Sum = 0;
578   for (auto Prob : Probs)
579     Sum += Prob.getNumerator();
580   // Due to precision issue, we assume that the sum of probabilities is one if
581   // the difference between the sum of their numerators and the denominator is
582   // no greater than the number of successors.
583   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
584              Probs.size() &&
585          "The sum of successors's probabilities exceeds one.");
586 #endif // NDEBUG
587 }
588 
589 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
590                                      BranchProbability Prob) {
591   // Probability list is either empty (if successor list isn't empty, this means
592   // disabled optimization) or has the same size as successor list.
593   if (!(Probs.empty() && !Successors.empty()))
594     Probs.push_back(Prob);
595   Successors.push_back(Succ);
596   Succ->addPredecessor(this);
597 }
598 
599 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
600   // We need to make sure probability list is either empty or has the same size
601   // of successor list. When this function is called, we can safely delete all
602   // probability in the list.
603   Probs.clear();
604   Successors.push_back(Succ);
605   Succ->addPredecessor(this);
606 }
607 
608 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
609                                         bool NormalizeSuccProbs) {
610   succ_iterator I = find(Successors, Succ);
611   removeSuccessor(I, NormalizeSuccProbs);
612 }
613 
614 MachineBasicBlock::succ_iterator
615 MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
616   assert(I != Successors.end() && "Not a current successor!");
617 
618   // If probability list is empty it means we don't use it (disabled
619   // optimization).
620   if (!Probs.empty()) {
621     probability_iterator WI = getProbabilityIterator(I);
622     Probs.erase(WI);
623     if (NormalizeSuccProbs)
624       normalizeSuccProbs();
625   }
626 
627   (*I)->removePredecessor(this);
628   return Successors.erase(I);
629 }
630 
631 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
632                                          MachineBasicBlock *New) {
633   if (Old == New)
634     return;
635 
636   succ_iterator E = succ_end();
637   succ_iterator NewI = E;
638   succ_iterator OldI = E;
639   for (succ_iterator I = succ_begin(); I != E; ++I) {
640     if (*I == Old) {
641       OldI = I;
642       if (NewI != E)
643         break;
644     }
645     if (*I == New) {
646       NewI = I;
647       if (OldI != E)
648         break;
649     }
650   }
651   assert(OldI != E && "Old is not a successor of this block");
652 
653   // If New isn't already a successor, let it take Old's place.
654   if (NewI == E) {
655     Old->removePredecessor(this);
656     New->addPredecessor(this);
657     *OldI = New;
658     return;
659   }
660 
661   // New is already a successor.
662   // Update its probability instead of adding a duplicate edge.
663   if (!Probs.empty()) {
664     auto ProbIter = getProbabilityIterator(NewI);
665     if (!ProbIter->isUnknown())
666       *ProbIter += *getProbabilityIterator(OldI);
667   }
668   removeSuccessor(OldI);
669 }
670 
671 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
672   Predecessors.push_back(Pred);
673 }
674 
675 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
676   pred_iterator I = find(Predecessors, Pred);
677   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
678   Predecessors.erase(I);
679 }
680 
681 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
682   if (this == FromMBB)
683     return;
684 
685   while (!FromMBB->succ_empty()) {
686     MachineBasicBlock *Succ = *FromMBB->succ_begin();
687 
688     // If probability list is empty it means we don't use it (disabled optimization).
689     if (!FromMBB->Probs.empty()) {
690       auto Prob = *FromMBB->Probs.begin();
691       addSuccessor(Succ, Prob);
692     } else
693       addSuccessorWithoutProb(Succ);
694 
695     FromMBB->removeSuccessor(Succ);
696   }
697 }
698 
699 void
700 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
701   if (this == FromMBB)
702     return;
703 
704   while (!FromMBB->succ_empty()) {
705     MachineBasicBlock *Succ = *FromMBB->succ_begin();
706     if (!FromMBB->Probs.empty()) {
707       auto Prob = *FromMBB->Probs.begin();
708       addSuccessor(Succ, Prob);
709     } else
710       addSuccessorWithoutProb(Succ);
711     FromMBB->removeSuccessor(Succ);
712 
713     // Fix up any PHI nodes in the successor.
714     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
715            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
716       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
717         MachineOperand &MO = MI->getOperand(i);
718         if (MO.getMBB() == FromMBB)
719           MO.setMBB(this);
720       }
721   }
722   normalizeSuccProbs();
723 }
724 
725 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
726   return is_contained(predecessors(), MBB);
727 }
728 
729 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
730   return is_contained(successors(), MBB);
731 }
732 
733 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
734   MachineFunction::const_iterator I(this);
735   return std::next(I) == MachineFunction::const_iterator(MBB);
736 }
737 
738 MachineBasicBlock *MachineBasicBlock::getFallThrough() {
739   MachineFunction::iterator Fallthrough = getIterator();
740   ++Fallthrough;
741   // If FallthroughBlock is off the end of the function, it can't fall through.
742   if (Fallthrough == getParent()->end())
743     return nullptr;
744 
745   // If FallthroughBlock isn't a successor, no fallthrough is possible.
746   if (!isSuccessor(&*Fallthrough))
747     return nullptr;
748 
749   // Analyze the branches, if any, at the end of the block.
750   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
751   SmallVector<MachineOperand, 4> Cond;
752   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
753   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
754     // If we couldn't analyze the branch, examine the last instruction.
755     // If the block doesn't end in a known control barrier, assume fallthrough
756     // is possible. The isPredicated check is needed because this code can be
757     // called during IfConversion, where an instruction which is normally a
758     // Barrier is predicated and thus no longer an actual control barrier.
759     return (empty() || !back().isBarrier() || TII->isPredicated(back()))
760                ? &*Fallthrough
761                : nullptr;
762   }
763 
764   // If there is no branch, control always falls through.
765   if (!TBB) return &*Fallthrough;
766 
767   // If there is some explicit branch to the fallthrough block, it can obviously
768   // reach, even though the branch should get folded to fall through implicitly.
769   if (MachineFunction::iterator(TBB) == Fallthrough ||
770       MachineFunction::iterator(FBB) == Fallthrough)
771     return &*Fallthrough;
772 
773   // If it's an unconditional branch to some block not the fall through, it
774   // doesn't fall through.
775   if (Cond.empty()) return nullptr;
776 
777   // Otherwise, if it is conditional and has no explicit false block, it falls
778   // through.
779   return (FBB == nullptr) ? &*Fallthrough : nullptr;
780 }
781 
782 bool MachineBasicBlock::canFallThrough() {
783   return getFallThrough() != nullptr;
784 }
785 
786 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ,
787                                                         Pass &P) {
788   if (!canSplitCriticalEdge(Succ))
789     return nullptr;
790 
791   MachineFunction *MF = getParent();
792   DebugLoc DL;  // FIXME: this is nowhere
793 
794   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
795   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
796   DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
797                << " -- " << printMBBReference(*NMBB) << " -- "
798                << printMBBReference(*Succ) << '\n');
799 
800   LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
801   SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
802   if (LIS)
803     LIS->insertMBBInMaps(NMBB);
804   else if (Indexes)
805     Indexes->insertMBBInMaps(NMBB);
806 
807   // On some targets like Mips, branches may kill virtual registers. Make sure
808   // that LiveVariables is properly updated after updateTerminator replaces the
809   // terminators.
810   LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
811 
812   // Collect a list of virtual registers killed by the terminators.
813   SmallVector<unsigned, 4> KilledRegs;
814   if (LV)
815     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
816          I != E; ++I) {
817       MachineInstr *MI = &*I;
818       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
819            OE = MI->operands_end(); OI != OE; ++OI) {
820         if (!OI->isReg() || OI->getReg() == 0 ||
821             !OI->isUse() || !OI->isKill() || OI->isUndef())
822           continue;
823         unsigned Reg = OI->getReg();
824         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
825             LV->getVarInfo(Reg).removeKill(*MI)) {
826           KilledRegs.push_back(Reg);
827           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
828           OI->setIsKill(false);
829         }
830       }
831     }
832 
833   SmallVector<unsigned, 4> UsedRegs;
834   if (LIS) {
835     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
836          I != E; ++I) {
837       MachineInstr *MI = &*I;
838 
839       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
840            OE = MI->operands_end(); OI != OE; ++OI) {
841         if (!OI->isReg() || OI->getReg() == 0)
842           continue;
843 
844         unsigned Reg = OI->getReg();
845         if (!is_contained(UsedRegs, Reg))
846           UsedRegs.push_back(Reg);
847       }
848     }
849   }
850 
851   ReplaceUsesOfBlockWith(Succ, NMBB);
852 
853   // If updateTerminator() removes instructions, we need to remove them from
854   // SlotIndexes.
855   SmallVector<MachineInstr*, 4> Terminators;
856   if (Indexes) {
857     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
858          I != E; ++I)
859       Terminators.push_back(&*I);
860   }
861 
862   updateTerminator();
863 
864   if (Indexes) {
865     SmallVector<MachineInstr*, 4> NewTerminators;
866     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
867          I != E; ++I)
868       NewTerminators.push_back(&*I);
869 
870     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
871         E = Terminators.end(); I != E; ++I) {
872       if (!is_contained(NewTerminators, *I))
873         Indexes->removeMachineInstrFromMaps(**I);
874     }
875   }
876 
877   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
878   NMBB->addSuccessor(Succ);
879   if (!NMBB->isLayoutSuccessor(Succ)) {
880     SmallVector<MachineOperand, 4> Cond;
881     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
882     TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
883 
884     if (Indexes) {
885       for (MachineInstr &MI : NMBB->instrs()) {
886         // Some instructions may have been moved to NMBB by updateTerminator(),
887         // so we first remove any instruction that already has an index.
888         if (Indexes->hasIndex(MI))
889           Indexes->removeMachineInstrFromMaps(MI);
890         Indexes->insertMachineInstrInMaps(MI);
891       }
892     }
893   }
894 
895   // Fix PHI nodes in Succ so they refer to NMBB instead of this
896   for (MachineBasicBlock::instr_iterator
897          i = Succ->instr_begin(),e = Succ->instr_end();
898        i != e && i->isPHI(); ++i)
899     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
900       if (i->getOperand(ni+1).getMBB() == this)
901         i->getOperand(ni+1).setMBB(NMBB);
902 
903   // Inherit live-ins from the successor
904   for (const auto &LI : Succ->liveins())
905     NMBB->addLiveIn(LI);
906 
907   // Update LiveVariables.
908   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
909   if (LV) {
910     // Restore kills of virtual registers that were killed by the terminators.
911     while (!KilledRegs.empty()) {
912       unsigned Reg = KilledRegs.pop_back_val();
913       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
914         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
915           continue;
916         if (TargetRegisterInfo::isVirtualRegister(Reg))
917           LV->getVarInfo(Reg).Kills.push_back(&*I);
918         DEBUG(dbgs() << "Restored terminator kill: " << *I);
919         break;
920       }
921     }
922     // Update relevant live-through information.
923     LV->addNewBlock(NMBB, this, Succ);
924   }
925 
926   if (LIS) {
927     // After splitting the edge and updating SlotIndexes, live intervals may be
928     // in one of two situations, depending on whether this block was the last in
929     // the function. If the original block was the last in the function, all
930     // live intervals will end prior to the beginning of the new split block. If
931     // the original block was not at the end of the function, all live intervals
932     // will extend to the end of the new split block.
933 
934     bool isLastMBB =
935       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
936 
937     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
938     SlotIndex PrevIndex = StartIndex.getPrevSlot();
939     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
940 
941     // Find the registers used from NMBB in PHIs in Succ.
942     SmallSet<unsigned, 8> PHISrcRegs;
943     for (MachineBasicBlock::instr_iterator
944          I = Succ->instr_begin(), E = Succ->instr_end();
945          I != E && I->isPHI(); ++I) {
946       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
947         if (I->getOperand(ni+1).getMBB() == NMBB) {
948           MachineOperand &MO = I->getOperand(ni);
949           unsigned Reg = MO.getReg();
950           PHISrcRegs.insert(Reg);
951           if (MO.isUndef())
952             continue;
953 
954           LiveInterval &LI = LIS->getInterval(Reg);
955           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
956           assert(VNI &&
957                  "PHI sources should be live out of their predecessors.");
958           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
959         }
960       }
961     }
962 
963     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
964     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
965       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
966       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
967         continue;
968 
969       LiveInterval &LI = LIS->getInterval(Reg);
970       if (!LI.liveAt(PrevIndex))
971         continue;
972 
973       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
974       if (isLiveOut && isLastMBB) {
975         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
976         assert(VNI && "LiveInterval should have VNInfo where it is live.");
977         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
978       } else if (!isLiveOut && !isLastMBB) {
979         LI.removeSegment(StartIndex, EndIndex);
980       }
981     }
982 
983     // Update all intervals for registers whose uses may have been modified by
984     // updateTerminator().
985     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
986   }
987 
988   if (MachineDominatorTree *MDT =
989           P.getAnalysisIfAvailable<MachineDominatorTree>())
990     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
991 
992   if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
993     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
994       // If one or the other blocks were not in a loop, the new block is not
995       // either, and thus LI doesn't need to be updated.
996       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
997         if (TIL == DestLoop) {
998           // Both in the same loop, the NMBB joins loop.
999           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1000         } else if (TIL->contains(DestLoop)) {
1001           // Edge from an outer loop to an inner loop.  Add to the outer loop.
1002           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
1003         } else if (DestLoop->contains(TIL)) {
1004           // Edge from an inner loop to an outer loop.  Add to the outer loop.
1005           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1006         } else {
1007           // Edge from two loops with no containment relation.  Because these
1008           // are natural loops, we know that the destination block must be the
1009           // header of its loop (adding a branch into a loop elsewhere would
1010           // create an irreducible loop).
1011           assert(DestLoop->getHeader() == Succ &&
1012                  "Should not create irreducible loops!");
1013           if (MachineLoop *P = DestLoop->getParentLoop())
1014             P->addBasicBlockToLoop(NMBB, MLI->getBase());
1015         }
1016       }
1017     }
1018 
1019   return NMBB;
1020 }
1021 
1022 bool MachineBasicBlock::canSplitCriticalEdge(
1023     const MachineBasicBlock *Succ) const {
1024   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1025   // it in this generic function.
1026   if (Succ->isEHPad())
1027     return false;
1028 
1029   const MachineFunction *MF = getParent();
1030 
1031   // Performance might be harmed on HW that implements branching using exec mask
1032   // where both sides of the branches are always executed.
1033   if (MF->getTarget().requiresStructuredCFG())
1034     return false;
1035 
1036   // We may need to update this's terminator, but we can't do that if
1037   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
1038   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1039   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1040   SmallVector<MachineOperand, 4> Cond;
1041   // AnalyzeBanch should modify this, since we did not allow modification.
1042   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1043                          /*AllowModify*/ false))
1044     return false;
1045 
1046   // Avoid bugpoint weirdness: A block may end with a conditional branch but
1047   // jumps to the same MBB is either case. We have duplicate CFG edges in that
1048   // case that we can't handle. Since this never happens in properly optimized
1049   // code, just skip those edges.
1050   if (TBB && TBB == FBB) {
1051     DEBUG(dbgs() << "Won't split critical edge after degenerate "
1052                  << printMBBReference(*this) << '\n');
1053     return false;
1054   }
1055   return true;
1056 }
1057 
1058 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1059 /// neighboring instructions so the bundle won't be broken by removing MI.
1060 static void unbundleSingleMI(MachineInstr *MI) {
1061   // Removing the first instruction in a bundle.
1062   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1063     MI->unbundleFromSucc();
1064   // Removing the last instruction in a bundle.
1065   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1066     MI->unbundleFromPred();
1067   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1068   // are already fine.
1069 }
1070 
1071 MachineBasicBlock::instr_iterator
1072 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1073   unbundleSingleMI(&*I);
1074   return Insts.erase(I);
1075 }
1076 
1077 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1078   unbundleSingleMI(MI);
1079   MI->clearFlag(MachineInstr::BundledPred);
1080   MI->clearFlag(MachineInstr::BundledSucc);
1081   return Insts.remove(MI);
1082 }
1083 
1084 MachineBasicBlock::instr_iterator
1085 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1086   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1087          "Cannot insert instruction with bundle flags");
1088   // Set the bundle flags when inserting inside a bundle.
1089   if (I != instr_end() && I->isBundledWithPred()) {
1090     MI->setFlag(MachineInstr::BundledPred);
1091     MI->setFlag(MachineInstr::BundledSucc);
1092   }
1093   return Insts.insert(I, MI);
1094 }
1095 
1096 /// This method unlinks 'this' from the containing function, and returns it, but
1097 /// does not delete it.
1098 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1099   assert(getParent() && "Not embedded in a function!");
1100   getParent()->remove(this);
1101   return this;
1102 }
1103 
1104 /// This method unlinks 'this' from the containing function, and deletes it.
1105 void MachineBasicBlock::eraseFromParent() {
1106   assert(getParent() && "Not embedded in a function!");
1107   getParent()->erase(this);
1108 }
1109 
1110 /// Given a machine basic block that branched to 'Old', change the code and CFG
1111 /// so that it branches to 'New' instead.
1112 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1113                                                MachineBasicBlock *New) {
1114   assert(Old != New && "Cannot replace self with self!");
1115 
1116   MachineBasicBlock::instr_iterator I = instr_end();
1117   while (I != instr_begin()) {
1118     --I;
1119     if (!I->isTerminator()) break;
1120 
1121     // Scan the operands of this machine instruction, replacing any uses of Old
1122     // with New.
1123     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1124       if (I->getOperand(i).isMBB() &&
1125           I->getOperand(i).getMBB() == Old)
1126         I->getOperand(i).setMBB(New);
1127   }
1128 
1129   // Update the successor information.
1130   replaceSuccessor(Old, New);
1131 }
1132 
1133 /// Various pieces of code can cause excess edges in the CFG to be inserted.  If
1134 /// we have proven that MBB can only branch to DestA and DestB, remove any other
1135 /// MBB successors from the CFG.  DestA and DestB can be null.
1136 ///
1137 /// Besides DestA and DestB, retain other edges leading to LandingPads
1138 /// (currently there can be only one; we don't check or require that here).
1139 /// Note it is possible that DestA and/or DestB are LandingPads.
1140 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1141                                              MachineBasicBlock *DestB,
1142                                              bool IsCond) {
1143   // The values of DestA and DestB frequently come from a call to the
1144   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1145   // values from there.
1146   //
1147   // 1. If both DestA and DestB are null, then the block ends with no branches
1148   //    (it falls through to its successor).
1149   // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
1150   //    with only an unconditional branch.
1151   // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
1152   //    with a conditional branch that falls through to a successor (DestB).
1153   // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
1154   //    conditional branch followed by an unconditional branch. DestA is the
1155   //    'true' destination and DestB is the 'false' destination.
1156 
1157   bool Changed = false;
1158 
1159   MachineBasicBlock *FallThru = getNextNode();
1160 
1161   if (!DestA && !DestB) {
1162     // Block falls through to successor.
1163     DestA = FallThru;
1164     DestB = FallThru;
1165   } else if (DestA && !DestB) {
1166     if (IsCond)
1167       // Block ends in conditional jump that falls through to successor.
1168       DestB = FallThru;
1169   } else {
1170     assert(DestA && DestB && IsCond &&
1171            "CFG in a bad state. Cannot correct CFG edges");
1172   }
1173 
1174   // Remove superfluous edges. I.e., those which aren't destinations of this
1175   // basic block, duplicate edges, or landing pads.
1176   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1177   MachineBasicBlock::succ_iterator SI = succ_begin();
1178   while (SI != succ_end()) {
1179     const MachineBasicBlock *MBB = *SI;
1180     if (!SeenMBBs.insert(MBB).second ||
1181         (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
1182       // This is a superfluous edge, remove it.
1183       SI = removeSuccessor(SI);
1184       Changed = true;
1185     } else {
1186       ++SI;
1187     }
1188   }
1189 
1190   if (Changed)
1191     normalizeSuccProbs();
1192   return Changed;
1193 }
1194 
1195 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1196 /// instructions.  Return UnknownLoc if there is none.
1197 DebugLoc
1198 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1199   // Skip debug declarations, we don't want a DebugLoc from them.
1200   MBBI = skipDebugInstructionsForward(MBBI, instr_end());
1201   if (MBBI != instr_end())
1202     return MBBI->getDebugLoc();
1203   return {};
1204 }
1205 
1206 /// Find and return the merged DebugLoc of the branch instructions of the block.
1207 /// Return UnknownLoc if there is none.
1208 DebugLoc
1209 MachineBasicBlock::findBranchDebugLoc() {
1210   DebugLoc DL;
1211   auto TI = getFirstTerminator();
1212   while (TI != end() && !TI->isBranch())
1213     ++TI;
1214 
1215   if (TI != end()) {
1216     DL = TI->getDebugLoc();
1217     for (++TI ; TI != end() ; ++TI)
1218       if (TI->isBranch())
1219         DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
1220   }
1221   return DL;
1222 }
1223 
1224 /// Return probability of the edge from this block to MBB.
1225 BranchProbability
1226 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1227   if (Probs.empty())
1228     return BranchProbability(1, succ_size());
1229 
1230   const auto &Prob = *getProbabilityIterator(Succ);
1231   if (Prob.isUnknown()) {
1232     // For unknown probabilities, collect the sum of all known ones, and evenly
1233     // ditribute the complemental of the sum to each unknown probability.
1234     unsigned KnownProbNum = 0;
1235     auto Sum = BranchProbability::getZero();
1236     for (auto &P : Probs) {
1237       if (!P.isUnknown()) {
1238         Sum += P;
1239         KnownProbNum++;
1240       }
1241     }
1242     return Sum.getCompl() / (Probs.size() - KnownProbNum);
1243   } else
1244     return Prob;
1245 }
1246 
1247 /// Set successor probability of a given iterator.
1248 void MachineBasicBlock::setSuccProbability(succ_iterator I,
1249                                            BranchProbability Prob) {
1250   assert(!Prob.isUnknown());
1251   if (Probs.empty())
1252     return;
1253   *getProbabilityIterator(I) = Prob;
1254 }
1255 
1256 /// Return probability iterator corresonding to the I successor iterator
1257 MachineBasicBlock::const_probability_iterator
1258 MachineBasicBlock::getProbabilityIterator(
1259     MachineBasicBlock::const_succ_iterator I) const {
1260   assert(Probs.size() == Successors.size() && "Async probability list!");
1261   const size_t index = std::distance(Successors.begin(), I);
1262   assert(index < Probs.size() && "Not a current successor!");
1263   return Probs.begin() + index;
1264 }
1265 
1266 /// Return probability iterator corresonding to the I successor iterator.
1267 MachineBasicBlock::probability_iterator
1268 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1269   assert(Probs.size() == Successors.size() && "Async probability list!");
1270   const size_t index = std::distance(Successors.begin(), I);
1271   assert(index < Probs.size() && "Not a current successor!");
1272   return Probs.begin() + index;
1273 }
1274 
1275 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1276 /// as of just before "MI".
1277 ///
1278 /// Search is localised to a neighborhood of
1279 /// Neighborhood instructions before (searching for defs or kills) and N
1280 /// instructions after (searching just for defs) MI.
1281 MachineBasicBlock::LivenessQueryResult
1282 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1283                                            unsigned Reg, const_iterator Before,
1284                                            unsigned Neighborhood) const {
1285   unsigned N = Neighborhood;
1286 
1287   // Start by searching backwards from Before, looking for kills, reads or defs.
1288   const_iterator I(Before);
1289   // If this is the first insn in the block, don't search backwards.
1290   if (I != begin()) {
1291     do {
1292       --I;
1293 
1294       MachineOperandIteratorBase::PhysRegInfo Info =
1295           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
1296 
1297       // Defs happen after uses so they take precedence if both are present.
1298 
1299       // Register is dead after a dead def of the full register.
1300       if (Info.DeadDef)
1301         return LQR_Dead;
1302       // Register is (at least partially) live after a def.
1303       if (Info.Defined) {
1304         if (!Info.PartialDeadDef)
1305           return LQR_Live;
1306         // As soon as we saw a partial definition (dead or not),
1307         // we cannot tell if the value is partial live without
1308         // tracking the lanemasks. We are not going to do this,
1309         // so fall back on the remaining of the analysis.
1310         break;
1311       }
1312       // Register is dead after a full kill or clobber and no def.
1313       if (Info.Killed || Info.Clobbered)
1314         return LQR_Dead;
1315       // Register must be live if we read it.
1316       if (Info.Read)
1317         return LQR_Live;
1318     } while (I != begin() && --N > 0);
1319   }
1320 
1321   // Did we get to the start of the block?
1322   if (I == begin()) {
1323     // If so, the register's state is definitely defined by the live-in state.
1324     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); RAI.isValid();
1325          ++RAI)
1326       if (isLiveIn(*RAI))
1327         return LQR_Live;
1328 
1329     return LQR_Dead;
1330   }
1331 
1332   N = Neighborhood;
1333 
1334   // Try searching forwards from Before, looking for reads or defs.
1335   I = const_iterator(Before);
1336   // If this is the last insn in the block, don't search forwards.
1337   if (I != end()) {
1338     for (++I; I != end() && N > 0; ++I, --N) {
1339       MachineOperandIteratorBase::PhysRegInfo Info =
1340           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
1341 
1342       // Register is live when we read it here.
1343       if (Info.Read)
1344         return LQR_Live;
1345       // Register is dead if we can fully overwrite or clobber it here.
1346       if (Info.FullyDefined || Info.Clobbered)
1347         return LQR_Dead;
1348     }
1349   }
1350 
1351   // At this point we have no idea of the liveness of the register.
1352   return LQR_Unknown;
1353 }
1354 
1355 const uint32_t *
1356 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1357   // EH funclet entry does not preserve any registers.
1358   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1359 }
1360 
1361 const uint32_t *
1362 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1363   // If we see a return block with successors, this must be a funclet return,
1364   // which does not preserve any registers. If there are no successors, we don't
1365   // care what kind of return it is, putting a mask after it is a no-op.
1366   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1367 }
1368 
1369 void MachineBasicBlock::clearLiveIns() {
1370   LiveIns.clear();
1371 }
1372 
1373 MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
1374   assert(getParent()->getProperties().hasProperty(
1375       MachineFunctionProperties::Property::TracksLiveness) &&
1376       "Liveness information is accurate");
1377   return LiveIns.begin();
1378 }
1379