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/ADT/SmallString.h"
17139f7f9bSDimitry Andric #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18ffd1746dSEd Schouten #include "llvm/CodeGen/LiveVariables.h"
19ffd1746dSEd Schouten #include "llvm/CodeGen/MachineDominators.h"
20f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineFunction.h"
21*6beeb091SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
22ffd1746dSEd Schouten #include "llvm/CodeGen/MachineLoopInfo.h"
23139f7f9bSDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
242754fe60SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
25139f7f9bSDimitry Andric #include "llvm/IR/BasicBlock.h"
26139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
273dac3a9bSDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
28f22ef01cSRoman Divacky #include "llvm/MC/MCAsmInfo.h"
29f22ef01cSRoman Divacky #include "llvm/MC/MCContext.h"
307d523365SDimitry Andric #include "llvm/Support/DataTypes.h"
31f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
32f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
33139f7f9bSDimitry Andric #include "llvm/Target/TargetInstrInfo.h"
34139f7f9bSDimitry Andric #include "llvm/Target/TargetMachine.h"
35139f7f9bSDimitry Andric #include "llvm/Target/TargetRegisterInfo.h"
3639d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
37f22ef01cSRoman Divacky #include <algorithm>
38f22ef01cSRoman Divacky using namespace llvm;
39f22ef01cSRoman Divacky 
4091bc56edSDimitry Andric #define DEBUG_TYPE "codegen"
4191bc56edSDimitry Andric 
427d523365SDimitry Andric MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
437d523365SDimitry Andric     : BB(B), Number(-1), xParent(&MF) {
44f22ef01cSRoman Divacky   Insts.Parent = this;
45f22ef01cSRoman Divacky }
46f22ef01cSRoman Divacky 
47f22ef01cSRoman Divacky MachineBasicBlock::~MachineBasicBlock() {
48f22ef01cSRoman Divacky }
49f22ef01cSRoman Divacky 
507d523365SDimitry Andric /// Return the MCSymbol for this basic block.
51f22ef01cSRoman Divacky MCSymbol *MachineBasicBlock::getSymbol() const {
52284c1978SDimitry Andric   if (!CachedMCSymbol) {
53f22ef01cSRoman Divacky     const MachineFunction *MF = getParent();
54f22ef01cSRoman Divacky     MCContext &Ctx = MF->getContext();
5539d628a0SDimitry Andric     const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
567d523365SDimitry Andric     assert(getNumber() >= 0 && "cannot get label for unreachable MBB");
57ff0cc061SDimitry Andric     CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
58284c1978SDimitry Andric                                            Twine(MF->getFunctionNumber()) +
59284c1978SDimitry Andric                                            "_" + Twine(getNumber()));
60284c1978SDimitry Andric   }
61284c1978SDimitry Andric 
62284c1978SDimitry Andric   return CachedMCSymbol;
63f22ef01cSRoman Divacky }
64f22ef01cSRoman Divacky 
65f22ef01cSRoman Divacky 
66f22ef01cSRoman Divacky raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
67f22ef01cSRoman Divacky   MBB.print(OS);
68f22ef01cSRoman Divacky   return OS;
69f22ef01cSRoman Divacky }
70f22ef01cSRoman Divacky 
717d523365SDimitry Andric /// When an MBB is added to an MF, we need to update the parent pointer of the
727d523365SDimitry Andric /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
737d523365SDimitry Andric /// operand list for registers.
74f22ef01cSRoman Divacky ///
75f22ef01cSRoman Divacky /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
76f22ef01cSRoman Divacky /// gets the next available unique MBB number. If it is removed from a
77f22ef01cSRoman Divacky /// MachineFunction, it goes back to being #-1.
78f22ef01cSRoman Divacky void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
79f22ef01cSRoman Divacky   MachineFunction &MF = *N->getParent();
80f22ef01cSRoman Divacky   N->Number = MF.addToMBBNumbering(N);
81f22ef01cSRoman Divacky 
82f22ef01cSRoman Divacky   // Make sure the instructions have their operands in the reginfo lists.
83f22ef01cSRoman Divacky   MachineRegisterInfo &RegInfo = MF.getRegInfo();
84dff0c46cSDimitry Andric   for (MachineBasicBlock::instr_iterator
85dff0c46cSDimitry Andric          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
86f22ef01cSRoman Divacky     I->AddRegOperandsToUseLists(RegInfo);
87f22ef01cSRoman Divacky }
88f22ef01cSRoman Divacky 
89f22ef01cSRoman Divacky void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
90f22ef01cSRoman Divacky   N->getParent()->removeFromMBBNumbering(N->Number);
91f22ef01cSRoman Divacky   N->Number = -1;
92f22ef01cSRoman Divacky }
93f22ef01cSRoman Divacky 
947d523365SDimitry Andric /// When we add an instruction to a basic block list, we update its parent
957d523365SDimitry Andric /// pointer and add its operands from reg use/def lists if appropriate.
96f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
9791bc56edSDimitry Andric   assert(!N->getParent() && "machine instruction already in a basic block");
98f22ef01cSRoman Divacky   N->setParent(Parent);
99f22ef01cSRoman Divacky 
100f22ef01cSRoman Divacky   // Add the instruction's register operands to their corresponding
101f22ef01cSRoman Divacky   // use/def lists.
102f22ef01cSRoman Divacky   MachineFunction *MF = Parent->getParent();
103f22ef01cSRoman Divacky   N->AddRegOperandsToUseLists(MF->getRegInfo());
104f22ef01cSRoman Divacky }
105f22ef01cSRoman Divacky 
1067d523365SDimitry Andric /// When we remove an instruction from a basic block list, we update its parent
1077d523365SDimitry Andric /// pointer and remove its operands from reg use/def lists if appropriate.
108f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
10991bc56edSDimitry Andric   assert(N->getParent() && "machine instruction not in a basic block");
110f22ef01cSRoman Divacky 
111f22ef01cSRoman Divacky   // Remove from the use/def lists.
1127ae0e2c9SDimitry Andric   if (MachineFunction *MF = N->getParent()->getParent())
1137ae0e2c9SDimitry Andric     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
114f22ef01cSRoman Divacky 
11591bc56edSDimitry Andric   N->setParent(nullptr);
116f22ef01cSRoman Divacky }
117f22ef01cSRoman Divacky 
1187d523365SDimitry Andric /// When moving a range of instructions from one MBB list to another, we need to
1197d523365SDimitry Andric /// update the parent pointers and the use/def lists.
120f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::
1217d523365SDimitry Andric transferNodesFromList(ilist_traits<MachineInstr> &FromList,
1227d523365SDimitry Andric                       ilist_iterator<MachineInstr> First,
1237d523365SDimitry Andric                       ilist_iterator<MachineInstr> Last) {
1247d523365SDimitry Andric   assert(Parent->getParent() == FromList.Parent->getParent() &&
125f22ef01cSRoman Divacky         "MachineInstr parent mismatch!");
126f22ef01cSRoman Divacky 
127f22ef01cSRoman Divacky   // Splice within the same MBB -> no change.
1287d523365SDimitry Andric   if (Parent == FromList.Parent) return;
129f22ef01cSRoman Divacky 
130f22ef01cSRoman Divacky   // If splicing between two blocks within the same function, just update the
131f22ef01cSRoman Divacky   // parent pointers.
1327d523365SDimitry Andric   for (; First != Last; ++First)
1337d523365SDimitry Andric     First->setParent(Parent);
134f22ef01cSRoman Divacky }
135f22ef01cSRoman Divacky 
136f22ef01cSRoman Divacky void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
137f22ef01cSRoman Divacky   assert(!MI->getParent() && "MI is still in a block!");
138f22ef01cSRoman Divacky   Parent->getParent()->DeleteMachineInstr(MI);
139f22ef01cSRoman Divacky }
140f22ef01cSRoman Divacky 
141ffd1746dSEd Schouten MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
142dff0c46cSDimitry Andric   instr_iterator I = instr_begin(), E = instr_end();
143dff0c46cSDimitry Andric   while (I != E && I->isPHI())
144ffd1746dSEd Schouten     ++I;
1453861d79fSDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
1463861d79fSDimitry Andric          "First non-phi MI cannot be inside a bundle!");
147ffd1746dSEd Schouten   return I;
148ffd1746dSEd Schouten }
149ffd1746dSEd Schouten 
1502754fe60SDimitry Andric MachineBasicBlock::iterator
1512754fe60SDimitry Andric MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
152dff0c46cSDimitry Andric   iterator E = end();
15391bc56edSDimitry Andric   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
1542754fe60SDimitry Andric     ++I;
155dff0c46cSDimitry Andric   // FIXME: This needs to change if we wish to bundle labels / dbg_values
156dff0c46cSDimitry Andric   // inside the bundle.
1573861d79fSDimitry Andric   assert((I == E || !I->isInsideBundle()) &&
158dff0c46cSDimitry Andric          "First non-phi / non-label instruction is inside a bundle!");
1592754fe60SDimitry Andric   return I;
1602754fe60SDimitry Andric }
1612754fe60SDimitry Andric 
162f22ef01cSRoman Divacky MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
163dff0c46cSDimitry Andric   iterator B = begin(), E = end(), I = E;
164dff0c46cSDimitry Andric   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
165f22ef01cSRoman Divacky     ; /*noop */
166dff0c46cSDimitry Andric   while (I != E && !I->isTerminator())
167dff0c46cSDimitry Andric     ++I;
168dff0c46cSDimitry Andric   return I;
169dff0c46cSDimitry Andric }
170dff0c46cSDimitry Andric 
171dff0c46cSDimitry Andric MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
172dff0c46cSDimitry Andric   instr_iterator B = instr_begin(), E = instr_end(), I = E;
173dff0c46cSDimitry Andric   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
174dff0c46cSDimitry Andric     ; /*noop */
175dff0c46cSDimitry Andric   while (I != E && !I->isTerminator())
1762754fe60SDimitry Andric     ++I;
177f22ef01cSRoman Divacky   return I;
178f22ef01cSRoman Divacky }
179f22ef01cSRoman Divacky 
1803dac3a9bSDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
1813dac3a9bSDimitry Andric   // Skip over begin-of-block dbg_value instructions.
1823dac3a9bSDimitry Andric   iterator I = begin(), E = end();
1833dac3a9bSDimitry Andric   while (I != E && I->isDebugValue())
1843dac3a9bSDimitry Andric     ++I;
1853dac3a9bSDimitry Andric   return I;
1863dac3a9bSDimitry Andric }
1873dac3a9bSDimitry Andric 
1882754fe60SDimitry Andric MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
189dff0c46cSDimitry Andric   // Skip over end-of-block dbg_value instructions.
190dff0c46cSDimitry Andric   instr_iterator B = instr_begin(), I = instr_end();
1912754fe60SDimitry Andric   while (I != B) {
1922754fe60SDimitry Andric     --I;
193dff0c46cSDimitry Andric     // Return instruction that starts a bundle.
194dff0c46cSDimitry Andric     if (I->isDebugValue() || I->isInsideBundle())
195dff0c46cSDimitry Andric       continue;
196dff0c46cSDimitry Andric     return I;
197dff0c46cSDimitry Andric   }
198dff0c46cSDimitry Andric   // The block is all debug values.
199dff0c46cSDimitry Andric   return end();
200dff0c46cSDimitry Andric }
201dff0c46cSDimitry Andric 
2022754fe60SDimitry Andric const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
2032754fe60SDimitry Andric   // A block with a landing pad successor only has one other successor.
2042754fe60SDimitry Andric   if (succ_size() > 2)
20591bc56edSDimitry Andric     return nullptr;
2062754fe60SDimitry Andric   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
2077d523365SDimitry Andric     if ((*I)->isEHPad())
2082754fe60SDimitry Andric       return *I;
20991bc56edSDimitry Andric   return nullptr;
2102754fe60SDimitry Andric }
2112754fe60SDimitry Andric 
2127d523365SDimitry Andric bool MachineBasicBlock::hasEHPadSuccessor() const {
2137d523365SDimitry Andric   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
2147d523365SDimitry Andric     if ((*I)->isEHPad())
2157d523365SDimitry Andric       return true;
2167d523365SDimitry Andric   return false;
2177d523365SDimitry Andric }
2187d523365SDimitry Andric 
2193861d79fSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
220f22ef01cSRoman Divacky void MachineBasicBlock::dump() const {
221f22ef01cSRoman Divacky   print(dbgs());
222f22ef01cSRoman Divacky }
2233861d79fSDimitry Andric #endif
224f22ef01cSRoman Divacky 
225f22ef01cSRoman Divacky StringRef MachineBasicBlock::getName() const {
226f22ef01cSRoman Divacky   if (const BasicBlock *LBB = getBasicBlock())
227f22ef01cSRoman Divacky     return LBB->getName();
228f22ef01cSRoman Divacky   else
229f22ef01cSRoman Divacky     return "(null)";
230f22ef01cSRoman Divacky }
231f22ef01cSRoman Divacky 
232dff0c46cSDimitry Andric /// Return a hopefully unique identifier for this block.
233dff0c46cSDimitry Andric std::string MachineBasicBlock::getFullName() const {
234dff0c46cSDimitry Andric   std::string Name;
235dff0c46cSDimitry Andric   if (getParent())
2363861d79fSDimitry Andric     Name = (getParent()->getName() + ":").str();
237dff0c46cSDimitry Andric   if (getBasicBlock())
238dff0c46cSDimitry Andric     Name += getBasicBlock()->getName();
239dff0c46cSDimitry Andric   else
240ff0cc061SDimitry Andric     Name += ("BB" + Twine(getNumber())).str();
241dff0c46cSDimitry Andric   return Name;
242dff0c46cSDimitry Andric }
243dff0c46cSDimitry Andric 
2442754fe60SDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
245f22ef01cSRoman Divacky   const MachineFunction *MF = getParent();
246f22ef01cSRoman Divacky   if (!MF) {
247f22ef01cSRoman Divacky     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
248f22ef01cSRoman Divacky        << " is null\n";
249f22ef01cSRoman Divacky     return;
250f22ef01cSRoman Divacky   }
2513dac3a9bSDimitry Andric   const Function *F = MF->getFunction();
2523dac3a9bSDimitry Andric   const Module *M = F ? F->getParent() : nullptr;
2533dac3a9bSDimitry Andric   ModuleSlotTracker MST(M);
2543dac3a9bSDimitry Andric   print(OS, MST, Indexes);
2553dac3a9bSDimitry Andric }
2563dac3a9bSDimitry Andric 
2573dac3a9bSDimitry Andric void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
2583dac3a9bSDimitry Andric                               SlotIndexes *Indexes) const {
2593dac3a9bSDimitry Andric   const MachineFunction *MF = getParent();
2603dac3a9bSDimitry Andric   if (!MF) {
2613dac3a9bSDimitry Andric     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
2623dac3a9bSDimitry Andric        << " is null\n";
2633dac3a9bSDimitry Andric     return;
2643dac3a9bSDimitry Andric   }
265f22ef01cSRoman Divacky 
2662754fe60SDimitry Andric   if (Indexes)
2672754fe60SDimitry Andric     OS << Indexes->getMBBStartIdx(this) << '\t';
2682754fe60SDimitry Andric 
269f22ef01cSRoman Divacky   OS << "BB#" << getNumber() << ": ";
270f22ef01cSRoman Divacky 
271f22ef01cSRoman Divacky   const char *Comma = "";
272f22ef01cSRoman Divacky   if (const BasicBlock *LBB = getBasicBlock()) {
273f22ef01cSRoman Divacky     OS << Comma << "derived from LLVM BB ";
2743dac3a9bSDimitry Andric     LBB->printAsOperand(OS, /*PrintType=*/false, MST);
275f22ef01cSRoman Divacky     Comma = ", ";
276f22ef01cSRoman Divacky   }
2777d523365SDimitry Andric   if (isEHPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
278f22ef01cSRoman Divacky   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
2797ae0e2c9SDimitry Andric   if (Alignment)
280dff0c46cSDimitry Andric     OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
281dff0c46cSDimitry Andric        << " bytes)";
282dff0c46cSDimitry Andric 
283f22ef01cSRoman Divacky   OS << '\n';
284f22ef01cSRoman Divacky 
28539d628a0SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
286f22ef01cSRoman Divacky   if (!livein_empty()) {
2872754fe60SDimitry Andric     if (Indexes) OS << '\t';
288f22ef01cSRoman Divacky     OS << "    Live Ins:";
2897d523365SDimitry Andric     for (const auto &LI : make_range(livein_begin(), livein_end())) {
2907d523365SDimitry Andric       OS << ' ' << PrintReg(LI.PhysReg, TRI);
2917d523365SDimitry Andric       if (LI.LaneMask != ~0u)
2927d523365SDimitry Andric         OS << ':' << PrintLaneMask(LI.LaneMask);
2937d523365SDimitry Andric     }
294f22ef01cSRoman Divacky     OS << '\n';
295f22ef01cSRoman Divacky   }
296f22ef01cSRoman Divacky   // Print the preds of this block according to the CFG.
297f22ef01cSRoman Divacky   if (!pred_empty()) {
2982754fe60SDimitry Andric     if (Indexes) OS << '\t';
299f22ef01cSRoman Divacky     OS << "    Predecessors according to CFG:";
300f22ef01cSRoman Divacky     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
301f22ef01cSRoman Divacky       OS << " BB#" << (*PI)->getNumber();
302f22ef01cSRoman Divacky     OS << '\n';
303f22ef01cSRoman Divacky   }
304f22ef01cSRoman Divacky 
305dff0c46cSDimitry Andric   for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
3062754fe60SDimitry Andric     if (Indexes) {
3077d523365SDimitry Andric       if (Indexes->hasIndex(&*I))
3087d523365SDimitry Andric         OS << Indexes->getInstructionIndex(&*I);
3092754fe60SDimitry Andric       OS << '\t';
3102754fe60SDimitry Andric     }
311f22ef01cSRoman Divacky     OS << '\t';
312dff0c46cSDimitry Andric     if (I->isInsideBundle())
313dff0c46cSDimitry Andric       OS << "  * ";
3143dac3a9bSDimitry Andric     I->print(OS, MST);
315f22ef01cSRoman Divacky   }
316f22ef01cSRoman Divacky 
317f22ef01cSRoman Divacky   // Print the successors of this block according to the CFG.
318f22ef01cSRoman Divacky   if (!succ_empty()) {
3192754fe60SDimitry Andric     if (Indexes) OS << '\t';
320f22ef01cSRoman Divacky     OS << "    Successors according to CFG:";
3217ae0e2c9SDimitry Andric     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
322f22ef01cSRoman Divacky       OS << " BB#" << (*SI)->getNumber();
3237d523365SDimitry Andric       if (!Probs.empty())
3247d523365SDimitry Andric         OS << '(' << *getProbabilityIterator(SI) << ')';
3257ae0e2c9SDimitry Andric     }
326f22ef01cSRoman Divacky     OS << '\n';
327f22ef01cSRoman Divacky   }
328f22ef01cSRoman Divacky }
329f22ef01cSRoman Divacky 
3307d523365SDimitry Andric void MachineBasicBlock::printAsOperand(raw_ostream &OS,
3317d523365SDimitry Andric                                        bool /*PrintType*/) const {
33291bc56edSDimitry Andric   OS << "BB#" << getNumber();
33391bc56edSDimitry Andric }
33491bc56edSDimitry Andric 
3357d523365SDimitry Andric void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
3367d523365SDimitry Andric   LiveInVector::iterator I = std::find_if(
3377d523365SDimitry Andric       LiveIns.begin(), LiveIns.end(),
3387d523365SDimitry Andric       [Reg] (const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
3397d523365SDimitry Andric   if (I == LiveIns.end())
3407d523365SDimitry Andric     return;
3417d523365SDimitry Andric 
3427d523365SDimitry Andric   I->LaneMask &= ~LaneMask;
3437d523365SDimitry Andric   if (I->LaneMask == 0)
344f22ef01cSRoman Divacky     LiveIns.erase(I);
345f22ef01cSRoman Divacky }
346f22ef01cSRoman Divacky 
3477d523365SDimitry Andric bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
3487d523365SDimitry Andric   livein_iterator I = std::find_if(
3497d523365SDimitry Andric       LiveIns.begin(), LiveIns.end(),
3507d523365SDimitry Andric       [Reg] (const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
3517d523365SDimitry Andric   return I != livein_end() && (I->LaneMask & LaneMask) != 0;
3527d523365SDimitry Andric }
3537d523365SDimitry Andric 
3547d523365SDimitry Andric void MachineBasicBlock::sortUniqueLiveIns() {
3557d523365SDimitry Andric   std::sort(LiveIns.begin(), LiveIns.end(),
3567d523365SDimitry Andric             [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
3577d523365SDimitry Andric               return LI0.PhysReg < LI1.PhysReg;
3587d523365SDimitry Andric             });
3597d523365SDimitry Andric   // Liveins are sorted by physreg now we can merge their lanemasks.
3607d523365SDimitry Andric   LiveInVector::const_iterator I = LiveIns.begin();
3617d523365SDimitry Andric   LiveInVector::const_iterator J;
3627d523365SDimitry Andric   LiveInVector::iterator Out = LiveIns.begin();
3637d523365SDimitry Andric   for (; I != LiveIns.end(); ++Out, I = J) {
3647d523365SDimitry Andric     unsigned PhysReg = I->PhysReg;
3657d523365SDimitry Andric     LaneBitmask LaneMask = I->LaneMask;
3667d523365SDimitry Andric     for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
3677d523365SDimitry Andric       LaneMask |= J->LaneMask;
3687d523365SDimitry Andric     Out->PhysReg = PhysReg;
3697d523365SDimitry Andric     Out->LaneMask = LaneMask;
3707d523365SDimitry Andric   }
3717d523365SDimitry Andric   LiveIns.erase(Out, LiveIns.end());
372f22ef01cSRoman Divacky }
373f22ef01cSRoman Divacky 
374*6beeb091SDimitry Andric unsigned
3757d523365SDimitry Andric MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
376*6beeb091SDimitry Andric   assert(getParent() && "MBB must be inserted in function");
377*6beeb091SDimitry Andric   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
378*6beeb091SDimitry Andric   assert(RC && "Register class is required");
3797d523365SDimitry Andric   assert((isEHPad() || this == &getParent()->front()) &&
380*6beeb091SDimitry Andric          "Only the entry block and landing pads can have physreg live ins");
381*6beeb091SDimitry Andric 
382*6beeb091SDimitry Andric   bool LiveIn = isLiveIn(PhysReg);
383*6beeb091SDimitry Andric   iterator I = SkipPHIsAndLabels(begin()), E = end();
384*6beeb091SDimitry Andric   MachineRegisterInfo &MRI = getParent()->getRegInfo();
38539d628a0SDimitry Andric   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
386*6beeb091SDimitry Andric 
387*6beeb091SDimitry Andric   // Look for an existing copy.
388*6beeb091SDimitry Andric   if (LiveIn)
389*6beeb091SDimitry Andric     for (;I != E && I->isCopy(); ++I)
390*6beeb091SDimitry Andric       if (I->getOperand(1).getReg() == PhysReg) {
391*6beeb091SDimitry Andric         unsigned VirtReg = I->getOperand(0).getReg();
392*6beeb091SDimitry Andric         if (!MRI.constrainRegClass(VirtReg, RC))
393*6beeb091SDimitry Andric           llvm_unreachable("Incompatible live-in register class.");
394*6beeb091SDimitry Andric         return VirtReg;
395*6beeb091SDimitry Andric       }
396*6beeb091SDimitry Andric 
397*6beeb091SDimitry Andric   // No luck, create a virtual register.
398*6beeb091SDimitry Andric   unsigned VirtReg = MRI.createVirtualRegister(RC);
399*6beeb091SDimitry Andric   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
400*6beeb091SDimitry Andric     .addReg(PhysReg, RegState::Kill);
401*6beeb091SDimitry Andric   if (!LiveIn)
402*6beeb091SDimitry Andric     addLiveIn(PhysReg);
403*6beeb091SDimitry Andric   return VirtReg;
404*6beeb091SDimitry Andric }
405*6beeb091SDimitry Andric 
406f22ef01cSRoman Divacky void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
4077d523365SDimitry Andric   getParent()->splice(NewAfter->getIterator(), getIterator());
408f22ef01cSRoman Divacky }
409f22ef01cSRoman Divacky 
410f22ef01cSRoman Divacky void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
4117d523365SDimitry Andric   getParent()->splice(++NewBefore->getIterator(), getIterator());
412f22ef01cSRoman Divacky }
413f22ef01cSRoman Divacky 
414f22ef01cSRoman Divacky void MachineBasicBlock::updateTerminator() {
41539d628a0SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
416f22ef01cSRoman Divacky   // A block with no successors has no concerns with fall-through edges.
417f22ef01cSRoman Divacky   if (this->succ_empty()) return;
418f22ef01cSRoman Divacky 
41991bc56edSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
420f22ef01cSRoman Divacky   SmallVector<MachineOperand, 4> Cond;
4217d523365SDimitry Andric   DebugLoc DL;  // FIXME: this is nowhere
422f22ef01cSRoman Divacky   bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
423f22ef01cSRoman Divacky   (void) B;
424f22ef01cSRoman Divacky   assert(!B && "UpdateTerminators requires analyzable predecessors!");
425f22ef01cSRoman Divacky   if (Cond.empty()) {
426f22ef01cSRoman Divacky     if (TBB) {
427f22ef01cSRoman Divacky       // The block has an unconditional branch. If its successor is now
428f22ef01cSRoman Divacky       // its layout successor, delete the branch.
429f22ef01cSRoman Divacky       if (isLayoutSuccessor(TBB))
430f22ef01cSRoman Divacky         TII->RemoveBranch(*this);
431f22ef01cSRoman Divacky     } else {
432f22ef01cSRoman Divacky       // The block has an unconditional fallthrough. If its successor is not
433dff0c46cSDimitry Andric       // its layout successor, insert a branch. First we have to locate the
434dff0c46cSDimitry Andric       // only non-landing-pad successor, as that is the fallthrough block.
435dff0c46cSDimitry Andric       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
4367d523365SDimitry Andric         if ((*SI)->isEHPad())
437dff0c46cSDimitry Andric           continue;
438dff0c46cSDimitry Andric         assert(!TBB && "Found more than one non-landing-pad successor!");
439dff0c46cSDimitry Andric         TBB = *SI;
440dff0c46cSDimitry Andric       }
441dff0c46cSDimitry Andric 
442dff0c46cSDimitry Andric       // If there is no non-landing-pad successor, the block has no
443dff0c46cSDimitry Andric       // fall-through edges to be concerned with.
444dff0c46cSDimitry Andric       if (!TBB)
445dff0c46cSDimitry Andric         return;
446dff0c46cSDimitry Andric 
447dff0c46cSDimitry Andric       // Finally update the unconditional successor to be reached via a branch
448dff0c46cSDimitry Andric       // if it would not be reached by fallthrough.
449f22ef01cSRoman Divacky       if (!isLayoutSuccessor(TBB))
4507d523365SDimitry Andric         TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
451f22ef01cSRoman Divacky     }
452f22ef01cSRoman Divacky   } else {
453f22ef01cSRoman Divacky     if (FBB) {
454f22ef01cSRoman Divacky       // The block has a non-fallthrough conditional branch. If one of its
455f22ef01cSRoman Divacky       // successors is its layout successor, rewrite it to a fallthrough
456f22ef01cSRoman Divacky       // conditional branch.
457f22ef01cSRoman Divacky       if (isLayoutSuccessor(TBB)) {
458f22ef01cSRoman Divacky         if (TII->ReverseBranchCondition(Cond))
459f22ef01cSRoman Divacky           return;
460f22ef01cSRoman Divacky         TII->RemoveBranch(*this);
4617d523365SDimitry Andric         TII->InsertBranch(*this, FBB, nullptr, Cond, DL);
462f22ef01cSRoman Divacky       } else if (isLayoutSuccessor(FBB)) {
463f22ef01cSRoman Divacky         TII->RemoveBranch(*this);
4647d523365SDimitry Andric         TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
465f22ef01cSRoman Divacky       }
466f22ef01cSRoman Divacky     } else {
467cb4dff85SDimitry Andric       // Walk through the successors and find the successor which is not
468cb4dff85SDimitry Andric       // a landing pad and is not the conditional branch destination (in TBB)
469cb4dff85SDimitry Andric       // as the fallthrough successor.
47091bc56edSDimitry Andric       MachineBasicBlock *FallthroughBB = nullptr;
471cb4dff85SDimitry Andric       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
4727d523365SDimitry Andric         if ((*SI)->isEHPad() || *SI == TBB)
473cb4dff85SDimitry Andric           continue;
474cb4dff85SDimitry Andric         assert(!FallthroughBB && "Found more than one fallthrough successor.");
475cb4dff85SDimitry Andric         FallthroughBB = *SI;
476cb4dff85SDimitry Andric       }
477cb4dff85SDimitry Andric       if (!FallthroughBB && canFallThrough()) {
478cb4dff85SDimitry Andric         // We fallthrough to the same basic block as the conditional jump
479cb4dff85SDimitry Andric         // targets. Remove the conditional jump, leaving unconditional
480cb4dff85SDimitry Andric         // fallthrough.
4817d523365SDimitry Andric         // FIXME: This does not seem like a reasonable pattern to support, but
4827d523365SDimitry Andric         // it has been seen in the wild coming out of degenerate ARM test cases.
483cb4dff85SDimitry Andric         TII->RemoveBranch(*this);
484cb4dff85SDimitry Andric 
485cb4dff85SDimitry Andric         // Finally update the unconditional successor to be reached via a branch
486cb4dff85SDimitry Andric         // if it would not be reached by fallthrough.
487cb4dff85SDimitry Andric         if (!isLayoutSuccessor(TBB))
4887d523365SDimitry Andric           TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
489cb4dff85SDimitry Andric         return;
490cb4dff85SDimitry Andric       }
491cb4dff85SDimitry Andric 
492f22ef01cSRoman Divacky       // The block has a fallthrough conditional branch.
493f22ef01cSRoman Divacky       if (isLayoutSuccessor(TBB)) {
494f22ef01cSRoman Divacky         if (TII->ReverseBranchCondition(Cond)) {
495f22ef01cSRoman Divacky           // We can't reverse the condition, add an unconditional branch.
496f22ef01cSRoman Divacky           Cond.clear();
4977d523365SDimitry Andric           TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, DL);
498f22ef01cSRoman Divacky           return;
499f22ef01cSRoman Divacky         }
500f22ef01cSRoman Divacky         TII->RemoveBranch(*this);
5017d523365SDimitry Andric         TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, DL);
502cb4dff85SDimitry Andric       } else if (!isLayoutSuccessor(FallthroughBB)) {
503f22ef01cSRoman Divacky         TII->RemoveBranch(*this);
5047d523365SDimitry Andric         TII->InsertBranch(*this, TBB, FallthroughBB, Cond, DL);
505f22ef01cSRoman Divacky       }
506f22ef01cSRoman Divacky     }
507f22ef01cSRoman Divacky   }
508f22ef01cSRoman Divacky }
509f22ef01cSRoman Divacky 
5107d523365SDimitry Andric void MachineBasicBlock::validateSuccProbs() const {
5117d523365SDimitry Andric #ifndef NDEBUG
5127d523365SDimitry Andric   int64_t Sum = 0;
5137d523365SDimitry Andric   for (auto Prob : Probs)
5147d523365SDimitry Andric     Sum += Prob.getNumerator();
5157d523365SDimitry Andric   // Due to precision issue, we assume that the sum of probabilities is one if
5167d523365SDimitry Andric   // the difference between the sum of their numerators and the denominator is
5177d523365SDimitry Andric   // no greater than the number of successors.
5187d523365SDimitry Andric   assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
5197d523365SDimitry Andric              Probs.size() &&
5207d523365SDimitry Andric          "The sum of successors's probabilities exceeds one.");
5217d523365SDimitry Andric #endif // NDEBUG
522f22ef01cSRoman Divacky }
523f22ef01cSRoman Divacky 
5247d523365SDimitry Andric void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
5257d523365SDimitry Andric                                      BranchProbability Prob) {
5267d523365SDimitry Andric   // Probability list is either empty (if successor list isn't empty, this means
5277d523365SDimitry Andric   // disabled optimization) or has the same size as successor list.
5287d523365SDimitry Andric   if (!(Probs.empty() && !Successors.empty()))
5297d523365SDimitry Andric     Probs.push_back(Prob);
5307d523365SDimitry Andric   Successors.push_back(Succ);
5317d523365SDimitry Andric   Succ->addPredecessor(this);
53217a519f9SDimitry Andric }
53317a519f9SDimitry Andric 
5347d523365SDimitry Andric void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
5357d523365SDimitry Andric   // We need to make sure probability list is either empty or has the same size
5367d523365SDimitry Andric   // of successor list. When this function is called, we can safely delete all
5377d523365SDimitry Andric   // probability in the list.
5387d523365SDimitry Andric   Probs.clear();
5397d523365SDimitry Andric   Successors.push_back(Succ);
5407d523365SDimitry Andric   Succ->addPredecessor(this);
5417d523365SDimitry Andric }
5427d523365SDimitry Andric 
5437d523365SDimitry Andric void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
5447d523365SDimitry Andric                                         bool NormalizeSuccProbs) {
5457d523365SDimitry Andric   succ_iterator I = std::find(Successors.begin(), Successors.end(), Succ);
5467d523365SDimitry Andric   removeSuccessor(I, NormalizeSuccProbs);
547f22ef01cSRoman Divacky }
548f22ef01cSRoman Divacky 
549f22ef01cSRoman Divacky MachineBasicBlock::succ_iterator
5507d523365SDimitry Andric MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
551f22ef01cSRoman Divacky   assert(I != Successors.end() && "Not a current successor!");
55217a519f9SDimitry Andric 
5537d523365SDimitry Andric   // If probability list is empty it means we don't use it (disabled
5547d523365SDimitry Andric   // optimization).
5557d523365SDimitry Andric   if (!Probs.empty()) {
5567d523365SDimitry Andric     probability_iterator WI = getProbabilityIterator(I);
5577d523365SDimitry Andric     Probs.erase(WI);
5587d523365SDimitry Andric     if (NormalizeSuccProbs)
5597d523365SDimitry Andric       normalizeSuccProbs();
56017a519f9SDimitry Andric   }
56117a519f9SDimitry Andric 
562f22ef01cSRoman Divacky   (*I)->removePredecessor(this);
563f22ef01cSRoman Divacky   return Successors.erase(I);
564f22ef01cSRoman Divacky }
565f22ef01cSRoman Divacky 
56617a519f9SDimitry Andric void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
56717a519f9SDimitry Andric                                          MachineBasicBlock *New) {
5687ae0e2c9SDimitry Andric   if (Old == New)
5697ae0e2c9SDimitry Andric     return;
57017a519f9SDimitry Andric 
5717ae0e2c9SDimitry Andric   succ_iterator E = succ_end();
5727ae0e2c9SDimitry Andric   succ_iterator NewI = E;
5737ae0e2c9SDimitry Andric   succ_iterator OldI = E;
5747ae0e2c9SDimitry Andric   for (succ_iterator I = succ_begin(); I != E; ++I) {
5757ae0e2c9SDimitry Andric     if (*I == Old) {
5767ae0e2c9SDimitry Andric       OldI = I;
5777ae0e2c9SDimitry Andric       if (NewI != E)
5787ae0e2c9SDimitry Andric         break;
5797ae0e2c9SDimitry Andric     }
5807ae0e2c9SDimitry Andric     if (*I == New) {
5817ae0e2c9SDimitry Andric       NewI = I;
5827ae0e2c9SDimitry Andric       if (OldI != E)
5837ae0e2c9SDimitry Andric         break;
5847ae0e2c9SDimitry Andric     }
5857ae0e2c9SDimitry Andric   }
5867ae0e2c9SDimitry Andric   assert(OldI != E && "Old is not a successor of this block");
5877ae0e2c9SDimitry Andric 
5887ae0e2c9SDimitry Andric   // If New isn't already a successor, let it take Old's place.
5897ae0e2c9SDimitry Andric   if (NewI == E) {
5907d523365SDimitry Andric     Old->removePredecessor(this);
5917ae0e2c9SDimitry Andric     New->addPredecessor(this);
5927ae0e2c9SDimitry Andric     *OldI = New;
5937ae0e2c9SDimitry Andric     return;
59417a519f9SDimitry Andric   }
59517a519f9SDimitry Andric 
5967ae0e2c9SDimitry Andric   // New is already a successor.
5977d523365SDimitry Andric   // Update its probability instead of adding a duplicate edge.
5987d523365SDimitry Andric   if (!Probs.empty()) {
5997d523365SDimitry Andric     auto ProbIter = getProbabilityIterator(NewI);
6007d523365SDimitry Andric     if (!ProbIter->isUnknown())
6017d523365SDimitry Andric       *ProbIter += *getProbabilityIterator(OldI);
6027ae0e2c9SDimitry Andric   }
6037d523365SDimitry Andric   removeSuccessor(OldI);
60417a519f9SDimitry Andric }
60517a519f9SDimitry Andric 
6067d523365SDimitry Andric void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
6077d523365SDimitry Andric   Predecessors.push_back(Pred);
608f22ef01cSRoman Divacky }
609f22ef01cSRoman Divacky 
6107d523365SDimitry Andric void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
6117d523365SDimitry Andric   pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), Pred);
612f22ef01cSRoman Divacky   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
613f22ef01cSRoman Divacky   Predecessors.erase(I);
614f22ef01cSRoman Divacky }
615f22ef01cSRoman Divacky 
6167d523365SDimitry Andric void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
6177d523365SDimitry Andric   if (this == FromMBB)
618f22ef01cSRoman Divacky     return;
619f22ef01cSRoman Divacky 
6207d523365SDimitry Andric   while (!FromMBB->succ_empty()) {
6217d523365SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
62217a519f9SDimitry Andric 
6237d523365SDimitry Andric     // If probability list is empty it means we don't use it (disabled optimization).
6247d523365SDimitry Andric     if (!FromMBB->Probs.empty()) {
6257d523365SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
6267d523365SDimitry Andric       addSuccessor(Succ, Prob);
6277d523365SDimitry Andric     } else
6287d523365SDimitry Andric       addSuccessorWithoutProb(Succ);
62917a519f9SDimitry Andric 
6307d523365SDimitry Andric     FromMBB->removeSuccessor(Succ);
631ffd1746dSEd Schouten   }
632ffd1746dSEd Schouten }
633f22ef01cSRoman Divacky 
634ffd1746dSEd Schouten void
6357d523365SDimitry Andric MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
6367d523365SDimitry Andric   if (this == FromMBB)
637ffd1746dSEd Schouten     return;
638ffd1746dSEd Schouten 
6397d523365SDimitry Andric   while (!FromMBB->succ_empty()) {
6407d523365SDimitry Andric     MachineBasicBlock *Succ = *FromMBB->succ_begin();
6417d523365SDimitry Andric     if (!FromMBB->Probs.empty()) {
6427d523365SDimitry Andric       auto Prob = *FromMBB->Probs.begin();
6437d523365SDimitry Andric       addSuccessor(Succ, Prob);
6447d523365SDimitry Andric     } else
6457d523365SDimitry Andric       addSuccessorWithoutProb(Succ);
6467d523365SDimitry Andric     FromMBB->removeSuccessor(Succ);
647ffd1746dSEd Schouten 
648ffd1746dSEd Schouten     // Fix up any PHI nodes in the successor.
649dff0c46cSDimitry Andric     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
650dff0c46cSDimitry Andric            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
651ffd1746dSEd Schouten       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
652ffd1746dSEd Schouten         MachineOperand &MO = MI->getOperand(i);
6537d523365SDimitry Andric         if (MO.getMBB() == FromMBB)
654ffd1746dSEd Schouten           MO.setMBB(this);
655ffd1746dSEd Schouten       }
656ffd1746dSEd Schouten   }
6577d523365SDimitry Andric   normalizeSuccProbs();
658f22ef01cSRoman Divacky }
659f22ef01cSRoman Divacky 
6607ae0e2c9SDimitry Andric bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
6617ae0e2c9SDimitry Andric   return std::find(pred_begin(), pred_end(), MBB) != pred_end();
6627ae0e2c9SDimitry Andric }
6637ae0e2c9SDimitry Andric 
664f22ef01cSRoman Divacky bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
6657ae0e2c9SDimitry Andric   return std::find(succ_begin(), succ_end(), MBB) != succ_end();
666f22ef01cSRoman Divacky }
667f22ef01cSRoman Divacky 
668f22ef01cSRoman Divacky bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
669f22ef01cSRoman Divacky   MachineFunction::const_iterator I(this);
67091bc56edSDimitry Andric   return std::next(I) == MachineFunction::const_iterator(MBB);
671f22ef01cSRoman Divacky }
672f22ef01cSRoman Divacky 
673f22ef01cSRoman Divacky bool MachineBasicBlock::canFallThrough() {
6747d523365SDimitry Andric   MachineFunction::iterator Fallthrough = getIterator();
675f22ef01cSRoman Divacky   ++Fallthrough;
676f22ef01cSRoman Divacky   // If FallthroughBlock is off the end of the function, it can't fall through.
677f22ef01cSRoman Divacky   if (Fallthrough == getParent()->end())
678f22ef01cSRoman Divacky     return false;
679f22ef01cSRoman Divacky 
680f22ef01cSRoman Divacky   // If FallthroughBlock isn't a successor, no fallthrough is possible.
6817d523365SDimitry Andric   if (!isSuccessor(&*Fallthrough))
682f22ef01cSRoman Divacky     return false;
683f22ef01cSRoman Divacky 
684f22ef01cSRoman Divacky   // Analyze the branches, if any, at the end of the block.
68591bc56edSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
686f22ef01cSRoman Divacky   SmallVector<MachineOperand, 4> Cond;
68739d628a0SDimitry Andric   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
688f22ef01cSRoman Divacky   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
689f22ef01cSRoman Divacky     // If we couldn't analyze the branch, examine the last instruction.
690f22ef01cSRoman Divacky     // If the block doesn't end in a known control barrier, assume fallthrough
691dff0c46cSDimitry Andric     // is possible. The isPredicated check is needed because this code can be
692f22ef01cSRoman Divacky     // called during IfConversion, where an instruction which is normally a
693dff0c46cSDimitry Andric     // Barrier is predicated and thus no longer an actual control barrier.
694dff0c46cSDimitry Andric     return empty() || !back().isBarrier() || TII->isPredicated(&back());
695f22ef01cSRoman Divacky   }
696f22ef01cSRoman Divacky 
697f22ef01cSRoman Divacky   // If there is no branch, control always falls through.
69891bc56edSDimitry Andric   if (!TBB) return true;
699f22ef01cSRoman Divacky 
700f22ef01cSRoman Divacky   // If there is some explicit branch to the fallthrough block, it can obviously
701f22ef01cSRoman Divacky   // reach, even though the branch should get folded to fall through implicitly.
702f22ef01cSRoman Divacky   if (MachineFunction::iterator(TBB) == Fallthrough ||
703f22ef01cSRoman Divacky       MachineFunction::iterator(FBB) == Fallthrough)
704f22ef01cSRoman Divacky     return true;
705f22ef01cSRoman Divacky 
706f22ef01cSRoman Divacky   // If it's an unconditional branch to some block not the fall through, it
707f22ef01cSRoman Divacky   // doesn't fall through.
708f22ef01cSRoman Divacky   if (Cond.empty()) return false;
709f22ef01cSRoman Divacky 
710f22ef01cSRoman Divacky   // Otherwise, if it is conditional and has no explicit false block, it falls
711f22ef01cSRoman Divacky   // through.
71291bc56edSDimitry Andric   return FBB == nullptr;
713f22ef01cSRoman Divacky }
714f22ef01cSRoman Divacky 
715ffd1746dSEd Schouten MachineBasicBlock *
716ffd1746dSEd Schouten MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
7177ae0e2c9SDimitry Andric   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
7187ae0e2c9SDimitry Andric   // it in this generic function.
7197d523365SDimitry Andric   if (Succ->isEHPad())
72091bc56edSDimitry Andric     return nullptr;
7217ae0e2c9SDimitry Andric 
722ffd1746dSEd Schouten   MachineFunction *MF = getParent();
7237d523365SDimitry Andric   DebugLoc DL;  // FIXME: this is nowhere
724ffd1746dSEd Schouten 
72591bc56edSDimitry Andric   // Performance might be harmed on HW that implements branching using exec mask
72691bc56edSDimitry Andric   // where both sides of the branches are always executed.
72791bc56edSDimitry Andric   if (MF->getTarget().requiresStructuredCFG())
72891bc56edSDimitry Andric     return nullptr;
72991bc56edSDimitry Andric 
7302754fe60SDimitry Andric   // We may need to update this's terminator, but we can't do that if
7312754fe60SDimitry Andric   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
73239d628a0SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
73391bc56edSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
734ffd1746dSEd Schouten   SmallVector<MachineOperand, 4> Cond;
735ffd1746dSEd Schouten   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
73691bc56edSDimitry Andric     return nullptr;
737ffd1746dSEd Schouten 
7382754fe60SDimitry Andric   // Avoid bugpoint weirdness: A block may end with a conditional branch but
7392754fe60SDimitry Andric   // jumps to the same MBB is either case. We have duplicate CFG edges in that
7402754fe60SDimitry Andric   // case that we can't handle. Since this never happens in properly optimized
7412754fe60SDimitry Andric   // code, just skip those edges.
7422754fe60SDimitry Andric   if (TBB && TBB == FBB) {
7432754fe60SDimitry Andric     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
7442754fe60SDimitry Andric                  << getNumber() << '\n');
74591bc56edSDimitry Andric     return nullptr;
7462754fe60SDimitry Andric   }
7472754fe60SDimitry Andric 
748ffd1746dSEd Schouten   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
74991bc56edSDimitry Andric   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
750e580952dSDimitry Andric   DEBUG(dbgs() << "Splitting critical edge:"
751ffd1746dSEd Schouten         " BB#" << getNumber()
752ffd1746dSEd Schouten         << " -- BB#" << NMBB->getNumber()
753ffd1746dSEd Schouten         << " -- BB#" << Succ->getNumber() << '\n');
754ffd1746dSEd Schouten 
755139f7f9bSDimitry Andric   LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
756139f7f9bSDimitry Andric   SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
757139f7f9bSDimitry Andric   if (LIS)
758139f7f9bSDimitry Andric     LIS->insertMBBInMaps(NMBB);
759139f7f9bSDimitry Andric   else if (Indexes)
760139f7f9bSDimitry Andric     Indexes->insertMBBInMaps(NMBB);
761139f7f9bSDimitry Andric 
762bd5abe19SDimitry Andric   // On some targets like Mips, branches may kill virtual registers. Make sure
763bd5abe19SDimitry Andric   // that LiveVariables is properly updated after updateTerminator replaces the
764bd5abe19SDimitry Andric   // terminators.
765bd5abe19SDimitry Andric   LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
766bd5abe19SDimitry Andric 
767bd5abe19SDimitry Andric   // Collect a list of virtual registers killed by the terminators.
768bd5abe19SDimitry Andric   SmallVector<unsigned, 4> KilledRegs;
769bd5abe19SDimitry Andric   if (LV)
770dff0c46cSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
771dff0c46cSDimitry Andric          I != E; ++I) {
7727d523365SDimitry Andric       MachineInstr *MI = &*I;
773bd5abe19SDimitry Andric       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
774bd5abe19SDimitry Andric            OE = MI->operands_end(); OI != OE; ++OI) {
775dff0c46cSDimitry Andric         if (!OI->isReg() || OI->getReg() == 0 ||
776dff0c46cSDimitry Andric             !OI->isUse() || !OI->isKill() || OI->isUndef())
777bd5abe19SDimitry Andric           continue;
778bd5abe19SDimitry Andric         unsigned Reg = OI->getReg();
779dff0c46cSDimitry Andric         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
780bd5abe19SDimitry Andric             LV->getVarInfo(Reg).removeKill(MI)) {
781bd5abe19SDimitry Andric           KilledRegs.push_back(Reg);
782bd5abe19SDimitry Andric           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
783bd5abe19SDimitry Andric           OI->setIsKill(false);
784bd5abe19SDimitry Andric         }
785bd5abe19SDimitry Andric       }
786bd5abe19SDimitry Andric     }
787bd5abe19SDimitry Andric 
788139f7f9bSDimitry Andric   SmallVector<unsigned, 4> UsedRegs;
789139f7f9bSDimitry Andric   if (LIS) {
790139f7f9bSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
791139f7f9bSDimitry Andric          I != E; ++I) {
7927d523365SDimitry Andric       MachineInstr *MI = &*I;
793139f7f9bSDimitry Andric 
794139f7f9bSDimitry Andric       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
795139f7f9bSDimitry Andric            OE = MI->operands_end(); OI != OE; ++OI) {
796139f7f9bSDimitry Andric         if (!OI->isReg() || OI->getReg() == 0)
797139f7f9bSDimitry Andric           continue;
798139f7f9bSDimitry Andric 
799139f7f9bSDimitry Andric         unsigned Reg = OI->getReg();
800139f7f9bSDimitry Andric         if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
801139f7f9bSDimitry Andric           UsedRegs.push_back(Reg);
802139f7f9bSDimitry Andric       }
803139f7f9bSDimitry Andric     }
804139f7f9bSDimitry Andric   }
805139f7f9bSDimitry Andric 
806ffd1746dSEd Schouten   ReplaceUsesOfBlockWith(Succ, NMBB);
807139f7f9bSDimitry Andric 
808139f7f9bSDimitry Andric   // If updateTerminator() removes instructions, we need to remove them from
809139f7f9bSDimitry Andric   // SlotIndexes.
810139f7f9bSDimitry Andric   SmallVector<MachineInstr*, 4> Terminators;
811139f7f9bSDimitry Andric   if (Indexes) {
812139f7f9bSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
813139f7f9bSDimitry Andric          I != E; ++I)
8147d523365SDimitry Andric       Terminators.push_back(&*I);
815139f7f9bSDimitry Andric   }
816139f7f9bSDimitry Andric 
817ffd1746dSEd Schouten   updateTerminator();
818ffd1746dSEd Schouten 
819139f7f9bSDimitry Andric   if (Indexes) {
820139f7f9bSDimitry Andric     SmallVector<MachineInstr*, 4> NewTerminators;
821139f7f9bSDimitry Andric     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
822139f7f9bSDimitry Andric          I != E; ++I)
8237d523365SDimitry Andric       NewTerminators.push_back(&*I);
824139f7f9bSDimitry Andric 
825139f7f9bSDimitry Andric     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
826139f7f9bSDimitry Andric         E = Terminators.end(); I != E; ++I) {
827139f7f9bSDimitry Andric       if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
828139f7f9bSDimitry Andric           NewTerminators.end())
829139f7f9bSDimitry Andric        Indexes->removeMachineInstrFromMaps(*I);
830139f7f9bSDimitry Andric     }
831139f7f9bSDimitry Andric   }
832139f7f9bSDimitry Andric 
833ffd1746dSEd Schouten   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
834ffd1746dSEd Schouten   NMBB->addSuccessor(Succ);
835ffd1746dSEd Schouten   if (!NMBB->isLayoutSuccessor(Succ)) {
836ffd1746dSEd Schouten     Cond.clear();
8377d523365SDimitry Andric     TII->InsertBranch(*NMBB, Succ, nullptr, Cond, DL);
838139f7f9bSDimitry Andric 
839139f7f9bSDimitry Andric     if (Indexes) {
840139f7f9bSDimitry Andric       for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
841139f7f9bSDimitry Andric            I != E; ++I) {
842139f7f9bSDimitry Andric         // Some instructions may have been moved to NMBB by updateTerminator(),
843139f7f9bSDimitry Andric         // so we first remove any instruction that already has an index.
8447d523365SDimitry Andric         if (Indexes->hasIndex(&*I))
8457d523365SDimitry Andric           Indexes->removeMachineInstrFromMaps(&*I);
8467d523365SDimitry Andric         Indexes->insertMachineInstrInMaps(&*I);
847139f7f9bSDimitry Andric       }
848139f7f9bSDimitry Andric     }
849ffd1746dSEd Schouten   }
850ffd1746dSEd Schouten 
851ffd1746dSEd Schouten   // Fix PHI nodes in Succ so they refer to NMBB instead of this
852dff0c46cSDimitry Andric   for (MachineBasicBlock::instr_iterator
853dff0c46cSDimitry Andric          i = Succ->instr_begin(),e = Succ->instr_end();
854ffd1746dSEd Schouten        i != e && i->isPHI(); ++i)
855ffd1746dSEd Schouten     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
856ffd1746dSEd Schouten       if (i->getOperand(ni+1).getMBB() == this)
857ffd1746dSEd Schouten         i->getOperand(ni+1).setMBB(NMBB);
858ffd1746dSEd Schouten 
8596122f3e6SDimitry Andric   // Inherit live-ins from the successor
8607d523365SDimitry Andric   for (const auto &LI : Succ->liveins())
8617d523365SDimitry Andric     NMBB->addLiveIn(LI);
8626122f3e6SDimitry Andric 
863bd5abe19SDimitry Andric   // Update LiveVariables.
86439d628a0SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
865bd5abe19SDimitry Andric   if (LV) {
866bd5abe19SDimitry Andric     // Restore kills of virtual registers that were killed by the terminators.
867bd5abe19SDimitry Andric     while (!KilledRegs.empty()) {
868bd5abe19SDimitry Andric       unsigned Reg = KilledRegs.pop_back_val();
869dff0c46cSDimitry Andric       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
870dff0c46cSDimitry Andric         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
871bd5abe19SDimitry Andric           continue;
872dff0c46cSDimitry Andric         if (TargetRegisterInfo::isVirtualRegister(Reg))
8737d523365SDimitry Andric           LV->getVarInfo(Reg).Kills.push_back(&*I);
874bd5abe19SDimitry Andric         DEBUG(dbgs() << "Restored terminator kill: " << *I);
875bd5abe19SDimitry Andric         break;
876bd5abe19SDimitry Andric       }
877bd5abe19SDimitry Andric     }
878bd5abe19SDimitry Andric     // Update relevant live-through information.
879ffd1746dSEd Schouten     LV->addNewBlock(NMBB, this, Succ);
880bd5abe19SDimitry Andric   }
881ffd1746dSEd Schouten 
882139f7f9bSDimitry Andric   if (LIS) {
883139f7f9bSDimitry Andric     // After splitting the edge and updating SlotIndexes, live intervals may be
884139f7f9bSDimitry Andric     // in one of two situations, depending on whether this block was the last in
8857d523365SDimitry Andric     // the function. If the original block was the last in the function, all
8867d523365SDimitry Andric     // live intervals will end prior to the beginning of the new split block. If
8877d523365SDimitry Andric     // the original block was not at the end of the function, all live intervals
8887d523365SDimitry Andric     // will extend to the end of the new split block.
889139f7f9bSDimitry Andric 
890139f7f9bSDimitry Andric     bool isLastMBB =
89191bc56edSDimitry Andric       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
892139f7f9bSDimitry Andric 
893139f7f9bSDimitry Andric     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
894139f7f9bSDimitry Andric     SlotIndex PrevIndex = StartIndex.getPrevSlot();
895139f7f9bSDimitry Andric     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
896139f7f9bSDimitry Andric 
897139f7f9bSDimitry Andric     // Find the registers used from NMBB in PHIs in Succ.
898139f7f9bSDimitry Andric     SmallSet<unsigned, 8> PHISrcRegs;
899139f7f9bSDimitry Andric     for (MachineBasicBlock::instr_iterator
900139f7f9bSDimitry Andric          I = Succ->instr_begin(), E = Succ->instr_end();
901139f7f9bSDimitry Andric          I != E && I->isPHI(); ++I) {
902139f7f9bSDimitry Andric       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
903139f7f9bSDimitry Andric         if (I->getOperand(ni+1).getMBB() == NMBB) {
904139f7f9bSDimitry Andric           MachineOperand &MO = I->getOperand(ni);
905139f7f9bSDimitry Andric           unsigned Reg = MO.getReg();
906139f7f9bSDimitry Andric           PHISrcRegs.insert(Reg);
907139f7f9bSDimitry Andric           if (MO.isUndef())
908139f7f9bSDimitry Andric             continue;
909139f7f9bSDimitry Andric 
910139f7f9bSDimitry Andric           LiveInterval &LI = LIS->getInterval(Reg);
911139f7f9bSDimitry Andric           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
9127d523365SDimitry Andric           assert(VNI &&
9137d523365SDimitry Andric                  "PHI sources should be live out of their predecessors.");
914f785676fSDimitry Andric           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
915139f7f9bSDimitry Andric         }
916139f7f9bSDimitry Andric       }
917139f7f9bSDimitry Andric     }
918139f7f9bSDimitry Andric 
919139f7f9bSDimitry Andric     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
920139f7f9bSDimitry Andric     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
921139f7f9bSDimitry Andric       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
922139f7f9bSDimitry Andric       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
923139f7f9bSDimitry Andric         continue;
924139f7f9bSDimitry Andric 
925139f7f9bSDimitry Andric       LiveInterval &LI = LIS->getInterval(Reg);
926139f7f9bSDimitry Andric       if (!LI.liveAt(PrevIndex))
927139f7f9bSDimitry Andric         continue;
928139f7f9bSDimitry Andric 
929139f7f9bSDimitry Andric       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
930139f7f9bSDimitry Andric       if (isLiveOut && isLastMBB) {
931139f7f9bSDimitry Andric         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
932139f7f9bSDimitry Andric         assert(VNI && "LiveInterval should have VNInfo where it is live.");
933f785676fSDimitry Andric         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
934139f7f9bSDimitry Andric       } else if (!isLiveOut && !isLastMBB) {
935f785676fSDimitry Andric         LI.removeSegment(StartIndex, EndIndex);
936139f7f9bSDimitry Andric       }
937139f7f9bSDimitry Andric     }
938139f7f9bSDimitry Andric 
939139f7f9bSDimitry Andric     // Update all intervals for registers whose uses may have been modified by
940139f7f9bSDimitry Andric     // updateTerminator().
941139f7f9bSDimitry Andric     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
942139f7f9bSDimitry Andric   }
943139f7f9bSDimitry Andric 
944ffd1746dSEd Schouten   if (MachineDominatorTree *MDT =
94539d628a0SDimitry Andric       P->getAnalysisIfAvailable<MachineDominatorTree>())
94639d628a0SDimitry Andric     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
947e580952dSDimitry Andric 
948e580952dSDimitry Andric   if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
949ffd1746dSEd Schouten     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
950ffd1746dSEd Schouten       // If one or the other blocks were not in a loop, the new block is not
951ffd1746dSEd Schouten       // either, and thus LI doesn't need to be updated.
952ffd1746dSEd Schouten       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
953ffd1746dSEd Schouten         if (TIL == DestLoop) {
954ffd1746dSEd Schouten           // Both in the same loop, the NMBB joins loop.
955ffd1746dSEd Schouten           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
956ffd1746dSEd Schouten         } else if (TIL->contains(DestLoop)) {
957ffd1746dSEd Schouten           // Edge from an outer loop to an inner loop.  Add to the outer loop.
958ffd1746dSEd Schouten           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
959ffd1746dSEd Schouten         } else if (DestLoop->contains(TIL)) {
960ffd1746dSEd Schouten           // Edge from an inner loop to an outer loop.  Add to the outer loop.
961ffd1746dSEd Schouten           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
962ffd1746dSEd Schouten         } else {
963ffd1746dSEd Schouten           // Edge from two loops with no containment relation.  Because these
964ffd1746dSEd Schouten           // are natural loops, we know that the destination block must be the
965ffd1746dSEd Schouten           // header of its loop (adding a branch into a loop elsewhere would
966ffd1746dSEd Schouten           // create an irreducible loop).
967ffd1746dSEd Schouten           assert(DestLoop->getHeader() == Succ &&
968ffd1746dSEd Schouten                  "Should not create irreducible loops!");
969ffd1746dSEd Schouten           if (MachineLoop *P = DestLoop->getParentLoop())
970ffd1746dSEd Schouten             P->addBasicBlockToLoop(NMBB, MLI->getBase());
971ffd1746dSEd Schouten         }
972ffd1746dSEd Schouten       }
973ffd1746dSEd Schouten     }
974ffd1746dSEd Schouten 
975ffd1746dSEd Schouten   return NMBB;
976ffd1746dSEd Schouten }
977ffd1746dSEd Schouten 
978139f7f9bSDimitry Andric /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
979139f7f9bSDimitry Andric /// neighboring instructions so the bundle won't be broken by removing MI.
980139f7f9bSDimitry Andric static void unbundleSingleMI(MachineInstr *MI) {
981139f7f9bSDimitry Andric   // Removing the first instruction in a bundle.
982139f7f9bSDimitry Andric   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
983139f7f9bSDimitry Andric     MI->unbundleFromSucc();
984139f7f9bSDimitry Andric   // Removing the last instruction in a bundle.
985139f7f9bSDimitry Andric   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
986139f7f9bSDimitry Andric     MI->unbundleFromPred();
987139f7f9bSDimitry Andric   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
988139f7f9bSDimitry Andric   // are already fine.
989dff0c46cSDimitry Andric }
990dff0c46cSDimitry Andric 
991139f7f9bSDimitry Andric MachineBasicBlock::instr_iterator
992139f7f9bSDimitry Andric MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
9937d523365SDimitry Andric   unbundleSingleMI(&*I);
994139f7f9bSDimitry Andric   return Insts.erase(I);
995dff0c46cSDimitry Andric }
996dff0c46cSDimitry Andric 
997139f7f9bSDimitry Andric MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
998139f7f9bSDimitry Andric   unbundleSingleMI(MI);
999139f7f9bSDimitry Andric   MI->clearFlag(MachineInstr::BundledPred);
1000139f7f9bSDimitry Andric   MI->clearFlag(MachineInstr::BundledSucc);
1001139f7f9bSDimitry Andric   return Insts.remove(MI);
1002dff0c46cSDimitry Andric }
1003dff0c46cSDimitry Andric 
1004139f7f9bSDimitry Andric MachineBasicBlock::instr_iterator
1005139f7f9bSDimitry Andric MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1006139f7f9bSDimitry Andric   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1007139f7f9bSDimitry Andric          "Cannot insert instruction with bundle flags");
1008139f7f9bSDimitry Andric   // Set the bundle flags when inserting inside a bundle.
1009139f7f9bSDimitry Andric   if (I != instr_end() && I->isBundledWithPred()) {
1010139f7f9bSDimitry Andric     MI->setFlag(MachineInstr::BundledPred);
1011139f7f9bSDimitry Andric     MI->setFlag(MachineInstr::BundledSucc);
1012dff0c46cSDimitry Andric   }
1013139f7f9bSDimitry Andric   return Insts.insert(I, MI);
1014dff0c46cSDimitry Andric }
1015dff0c46cSDimitry Andric 
10167d523365SDimitry Andric /// This method unlinks 'this' from the containing function, and returns it, but
10177d523365SDimitry Andric /// does not delete it.
1018f22ef01cSRoman Divacky MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1019f22ef01cSRoman Divacky   assert(getParent() && "Not embedded in a function!");
1020f22ef01cSRoman Divacky   getParent()->remove(this);
1021f22ef01cSRoman Divacky   return this;
1022f22ef01cSRoman Divacky }
1023f22ef01cSRoman Divacky 
10247d523365SDimitry Andric /// This method unlinks 'this' from the containing function, and deletes it.
1025f22ef01cSRoman Divacky void MachineBasicBlock::eraseFromParent() {
1026f22ef01cSRoman Divacky   assert(getParent() && "Not embedded in a function!");
1027f22ef01cSRoman Divacky   getParent()->erase(this);
1028f22ef01cSRoman Divacky }
1029f22ef01cSRoman Divacky 
10307d523365SDimitry Andric /// Given a machine basic block that branched to 'Old', change the code and CFG
10317d523365SDimitry Andric /// so that it branches to 'New' instead.
1032f22ef01cSRoman Divacky void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1033f22ef01cSRoman Divacky                                                MachineBasicBlock *New) {
1034f22ef01cSRoman Divacky   assert(Old != New && "Cannot replace self with self!");
1035f22ef01cSRoman Divacky 
1036dff0c46cSDimitry Andric   MachineBasicBlock::instr_iterator I = instr_end();
1037dff0c46cSDimitry Andric   while (I != instr_begin()) {
1038f22ef01cSRoman Divacky     --I;
1039dff0c46cSDimitry Andric     if (!I->isTerminator()) break;
1040f22ef01cSRoman Divacky 
1041f22ef01cSRoman Divacky     // Scan the operands of this machine instruction, replacing any uses of Old
1042f22ef01cSRoman Divacky     // with New.
1043f22ef01cSRoman Divacky     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1044f22ef01cSRoman Divacky       if (I->getOperand(i).isMBB() &&
1045f22ef01cSRoman Divacky           I->getOperand(i).getMBB() == Old)
1046f22ef01cSRoman Divacky         I->getOperand(i).setMBB(New);
1047f22ef01cSRoman Divacky   }
1048f22ef01cSRoman Divacky 
1049f22ef01cSRoman Divacky   // Update the successor information.
105017a519f9SDimitry Andric   replaceSuccessor(Old, New);
1051f22ef01cSRoman Divacky }
1052f22ef01cSRoman Divacky 
10537d523365SDimitry Andric /// Various pieces of code can cause excess edges in the CFG to be inserted.  If
10547d523365SDimitry Andric /// we have proven that MBB can only branch to DestA and DestB, remove any other
10557d523365SDimitry Andric /// MBB successors from the CFG.  DestA and DestB can be null.
1056f22ef01cSRoman Divacky ///
1057f22ef01cSRoman Divacky /// Besides DestA and DestB, retain other edges leading to LandingPads
1058f22ef01cSRoman Divacky /// (currently there can be only one; we don't check or require that here).
1059f22ef01cSRoman Divacky /// Note it is possible that DestA and/or DestB are LandingPads.
1060f22ef01cSRoman Divacky bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1061f22ef01cSRoman Divacky                                              MachineBasicBlock *DestB,
10627d523365SDimitry Andric                                              bool IsCond) {
1063f22ef01cSRoman Divacky   // The values of DestA and DestB frequently come from a call to the
1064f22ef01cSRoman Divacky   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1065f22ef01cSRoman Divacky   // values from there.
1066f22ef01cSRoman Divacky   //
1067f22ef01cSRoman Divacky   // 1. If both DestA and DestB are null, then the block ends with no branches
1068f22ef01cSRoman Divacky   //    (it falls through to its successor).
10697d523365SDimitry Andric   // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
1070f22ef01cSRoman Divacky   //    with only an unconditional branch.
10717d523365SDimitry Andric   // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
1072f22ef01cSRoman Divacky   //    with a conditional branch that falls through to a successor (DestB).
10737d523365SDimitry Andric   // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
1074f22ef01cSRoman Divacky   //    conditional branch followed by an unconditional branch. DestA is the
1075f22ef01cSRoman Divacky   //    'true' destination and DestB is the 'false' destination.
1076f22ef01cSRoman Divacky 
1077f22ef01cSRoman Divacky   bool Changed = false;
1078f22ef01cSRoman Divacky 
10797d523365SDimitry Andric   MachineFunction::iterator FallThru = std::next(getIterator());
1080f22ef01cSRoman Divacky 
108191bc56edSDimitry Andric   if (!DestA && !DestB) {
1082f22ef01cSRoman Divacky     // Block falls through to successor.
10837d523365SDimitry Andric     DestA = &*FallThru;
10847d523365SDimitry Andric     DestB = &*FallThru;
108591bc56edSDimitry Andric   } else if (DestA && !DestB) {
10867d523365SDimitry Andric     if (IsCond)
1087f22ef01cSRoman Divacky       // Block ends in conditional jump that falls through to successor.
10887d523365SDimitry Andric       DestB = &*FallThru;
1089f22ef01cSRoman Divacky   } else {
10907d523365SDimitry Andric     assert(DestA && DestB && IsCond &&
1091f22ef01cSRoman Divacky            "CFG in a bad state. Cannot correct CFG edges");
1092f22ef01cSRoman Divacky   }
1093f22ef01cSRoman Divacky 
1094f22ef01cSRoman Divacky   // Remove superfluous edges. I.e., those which aren't destinations of this
1095f22ef01cSRoman Divacky   // basic block, duplicate edges, or landing pads.
1096f22ef01cSRoman Divacky   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1097f22ef01cSRoman Divacky   MachineBasicBlock::succ_iterator SI = succ_begin();
1098f22ef01cSRoman Divacky   while (SI != succ_end()) {
1099f22ef01cSRoman Divacky     const MachineBasicBlock *MBB = *SI;
110039d628a0SDimitry Andric     if (!SeenMBBs.insert(MBB).second ||
11017d523365SDimitry Andric         (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
1102f22ef01cSRoman Divacky       // This is a superfluous edge, remove it.
1103f22ef01cSRoman Divacky       SI = removeSuccessor(SI);
1104f22ef01cSRoman Divacky       Changed = true;
1105f22ef01cSRoman Divacky     } else {
1106f22ef01cSRoman Divacky       ++SI;
1107f22ef01cSRoman Divacky     }
1108f22ef01cSRoman Divacky   }
1109f22ef01cSRoman Divacky 
11107d523365SDimitry Andric   if (Changed)
11117d523365SDimitry Andric     normalizeSuccProbs();
1112f22ef01cSRoman Divacky   return Changed;
1113f22ef01cSRoman Divacky }
1114f22ef01cSRoman Divacky 
11157d523365SDimitry Andric /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
11167d523365SDimitry Andric /// instructions.  Return UnknownLoc if there is none.
1117f22ef01cSRoman Divacky DebugLoc
1118dff0c46cSDimitry Andric MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1119f22ef01cSRoman Divacky   DebugLoc DL;
1120dff0c46cSDimitry Andric   instr_iterator E = instr_end();
1121dff0c46cSDimitry Andric   if (MBBI == E)
1122dff0c46cSDimitry Andric     return DL;
1123dff0c46cSDimitry Andric 
1124f22ef01cSRoman Divacky   // Skip debug declarations, we don't want a DebugLoc from them.
1125dff0c46cSDimitry Andric   while (MBBI != E && MBBI->isDebugValue())
1126dff0c46cSDimitry Andric     MBBI++;
1127dff0c46cSDimitry Andric   if (MBBI != E)
1128dff0c46cSDimitry Andric     DL = MBBI->getDebugLoc();
1129f22ef01cSRoman Divacky   return DL;
1130f22ef01cSRoman Divacky }
1131f22ef01cSRoman Divacky 
11327d523365SDimitry Andric /// Return probability of the edge from this block to MBB.
11337d523365SDimitry Andric BranchProbability
11347d523365SDimitry Andric MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
11357d523365SDimitry Andric   if (Probs.empty())
11367d523365SDimitry Andric     return BranchProbability(1, succ_size());
113717a519f9SDimitry Andric 
11387d523365SDimitry Andric   const auto &Prob = *getProbabilityIterator(Succ);
11397d523365SDimitry Andric   if (Prob.isUnknown()) {
11407d523365SDimitry Andric     // For unknown probabilities, collect the sum of all known ones, and evenly
11417d523365SDimitry Andric     // ditribute the complemental of the sum to each unknown probability.
11427d523365SDimitry Andric     unsigned KnownProbNum = 0;
11437d523365SDimitry Andric     auto Sum = BranchProbability::getZero();
11447d523365SDimitry Andric     for (auto &P : Probs) {
11457d523365SDimitry Andric       if (!P.isUnknown()) {
11467d523365SDimitry Andric         Sum += P;
11477d523365SDimitry Andric         KnownProbNum++;
11487d523365SDimitry Andric       }
11497d523365SDimitry Andric     }
11507d523365SDimitry Andric     return Sum.getCompl() / (Probs.size() - KnownProbNum);
11517d523365SDimitry Andric   } else
11527d523365SDimitry Andric     return Prob;
115317a519f9SDimitry Andric }
115417a519f9SDimitry Andric 
11557d523365SDimitry Andric /// Set successor probability of a given iterator.
11567d523365SDimitry Andric void MachineBasicBlock::setSuccProbability(succ_iterator I,
11577d523365SDimitry Andric                                            BranchProbability Prob) {
11587d523365SDimitry Andric   assert(!Prob.isUnknown());
11597d523365SDimitry Andric   if (Probs.empty())
116091bc56edSDimitry Andric     return;
11617d523365SDimitry Andric   *getProbabilityIterator(I) = Prob;
116291bc56edSDimitry Andric }
116391bc56edSDimitry Andric 
11647d523365SDimitry Andric /// Return probability iterator corresonding to the I successor iterator
11657d523365SDimitry Andric MachineBasicBlock::const_probability_iterator
11667d523365SDimitry Andric MachineBasicBlock::getProbabilityIterator(
11677d523365SDimitry Andric     MachineBasicBlock::const_succ_iterator I) const {
11687d523365SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
1169dff0c46cSDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
11707d523365SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
11717d523365SDimitry Andric   return Probs.begin() + index;
11727d523365SDimitry Andric }
11737d523365SDimitry Andric 
11747d523365SDimitry Andric /// Return probability iterator corresonding to the I successor iterator.
11757d523365SDimitry Andric MachineBasicBlock::probability_iterator
11767d523365SDimitry Andric MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
11777d523365SDimitry Andric   assert(Probs.size() == Successors.size() && "Async probability list!");
11787d523365SDimitry Andric   const size_t index = std::distance(Successors.begin(), I);
11797d523365SDimitry Andric   assert(index < Probs.size() && "Not a current successor!");
11807d523365SDimitry Andric   return Probs.begin() + index;
1181dff0c46cSDimitry Andric }
1182dff0c46cSDimitry Andric 
11833861d79fSDimitry Andric /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
11843861d79fSDimitry Andric /// as of just before "MI".
11853861d79fSDimitry Andric ///
11863861d79fSDimitry Andric /// Search is localised to a neighborhood of
11873861d79fSDimitry Andric /// Neighborhood instructions before (searching for defs or kills) and N
11883861d79fSDimitry Andric /// instructions after (searching just for defs) MI.
11893861d79fSDimitry Andric MachineBasicBlock::LivenessQueryResult
11903861d79fSDimitry Andric MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1191ff0cc061SDimitry Andric                                            unsigned Reg, const_iterator Before,
1192ff0cc061SDimitry Andric                                            unsigned Neighborhood) const {
11933861d79fSDimitry Andric   unsigned N = Neighborhood;
11943861d79fSDimitry Andric 
1195ff0cc061SDimitry Andric   // Start by searching backwards from Before, looking for kills, reads or defs.
1196ff0cc061SDimitry Andric   const_iterator I(Before);
11973861d79fSDimitry Andric   // If this is the first insn in the block, don't search backwards.
1198ff0cc061SDimitry Andric   if (I != begin()) {
11993861d79fSDimitry Andric     do {
12003861d79fSDimitry Andric       --I;
12013861d79fSDimitry Andric 
12027d523365SDimitry Andric       MachineOperandIteratorBase::PhysRegInfo Info =
1203ff0cc061SDimitry Andric         ConstMIOperands(I).analyzePhysReg(Reg, TRI);
12043861d79fSDimitry Andric 
12057d523365SDimitry Andric       // Defs happen after uses so they take precedence if both are present.
1206139f7f9bSDimitry Andric 
12077d523365SDimitry Andric       // Register is dead after a dead def of the full register.
12087d523365SDimitry Andric       if (Info.DeadDef)
12093861d79fSDimitry Andric         return LQR_Dead;
12107d523365SDimitry Andric       // Register is (at least partially) live after a def.
12117d523365SDimitry Andric       if (Info.Defined)
12127d523365SDimitry Andric         return LQR_Live;
12137d523365SDimitry Andric       // Register is dead after a full kill or clobber and no def.
12147d523365SDimitry Andric       if (Info.Killed || Info.Clobbered)
12157d523365SDimitry Andric         return LQR_Dead;
12167d523365SDimitry Andric       // Register must be live if we read it.
12177d523365SDimitry Andric       if (Info.Read)
12187d523365SDimitry Andric         return LQR_Live;
1219ff0cc061SDimitry Andric     } while (I != begin() && --N > 0);
12203861d79fSDimitry Andric   }
12213861d79fSDimitry Andric 
12223861d79fSDimitry Andric   // Did we get to the start of the block?
1223ff0cc061SDimitry Andric   if (I == begin()) {
12243861d79fSDimitry Andric     // If so, the register's state is definitely defined by the live-in state.
12257d523365SDimitry Andric     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); RAI.isValid();
12267d523365SDimitry Andric          ++RAI)
1227ff0cc061SDimitry Andric       if (isLiveIn(*RAI))
12287d523365SDimitry Andric         return LQR_Live;
12293861d79fSDimitry Andric 
12303861d79fSDimitry Andric     return LQR_Dead;
12313861d79fSDimitry Andric   }
12323861d79fSDimitry Andric 
12333861d79fSDimitry Andric   N = Neighborhood;
12343861d79fSDimitry Andric 
1235ff0cc061SDimitry Andric   // Try searching forwards from Before, looking for reads or defs.
1236ff0cc061SDimitry Andric   I = const_iterator(Before);
12373861d79fSDimitry Andric   // If this is the last insn in the block, don't search forwards.
1238ff0cc061SDimitry Andric   if (I != end()) {
1239ff0cc061SDimitry Andric     for (++I; I != end() && N > 0; ++I, --N) {
12407d523365SDimitry Andric       MachineOperandIteratorBase::PhysRegInfo Info =
1241ff0cc061SDimitry Andric         ConstMIOperands(I).analyzePhysReg(Reg, TRI);
12423861d79fSDimitry Andric 
12437d523365SDimitry Andric       // Register is live when we read it here.
12447d523365SDimitry Andric       if (Info.Read)
12457d523365SDimitry Andric         return LQR_Live;
12467d523365SDimitry Andric       // Register is dead if we can fully overwrite or clobber it here.
12477d523365SDimitry Andric       if (Info.FullyDefined || Info.Clobbered)
12483861d79fSDimitry Andric         return LQR_Dead;
12493861d79fSDimitry Andric     }
12503861d79fSDimitry Andric   }
12513861d79fSDimitry Andric 
12523861d79fSDimitry Andric   // At this point we have no idea of the liveness of the register.
12533861d79fSDimitry Andric   return LQR_Unknown;
12543861d79fSDimitry Andric }
12557d523365SDimitry Andric 
12567d523365SDimitry Andric const uint32_t *
12577d523365SDimitry Andric MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
12587d523365SDimitry Andric   // EH funclet entry does not preserve any registers.
12597d523365SDimitry Andric   return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
12607d523365SDimitry Andric }
12617d523365SDimitry Andric 
12627d523365SDimitry Andric const uint32_t *
12637d523365SDimitry Andric MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
12647d523365SDimitry Andric   // If we see a return block with successors, this must be a funclet return,
12657d523365SDimitry Andric   // which does not preserve any registers. If there are no successors, we don't
12667d523365SDimitry Andric   // care what kind of return it is, putting a mask after it is a no-op.
12677d523365SDimitry Andric   return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
12687d523365SDimitry Andric }
1269