1f22ef01cSRoman Divacky //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // Collect the sequence of machine instructions for a basic block.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineBasicBlock.h"
15139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
16139f7f9bSDimitry Andric #include "llvm/CodeGen/LiveIntervalAnalysis.h"
17ffd1746dSEd Schouten #include "llvm/CodeGen/LiveVariables.h"
18ffd1746dSEd Schouten #include "llvm/CodeGen/MachineDominators.h"
19f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineFunction.h"
20*6beeb091SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
21ffd1746dSEd Schouten #include "llvm/CodeGen/MachineLoopInfo.h"
22139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
232754fe60SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
24139f7f9bSDimitry Andric #include "llvm/IR/BasicBlock.h"
25139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
263dac3a9bSDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
27f22ef01cSRoman Divacky #include "llvm/MC/MCAsmInfo.h"
28f22ef01cSRoman Divacky #include "llvm/MC/MCContext.h"
297d523365SDimitry Andric #include "llvm/Support/DataTypes.h"
30f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
31f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
32139f7f9bSDimitry Andric #include "llvm/Target/TargetInstrInfo.h"
33139f7f9bSDimitry Andric #include "llvm/Target/TargetMachine.h"
34139f7f9bSDimitry Andric #include "llvm/Target/TargetRegisterInfo.h"
3539d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
36f22ef01cSRoman Divacky #include <algorithm>
37f22ef01cSRoman Divacky using namespace llvm;
38f22ef01cSRoman Divacky 
3991bc56edSDimitry Andric #define DEBUG_TYPE "codegen"
4091bc56edSDimitry Andric 
417d523365SDimitry Andric MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
427d523365SDimitry Andric     : BB(B), Number(-1), xParent(&MF) {
43f22ef01cSRoman Divacky   Insts.Parent = this;
44f22ef01cSRoman Divacky }
45f22ef01cSRoman Divacky 
46f22ef01cSRoman Divacky MachineBasicBlock::~MachineBasicBlock() {
47f22ef01cSRoman Divacky }
48f22ef01cSRoman Divacky 
497d523365SDimitry Andric /// Return the MCSymbol for this basic block.
50f22ef01cSRoman Divacky MCSymbol *MachineBasicBlock::getSymbol() const {
51284c1978SDimitry Andric   if (!CachedMCSymbol) {
52f22ef01cSRoman Divacky     const MachineFunction *MF = getParent();
53f22ef01cSRoman Divacky     MCContext &Ctx = MF->getContext();
5439d628a0SDimitry Andric     const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
557d523365SDimitry Andric     assert(getNumber() >= 0 && "cannot get label for unreachable MBB");
56ff0cc061SDimitry Andric     CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
57284c1978SDimitry Andric                                            Twine(MF->getFunctionNumber()) +
58284c1978SDimitry Andric                                            "_" + Twine(getNumber()));
59284c1978SDimitry Andric   }
60284c1978SDimitry Andric 
61284c1978SDimitry Andric   return CachedMCSymbol;
62f22ef01cSRoman Divacky }
63f22ef01cSRoman Divacky 
64f22ef01cSRoman Divacky 
65f22ef01cSRoman Divacky raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
66f22ef01cSRoman Divacky   MBB.print(OS);
67f22ef01cSRoman Divacky   return OS;
68f22ef01cSRoman Divacky }
69f22ef01cSRoman Divacky 
707d523365SDimitry Andric /// When an MBB is added to an MF, we need to update the parent pointer of the
717d523365SDimitry Andric /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
727d523365SDimitry Andric /// operand list for registers.
73f22ef01cSRoman Divacky ///
74f22ef01cSRoman Divacky /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
75f22ef01cSRoman Divacky /// gets the next available unique MBB number. If it is removed from a
76f22ef01cSRoman Divacky /// MachineFunction, it goes back to being #-1.
77f22ef01cSRoman Divacky void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
78f22ef01cSRoman Divacky   MachineFunction &MF = *N->getParent();
79f22ef01cSRoman Divacky   N->Number = MF.addToMBBNumbering(N);
80f22ef01cSRoman Divacky 
81f22ef01cSRoman Divacky   // Make sure the instructions have their operands in the reginfo lists.
82f22ef01cSRoman Divacky   MachineRegisterInfo &RegInfo = MF.getRegInfo();
83dff0c46cSDimitry Andric   for (MachineBasicBlock::instr_iterator
84dff0c46cSDimitry Andric          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
85f22ef01cSRoman Divacky     I->AddRegOperandsToUseLists(RegInfo);
86f22ef01cSRoman Divacky }
87f22ef01cSRoman Divacky 
88f22ef01cSRoman Divacky void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
89f22ef01cSRoman Divacky   N->getParent()->removeFromMBBNumbering(N->Number);
90f22ef01cSRoman Divacky   N->Number = -1;
91f22ef01cSRoman Divacky }
92f22ef01cSRoman Divacky 
937d523365SDimitry Andric /// When we add an instruction to a basic block list, we update its parent
947d523365SDimitry Andric /// pointer and add its operands from reg use/def lists if appropriate.
95f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
9691bc56edSDimitry Andric   assert(!N->getParent() && "machine instruction already in a basic block");
97f22ef01cSRoman Divacky   N->setParent(Parent);
98f22ef01cSRoman Divacky 
99f22ef01cSRoman Divacky   // Add the instruction's register operands to their corresponding
100f22ef01cSRoman Divacky   // use/def lists.
101f22ef01cSRoman Divacky   MachineFunction *MF = Parent->getParent();
102f22ef01cSRoman Divacky   N->AddRegOperandsToUseLists(MF->getRegInfo());
103f22ef01cSRoman Divacky }
104f22ef01cSRoman Divacky 
1057d523365SDimitry Andric /// When we remove an instruction from a basic block list, we update its parent
1067d523365SDimitry Andric /// pointer and remove its operands from reg use/def lists if appropriate.
107f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
10891bc56edSDimitry Andric   assert(N->getParent() && "machine instruction not in a basic block");
109f22ef01cSRoman Divacky 
110f22ef01cSRoman Divacky   // Remove from the use/def lists.
1117ae0e2c9SDimitry Andric   if (MachineFunction *MF = N->getParent()->getParent())
1127ae0e2c9SDimitry Andric     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
113f22ef01cSRoman Divacky 
11491bc56edSDimitry Andric   N->setParent(nullptr);
115f22ef01cSRoman Divacky }
116f22ef01cSRoman Divacky 
1177d523365SDimitry Andric /// When moving a range of instructions from one MBB list to another, we need to
1187d523365SDimitry Andric /// update the parent pointers and the use/def lists.
119f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::
1207d523365SDimitry Andric transferNodesFromList(ilist_traits<MachineInstr> &FromList,
1217d523365SDimitry Andric                       ilist_iterator<MachineInstr> First,
1227d523365SDimitry Andric                       ilist_iterator<MachineInstr> Last) {
1237d523365SDimitry Andric   assert(Parent->getParent() == FromList.Parent->getParent() &&
124f22ef01cSRoman Divacky         "MachineInstr parent mismatch!");
125f22ef01cSRoman Divacky 
126f22ef01cSRoman Divacky   // Splice within the same MBB -> no change.
1277d523365SDimitry Andric   if (Parent == FromList.Parent) return;
128f22ef01cSRoman Divacky 
129f22ef01cSRoman Divacky   // If splicing between two blocks within the same function, just update the
130f22ef01cSRoman Divacky   // parent pointers.
1317d523365SDimitry Andric   for (; First != Last; ++First)
1327d523365SDimitry Andric     First->setParent(Parent);
133f22ef01cSRoman Divacky }
134f22ef01cSRoman Divacky 
135f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
136f22ef01cSRoman Divacky   assert(!MI->getParent() && "MI is still in a block!");
137f22ef01cSRoman Divacky   Parent->getParent()->DeleteMachineInstr(MI);
138f22ef01cSRoman Divacky }
139f22ef01cSRoman Divacky 
140ffd1746dSEd Schouten MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
141dff0c46cSDimitry Andric   instr_iterator I = instr_begin(), E = instr_end();
142dff0c46cSDimitry Andric   while (I != E && I->isPHI())
143ffd1746dSEd Schouten     ++I;
1443861d79fSDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
1453861d79fSDimitry Andric          "First non-phi MI cannot be inside a bundle!");
146ffd1746dSEd Schouten   return I;
147ffd1746dSEd Schouten }
148ffd1746dSEd Schouten 
1492754fe60SDimitry Andric MachineBasicBlock::iterator
1502754fe60SDimitry Andric MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
151dff0c46cSDimitry Andric   iterator E = end();
15291bc56edSDimitry Andric   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
1532754fe60SDimitry Andric     ++I;
154dff0c46cSDimitry Andric   // FIXME: This needs to change if we wish to bundle labels / dbg_values
155dff0c46cSDimitry Andric   // inside the bundle.
1563861d79fSDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
157dff0c46cSDimitry Andric          "First non-phi / non-label instruction is inside a bundle!");
1582754fe60SDimitry Andric   return I;
1592754fe60SDimitry Andric }
1602754fe60SDimitry Andric 
161f22ef01cSRoman Divacky MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
162dff0c46cSDimitry Andric   iterator B = begin(), E = end(), I = E;
163dff0c46cSDimitry Andric   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
164f22ef01cSRoman Divacky     ; /*noop */
165dff0c46cSDimitry Andric   while (I != E && !I->isTerminator())
166dff0c46cSDimitry Andric     ++I;
167dff0c46cSDimitry Andric   return I;
168dff0c46cSDimitry Andric }
169dff0c46cSDimitry Andric 
170dff0c46cSDimitry Andric MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
171dff0c46cSDimitry Andric   instr_iterator B = instr_begin(), E = instr_end(), I = E;
172dff0c46cSDimitry Andric   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
173dff0c46cSDimitry Andric     ; /*noop */
174dff0c46cSDimitry Andric   while (I != E && !I->isTerminator())
1752754fe60SDimitry Andric     ++I;
176f22ef01cSRoman Divacky   return I;
177f22ef01cSRoman Divacky }
178f22ef01cSRoman Divacky 
1793dac3a9bSDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
1803dac3a9bSDimitry Andric   // Skip over begin-of-block dbg_value instructions.
1813dac3a9bSDimitry Andric   iterator I = begin(), E = end();
1823dac3a9bSDimitry Andric   while (I != E && I->isDebugValue())
1833dac3a9bSDimitry Andric     ++I;
1843dac3a9bSDimitry Andric   return I;
1853dac3a9bSDimitry Andric }
1863dac3a9bSDimitry Andric 
1872754fe60SDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
188dff0c46cSDimitry Andric   // Skip over end-of-block dbg_value instructions.
189dff0c46cSDimitry Andric   instr_iterator B = instr_begin(), I = instr_end();
1902754fe60SDimitry Andric   while (I != B) {
1912754fe60SDimitry Andric     --I;
192dff0c46cSDimitry Andric     // Return instruction that starts a bundle.
193dff0c46cSDimitry Andric     if (I->isDebugValue() || I->isInsideBundle())
194dff0c46cSDimitry Andric       continue;
195dff0c46cSDimitry Andric     return I;
196dff0c46cSDimitry Andric   }
197dff0c46cSDimitry Andric   // The block is all debug values.
198dff0c46cSDimitry Andric   return end();
199dff0c46cSDimitry Andric }
200dff0c46cSDimitry Andric 
2017d523365SDimitry Andric bool MachineBasicBlock::hasEHPadSuccessor() const {
2027d523365SDimitry Andric   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
2037d523365SDimitry Andric     if ((*I)->isEHPad())
2047d523365SDimitry Andric       return true;
2057d523365SDimitry Andric   return false;
2067d523365SDimitry Andric }
2077d523365SDimitry Andric 
2083861d79fSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2093ca95b02SDimitry Andric LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
210f22ef01cSRoman Divacky   print(dbgs());
211f22ef01cSRoman Divacky }
2123861d79fSDimitry Andric #endif
213f22ef01cSRoman Divacky 
214f22ef01cSRoman Divacky StringRef MachineBasicBlock::getName() const {
215f22ef01cSRoman Divacky   if (const BasicBlock *LBB = getBasicBlock())
216f22ef01cSRoman Divacky     return LBB->getName();
217f22ef01cSRoman Divacky   else
218f22ef01cSRoman Divacky     return "(null)";
219f22ef01cSRoman Divacky }
220f22ef01cSRoman Divacky 
221dff0c46cSDimitry Andric /// Return a hopefully unique identifier for this block.
222dff0c46cSDimitry Andric std::string MachineBasicBlock::getFullName() const {
223dff0c46cSDimitry Andric   std::string Name;
224dff0c46cSDimitry Andric   if (getParent())
2253861d79fSDimitry Andric     Name = (getParent()->getName() + ":").str();
226dff0c46cSDimitry Andric   if (getBasicBlock())
227dff0c46cSDimitry Andric     Name += getBasicBlock()->getName();
228dff0c46cSDimitry Andric   else
229ff0cc061SDimitry Andric     Name += ("BB" + Twine(getNumber())).str();
230dff0c46cSDimitry Andric   return Name;
231dff0c46cSDimitry Andric }
232dff0c46cSDimitry Andric 
2333ca95b02SDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes)
2343ca95b02SDimitry Andric     const {
235f22ef01cSRoman Divacky   const MachineFunction *MF = getParent();
236f22ef01cSRoman Divacky   if (!MF) {
237f22ef01cSRoman Divacky     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
238f22ef01cSRoman Divacky        << " is null\n";
239f22ef01cSRoman Divacky     return;
240f22ef01cSRoman Divacky   }
2413dac3a9bSDimitry Andric   const Function *F = MF->getFunction();
2423dac3a9bSDimitry Andric   const Module *M = F ? F->getParent() : nullptr;
2433dac3a9bSDimitry Andric   ModuleSlotTracker MST(M);
2443dac3a9bSDimitry Andric   print(OS, MST, Indexes);
2453dac3a9bSDimitry Andric }
2463dac3a9bSDimitry Andric 
2473dac3a9bSDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
2483ca95b02SDimitry Andric                               const SlotIndexes *Indexes) const {
2493dac3a9bSDimitry Andric   const MachineFunction *MF = getParent();
2503dac3a9bSDimitry Andric   if (!MF) {
2513dac3a9bSDimitry Andric     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
2523dac3a9bSDimitry Andric        << " is null\n";
2533dac3a9bSDimitry Andric     return;
2543dac3a9bSDimitry Andric   }
255f22ef01cSRoman Divacky 
2562754fe60SDimitry Andric   if (Indexes)
2572754fe60SDimitry Andric     OS << Indexes->getMBBStartIdx(this) << '\t';
2582754fe60SDimitry Andric 
259f22ef01cSRoman Divacky   OS << "BB#" << getNumber() << ": ";
260f22ef01cSRoman Divacky 
261f22ef01cSRoman Divacky   const char *Comma = "";
262f22ef01cSRoman Divacky   if (const BasicBlock *LBB = getBasicBlock()) {
263f22ef01cSRoman Divacky     OS << Comma << "derived from LLVM BB ";
2643dac3a9bSDimitry Andric     LBB->printAsOperand(OS, /*PrintType=*/false, MST);
265f22ef01cSRoman Divacky     Comma = ", ";
266f22ef01cSRoman Divacky   }
2677d523365SDimitry Andric   if (isEHPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
268f22ef01cSRoman Divacky   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
2697ae0e2c9SDimitry Andric   if (Alignment)
270dff0c46cSDimitry Andric     OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
271dff0c46cSDimitry Andric        << " bytes)";
272dff0c46cSDimitry Andric 
273f22ef01cSRoman Divacky   OS << '\n';
274f22ef01cSRoman Divacky 
27539d628a0SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
276f22ef01cSRoman Divacky   if (!livein_empty()) {
2772754fe60SDimitry Andric     if (Indexes) OS << '\t';
278f22ef01cSRoman Divacky     OS << "    Live Ins:";
2797d523365SDimitry Andric     for (const auto &LI : make_range(livein_begin(), livein_end())) {
2807d523365SDimitry Andric       OS << ' ' << PrintReg(LI.PhysReg, TRI);
2817d523365SDimitry Andric       if (LI.LaneMask != ~0u)
2827d523365SDimitry Andric         OS << ':' << PrintLaneMask(LI.LaneMask);
2837d523365SDimitry Andric     }
284f22ef01cSRoman Divacky     OS << '\n';
285f22ef01cSRoman Divacky   }
286f22ef01cSRoman Divacky   // Print the preds of this block according to the CFG.
287f22ef01cSRoman Divacky   if (!pred_empty()) {
2882754fe60SDimitry Andric     if (Indexes) OS << '\t';
289f22ef01cSRoman Divacky     OS << "    Predecessors according to CFG:";
290f22ef01cSRoman Divacky     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
291f22ef01cSRoman Divacky       OS << " BB#" << (*PI)->getNumber();
292f22ef01cSRoman Divacky     OS << '\n';
293f22ef01cSRoman Divacky   }
294f22ef01cSRoman Divacky 
2953ca95b02SDimitry Andric   for (auto &I : instrs()) {
2962754fe60SDimitry Andric     if (Indexes) {
2973ca95b02SDimitry Andric       if (Indexes->hasIndex(I))
2983ca95b02SDimitry Andric         OS << Indexes->getInstructionIndex(I);
2992754fe60SDimitry Andric       OS << '\t';
3002754fe60SDimitry Andric     }
301f22ef01cSRoman Divacky     OS << '\t';
3023ca95b02SDimitry Andric     if (I.isInsideBundle())
303dff0c46cSDimitry Andric       OS << "  * ";
3043ca95b02SDimitry Andric     I.print(OS, MST);
305f22ef01cSRoman Divacky   }
306f22ef01cSRoman Divacky 
307f22ef01cSRoman Divacky   // Print the successors of this block according to the CFG.
308f22ef01cSRoman Divacky   if (!succ_empty()) {
3092754fe60SDimitry Andric     if (Indexes) OS << '\t';
310f22ef01cSRoman Divacky     OS << "    Successors according to CFG:";
3117ae0e2c9SDimitry Andric     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
312f22ef01cSRoman Divacky       OS << " BB#" << (*SI)->getNumber();
3137d523365SDimitry Andric       if (!Probs.empty())
3147d523365SDimitry Andric         OS << '(' << *getProbabilityIterator(SI) << ')';
3157ae0e2c9SDimitry Andric     }
316f22ef01cSRoman Divacky     OS << '\n';
317f22ef01cSRoman Divacky   }
318f22ef01cSRoman Divacky }
319f22ef01cSRoman Divacky 
3207d523365SDimitry Andric void MachineBasicBlock::printAsOperand(raw_ostream &OS,
3217d523365SDimitry Andric                                        bool /*PrintType*/) const {
32291bc56edSDimitry Andric   OS << "BB#" << getNumber();
32391bc56edSDimitry Andric }
32491bc56edSDimitry Andric 
3257d523365SDimitry Andric void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
3267d523365SDimitry Andric   LiveInVector::iterator I = std::find_if(
3277d523365SDimitry Andric       LiveIns.begin(), LiveIns.end(),
3287d523365SDimitry Andric       [Reg] (const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
3297d523365SDimitry Andric   if (I == LiveIns.end())
3307d523365SDimitry Andric     return;
3317d523365SDimitry Andric 
3327d523365SDimitry Andric   I->LaneMask &= ~LaneMask;
3337d523365SDimitry Andric   if (I->LaneMask == 0)
334f22ef01cSRoman Divacky     LiveIns.erase(I);
335f22ef01cSRoman Divacky }
336f22ef01cSRoman Divacky 
3377d523365SDimitry Andric bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
3387d523365SDimitry Andric   livein_iterator I = std::find_if(
3397d523365SDimitry Andric       LiveIns.begin(), LiveIns.end(),
3407d523365SDimitry Andric       [Reg] (const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
3417d523365SDimitry Andric   return I != livein_end() && (I->LaneMask & LaneMask) != 0;
3427d523365SDimitry Andric }
3437d523365SDimitry Andric 
3447d523365SDimitry Andric void MachineBasicBlock::sortUniqueLiveIns() {
3457d523365SDimitry Andric   std::sort(LiveIns.begin(), LiveIns.end(),
3467d523365SDimitry Andric             [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
3477d523365SDimitry Andric               return LI0.PhysReg < LI1.PhysReg;
3487d523365SDimitry Andric             });
3497d523365SDimitry Andric   // Liveins are sorted by physreg now we can merge their lanemasks.
3507d523365SDimitry Andric   LiveInVector::const_iterator I = LiveIns.begin();
3517d523365SDimitry Andric   LiveInVector::const_iterator J;
3527d523365SDimitry Andric   LiveInVector::iterator Out = LiveIns.begin();
3537d523365SDimitry Andric   for (; I != LiveIns.end(); ++Out, I = J) {
3547d523365SDimitry Andric     unsigned PhysReg = I->PhysReg;
3557d523365SDimitry Andric     LaneBitmask LaneMask = I->LaneMask;
3567d523365SDimitry Andric     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
3577d523365SDimitry Andric       LaneMask |= J->LaneMask;
3587d523365SDimitry Andric     Out->PhysReg = PhysReg;
3597d523365SDimitry Andric     Out->LaneMask = LaneMask;
3607d523365SDimitry Andric   }
3617d523365SDimitry Andric   LiveIns.erase(Out, LiveIns.end());
362f22ef01cSRoman Divacky }
363f22ef01cSRoman Divacky 
364*6beeb091SDimitry Andric unsigned
3657d523365SDimitry Andric MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
366*6beeb091SDimitry Andric   assert(getParent() && "MBB must be inserted in function");
367*6beeb091SDimitry Andric   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
368*6beeb091SDimitry Andric   assert(RC && "Register class is required");
3697d523365SDimitry Andric   assert((isEHPad() || this == &getParent()->front()) &&
370*6beeb091SDimitry Andric          "Only the entry block and landing pads can have physreg live ins");
371*6beeb091SDimitry Andric 
372*6beeb091SDimitry Andric   bool LiveIn = isLiveIn(PhysReg);
373*6beeb091SDimitry Andric   iterator I = SkipPHIsAndLabels(begin()), E = end();
374*6beeb091SDimitry Andric   MachineRegisterInfo &MRI = getParent()->getRegInfo();
37539d628a0SDimitry Andric   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
376*6beeb091SDimitry Andric 
377*6beeb091SDimitry Andric   // Look for an existing copy.
378*6beeb091SDimitry Andric   if (LiveIn)
379*6beeb091SDimitry Andric     for (;I != E && I->isCopy(); ++I)
380*6beeb091SDimitry Andric       if (I->getOperand(1).getReg() == PhysReg) {
381*6beeb091SDimitry Andric         unsigned VirtReg = I->getOperand(0).getReg();
382*6beeb091SDimitry Andric         if (!MRI.constrainRegClass(VirtReg, RC))
383*6beeb091SDimitry Andric           llvm_unreachable("Incompatible live-in register class.");
384*6beeb091SDimitry Andric         return VirtReg;
385*6beeb091SDimitry Andric       }
386*6beeb091SDimitry Andric 
387*6beeb091SDimitry Andric   // No luck, create a virtual register.
388*6beeb091SDimitry Andric   unsigned VirtReg = MRI.createVirtualRegister(RC);
389*6beeb091SDimitry Andric   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
390*6beeb091SDimitry Andric     .addReg(PhysReg, RegState::Kill);
391*6beeb091SDimitry Andric   if (!LiveIn)
392*6beeb091SDimitry Andric     addLiveIn(PhysReg);
393*6beeb091SDimitry Andric   return VirtReg;
394*6beeb091SDimitry Andric }
395*6beeb091SDimitry Andric 
396f22ef01cSRoman Divacky void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
3977d523365SDimitry Andric   getParent()->splice(NewAfter->getIterator(), getIterator());
398f22ef01cSRoman Divacky }
399f22ef01cSRoman Divacky 
400f22ef01cSRoman Divacky void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
4017d523365SDimitry Andric   getParent()->splice(++NewBefore->getIterator(), getIterator());
402f22ef01cSRoman Divacky }
403f22ef01cSRoman Divacky 
404f22ef01cSRoman Divacky void MachineBasicBlock::updateTerminator() {
40539d628a0SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
406f22ef01cSRoman Divacky   // A block with no successors has no concerns with fall-through edges.
4073ca95b02SDimitry Andric   if (this->succ_empty())
4083ca95b02SDimitry Andric     return;
409f22ef01cSRoman Divacky 
41091bc56edSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
411f22ef01cSRoman Divacky   SmallVector<MachineOperand, 4> Cond;
4127d523365SDimitry Andric   DebugLoc DL;  // FIXME: this is nowhere
4133ca95b02SDimitry Andric   bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
414f22ef01cSRoman Divacky   (void) B;
415f22ef01cSRoman Divacky   assert(!B && "UpdateTerminators requires analyzable predecessors!");
416f22ef01cSRoman Divacky   if (Cond.empty()) {
417f22ef01cSRoman Divacky     if (TBB) {
4183ca95b02SDimitry Andric       // The block has an unconditional branch. If its successor is now its
4193ca95b02SDimitry Andric       // layout successor, delete the branch.
420f22ef01cSRoman Divacky       if (isLayoutSuccessor(TBB))
421f22ef01cSRoman Divacky         TII->RemoveBranch(*this);
422f22ef01cSRoman Divacky     } else {
4233ca95b02SDimitry Andric       // The block has an unconditional fallthrough. If its successor is not its
4243ca95b02SDimitry Andric       // layout successor, insert a branch. First we have to locate the only
4253ca95b02SDimitry Andric       // non-landing-pad successor, as that is the fallthrough block.
426dff0c46cSDimitry Andric       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
4277d523365SDimitry Andric         if ((*SI)->isEHPad())
428dff0c46cSDimitry Andric           continue;
429dff0c46cSDimitry Andric         assert(!TBB && "Found more than one non-landing-pad successor!");
430dff0c46cSDimitry Andric         TBB = *SI;
431dff0c46cSDimitry Andric       }
432dff0c46cSDimitry Andric 
4333ca95b02SDimitry Andric       // If there is no non-landing-pad successor, the block has no fall-through
4343ca95b02SDimitry Andric       // edges to be concerned with.
435dff0c46cSDimitry Andric       if (!TBB)
436dff0c46cSDimitry Andric         return;
437dff0c46cSDimitry Andric 
438dff0c46cSDimitry Andric       // Finally update the unconditional successor to be reached via a branch
439dff0c46cSDimitry Andric       // if it would not be reached by fallthrough.
440f22ef01cSRoman Divacky       if (!isLayoutSuccessor(TBB))
4417d523365SDimitry Andric         TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
442f22ef01cSRoman Divacky     }
4433ca95b02SDimitry Andric     return;
4443ca95b02SDimitry Andric   }
4453ca95b02SDimitry Andric 
446f22ef01cSRoman Divacky   if (FBB) {
447f22ef01cSRoman Divacky     // The block has a non-fallthrough conditional branch. If one of its
448f22ef01cSRoman Divacky     // successors is its layout successor, rewrite it to a fallthrough
449f22ef01cSRoman Divacky     // conditional branch.
450f22ef01cSRoman Divacky     if (isLayoutSuccessor(TBB)) {
451f22ef01cSRoman Divacky       if (TII->ReverseBranchCondition(Cond))
452f22ef01cSRoman Divacky         return;
453f22ef01cSRoman Divacky       TII->RemoveBranch(*this);
4547d523365SDimitry Andric       TII->InsertBranch(*this, FBB, nullptr, Cond, DL);
455f22ef01cSRoman Divacky     } else if (isLayoutSuccessor(FBB)) {
456f22ef01cSRoman Divacky       TII->RemoveBranch(*this);
4577d523365SDimitry Andric       TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
458f22ef01cSRoman Divacky     }
4593ca95b02SDimitry Andric     return;
4603ca95b02SDimitry Andric   }
4613ca95b02SDimitry Andric 
4623ca95b02SDimitry Andric   // Walk through the successors and find the successor which is not a landing
4633ca95b02SDimitry Andric   // pad and is not the conditional branch destination (in TBB) as the
4643ca95b02SDimitry Andric   // fallthrough successor.
46591bc56edSDimitry Andric   MachineBasicBlock *FallthroughBB = nullptr;
466cb4dff85SDimitry Andric   for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
4677d523365SDimitry Andric     if ((*SI)->isEHPad() || *SI == TBB)
468cb4dff85SDimitry Andric       continue;
469cb4dff85SDimitry Andric     assert(!FallthroughBB && "Found more than one fallthrough successor.");
470cb4dff85SDimitry Andric     FallthroughBB = *SI;
471cb4dff85SDimitry Andric   }
4723ca95b02SDimitry Andric 
4733ca95b02SDimitry Andric   if (!FallthroughBB) {
4743ca95b02SDimitry Andric     if (canFallThrough()) {
4753ca95b02SDimitry Andric       // We fallthrough to the same basic block as the conditional jump targets.
4763ca95b02SDimitry Andric       // Remove the conditional jump, leaving unconditional fallthrough.
4773ca95b02SDimitry Andric       // FIXME: This does not seem like a reasonable pattern to support, but it
4783ca95b02SDimitry Andric       // has been seen in the wild coming out of degenerate ARM test cases.
479cb4dff85SDimitry Andric       TII->RemoveBranch(*this);
480cb4dff85SDimitry Andric 
4813ca95b02SDimitry Andric       // Finally update the unconditional successor to be reached via a branch if
4823ca95b02SDimitry Andric       // it would not be reached by fallthrough.
483cb4dff85SDimitry Andric       if (!isLayoutSuccessor(TBB))
4847d523365SDimitry Andric         TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
485cb4dff85SDimitry Andric       return;
486cb4dff85SDimitry Andric     }
487cb4dff85SDimitry Andric 
4883ca95b02SDimitry Andric     // We enter here iff exactly one successor is TBB which cannot fallthrough
4893ca95b02SDimitry Andric     // and the rest successors if any are EHPads.  In this case, we need to
4903ca95b02SDimitry Andric     // change the conditional branch into unconditional branch.
4913ca95b02SDimitry Andric     TII->RemoveBranch(*this);
4923ca95b02SDimitry Andric     Cond.clear();
4933ca95b02SDimitry Andric     TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
4943ca95b02SDimitry Andric     return;
4953ca95b02SDimitry Andric   }
4963ca95b02SDimitry Andric 
497f22ef01cSRoman Divacky   // The block has a fallthrough conditional branch.
498f22ef01cSRoman Divacky   if (isLayoutSuccessor(TBB)) {
499f22ef01cSRoman Divacky     if (TII->ReverseBranchCondition(Cond)) {
500f22ef01cSRoman Divacky       // We can't reverse the condition, add an unconditional branch.
501f22ef01cSRoman Divacky       Cond.clear();
5027d523365SDimitry Andric       TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, DL);
503f22ef01cSRoman Divacky       return;
504f22ef01cSRoman Divacky     }
505f22ef01cSRoman Divacky     TII->RemoveBranch(*this);
5067d523365SDimitry Andric     TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, DL);
507cb4dff85SDimitry Andric   } else if (!isLayoutSuccessor(FallthroughBB)) {
508f22ef01cSRoman Divacky     TII->RemoveBranch(*this);
5097d523365SDimitry Andric     TII->InsertBranch(*this, TBB, FallthroughBB, Cond, DL);
510f22ef01cSRoman Divacky   }
511f22ef01cSRoman Divacky }
512f22ef01cSRoman Divacky 
5137d523365SDimitry Andric void MachineBasicBlock::validateSuccProbs() const {
5147d523365SDimitry Andric #ifndef NDEBUG
5157d523365SDimitry Andric   int64_t Sum = 0;
5167d523365SDimitry Andric   for (auto Prob : Probs)
5177d523365SDimitry Andric     Sum += Prob.getNumerator();
5187d523365SDimitry Andric   // Due to precision issue, we assume that the sum of probabilities is one if
5197d523365SDimitry Andric   // the difference between the sum of their numerators and the denominator is
5207d523365SDimitry Andric   // no greater than the number of successors.
5217d523365SDimitry Andric   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
5227d523365SDimitry Andric              Probs.size() &&
5237d523365SDimitry Andric          "The sum of successors's probabilities exceeds one.");
5247d523365SDimitry Andric #endif // NDEBUG
525f22ef01cSRoman Divacky }
526f22ef01cSRoman Divacky 
5277d523365SDimitry Andric void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
5287d523365SDimitry Andric                                      BranchProbability Prob) {
5297d523365SDimitry Andric   // Probability list is either empty (if successor list isn't empty, this means
5307d523365SDimitry Andric   // disabled optimization) or has the same size as successor list.
5317d523365SDimitry Andric   if (!(Probs.empty() && !Successors.empty()))
5327d523365SDimitry Andric     Probs.push_back(Prob);
5337d523365SDimitry Andric   Successors.push_back(Succ);
5347d523365SDimitry Andric   Succ->addPredecessor(this);
53517a519f9SDimitry Andric }
53617a519f9SDimitry Andric 
5377d523365SDimitry Andric void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
5387d523365SDimitry Andric   // We need to make sure probability list is either empty or has the same size
5397d523365SDimitry Andric   // of successor list. When this function is called, we can safely delete all
5407d523365SDimitry Andric   // probability in the list.
5417d523365SDimitry Andric   Probs.clear();
5427d523365SDimitry Andric   Successors.push_back(Succ);
5437d523365SDimitry Andric   Succ->addPredecessor(this);
5447d523365SDimitry Andric }
5457d523365SDimitry Andric 
5467d523365SDimitry Andric void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
5477d523365SDimitry Andric                                         bool NormalizeSuccProbs) {
5487d523365SDimitry Andric   succ_iterator I = std::find(Successors.begin(), Successors.end(), Succ);
5497d523365SDimitry Andric   removeSuccessor(I, NormalizeSuccProbs);
550f22ef01cSRoman Divacky }
551f22ef01cSRoman Divacky 
552f22ef01cSRoman Divacky MachineBasicBlock::succ_iterator
5537d523365SDimitry Andric MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
554f22ef01cSRoman Divacky   assert(I != Successors.end() && "Not a current successor!");
55517a519f9SDimitry Andric 
5567d523365SDimitry Andric   // If probability list is empty it means we don't use it (disabled
5577d523365SDimitry Andric   // optimization).
5587d523365SDimitry Andric   if (!Probs.empty()) {
5597d523365SDimitry Andric     probability_iterator WI = getProbabilityIterator(I);
5607d523365SDimitry Andric     Probs.erase(WI);
5617d523365SDimitry Andric     if (NormalizeSuccProbs)
5627d523365SDimitry Andric       normalizeSuccProbs();
56317a519f9SDimitry Andric   }
56417a519f9SDimitry Andric 
565f22ef01cSRoman Divacky   (*I)->removePredecessor(this);
566f22ef01cSRoman Divacky   return Successors.erase(I);
567f22ef01cSRoman Divacky }
568f22ef01cSRoman Divacky 
56917a519f9SDimitry Andric void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
57017a519f9SDimitry Andric                                          MachineBasicBlock *New) {
5717ae0e2c9SDimitry Andric   if (Old == New)
5727ae0e2c9SDimitry Andric     return;
57317a519f9SDimitry Andric 
5747ae0e2c9SDimitry Andric   succ_iterator E = succ_end();
5757ae0e2c9SDimitry Andric   succ_iterator NewI = E;
5767ae0e2c9SDimitry Andric   succ_iterator OldI = E;
5777ae0e2c9SDimitry Andric   for (succ_iterator I = succ_begin(); I != E; ++I) {
5787ae0e2c9SDimitry Andric     if (*I == Old) {
5797ae0e2c9SDimitry Andric       OldI = I;
5807ae0e2c9SDimitry Andric       if (NewI != E)
5817ae0e2c9SDimitry Andric         break;
5827ae0e2c9SDimitry Andric     }
5837ae0e2c9SDimitry Andric     if (*I == New) {
5847ae0e2c9SDimitry Andric       NewI = I;
5857ae0e2c9SDimitry Andric       if (OldI != E)
5867ae0e2c9SDimitry Andric         break;
5877ae0e2c9SDimitry Andric     }
5887ae0e2c9SDimitry Andric   }
5897ae0e2c9SDimitry Andric   assert(OldI != E && "Old is not a successor of this block");
5907ae0e2c9SDimitry Andric 
5917ae0e2c9SDimitry Andric   // If New isn't already a successor, let it take Old's place.
5927ae0e2c9SDimitry Andric   if (NewI == E) {
5937d523365SDimitry Andric     Old->removePredecessor(this);
5947ae0e2c9SDimitry Andric     New->addPredecessor(this);
5957ae0e2c9SDimitry Andric     *OldI = New;
5967ae0e2c9SDimitry Andric     return;
59717a519f9SDimitry Andric   }
59817a519f9SDimitry Andric 
5997ae0e2c9SDimitry Andric   // New is already a successor.
6007d523365SDimitry Andric   // Update its probability instead of adding a duplicate edge.
6017d523365SDimitry Andric   if (!Probs.empty()) {
6027d523365SDimitry Andric     auto ProbIter = getProbabilityIterator(NewI);
6037d523365SDimitry Andric     if (!ProbIter->isUnknown())
6047d523365SDimitry Andric       *ProbIter += *getProbabilityIterator(OldI);
6057ae0e2c9SDimitry Andric   }
6067d523365SDimitry Andric   removeSuccessor(OldI);
60717a519f9SDimitry Andric }
60817a519f9SDimitry Andric 
6097d523365SDimitry Andric void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
6107d523365SDimitry Andric   Predecessors.push_back(Pred);
611f22ef01cSRoman Divacky }
612f22ef01cSRoman Divacky 
6137d523365SDimitry Andric void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
6147d523365SDimitry Andric   pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), Pred);
615f22ef01cSRoman Divacky   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
616f22ef01cSRoman Divacky   Predecessors.erase(I);
617f22ef01cSRoman Divacky }
618f22ef01cSRoman Divacky 
6197d523365SDimitry Andric void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
6207d523365SDimitry Andric   if (this == FromMBB)
621f22ef01cSRoman Divacky     return;
622f22ef01cSRoman Divacky 
6237d523365SDimitry Andric   while (!FromMBB->succ_empty()) {
6247d523365SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
62517a519f9SDimitry Andric 
6267d523365SDimitry Andric     // If probability list is empty it means we don't use it (disabled optimization).
6277d523365SDimitry Andric     if (!FromMBB->Probs.empty()) {
6287d523365SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
6297d523365SDimitry Andric       addSuccessor(Succ, Prob);
6307d523365SDimitry Andric     } else
6317d523365SDimitry Andric       addSuccessorWithoutProb(Succ);
63217a519f9SDimitry Andric 
6337d523365SDimitry Andric     FromMBB->removeSuccessor(Succ);
634ffd1746dSEd Schouten   }
635ffd1746dSEd Schouten }
636f22ef01cSRoman Divacky 
637ffd1746dSEd Schouten void
6387d523365SDimitry Andric MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
6397d523365SDimitry Andric   if (this == FromMBB)
640ffd1746dSEd Schouten     return;
641ffd1746dSEd Schouten 
6427d523365SDimitry Andric   while (!FromMBB->succ_empty()) {
6437d523365SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
6447d523365SDimitry Andric     if (!FromMBB->Probs.empty()) {
6457d523365SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
6467d523365SDimitry Andric       addSuccessor(Succ, Prob);
6477d523365SDimitry Andric     } else
6487d523365SDimitry Andric       addSuccessorWithoutProb(Succ);
6497d523365SDimitry Andric     FromMBB->removeSuccessor(Succ);
650ffd1746dSEd Schouten 
651ffd1746dSEd Schouten     // Fix up any PHI nodes in the successor.
652dff0c46cSDimitry Andric     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
653dff0c46cSDimitry Andric            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
654ffd1746dSEd Schouten       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
655ffd1746dSEd Schouten         MachineOperand &MO = MI->getOperand(i);
6567d523365SDimitry Andric         if (MO.getMBB() == FromMBB)
657ffd1746dSEd Schouten           MO.setMBB(this);
658ffd1746dSEd Schouten       }
659ffd1746dSEd Schouten   }
6607d523365SDimitry Andric   normalizeSuccProbs();
661f22ef01cSRoman Divacky }
662f22ef01cSRoman Divacky 
6637ae0e2c9SDimitry Andric bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
6647ae0e2c9SDimitry Andric   return std::find(pred_begin(), pred_end(), MBB) != pred_end();
6657ae0e2c9SDimitry Andric }
6667ae0e2c9SDimitry Andric 
667f22ef01cSRoman Divacky bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
6687ae0e2c9SDimitry Andric   return std::find(succ_begin(), succ_end(), MBB) != succ_end();
669f22ef01cSRoman Divacky }
670f22ef01cSRoman Divacky 
671f22ef01cSRoman Divacky bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
672f22ef01cSRoman Divacky   MachineFunction::const_iterator I(this);
67391bc56edSDimitry Andric   return std::next(I) == MachineFunction::const_iterator(MBB);
674f22ef01cSRoman Divacky }
675f22ef01cSRoman Divacky 
676f22ef01cSRoman Divacky bool MachineBasicBlock::canFallThrough() {
6777d523365SDimitry Andric   MachineFunction::iterator Fallthrough = getIterator();
678f22ef01cSRoman Divacky   ++Fallthrough;
679f22ef01cSRoman Divacky   // If FallthroughBlock is off the end of the function, it can't fall through.
680f22ef01cSRoman Divacky   if (Fallthrough == getParent()->end())
681f22ef01cSRoman Divacky     return false;
682f22ef01cSRoman Divacky 
683f22ef01cSRoman Divacky   // If FallthroughBlock isn't a successor, no fallthrough is possible.
6847d523365SDimitry Andric   if (!isSuccessor(&*Fallthrough))
685f22ef01cSRoman Divacky     return false;
686f22ef01cSRoman Divacky 
687f22ef01cSRoman Divacky   // Analyze the branches, if any, at the end of the block.
68891bc56edSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
689f22ef01cSRoman Divacky   SmallVector<MachineOperand, 4> Cond;
69039d628a0SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
6913ca95b02SDimitry Andric   if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
692f22ef01cSRoman Divacky     // If we couldn't analyze the branch, examine the last instruction.
693f22ef01cSRoman Divacky     // If the block doesn't end in a known control barrier, assume fallthrough
694dff0c46cSDimitry Andric     // is possible. The isPredicated check is needed because this code can be
695f22ef01cSRoman Divacky     // called during IfConversion, where an instruction which is normally a
696dff0c46cSDimitry Andric     // Barrier is predicated and thus no longer an actual control barrier.
6973ca95b02SDimitry Andric     return empty() || !back().isBarrier() || TII->isPredicated(back());
698f22ef01cSRoman Divacky   }
699f22ef01cSRoman Divacky 
700f22ef01cSRoman Divacky   // If there is no branch, control always falls through.
70191bc56edSDimitry Andric   if (!TBB) return true;
702f22ef01cSRoman Divacky 
703f22ef01cSRoman Divacky   // If there is some explicit branch to the fallthrough block, it can obviously
704f22ef01cSRoman Divacky   // reach, even though the branch should get folded to fall through implicitly.
705f22ef01cSRoman Divacky   if (MachineFunction::iterator(TBB) == Fallthrough ||
706f22ef01cSRoman Divacky       MachineFunction::iterator(FBB) == Fallthrough)
707f22ef01cSRoman Divacky     return true;
708f22ef01cSRoman Divacky 
709f22ef01cSRoman Divacky   // If it's an unconditional branch to some block not the fall through, it
710f22ef01cSRoman Divacky   // doesn't fall through.
711f22ef01cSRoman Divacky   if (Cond.empty()) return false;
712f22ef01cSRoman Divacky 
713f22ef01cSRoman Divacky   // Otherwise, if it is conditional and has no explicit false block, it falls
714f22ef01cSRoman Divacky   // through.
71591bc56edSDimitry Andric   return FBB == nullptr;
716f22ef01cSRoman Divacky }
717f22ef01cSRoman Divacky 
7183ca95b02SDimitry Andric MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ,
7193ca95b02SDimitry Andric                                                         Pass &P) {
7203ca95b02SDimitry Andric   if (!canSplitCriticalEdge(Succ))
72191bc56edSDimitry Andric     return nullptr;
7227ae0e2c9SDimitry Andric 
723ffd1746dSEd Schouten   MachineFunction *MF = getParent();
7247d523365SDimitry Andric   DebugLoc DL;  // FIXME: this is nowhere
725ffd1746dSEd Schouten 
726ffd1746dSEd Schouten   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
72791bc56edSDimitry Andric   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
728e580952dSDimitry Andric   DEBUG(dbgs() << "Splitting critical edge:"
729ffd1746dSEd Schouten         " BB#" << getNumber()
730ffd1746dSEd Schouten         << " -- BB#" << NMBB->getNumber()
731ffd1746dSEd Schouten         << " -- BB#" << Succ->getNumber() << '\n');
732ffd1746dSEd Schouten 
7333ca95b02SDimitry Andric   LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
7343ca95b02SDimitry Andric   SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
735139f7f9bSDimitry Andric   if (LIS)
736139f7f9bSDimitry Andric     LIS->insertMBBInMaps(NMBB);
737139f7f9bSDimitry Andric   else if (Indexes)
738139f7f9bSDimitry Andric     Indexes->insertMBBInMaps(NMBB);
739139f7f9bSDimitry Andric 
740bd5abe19SDimitry Andric   // On some targets like Mips, branches may kill virtual registers. Make sure
741bd5abe19SDimitry Andric   // that LiveVariables is properly updated after updateTerminator replaces the
742bd5abe19SDimitry Andric   // terminators.
7433ca95b02SDimitry Andric   LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
744bd5abe19SDimitry Andric 
745bd5abe19SDimitry Andric   // Collect a list of virtual registers killed by the terminators.
746bd5abe19SDimitry Andric   SmallVector<unsigned, 4> KilledRegs;
747bd5abe19SDimitry Andric   if (LV)
748dff0c46cSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
749dff0c46cSDimitry Andric          I != E; ++I) {
7507d523365SDimitry Andric       MachineInstr *MI = &*I;
751bd5abe19SDimitry Andric       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
752bd5abe19SDimitry Andric            OE = MI->operands_end(); OI != OE; ++OI) {
753dff0c46cSDimitry Andric         if (!OI->isReg() || OI->getReg() == 0 ||
754dff0c46cSDimitry Andric             !OI->isUse() || !OI->isKill() || OI->isUndef())
755bd5abe19SDimitry Andric           continue;
756bd5abe19SDimitry Andric         unsigned Reg = OI->getReg();
757dff0c46cSDimitry Andric         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
7583ca95b02SDimitry Andric             LV->getVarInfo(Reg).removeKill(*MI)) {
759bd5abe19SDimitry Andric           KilledRegs.push_back(Reg);
760bd5abe19SDimitry Andric           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
761bd5abe19SDimitry Andric           OI->setIsKill(false);
762bd5abe19SDimitry Andric         }
763bd5abe19SDimitry Andric       }
764bd5abe19SDimitry Andric     }
765bd5abe19SDimitry Andric 
766139f7f9bSDimitry Andric   SmallVector<unsigned, 4> UsedRegs;
767139f7f9bSDimitry Andric   if (LIS) {
768139f7f9bSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
769139f7f9bSDimitry Andric          I != E; ++I) {
7707d523365SDimitry Andric       MachineInstr *MI = &*I;
771139f7f9bSDimitry Andric 
772139f7f9bSDimitry Andric       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
773139f7f9bSDimitry Andric            OE = MI->operands_end(); OI != OE; ++OI) {
774139f7f9bSDimitry Andric         if (!OI->isReg() || OI->getReg() == 0)
775139f7f9bSDimitry Andric           continue;
776139f7f9bSDimitry Andric 
777139f7f9bSDimitry Andric         unsigned Reg = OI->getReg();
778139f7f9bSDimitry Andric         if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
779139f7f9bSDimitry Andric           UsedRegs.push_back(Reg);
780139f7f9bSDimitry Andric       }
781139f7f9bSDimitry Andric     }
782139f7f9bSDimitry Andric   }
783139f7f9bSDimitry Andric 
784ffd1746dSEd Schouten   ReplaceUsesOfBlockWith(Succ, NMBB);
785139f7f9bSDimitry Andric 
786139f7f9bSDimitry Andric   // If updateTerminator() removes instructions, we need to remove them from
787139f7f9bSDimitry Andric   // SlotIndexes.
788139f7f9bSDimitry Andric   SmallVector<MachineInstr*, 4> Terminators;
789139f7f9bSDimitry Andric   if (Indexes) {
790139f7f9bSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
791139f7f9bSDimitry Andric          I != E; ++I)
7927d523365SDimitry Andric       Terminators.push_back(&*I);
793139f7f9bSDimitry Andric   }
794139f7f9bSDimitry Andric 
795ffd1746dSEd Schouten   updateTerminator();
796ffd1746dSEd Schouten 
797139f7f9bSDimitry Andric   if (Indexes) {
798139f7f9bSDimitry Andric     SmallVector<MachineInstr*, 4> NewTerminators;
799139f7f9bSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
800139f7f9bSDimitry Andric          I != E; ++I)
8017d523365SDimitry Andric       NewTerminators.push_back(&*I);
802139f7f9bSDimitry Andric 
803139f7f9bSDimitry Andric     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
804139f7f9bSDimitry Andric         E = Terminators.end(); I != E; ++I) {
805139f7f9bSDimitry Andric       if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
806139f7f9bSDimitry Andric           NewTerminators.end())
8073ca95b02SDimitry Andric        Indexes->removeMachineInstrFromMaps(**I);
808139f7f9bSDimitry Andric     }
809139f7f9bSDimitry Andric   }
810139f7f9bSDimitry Andric 
811ffd1746dSEd Schouten   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
812ffd1746dSEd Schouten   NMBB->addSuccessor(Succ);
813ffd1746dSEd Schouten   if (!NMBB->isLayoutSuccessor(Succ)) {
8143ca95b02SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
8153ca95b02SDimitry Andric     const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
8167d523365SDimitry Andric     TII->InsertBranch(*NMBB, Succ, nullptr, Cond, DL);
817139f7f9bSDimitry Andric 
818139f7f9bSDimitry Andric     if (Indexes) {
8193ca95b02SDimitry Andric       for (MachineInstr &MI : NMBB->instrs()) {
820139f7f9bSDimitry Andric         // Some instructions may have been moved to NMBB by updateTerminator(),
821139f7f9bSDimitry Andric         // so we first remove any instruction that already has an index.
8223ca95b02SDimitry Andric         if (Indexes->hasIndex(MI))
8233ca95b02SDimitry Andric           Indexes->removeMachineInstrFromMaps(MI);
8243ca95b02SDimitry Andric         Indexes->insertMachineInstrInMaps(MI);
825139f7f9bSDimitry Andric       }
826139f7f9bSDimitry Andric     }
827ffd1746dSEd Schouten   }
828ffd1746dSEd Schouten 
829ffd1746dSEd Schouten   // Fix PHI nodes in Succ so they refer to NMBB instead of this
830dff0c46cSDimitry Andric   for (MachineBasicBlock::instr_iterator
831dff0c46cSDimitry Andric          i = Succ->instr_begin(),e = Succ->instr_end();
832ffd1746dSEd Schouten        i != e && i->isPHI(); ++i)
833ffd1746dSEd Schouten     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
834ffd1746dSEd Schouten       if (i->getOperand(ni+1).getMBB() == this)
835ffd1746dSEd Schouten         i->getOperand(ni+1).setMBB(NMBB);
836ffd1746dSEd Schouten 
8376122f3e6SDimitry Andric   // Inherit live-ins from the successor
8387d523365SDimitry Andric   for (const auto &LI : Succ->liveins())
8397d523365SDimitry Andric     NMBB->addLiveIn(LI);
8406122f3e6SDimitry Andric 
841bd5abe19SDimitry Andric   // Update LiveVariables.
84239d628a0SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
843bd5abe19SDimitry Andric   if (LV) {
844bd5abe19SDimitry Andric     // Restore kills of virtual registers that were killed by the terminators.
845bd5abe19SDimitry Andric     while (!KilledRegs.empty()) {
846bd5abe19SDimitry Andric       unsigned Reg = KilledRegs.pop_back_val();
847dff0c46cSDimitry Andric       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
848dff0c46cSDimitry Andric         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
849bd5abe19SDimitry Andric           continue;
850dff0c46cSDimitry Andric         if (TargetRegisterInfo::isVirtualRegister(Reg))
8517d523365SDimitry Andric           LV->getVarInfo(Reg).Kills.push_back(&*I);
852bd5abe19SDimitry Andric         DEBUG(dbgs() << "Restored terminator kill: " << *I);
853bd5abe19SDimitry Andric         break;
854bd5abe19SDimitry Andric       }
855bd5abe19SDimitry Andric     }
856bd5abe19SDimitry Andric     // Update relevant live-through information.
857ffd1746dSEd Schouten     LV->addNewBlock(NMBB, this, Succ);
858bd5abe19SDimitry Andric   }
859ffd1746dSEd Schouten 
860139f7f9bSDimitry Andric   if (LIS) {
861139f7f9bSDimitry Andric     // After splitting the edge and updating SlotIndexes, live intervals may be
862139f7f9bSDimitry Andric     // in one of two situations, depending on whether this block was the last in
8637d523365SDimitry Andric     // the function. If the original block was the last in the function, all
8647d523365SDimitry Andric     // live intervals will end prior to the beginning of the new split block. If
8657d523365SDimitry Andric     // the original block was not at the end of the function, all live intervals
8667d523365SDimitry Andric     // will extend to the end of the new split block.
867139f7f9bSDimitry Andric 
868139f7f9bSDimitry Andric     bool isLastMBB =
86991bc56edSDimitry Andric       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
870139f7f9bSDimitry Andric 
871139f7f9bSDimitry Andric     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
872139f7f9bSDimitry Andric     SlotIndex PrevIndex = StartIndex.getPrevSlot();
873139f7f9bSDimitry Andric     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
874139f7f9bSDimitry Andric 
875139f7f9bSDimitry Andric     // Find the registers used from NMBB in PHIs in Succ.
876139f7f9bSDimitry Andric     SmallSet<unsigned, 8> PHISrcRegs;
877139f7f9bSDimitry Andric     for (MachineBasicBlock::instr_iterator
878139f7f9bSDimitry Andric          I = Succ->instr_begin(), E = Succ->instr_end();
879139f7f9bSDimitry Andric          I != E && I->isPHI(); ++I) {
880139f7f9bSDimitry Andric       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
881139f7f9bSDimitry Andric         if (I->getOperand(ni+1).getMBB() == NMBB) {
882139f7f9bSDimitry Andric           MachineOperand &MO = I->getOperand(ni);
883139f7f9bSDimitry Andric           unsigned Reg = MO.getReg();
884139f7f9bSDimitry Andric           PHISrcRegs.insert(Reg);
885139f7f9bSDimitry Andric           if (MO.isUndef())
886139f7f9bSDimitry Andric             continue;
887139f7f9bSDimitry Andric 
888139f7f9bSDimitry Andric           LiveInterval &LI = LIS->getInterval(Reg);
889139f7f9bSDimitry Andric           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
8907d523365SDimitry Andric           assert(VNI &&
8917d523365SDimitry Andric                  "PHI sources should be live out of their predecessors.");
892f785676fSDimitry Andric           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
893139f7f9bSDimitry Andric         }
894139f7f9bSDimitry Andric       }
895139f7f9bSDimitry Andric     }
896139f7f9bSDimitry Andric 
897139f7f9bSDimitry Andric     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
898139f7f9bSDimitry Andric     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
899139f7f9bSDimitry Andric       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
900139f7f9bSDimitry Andric       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
901139f7f9bSDimitry Andric         continue;
902139f7f9bSDimitry Andric 
903139f7f9bSDimitry Andric       LiveInterval &LI = LIS->getInterval(Reg);
904139f7f9bSDimitry Andric       if (!LI.liveAt(PrevIndex))
905139f7f9bSDimitry Andric         continue;
906139f7f9bSDimitry Andric 
907139f7f9bSDimitry Andric       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
908139f7f9bSDimitry Andric       if (isLiveOut && isLastMBB) {
909139f7f9bSDimitry Andric         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
910139f7f9bSDimitry Andric         assert(VNI && "LiveInterval should have VNInfo where it is live.");
911f785676fSDimitry Andric         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
912139f7f9bSDimitry Andric       } else if (!isLiveOut && !isLastMBB) {
913f785676fSDimitry Andric         LI.removeSegment(StartIndex, EndIndex);
914139f7f9bSDimitry Andric       }
915139f7f9bSDimitry Andric     }
916139f7f9bSDimitry Andric 
917139f7f9bSDimitry Andric     // Update all intervals for registers whose uses may have been modified by
918139f7f9bSDimitry Andric     // updateTerminator().
919139f7f9bSDimitry Andric     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
920139f7f9bSDimitry Andric   }
921139f7f9bSDimitry Andric 
922ffd1746dSEd Schouten   if (MachineDominatorTree *MDT =
9233ca95b02SDimitry Andric           P.getAnalysisIfAvailable<MachineDominatorTree>())
92439d628a0SDimitry Andric     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
925e580952dSDimitry Andric 
9263ca95b02SDimitry Andric   if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
927ffd1746dSEd Schouten     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
928ffd1746dSEd Schouten       // If one or the other blocks were not in a loop, the new block is not
929ffd1746dSEd Schouten       // either, and thus LI doesn't need to be updated.
930ffd1746dSEd Schouten       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
931ffd1746dSEd Schouten         if (TIL == DestLoop) {
932ffd1746dSEd Schouten           // Both in the same loop, the NMBB joins loop.
933ffd1746dSEd Schouten           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
934ffd1746dSEd Schouten         } else if (TIL->contains(DestLoop)) {
935ffd1746dSEd Schouten           // Edge from an outer loop to an inner loop.  Add to the outer loop.
936ffd1746dSEd Schouten           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
937ffd1746dSEd Schouten         } else if (DestLoop->contains(TIL)) {
938ffd1746dSEd Schouten           // Edge from an inner loop to an outer loop.  Add to the outer loop.
939ffd1746dSEd Schouten           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
940ffd1746dSEd Schouten         } else {
941ffd1746dSEd Schouten           // Edge from two loops with no containment relation.  Because these
942ffd1746dSEd Schouten           // are natural loops, we know that the destination block must be the
943ffd1746dSEd Schouten           // header of its loop (adding a branch into a loop elsewhere would
944ffd1746dSEd Schouten           // create an irreducible loop).
945ffd1746dSEd Schouten           assert(DestLoop->getHeader() == Succ &&
946ffd1746dSEd Schouten                  "Should not create irreducible loops!");
947ffd1746dSEd Schouten           if (MachineLoop *P = DestLoop->getParentLoop())
948ffd1746dSEd Schouten             P->addBasicBlockToLoop(NMBB, MLI->getBase());
949ffd1746dSEd Schouten         }
950ffd1746dSEd Schouten       }
951ffd1746dSEd Schouten     }
952ffd1746dSEd Schouten 
953ffd1746dSEd Schouten   return NMBB;
954ffd1746dSEd Schouten }
955ffd1746dSEd Schouten 
9563ca95b02SDimitry Andric bool MachineBasicBlock::canSplitCriticalEdge(
9573ca95b02SDimitry Andric     const MachineBasicBlock *Succ) const {
9583ca95b02SDimitry Andric   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
9593ca95b02SDimitry Andric   // it in this generic function.
9603ca95b02SDimitry Andric   if (Succ->isEHPad())
9613ca95b02SDimitry Andric     return false;
9623ca95b02SDimitry Andric 
9633ca95b02SDimitry Andric   const MachineFunction *MF = getParent();
9643ca95b02SDimitry Andric 
9653ca95b02SDimitry Andric   // Performance might be harmed on HW that implements branching using exec mask
9663ca95b02SDimitry Andric   // where both sides of the branches are always executed.
9673ca95b02SDimitry Andric   if (MF->getTarget().requiresStructuredCFG())
9683ca95b02SDimitry Andric     return false;
9693ca95b02SDimitry Andric 
9703ca95b02SDimitry Andric   // We may need to update this's terminator, but we can't do that if
9713ca95b02SDimitry Andric   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
9723ca95b02SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
9733ca95b02SDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
9743ca95b02SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
9753ca95b02SDimitry Andric   // AnalyzeBanch should modify this, since we did not allow modification.
9763ca95b02SDimitry Andric   if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
9773ca95b02SDimitry Andric                          /*AllowModify*/ false))
9783ca95b02SDimitry Andric     return false;
9793ca95b02SDimitry Andric 
9803ca95b02SDimitry Andric   // Avoid bugpoint weirdness: A block may end with a conditional branch but
9813ca95b02SDimitry Andric   // jumps to the same MBB is either case. We have duplicate CFG edges in that
9823ca95b02SDimitry Andric   // case that we can't handle. Since this never happens in properly optimized
9833ca95b02SDimitry Andric   // code, just skip those edges.
9843ca95b02SDimitry Andric   if (TBB && TBB == FBB) {
9853ca95b02SDimitry Andric     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
9863ca95b02SDimitry Andric                  << getNumber() << '\n');
9873ca95b02SDimitry Andric     return false;
9883ca95b02SDimitry Andric   }
9893ca95b02SDimitry Andric   return true;
9903ca95b02SDimitry Andric }
9913ca95b02SDimitry Andric 
992139f7f9bSDimitry Andric /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
993139f7f9bSDimitry Andric /// neighboring instructions so the bundle won't be broken by removing MI.
994139f7f9bSDimitry Andric static void unbundleSingleMI(MachineInstr *MI) {
995139f7f9bSDimitry Andric   // Removing the first instruction in a bundle.
996139f7f9bSDimitry Andric   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
997139f7f9bSDimitry Andric     MI->unbundleFromSucc();
998139f7f9bSDimitry Andric   // Removing the last instruction in a bundle.
999139f7f9bSDimitry Andric   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1000139f7f9bSDimitry Andric     MI->unbundleFromPred();
1001139f7f9bSDimitry Andric   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1002139f7f9bSDimitry Andric   // are already fine.
1003dff0c46cSDimitry Andric }
1004dff0c46cSDimitry Andric 
1005139f7f9bSDimitry Andric MachineBasicBlock::instr_iterator
1006139f7f9bSDimitry Andric MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
10077d523365SDimitry Andric   unbundleSingleMI(&*I);
1008139f7f9bSDimitry Andric   return Insts.erase(I);
1009dff0c46cSDimitry Andric }
1010dff0c46cSDimitry Andric 
1011139f7f9bSDimitry Andric MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1012139f7f9bSDimitry Andric   unbundleSingleMI(MI);
1013139f7f9bSDimitry Andric   MI->clearFlag(MachineInstr::BundledPred);
1014139f7f9bSDimitry Andric   MI->clearFlag(MachineInstr::BundledSucc);
1015139f7f9bSDimitry Andric   return Insts.remove(MI);
1016dff0c46cSDimitry Andric }
1017dff0c46cSDimitry Andric 
1018139f7f9bSDimitry Andric MachineBasicBlock::instr_iterator
1019139f7f9bSDimitry Andric MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1020139f7f9bSDimitry Andric   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1021139f7f9bSDimitry Andric          "Cannot insert instruction with bundle flags");
1022139f7f9bSDimitry Andric   // Set the bundle flags when inserting inside a bundle.
1023139f7f9bSDimitry Andric   if (I != instr_end() && I->isBundledWithPred()) {
1024139f7f9bSDimitry Andric     MI->setFlag(MachineInstr::BundledPred);
1025139f7f9bSDimitry Andric     MI->setFlag(MachineInstr::BundledSucc);
1026dff0c46cSDimitry Andric   }
1027139f7f9bSDimitry Andric   return Insts.insert(I, MI);
1028dff0c46cSDimitry Andric }
1029dff0c46cSDimitry Andric 
10307d523365SDimitry Andric /// This method unlinks 'this' from the containing function, and returns it, but
10317d523365SDimitry Andric /// does not delete it.
1032f22ef01cSRoman Divacky MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1033f22ef01cSRoman Divacky   assert(getParent() && "Not embedded in a function!");
1034f22ef01cSRoman Divacky   getParent()->remove(this);
1035f22ef01cSRoman Divacky   return this;
1036f22ef01cSRoman Divacky }
1037f22ef01cSRoman Divacky 
10387d523365SDimitry Andric /// This method unlinks 'this' from the containing function, and deletes it.
1039f22ef01cSRoman Divacky void MachineBasicBlock::eraseFromParent() {
1040f22ef01cSRoman Divacky   assert(getParent() && "Not embedded in a function!");
1041f22ef01cSRoman Divacky   getParent()->erase(this);
1042f22ef01cSRoman Divacky }
1043f22ef01cSRoman Divacky 
10447d523365SDimitry Andric /// Given a machine basic block that branched to 'Old', change the code and CFG
10457d523365SDimitry Andric /// so that it branches to 'New' instead.
1046f22ef01cSRoman Divacky void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1047f22ef01cSRoman Divacky                                                MachineBasicBlock *New) {
1048f22ef01cSRoman Divacky   assert(Old != New && "Cannot replace self with self!");
1049f22ef01cSRoman Divacky 
1050dff0c46cSDimitry Andric   MachineBasicBlock::instr_iterator I = instr_end();
1051dff0c46cSDimitry Andric   while (I != instr_begin()) {
1052f22ef01cSRoman Divacky     --I;
1053dff0c46cSDimitry Andric     if (!I->isTerminator()) break;
1054f22ef01cSRoman Divacky 
1055f22ef01cSRoman Divacky     // Scan the operands of this machine instruction, replacing any uses of Old
1056f22ef01cSRoman Divacky     // with New.
1057f22ef01cSRoman Divacky     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1058f22ef01cSRoman Divacky       if (I->getOperand(i).isMBB() &&
1059f22ef01cSRoman Divacky           I->getOperand(i).getMBB() == Old)
1060f22ef01cSRoman Divacky         I->getOperand(i).setMBB(New);
1061f22ef01cSRoman Divacky   }
1062f22ef01cSRoman Divacky 
1063f22ef01cSRoman Divacky   // Update the successor information.
106417a519f9SDimitry Andric   replaceSuccessor(Old, New);
1065f22ef01cSRoman Divacky }
1066f22ef01cSRoman Divacky 
10677d523365SDimitry Andric /// Various pieces of code can cause excess edges in the CFG to be inserted.  If
10687d523365SDimitry Andric /// we have proven that MBB can only branch to DestA and DestB, remove any other
10697d523365SDimitry Andric /// MBB successors from the CFG.  DestA and DestB can be null.
1070f22ef01cSRoman Divacky ///
1071f22ef01cSRoman Divacky /// Besides DestA and DestB, retain other edges leading to LandingPads
1072f22ef01cSRoman Divacky /// (currently there can be only one; we don't check or require that here).
1073f22ef01cSRoman Divacky /// Note it is possible that DestA and/or DestB are LandingPads.
1074f22ef01cSRoman Divacky bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1075f22ef01cSRoman Divacky                                              MachineBasicBlock *DestB,
10767d523365SDimitry Andric                                              bool IsCond) {
1077f22ef01cSRoman Divacky   // The values of DestA and DestB frequently come from a call to the
1078f22ef01cSRoman Divacky   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1079f22ef01cSRoman Divacky   // values from there.
1080f22ef01cSRoman Divacky   //
1081f22ef01cSRoman Divacky   // 1. If both DestA and DestB are null, then the block ends with no branches
1082f22ef01cSRoman Divacky   //    (it falls through to its successor).
10837d523365SDimitry Andric   // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
1084f22ef01cSRoman Divacky   //    with only an unconditional branch.
10857d523365SDimitry Andric   // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
1086f22ef01cSRoman Divacky   //    with a conditional branch that falls through to a successor (DestB).
10877d523365SDimitry Andric   // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
1088f22ef01cSRoman Divacky   //    conditional branch followed by an unconditional branch. DestA is the
1089f22ef01cSRoman Divacky   //    'true' destination and DestB is the 'false' destination.
1090f22ef01cSRoman Divacky 
1091f22ef01cSRoman Divacky   bool Changed = false;
1092f22ef01cSRoman Divacky 
10937d523365SDimitry Andric   MachineFunction::iterator FallThru = std::next(getIterator());
1094f22ef01cSRoman Divacky 
109591bc56edSDimitry Andric   if (!DestA && !DestB) {
1096f22ef01cSRoman Divacky     // Block falls through to successor.
10977d523365SDimitry Andric     DestA = &*FallThru;
10987d523365SDimitry Andric     DestB = &*FallThru;
109991bc56edSDimitry Andric   } else if (DestA && !DestB) {
11007d523365SDimitry Andric     if (IsCond)
1101f22ef01cSRoman Divacky       // Block ends in conditional jump that falls through to successor.
11027d523365SDimitry Andric       DestB = &*FallThru;
1103f22ef01cSRoman Divacky   } else {
11047d523365SDimitry Andric     assert(DestA && DestB && IsCond &&
1105f22ef01cSRoman Divacky            "CFG in a bad state. Cannot correct CFG edges");
1106f22ef01cSRoman Divacky   }
1107f22ef01cSRoman Divacky 
1108f22ef01cSRoman Divacky   // Remove superfluous edges. I.e., those which aren't destinations of this
1109f22ef01cSRoman Divacky   // basic block, duplicate edges, or landing pads.
1110f22ef01cSRoman Divacky   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1111f22ef01cSRoman Divacky   MachineBasicBlock::succ_iterator SI = succ_begin();
1112f22ef01cSRoman Divacky   while (SI != succ_end()) {
1113f22ef01cSRoman Divacky     const MachineBasicBlock *MBB = *SI;
111439d628a0SDimitry Andric     if (!SeenMBBs.insert(MBB).second ||
11157d523365SDimitry Andric         (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
1116f22ef01cSRoman Divacky       // This is a superfluous edge, remove it.
1117f22ef01cSRoman Divacky       SI = removeSuccessor(SI);
1118f22ef01cSRoman Divacky       Changed = true;
1119f22ef01cSRoman Divacky     } else {
1120f22ef01cSRoman Divacky       ++SI;
1121f22ef01cSRoman Divacky     }
1122f22ef01cSRoman Divacky   }
1123f22ef01cSRoman Divacky 
11247d523365SDimitry Andric   if (Changed)
11257d523365SDimitry Andric     normalizeSuccProbs();
1126f22ef01cSRoman Divacky   return Changed;
1127f22ef01cSRoman Divacky }
1128f22ef01cSRoman Divacky 
11297d523365SDimitry Andric /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
11307d523365SDimitry Andric /// instructions.  Return UnknownLoc if there is none.
1131f22ef01cSRoman Divacky DebugLoc
1132dff0c46cSDimitry Andric MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1133f22ef01cSRoman Divacky   DebugLoc DL;
1134dff0c46cSDimitry Andric   instr_iterator E = instr_end();
1135dff0c46cSDimitry Andric   if (MBBI == E)
1136dff0c46cSDimitry Andric     return DL;
1137dff0c46cSDimitry Andric 
1138f22ef01cSRoman Divacky   // Skip debug declarations, we don't want a DebugLoc from them.
1139dff0c46cSDimitry Andric   while (MBBI != E && MBBI->isDebugValue())
1140dff0c46cSDimitry Andric     MBBI++;
1141dff0c46cSDimitry Andric   if (MBBI != E)
1142dff0c46cSDimitry Andric     DL = MBBI->getDebugLoc();
1143f22ef01cSRoman Divacky   return DL;
1144f22ef01cSRoman Divacky }
1145f22ef01cSRoman Divacky 
11467d523365SDimitry Andric /// Return probability of the edge from this block to MBB.
11477d523365SDimitry Andric BranchProbability
11487d523365SDimitry Andric MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
11497d523365SDimitry Andric   if (Probs.empty())
11507d523365SDimitry Andric     return BranchProbability(1, succ_size());
115117a519f9SDimitry Andric 
11527d523365SDimitry Andric   const auto &Prob = *getProbabilityIterator(Succ);
11537d523365SDimitry Andric   if (Prob.isUnknown()) {
11547d523365SDimitry Andric     // For unknown probabilities, collect the sum of all known ones, and evenly
11557d523365SDimitry Andric     // ditribute the complemental of the sum to each unknown probability.
11567d523365SDimitry Andric     unsigned KnownProbNum = 0;
11577d523365SDimitry Andric     auto Sum = BranchProbability::getZero();
11587d523365SDimitry Andric     for (auto &P : Probs) {
11597d523365SDimitry Andric       if (!P.isUnknown()) {
11607d523365SDimitry Andric         Sum += P;
11617d523365SDimitry Andric         KnownProbNum++;
11627d523365SDimitry Andric       }
11637d523365SDimitry Andric     }
11647d523365SDimitry Andric     return Sum.getCompl() / (Probs.size() - KnownProbNum);
11657d523365SDimitry Andric   } else
11667d523365SDimitry Andric     return Prob;
116717a519f9SDimitry Andric }
116817a519f9SDimitry Andric 
11697d523365SDimitry Andric /// Set successor probability of a given iterator.
11707d523365SDimitry Andric void MachineBasicBlock::setSuccProbability(succ_iterator I,
11717d523365SDimitry Andric                                            BranchProbability Prob) {
11727d523365SDimitry Andric   assert(!Prob.isUnknown());
11737d523365SDimitry Andric   if (Probs.empty())
117491bc56edSDimitry Andric     return;
11757d523365SDimitry Andric   *getProbabilityIterator(I) = Prob;
117691bc56edSDimitry Andric }
117791bc56edSDimitry Andric 
11787d523365SDimitry Andric /// Return probability iterator corresonding to the I successor iterator
11797d523365SDimitry Andric MachineBasicBlock::const_probability_iterator
11807d523365SDimitry Andric MachineBasicBlock::getProbabilityIterator(
11817d523365SDimitry Andric     MachineBasicBlock::const_succ_iterator I) const {
11827d523365SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
1183dff0c46cSDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
11847d523365SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
11857d523365SDimitry Andric   return Probs.begin() + index;
11867d523365SDimitry Andric }
11877d523365SDimitry Andric 
11887d523365SDimitry Andric /// Return probability iterator corresonding to the I successor iterator.
11897d523365SDimitry Andric MachineBasicBlock::probability_iterator
11907d523365SDimitry Andric MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
11917d523365SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
11927d523365SDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
11937d523365SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
11947d523365SDimitry Andric   return Probs.begin() + index;
1195dff0c46cSDimitry Andric }
1196dff0c46cSDimitry Andric 
11973861d79fSDimitry Andric /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
11983861d79fSDimitry Andric /// as of just before "MI".
11993861d79fSDimitry Andric ///
12003861d79fSDimitry Andric /// Search is localised to a neighborhood of
12013861d79fSDimitry Andric /// Neighborhood instructions before (searching for defs or kills) and N
12023861d79fSDimitry Andric /// instructions after (searching just for defs) MI.
12033861d79fSDimitry Andric MachineBasicBlock::LivenessQueryResult
12043861d79fSDimitry Andric MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1205ff0cc061SDimitry Andric                                            unsigned Reg, const_iterator Before,
1206ff0cc061SDimitry Andric                                            unsigned Neighborhood) const {
12073861d79fSDimitry Andric   unsigned N = Neighborhood;
12083861d79fSDimitry Andric 
1209ff0cc061SDimitry Andric   // Start by searching backwards from Before, looking for kills, reads or defs.
1210ff0cc061SDimitry Andric   const_iterator I(Before);
12113861d79fSDimitry Andric   // If this is the first insn in the block, don't search backwards.
1212ff0cc061SDimitry Andric   if (I != begin()) {
12133861d79fSDimitry Andric     do {
12143861d79fSDimitry Andric       --I;
12153861d79fSDimitry Andric 
12167d523365SDimitry Andric       MachineOperandIteratorBase::PhysRegInfo Info =
12173ca95b02SDimitry Andric           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
12183861d79fSDimitry Andric 
12197d523365SDimitry Andric       // Defs happen after uses so they take precedence if both are present.
1220139f7f9bSDimitry Andric 
12217d523365SDimitry Andric       // Register is dead after a dead def of the full register.
12227d523365SDimitry Andric       if (Info.DeadDef)
12233861d79fSDimitry Andric         return LQR_Dead;
12247d523365SDimitry Andric       // Register is (at least partially) live after a def.
12253ca95b02SDimitry Andric       if (Info.Defined) {
12263ca95b02SDimitry Andric         if (!Info.PartialDeadDef)
12277d523365SDimitry Andric           return LQR_Live;
12283ca95b02SDimitry Andric         // As soon as we saw a partial definition (dead or not),
12293ca95b02SDimitry Andric         // we cannot tell if the value is partial live without
12303ca95b02SDimitry Andric         // tracking the lanemasks. We are not going to do this,
12313ca95b02SDimitry Andric         // so fall back on the remaining of the analysis.
12323ca95b02SDimitry Andric         break;
12333ca95b02SDimitry Andric       }
12347d523365SDimitry Andric       // Register is dead after a full kill or clobber and no def.
12357d523365SDimitry Andric       if (Info.Killed || Info.Clobbered)
12367d523365SDimitry Andric         return LQR_Dead;
12377d523365SDimitry Andric       // Register must be live if we read it.
12387d523365SDimitry Andric       if (Info.Read)
12397d523365SDimitry Andric         return LQR_Live;
1240ff0cc061SDimitry Andric     } while (I != begin() && --N > 0);
12413861d79fSDimitry Andric   }
12423861d79fSDimitry Andric 
12433861d79fSDimitry Andric   // Did we get to the start of the block?
1244ff0cc061SDimitry Andric   if (I == begin()) {
12453861d79fSDimitry Andric     // If so, the register's state is definitely defined by the live-in state.
12467d523365SDimitry Andric     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); RAI.isValid();
12477d523365SDimitry Andric          ++RAI)
1248ff0cc061SDimitry Andric       if (isLiveIn(*RAI))
12497d523365SDimitry Andric         return LQR_Live;
12503861d79fSDimitry Andric 
12513861d79fSDimitry Andric     return LQR_Dead;
12523861d79fSDimitry Andric   }
12533861d79fSDimitry Andric 
12543861d79fSDimitry Andric   N = Neighborhood;
12553861d79fSDimitry Andric 
1256ff0cc061SDimitry Andric   // Try searching forwards from Before, looking for reads or defs.
1257ff0cc061SDimitry Andric   I = const_iterator(Before);
12583861d79fSDimitry Andric   // If this is the last insn in the block, don't search forwards.
1259ff0cc061SDimitry Andric   if (I != end()) {
1260ff0cc061SDimitry Andric     for (++I; I != end() && N > 0; ++I, --N) {
12617d523365SDimitry Andric       MachineOperandIteratorBase::PhysRegInfo Info =
12623ca95b02SDimitry Andric           ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
12633861d79fSDimitry Andric 
12647d523365SDimitry Andric       // Register is live when we read it here.
12657d523365SDimitry Andric       if (Info.Read)
12667d523365SDimitry Andric         return LQR_Live;
12677d523365SDimitry Andric       // Register is dead if we can fully overwrite or clobber it here.
12687d523365SDimitry Andric       if (Info.FullyDefined || Info.Clobbered)
12693861d79fSDimitry Andric         return LQR_Dead;
12703861d79fSDimitry Andric     }
12713861d79fSDimitry Andric   }
12723861d79fSDimitry Andric 
12733861d79fSDimitry Andric   // At this point we have no idea of the liveness of the register.
12743861d79fSDimitry Andric   return LQR_Unknown;
12753861d79fSDimitry Andric }
12767d523365SDimitry Andric 
12777d523365SDimitry Andric const uint32_t *
12787d523365SDimitry Andric MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
12797d523365SDimitry Andric   // EH funclet entry does not preserve any registers.
12807d523365SDimitry Andric   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
12817d523365SDimitry Andric }
12827d523365SDimitry Andric 
12837d523365SDimitry Andric const uint32_t *
12847d523365SDimitry Andric MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
12857d523365SDimitry Andric   // If we see a return block with successors, this must be a funclet return,
12867d523365SDimitry Andric   // which does not preserve any registers. If there are no successors, we don't
12877d523365SDimitry Andric   // care what kind of return it is, putting a mask after it is a no-op.
12887d523365SDimitry Andric   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
12897d523365SDimitry Andric }
1290