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