1//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Collect the sequence of machine instructions for a basic block.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/MachineBasicBlock.h"
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/StringExtras.h"
16#include "llvm/CodeGen/LiveIntervals.h"
17#include "llvm/CodeGen/LivePhysRegs.h"
18#include "llvm/CodeGen/LiveVariables.h"
19#include "llvm/CodeGen/MachineDomTreeUpdater.h"
20#include "llvm/CodeGen/MachineDominators.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineJumpTableInfo.h"
24#include "llvm/CodeGen/MachineLoopInfo.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/SlotIndexes.h"
27#include "llvm/CodeGen/TargetInstrInfo.h"
28#include "llvm/CodeGen/TargetLowering.h"
29#include "llvm/CodeGen/TargetRegisterInfo.h"
30#include "llvm/CodeGen/TargetSubtargetInfo.h"
31#include "llvm/Config/llvm-config.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/IRPrintingPasses.h"
34#include "llvm/IR/ModuleSlotTracker.h"
35#include "llvm/MC/MCAsmInfo.h"
36#include "llvm/MC/MCContext.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Target/TargetMachine.h"
40#include <algorithm>
41#include <cmath>
42using namespace llvm;
43
44#define DEBUG_TYPE "codegen"
45
46static cl::opt<bool> PrintSlotIndexes(
47 "print-slotindexes",
48 cl::desc("When printing machine IR, annotate instructions and blocks with "
49 "SlotIndexes when available"),
50 cl::init(Val: true), cl::Hidden);
51
52MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
53 : BB(B), Number(-1), xParent(&MF) {
54 Insts.Parent = this;
55 if (B)
56 IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
57}
58
59MachineBasicBlock::~MachineBasicBlock() = default;
60
61/// Return the MCSymbol for this basic block.
62MCSymbol *MachineBasicBlock::getSymbol() const {
63 if (!CachedMCSymbol) {
64 const MachineFunction *MF = getParent();
65 MCContext &Ctx = MF->getContext();
66
67 // We emit a non-temporary symbol -- with a descriptive name -- if it begins
68 // a section (with basic block sections). Otherwise we fall back to use temp
69 // label.
70 if (MF->hasBBSections() && isBeginSection()) {
71 SmallString<5> Suffix;
72 if (SectionID == MBBSectionID::ColdSectionID) {
73 Suffix += ".cold";
74 } else if (SectionID == MBBSectionID::ExceptionSectionID) {
75 Suffix += ".eh";
76 } else {
77 // For symbols that represent basic block sections, we add ".__part." to
78 // allow tools like symbolizers to know that this represents a part of
79 // the original function.
80 Suffix = (Suffix + Twine(".__part.") + Twine(SectionID.Number)).str();
81 }
82 CachedMCSymbol = Ctx.getOrCreateSymbol(Name: MF->getName() + Suffix);
83 } else {
84 // If the block occurs as label in inline assembly, parsing the assembly
85 // needs an actual label name => set AlwaysEmit in these cases.
86 CachedMCSymbol = Ctx.createBlockSymbol(
87 Name: "BB" + Twine(MF->getFunctionNumber()) + "_" + Twine(getNumber()),
88 /*AlwaysEmit=*/hasLabelMustBeEmitted());
89 }
90 }
91 return CachedMCSymbol;
92}
93
94MCSymbol *MachineBasicBlock::getEHContSymbol() const {
95 if (!CachedEHContMCSymbol) {
96 const MachineFunction *MF = getParent();
97 SmallString<128> SymbolName;
98 raw_svector_ostream(SymbolName)
99 << "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber();
100 CachedEHContMCSymbol = MF->getContext().getOrCreateSymbol(Name: SymbolName);
101 }
102 return CachedEHContMCSymbol;
103}
104
105MCSymbol *MachineBasicBlock::getEndSymbol() const {
106 if (!CachedEndMCSymbol) {
107 const MachineFunction *MF = getParent();
108 MCContext &Ctx = MF->getContext();
109 CachedEndMCSymbol = Ctx.createBlockSymbol(
110 Name: "BB_END" + Twine(MF->getFunctionNumber()) + "_" + Twine(getNumber()),
111 /*AlwaysEmit=*/false);
112 }
113 return CachedEndMCSymbol;
114}
115
116raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
117 MBB.print(OS);
118 return OS;
119}
120
121Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
122 return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
123}
124
125/// When an MBB is added to an MF, we need to update the parent pointer of the
126/// MBB, the MBB numbering, and any instructions in the MBB to be on the right
127/// operand list for registers.
128///
129/// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
130/// gets the next available unique MBB number. If it is removed from a
131/// MachineFunction, it goes back to being #-1.
132void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
133 MachineBasicBlock *N) {
134 MachineFunction &MF = *N->getParent();
135 N->Number = MF.addToMBBNumbering(MBB: N);
136 N->AnalysisNumber = MF.assignAnalysisNumber();
137
138 // Make sure the instructions have their operands in the reginfo lists.
139 MachineRegisterInfo &RegInfo = MF.getRegInfo();
140 for (MachineInstr &MI : N->instrs())
141 MI.addRegOperandsToUseLists(RegInfo);
142}
143
144void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
145 MachineBasicBlock *N) {
146 N->getParent()->removeFromMBBNumbering(N: N->Number);
147 N->Number = -1;
148 N->AnalysisNumber = -1;
149}
150
151/// When we add an instruction to a basic block list, we update its parent
152/// pointer and add its operands from reg use/def lists if appropriate.
153void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
154 assert(!N->getParent() && "machine instruction already in a basic block");
155 N->setParent(Parent);
156
157 // Add the instruction's register operands to their corresponding
158 // use/def lists.
159 MachineFunction *MF = Parent->getParent();
160 N->addRegOperandsToUseLists(MF->getRegInfo());
161 MF->handleInsertion(MI&: *N);
162}
163
164/// When we remove an instruction from a basic block list, we update its parent
165/// pointer and remove its operands from reg use/def lists if appropriate.
166void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
167 assert(N->getParent() && "machine instruction not in a basic block");
168
169 // Remove from the use/def lists.
170 if (MachineFunction *MF = N->getMF()) {
171 MF->handleRemoval(MI&: *N);
172 N->removeRegOperandsFromUseLists(MF->getRegInfo());
173 }
174
175 N->setParent(nullptr);
176}
177
178/// When moving a range of instructions from one MBB list to another, we need to
179/// update the parent pointers and the use/def lists.
180void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
181 instr_iterator First,
182 instr_iterator Last) {
183 assert(Parent->getParent() == FromList.Parent->getParent() &&
184 "cannot transfer MachineInstrs between MachineFunctions");
185
186 // If it's within the same BB, there's nothing to do.
187 if (this == &FromList)
188 return;
189
190 assert(Parent != FromList.Parent && "Two lists have the same parent?");
191
192 // If splicing between two blocks within the same function, just update the
193 // parent pointers.
194 for (; First != Last; ++First)
195 First->setParent(Parent);
196}
197
198void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
199 assert(!MI->getParent() && "MI is still in a block!");
200 Parent->getParent()->deleteMachineInstr(MI);
201}
202
203MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
204 instr_iterator I = instr_begin(), E = instr_end();
205 while (I != E && I->isPHI())
206 ++I;
207 assert((I == E || !I->isInsideBundle()) &&
208 "First non-phi MI cannot be inside a bundle!");
209 return I;
210}
211
212MachineBasicBlock::iterator
213MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
214 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
215
216 iterator E = end();
217 while (I != E && (I->isPHI() || I->isPosition() ||
218 TII->isBasicBlockPrologue(MI: *I)))
219 ++I;
220 // FIXME: This needs to change if we wish to bundle labels
221 // inside the bundle.
222 assert((I == E || !I->isInsideBundle()) &&
223 "First non-phi / non-label instruction is inside a bundle!");
224 return I;
225}
226
227MachineBasicBlock::iterator
228MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I,
229 Register Reg, bool SkipPseudoOp) {
230 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
231
232 iterator E = end();
233 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
234 (SkipPseudoOp && I->isPseudoProbe()) ||
235 TII->isBasicBlockPrologue(MI: *I, Reg)))
236 ++I;
237 // FIXME: This needs to change if we wish to bundle labels / dbg_values
238 // inside the bundle.
239 assert((I == E || !I->isInsideBundle()) &&
240 "First non-phi / non-label / non-debug "
241 "instruction is inside a bundle!");
242 return I;
243}
244
245MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
246 iterator B = begin(), E = end(), I = E;
247 while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
248 ; /*noop */
249 while (I != E && !I->isTerminator())
250 ++I;
251 return I;
252}
253
254MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
255 instr_iterator B = instr_begin(), E = instr_end(), I = E;
256 while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
257 ; /*noop */
258 while (I != E && !I->isTerminator())
259 ++I;
260 return I;
261}
262
263MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminatorForward() {
264 return find_if(Range: instrs(), P: [](auto &II) { return II.isTerminator(); });
265}
266
267MachineBasicBlock::iterator
268MachineBasicBlock::getFirstNonDebugInstr(bool SkipPseudoOp) {
269 // Skip over begin-of-block dbg_value instructions.
270 return skipDebugInstructionsForward(It: begin(), End: end(), SkipPseudoOp);
271}
272
273MachineBasicBlock::iterator
274MachineBasicBlock::getLastNonDebugInstr(bool SkipPseudoOp) {
275 // Skip over end-of-block dbg_value instructions.
276 instr_iterator B = instr_begin(), I = instr_end();
277 while (I != B) {
278 --I;
279 // Return instruction that starts a bundle.
280 if (I->isDebugInstr() || I->isInsideBundle())
281 continue;
282 if (SkipPseudoOp && I->isPseudoProbe())
283 continue;
284 return I;
285 }
286 // The block is all debug values.
287 return end();
288}
289
290bool MachineBasicBlock::hasEHPadSuccessor() const {
291 for (const MachineBasicBlock *Succ : successors())
292 if (Succ->isEHPad())
293 return true;
294 return false;
295}
296
297bool MachineBasicBlock::isEntryBlock() const {
298 return getParent()->begin() == getIterator();
299}
300
301#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
302LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
303 print(dbgs());
304}
305#endif
306
307bool MachineBasicBlock::mayHaveInlineAsmBr() const {
308 for (const MachineBasicBlock *Succ : successors()) {
309 if (Succ->isInlineAsmBrIndirectTarget())
310 return true;
311 }
312 return false;
313}
314
315bool MachineBasicBlock::isLegalToHoistInto() const {
316 if (isReturnBlock() || hasEHPadSuccessor() || mayHaveInlineAsmBr())
317 return false;
318 return true;
319}
320
321bool MachineBasicBlock::hasName() const {
322 if (const BasicBlock *LBB = getBasicBlock())
323 return LBB->hasName();
324 return false;
325}
326
327StringRef MachineBasicBlock::getName() const {
328 if (const BasicBlock *LBB = getBasicBlock())
329 return LBB->getName();
330 else
331 return StringRef("", 0);
332}
333
334/// Return a hopefully unique identifier for this block.
335std::string MachineBasicBlock::getFullName() const {
336 std::string Name;
337 if (getParent())
338 Name = (getParent()->getName() + ":").str();
339 if (getBasicBlock())
340 Name += getBasicBlock()->getName();
341 else
342 Name += ("BB" + Twine(getNumber())).str();
343 return Name;
344}
345
346void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
347 bool IsStandalone) const {
348 const MachineFunction *MF = getParent();
349 if (!MF) {
350 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
351 << " is null\n";
352 return;
353 }
354 const Function &F = MF->getFunction();
355 const Module *M = F.getParent();
356 ModuleSlotTracker MST(M);
357 MST.incorporateFunction(F);
358 print(OS, MST, Indexes, IsStandalone);
359}
360
361void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
362 const SlotIndexes *Indexes,
363 bool IsStandalone) const {
364 const MachineFunction *MF = getParent();
365 if (!MF) {
366 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
367 << " is null\n";
368 return;
369 }
370
371 if (Indexes && PrintSlotIndexes)
372 OS << Indexes->getMBBStartIdx(mbb: this) << '\t';
373
374 printName(os&: OS, printNameFlags: PrintNameIr | PrintNameAttributes, moduleSlotTracker: &MST);
375 OS << ":\n";
376
377 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
378 const MachineRegisterInfo &MRI = MF->getRegInfo();
379 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
380 bool HasLineAttributes = false;
381
382 // Print the preds of this block according to the CFG.
383 if (!pred_empty() && IsStandalone) {
384 if (Indexes) OS << '\t';
385 // Don't indent(2), align with previous line attributes.
386 OS << "; predecessors: ";
387 ListSeparator LS;
388 for (auto *Pred : predecessors())
389 OS << LS << printMBBReference(MBB: *Pred);
390 OS << '\n';
391 HasLineAttributes = true;
392 }
393
394 if (!succ_empty()) {
395 if (Indexes) OS << '\t';
396 // Print the successors
397 OS.indent(NumSpaces: 2) << "successors: ";
398 ListSeparator LS;
399 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
400 OS << LS << printMBBReference(MBB: **I);
401 if (!Probs.empty())
402 OS << '('
403 << format(Fmt: "0x%08" PRIx32, Vals: getSuccProbability(Succ: I).getNumerator())
404 << ')';
405 }
406 if (!Probs.empty() && IsStandalone) {
407 // Print human readable probabilities as comments.
408 OS << "; ";
409 ListSeparator LS;
410 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
411 const BranchProbability &BP = getSuccProbability(Succ: I);
412 OS << LS << printMBBReference(MBB: **I) << '('
413 << format(Fmt: "%.2f%%",
414 Vals: rint(x: ((double)BP.getNumerator() / BP.getDenominator()) *
415 100.0 * 100.0) /
416 100.0)
417 << ')';
418 }
419 }
420
421 OS << '\n';
422 HasLineAttributes = true;
423 }
424
425 if (!livein_empty() && MRI.tracksLiveness()) {
426 if (Indexes) OS << '\t';
427 OS.indent(NumSpaces: 2) << "liveins: ";
428
429 ListSeparator LS;
430 for (const auto &LI : liveins()) {
431 OS << LS << printReg(Reg: LI.PhysReg, TRI);
432 if (!LI.LaneMask.all())
433 OS << ":0x" << PrintLaneMask(LaneMask: LI.LaneMask);
434 }
435 HasLineAttributes = true;
436 }
437
438 if (HasLineAttributes)
439 OS << '\n';
440
441 bool IsInBundle = false;
442 for (const MachineInstr &MI : instrs()) {
443 if (Indexes && PrintSlotIndexes) {
444 if (Indexes->hasIndex(instr: MI))
445 OS << Indexes->getInstructionIndex(MI);
446 OS << '\t';
447 }
448
449 if (IsInBundle && !MI.isInsideBundle()) {
450 OS.indent(NumSpaces: 2) << "}\n";
451 IsInBundle = false;
452 }
453
454 OS.indent(NumSpaces: IsInBundle ? 4 : 2);
455 MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
456 /*AddNewLine=*/false, TII: &TII);
457
458 if (!IsInBundle && MI.getFlag(Flag: MachineInstr::BundledSucc)) {
459 OS << " {";
460 IsInBundle = true;
461 }
462 OS << '\n';
463 }
464
465 if (IsInBundle)
466 OS.indent(NumSpaces: 2) << "}\n";
467
468 if (IrrLoopHeaderWeight && IsStandalone) {
469 if (Indexes) OS << '\t';
470 OS.indent(NumSpaces: 2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight
471 << '\n';
472 }
473}
474
475/// Print the basic block's name as:
476///
477/// bb.{number}[.{ir-name}] [(attributes...)]
478///
479/// The {ir-name} is only printed when the \ref PrintNameIr flag is passed
480/// (which is the default). If the IR block has no name, it is identified
481/// numerically using the attribute syntax as "(%ir-block.{ir-slot})".
482///
483/// When the \ref PrintNameAttributes flag is passed, additional attributes
484/// of the block are printed when set.
485///
486/// \param printNameFlags Combination of \ref PrintNameFlag flags indicating
487/// the parts to print.
488/// \param moduleSlotTracker Optional ModuleSlotTracker. This method will
489/// incorporate its own tracker when necessary to
490/// determine the block's IR name.
491void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags,
492 ModuleSlotTracker *moduleSlotTracker) const {
493 os << "bb." << getNumber();
494 bool hasAttributes = false;
495
496 auto PrintBBRef = [&](const BasicBlock *bb) {
497 os << "%ir-block.";
498 if (bb->hasName()) {
499 printLLVMNameWithoutPrefix(OS&: os, Name: bb->getName());
500 } else {
501 int slot = -1;
502
503 if (moduleSlotTracker) {
504 slot = moduleSlotTracker->getLocalSlot(V: bb);
505 } else if (bb->getParent()) {
506 ModuleSlotTracker tmpTracker(bb->getModule(), false);
507 tmpTracker.incorporateFunction(F: *bb->getParent());
508 slot = tmpTracker.getLocalSlot(V: bb);
509 }
510
511 if (slot == -1)
512 os << "<ir-block badref>";
513 else
514 os << slot;
515 }
516 };
517
518 if (printNameFlags & PrintNameIr) {
519 if (const auto *bb = getBasicBlock()) {
520 if (bb->hasName()) {
521 // Quote if not a plain identifier, or the MIR cannot be parsed back.
522 os << '.';
523 printLLVMNameWithoutPrefix(OS&: os, Name: bb->getName());
524 } else {
525 hasAttributes = true;
526 os << " (";
527 PrintBBRef(bb);
528 }
529 }
530 }
531
532 if (printNameFlags & PrintNameAttributes) {
533 if (isMachineBlockAddressTaken()) {
534 os << (hasAttributes ? ", " : " (");
535 os << "machine-block-address-taken";
536 hasAttributes = true;
537 }
538 if (isIRBlockAddressTaken()) {
539 os << (hasAttributes ? ", " : " (");
540 os << "ir-block-address-taken ";
541 PrintBBRef(getAddressTakenIRBlock());
542 hasAttributes = true;
543 }
544 if (isEHPad()) {
545 os << (hasAttributes ? ", " : " (");
546 os << "landing-pad";
547 hasAttributes = true;
548 }
549 if (isInlineAsmBrIndirectTarget()) {
550 os << (hasAttributes ? ", " : " (");
551 os << "inlineasm-br-indirect-target";
552 hasAttributes = true;
553 }
554 if (isEHFuncletEntry()) {
555 os << (hasAttributes ? ", " : " (");
556 os << "ehfunclet-entry";
557 hasAttributes = true;
558 }
559 if (isEHScopeEntry()) {
560 os << (hasAttributes ? ", " : " (");
561 os << "ehscope-entry";
562 hasAttributes = true;
563 }
564 if (getAlignment() != Align(1)) {
565 os << (hasAttributes ? ", " : " (");
566 os << "align " << getAlignment().value();
567 hasAttributes = true;
568 }
569 if (getSectionID() != MBBSectionID(0)) {
570 os << (hasAttributes ? ", " : " (");
571 os << "bbsections ";
572 switch (getSectionID().Type) {
573 case MBBSectionID::SectionType::Exception:
574 os << "Exception";
575 break;
576 case MBBSectionID::SectionType::Cold:
577 os << "Cold";
578 break;
579 default:
580 os << getSectionID().Number;
581 }
582 hasAttributes = true;
583 }
584 if (getBBID().has_value()) {
585 os << (hasAttributes ? ", " : " (");
586 os << "bb_id " << getBBID()->BaseID;
587 if (getBBID()->CloneID != 0)
588 os << " " << getBBID()->CloneID;
589 hasAttributes = true;
590 }
591 if (CallFrameSize != 0) {
592 os << (hasAttributes ? ", " : " (");
593 os << "call-frame-size " << CallFrameSize;
594 hasAttributes = true;
595 }
596 }
597
598 if (hasAttributes)
599 os << ')';
600}
601
602void MachineBasicBlock::printAsOperand(raw_ostream &OS,
603 bool /*PrintType*/) const {
604 OS << '%';
605 printName(os&: OS, printNameFlags: 0);
606}
607
608void MachineBasicBlock::removeLiveIn(MCRegister Reg, LaneBitmask LaneMask) {
609 assert(Reg.isPhysical());
610 LiveInVector::iterator I = find_if(
611 Range&: LiveIns, P: [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
612 if (I == LiveIns.end())
613 return;
614
615 I->LaneMask &= ~LaneMask;
616 if (I->LaneMask.none())
617 LiveIns.erase(position: I);
618}
619
620void MachineBasicBlock::removeLiveInOverlappedWith(MCRegister Reg) {
621 const MachineFunction *MF = getParent();
622 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
623 // Remove Reg and its subregs from live in set.
624 for (MCPhysReg S : TRI->subregs_inclusive(Reg))
625 removeLiveIn(Reg: S);
626
627 // Remove live-in bitmask in super registers as well.
628 for (MCPhysReg Super : TRI->superregs(Reg)) {
629 for (MCSubRegIndexIterator SRI(Super, TRI); SRI.isValid(); ++SRI) {
630 if (Reg == SRI.getSubReg()) {
631 unsigned SubRegIndex = SRI.getSubRegIndex();
632 LaneBitmask SubRegLaneMask = TRI->getSubRegIndexLaneMask(SubIdx: SubRegIndex);
633 removeLiveIn(Reg: Super, LaneMask: SubRegLaneMask);
634 break;
635 }
636 }
637 }
638}
639
640MachineBasicBlock::livein_iterator
641MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
642 // Get non-const version of iterator.
643 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
644 return LiveIns.erase(position: LI);
645}
646
647bool MachineBasicBlock::isLiveIn(MCRegister Reg, LaneBitmask LaneMask) const {
648 assert(Reg.isPhysical());
649 livein_iterator I = find_if(
650 Range: LiveIns, P: [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
651 return I != livein_end() && (I->LaneMask & LaneMask).any();
652}
653
654void MachineBasicBlock::sortUniqueLiveIns() {
655 llvm::sort(C&: LiveIns,
656 Comp: [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
657 return LI0.PhysReg < LI1.PhysReg;
658 });
659 // Liveins are sorted by physreg now we can merge their lanemasks.
660 LiveInVector::const_iterator I = LiveIns.begin();
661 LiveInVector::const_iterator J;
662 LiveInVector::iterator Out = LiveIns.begin();
663 for (; I != LiveIns.end(); ++Out, I = J) {
664 MCRegister PhysReg = I->PhysReg;
665 LaneBitmask LaneMask = I->LaneMask;
666 for (J = std::next(x: I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
667 LaneMask |= J->LaneMask;
668 Out->PhysReg = PhysReg;
669 Out->LaneMask = LaneMask;
670 }
671 LiveIns.erase(first: Out, last: LiveIns.end());
672}
673
674Register
675MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
676 assert(getParent() && "MBB must be inserted in function");
677 assert(PhysReg.isPhysical() && "Expected physreg");
678 assert(RC && "Register class is required");
679 assert((isEHPad() || this == &getParent()->front()) &&
680 "Only the entry block and landing pads can have physreg live ins");
681
682 bool LiveIn = isLiveIn(Reg: PhysReg);
683 iterator I = SkipPHIsAndLabels(I: begin()), E = end();
684 MachineRegisterInfo &MRI = getParent()->getRegInfo();
685 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
686
687 // Look for an existing copy.
688 if (LiveIn)
689 for (;I != E && I->isCopy(); ++I)
690 if (I->getOperand(i: 1).getReg() == PhysReg) {
691 Register VirtReg = I->getOperand(i: 0).getReg();
692 if (!MRI.constrainRegClass(Reg: VirtReg, RC))
693 llvm_unreachable("Incompatible live-in register class.");
694 return VirtReg;
695 }
696
697 // No luck, create a virtual register.
698 Register VirtReg = MRI.createVirtualRegister(RegClass: RC);
699 BuildMI(BB&: *this, I, MIMD: DebugLoc(), MCID: TII.get(Opcode: TargetOpcode::COPY), DestReg: VirtReg)
700 .addReg(RegNo: PhysReg, Flags: RegState::Kill);
701 if (!LiveIn)
702 addLiveIn(PhysReg);
703 return VirtReg;
704}
705
706void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
707 getParent()->splice(InsertPt: NewAfter->getIterator(), MBBI: getIterator());
708}
709
710void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
711 getParent()->splice(InsertPt: ++NewBefore->getIterator(), MBBI: getIterator());
712}
713
714static int findJumpTableIndex(const MachineBasicBlock &MBB) {
715 MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator();
716 if (TerminatorI == MBB.end())
717 return -1;
718 const MachineInstr &Terminator = *TerminatorI;
719 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
720 return TII->getJumpTableIndex(MI: Terminator);
721}
722
723void MachineBasicBlock::updateTerminator(
724 MachineBasicBlock *PreviousLayoutSuccessor) {
725 LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
726 << "\n");
727
728 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
729 // A block with no successors has no concerns with fall-through edges.
730 if (this->succ_empty())
731 return;
732
733 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
734 SmallVector<MachineOperand, 4> Cond;
735 DebugLoc DL = findBranchDebugLoc();
736 bool B = TII->analyzeBranch(MBB&: *this, TBB, FBB, Cond);
737 (void) B;
738 assert(!B && "UpdateTerminators requires analyzable predecessors!");
739 if (Cond.empty()) {
740 if (TBB) {
741 // The block has an unconditional branch. If its successor is now its
742 // layout successor, delete the branch.
743 if (isLayoutSuccessor(MBB: TBB))
744 TII->removeBranch(MBB&: *this);
745 } else {
746 // The block has an unconditional fallthrough, or the end of the block is
747 // unreachable.
748
749 // Unfortunately, whether the end of the block is unreachable is not
750 // immediately obvious; we must fall back to checking the successor list,
751 // and assuming that if the passed in block is in the succesor list and
752 // not an EHPad, it must be the intended target.
753 if (!PreviousLayoutSuccessor || !isSuccessor(MBB: PreviousLayoutSuccessor) ||
754 PreviousLayoutSuccessor->isEHPad())
755 return;
756
757 // If the unconditional successor block is not the current layout
758 // successor, insert a branch to jump to it.
759 if (!isLayoutSuccessor(MBB: PreviousLayoutSuccessor))
760 TII->insertBranch(MBB&: *this, TBB: PreviousLayoutSuccessor, FBB: nullptr, Cond, DL);
761 }
762 return;
763 }
764
765 if (FBB) {
766 // The block has a non-fallthrough conditional branch. If one of its
767 // successors is its layout successor, rewrite it to a fallthrough
768 // conditional branch.
769 if (isLayoutSuccessor(MBB: TBB)) {
770 if (TII->reverseBranchCondition(Cond))
771 return;
772 TII->removeBranch(MBB&: *this);
773 TII->insertBranch(MBB&: *this, TBB: FBB, FBB: nullptr, Cond, DL);
774 } else if (isLayoutSuccessor(MBB: FBB)) {
775 TII->removeBranch(MBB&: *this);
776 TII->insertBranch(MBB&: *this, TBB, FBB: nullptr, Cond, DL);
777 }
778 return;
779 }
780
781 // We now know we're going to fallthrough to PreviousLayoutSuccessor.
782 assert(PreviousLayoutSuccessor);
783 assert(!PreviousLayoutSuccessor->isEHPad());
784 assert(isSuccessor(PreviousLayoutSuccessor));
785
786 if (PreviousLayoutSuccessor == TBB) {
787 // We had a fallthrough to the same basic block as the conditional jump
788 // targets. Remove the conditional jump, leaving an unconditional
789 // fallthrough or an unconditional jump.
790 TII->removeBranch(MBB&: *this);
791 if (!isLayoutSuccessor(MBB: TBB)) {
792 Cond.clear();
793 TII->insertBranch(MBB&: *this, TBB, FBB: nullptr, Cond, DL);
794 }
795 return;
796 }
797
798 // The block has a fallthrough conditional branch.
799 if (isLayoutSuccessor(MBB: TBB)) {
800 if (TII->reverseBranchCondition(Cond)) {
801 // We can't reverse the condition, add an unconditional branch.
802 Cond.clear();
803 TII->insertBranch(MBB&: *this, TBB: PreviousLayoutSuccessor, FBB: nullptr, Cond, DL);
804 return;
805 }
806 TII->removeBranch(MBB&: *this);
807 TII->insertBranch(MBB&: *this, TBB: PreviousLayoutSuccessor, FBB: nullptr, Cond, DL);
808 } else if (!isLayoutSuccessor(MBB: PreviousLayoutSuccessor)) {
809 TII->removeBranch(MBB&: *this);
810 TII->insertBranch(MBB&: *this, TBB, FBB: PreviousLayoutSuccessor, Cond, DL);
811 }
812}
813
814void MachineBasicBlock::validateSuccProbs() const {
815#ifndef NDEBUG
816 int64_t Sum = 0;
817 for (auto Prob : Probs)
818 Sum += Prob.getNumerator();
819 // Due to precision issue, we assume that the sum of probabilities is one if
820 // the difference between the sum of their numerators and the denominator is
821 // no greater than the number of successors.
822 assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
823 Probs.size() &&
824 "The sum of successors's probabilities exceeds one.");
825#endif // NDEBUG
826}
827
828void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
829 BranchProbability Prob) {
830 // Probability list is either empty (if successor list isn't empty, this means
831 // disabled optimization) or has the same size as successor list.
832 if (!(Probs.empty() && !Successors.empty()))
833 Probs.push_back(x: Prob);
834 Successors.push_back(Elt: Succ);
835 Succ->addPredecessor(Pred: this);
836}
837
838void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
839 // We need to make sure probability list is either empty or has the same size
840 // of successor list. When this function is called, we can safely delete all
841 // probability in the list.
842 Probs.clear();
843 Successors.push_back(Elt: Succ);
844 Succ->addPredecessor(Pred: this);
845}
846
847void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
848 MachineBasicBlock *New,
849 bool NormalizeSuccProbs) {
850 succ_iterator OldI = llvm::find(Range: successors(), Val: Old);
851 assert(OldI != succ_end() && "Old is not a successor of this block!");
852 assert(!llvm::is_contained(successors(), New) &&
853 "New is already a successor of this block!");
854
855 // Add a new successor with equal probability as the original one. Note
856 // that we directly copy the probability using the iterator rather than
857 // getting a potentially synthetic probability computed when unknown. This
858 // preserves the probabilities as-is and then we can renormalize them and
859 // query them effectively afterward.
860 addSuccessor(Succ: New, Prob: Probs.empty() ? BranchProbability::getUnknown()
861 : *getProbabilityIterator(I: OldI));
862 if (NormalizeSuccProbs)
863 normalizeSuccProbs();
864}
865
866void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
867 bool NormalizeSuccProbs) {
868 succ_iterator I = find(Range&: Successors, Val: Succ);
869 removeSuccessor(I, NormalizeSuccProbs);
870}
871
872MachineBasicBlock::succ_iterator
873MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
874 assert(I != Successors.end() && "Not a current successor!");
875
876 // If probability list is empty it means we don't use it (disabled
877 // optimization).
878 if (!Probs.empty()) {
879 probability_iterator WI = getProbabilityIterator(I);
880 Probs.erase(position: WI);
881 if (NormalizeSuccProbs)
882 normalizeSuccProbs();
883 }
884
885 (*I)->removePredecessor(Pred: this);
886 return Successors.erase(CI: I);
887}
888
889void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
890 MachineBasicBlock *New) {
891 if (Old == New)
892 return;
893
894 succ_iterator E = succ_end();
895 succ_iterator NewI = E;
896 succ_iterator OldI = E;
897 for (succ_iterator I = succ_begin(); I != E; ++I) {
898 if (*I == Old) {
899 OldI = I;
900 if (NewI != E)
901 break;
902 }
903 if (*I == New) {
904 NewI = I;
905 if (OldI != E)
906 break;
907 }
908 }
909 assert(OldI != E && "Old is not a successor of this block");
910
911 // If New isn't already a successor, let it take Old's place.
912 if (NewI == E) {
913 Old->removePredecessor(Pred: this);
914 New->addPredecessor(Pred: this);
915 *OldI = New;
916 return;
917 }
918
919 // New is already a successor.
920 // Update its probability instead of adding a duplicate edge.
921 if (!Probs.empty()) {
922 auto ProbIter = getProbabilityIterator(I: NewI);
923 if (!ProbIter->isUnknown())
924 *ProbIter += *getProbabilityIterator(I: OldI);
925 }
926 removeSuccessor(I: OldI);
927}
928
929void MachineBasicBlock::copySuccessor(const MachineBasicBlock *Orig,
930 succ_iterator I) {
931 if (!Orig->Probs.empty())
932 addSuccessor(Succ: *I, Prob: Orig->getSuccProbability(Succ: I));
933 else
934 addSuccessorWithoutProb(Succ: *I);
935}
936
937void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
938 Predecessors.push_back(Elt: Pred);
939}
940
941void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
942 // This is often called on many predecessors in reverse order.
943 // Do a reverse search and removal to avoid quadratic behavior in such cases.
944 auto RI = llvm::find(Range: reverse(C&: Predecessors), Val: Pred);
945 assert(RI != Predecessors.rend() &&
946 "Pred is not a predecessor of this block!");
947 Predecessors.erase(CI: std::prev(x: RI.base()));
948}
949
950void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
951 if (this == FromMBB)
952 return;
953
954 while (!FromMBB->succ_empty()) {
955 MachineBasicBlock *Succ = *FromMBB->succ_begin();
956
957 // If probability list is empty it means we don't use it (disabled
958 // optimization).
959 if (!FromMBB->Probs.empty()) {
960 auto Prob = *FromMBB->Probs.begin();
961 addSuccessor(Succ, Prob);
962 } else
963 addSuccessorWithoutProb(Succ);
964
965 FromMBB->removeSuccessor(Succ);
966 }
967}
968
969void
970MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
971 if (this == FromMBB)
972 return;
973
974 while (!FromMBB->succ_empty()) {
975 MachineBasicBlock *Succ = *FromMBB->succ_begin();
976 if (!FromMBB->Probs.empty()) {
977 auto Prob = *FromMBB->Probs.begin();
978 addSuccessor(Succ, Prob);
979 } else
980 addSuccessorWithoutProb(Succ);
981 FromMBB->removeSuccessor(Succ);
982
983 // Fix up any PHI nodes in the successor.
984 Succ->replacePhiUsesWith(Old: FromMBB, New: this);
985 }
986 normalizeSuccProbs();
987}
988
989bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
990 return is_contained(Range: predecessors(), Element: MBB);
991}
992
993bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
994 return is_contained(Range: successors(), Element: MBB);
995}
996
997bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
998 MachineFunction::const_iterator I(this);
999 return std::next(x: I) == MachineFunction::const_iterator(MBB);
1000}
1001
1002const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const {
1003 return Successors.size() == 1 ? Successors[0] : nullptr;
1004}
1005
1006const MachineBasicBlock *MachineBasicBlock::getSinglePredecessor() const {
1007 return Predecessors.size() == 1 ? Predecessors[0] : nullptr;
1008}
1009
1010MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) {
1011 MachineFunction::iterator Fallthrough = getIterator();
1012 ++Fallthrough;
1013 // If FallthroughBlock is off the end of the function, it can't fall through.
1014 if (Fallthrough == getParent()->end())
1015 return nullptr;
1016
1017 // If FallthroughBlock isn't a successor, no fallthrough is possible.
1018 if (!isSuccessor(MBB: &*Fallthrough))
1019 return nullptr;
1020
1021 // Analyze the branches, if any, at the end of the block.
1022 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1023 SmallVector<MachineOperand, 4> Cond;
1024 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
1025 if (TII->analyzeBranch(MBB&: *this, TBB, FBB, Cond)) {
1026 // If we couldn't analyze the branch, examine the last instruction.
1027 // If the block doesn't end in a known control barrier, assume fallthrough
1028 // is possible. The isPredicated check is needed because this code can be
1029 // called during IfConversion, where an instruction which is normally a
1030 // Barrier is predicated and thus no longer an actual control barrier.
1031 return (empty() || !back().isBarrier() || TII->isPredicated(MI: back()))
1032 ? &*Fallthrough
1033 : nullptr;
1034 }
1035
1036 // If there is no branch, control always falls through.
1037 if (!TBB) return &*Fallthrough;
1038
1039 // If there is some explicit branch to the fallthrough block, it can obviously
1040 // reach, even though the branch should get folded to fall through implicitly.
1041 if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
1042 MachineFunction::iterator(FBB) == Fallthrough))
1043 return &*Fallthrough;
1044
1045 // If it's an unconditional branch to some block not the fall through, it
1046 // doesn't fall through.
1047 if (Cond.empty()) return nullptr;
1048
1049 // Otherwise, if it is conditional and has no explicit false block, it falls
1050 // through.
1051 return (FBB == nullptr) ? &*Fallthrough : nullptr;
1052}
1053
1054bool MachineBasicBlock::canFallThrough() {
1055 return getFallThrough() != nullptr;
1056}
1057
1058MachineBasicBlock *MachineBasicBlock::splitAt(MachineInstr &MI,
1059 bool UpdateLiveIns,
1060 LiveIntervals *LIS) {
1061 MachineBasicBlock::iterator SplitPoint(&MI);
1062 ++SplitPoint;
1063
1064 if (SplitPoint == end()) {
1065 // Don't bother with a new block.
1066 return this;
1067 }
1068
1069 MachineFunction *MF = getParent();
1070
1071 LivePhysRegs LiveRegs;
1072 if (UpdateLiveIns) {
1073 // Make sure we add any physregs we define in the block as liveins to the
1074 // new block.
1075 MachineBasicBlock::iterator Prev(&MI);
1076 LiveRegs.init(TRI: *MF->getSubtarget().getRegisterInfo());
1077 LiveRegs.addLiveOuts(MBB: *this);
1078 for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1079 LiveRegs.stepBackward(MI: *I);
1080 }
1081
1082 MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(BB: getBasicBlock());
1083
1084 MF->insert(MBBI: ++MachineFunction::iterator(this), MBB: SplitBB);
1085 SplitBB->splice(Where: SplitBB->begin(), Other: this, From: SplitPoint, To: end());
1086
1087 SplitBB->transferSuccessorsAndUpdatePHIs(FromMBB: this);
1088 addSuccessor(Succ: SplitBB);
1089
1090 if (UpdateLiveIns)
1091 addLiveIns(MBB&: *SplitBB, LiveRegs);
1092
1093 if (LIS)
1094 LIS->splitAt(Orig&: *this, SplitBB&: *SplitBB);
1095
1096 return SplitBB;
1097}
1098
1099// Returns `true` if there are possibly other users of the jump table at
1100// `JumpTableIndex` except for the ones in `IgnoreMBB`.
1101static bool jumpTableHasOtherUses(const MachineFunction &MF,
1102 const MachineBasicBlock &IgnoreMBB,
1103 int JumpTableIndex) {
1104 assert(JumpTableIndex >= 0 && "need valid index");
1105 const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1106 const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1107 // Take any basic block from the table; every user of the jump table must
1108 // show up in the predecessor list.
1109 const MachineBasicBlock *MBB = nullptr;
1110 for (MachineBasicBlock *B : MJTE.MBBs) {
1111 if (B != nullptr) {
1112 MBB = B;
1113 break;
1114 }
1115 }
1116 if (MBB == nullptr)
1117 return true; // can't rule out other users if there isn't any block.
1118 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1119 SmallVector<MachineOperand, 4> Cond;
1120 for (MachineBasicBlock *Pred : MBB->predecessors()) {
1121 if (Pred == &IgnoreMBB)
1122 continue;
1123 MachineBasicBlock *DummyT = nullptr;
1124 MachineBasicBlock *DummyF = nullptr;
1125 Cond.clear();
1126 if (!TII.analyzeBranch(MBB&: *Pred, TBB&: DummyT, FBB&: DummyF, Cond,
1127 /*AllowModify=*/false)) {
1128 // analyzable direct jump
1129 continue;
1130 }
1131 int PredJTI = findJumpTableIndex(MBB: *Pred);
1132 if (PredJTI >= 0) {
1133 if (PredJTI == JumpTableIndex)
1134 return true;
1135 continue;
1136 }
1137 // Be conservative for unanalyzable jumps.
1138 return true;
1139 }
1140 return false;
1141}
1142
1143class SlotIndexUpdateDelegate : public MachineFunction::Delegate {
1144private:
1145 MachineFunction &MF;
1146 SlotIndexes *Indexes;
1147 SmallSetVector<MachineInstr *, 2> Insertions;
1148
1149public:
1150 SlotIndexUpdateDelegate(MachineFunction &MF, SlotIndexes *Indexes)
1151 : MF(MF), Indexes(Indexes) {
1152 MF.setDelegate(this);
1153 }
1154
1155 ~SlotIndexUpdateDelegate() override {
1156 MF.resetDelegate(delegate: this);
1157 for (auto MI : Insertions)
1158 Indexes->insertMachineInstrInMaps(MI&: *MI);
1159 }
1160
1161 void MF_HandleInsertion(MachineInstr &MI) override {
1162 // This is called before MI is inserted into block so defer index update.
1163 if (Indexes)
1164 Insertions.insert(X: &MI);
1165 }
1166
1167 void MF_HandleRemoval(MachineInstr &MI) override {
1168 if (Indexes && !Insertions.remove(X: &MI))
1169 Indexes->removeMachineInstrFromMaps(MI);
1170 }
1171};
1172
1173MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
1174 MachineBasicBlock *Succ, Pass *P, MachineFunctionAnalysisManager *MFAM,
1175 std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater *MDTU) {
1176#define GET_RESULT(RESULT, GETTER, INFIX) \
1177 [MF, P, MFAM]() { \
1178 if (P) { \
1179 auto *Wrapper = P->getAnalysisIfAvailable<RESULT##INFIX##WrapperPass>(); \
1180 return Wrapper ? &Wrapper->GETTER() : nullptr; \
1181 } \
1182 return MFAM->getCachedResult<RESULT##Analysis>(*MF); \
1183 }()
1184
1185 assert((P || MFAM) && "Need a way to get analysis results!");
1186 MachineFunction *MF = getParent();
1187 LiveIntervals *LIS = GET_RESULT(LiveIntervals, getLIS, );
1188 SlotIndexes *Indexes = GET_RESULT(SlotIndexes, getSI, );
1189 LiveVariables *LV = GET_RESULT(LiveVariables, getLV, );
1190 MachineLoopInfo *MLI = GET_RESULT(MachineLoop, getLI, Info);
1191 return SplitCriticalEdge(Succ, Analyses: {.LIS: LIS, .SI: Indexes, .LV: LV, .MLI: MLI}, LiveInSets, MDTU);
1192#undef GET_RESULT
1193}
1194
1195MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(
1196 MachineBasicBlock *Succ, const SplitCriticalEdgeAnalyses &Analyses,
1197 std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater *MDTU) {
1198 if (!canSplitCriticalEdge(Succ, MLI: Analyses.MLI))
1199 return nullptr;
1200
1201 MachineFunction *MF = getParent();
1202 MachineBasicBlock *PrevFallthrough = getNextNode();
1203
1204 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
1205 NMBB->setCallFrameSize(Succ->getCallFrameSize());
1206
1207 // Is there an indirect jump with jump table?
1208 bool ChangedIndirectJump = false;
1209 int JTI = findJumpTableIndex(MBB: *this);
1210 if (JTI >= 0) {
1211 MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo();
1212 MJTI.ReplaceMBBInJumpTable(Idx: JTI, Old: Succ, New: NMBB);
1213 ChangedIndirectJump = true;
1214 }
1215
1216 MF->insert(MBBI: std::next(x: MachineFunction::iterator(this)), MBB: NMBB);
1217 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
1218 << " -- " << printMBBReference(*NMBB) << " -- "
1219 << printMBBReference(*Succ) << '\n');
1220 auto *LIS = Analyses.LIS;
1221 if (LIS)
1222 LIS->insertMBBInMaps(MBB: NMBB);
1223 else if (Analyses.SI)
1224 Analyses.SI->insertMBBInMaps(mbb: NMBB);
1225
1226 // On some targets like Mips, branches may kill virtual registers. Make sure
1227 // that LiveVariables is properly updated after updateTerminator replaces the
1228 // terminators.
1229 auto *LV = Analyses.LV;
1230 // Collect a list of virtual registers killed by the terminators.
1231 SmallVector<Register, 4> KilledRegs;
1232 if (LV)
1233 for (MachineInstr &MI :
1234 llvm::make_range(x: getFirstInstrTerminator(), y: instr_end())) {
1235 for (MachineOperand &MO : MI.all_uses()) {
1236 if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef())
1237 continue;
1238 Register Reg = MO.getReg();
1239 if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) {
1240 KilledRegs.push_back(Elt: Reg);
1241 LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI);
1242 MO.setIsKill(false);
1243 }
1244 }
1245 }
1246
1247 SmallVector<Register, 4> UsedRegs;
1248 if (LIS) {
1249 for (MachineInstr &MI :
1250 llvm::make_range(x: getFirstInstrTerminator(), y: instr_end())) {
1251 for (const MachineOperand &MO : MI.operands()) {
1252 if (!MO.isReg() || MO.getReg() == 0)
1253 continue;
1254
1255 Register Reg = MO.getReg();
1256 if (!is_contained(Range&: UsedRegs, Element: Reg))
1257 UsedRegs.push_back(Elt: Reg);
1258 }
1259 }
1260 }
1261
1262 ReplaceUsesOfBlockWith(Old: Succ, New: NMBB);
1263
1264 // Since we replaced all uses of Succ with NMBB, that should also be treated
1265 // as the fallthrough successor
1266 if (Succ == PrevFallthrough)
1267 PrevFallthrough = NMBB;
1268 auto *Indexes = Analyses.SI;
1269 if (!ChangedIndirectJump) {
1270 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1271 updateTerminator(PreviousLayoutSuccessor: PrevFallthrough);
1272 }
1273
1274 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
1275 NMBB->addSuccessor(Succ);
1276 if (!NMBB->isLayoutSuccessor(MBB: Succ)) {
1277 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1278 SmallVector<MachineOperand, 4> Cond;
1279 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
1280
1281 // In original 'this' BB, there must be a branch instruction targeting at
1282 // Succ. We can not find it out since currently getBranchDestBlock was not
1283 // implemented for all targets. However, if the merged DL has column or line
1284 // number, the scope and non-zero column and line number is same with that
1285 // branch instruction so we can safely use it.
1286 DebugLoc DL, MergedDL = findBranchDebugLoc();
1287 if (MergedDL && (MergedDL.getLine() || MergedDL.getCol()))
1288 DL = MergedDL;
1289 TII->insertBranch(MBB&: *NMBB, TBB: Succ, FBB: nullptr, Cond, DL);
1290 }
1291
1292 // Fix PHI nodes in Succ so they refer to NMBB instead of this.
1293 Succ->replacePhiUsesWith(Old: this, New: NMBB);
1294
1295 // Inherit live-ins from the successor
1296 for (const auto &LI : Succ->liveins())
1297 NMBB->addLiveIn(RegMaskPair: LI);
1298
1299 // Update LiveVariables.
1300 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1301 if (LV) {
1302 // Restore kills of virtual registers that were killed by the terminators.
1303 while (!KilledRegs.empty()) {
1304 Register Reg = KilledRegs.pop_back_val();
1305 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
1306 if (!(--I)->addRegisterKilled(IncomingReg: Reg, RegInfo: TRI, /* AddIfNotFound= */ false))
1307 continue;
1308 if (Reg.isVirtual())
1309 LV->getVarInfo(Reg).Kills.push_back(x: &*I);
1310 LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
1311 break;
1312 }
1313 }
1314 // Update relevant live-through information.
1315 if (LiveInSets != nullptr)
1316 LV->addNewBlock(BB: NMBB, DomBB: this, SuccBB: Succ, LiveInSets&: *LiveInSets);
1317 else
1318 LV->addNewBlock(BB: NMBB, DomBB: this, SuccBB: Succ);
1319 }
1320
1321 if (LIS) {
1322 // After splitting the edge and updating SlotIndexes, live intervals may be
1323 // in one of two situations, depending on whether this block was the last in
1324 // the function. If the original block was the last in the function, all
1325 // live intervals will end prior to the beginning of the new split block. If
1326 // the original block was not at the end of the function, all live intervals
1327 // will extend to the end of the new split block.
1328
1329 bool isLastMBB =
1330 std::next(x: MachineFunction::iterator(NMBB)) == getParent()->end();
1331
1332 SlotIndex StartIndex = Indexes->getMBBEndIdx(mbb: this);
1333 SlotIndex PrevIndex = StartIndex.getPrevSlot();
1334 SlotIndex EndIndex = Indexes->getMBBEndIdx(mbb: NMBB);
1335
1336 // Find the registers used from NMBB in PHIs in Succ.
1337 SmallSet<Register, 8> PHISrcRegs;
1338 for (MachineBasicBlock::instr_iterator
1339 I = Succ->instr_begin(), E = Succ->instr_end();
1340 I != E && I->isPHI(); ++I) {
1341 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1342 if (I->getOperand(i: ni+1).getMBB() == NMBB) {
1343 MachineOperand &MO = I->getOperand(i: ni);
1344 Register Reg = MO.getReg();
1345 PHISrcRegs.insert(V: Reg);
1346 if (MO.isUndef())
1347 continue;
1348
1349 LiveInterval &LI = LIS->getInterval(Reg);
1350 VNInfo *VNI = LI.getVNInfoAt(Idx: PrevIndex);
1351 assert(VNI &&
1352 "PHI sources should be live out of their predecessors.");
1353 LI.addSegment(S: LiveInterval::Segment(StartIndex, EndIndex, VNI));
1354 for (auto &SR : LI.subranges())
1355 SR.addSegment(S: LiveInterval::Segment(StartIndex, EndIndex, VNI));
1356 }
1357 }
1358 }
1359
1360 MachineRegisterInfo *MRI = &getParent()->getRegInfo();
1361 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1362 Register Reg = Register::index2VirtReg(Index: i);
1363 if (PHISrcRegs.count(V: Reg) || !LIS->hasInterval(Reg))
1364 continue;
1365
1366 LiveInterval &LI = LIS->getInterval(Reg);
1367 if (!LI.liveAt(index: PrevIndex))
1368 continue;
1369
1370 bool isLiveOut = LI.liveAt(index: LIS->getMBBStartIdx(mbb: Succ));
1371 if (isLiveOut && isLastMBB) {
1372 VNInfo *VNI = LI.getVNInfoAt(Idx: PrevIndex);
1373 assert(VNI && "LiveInterval should have VNInfo where it is live.");
1374 LI.addSegment(S: LiveInterval::Segment(StartIndex, EndIndex, VNI));
1375 // Update subranges with live values
1376 for (auto &SR : LI.subranges()) {
1377 VNInfo *VNI = SR.getVNInfoAt(Idx: PrevIndex);
1378 if (VNI)
1379 SR.addSegment(S: LiveInterval::Segment(StartIndex, EndIndex, VNI));
1380 }
1381 } else if (!isLiveOut && !isLastMBB) {
1382 LI.removeSegment(Start: StartIndex, End: EndIndex);
1383 for (auto &SR : LI.subranges())
1384 SR.removeSegment(Start: StartIndex, End: EndIndex);
1385 }
1386 }
1387
1388 // Update all intervals for registers whose uses may have been modified by
1389 // updateTerminator().
1390 LIS->repairIntervalsInRange(MBB: this, Begin: getFirstTerminator(), End: end(), OrigRegs: UsedRegs);
1391 }
1392
1393 if (MDTU)
1394 MDTU->splitCriticalEdge(FromBB: this, ToBB: Succ, NewBB: NMBB);
1395
1396 if (MachineLoopInfo *MLI = Analyses.MLI)
1397 if (MachineLoop *TIL = MLI->getLoopFor(BB: this)) {
1398 // If one or the other blocks were not in a loop, the new block is not
1399 // either, and thus LI doesn't need to be updated.
1400 if (MachineLoop *DestLoop = MLI->getLoopFor(BB: Succ)) {
1401 if (TIL == DestLoop) {
1402 // Both in the same loop, the NMBB joins loop.
1403 DestLoop->addBasicBlockToLoop(NewBB: NMBB, LI&: *MLI);
1404 } else if (TIL->contains(L: DestLoop)) {
1405 // Edge from an outer loop to an inner loop. Add to the outer loop.
1406 TIL->addBasicBlockToLoop(NewBB: NMBB, LI&: *MLI);
1407 } else if (DestLoop->contains(L: TIL)) {
1408 // Edge from an inner loop to an outer loop. Add to the outer loop.
1409 DestLoop->addBasicBlockToLoop(NewBB: NMBB, LI&: *MLI);
1410 } else {
1411 // Edge from two loops with no containment relation. Because these
1412 // are natural loops, we know that the destination block must be the
1413 // header of its loop (adding a branch into a loop elsewhere would
1414 // create an irreducible loop).
1415 assert(DestLoop->getHeader() == Succ &&
1416 "Should not create irreducible loops!");
1417 if (MachineLoop *P = DestLoop->getParentLoop())
1418 P->addBasicBlockToLoop(NewBB: NMBB, LI&: *MLI);
1419 }
1420 }
1421 }
1422
1423 return NMBB;
1424}
1425
1426bool MachineBasicBlock::canSplitCriticalEdge(const MachineBasicBlock *Succ,
1427 const MachineLoopInfo *MLI) const {
1428 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1429 // it in this generic function.
1430 if (Succ->isEHPad())
1431 return false;
1432
1433 // Splitting the critical edge to a callbr's indirect block isn't advised.
1434 // Don't do it in this generic function.
1435 if (Succ->isInlineAsmBrIndirectTarget())
1436 return false;
1437
1438 const MachineFunction *MF = getParent();
1439 // Performance might be harmed on HW that implements branching using exec mask
1440 // where both sides of the branches are always executed.
1441
1442 if (MF->getTarget().requiresStructuredCFG()) {
1443 if (!MLI)
1444 return false;
1445 const MachineLoop *L = MLI->getLoopFor(BB: Succ);
1446 // Only if `Succ` is a loop header, splitting the critical edge will not
1447 // break structured CFG. And fallthrough to check if this's terminator is
1448 // analyzable.
1449 if (!L || L->getHeader() != Succ)
1450 return false;
1451 }
1452
1453 // Do we have an Indirect jump with a jumptable that we can rewrite?
1454 int JTI = findJumpTableIndex(MBB: *this);
1455 if (JTI >= 0 && !jumpTableHasOtherUses(MF: *MF, IgnoreMBB: *this, JumpTableIndex: JTI))
1456 return true;
1457
1458 // We may need to update this's terminator, but we can't do that if
1459 // analyzeBranch fails.
1460 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1461 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1462 SmallVector<MachineOperand, 4> Cond;
1463 // AnalyzeBanch should modify this, since we did not allow modification.
1464 if (TII->analyzeBranch(MBB&: *const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
1465 /*AllowModify*/ false))
1466 return false;
1467
1468 // Handle weird inputs (e.g., generated by a test case reducer/fuzzer): A
1469 // block may end with a conditional branch but jumps to the same MBB is either
1470 // case. We have duplicate CFG edges in that case that we can't handle. Since
1471 // this never happens in properly optimized code, just skip those edges.
1472 if (TBB && TBB == FBB) {
1473 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1474 << printMBBReference(*this) << '\n');
1475 return false;
1476 }
1477 return true;
1478}
1479
1480/// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1481/// neighboring instructions so the bundle won't be broken by removing MI.
1482static void unbundleSingleMI(MachineInstr *MI) {
1483 // Removing the first instruction in a bundle.
1484 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1485 MI->unbundleFromSucc();
1486 // Removing the last instruction in a bundle.
1487 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1488 MI->unbundleFromPred();
1489 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1490 // are already fine.
1491}
1492
1493MachineBasicBlock::instr_iterator
1494MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1495 unbundleSingleMI(MI: &*I);
1496 return Insts.erase(where: I);
1497}
1498
1499MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1500 unbundleSingleMI(MI);
1501 MI->clearFlag(Flag: MachineInstr::BundledPred);
1502 MI->clearFlag(Flag: MachineInstr::BundledSucc);
1503 return Insts.remove(IT: MI);
1504}
1505
1506MachineBasicBlock::instr_iterator
1507MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1508 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1509 "Cannot insert instruction with bundle flags");
1510 // Set the bundle flags when inserting inside a bundle.
1511 if (I != instr_end() && I->isBundledWithPred()) {
1512 MI->setFlag(MachineInstr::BundledPred);
1513 MI->setFlag(MachineInstr::BundledSucc);
1514 }
1515 return Insts.insert(where: I, New: MI);
1516}
1517
1518/// This method unlinks 'this' from the containing function, and returns it, but
1519/// does not delete it.
1520MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1521 assert(getParent() && "Not embedded in a function!");
1522 getParent()->remove(MBBI: this);
1523 return this;
1524}
1525
1526/// This method unlinks 'this' from the containing function, and deletes it.
1527void MachineBasicBlock::eraseFromParent() {
1528 assert(getParent() && "Not embedded in a function!");
1529 getParent()->erase(MBBI: this);
1530}
1531
1532/// Given a machine basic block that branched to 'Old', change the code and CFG
1533/// so that it branches to 'New' instead.
1534void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1535 MachineBasicBlock *New) {
1536 assert(Old != New && "Cannot replace self with self!");
1537
1538 MachineBasicBlock::instr_iterator I = instr_end();
1539 while (I != instr_begin()) {
1540 --I;
1541 if (!I->isTerminator()) break;
1542
1543 // Scan the operands of this machine instruction, replacing any uses of Old
1544 // with New.
1545 for (MachineOperand &MO : I->operands())
1546 if (MO.isMBB() && MO.getMBB() == Old)
1547 MO.setMBB(New);
1548 }
1549
1550 // Update the successor information.
1551 replaceSuccessor(Old, New);
1552}
1553
1554void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
1555 MachineBasicBlock *New) {
1556 for (MachineInstr &MI : phis())
1557 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1558 MachineOperand &MO = MI.getOperand(i);
1559 if (MO.getMBB() == Old)
1560 MO.setMBB(New);
1561 }
1562}
1563
1564/// Find the next valid DebugLoc starting at MBBI, skipping any debug
1565/// instructions. Return UnknownLoc if there is none.
1566DebugLoc
1567MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1568 // Skip debug declarations, we don't want a DebugLoc from them.
1569 MBBI = skipDebugInstructionsForward(It: MBBI, End: instr_end());
1570 if (MBBI != instr_end())
1571 return MBBI->getDebugLoc();
1572 return {};
1573}
1574
1575DebugLoc MachineBasicBlock::rfindDebugLoc(reverse_instr_iterator MBBI) {
1576 if (MBBI == instr_rend())
1577 return findDebugLoc(MBBI: instr_begin());
1578 // Skip debug declarations, we don't want a DebugLoc from them.
1579 MBBI = skipDebugInstructionsBackward(It: MBBI, Begin: instr_rbegin());
1580 if (!MBBI->isDebugInstr())
1581 return MBBI->getDebugLoc();
1582 return {};
1583}
1584
1585/// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1586/// instructions. Return UnknownLoc if there is none.
1587DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) {
1588 if (MBBI == instr_begin())
1589 return {};
1590 // Skip debug instructions, we don't want a DebugLoc from them.
1591 MBBI = prev_nodbg(It: MBBI, Begin: instr_begin());
1592 if (!MBBI->isDebugInstr())
1593 return MBBI->getDebugLoc();
1594 return {};
1595}
1596
1597DebugLoc MachineBasicBlock::rfindPrevDebugLoc(reverse_instr_iterator MBBI) {
1598 if (MBBI == instr_rend())
1599 return {};
1600 // Skip debug declarations, we don't want a DebugLoc from them.
1601 MBBI = next_nodbg(It: MBBI, End: instr_rend());
1602 if (MBBI != instr_rend())
1603 return MBBI->getDebugLoc();
1604 return {};
1605}
1606
1607/// Find and return the merged DebugLoc of the branch instructions of the block.
1608/// Return UnknownLoc if there is none.
1609DebugLoc
1610MachineBasicBlock::findBranchDebugLoc() {
1611 DebugLoc DL;
1612 auto TI = getFirstTerminator();
1613 while (TI != end() && !TI->isBranch())
1614 ++TI;
1615
1616 if (TI != end()) {
1617 DL = TI->getDebugLoc();
1618 for (++TI ; TI != end() ; ++TI)
1619 if (TI->isBranch())
1620 DL = DebugLoc::getMergedLocation(LocA: DL, LocB: TI->getDebugLoc());
1621 }
1622 return DL;
1623}
1624
1625/// Return probability of the edge from this block to MBB.
1626BranchProbability
1627MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1628 if (Probs.empty())
1629 return BranchProbability(1, succ_size());
1630
1631 const auto &Prob = *getProbabilityIterator(I: Succ);
1632 if (!Prob.isUnknown())
1633 return Prob;
1634 // For unknown probabilities, collect the sum of all known ones, and evenly
1635 // ditribute the complemental of the sum to each unknown probability.
1636 unsigned KnownProbNum = 0;
1637 auto Sum = BranchProbability::getZero();
1638 for (const auto &P : Probs) {
1639 if (!P.isUnknown()) {
1640 Sum += P;
1641 KnownProbNum++;
1642 }
1643 }
1644 return Sum.getCompl() / (Probs.size() - KnownProbNum);
1645}
1646
1647bool MachineBasicBlock::canPredictBranchProbabilities() const {
1648 if (succ_size() <= 1)
1649 return true;
1650 if (!hasSuccessorProbabilities())
1651 return true;
1652
1653 SmallVector<BranchProbability, 8> Normalized(Probs.begin(), Probs.end());
1654 BranchProbability::normalizeProbabilities(R&: Normalized);
1655
1656 // Normalize assuming unknown probabilities. This will assign equal
1657 // probabilities to all successors.
1658 SmallVector<BranchProbability, 8> Equal(Normalized.size());
1659 BranchProbability::normalizeProbabilities(R&: Equal);
1660
1661 return llvm::equal(LRange&: Normalized, RRange&: Equal);
1662}
1663
1664/// Set successor probability of a given iterator.
1665void MachineBasicBlock::setSuccProbability(succ_iterator I,
1666 BranchProbability Prob) {
1667 assert(!Prob.isUnknown());
1668 if (Probs.empty())
1669 return;
1670 *getProbabilityIterator(I) = Prob;
1671}
1672
1673/// Return probability iterator corresonding to the I successor iterator
1674MachineBasicBlock::const_probability_iterator
1675MachineBasicBlock::getProbabilityIterator(
1676 MachineBasicBlock::const_succ_iterator I) const {
1677 assert(Probs.size() == Successors.size() && "Async probability list!");
1678 const size_t index = std::distance(first: Successors.begin(), last: I);
1679 assert(index < Probs.size() && "Not a current successor!");
1680 return Probs.begin() + index;
1681}
1682
1683/// Return probability iterator corresonding to the I successor iterator.
1684MachineBasicBlock::probability_iterator
1685MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1686 assert(Probs.size() == Successors.size() && "Async probability list!");
1687 const size_t index = std::distance(first: Successors.begin(), last: I);
1688 assert(index < Probs.size() && "Not a current successor!");
1689 return Probs.begin() + index;
1690}
1691
1692/// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1693/// as of just before "MI".
1694///
1695/// Search is localised to a neighborhood of
1696/// Neighborhood instructions before (searching for defs or kills) and N
1697/// instructions after (searching just for defs) MI.
1698MachineBasicBlock::LivenessQueryResult
1699MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1700 MCRegister Reg, const_iterator Before,
1701 unsigned Neighborhood) const {
1702 assert(Reg.isPhysical());
1703 unsigned N = Neighborhood;
1704
1705 // Try searching forwards from Before, looking for reads or defs.
1706 const_iterator I(Before);
1707 for (; I != end() && N > 0; ++I) {
1708 if (I->isDebugOrPseudoInstr())
1709 continue;
1710
1711 --N;
1712
1713 PhysRegInfo Info = AnalyzePhysRegInBundle(MI: *I, Reg, TRI);
1714
1715 // Register is live when we read it here.
1716 if (Info.Read)
1717 return LQR_Live;
1718 // Register is dead if we can fully overwrite or clobber it here.
1719 if (Info.FullyDefined || Info.Clobbered)
1720 return LQR_Dead;
1721 }
1722
1723 // If we reached the end, it is safe to clobber Reg at the end of a block of
1724 // no successor has it live in.
1725 if (I == end()) {
1726 for (MachineBasicBlock *S : successors()) {
1727 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1728 if (TRI->regsOverlap(RegA: LI.PhysReg, RegB: Reg))
1729 return LQR_Live;
1730 }
1731 }
1732
1733 return LQR_Dead;
1734 }
1735
1736
1737 N = Neighborhood;
1738
1739 // Start by searching backwards from Before, looking for kills, reads or defs.
1740 I = const_iterator(Before);
1741 // If this is the first insn in the block, don't search backwards.
1742 if (I != begin()) {
1743 do {
1744 --I;
1745
1746 if (I->isDebugOrPseudoInstr())
1747 continue;
1748
1749 --N;
1750
1751 PhysRegInfo Info = AnalyzePhysRegInBundle(MI: *I, Reg, TRI);
1752
1753 // Defs happen after uses so they take precedence if both are present.
1754
1755 // Register is dead after a dead def of the full register.
1756 if (Info.DeadDef)
1757 return LQR_Dead;
1758 // Register is (at least partially) live after a def.
1759 if (Info.Defined) {
1760 if (!Info.PartialDeadDef)
1761 return LQR_Live;
1762 // As soon as we saw a partial definition (dead or not),
1763 // we cannot tell if the value is partial live without
1764 // tracking the lanemasks. We are not going to do this,
1765 // so fall back on the remaining of the analysis.
1766 break;
1767 }
1768 // Register is dead after a full kill or clobber and no def.
1769 if (Info.Killed || Info.Clobbered)
1770 return LQR_Dead;
1771 // Register must be live if we read it.
1772 if (Info.Read)
1773 return LQR_Live;
1774
1775 } while (I != begin() && N > 0);
1776 }
1777
1778 // If all the instructions before this in the block are debug instructions,
1779 // skip over them.
1780 while (I != begin() && std::prev(x: I)->isDebugOrPseudoInstr())
1781 --I;
1782
1783 // Did we get to the start of the block?
1784 if (I == begin()) {
1785 // If so, the register's state is definitely defined by the live-in state.
1786 for (const MachineBasicBlock::RegisterMaskPair &LI : liveins())
1787 if (TRI->regsOverlap(RegA: LI.PhysReg, RegB: Reg))
1788 return LQR_Live;
1789
1790 return LQR_Dead;
1791 }
1792
1793 // At this point we have no idea of the liveness of the register.
1794 return LQR_Unknown;
1795}
1796
1797const uint32_t *
1798MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1799 // EH funclet entry does not preserve any registers.
1800 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1801}
1802
1803const uint32_t *
1804MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1805 // If we see a return block with successors, this must be a funclet return,
1806 // which does not preserve any registers. If there are no successors, we don't
1807 // care what kind of return it is, putting a mask after it is a no-op.
1808 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1809}
1810
1811void MachineBasicBlock::clearLiveIns() {
1812 LiveIns.clear();
1813}
1814
1815void MachineBasicBlock::clearLiveIns(
1816 std::vector<RegisterMaskPair> &OldLiveIns) {
1817 assert(OldLiveIns.empty() && "Vector must be empty");
1818 std::swap(x&: LiveIns, y&: OldLiveIns);
1819}
1820
1821MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
1822 assert(getParent()->getProperties().hasTracksLiveness() &&
1823 "Liveness information is accurate");
1824 return LiveIns.begin();
1825}
1826
1827MachineBasicBlock::liveout_iterator MachineBasicBlock::liveout_begin() const {
1828 const MachineFunction &MF = *getParent();
1829 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1830 MCRegister ExceptionPointer, ExceptionSelector;
1831 if (MF.getFunction().hasPersonalityFn()) {
1832 auto PersonalityFn = MF.getFunction().getPersonalityFn();
1833 ExceptionPointer = TLI.getExceptionPointerRegister(
1834 EH: TLI.getTargetMachine().getExceptionModel(), PersonalityFn);
1835 ExceptionSelector = TLI.getExceptionSelectorRegister(
1836 EH: TLI.getTargetMachine().getExceptionModel(), PersonalityFn);
1837 }
1838
1839 return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1840}
1841
1842bool MachineBasicBlock::sizeWithoutDebugLargerThan(unsigned Limit) const {
1843 unsigned Cntr = 0;
1844 auto R = instructionsWithoutDebug(It: begin(), End: end());
1845 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1846 if (++Cntr > Limit)
1847 return true;
1848 }
1849 return false;
1850}
1851
1852void MachineBasicBlock::removePHIsIncomingValuesForPredecessor(
1853 const MachineBasicBlock &PredMBB) {
1854 for (MachineInstr &Phi : phis())
1855 Phi.removePHIIncomingValueFor(MBB: PredMBB);
1856}
1857
1858const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold);
1859const MBBSectionID
1860 MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception);
1861