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/MachineDomTreeUpdater.h"
19#include "llvm/CodeGen/MachineDominators.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineInstrBuilder.h"
22#include "llvm/CodeGen/MachineJumpTableInfo.h"
23#include "llvm/CodeGen/MachineLoopInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/SlotIndexes.h"
26#include "llvm/CodeGen/TargetInstrInfo.h"
27#include "llvm/CodeGen/TargetLowering.h"
28#include "llvm/CodeGen/TargetRegisterInfo.h"
29#include "llvm/CodeGen/TargetSubtargetInfo.h"
30#include "llvm/Config/llvm-config.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/IRPrintingPasses.h"
33#include "llvm/IR/Module.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());
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 (isCleanupFuncletEntry()) {
565 os << (hasAttributes ? ", " : " (");
566 os << "cleanup-funclet-entry";
567 hasAttributes = true;
568 }
569 if (isEHContTarget()) {
570 os << (hasAttributes ? ", " : " (");
571 os << "ehcont-target";
572 hasAttributes = true;
573 }
574 if (getAlignment() != Align(1)) {
575 os << (hasAttributes ? ", " : " (");
576 os << "align " << getAlignment().value();
577 hasAttributes = true;
578 if (getMaxBytesForAlignment())
579 os << ", max-bytes-for-alignment " << getMaxBytesForAlignment();
580 }
581 if (getSectionID() != MBBSectionID(0)) {
582 os << (hasAttributes ? ", " : " (");
583 os << "bbsections ";
584 switch (getSectionID().Type) {
585 case MBBSectionID::SectionType::Exception:
586 os << "Exception";
587 break;
588 case MBBSectionID::SectionType::Cold:
589 os << "Cold";
590 break;
591 default:
592 os << getSectionID().Number;
593 }
594 hasAttributes = true;
595 }
596 if (getBBID().has_value()) {
597 os << (hasAttributes ? ", " : " (");
598 os << "bb_id " << getBBID()->BaseID;
599 if (getBBID()->CloneID != 0)
600 os << " " << getBBID()->CloneID;
601 hasAttributes = true;
602 }
603 if (CallFrameSize != 0) {
604 os << (hasAttributes ? ", " : " (");
605 os << "call-frame-size " << CallFrameSize;
606 hasAttributes = true;
607 }
608 }
609
610 if (hasAttributes)
611 os << ')';
612}
613
614void MachineBasicBlock::printAsOperand(raw_ostream &OS,
615 bool /*PrintType*/) const {
616 OS << '%';
617 printName(os&: OS, printNameFlags: 0);
618}
619
620void MachineBasicBlock::removeLiveIn(MCRegister Reg, LaneBitmask LaneMask) {
621 assert(Reg.isPhysical());
622 LiveInVector::iterator I = find_if(
623 Range&: LiveIns, P: [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
624 if (I == LiveIns.end())
625 return;
626
627 I->LaneMask &= ~LaneMask;
628 if (I->LaneMask.none())
629 LiveIns.erase(position: I);
630}
631
632void MachineBasicBlock::removeLiveInOverlappedWith(MCRegister Reg) {
633 const MachineFunction *MF = getParent();
634 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
635 // Remove Reg and its subregs from live in set.
636 for (MCPhysReg S : TRI->subregs_inclusive(Reg))
637 removeLiveIn(Reg: S);
638
639 // Remove live-in bitmask in super registers as well.
640 for (MCPhysReg Super : TRI->superregs(Reg)) {
641 for (MCSubRegIndexIterator SRI(Super, TRI); SRI.isValid(); ++SRI) {
642 if (Reg == SRI.getSubReg()) {
643 unsigned SubRegIndex = SRI.getSubRegIndex();
644 LaneBitmask SubRegLaneMask = TRI->getSubRegIndexLaneMask(SubIdx: SubRegIndex);
645 removeLiveIn(Reg: Super, LaneMask: SubRegLaneMask);
646 break;
647 }
648 }
649 }
650}
651
652MachineBasicBlock::livein_iterator
653MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
654 // Get non-const version of iterator.
655 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
656 return LiveIns.erase(position: LI);
657}
658
659bool MachineBasicBlock::isLiveIn(MCRegister Reg, LaneBitmask LaneMask) const {
660 assert(Reg.isPhysical());
661 livein_iterator I = find_if(
662 Range: LiveIns, P: [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
663 return I != livein_end() && (I->LaneMask & LaneMask).any();
664}
665
666void MachineBasicBlock::sortUniqueLiveIns() {
667 llvm::sort(C&: LiveIns,
668 Comp: [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
669 return LI0.PhysReg < LI1.PhysReg;
670 });
671 // Liveins are sorted by physreg now we can merge their lanemasks.
672 LiveInVector::const_iterator I = LiveIns.begin();
673 LiveInVector::const_iterator J;
674 LiveInVector::iterator Out = LiveIns.begin();
675 for (; I != LiveIns.end(); ++Out, I = J) {
676 MCRegister PhysReg = I->PhysReg;
677 LaneBitmask LaneMask = I->LaneMask;
678 for (J = std::next(x: I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
679 LaneMask |= J->LaneMask;
680 Out->PhysReg = PhysReg;
681 Out->LaneMask = LaneMask;
682 }
683 LiveIns.erase(first: Out, last: LiveIns.end());
684}
685
686Register
687MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) {
688 assert(getParent() && "MBB must be inserted in function");
689 assert(PhysReg.isPhysical() && "Expected physreg");
690 assert(RC && "Register class is required");
691 assert((isEHPad() || this == &getParent()->front()) &&
692 "Only the entry block and landing pads can have physreg live ins");
693
694 bool LiveIn = isLiveIn(Reg: PhysReg);
695 iterator I = SkipPHIsAndLabels(I: begin()), E = end();
696 MachineRegisterInfo &MRI = getParent()->getRegInfo();
697 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
698
699 // Look for an existing copy.
700 if (LiveIn)
701 for (;I != E && I->isCopy(); ++I)
702 if (I->getOperand(i: 1).getReg() == PhysReg) {
703 Register VirtReg = I->getOperand(i: 0).getReg();
704 if (!MRI.constrainRegClass(Reg: VirtReg, RC))
705 llvm_unreachable("Incompatible live-in register class.");
706 return VirtReg;
707 }
708
709 // No luck, create a virtual register.
710 Register VirtReg = MRI.createVirtualRegister(RegClass: RC);
711 BuildMI(BB&: *this, I, MIMD: DebugLoc(), MCID: TII.get(Opcode: TargetOpcode::COPY), DestReg: VirtReg)
712 .addReg(RegNo: PhysReg, Flags: RegState::Kill);
713 if (!LiveIn)
714 addLiveIn(PhysReg);
715 return VirtReg;
716}
717
718void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
719 getParent()->splice(InsertPt: NewAfter->getIterator(), MBBI: getIterator());
720}
721
722void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
723 getParent()->splice(InsertPt: ++NewBefore->getIterator(), MBBI: getIterator());
724}
725
726static int findJumpTableIndex(const MachineBasicBlock &MBB) {
727 MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator();
728 if (TerminatorI == MBB.end())
729 return -1;
730 const MachineInstr &Terminator = *TerminatorI;
731 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
732 return TII->getJumpTableIndex(MI: Terminator);
733}
734
735void MachineBasicBlock::updateTerminator(
736 MachineBasicBlock *PreviousLayoutSuccessor) {
737 LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this)
738 << "\n");
739
740 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
741 // A block with no successors has no concerns with fall-through edges.
742 if (this->succ_empty())
743 return;
744
745 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
746 SmallVector<MachineOperand, 4> Cond;
747 DebugLoc DL = findBranchDebugLoc();
748 bool B = TII->analyzeBranch(MBB&: *this, TBB, FBB, Cond);
749 (void) B;
750 assert(!B && "UpdateTerminators requires analyzable predecessors!");
751 if (Cond.empty()) {
752 if (TBB) {
753 // The block has an unconditional branch. If its successor is now its
754 // layout successor, delete the branch.
755 if (isLayoutSuccessor(MBB: TBB))
756 TII->removeBranch(MBB&: *this);
757 } else {
758 // The block has an unconditional fallthrough, or the end of the block is
759 // unreachable.
760
761 // Unfortunately, whether the end of the block is unreachable is not
762 // immediately obvious; we must fall back to checking the successor list,
763 // and assuming that if the passed in block is in the succesor list and
764 // not an EHPad, it must be the intended target.
765 if (!PreviousLayoutSuccessor || !isSuccessor(MBB: PreviousLayoutSuccessor) ||
766 PreviousLayoutSuccessor->isEHPad())
767 return;
768
769 // If the unconditional successor block is not the current layout
770 // successor, insert a branch to jump to it.
771 if (!isLayoutSuccessor(MBB: PreviousLayoutSuccessor))
772 TII->insertBranch(MBB&: *this, TBB: PreviousLayoutSuccessor, FBB: nullptr, Cond, DL);
773 }
774 return;
775 }
776
777 if (FBB) {
778 // The block has a non-fallthrough conditional branch. If one of its
779 // successors is its layout successor, rewrite it to a fallthrough
780 // conditional branch.
781 if (isLayoutSuccessor(MBB: TBB)) {
782 if (TII->reverseBranchCondition(Cond))
783 return;
784 TII->removeBranch(MBB&: *this);
785 TII->insertBranch(MBB&: *this, TBB: FBB, FBB: nullptr, Cond, DL);
786 } else if (isLayoutSuccessor(MBB: FBB)) {
787 TII->removeBranch(MBB&: *this);
788 TII->insertBranch(MBB&: *this, TBB, FBB: nullptr, Cond, DL);
789 }
790 return;
791 }
792
793 // We now know we're going to fallthrough to PreviousLayoutSuccessor.
794 assert(PreviousLayoutSuccessor);
795 assert(!PreviousLayoutSuccessor->isEHPad());
796 assert(isSuccessor(PreviousLayoutSuccessor));
797
798 if (PreviousLayoutSuccessor == TBB) {
799 // We had a fallthrough to the same basic block as the conditional jump
800 // targets. Remove the conditional jump, leaving an unconditional
801 // fallthrough or an unconditional jump.
802 TII->removeBranch(MBB&: *this);
803 if (!isLayoutSuccessor(MBB: TBB)) {
804 Cond.clear();
805 TII->insertBranch(MBB&: *this, TBB, FBB: nullptr, Cond, DL);
806 }
807 return;
808 }
809
810 // The block has a fallthrough conditional branch.
811 if (isLayoutSuccessor(MBB: TBB)) {
812 if (TII->reverseBranchCondition(Cond)) {
813 // We can't reverse the condition, add an unconditional branch.
814 Cond.clear();
815 TII->insertBranch(MBB&: *this, TBB: PreviousLayoutSuccessor, FBB: nullptr, Cond, DL);
816 return;
817 }
818 TII->removeBranch(MBB&: *this);
819 TII->insertBranch(MBB&: *this, TBB: PreviousLayoutSuccessor, FBB: nullptr, Cond, DL);
820 } else if (!isLayoutSuccessor(MBB: PreviousLayoutSuccessor)) {
821 TII->removeBranch(MBB&: *this);
822 TII->insertBranch(MBB&: *this, TBB, FBB: PreviousLayoutSuccessor, Cond, DL);
823 }
824}
825
826void MachineBasicBlock::validateSuccProbs() const {
827#ifndef NDEBUG
828 int64_t Sum = 0;
829 for (auto Prob : Probs)
830 Sum += Prob.getNumerator();
831 // Due to precision issue, we assume that the sum of probabilities is one if
832 // the difference between the sum of their numerators and the denominator is
833 // no greater than the number of successors.
834 assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
835 Probs.size() &&
836 "The sum of successors's probabilities exceeds one.");
837#endif // NDEBUG
838}
839
840void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
841 BranchProbability Prob) {
842 // Probability list is either empty (if successor list isn't empty, this means
843 // disabled optimization) or has the same size as successor list.
844 if (!(Probs.empty() && !Successors.empty()))
845 Probs.push_back(x: Prob);
846 Successors.push_back(Elt: Succ);
847 Succ->addPredecessor(Pred: this);
848}
849
850void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
851 // We need to make sure probability list is either empty or has the same size
852 // of successor list. When this function is called, we can safely delete all
853 // probability in the list.
854 Probs.clear();
855 Successors.push_back(Elt: Succ);
856 Succ->addPredecessor(Pred: this);
857}
858
859void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
860 MachineBasicBlock *New,
861 bool NormalizeSuccProbs) {
862 succ_iterator OldI = llvm::find(Range: successors(), Val: Old);
863 assert(OldI != succ_end() && "Old is not a successor of this block!");
864 assert(!llvm::is_contained(successors(), New) &&
865 "New is already a successor of this block!");
866
867 // Add a new successor with equal probability as the original one. Note
868 // that we directly copy the probability using the iterator rather than
869 // getting a potentially synthetic probability computed when unknown. This
870 // preserves the probabilities as-is and then we can renormalize them and
871 // query them effectively afterward.
872 addSuccessor(Succ: New, Prob: Probs.empty() ? BranchProbability::getUnknown()
873 : *getProbabilityIterator(I: OldI));
874 if (NormalizeSuccProbs)
875 normalizeSuccProbs();
876}
877
878void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
879 bool NormalizeSuccProbs) {
880 succ_iterator I = find(Range&: Successors, Val: Succ);
881 removeSuccessor(I, NormalizeSuccProbs);
882}
883
884MachineBasicBlock::succ_iterator
885MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
886 assert(I != Successors.end() && "Not a current successor!");
887
888 // If probability list is empty it means we don't use it (disabled
889 // optimization).
890 if (!Probs.empty()) {
891 probability_iterator WI = getProbabilityIterator(I);
892 Probs.erase(position: WI);
893 if (NormalizeSuccProbs)
894 normalizeSuccProbs();
895 }
896
897 (*I)->removePredecessor(Pred: this);
898 return Successors.erase(CI: I);
899}
900
901void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
902 MachineBasicBlock *New) {
903 if (Old == New)
904 return;
905
906 succ_iterator E = succ_end();
907 succ_iterator NewI = E;
908 succ_iterator OldI = E;
909 for (succ_iterator I = succ_begin(); I != E; ++I) {
910 if (*I == Old) {
911 OldI = I;
912 if (NewI != E)
913 break;
914 }
915 if (*I == New) {
916 NewI = I;
917 if (OldI != E)
918 break;
919 }
920 }
921 assert(OldI != E && "Old is not a successor of this block");
922
923 // If New isn't already a successor, let it take Old's place.
924 if (NewI == E) {
925 Old->removePredecessor(Pred: this);
926 New->addPredecessor(Pred: this);
927 *OldI = New;
928 return;
929 }
930
931 // New is already a successor.
932 // Update its probability instead of adding a duplicate edge.
933 if (!Probs.empty()) {
934 auto ProbIter = getProbabilityIterator(I: NewI);
935 if (!ProbIter->isUnknown())
936 *ProbIter += *getProbabilityIterator(I: OldI);
937 }
938 removeSuccessor(I: OldI);
939}
940
941void MachineBasicBlock::copySuccessor(const MachineBasicBlock *Orig,
942 succ_iterator I) {
943 if (!Orig->Probs.empty())
944 addSuccessor(Succ: *I, Prob: Orig->getSuccProbability(Succ: I));
945 else
946 addSuccessorWithoutProb(Succ: *I);
947}
948
949void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
950 Predecessors.push_back(Elt: Pred);
951}
952
953void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
954 // This is often called on many predecessors in reverse order.
955 // Do a reverse search and removal to avoid quadratic behavior in such cases.
956 auto RI = llvm::find(Range: reverse(C&: Predecessors), Val: Pred);
957 assert(RI != Predecessors.rend() &&
958 "Pred is not a predecessor of this block!");
959 Predecessors.erase(CI: std::prev(x: RI.base()));
960}
961
962void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
963 if (this == FromMBB)
964 return;
965
966 while (!FromMBB->succ_empty()) {
967 MachineBasicBlock *Succ = *FromMBB->succ_begin();
968
969 // If probability list is empty it means we don't use it (disabled
970 // optimization).
971 if (!FromMBB->Probs.empty()) {
972 auto Prob = *FromMBB->Probs.begin();
973 addSuccessor(Succ, Prob);
974 } else
975 addSuccessorWithoutProb(Succ);
976
977 FromMBB->removeSuccessor(Succ);
978 }
979}
980
981void
982MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
983 if (this == FromMBB)
984 return;
985
986 while (!FromMBB->succ_empty()) {
987 MachineBasicBlock *Succ = *FromMBB->succ_begin();
988 if (!FromMBB->Probs.empty()) {
989 auto Prob = *FromMBB->Probs.begin();
990 addSuccessor(Succ, Prob);
991 } else
992 addSuccessorWithoutProb(Succ);
993 FromMBB->removeSuccessor(Succ);
994
995 // Fix up any PHI nodes in the successor.
996 Succ->replacePhiUsesWith(Old: FromMBB, New: this);
997 }
998 normalizeSuccProbs();
999}
1000
1001bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
1002 return is_contained(Range: predecessors(), Element: MBB);
1003}
1004
1005bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
1006 return is_contained(Range: successors(), Element: MBB);
1007}
1008
1009bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
1010 MachineFunction::const_iterator I(this);
1011 return std::next(x: I) == MachineFunction::const_iterator(MBB);
1012}
1013
1014const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const {
1015 return Successors.size() == 1 ? Successors[0] : nullptr;
1016}
1017
1018const MachineBasicBlock *MachineBasicBlock::getSinglePredecessor() const {
1019 return Predecessors.size() == 1 ? Predecessors[0] : nullptr;
1020}
1021
1022MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) {
1023 MachineFunction::iterator Fallthrough = getIterator();
1024 ++Fallthrough;
1025 // If FallthroughBlock is off the end of the function, it can't fall through.
1026 if (Fallthrough == getParent()->end())
1027 return nullptr;
1028
1029 // If FallthroughBlock isn't a successor, no fallthrough is possible.
1030 if (!isSuccessor(MBB: &*Fallthrough))
1031 return nullptr;
1032
1033 // Analyze the branches, if any, at the end of the block.
1034 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1035 SmallVector<MachineOperand, 4> Cond;
1036 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
1037 if (TII->analyzeBranch(MBB&: *this, TBB, FBB, Cond)) {
1038 // If we couldn't analyze the branch, examine the last instruction.
1039 // If the block doesn't end in a known control barrier, assume fallthrough
1040 // is possible. The isPredicated check is needed because this code can be
1041 // called during IfConversion, where an instruction which is normally a
1042 // Barrier is predicated and thus no longer an actual control barrier.
1043 return (empty() || !back().isBarrier() || TII->isPredicated(MI: back()))
1044 ? &*Fallthrough
1045 : nullptr;
1046 }
1047
1048 // If there is no branch, control always falls through.
1049 if (!TBB) return &*Fallthrough;
1050
1051 // If there is some explicit branch to the fallthrough block, it can obviously
1052 // reach, even though the branch should get folded to fall through implicitly.
1053 if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough ||
1054 MachineFunction::iterator(FBB) == Fallthrough))
1055 return &*Fallthrough;
1056
1057 // If it's an unconditional branch to some block not the fall through, it
1058 // doesn't fall through.
1059 if (Cond.empty()) return nullptr;
1060
1061 // Otherwise, if it is conditional and has no explicit false block, it falls
1062 // through.
1063 return (FBB == nullptr) ? &*Fallthrough : nullptr;
1064}
1065
1066bool MachineBasicBlock::canFallThrough() {
1067 return getFallThrough() != nullptr;
1068}
1069
1070MachineBasicBlock *MachineBasicBlock::splitAt(MachineInstr &MI,
1071 bool UpdateLiveIns,
1072 LiveIntervals *LIS) {
1073 MachineBasicBlock::iterator SplitPoint(&MI);
1074 ++SplitPoint;
1075
1076 if (SplitPoint == end()) {
1077 // Don't bother with a new block.
1078 return this;
1079 }
1080
1081 MachineFunction *MF = getParent();
1082
1083 LivePhysRegs LiveRegs;
1084 if (UpdateLiveIns) {
1085 // Make sure we add any physregs we define in the block as liveins to the
1086 // new block.
1087 MachineBasicBlock::iterator Prev(&MI);
1088 LiveRegs.init(TRI: *MF->getSubtarget().getRegisterInfo());
1089 LiveRegs.addLiveOuts(MBB: *this);
1090 for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I)
1091 LiveRegs.stepBackward(MI: *I);
1092 }
1093
1094 MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(BB: getBasicBlock());
1095
1096 MF->insert(MBBI: ++MachineFunction::iterator(this), MBB: SplitBB);
1097 SplitBB->splice(Where: SplitBB->begin(), Other: this, From: SplitPoint, To: end());
1098
1099 SplitBB->transferSuccessorsAndUpdatePHIs(FromMBB: this);
1100 addSuccessor(Succ: SplitBB);
1101
1102 if (UpdateLiveIns)
1103 addLiveIns(MBB&: *SplitBB, LiveRegs);
1104
1105 if (LIS)
1106 LIS->splitAt(Orig&: *this, SplitBB&: *SplitBB);
1107
1108 return SplitBB;
1109}
1110
1111// Returns `true` if there are possibly other users of the jump table at
1112// `JumpTableIndex` except for the ones in `IgnoreMBB`.
1113static bool jumpTableHasOtherUses(const MachineFunction &MF,
1114 const MachineBasicBlock &IgnoreMBB,
1115 int JumpTableIndex) {
1116 assert(JumpTableIndex >= 0 && "need valid index");
1117 const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo();
1118 const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex];
1119 // Take any basic block from the table; every user of the jump table must
1120 // show up in the predecessor list.
1121 const MachineBasicBlock *MBB = nullptr;
1122 for (MachineBasicBlock *B : MJTE.MBBs) {
1123 if (B != nullptr) {
1124 MBB = B;
1125 break;
1126 }
1127 }
1128 if (MBB == nullptr)
1129 return true; // can't rule out other users if there isn't any block.
1130 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1131 SmallVector<MachineOperand, 4> Cond;
1132 for (MachineBasicBlock *Pred : MBB->predecessors()) {
1133 if (Pred == &IgnoreMBB)
1134 continue;
1135 MachineBasicBlock *DummyT = nullptr;
1136 MachineBasicBlock *DummyF = nullptr;
1137 Cond.clear();
1138 if (!TII.analyzeBranch(MBB&: *Pred, TBB&: DummyT, FBB&: DummyF, Cond,
1139 /*AllowModify=*/false)) {
1140 // analyzable direct jump
1141 continue;
1142 }
1143 int PredJTI = findJumpTableIndex(MBB: *Pred);
1144 if (PredJTI >= 0) {
1145 if (PredJTI == JumpTableIndex)
1146 return true;
1147 continue;
1148 }
1149 // Be conservative for unanalyzable jumps.
1150 return true;
1151 }
1152 return false;
1153}
1154
1155class SlotIndexUpdateDelegate : public MachineFunction::Delegate {
1156private:
1157 MachineFunction &MF;
1158 SlotIndexes *Indexes;
1159 SmallSetVector<MachineInstr *, 2> Insertions;
1160
1161public:
1162 SlotIndexUpdateDelegate(MachineFunction &MF, SlotIndexes *Indexes)
1163 : MF(MF), Indexes(Indexes) {
1164 MF.setDelegate(this);
1165 }
1166
1167 ~SlotIndexUpdateDelegate() override {
1168 MF.resetDelegate(delegate: this);
1169 for (auto MI : Insertions)
1170 Indexes->insertMachineInstrInMaps(MI&: *MI);
1171 }
1172
1173 void MF_HandleInsertion(MachineInstr &MI) override {
1174 // This is called before MI is inserted into block so defer index update.
1175 if (Indexes)
1176 Insertions.insert(X: &MI);
1177 }
1178
1179 void MF_HandleRemoval(MachineInstr &MI) override {
1180 if (Indexes && !Insertions.remove(X: &MI))
1181 Indexes->removeMachineInstrFromMaps(MI);
1182 }
1183};
1184
1185MachineBasicBlock *
1186MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P,
1187 MachineFunctionAnalysisManager *MFAM,
1188 MachineDomTreeUpdater *MDTU) {
1189#define GET_RESULT(RESULT, GETTER, INFIX) \
1190 [MF, P, MFAM]() { \
1191 if (P) { \
1192 auto *Wrapper = P->getAnalysisIfAvailable<RESULT##INFIX##WrapperPass>(); \
1193 return Wrapper ? &Wrapper->GETTER() : nullptr; \
1194 } \
1195 return MFAM->getCachedResult<RESULT##Analysis>(*MF); \
1196 }()
1197
1198 assert((P || MFAM) && "Need a way to get analysis results!");
1199 MachineFunction *MF = getParent();
1200 LiveIntervals *LIS = GET_RESULT(LiveIntervals, getLIS, );
1201 SlotIndexes *Indexes = GET_RESULT(SlotIndexes, getSI, );
1202 MachineLoopInfo *MLI = GET_RESULT(MachineLoop, getLI, Info);
1203 return SplitCriticalEdge(Succ, Analyses: {.LIS: LIS, .SI: Indexes, .MLI: MLI}, MDTU);
1204#undef GET_RESULT
1205}
1206
1207MachineBasicBlock *
1208MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ,
1209 const SplitCriticalEdgeAnalyses &Analyses,
1210 MachineDomTreeUpdater *MDTU) {
1211 if (!canSplitCriticalEdge(Succ, MLI: Analyses.MLI))
1212 return nullptr;
1213
1214 MachineFunction *MF = getParent();
1215 MachineBasicBlock *PrevFallthrough = getNextNode();
1216
1217 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
1218 NMBB->setCallFrameSize(Succ->getCallFrameSize());
1219
1220 // Is there an indirect jump with jump table?
1221 bool ChangedIndirectJump = false;
1222 int JTI = findJumpTableIndex(MBB: *this);
1223 if (JTI >= 0) {
1224 MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo();
1225 MJTI.ReplaceMBBInJumpTable(Idx: JTI, Old: Succ, New: NMBB);
1226 ChangedIndirectJump = true;
1227 }
1228
1229 MF->insert(MBBI: std::next(x: MachineFunction::iterator(this)), MBB: NMBB);
1230 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
1231 << " -- " << printMBBReference(*NMBB) << " -- "
1232 << printMBBReference(*Succ) << '\n');
1233 auto *LIS = Analyses.LIS;
1234 if (LIS)
1235 LIS->insertMBBInMaps(MBB: NMBB);
1236 else if (Analyses.SI)
1237 Analyses.SI->insertMBBInMaps(mbb: NMBB);
1238
1239 SmallVector<Register, 4> UsedRegs;
1240 if (LIS) {
1241 for (MachineInstr &MI :
1242 llvm::make_range(x: getFirstInstrTerminator(), y: instr_end())) {
1243 for (const MachineOperand &MO : MI.operands()) {
1244 if (!MO.isReg() || MO.getReg() == 0)
1245 continue;
1246
1247 Register Reg = MO.getReg();
1248 if (!is_contained(Range&: UsedRegs, Element: Reg))
1249 UsedRegs.push_back(Elt: Reg);
1250 }
1251 }
1252 }
1253
1254 ReplaceUsesOfBlockWith(Old: Succ, New: NMBB);
1255
1256 // Since we replaced all uses of Succ with NMBB, that should also be treated
1257 // as the fallthrough successor
1258 if (Succ == PrevFallthrough)
1259 PrevFallthrough = NMBB;
1260 auto *Indexes = Analyses.SI;
1261 if (!ChangedIndirectJump) {
1262 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1263 updateTerminator(PreviousLayoutSuccessor: PrevFallthrough);
1264 }
1265
1266 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
1267 NMBB->addSuccessor(Succ);
1268 if (!NMBB->isLayoutSuccessor(MBB: Succ)) {
1269 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes);
1270 SmallVector<MachineOperand, 4> Cond;
1271 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
1272
1273 // In original 'this' BB, there must be a branch instruction targeting at
1274 // Succ. We can not find it out since currently getBranchDestBlock was not
1275 // implemented for all targets. However, if the merged DL has column or line
1276 // number, the scope and non-zero column and line number is same with that
1277 // branch instruction so we can safely use it.
1278 DebugLoc DL, MergedDL = findBranchDebugLoc();
1279 if (MergedDL && (MergedDL.getLine() || MergedDL.getCol()))
1280 DL = MergedDL;
1281 TII->insertBranch(MBB&: *NMBB, TBB: Succ, FBB: nullptr, Cond, DL);
1282 }
1283
1284 // Fix PHI nodes in Succ so they refer to NMBB instead of this, and find the
1285 // registers used from NMBB in them.
1286 SmallSet<Register, 8> PHISrcRegs;
1287 for (MachineInstr &MI : Succ->phis()) {
1288 for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
1289 MachineOperand &MBBOp = MI.getOperand(i: I + 1);
1290 if (MBBOp.getMBB() != this)
1291 continue;
1292 MBBOp.setMBB(NMBB);
1293 const MachineOperand &MO = MI.getOperand(i: I);
1294 if (LIS && !MO.isUndef())
1295 PHISrcRegs.insert(V: MO.getReg());
1296 }
1297 }
1298
1299 // Inherit live-ins from the successor
1300 for (const auto &LI : Succ->liveins())
1301 NMBB->addLiveIn(RegMaskPair: LI);
1302
1303 if (LIS) {
1304 // After splitting the edge and updating SlotIndexes, live intervals may be
1305 // in one of two situations, depending on whether this block was the last in
1306 // the function. If the original block was the last in the function, all
1307 // live intervals will end prior to the beginning of the new split block. If
1308 // the original block was not at the end of the function, all live intervals
1309 // will extend to the end of the new split block.
1310
1311 bool isLastMBB =
1312 std::next(x: MachineFunction::iterator(NMBB)) == getParent()->end();
1313
1314 SlotIndex StartIndex = Indexes->getMBBEndIdx(mbb: this);
1315 SlotIndex PrevIndex = StartIndex.getPrevSlot();
1316 SlotIndex EndIndex = Indexes->getMBBEndIdx(mbb: NMBB);
1317
1318 for (Register Reg : PHISrcRegs) {
1319 LiveInterval &LI = LIS->getInterval(Reg);
1320 VNInfo *VNI = LI.getVNInfoAt(Idx: PrevIndex);
1321 assert(VNI && "PHI sources should be live out of their predecessors.");
1322 LI.addSegment(S: LiveInterval::Segment(StartIndex, EndIndex, VNI));
1323 for (auto &SR : LI.subranges()) {
1324 if (VNInfo *SRVNI = SR.getVNInfoAt(Idx: PrevIndex))
1325 SR.addSegment(S: LiveInterval::Segment(StartIndex, EndIndex, SRVNI));
1326 }
1327 }
1328
1329 auto UpdateLiveOutReg = [&](Register Reg) {
1330 if (PHISrcRegs.count(V: Reg))
1331 return true;
1332 if (!LIS->hasInterval(Reg))
1333 return false;
1334
1335 LiveInterval &LI = LIS->getInterval(Reg);
1336 if (!LI.liveAt(index: PrevIndex))
1337 return false;
1338
1339 bool isLiveOut = LI.liveAt(index: LIS->getMBBStartIdx(mbb: Succ));
1340 if (isLiveOut && isLastMBB) {
1341 VNInfo *VNI = LI.getVNInfoAt(Idx: PrevIndex);
1342 assert(VNI && "LiveInterval should have VNInfo where it is live.");
1343 LI.addSegment(S: LiveInterval::Segment(StartIndex, EndIndex, VNI));
1344 // Update subranges with live values
1345 for (auto &SR : LI.subranges()) {
1346 VNInfo *VNI = SR.getVNInfoAt(Idx: PrevIndex);
1347 if (VNI)
1348 SR.addSegment(S: LiveInterval::Segment(StartIndex, EndIndex, VNI));
1349 }
1350 } else if (!isLiveOut && !isLastMBB) {
1351 LI.removeSegment(Start: StartIndex, End: EndIndex);
1352 // The main range is live across NMBB, but an individual lane need not
1353 // be.
1354 for (auto &SR : LI.subranges()) {
1355 if (SR.liveAt(index: PrevIndex))
1356 SR.removeSegment(Start: StartIndex, End: EndIndex);
1357 }
1358 }
1359 return isLiveOut;
1360 };
1361
1362 if (std::vector<SparseBitVector<>> *LiveOutSets = Analyses.LiveOutSets) {
1363 LiveOutSets->resize(new_size: MF->getNumBlockIDs());
1364 const SparseBitVector<> &LiveOut = (*LiveOutSets)[getNumber()];
1365 SparseBitVector<> &NewLiveOut = (*LiveOutSets)[NMBB->getNumber()];
1366 for (unsigned Idx : LiveOut) {
1367 if (UpdateLiveOutReg(Register::index2VirtReg(Index: Idx)))
1368 NewLiveOut.set(Idx);
1369 }
1370 } else {
1371 MachineRegisterInfo *MRI = &getParent()->getRegInfo();
1372 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i)
1373 UpdateLiveOutReg(Register::index2VirtReg(Index: i));
1374 }
1375
1376 // Update all intervals for registers whose uses may have been modified by
1377 // updateTerminator().
1378 LIS->repairIntervalsInRange(MBB: this, Begin: getFirstTerminator(), End: end(), OrigRegs: UsedRegs);
1379
1380 // repairIntervalsInRange() does not update physregs; clear their ranges
1381 // since updateTerminator() may have replaced defs.
1382 for (Register Reg : UsedRegs) {
1383 if (Reg.isPhysical())
1384 LIS->removeAllRegUnitsForPhysReg(Reg: Reg.asMCReg());
1385 }
1386 }
1387
1388 if (MDTU)
1389 MDTU->splitCriticalEdge(FromBB: this, ToBB: Succ, NewBB: NMBB);
1390
1391 if (MachineLoopInfo *MLI = Analyses.MLI)
1392 if (MachineLoop *TIL = MLI->getLoopFor(BB: this)) {
1393 // If one or the other blocks were not in a loop, the new block is not
1394 // either, and thus LI doesn't need to be updated.
1395 if (MachineLoop *DestLoop = MLI->getLoopFor(BB: Succ)) {
1396 if (TIL == DestLoop) {
1397 // Both in the same loop, the NMBB joins loop.
1398 DestLoop->addBasicBlockToLoop(NewBB: NMBB, LI&: *MLI);
1399 } else if (TIL->contains(L: DestLoop)) {
1400 // Edge from an outer loop to an inner loop. Add to the outer loop.
1401 TIL->addBasicBlockToLoop(NewBB: NMBB, LI&: *MLI);
1402 } else if (DestLoop->contains(L: TIL)) {
1403 // Edge from an inner loop to an outer loop. Add to the outer loop.
1404 DestLoop->addBasicBlockToLoop(NewBB: NMBB, LI&: *MLI);
1405 } else {
1406 // Edge from two loops with no containment relation. Because these
1407 // are natural loops, we know that the destination block must be the
1408 // header of its loop (adding a branch into a loop elsewhere would
1409 // create an irreducible loop).
1410 assert(DestLoop->getHeader() == Succ &&
1411 "Should not create irreducible loops!");
1412 if (MachineLoop *P = DestLoop->getParentLoop())
1413 P->addBasicBlockToLoop(NewBB: NMBB, LI&: *MLI);
1414 }
1415 }
1416 }
1417
1418 return NMBB;
1419}
1420
1421bool MachineBasicBlock::canSplitCriticalEdge(const MachineBasicBlock *Succ,
1422 const MachineLoopInfo *MLI) const {
1423 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1424 // it in this generic function.
1425 if (Succ->isEHPad())
1426 return false;
1427
1428 // Splitting the critical edge to a callbr's indirect block isn't advised.
1429 // Don't do it in this generic function.
1430 if (Succ->isInlineAsmBrIndirectTarget())
1431 return false;
1432
1433 const MachineFunction *MF = getParent();
1434 // Performance might be harmed on HW that implements branching using exec mask
1435 // where both sides of the branches are always executed.
1436
1437 if (MF->getTarget().requiresStructuredCFG()) {
1438 if (!MLI)
1439 return false;
1440 const MachineLoop *L = MLI->getLoopFor(BB: Succ);
1441 // Only if `Succ` is a loop header, splitting the critical edge will not
1442 // break structured CFG. And fallthrough to check if this's terminator is
1443 // analyzable.
1444 if (!L || L->getHeader() != Succ)
1445 return false;
1446 }
1447
1448 // Do we have an Indirect jump with a jumptable that we can rewrite?
1449 int JTI = findJumpTableIndex(MBB: *this);
1450 if (JTI >= 0 && !jumpTableHasOtherUses(MF: *MF, IgnoreMBB: *this, JumpTableIndex: JTI))
1451 return true;
1452
1453 // We may need to update this's terminator, but we can't do that if
1454 // analyzeBranch fails.
1455 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1456 const MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1457 SmallVector<MachineOperand, 4> Cond;
1458 // AnalyzeBanch should modify this, since we did not allow modification.
1459 if (TII->analyzeBranch(MBB: *this, TBB, FBB, Cond))
1460 return false;
1461
1462 // Handle weird inputs (e.g., generated by a test case reducer/fuzzer): A
1463 // block may end with a conditional branch but jumps to the same MBB is either
1464 // case. We have duplicate CFG edges in that case that we can't handle. Since
1465 // this never happens in properly optimized code, just skip those edges.
1466 if (TBB && TBB == FBB) {
1467 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1468 << printMBBReference(*this) << '\n');
1469 return false;
1470 }
1471 return true;
1472}
1473
1474/// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1475/// neighboring instructions so the bundle won't be broken by removing MI.
1476static void unbundleSingleMI(MachineInstr *MI) {
1477 // Removing the first instruction in a bundle.
1478 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1479 MI->unbundleFromSucc();
1480 // Removing the last instruction in a bundle.
1481 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1482 MI->unbundleFromPred();
1483 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1484 // are already fine.
1485}
1486
1487MachineBasicBlock::instr_iterator
1488MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
1489 unbundleSingleMI(MI: &*I);
1490 return Insts.erase(where: I);
1491}
1492
1493MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1494 unbundleSingleMI(MI);
1495 MI->clearFlag(Flag: MachineInstr::BundledPred);
1496 MI->clearFlag(Flag: MachineInstr::BundledSucc);
1497 return Insts.remove(IT: MI);
1498}
1499
1500MachineBasicBlock::instr_iterator
1501MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1502 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1503 "Cannot insert instruction with bundle flags");
1504 // Set the bundle flags when inserting inside a bundle.
1505 if (I != instr_end() && I->isBundledWithPred()) {
1506 MI->setFlag(MachineInstr::BundledPred);
1507 MI->setFlag(MachineInstr::BundledSucc);
1508 }
1509 return Insts.insert(where: I, New: MI);
1510}
1511
1512/// This method unlinks 'this' from the containing function, and returns it, but
1513/// does not delete it.
1514MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1515 assert(getParent() && "Not embedded in a function!");
1516 getParent()->remove(MBBI: this);
1517 return this;
1518}
1519
1520/// This method unlinks 'this' from the containing function, and deletes it.
1521void MachineBasicBlock::eraseFromParent() {
1522 assert(getParent() && "Not embedded in a function!");
1523 getParent()->erase(MBBI: this);
1524}
1525
1526/// Given a machine basic block that branched to 'Old', change the code and CFG
1527/// so that it branches to 'New' instead.
1528void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1529 MachineBasicBlock *New) {
1530 assert(Old != New && "Cannot replace self with self!");
1531
1532 MachineBasicBlock::instr_iterator I = instr_end();
1533 while (I != instr_begin()) {
1534 --I;
1535 if (!I->isTerminator()) break;
1536
1537 // Scan the operands of this machine instruction, replacing any uses of Old
1538 // with New.
1539 for (MachineOperand &MO : I->operands())
1540 if (MO.isMBB() && MO.getMBB() == Old)
1541 MO.setMBB(New);
1542 }
1543
1544 // Update the successor information.
1545 replaceSuccessor(Old, New);
1546}
1547
1548void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old,
1549 MachineBasicBlock *New) {
1550 for (MachineInstr &MI : phis())
1551 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
1552 MachineOperand &MO = MI.getOperand(i);
1553 if (MO.getMBB() == Old)
1554 MO.setMBB(New);
1555 }
1556}
1557
1558/// Find the next valid DebugLoc starting at MBBI, skipping any debug
1559/// instructions. Return UnknownLoc if there is none.
1560DebugLoc
1561MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1562 // Skip debug declarations, we don't want a DebugLoc from them.
1563 MBBI = skipDebugInstructionsForward(It: MBBI, End: instr_end());
1564 if (MBBI != instr_end())
1565 return MBBI->getDebugLoc();
1566 return {};
1567}
1568
1569DebugLoc MachineBasicBlock::rfindDebugLoc(reverse_instr_iterator MBBI) {
1570 if (MBBI == instr_rend())
1571 return findDebugLoc(MBBI: instr_begin());
1572 // Skip debug declarations, we don't want a DebugLoc from them.
1573 MBBI = skipDebugInstructionsBackward(It: MBBI, Begin: instr_rbegin());
1574 if (!MBBI->isDebugInstr())
1575 return MBBI->getDebugLoc();
1576 return {};
1577}
1578
1579/// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1580/// instructions. Return UnknownLoc if there is none.
1581DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) {
1582 if (MBBI == instr_begin())
1583 return {};
1584 // Skip debug instructions, we don't want a DebugLoc from them.
1585 MBBI = prev_nodbg(It: MBBI, Begin: instr_begin());
1586 if (!MBBI->isDebugInstr())
1587 return MBBI->getDebugLoc();
1588 return {};
1589}
1590
1591DebugLoc MachineBasicBlock::rfindPrevDebugLoc(reverse_instr_iterator MBBI) {
1592 if (MBBI == instr_rend())
1593 return {};
1594 // Skip debug declarations, we don't want a DebugLoc from them.
1595 MBBI = next_nodbg(It: MBBI, End: instr_rend());
1596 if (MBBI != instr_rend())
1597 return MBBI->getDebugLoc();
1598 return {};
1599}
1600
1601/// Find and return the merged DebugLoc of the branch instructions of the block.
1602/// Return UnknownLoc if there is none.
1603DebugLoc
1604MachineBasicBlock::findBranchDebugLoc() {
1605 DebugLoc DL;
1606 auto TI = getFirstTerminator();
1607 while (TI != end() && !TI->isBranch())
1608 ++TI;
1609
1610 if (TI != end()) {
1611 DL = TI->getDebugLoc();
1612 for (++TI ; TI != end() ; ++TI)
1613 if (TI->isBranch())
1614 DL = DebugLoc::getMergedLocation(LocA: DL, LocB: TI->getDebugLoc());
1615 }
1616 return DL;
1617}
1618
1619/// Return probability of the edge from this block to MBB.
1620BranchProbability
1621MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1622 if (Probs.empty())
1623 return BranchProbability(1, succ_size());
1624
1625 const auto &Prob = *getProbabilityIterator(I: Succ);
1626 if (!Prob.isUnknown())
1627 return Prob;
1628 // For unknown probabilities, collect the sum of all known ones, and evenly
1629 // ditribute the complemental of the sum to each unknown probability.
1630 unsigned KnownProbNum = 0;
1631 auto Sum = BranchProbability::getZero();
1632 for (const auto &P : Probs) {
1633 if (!P.isUnknown()) {
1634 Sum += P;
1635 KnownProbNum++;
1636 }
1637 }
1638 return Sum.getCompl() / (Probs.size() - KnownProbNum);
1639}
1640
1641bool MachineBasicBlock::canPredictBranchProbabilities() const {
1642 if (succ_size() <= 1)
1643 return true;
1644 if (!hasSuccessorProbabilities())
1645 return true;
1646
1647 SmallVector<BranchProbability, 8> Normalized(Probs.begin(), Probs.end());
1648 BranchProbability::normalizeProbabilities(R&: Normalized);
1649
1650 // Normalize assuming unknown probabilities. This will assign equal
1651 // probabilities to all successors.
1652 SmallVector<BranchProbability, 8> Equal(Normalized.size());
1653 BranchProbability::normalizeProbabilities(R&: Equal);
1654
1655 return llvm::equal(LRange&: Normalized, RRange&: Equal);
1656}
1657
1658/// Set successor probability of a given iterator.
1659void MachineBasicBlock::setSuccProbability(succ_iterator I,
1660 BranchProbability Prob) {
1661 assert(!Prob.isUnknown());
1662 if (Probs.empty())
1663 return;
1664 *getProbabilityIterator(I) = Prob;
1665}
1666
1667/// Return probability iterator corresonding to the I successor iterator
1668MachineBasicBlock::const_probability_iterator
1669MachineBasicBlock::getProbabilityIterator(
1670 MachineBasicBlock::const_succ_iterator I) const {
1671 assert(Probs.size() == Successors.size() && "Async probability list!");
1672 const size_t index = std::distance(first: Successors.begin(), last: I);
1673 assert(index < Probs.size() && "Not a current successor!");
1674 return Probs.begin() + index;
1675}
1676
1677/// Return probability iterator corresonding to the I successor iterator.
1678MachineBasicBlock::probability_iterator
1679MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1680 assert(Probs.size() == Successors.size() && "Async probability list!");
1681 const size_t index = std::distance(first: Successors.begin(), last: I);
1682 assert(index < Probs.size() && "Not a current successor!");
1683 return Probs.begin() + index;
1684}
1685
1686/// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1687/// as of just before "MI".
1688///
1689/// Search is localised to a neighborhood of
1690/// Neighborhood instructions before (searching for defs or kills) and N
1691/// instructions after (searching just for defs) MI.
1692MachineBasicBlock::LivenessQueryResult
1693MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1694 MCRegister Reg, const_iterator Before,
1695 unsigned Neighborhood) const {
1696 assert(Reg.isPhysical());
1697 unsigned N = Neighborhood;
1698
1699 // Try searching forwards from Before, looking for reads or defs.
1700 const_iterator I(Before);
1701 for (; I != end() && N > 0; ++I) {
1702 if (I->isDebugOrPseudoInstr())
1703 continue;
1704
1705 --N;
1706
1707 PhysRegInfo Info = AnalyzePhysRegInBundle(MI: *I, Reg, TRI);
1708
1709 // Register is live when we read it here.
1710 if (Info.Read)
1711 return LQR_Live;
1712 // Register is dead if we can fully overwrite or clobber it here.
1713 if (Info.FullyDefined || Info.Clobbered)
1714 return LQR_Dead;
1715 }
1716
1717 // If we reached the end, it is safe to clobber Reg at the end of a block of
1718 // no successor has it live in.
1719 if (I == end()) {
1720 for (MachineBasicBlock *S : successors()) {
1721 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1722 if (TRI->regsOverlap(RegA: LI.PhysReg, RegB: Reg))
1723 return LQR_Live;
1724 }
1725 }
1726
1727 return LQR_Dead;
1728 }
1729
1730
1731 N = Neighborhood;
1732
1733 // Start by searching backwards from Before, looking for kills, reads or defs.
1734 I = const_iterator(Before);
1735 // If this is the first insn in the block, don't search backwards.
1736 if (I != begin()) {
1737 do {
1738 --I;
1739
1740 if (I->isDebugOrPseudoInstr())
1741 continue;
1742
1743 --N;
1744
1745 PhysRegInfo Info = AnalyzePhysRegInBundle(MI: *I, Reg, TRI);
1746
1747 // Defs happen after uses so they take precedence if both are present.
1748
1749 // Register is dead after a dead def of the full register.
1750 if (Info.DeadDef)
1751 return LQR_Dead;
1752 // Register is (at least partially) live after a def.
1753 if (Info.Defined) {
1754 if (!Info.PartialDeadDef)
1755 return LQR_Live;
1756 // As soon as we saw a partial definition (dead or not),
1757 // we cannot tell if the value is partial live without
1758 // tracking the lanemasks. We are not going to do this,
1759 // so fall back on the remaining of the analysis.
1760 break;
1761 }
1762 // Register is dead after a full kill or clobber and no def.
1763 if (Info.Killed || Info.Clobbered)
1764 return LQR_Dead;
1765 // Register must be live if we read it.
1766 if (Info.Read)
1767 return LQR_Live;
1768
1769 } while (I != begin() && N > 0);
1770 }
1771
1772 // If all the instructions before this in the block are debug instructions,
1773 // skip over them.
1774 while (I != begin() && std::prev(x: I)->isDebugOrPseudoInstr())
1775 --I;
1776
1777 // Did we get to the start of the block?
1778 if (I == begin()) {
1779 // If so, the register's state is definitely defined by the live-in state.
1780 for (const MachineBasicBlock::RegisterMaskPair &LI : liveins())
1781 if (TRI->regsOverlap(RegA: LI.PhysReg, RegB: Reg))
1782 return LQR_Live;
1783
1784 return LQR_Dead;
1785 }
1786
1787 // At this point we have no idea of the liveness of the register.
1788 return LQR_Unknown;
1789}
1790
1791const uint32_t *
1792MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1793 // EH funclet entry does not preserve any registers.
1794 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1795}
1796
1797const uint32_t *
1798MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1799 // If we see a return block with successors, this must be a funclet return,
1800 // which does not preserve any registers. If there are no successors, we don't
1801 // care what kind of return it is, putting a mask after it is a no-op.
1802 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1803}
1804
1805void MachineBasicBlock::clearLiveIns() {
1806 LiveIns.clear();
1807}
1808
1809void MachineBasicBlock::clearLiveIns(
1810 std::vector<RegisterMaskPair> &OldLiveIns) {
1811 assert(OldLiveIns.empty() && "Vector must be empty");
1812 std::swap(x&: LiveIns, y&: OldLiveIns);
1813}
1814
1815MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
1816 assert(getParent()->getProperties().hasTracksLiveness() &&
1817 "Liveness information is accurate");
1818 return LiveIns.begin();
1819}
1820
1821MachineBasicBlock::liveout_iterator MachineBasicBlock::liveout_begin() const {
1822 const MachineFunction &MF = *getParent();
1823 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1824 MCRegister ExceptionPointer, ExceptionSelector;
1825 if (MF.getFunction().hasPersonalityFn()) {
1826 auto PersonalityFn = MF.getFunction().getPersonalityFn();
1827 // Prefer the "exception-model" module flag, else the TargetOptions default.
1828 ExceptionHandling EH = MF.getFunction().getParent()->getExceptionModel();
1829 if (EH == ExceptionHandling::Default)
1830 EH = TLI.getTargetMachine().getExceptionModel();
1831 ExceptionPointer = TLI.getExceptionPointerRegister(EH, PersonalityFn);
1832 ExceptionSelector = TLI.getExceptionSelectorRegister(EH, PersonalityFn);
1833 }
1834
1835 return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false);
1836}
1837
1838bool MachineBasicBlock::sizeWithoutDebugLargerThan(unsigned Limit) const {
1839 unsigned Cntr = 0;
1840 auto R = instructionsWithoutDebug(It: begin(), End: end());
1841 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1842 if (++Cntr > Limit)
1843 return true;
1844 }
1845 return false;
1846}
1847
1848void MachineBasicBlock::removePHIsIncomingValuesForPredecessor(
1849 const MachineBasicBlock &PredMBB) {
1850 for (MachineInstr &Phi : phis())
1851 Phi.removePHIIncomingValueFor(MBB: PredMBB);
1852}
1853
1854const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold);
1855const MBBSectionID
1856 MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception);
1857