blob: 03771bc5dae10471e0154bd0a7b461b8e865e83b [file] [log] [blame]
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +00001//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Collect the sequence of machine instructions for a basic block.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm/ADT/SmallPtrSet.h"
Matthias Braunfa621d22017-12-13 02:51:04 +000016#include "llvm/CodeGen/LiveIntervals.h"
Dan Gohman853d3fb2010-06-22 17:25:57 +000017#include "llvm/CodeGen/LiveVariables.h"
18#include "llvm/CodeGen/MachineDominators.h"
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +000019#include "llvm/CodeGen/MachineFunction.h"
Jakob Stoklund Olesenf6476522013-07-03 23:56:20 +000020#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman853d3fb2010-06-22 17:25:57 +000021#include "llvm/CodeGen/MachineLoopInfo.h"
Cameron Zwarich8597c142013-02-11 09:24:47 +000022#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesenf4a1e1a2010-10-26 20:21:46 +000023#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie48319232017-11-08 01:01:31 +000024#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000025#include "llvm/CodeGen/TargetRegisterInfo.h"
26#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber0f38c602018-04-30 14:59:11 +000027#include "llvm/Config/llvm-config.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000028#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/DataLayout.h"
Taewook Oh9fdcd962017-02-13 18:15:31 +000030#include "llvm/IR/DebugInfoMetadata.h"
Duncan P. N. Exon Smith9a61a422015-06-26 22:04:20 +000031#include "llvm/IR/ModuleSlotTracker.h"
Chris Lattnerf71cb012010-01-26 04:55:51 +000032#include "llvm/MC/MCAsmInfo.h"
33#include "llvm/MC/MCContext.h"
Cong Hou14df2e82015-12-13 09:52:14 +000034#include "llvm/Support/DataTypes.h"
David Greenedbdbbd92010-01-04 23:22:07 +000035#include "llvm/Support/Debug.h"
Daniel Dunbar1cd1d982009-07-24 10:36:58 +000036#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000037#include "llvm/Target/TargetMachine.h"
Chris Lattner52c09d72004-10-26 15:43:42 +000038#include <algorithm>
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +000039using namespace llvm;
40
Chandler Carruth283b3992014-04-21 22:55:11 +000041#define DEBUG_TYPE "codegen"
42
Cong Houabae8482015-09-29 19:46:09 +000043MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
44 : BB(B), Number(-1), xParent(&MF) {
Dan Gohmanfed90b62008-07-28 21:51:04 +000045 Insts.Parent = this;
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +000046 if (B)
47 IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight();
Tanya Lattner17fb34b2004-05-24 07:14:35 +000048}
Tanya Lattner17fb34b2004-05-24 07:14:35 +000049
Dan Gohman2c3f7ae2008-07-17 23:49:46 +000050MachineBasicBlock::~MachineBasicBlock() {
Dan Gohman2c3f7ae2008-07-17 23:49:46 +000051}
52
Cong Hou30f85e52015-08-12 21:18:54 +000053/// Return the MCSymbol for this basic block.
Chris Lattner1b2eb0e2010-03-13 21:04:28 +000054MCSymbol *MachineBasicBlock::getSymbol() const {
Eli Bendersky2ad047e2013-04-22 21:21:08 +000055 if (!CachedMCSymbol) {
56 const MachineFunction *MF = getParent();
57 MCContext &Ctx = MF->getContext();
Mehdi Aminiec52cde2016-10-01 06:46:33 +000058 auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
Reid Kleckner758cf892015-11-11 23:09:31 +000059 assert(getNumber() >= 0 && "cannot get label for unreachable MBB");
Jim Grosbach19696da2015-05-18 18:43:14 +000060 CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
Eli Bendersky2ad047e2013-04-22 21:21:08 +000061 Twine(MF->getFunctionNumber()) +
62 "_" + Twine(getNumber()));
63 }
64
65 return CachedMCSymbol;
Chris Lattnerf71cb012010-01-26 04:55:51 +000066}
67
68
Chris Lattner6371ed52009-08-23 00:35:30 +000069raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
Daniel Dunbar1cd1d982009-07-24 10:36:58 +000070 MBB.print(OS);
71 return OS;
72}
Tanya Lattner17fb34b2004-05-24 07:14:35 +000073
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +000074Printable llvm::printMBBReference(const MachineBasicBlock &MBB) {
75 return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); });
76}
77
Cong Hou30f85e52015-08-12 21:18:54 +000078/// When an MBB is added to an MF, we need to update the parent pointer of the
79/// MBB, the MBB numbering, and any instructions in the MBB to be on the right
80/// operand list for registers.
Chris Lattner62ed6b92008-01-01 01:12:31 +000081///
82/// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
83/// gets the next available unique MBB number. If it is removed from a
84/// MachineFunction, it goes back to being #-1.
Duncan P. N. Exon Smith9c80b352016-08-30 18:40:47 +000085void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
86 MachineBasicBlock *N) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +000087 MachineFunction &MF = *N->getParent();
88 N->Number = MF.addToMBBNumbering(N);
Chris Lattner62ed6b92008-01-01 01:12:31 +000089
90 // Make sure the instructions have their operands in the reginfo lists.
Dan Gohman8e5f2c62008-07-07 23:14:23 +000091 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Evan Chengddfd1372011-12-14 02:11:42 +000092 for (MachineBasicBlock::instr_iterator
93 I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
Chris Lattner62ed6b92008-01-01 01:12:31 +000094 I->AddRegOperandsToUseLists(RegInfo);
Brian Gaeke0bcb1ad2004-05-12 21:35:22 +000095}
96
Duncan P. N. Exon Smith9c80b352016-08-30 18:40:47 +000097void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
98 MachineBasicBlock *N) {
Chris Lattnerf20c1a42007-12-31 04:56:33 +000099 N->getParent()->removeFromMBBNumbering(N->Number);
Brian Gaeke0bcb1ad2004-05-12 21:35:22 +0000100 N->Number = -1;
101}
102
Cong Hou30f85e52015-08-12 21:18:54 +0000103/// When we add an instruction to a basic block list, we update its parent
104/// pointer and add its operands from reg use/def lists if appropriate.
Chris Lattner6371ed52009-08-23 00:35:30 +0000105void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
Craig Topper4ba84432014-04-14 00:51:57 +0000106 assert(!N->getParent() && "machine instruction already in a basic block");
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000107 N->setParent(Parent);
Jakub Staszak12af5ff2011-06-16 18:01:17 +0000108
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000109 // Add the instruction's register operands to their corresponding
110 // use/def lists.
111 MachineFunction *MF = Parent->getParent();
112 N->AddRegOperandsToUseLists(MF->getRegInfo());
Aditya Nandakumar3b417742018-09-20 23:01:56 +0000113 MF->handleInsertion(*N);
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +0000114}
115
Cong Hou30f85e52015-08-12 21:18:54 +0000116/// When we remove an instruction from a basic block list, we update its parent
117/// pointer and remove its operands from reg use/def lists if appropriate.
Chris Lattner6371ed52009-08-23 00:35:30 +0000118void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
Craig Topper4ba84432014-04-14 00:51:57 +0000119 assert(N->getParent() && "machine instruction not in a basic block");
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000120
121 // Remove from the use/def lists.
Aditya Nandakumar3b417742018-09-20 23:01:56 +0000122 if (MachineFunction *MF = N->getMF()) {
123 MF->handleRemoval(*N);
Jakob Stoklund Olesenff2b99a2012-08-09 22:49:37 +0000124 N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
Aditya Nandakumar3b417742018-09-20 23:01:56 +0000125 }
Jakub Staszak12af5ff2011-06-16 18:01:17 +0000126
Craig Topper4ba84432014-04-14 00:51:57 +0000127 N->setParent(nullptr);
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +0000128}
129
Cong Hou30f85e52015-08-12 21:18:54 +0000130/// When moving a range of instructions from one MBB list to another, we need to
131/// update the parent pointers and the use/def lists.
Duncan P. N. Exon Smith6037e192016-09-11 16:38:18 +0000132void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
133 instr_iterator First,
134 instr_iterator Last) {
Cong Houabae8482015-09-29 19:46:09 +0000135 assert(Parent->getParent() == FromList.Parent->getParent() &&
Dan Gohmanfed90b62008-07-28 21:51:04 +0000136 "MachineInstr parent mismatch!");
Duncan P. N. Exon Smith2f1f35b2016-08-30 18:00:45 +0000137 assert(this != &FromList && "Called without a real transfer...");
138 assert(Parent != FromList.Parent && "Two lists have the same parent?");
Chris Lattner62ed6b92008-01-01 01:12:31 +0000139
140 // If splicing between two blocks within the same function, just update the
141 // parent pointers.
Cong Houabae8482015-09-29 19:46:09 +0000142 for (; First != Last; ++First)
143 First->setParent(Parent);
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +0000144}
145
Duncan P. N. Exon Smith9c80b352016-08-30 18:40:47 +0000146void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000147 assert(!MI->getParent() && "MI is still in a block!");
148 Parent->getParent()->DeleteMachineInstr(MI);
149}
150
Dan Gohmand463a742010-07-07 14:33:51 +0000151MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
Benjamin Kramerf378f5f2012-02-10 00:28:31 +0000152 instr_iterator I = instr_begin(), E = instr_end();
153 while (I != E && I->isPHI())
Dan Gohmand463a742010-07-07 14:33:51 +0000154 ++I;
Akira Hatanakaaf808222012-10-26 17:11:42 +0000155 assert((I == E || !I->isInsideBundle()) &&
156 "First non-phi MI cannot be inside a bundle!");
Dan Gohmand463a742010-07-07 14:33:51 +0000157 return I;
158}
159
Jakob Stoklund Olesen92095e72010-10-30 01:26:14 +0000160MachineBasicBlock::iterator
161MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
Stanislav Mekhanoshinf304f042017-01-20 00:44:31 +0000162 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
163
Benjamin Kramerf378f5f2012-02-10 00:28:31 +0000164 iterator E = end();
Stanislav Mekhanoshinf304f042017-01-20 00:44:31 +0000165 while (I != E && (I->isPHI() || I->isPosition() ||
166 TII->isBasicBlockPrologue(*I)))
Keith Walker7435b282016-09-16 14:07:29 +0000167 ++I;
168 // FIXME: This needs to change if we wish to bundle labels
169 // inside the bundle.
170 assert((I == E || !I->isInsideBundle()) &&
171 "First non-phi / non-label instruction is inside a bundle!");
172 return I;
173}
174
175MachineBasicBlock::iterator
176MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I) {
Stanislav Mekhanoshinf304f042017-01-20 00:44:31 +0000177 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
178
Keith Walker7435b282016-09-16 14:07:29 +0000179 iterator E = end();
Shiva Chen24abe712018-05-09 02:42:00 +0000180 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() ||
Stanislav Mekhanoshinf304f042017-01-20 00:44:31 +0000181 TII->isBasicBlockPrologue(*I)))
Jakob Stoklund Olesen92095e72010-10-30 01:26:14 +0000182 ++I;
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000183 // FIXME: This needs to change if we wish to bundle labels / dbg_values
184 // inside the bundle.
Akira Hatanakaaf808222012-10-26 17:11:42 +0000185 assert((I == E || !I->isInsideBundle()) &&
Keith Walker7435b282016-09-16 14:07:29 +0000186 "First non-phi / non-label / non-debug "
187 "instruction is inside a bundle!");
Jakob Stoklund Olesen92095e72010-10-30 01:26:14 +0000188 return I;
189}
190
Chris Lattner52c09d72004-10-26 15:43:42 +0000191MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
Benjamin Kramerf378f5f2012-02-10 00:28:31 +0000192 iterator B = begin(), E = end(), I = E;
Shiva Chen24abe712018-05-09 02:42:00 +0000193 while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
Jakob Stoklund Olesenb6436e52011-01-14 02:12:54 +0000194 ; /*noop */
Benjamin Kramerf378f5f2012-02-10 00:28:31 +0000195 while (I != E && !I->isTerminator())
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000196 ++I;
197 return I;
198}
199
Evan Chengddfd1372011-12-14 02:11:42 +0000200MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
Benjamin Kramerf378f5f2012-02-10 00:28:31 +0000201 instr_iterator B = instr_begin(), E = instr_end(), I = E;
Shiva Chen24abe712018-05-09 02:42:00 +0000202 while (I != B && ((--I)->isTerminator() || I->isDebugInstr()))
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000203 ; /*noop */
Benjamin Kramerf378f5f2012-02-10 00:28:31 +0000204 while (I != E && !I->isTerminator())
Jakob Stoklund Olesen04223902011-01-14 06:33:45 +0000205 ++I;
Jakob Stoklund Olesenb6436e52011-01-14 02:12:54 +0000206 return I;
Alkis Evlogimenos743d0a12004-02-23 18:14:48 +0000207}
208
Benjamin Kramer336ead02015-06-23 14:47:29 +0000209MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
210 // Skip over begin-of-block dbg_value instructions.
Florian Hahnf295c8c2016-12-16 11:10:26 +0000211 return skipDebugInstructionsForward(begin(), end());
Benjamin Kramer336ead02015-06-23 14:47:29 +0000212}
213
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000214MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000215 // Skip over end-of-block dbg_value instructions.
Evan Chengddfd1372011-12-14 02:11:42 +0000216 instr_iterator B = instr_begin(), I = instr_end();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000217 while (I != B) {
218 --I;
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000219 // Return instruction that starts a bundle.
Shiva Chen24abe712018-05-09 02:42:00 +0000220 if (I->isDebugInstr() || I->isInsideBundle())
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000221 continue;
222 return I;
223 }
224 // The block is all debug values.
225 return end();
226}
227
Reid Kleckner7ad3e0e2015-09-17 17:19:40 +0000228bool MachineBasicBlock::hasEHPadSuccessor() const {
229 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
230 if ((*I)->isEHPad())
231 return true;
232 return false;
233}
234
Aaron Ballman1d03d382017-10-15 14:32:27 +0000235#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Keren55307982016-01-29 20:50:44 +0000236LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
David Greenedbdbbd92010-01-04 23:22:07 +0000237 print(dbgs());
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +0000238}
Manman Ren77e300e2012-09-06 19:06:06 +0000239#endif
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +0000240
Andrew Kaylorc539eea2017-06-22 23:27:16 +0000241bool MachineBasicBlock::isLegalToHoistInto() const {
242 if (isReturnBlock() || hasEHPadSuccessor())
243 return false;
244 return true;
245}
246
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000247StringRef MachineBasicBlock::getName() const {
248 if (const BasicBlock *LBB = getBasicBlock())
249 return LBB->getName();
250 else
Matthias Braun5e554772017-02-18 00:41:16 +0000251 return StringRef("", 0);
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000252}
253
Andrew Trick8ceaa662012-03-07 00:18:18 +0000254/// Return a hopefully unique identifier for this block.
255std::string MachineBasicBlock::getFullName() const {
256 std::string Name;
257 if (getParent())
Craig Topper96601ca2012-08-22 06:07:19 +0000258 Name = (getParent()->getName() + ":").str();
Andrew Trick8ceaa662012-03-07 00:18:18 +0000259 if (getBasicBlock())
260 Name += getBasicBlock()->getName();
261 else
Yaron Keren2a9bbcb2015-03-27 17:51:30 +0000262 Name += ("BB" + Twine(getNumber())).str();
Andrew Trick8ceaa662012-03-07 00:18:18 +0000263 return Name;
264}
265
Francis Visoiu Mistrih96ed12f2018-01-18 17:59:06 +0000266void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes,
Francis Visoiu Mistrih7bee1ce2018-01-18 18:05:15 +0000267 bool IsStandalone) const {
Evan Cheng13d82852007-02-10 02:38:19 +0000268 const MachineFunction *MF = getParent();
Chris Lattner6371ed52009-08-23 00:35:30 +0000269 if (!MF) {
Chris Lattner52c09d72004-10-26 15:43:42 +0000270 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
271 << " is null\n";
Tanya Lattner792699c2004-05-24 06:11:51 +0000272 return;
273 }
Matthias Braund3181392017-12-15 22:22:58 +0000274 const Function &F = MF->getFunction();
275 const Module *M = F.getParent();
Duncan P. N. Exon Smith9a61a422015-06-26 22:04:20 +0000276 ModuleSlotTracker MST(M);
Francis Visoiu Mistrih530107f2018-02-08 05:02:00 +0000277 MST.incorporateFunction(F);
Francis Visoiu Mistrih7bee1ce2018-01-18 18:05:15 +0000278 print(OS, MST, Indexes, IsStandalone);
Duncan P. N. Exon Smith9a61a422015-06-26 22:04:20 +0000279}
280
281void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
Francis Visoiu Mistrih96ed12f2018-01-18 17:59:06 +0000282 const SlotIndexes *Indexes,
Francis Visoiu Mistrih7bee1ce2018-01-18 18:05:15 +0000283 bool IsStandalone) const {
Duncan P. N. Exon Smith9a61a422015-06-26 22:04:20 +0000284 const MachineFunction *MF = getParent();
285 if (!MF) {
286 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
287 << " is null\n";
288 return;
289 }
Alkis Evlogimenosa6382862004-09-05 18:39:20 +0000290
Jakob Stoklund Olesenf4a1e1a2010-10-26 20:21:46 +0000291 if (Indexes)
292 OS << Indexes->getMBBStartIdx(this) << '\t';
293
Francis Visoiu Mistrih530107f2018-02-08 05:02:00 +0000294 OS << "bb." << getNumber();
295 bool HasAttributes = false;
296 if (const auto *BB = getBasicBlock()) {
297 if (BB->hasName()) {
298 OS << "." << BB->getName();
299 } else {
300 HasAttributes = true;
301 OS << " (";
302 int Slot = MST.getLocalSlot(BB);
303 if (Slot == -1)
304 OS << "<ir-block badref>";
305 else
306 OS << (Twine("%ir-block.") + Twine(Slot)).str();
307 }
Dan Gohman0ba90f3e2009-10-31 20:19:03 +0000308 }
Jakob Stoklund Olesenf2e94452011-12-06 21:08:39 +0000309
Francis Visoiu Mistrih530107f2018-02-08 05:02:00 +0000310 if (hasAddressTaken()) {
311 OS << (HasAttributes ? ", " : " (");
312 OS << "address-taken";
313 HasAttributes = true;
314 }
315 if (isEHPad()) {
316 OS << (HasAttributes ? ", " : " (");
317 OS << "landing-pad";
318 HasAttributes = true;
319 }
320 if (getAlignment()) {
321 OS << (HasAttributes ? ", " : " (");
322 OS << "align " << getAlignment();
323 HasAttributes = true;
324 }
325 if (HasAttributes)
326 OS << ")";
327 OS << ":\n";
Evan Cheng13d82852007-02-10 02:38:19 +0000328
Eric Christopher60355182014-08-05 02:39:49 +0000329 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Francis Visoiu Mistrihd7d9e372018-02-09 01:14:44 +0000330 const MachineRegisterInfo &MRI = MF->getRegInfo();
Francis Visoiu Mistrih3fa22fa2018-02-13 18:08:26 +0000331 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
Francis Visoiu Mistrihe9184302018-02-15 16:23:59 +0000332 bool HasLineAttributes = false;
Francis Visoiu Mistrihd7d9e372018-02-09 01:14:44 +0000333
Francis Visoiu Mistrih4569bff2018-02-14 20:23:05 +0000334 // Print the preds of this block according to the CFG.
Francis Visoiu Mistrih454e6dc2018-02-26 15:23:42 +0000335 if (!pred_empty() && IsStandalone) {
Francis Visoiu Mistrih4569bff2018-02-14 20:23:05 +0000336 if (Indexes) OS << '\t';
337 // Don't indent(2), align with previous line attributes.
338 OS << "; predecessors: ";
339 for (auto I = pred_begin(), E = pred_end(); I != E; ++I) {
340 if (I != pred_begin())
Francis Visoiu Mistrihd7d9e372018-02-09 01:14:44 +0000341 OS << ", ";
Francis Visoiu Mistrih4569bff2018-02-14 20:23:05 +0000342 OS << printMBBReference(**I);
Matthias Braun56dd2d02015-08-24 22:59:52 +0000343 }
Chris Lattner6371ed52009-08-23 00:35:30 +0000344 OS << '\n';
Francis Visoiu Mistrihe9184302018-02-15 16:23:59 +0000345 HasLineAttributes = true;
Evan Cheng13d82852007-02-10 02:38:19 +0000346 }
Francis Visoiu Mistrihf66532b2018-02-09 00:10:31 +0000347
Francis Visoiu Mistrihe4de84b2018-02-09 00:12:53 +0000348 if (!succ_empty()) {
Francis Visoiu Mistrihd7d9e372018-02-09 01:14:44 +0000349 if (Indexes) OS << '\t';
Francis Visoiu Mistrihe4de84b2018-02-09 00:12:53 +0000350 // Print the successors
351 OS.indent(2) << "successors: ";
352 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
353 if (I != succ_begin())
354 OS << ", ";
355 OS << printMBBReference(**I);
Francis Visoiu Mistrih2abdc452018-02-09 00:40:57 +0000356 if (!Probs.empty())
357 OS << '('
358 << format("0x%08" PRIx32, getSuccProbability(I).getNumerator())
359 << ')';
Francis Visoiu Mistrihe4de84b2018-02-09 00:12:53 +0000360 }
Francis Visoiu Mistrih454e6dc2018-02-26 15:23:42 +0000361 if (!Probs.empty() && IsStandalone) {
Francis Visoiu Mistrih2abdc452018-02-09 00:40:57 +0000362 // Print human readable probabilities as comments.
363 OS << "; ";
364 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) {
Hiroshi Inoueea3df5e2018-09-28 05:27:32 +0000365 const BranchProbability &BP = getSuccProbability(I);
Francis Visoiu Mistrih2abdc452018-02-09 00:40:57 +0000366 if (I != succ_begin())
367 OS << ", ";
368 OS << printMBBReference(**I) << '('
369 << format("%.2f%%",
370 rint(((double)BP.getNumerator() / BP.getDenominator()) *
371 100.0 * 100.0) /
372 100.0)
373 << ')';
374 }
Francis Visoiu Mistrihe4de84b2018-02-09 00:12:53 +0000375 }
Francis Visoiu Mistrihe9184302018-02-15 16:23:59 +0000376
377 OS << '\n';
378 HasLineAttributes = true;
Francis Visoiu Mistrihf66532b2018-02-09 00:10:31 +0000379 }
380
Francis Visoiu Mistrih4569bff2018-02-14 20:23:05 +0000381 if (!livein_empty() && MRI.tracksLiveness()) {
Jakob Stoklund Olesenf4a1e1a2010-10-26 20:21:46 +0000382 if (Indexes) OS << '\t';
Francis Visoiu Mistrih4569bff2018-02-14 20:23:05 +0000383 OS.indent(2) << "liveins: ";
384
385 bool First = true;
386 for (const auto &LI : liveins()) {
387 if (!First)
Francis Visoiu Mistrihe18a2b42018-02-09 19:46:02 +0000388 OS << ", ";
Francis Visoiu Mistrih4569bff2018-02-14 20:23:05 +0000389 First = false;
390 OS << printReg(LI.PhysReg, TRI);
391 if (!LI.LaneMask.all())
392 OS << ":0x" << PrintLaneMask(LI.LaneMask);
Francis Visoiu Mistrihe18a2b42018-02-09 19:46:02 +0000393 }
Francis Visoiu Mistrihe9184302018-02-15 16:23:59 +0000394 HasLineAttributes = true;
Chris Lattner681764b2006-09-26 03:41:59 +0000395 }
Jakob Stoklund Olesenf4a1e1a2010-10-26 20:21:46 +0000396
Francis Visoiu Mistrihe9184302018-02-15 16:23:59 +0000397 if (HasLineAttributes)
398 OS << '\n';
399
Francis Visoiu Mistrih3fa22fa2018-02-13 18:08:26 +0000400 bool IsInBundle = false;
401 for (const MachineInstr &MI : instrs()) {
Jakob Stoklund Olesenf4a1e1a2010-10-26 20:21:46 +0000402 if (Indexes) {
Francis Visoiu Mistrih3fa22fa2018-02-13 18:08:26 +0000403 if (Indexes->hasIndex(MI))
404 OS << Indexes->getInstructionIndex(MI);
Jakob Stoklund Olesenf4a1e1a2010-10-26 20:21:46 +0000405 OS << '\t';
406 }
Francis Visoiu Mistrih3fa22fa2018-02-13 18:08:26 +0000407
408 if (IsInBundle && !MI.isInsideBundle()) {
409 OS.indent(2) << "}\n";
410 IsInBundle = false;
411 }
412
413 OS.indent(IsInBundle ? 4 : 2);
414 MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false,
Krzysztof Parzyszekb8924a02018-04-10 16:46:13 +0000415 /*AddNewLine=*/false, &TII);
Francis Visoiu Mistrih3fa22fa2018-02-13 18:08:26 +0000416
417 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
418 OS << " {";
419 IsInBundle = true;
420 }
Krzysztof Parzyszekb8924a02018-04-10 16:46:13 +0000421 OS << '\n';
Alkis Evlogimenosa6382862004-09-05 18:39:20 +0000422 }
Chris Lattner380ae492005-04-01 06:48:38 +0000423
Francis Visoiu Mistrih3fa22fa2018-02-13 18:08:26 +0000424 if (IsInBundle)
425 OS.indent(2) << "}\n";
426
Francis Visoiu Mistrih454e6dc2018-02-26 15:23:42 +0000427 if (IrrLoopHeaderWeight && IsStandalone) {
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000428 if (Indexes) OS << '\t';
Francis Visoiu Mistrih5ca07452018-02-15 15:27:34 +0000429 OS.indent(2) << "; Irreducible loop header weight: "
430 << IrrLoopHeaderWeight.getValue() << '\n';
Hiroshi Yamauchidd33e172017-11-02 22:26:51 +0000431 }
Alkis Evlogimenosaad5c052004-02-16 07:17:43 +0000432}
Chris Lattner52c09d72004-10-26 15:43:42 +0000433
Cong Hou7ab9abd2015-08-10 22:27:10 +0000434void MachineBasicBlock::printAsOperand(raw_ostream &OS,
435 bool /*PrintType*/) const {
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +0000436 OS << "%bb." << getNumber();
Chandler Carruth560e3952014-01-09 02:29:41 +0000437}
438
Matthias Braundfc5b652015-09-25 21:51:14 +0000439void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
David Majnemer2d62ce62016-08-12 03:55:06 +0000440 LiveInVector::iterator I = find_if(
441 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
Matthias Braunaf5ff602015-09-09 18:08:03 +0000442 if (I == LiveIns.end())
443 return;
444
445 I->LaneMask &= ~LaneMask;
Krzysztof Parzyszekd6ca3f02016-12-15 14:36:06 +0000446 if (I->LaneMask.none())
Jakob Stoklund Olesen78836f02012-03-28 20:11:42 +0000447 LiveIns.erase(I);
Evan Chengb371f452007-02-19 21:49:54 +0000448}
449
Matthias Braun3a135cf2017-05-31 20:30:22 +0000450MachineBasicBlock::livein_iterator
451MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) {
Matthias Braun20537d72017-05-31 21:25:03 +0000452 // Get non-const version of iterator.
453 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin());
454 return LiveIns.erase(LI);
Matthias Braun3a135cf2017-05-31 20:30:22 +0000455}
456
Matthias Braundfc5b652015-09-25 21:51:14 +0000457bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
David Majnemer2d62ce62016-08-12 03:55:06 +0000458 livein_iterator I = find_if(
459 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
Krzysztof Parzyszek308c60d2016-12-16 19:11:56 +0000460 return I != livein_end() && (I->LaneMask & LaneMask).any();
Matthias Braunaf5ff602015-09-09 18:08:03 +0000461}
462
463void MachineBasicBlock::sortUniqueLiveIns() {
Fangrui Song3b35e172018-09-27 02:13:45 +0000464 llvm::sort(LiveIns,
Mandeep Singh Grang8ba42a92018-04-06 18:08:42 +0000465 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
466 return LI0.PhysReg < LI1.PhysReg;
467 });
Matthias Braunaf5ff602015-09-09 18:08:03 +0000468 // Liveins are sorted by physreg now we can merge their lanemasks.
469 LiveInVector::const_iterator I = LiveIns.begin();
470 LiveInVector::const_iterator J;
471 LiveInVector::iterator Out = LiveIns.begin();
472 for (; I != LiveIns.end(); ++Out, I = J) {
473 unsigned PhysReg = I->PhysReg;
Matthias Braundfc5b652015-09-25 21:51:14 +0000474 LaneBitmask LaneMask = I->LaneMask;
Matthias Braunaf5ff602015-09-09 18:08:03 +0000475 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
476 LaneMask |= J->LaneMask;
477 Out->PhysReg = PhysReg;
478 Out->LaneMask = LaneMask;
479 }
480 LiveIns.erase(Out, LiveIns.end());
Aaron Ballmana2298462015-07-29 15:57:49 +0000481}
482
Jakob Stoklund Olesenf6476522013-07-03 23:56:20 +0000483unsigned
Matthias Braunfbf4c2b2015-08-25 22:05:55 +0000484MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
Jakob Stoklund Olesenf6476522013-07-03 23:56:20 +0000485 assert(getParent() && "MBB must be inserted in function");
486 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
487 assert(RC && "Register class is required");
Reid Klecknerc0e64ad2015-08-27 23:27:47 +0000488 assert((isEHPad() || this == &getParent()->front()) &&
Jakob Stoklund Olesenf6476522013-07-03 23:56:20 +0000489 "Only the entry block and landing pads can have physreg live ins");
490
491 bool LiveIn = isLiveIn(PhysReg);
Jakob Stoklund Olesenc982e142013-07-04 04:32:35 +0000492 iterator I = SkipPHIsAndLabels(begin()), E = end();
Jakob Stoklund Olesenf6476522013-07-03 23:56:20 +0000493 MachineRegisterInfo &MRI = getParent()->getRegInfo();
Eric Christopher60355182014-08-05 02:39:49 +0000494 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
Jakob Stoklund Olesenf6476522013-07-03 23:56:20 +0000495
496 // Look for an existing copy.
497 if (LiveIn)
498 for (;I != E && I->isCopy(); ++I)
499 if (I->getOperand(1).getReg() == PhysReg) {
500 unsigned VirtReg = I->getOperand(0).getReg();
501 if (!MRI.constrainRegClass(VirtReg, RC))
502 llvm_unreachable("Incompatible live-in register class.");
503 return VirtReg;
504 }
505
506 // No luck, create a virtual register.
507 unsigned VirtReg = MRI.createVirtualRegister(RC);
508 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
509 .addReg(PhysReg, RegState::Kill);
510 if (!LiveIn)
511 addLiveIn(PhysReg);
512 return VirtReg;
513}
514
Chris Lattnerc585a3f2006-10-24 00:02:26 +0000515void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +0000516 getParent()->splice(NewAfter->getIterator(), getIterator());
Chris Lattnerc585a3f2006-10-24 00:02:26 +0000517}
518
519void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +0000520 getParent()->splice(++NewBefore->getIterator(), getIterator());
Chris Lattnerc585a3f2006-10-24 00:02:26 +0000521}
522
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000523void MachineBasicBlock::updateTerminator() {
Eric Christopher60355182014-08-05 02:39:49 +0000524 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000525 // A block with no successors has no concerns with fall-through edges.
Chad Rosier1056b5b2016-05-25 21:53:46 +0000526 if (this->succ_empty())
527 return;
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000528
Craig Topper4ba84432014-04-14 00:51:57 +0000529 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000530 SmallVector<MachineOperand, 4> Cond;
Taewook Oh9fdcd962017-02-13 18:15:31 +0000531 DebugLoc DL = findBranchDebugLoc();
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +0000532 bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000533 (void) B;
534 assert(!B && "UpdateTerminators requires analyzable predecessors!");
535 if (Cond.empty()) {
536 if (TBB) {
Chad Rosier1056b5b2016-05-25 21:53:46 +0000537 // The block has an unconditional branch. If its successor is now its
538 // layout successor, delete the branch.
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000539 if (isLayoutSuccessor(TBB))
Matt Arsenault93e6e542016-09-14 20:43:16 +0000540 TII->removeBranch(*this);
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000541 } else {
Chad Rosier1056b5b2016-05-25 21:53:46 +0000542 // The block has an unconditional fallthrough. If its successor is not its
543 // layout successor, insert a branch. First we have to locate the only
544 // non-landing-pad successor, as that is the fallthrough block.
Chandler Carruth3b7b2092011-11-22 13:13:16 +0000545 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
Reid Klecknerc0e64ad2015-08-27 23:27:47 +0000546 if ((*SI)->isEHPad())
Chandler Carruth3b7b2092011-11-22 13:13:16 +0000547 continue;
548 assert(!TBB && "Found more than one non-landing-pad successor!");
549 TBB = *SI;
550 }
Chandler Carruth521fc5b2011-11-23 08:23:54 +0000551
Chad Rosier1056b5b2016-05-25 21:53:46 +0000552 // If there is no non-landing-pad successor, the block has no fall-through
553 // edges to be concerned with.
Chandler Carruth521fc5b2011-11-23 08:23:54 +0000554 if (!TBB)
555 return;
556
557 // Finally update the unconditional successor to be reached via a branch
558 // if it would not be reached by fallthrough.
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000559 if (!isLayoutSuccessor(TBB))
Matt Arsenaultb1a710d2016-09-14 17:24:15 +0000560 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000561 }
Chad Rosier1056b5b2016-05-25 21:53:46 +0000562 return;
563 }
Chandler Carruthf1a60c72012-04-16 22:03:00 +0000564
Chad Rosier1056b5b2016-05-25 21:53:46 +0000565 if (FBB) {
566 // The block has a non-fallthrough conditional branch. If one of its
567 // successors is its layout successor, rewrite it to a fallthrough
568 // conditional branch.
569 if (isLayoutSuccessor(TBB)) {
Matt Arsenault93e6e542016-09-14 20:43:16 +0000570 if (TII->reverseBranchCondition(Cond))
Chandler Carruthf1a60c72012-04-16 22:03:00 +0000571 return;
Matt Arsenault93e6e542016-09-14 20:43:16 +0000572 TII->removeBranch(*this);
Matt Arsenaultb1a710d2016-09-14 17:24:15 +0000573 TII->insertBranch(*this, FBB, nullptr, Cond, DL);
Chad Rosier1056b5b2016-05-25 21:53:46 +0000574 } else if (isLayoutSuccessor(FBB)) {
Matt Arsenault93e6e542016-09-14 20:43:16 +0000575 TII->removeBranch(*this);
Matt Arsenaultb1a710d2016-09-14 17:24:15 +0000576 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000577 }
Chad Rosier1056b5b2016-05-25 21:53:46 +0000578 return;
579 }
580
581 // Walk through the successors and find the successor which is not a landing
582 // pad and is not the conditional branch destination (in TBB) as the
583 // fallthrough successor.
584 MachineBasicBlock *FallthroughBB = nullptr;
585 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
586 if ((*SI)->isEHPad() || *SI == TBB)
587 continue;
588 assert(!FallthroughBB && "Found more than one fallthrough successor.");
589 FallthroughBB = *SI;
590 }
591
Haicheng Wue2d151c2016-07-03 19:14:17 +0000592 if (!FallthroughBB) {
593 if (canFallThrough()) {
594 // We fallthrough to the same basic block as the conditional jump targets.
595 // Remove the conditional jump, leaving unconditional fallthrough.
596 // FIXME: This does not seem like a reasonable pattern to support, but it
597 // has been seen in the wild coming out of degenerate ARM test cases.
Matt Arsenault93e6e542016-09-14 20:43:16 +0000598 TII->removeBranch(*this);
Taewook Oh9fdcd962017-02-13 18:15:31 +0000599
Haicheng Wue2d151c2016-07-03 19:14:17 +0000600 // Finally update the unconditional successor to be reached via a branch if
601 // it would not be reached by fallthrough.
602 if (!isLayoutSuccessor(TBB))
Matt Arsenaultb1a710d2016-09-14 17:24:15 +0000603 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
Haicheng Wue2d151c2016-07-03 19:14:17 +0000604 return;
605 }
Chad Rosier1056b5b2016-05-25 21:53:46 +0000606
Haicheng Wue2d151c2016-07-03 19:14:17 +0000607 // We enter here iff exactly one successor is TBB which cannot fallthrough
608 // and the rest successors if any are EHPads. In this case, we need to
609 // change the conditional branch into unconditional branch.
Matt Arsenault93e6e542016-09-14 20:43:16 +0000610 TII->removeBranch(*this);
Haicheng Wue2d151c2016-07-03 19:14:17 +0000611 Cond.clear();
Matt Arsenaultb1a710d2016-09-14 17:24:15 +0000612 TII->insertBranch(*this, TBB, nullptr, Cond, DL);
Chad Rosier1056b5b2016-05-25 21:53:46 +0000613 return;
614 }
615
616 // The block has a fallthrough conditional branch.
617 if (isLayoutSuccessor(TBB)) {
Matt Arsenault93e6e542016-09-14 20:43:16 +0000618 if (TII->reverseBranchCondition(Cond)) {
Chad Rosier1056b5b2016-05-25 21:53:46 +0000619 // We can't reverse the condition, add an unconditional branch.
620 Cond.clear();
Matt Arsenaultb1a710d2016-09-14 17:24:15 +0000621 TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
Chad Rosier1056b5b2016-05-25 21:53:46 +0000622 return;
623 }
Matt Arsenault93e6e542016-09-14 20:43:16 +0000624 TII->removeBranch(*this);
Matt Arsenaultb1a710d2016-09-14 17:24:15 +0000625 TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
Chad Rosier1056b5b2016-05-25 21:53:46 +0000626 } else if (!isLayoutSuccessor(FallthroughBB)) {
Matt Arsenault93e6e542016-09-14 20:43:16 +0000627 TII->removeBranch(*this);
Matt Arsenaultb1a710d2016-09-14 17:24:15 +0000628 TII->insertBranch(*this, TBB, FallthroughBB, Cond, DL);
Jim Grosbach7707a0d2009-11-12 03:55:33 +0000629 }
630}
Chris Lattnerc585a3f2006-10-24 00:02:26 +0000631
Cong Hou5ae2b852015-12-13 09:26:17 +0000632void MachineBasicBlock::validateSuccProbs() const {
633#ifndef NDEBUG
634 int64_t Sum = 0;
635 for (auto Prob : Probs)
636 Sum += Prob.getNumerator();
637 // Due to precision issue, we assume that the sum of probabilities is one if
638 // the difference between the sum of their numerators and the denominator is
639 // no greater than the number of successors.
Cong Hou778ee752015-12-13 17:00:25 +0000640 assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
Cong Hou5ae2b852015-12-13 09:26:17 +0000641 Probs.size() &&
642 "The sum of successors's probabilities exceeds one.");
643#endif // NDEBUG
644}
645
Cong Hou178bfbd2015-11-04 21:37:58 +0000646void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
647 BranchProbability Prob) {
648 // Probability list is either empty (if successor list isn't empty, this means
649 // disabled optimization) or has the same size as successor list.
Cong Hou1b91dc22015-12-01 11:05:39 +0000650 if (!(Probs.empty() && !Successors.empty()))
Cong Hou178bfbd2015-11-04 21:37:58 +0000651 Probs.push_back(Prob);
652 Successors.push_back(Succ);
653 Succ->addPredecessor(this);
654}
655
656void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
657 // We need to make sure probability list is either empty or has the same size
658 // of successor list. When this function is called, we can safely delete all
659 // probability in the list.
660 Probs.clear();
661 Successors.push_back(Succ);
662 Succ->addPredecessor(this);
663}
664
Chandler Carruthbd8c8d72018-07-13 11:13:58 +0000665void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old,
666 MachineBasicBlock *New,
667 bool NormalizeSuccProbs) {
668 succ_iterator OldI = llvm::find(successors(), Old);
669 assert(OldI != succ_end() && "Old is not a successor of this block!");
670 assert(llvm::find(successors(), New) == succ_end() &&
671 "New is already a successor of this block!");
672
673 // Add a new successor with equal probability as the original one. Note
674 // that we directly copy the probability using the iterator rather than
675 // getting a potentially synthetic probability computed when unknown. This
676 // preserves the probabilities as-is and then we can renormalize them and
677 // query them effectively afterward.
678 addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown()
679 : *getProbabilityIterator(OldI));
680 if (NormalizeSuccProbs)
681 normalizeSuccProbs();
682}
683
Cong Hou5ae2b852015-12-13 09:26:17 +0000684void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
685 bool NormalizeSuccProbs) {
David Majnemer975248e2016-08-11 22:21:41 +0000686 succ_iterator I = find(Successors, Succ);
Cong Hou5ae2b852015-12-13 09:26:17 +0000687 removeSuccessor(I, NormalizeSuccProbs);
Chris Lattner52c09d72004-10-26 15:43:42 +0000688}
689
Jakub Staszak12af5ff2011-06-16 18:01:17 +0000690MachineBasicBlock::succ_iterator
Cong Hou5ae2b852015-12-13 09:26:17 +0000691MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
Chris Lattner52c09d72004-10-26 15:43:42 +0000692 assert(I != Successors.end() && "Not a current successor!");
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000693
Cong Hou178bfbd2015-11-04 21:37:58 +0000694 // If probability list is empty it means we don't use it (disabled
695 // optimization).
696 if (!Probs.empty()) {
697 probability_iterator WI = getProbabilityIterator(I);
698 Probs.erase(WI);
Cong Hou5ae2b852015-12-13 09:26:17 +0000699 if (NormalizeSuccProbs)
700 normalizeSuccProbs();
Cong Hou178bfbd2015-11-04 21:37:58 +0000701 }
702
Chris Lattner52c09d72004-10-26 15:43:42 +0000703 (*I)->removePredecessor(this);
Dan Gohman5d5ee802009-01-08 22:19:34 +0000704 return Successors.erase(I);
Chris Lattner52c09d72004-10-26 15:43:42 +0000705}
706
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000707void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
708 MachineBasicBlock *New) {
Jakob Stoklund Olesen15121ca2012-08-10 03:23:27 +0000709 if (Old == New)
710 return;
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000711
Jakob Stoklund Olesen15121ca2012-08-10 03:23:27 +0000712 succ_iterator E = succ_end();
713 succ_iterator NewI = E;
714 succ_iterator OldI = E;
715 for (succ_iterator I = succ_begin(); I != E; ++I) {
716 if (*I == Old) {
717 OldI = I;
718 if (NewI != E)
719 break;
720 }
721 if (*I == New) {
722 NewI = I;
723 if (OldI != E)
724 break;
725 }
726 }
727 assert(OldI != E && "Old is not a successor of this block");
Jakob Stoklund Olesen15121ca2012-08-10 03:23:27 +0000728
729 // If New isn't already a successor, let it take Old's place.
730 if (NewI == E) {
Cong Hou70477052015-11-18 01:45:10 +0000731 Old->removePredecessor(this);
Jakob Stoklund Olesen15121ca2012-08-10 03:23:27 +0000732 New->addPredecessor(this);
733 *OldI = New;
734 return;
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000735 }
736
Jakob Stoklund Olesen15121ca2012-08-10 03:23:27 +0000737 // New is already a successor.
Cong Hou178bfbd2015-11-04 21:37:58 +0000738 // Update its probability instead of adding a duplicate edge.
Cong Hou51550212015-12-01 05:29:22 +0000739 if (!Probs.empty()) {
740 auto ProbIter = getProbabilityIterator(NewI);
741 if (!ProbIter->isUnknown())
742 *ProbIter += *getProbabilityIterator(OldI);
743 }
Cong Hou70477052015-11-18 01:45:10 +0000744 removeSuccessor(OldI);
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000745}
746
Chandler Carruth21a0c182018-04-10 01:41:17 +0000747void MachineBasicBlock::copySuccessor(MachineBasicBlock *Orig,
748 succ_iterator I) {
749 if (Orig->Probs.empty())
750 addSuccessor(*I, Orig->getSuccProbability(I));
751 else
752 addSuccessorWithoutProb(*I);
753}
754
Cong Houabae8482015-09-29 19:46:09 +0000755void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
756 Predecessors.push_back(Pred);
Chris Lattner52c09d72004-10-26 15:43:42 +0000757}
758
Cong Houabae8482015-09-29 19:46:09 +0000759void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
David Majnemer975248e2016-08-11 22:21:41 +0000760 pred_iterator I = find(Predecessors, Pred);
Chris Lattner52c09d72004-10-26 15:43:42 +0000761 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
762 Predecessors.erase(I);
763}
Evan Cheng4f098782007-05-17 23:58:53 +0000764
Cong Houabae8482015-09-29 19:46:09 +0000765void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
766 if (this == FromMBB)
Mon P Wang63307c32008-05-05 19:05:59 +0000767 return;
Jakub Staszak12af5ff2011-06-16 18:01:17 +0000768
Cong Houabae8482015-09-29 19:46:09 +0000769 while (!FromMBB->succ_empty()) {
770 MachineBasicBlock *Succ = *FromMBB->succ_begin();
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000771
Cong Hou51550212015-12-01 05:29:22 +0000772 // If probability list is empty it means we don't use it (disabled optimization).
773 if (!FromMBB->Probs.empty()) {
774 auto Prob = *FromMBB->Probs.begin();
775 addSuccessor(Succ, Prob);
776 } else
777 addSuccessorWithoutProb(Succ);
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000778
Cong Houabae8482015-09-29 19:46:09 +0000779 FromMBB->removeSuccessor(Succ);
Dan Gohman14152b42010-07-06 20:24:04 +0000780 }
781}
782
783void
Cong Houabae8482015-09-29 19:46:09 +0000784MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
785 if (this == FromMBB)
Dan Gohman14152b42010-07-06 20:24:04 +0000786 return;
Jakub Staszak12af5ff2011-06-16 18:01:17 +0000787
Cong Houabae8482015-09-29 19:46:09 +0000788 while (!FromMBB->succ_empty()) {
789 MachineBasicBlock *Succ = *FromMBB->succ_begin();
Cong Hou51550212015-12-01 05:29:22 +0000790 if (!FromMBB->Probs.empty()) {
791 auto Prob = *FromMBB->Probs.begin();
792 addSuccessor(Succ, Prob);
793 } else
794 addSuccessorWithoutProb(Succ);
Cong Houabae8482015-09-29 19:46:09 +0000795 FromMBB->removeSuccessor(Succ);
Dan Gohman14152b42010-07-06 20:24:04 +0000796
797 // Fix up any PHI nodes in the successor.
Evan Chengddfd1372011-12-14 02:11:42 +0000798 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
799 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
Dan Gohman14152b42010-07-06 20:24:04 +0000800 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
801 MachineOperand &MO = MI->getOperand(i);
Cong Houabae8482015-09-29 19:46:09 +0000802 if (MO.getMBB() == FromMBB)
Dan Gohman14152b42010-07-06 20:24:04 +0000803 MO.setMBB(this);
804 }
805 }
Cong Hou5ae2b852015-12-13 09:26:17 +0000806 normalizeSuccProbs();
Mon P Wang63307c32008-05-05 19:05:59 +0000807}
808
Jakob Stoklund Olesenf192b502012-07-30 17:36:47 +0000809bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
David Majnemer2d62ce62016-08-12 03:55:06 +0000810 return is_contained(predecessors(), MBB);
Jakob Stoklund Olesenf192b502012-07-30 17:36:47 +0000811}
812
Dan Gohman6d1b89e2009-03-30 20:06:29 +0000813bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
David Majnemer2d62ce62016-08-12 03:55:06 +0000814 return is_contained(successors(), MBB);
Evan Cheng4f098782007-05-17 23:58:53 +0000815}
Evan Cheng0370fad2007-06-04 06:44:01 +0000816
Dan Gohman6d1b89e2009-03-30 20:06:29 +0000817bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
Dan Gohman6ade6f52008-10-02 22:09:09 +0000818 MachineFunction::const_iterator I(this);
Benjamin Kramerd628f192014-03-02 12:27:27 +0000819 return std::next(I) == MachineFunction::const_iterator(MBB);
Dan Gohman6ade6f52008-10-02 22:09:09 +0000820}
821
Jan Sjodindcfd6182017-03-31 15:55:37 +0000822MachineBasicBlock *MachineBasicBlock::getFallThrough() {
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +0000823 MachineFunction::iterator Fallthrough = getIterator();
Bob Wilson15acadd2009-11-26 00:32:21 +0000824 ++Fallthrough;
825 // If FallthroughBlock is off the end of the function, it can't fall through.
826 if (Fallthrough == getParent()->end())
Jan Sjodindcfd6182017-03-31 15:55:37 +0000827 return nullptr;
Bob Wilson15acadd2009-11-26 00:32:21 +0000828
829 // If FallthroughBlock isn't a successor, no fallthrough is possible.
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +0000830 if (!isSuccessor(&*Fallthrough))
Jan Sjodindcfd6182017-03-31 15:55:37 +0000831 return nullptr;
Bob Wilson15acadd2009-11-26 00:32:21 +0000832
Dan Gohman735985f2009-12-05 00:32:59 +0000833 // Analyze the branches, if any, at the end of the block.
Craig Topper4ba84432014-04-14 00:51:57 +0000834 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Dan Gohman735985f2009-12-05 00:32:59 +0000835 SmallVector<MachineOperand, 4> Cond;
Eric Christopher60355182014-08-05 02:39:49 +0000836 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +0000837 if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
Dan Gohman735985f2009-12-05 00:32:59 +0000838 // If we couldn't analyze the branch, examine the last instruction.
839 // If the block doesn't end in a known control barrier, assume fallthrough
Chad Rosier0162ff42012-01-26 18:24:25 +0000840 // is possible. The isPredicated check is needed because this code can be
Dan Gohman735985f2009-12-05 00:32:59 +0000841 // called during IfConversion, where an instruction which is normally a
Chad Rosier6a5d0e22012-01-26 20:19:05 +0000842 // Barrier is predicated and thus no longer an actual control barrier.
Jan Sjodindcfd6182017-03-31 15:55:37 +0000843 return (empty() || !back().isBarrier() || TII->isPredicated(back()))
844 ? &*Fallthrough
845 : nullptr;
Dan Gohman735985f2009-12-05 00:32:59 +0000846 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000847
848 // If there is no branch, control always falls through.
Jan Sjodindcfd6182017-03-31 15:55:37 +0000849 if (!TBB) return &*Fallthrough;
Bob Wilson15acadd2009-11-26 00:32:21 +0000850
851 // If there is some explicit branch to the fallthrough block, it can obviously
852 // reach, even though the branch should get folded to fall through implicitly.
853 if (MachineFunction::iterator(TBB) == Fallthrough ||
854 MachineFunction::iterator(FBB) == Fallthrough)
Jan Sjodindcfd6182017-03-31 15:55:37 +0000855 return &*Fallthrough;
Bob Wilson15acadd2009-11-26 00:32:21 +0000856
857 // If it's an unconditional branch to some block not the fall through, it
858 // doesn't fall through.
Jan Sjodindcfd6182017-03-31 15:55:37 +0000859 if (Cond.empty()) return nullptr;
Bob Wilson15acadd2009-11-26 00:32:21 +0000860
861 // Otherwise, if it is conditional and has no explicit false block, it falls
862 // through.
Jan Sjodindcfd6182017-03-31 15:55:37 +0000863 return (FBB == nullptr) ? &*Fallthrough : nullptr;
864}
865
866bool MachineBasicBlock::canFallThrough() {
867 return getFallThrough() != nullptr;
Bob Wilson15acadd2009-11-26 00:32:21 +0000868}
869
Quentin Colombetf2cd1572016-04-21 21:01:13 +0000870MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ,
871 Pass &P) {
Quentin Colombete4d168d2016-04-21 20:46:27 +0000872 if (!canSplitCriticalEdge(Succ))
Craig Topper4ba84432014-04-14 00:51:57 +0000873 return nullptr;
Evan Chengddb14202012-04-24 19:06:55 +0000874
Dan Gohman853d3fb2010-06-22 17:25:57 +0000875 MachineFunction *MF = getParent();
Cong Houabae8482015-09-29 19:46:09 +0000876 DebugLoc DL; // FIXME: this is nowhere
Dan Gohman853d3fb2010-06-22 17:25:57 +0000877
Dan Gohman853d3fb2010-06-22 17:25:57 +0000878 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
Benjamin Kramerd628f192014-03-02 12:27:27 +0000879 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000880 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this)
881 << " -- " << printMBBReference(*NMBB) << " -- "
882 << printMBBReference(*Succ) << '\n');
Cameron Zwarichdd58fa42013-02-12 03:49:20 +0000883
Quentin Colombetf2cd1572016-04-21 21:01:13 +0000884 LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
885 SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
Cameron Zwarichdd58fa42013-02-12 03:49:20 +0000886 if (LIS)
887 LIS->insertMBBInMaps(NMBB);
888 else if (Indexes)
Cameron Zwarichf5844a72013-02-10 23:29:54 +0000889 Indexes->insertMBBInMaps(NMBB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000890
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +0000891 // On some targets like Mips, branches may kill virtual registers. Make sure
892 // that LiveVariables is properly updated after updateTerminator replaces the
893 // terminators.
Quentin Colombetf2cd1572016-04-21 21:01:13 +0000894 LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +0000895
896 // Collect a list of virtual registers killed by the terminators.
897 SmallVector<unsigned, 4> KilledRegs;
898 if (LV)
Evan Chengddfd1372011-12-14 02:11:42 +0000899 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000900 I != E; ++I) {
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +0000901 MachineInstr *MI = &*I;
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +0000902 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
903 OE = MI->operands_end(); OI != OE; ++OI) {
Lang Hames72a043f2012-02-09 05:59:36 +0000904 if (!OI->isReg() || OI->getReg() == 0 ||
905 !OI->isUse() || !OI->isKill() || OI->isUndef())
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +0000906 continue;
907 unsigned Reg = OI->getReg();
Lang Hames72a043f2012-02-09 05:59:36 +0000908 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
Duncan P. N. Exon Smith4383a512016-07-01 01:51:32 +0000909 LV->getVarInfo(Reg).removeKill(*MI)) {
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +0000910 KilledRegs.push_back(Reg);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000911 LLVM_DEBUG(dbgs() << "Removing terminator kill: " << *MI);
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +0000912 OI->setIsKill(false);
913 }
914 }
915 }
916
Cameron Zwarichf0b25352013-02-17 00:10:44 +0000917 SmallVector<unsigned, 4> UsedRegs;
918 if (LIS) {
919 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
920 I != E; ++I) {
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +0000921 MachineInstr *MI = &*I;
Cameron Zwarichf0b25352013-02-17 00:10:44 +0000922
923 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
924 OE = MI->operands_end(); OI != OE; ++OI) {
925 if (!OI->isReg() || OI->getReg() == 0)
926 continue;
927
928 unsigned Reg = OI->getReg();
David Majnemer975248e2016-08-11 22:21:41 +0000929 if (!is_contained(UsedRegs, Reg))
Cameron Zwarichf0b25352013-02-17 00:10:44 +0000930 UsedRegs.push_back(Reg);
931 }
932 }
933 }
934
Dan Gohman853d3fb2010-06-22 17:25:57 +0000935 ReplaceUsesOfBlockWith(Succ, NMBB);
Cameron Zwarichcbe3f5e2013-02-11 09:24:45 +0000936
937 // If updateTerminator() removes instructions, we need to remove them from
938 // SlotIndexes.
939 SmallVector<MachineInstr*, 4> Terminators;
940 if (Indexes) {
941 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
942 I != E; ++I)
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +0000943 Terminators.push_back(&*I);
Cameron Zwarichcbe3f5e2013-02-11 09:24:45 +0000944 }
945
Dan Gohman853d3fb2010-06-22 17:25:57 +0000946 updateTerminator();
947
Cameron Zwarichcbe3f5e2013-02-11 09:24:45 +0000948 if (Indexes) {
949 SmallVector<MachineInstr*, 4> NewTerminators;
950 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
951 I != E; ++I)
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +0000952 NewTerminators.push_back(&*I);
Cameron Zwarichcbe3f5e2013-02-11 09:24:45 +0000953
954 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
955 E = Terminators.end(); I != E; ++I) {
David Majnemer975248e2016-08-11 22:21:41 +0000956 if (!is_contained(NewTerminators, *I))
957 Indexes->removeMachineInstrFromMaps(**I);
Cameron Zwarichcbe3f5e2013-02-11 09:24:45 +0000958 }
959 }
960
Dan Gohman853d3fb2010-06-22 17:25:57 +0000961 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
962 NMBB->addSuccessor(Succ);
963 if (!NMBB->isLayoutSuccessor(Succ)) {
Quentin Colombete4d168d2016-04-21 20:46:27 +0000964 SmallVector<MachineOperand, 4> Cond;
965 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
Matt Arsenaultb1a710d2016-09-14 17:24:15 +0000966 TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
Cameron Zwarichf5844a72013-02-10 23:29:54 +0000967
968 if (Indexes) {
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000969 for (MachineInstr &MI : NMBB->instrs()) {
Cameron Zwarichf5844a72013-02-10 23:29:54 +0000970 // Some instructions may have been moved to NMBB by updateTerminator(),
971 // so we first remove any instruction that already has an index.
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000972 if (Indexes->hasIndex(MI))
973 Indexes->removeMachineInstrFromMaps(MI);
974 Indexes->insertMachineInstrInMaps(MI);
Cameron Zwarichf5844a72013-02-10 23:29:54 +0000975 }
976 }
Dan Gohman853d3fb2010-06-22 17:25:57 +0000977 }
978
979 // Fix PHI nodes in Succ so they refer to NMBB instead of this
Evan Chengddfd1372011-12-14 02:11:42 +0000980 for (MachineBasicBlock::instr_iterator
981 i = Succ->instr_begin(),e = Succ->instr_end();
982 i != e && i->isPHI(); ++i)
Dan Gohman853d3fb2010-06-22 17:25:57 +0000983 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
984 if (i->getOperand(ni+1).getMBB() == this)
985 i->getOperand(ni+1).setMBB(NMBB);
986
Jakob Stoklund Olesenac7caa02011-10-14 17:25:46 +0000987 // Inherit live-ins from the successor
Matthias Braunaf5ff602015-09-09 18:08:03 +0000988 for (const auto &LI : Succ->liveins())
Matthias Braun56dd2d02015-08-24 22:59:52 +0000989 NMBB->addLiveIn(LI);
Jakob Stoklund Olesenac7caa02011-10-14 17:25:46 +0000990
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +0000991 // Update LiveVariables.
Eric Christopher60355182014-08-05 02:39:49 +0000992 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +0000993 if (LV) {
994 // Restore kills of virtual registers that were killed by the terminators.
995 while (!KilledRegs.empty()) {
996 unsigned Reg = KilledRegs.pop_back_val();
Evan Chengddfd1372011-12-14 02:11:42 +0000997 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
Lang Hames72a043f2012-02-09 05:59:36 +0000998 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +0000999 continue;
Lang Hames72a043f2012-02-09 05:59:36 +00001000 if (TargetRegisterInfo::isVirtualRegister(Reg))
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +00001001 LV->getVarInfo(Reg).Kills.push_back(&*I);
Nicola Zaghen0818e782018-05-14 12:53:11 +00001002 LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I);
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +00001003 break;
1004 }
1005 }
1006 // Update relevant live-through information.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001007 LV->addNewBlock(NMBB, this, Succ);
Jakob Stoklund Olesen57903352011-05-29 20:10:28 +00001008 }
Dan Gohman853d3fb2010-06-22 17:25:57 +00001009
Cameron Zwarichdd58fa42013-02-12 03:49:20 +00001010 if (LIS) {
Cameron Zwarich8597c142013-02-11 09:24:47 +00001011 // After splitting the edge and updating SlotIndexes, live intervals may be
1012 // in one of two situations, depending on whether this block was the last in
Cong Hou7ab9abd2015-08-10 22:27:10 +00001013 // the function. If the original block was the last in the function, all
1014 // live intervals will end prior to the beginning of the new split block. If
1015 // the original block was not at the end of the function, all live intervals
1016 // will extend to the end of the new split block.
Cameron Zwarich8597c142013-02-11 09:24:47 +00001017
1018 bool isLastMBB =
Benjamin Kramerd628f192014-03-02 12:27:27 +00001019 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
Cameron Zwarich8597c142013-02-11 09:24:47 +00001020
1021 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
1022 SlotIndex PrevIndex = StartIndex.getPrevSlot();
1023 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
1024
1025 // Find the registers used from NMBB in PHIs in Succ.
1026 SmallSet<unsigned, 8> PHISrcRegs;
1027 for (MachineBasicBlock::instr_iterator
1028 I = Succ->instr_begin(), E = Succ->instr_end();
1029 I != E && I->isPHI(); ++I) {
1030 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
1031 if (I->getOperand(ni+1).getMBB() == NMBB) {
1032 MachineOperand &MO = I->getOperand(ni);
1033 unsigned Reg = MO.getReg();
1034 PHISrcRegs.insert(Reg);
Cameron Zwarichdbf10c42013-02-12 03:49:17 +00001035 if (MO.isUndef())
1036 continue;
Cameron Zwarich8597c142013-02-11 09:24:47 +00001037
1038 LiveInterval &LI = LIS->getInterval(Reg);
1039 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
Cong Hou7ab9abd2015-08-10 22:27:10 +00001040 assert(VNI &&
1041 "PHI sources should be live out of their predecessors.");
Matthias Braun331de112013-10-10 21:28:43 +00001042 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
Cameron Zwarich8597c142013-02-11 09:24:47 +00001043 }
1044 }
1045 }
1046
1047 MachineRegisterInfo *MRI = &getParent()->getRegInfo();
1048 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1049 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1050 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
1051 continue;
1052
1053 LiveInterval &LI = LIS->getInterval(Reg);
1054 if (!LI.liveAt(PrevIndex))
1055 continue;
1056
Cameron Zwarichdbf10c42013-02-12 03:49:17 +00001057 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
Cameron Zwarich8597c142013-02-11 09:24:47 +00001058 if (isLiveOut && isLastMBB) {
1059 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
1060 assert(VNI && "LiveInterval should have VNInfo where it is live.");
Matthias Braun331de112013-10-10 21:28:43 +00001061 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
Cameron Zwarich8597c142013-02-11 09:24:47 +00001062 } else if (!isLiveOut && !isLastMBB) {
Matthias Braun331de112013-10-10 21:28:43 +00001063 LI.removeSegment(StartIndex, EndIndex);
Cameron Zwarich8597c142013-02-11 09:24:47 +00001064 }
1065 }
Cameron Zwarichf0b25352013-02-17 00:10:44 +00001066
1067 // Update all intervals for registers whose uses may have been modified by
1068 // updateTerminator().
Cameron Zwarich680c98f2013-02-17 11:09:00 +00001069 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
Cameron Zwarich8597c142013-02-11 09:24:47 +00001070 }
1071
Dan Gohman853d3fb2010-06-22 17:25:57 +00001072 if (MachineDominatorTree *MDT =
Quentin Colombetf2cd1572016-04-21 21:01:13 +00001073 P.getAnalysisIfAvailable<MachineDominatorTree>())
Quentin Colombet49128632014-08-13 21:00:07 +00001074 MDT->recordSplitCriticalEdge(this, Succ, NMBB);
Dan Gohman853d3fb2010-06-22 17:25:57 +00001075
Quentin Colombetf2cd1572016-04-21 21:01:13 +00001076 if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
Dan Gohman853d3fb2010-06-22 17:25:57 +00001077 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
1078 // If one or the other blocks were not in a loop, the new block is not
1079 // either, and thus LI doesn't need to be updated.
1080 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
1081 if (TIL == DestLoop) {
1082 // Both in the same loop, the NMBB joins loop.
1083 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1084 } else if (TIL->contains(DestLoop)) {
1085 // Edge from an outer loop to an inner loop. Add to the outer loop.
1086 TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
1087 } else if (DestLoop->contains(TIL)) {
1088 // Edge from an inner loop to an outer loop. Add to the outer loop.
1089 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
1090 } else {
1091 // Edge from two loops with no containment relation. Because these
1092 // are natural loops, we know that the destination block must be the
1093 // header of its loop (adding a branch into a loop elsewhere would
1094 // create an irreducible loop).
1095 assert(DestLoop->getHeader() == Succ &&
1096 "Should not create irreducible loops!");
1097 if (MachineLoop *P = DestLoop->getParentLoop())
1098 P->addBasicBlockToLoop(NMBB, MLI->getBase());
1099 }
1100 }
1101 }
1102
1103 return NMBB;
1104}
1105
Quentin Colombete4d168d2016-04-21 20:46:27 +00001106bool MachineBasicBlock::canSplitCriticalEdge(
1107 const MachineBasicBlock *Succ) const {
1108 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
1109 // it in this generic function.
1110 if (Succ->isEHPad())
1111 return false;
1112
1113 const MachineFunction *MF = getParent();
1114
1115 // Performance might be harmed on HW that implements branching using exec mask
1116 // where both sides of the branches are always executed.
1117 if (MF->getTarget().requiresStructuredCFG())
1118 return false;
1119
1120 // We may need to update this's terminator, but we can't do that if
1121 // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
1122 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1123 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1124 SmallVector<MachineOperand, 4> Cond;
1125 // AnalyzeBanch should modify this, since we did not allow modification.
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +00001126 if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
Quentin Colombete4d168d2016-04-21 20:46:27 +00001127 /*AllowModify*/ false))
1128 return false;
1129
1130 // Avoid bugpoint weirdness: A block may end with a conditional branch but
1131 // jumps to the same MBB is either case. We have duplicate CFG edges in that
1132 // case that we can't handle. Since this never happens in properly optimized
1133 // code, just skip those edges.
1134 if (TBB && TBB == FBB) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001135 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate "
1136 << printMBBReference(*this) << '\n');
Quentin Colombete4d168d2016-04-21 20:46:27 +00001137 return false;
1138 }
1139 return true;
1140}
1141
Jakob Stoklund Olesen9f4692d2012-12-17 23:55:38 +00001142/// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
1143/// neighboring instructions so the bundle won't be broken by removing MI.
1144static void unbundleSingleMI(MachineInstr *MI) {
1145 // Removing the first instruction in a bundle.
1146 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
1147 MI->unbundleFromSucc();
1148 // Removing the last instruction in a bundle.
1149 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
1150 MI->unbundleFromPred();
1151 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
1152 // are already fine.
Evan Chengddfd1372011-12-14 02:11:42 +00001153}
1154
Jakob Stoklund Olesen9f4692d2012-12-17 23:55:38 +00001155MachineBasicBlock::instr_iterator
1156MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
Duncan P. N. Exon Smithb1510c22015-10-09 19:23:20 +00001157 unbundleSingleMI(&*I);
Jakob Stoklund Olesen9f4692d2012-12-17 23:55:38 +00001158 return Insts.erase(I);
1159}
Evan Chengddfd1372011-12-14 02:11:42 +00001160
Jakob Stoklund Olesen9f4692d2012-12-17 23:55:38 +00001161MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
1162 unbundleSingleMI(MI);
1163 MI->clearFlag(MachineInstr::BundledPred);
1164 MI->clearFlag(MachineInstr::BundledSucc);
1165 return Insts.remove(MI);
Evan Chengddfd1372011-12-14 02:11:42 +00001166}
1167
Jakob Stoklund Olesenedc35032012-12-18 17:54:53 +00001168MachineBasicBlock::instr_iterator
1169MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
1170 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1171 "Cannot insert instruction with bundle flags");
1172 // Set the bundle flags when inserting inside a bundle.
1173 if (I != instr_end() && I->isBundledWithPred()) {
1174 MI->setFlag(MachineInstr::BundledPred);
1175 MI->setFlag(MachineInstr::BundledSucc);
1176 }
1177 return Insts.insert(I, MI);
1178}
1179
Cong Hou30f85e52015-08-12 21:18:54 +00001180/// This method unlinks 'this' from the containing function, and returns it, but
1181/// does not delete it.
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001182MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1183 assert(getParent() && "Not embedded in a function!");
1184 getParent()->remove(this);
1185 return this;
1186}
1187
Cong Hou30f85e52015-08-12 21:18:54 +00001188/// This method unlinks 'this' from the containing function, and deletes it.
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001189void MachineBasicBlock::eraseFromParent() {
1190 assert(getParent() && "Not embedded in a function!");
1191 getParent()->erase(this);
1192}
1193
Cong Hou30f85e52015-08-12 21:18:54 +00001194/// Given a machine basic block that branched to 'Old', change the code and CFG
1195/// so that it branches to 'New' instead.
Evan Cheng0370fad2007-06-04 06:44:01 +00001196void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1197 MachineBasicBlock *New) {
1198 assert(Old != New && "Cannot replace self with self!");
1199
Evan Chengddfd1372011-12-14 02:11:42 +00001200 MachineBasicBlock::instr_iterator I = instr_end();
1201 while (I != instr_begin()) {
Evan Cheng0370fad2007-06-04 06:44:01 +00001202 --I;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001203 if (!I->isTerminator()) break;
Evan Cheng0370fad2007-06-04 06:44:01 +00001204
1205 // Scan the operands of this machine instruction, replacing any uses of Old
1206 // with New.
1207 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001208 if (I->getOperand(i).isMBB() &&
Dan Gohman014278e2008-09-13 17:58:21 +00001209 I->getOperand(i).getMBB() == Old)
Chris Lattner8aa797a2007-12-30 23:10:15 +00001210 I->getOperand(i).setMBB(New);
Evan Cheng0370fad2007-06-04 06:44:01 +00001211 }
1212
Dan Gohman5412d062009-05-05 21:10:19 +00001213 // Update the successor information.
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001214 replaceSuccessor(Old, New);
Evan Cheng0370fad2007-06-04 06:44:01 +00001215}
1216
Cong Hou30f85e52015-08-12 21:18:54 +00001217/// Various pieces of code can cause excess edges in the CFG to be inserted. If
1218/// we have proven that MBB can only branch to DestA and DestB, remove any other
1219/// MBB successors from the CFG. DestA and DestB can be null.
Jakub Staszak12af5ff2011-06-16 18:01:17 +00001220///
Chris Lattnerf20c1a42007-12-31 04:56:33 +00001221/// Besides DestA and DestB, retain other edges leading to LandingPads
1222/// (currently there can be only one; we don't check or require that here).
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001223/// Note it is possible that DestA and/or DestB are LandingPads.
1224bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1225 MachineBasicBlock *DestB,
Cong Houabae8482015-09-29 19:46:09 +00001226 bool IsCond) {
Bill Wendlingc70d33112009-12-16 00:08:36 +00001227 // The values of DestA and DestB frequently come from a call to the
1228 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1229 // values from there.
1230 //
1231 // 1. If both DestA and DestB are null, then the block ends with no branches
1232 // (it falls through to its successor).
Cong Houabae8482015-09-29 19:46:09 +00001233 // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
Bill Wendlingc70d33112009-12-16 00:08:36 +00001234 // with only an unconditional branch.
Cong Houabae8482015-09-29 19:46:09 +00001235 // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
Bill Wendlingc70d33112009-12-16 00:08:36 +00001236 // with a conditional branch that falls through to a successor (DestB).
Cong Houabae8482015-09-29 19:46:09 +00001237 // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
Bill Wendlingc70d33112009-12-16 00:08:36 +00001238 // conditional branch followed by an unconditional branch. DestA is the
1239 // 'true' destination and DestB is the 'false' destination.
1240
Bill Wendlinge543d162010-04-01 00:00:43 +00001241 bool Changed = false;
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001242
Duncan P. N. Exon Smith52a07ee2016-08-16 21:46:03 +00001243 MachineBasicBlock *FallThru = getNextNode();
Bill Wendlinge543d162010-04-01 00:00:43 +00001244
Craig Topper4ba84432014-04-14 00:51:57 +00001245 if (!DestA && !DestB) {
Bill Wendlinge543d162010-04-01 00:00:43 +00001246 // Block falls through to successor.
Duncan P. N. Exon Smith52a07ee2016-08-16 21:46:03 +00001247 DestA = FallThru;
1248 DestB = FallThru;
Craig Topper4ba84432014-04-14 00:51:57 +00001249 } else if (DestA && !DestB) {
Cong Houabae8482015-09-29 19:46:09 +00001250 if (IsCond)
Bill Wendlinge543d162010-04-01 00:00:43 +00001251 // Block ends in conditional jump that falls through to successor.
Duncan P. N. Exon Smith52a07ee2016-08-16 21:46:03 +00001252 DestB = FallThru;
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001253 } else {
Cong Houabae8482015-09-29 19:46:09 +00001254 assert(DestA && DestB && IsCond &&
Bill Wendlinge543d162010-04-01 00:00:43 +00001255 "CFG in a bad state. Cannot correct CFG edges");
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001256 }
Bill Wendlinge543d162010-04-01 00:00:43 +00001257
1258 // Remove superfluous edges. I.e., those which aren't destinations of this
1259 // basic block, duplicate edges, or landing pads.
1260 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001261 MachineBasicBlock::succ_iterator SI = succ_begin();
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001262 while (SI != succ_end()) {
Bill Wendlingc70d33112009-12-16 00:08:36 +00001263 const MachineBasicBlock *MBB = *SI;
David Blaikie5401ba72014-11-19 07:49:26 +00001264 if (!SeenMBBs.insert(MBB).second ||
Reid Klecknerc0e64ad2015-08-27 23:27:47 +00001265 (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
Bill Wendlinge543d162010-04-01 00:00:43 +00001266 // This is a superfluous edge, remove it.
Bill Wendling9e9cca42010-03-31 23:26:26 +00001267 SI = removeSuccessor(SI);
Bill Wendlinge543d162010-04-01 00:00:43 +00001268 Changed = true;
1269 } else {
1270 ++SI;
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001271 }
1272 }
Bill Wendlingc70d33112009-12-16 00:08:36 +00001273
Cong Hou5ae2b852015-12-13 09:26:17 +00001274 if (Changed)
1275 normalizeSuccProbs();
Bill Wendlinge543d162010-04-01 00:00:43 +00001276 return Changed;
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001277}
Evan Cheng2a085c32009-11-17 19:19:59 +00001278
Cong Hou30f85e52015-08-12 21:18:54 +00001279/// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1280/// instructions. Return UnknownLoc if there is none.
Dale Johannesen73e884b2010-01-20 21:36:02 +00001281DebugLoc
Evan Chengddfd1372011-12-14 02:11:42 +00001282MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
Evan Cheng7c2a4a32011-12-06 22:12:01 +00001283 // Skip debug declarations, we don't want a DebugLoc from them.
Florian Hahnf295c8c2016-12-16 11:10:26 +00001284 MBBI = skipDebugInstructionsForward(MBBI, instr_end());
1285 if (MBBI != instr_end())
1286 return MBBI->getDebugLoc();
1287 return {};
Dale Johannesen73e884b2010-01-20 21:36:02 +00001288}
1289
Derek Schuff1695e782018-03-15 22:06:51 +00001290/// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE
1291/// instructions. Return UnknownLoc if there is none.
1292DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) {
1293 if (MBBI == instr_begin()) return {};
1294 // Skip debug declarations, we don't want a DebugLoc from them.
1295 MBBI = skipDebugInstructionsBackward(std::prev(MBBI), instr_begin());
Shiva Chen24abe712018-05-09 02:42:00 +00001296 if (!MBBI->isDebugInstr()) return MBBI->getDebugLoc();
Derek Schuff1695e782018-03-15 22:06:51 +00001297 return {};
1298}
1299
Taewook Oh9fdcd962017-02-13 18:15:31 +00001300/// Find and return the merged DebugLoc of the branch instructions of the block.
1301/// Return UnknownLoc if there is none.
1302DebugLoc
1303MachineBasicBlock::findBranchDebugLoc() {
Taewook Oh47946ad2017-02-13 21:12:27 +00001304 DebugLoc DL;
Taewook Oh9fdcd962017-02-13 18:15:31 +00001305 auto TI = getFirstTerminator();
1306 while (TI != end() && !TI->isBranch())
1307 ++TI;
1308
1309 if (TI != end()) {
1310 DL = TI->getDebugLoc();
1311 for (++TI ; TI != end() ; ++TI)
1312 if (TI->isBranch())
1313 DL = DILocation::getMergedLocation(DL, TI->getDebugLoc());
1314 }
1315 return DL;
1316}
1317
Cong Hou51550212015-12-01 05:29:22 +00001318/// Return probability of the edge from this block to MBB.
Cong Hou178bfbd2015-11-04 21:37:58 +00001319BranchProbability
1320MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
Cong Hou1b91dc22015-12-01 11:05:39 +00001321 if (Probs.empty())
Cong Hou178bfbd2015-11-04 21:37:58 +00001322 return BranchProbability(1, succ_size());
1323
Cong Hou1b91dc22015-12-01 11:05:39 +00001324 const auto &Prob = *getProbabilityIterator(Succ);
1325 if (Prob.isUnknown()) {
1326 // For unknown probabilities, collect the sum of all known ones, and evenly
1327 // ditribute the complemental of the sum to each unknown probability.
1328 unsigned KnownProbNum = 0;
1329 auto Sum = BranchProbability::getZero();
1330 for (auto &P : Probs) {
1331 if (!P.isUnknown()) {
1332 Sum += P;
1333 KnownProbNum++;
1334 }
1335 }
1336 return Sum.getCompl() / (Probs.size() - KnownProbNum);
1337 } else
1338 return Prob;
Manman Renea120b62014-01-29 23:18:47 +00001339}
1340
Cong Hou178bfbd2015-11-04 21:37:58 +00001341/// Set successor probability of a given iterator.
1342void MachineBasicBlock::setSuccProbability(succ_iterator I,
1343 BranchProbability Prob) {
1344 assert(!Prob.isUnknown());
Cong Hou51550212015-12-01 05:29:22 +00001345 if (Probs.empty())
Cong Hou178bfbd2015-11-04 21:37:58 +00001346 return;
1347 *getProbabilityIterator(I) = Prob;
Cong Hou178bfbd2015-11-04 21:37:58 +00001348}
1349
Hans Wennborg8e83fe22015-12-01 03:49:42 +00001350/// Return probability iterator corresonding to the I successor iterator
1351MachineBasicBlock::const_probability_iterator
1352MachineBasicBlock::getProbabilityIterator(
1353 MachineBasicBlock::const_succ_iterator I) const {
Cong Hou92989cb2015-12-01 00:02:51 +00001354 assert(Probs.size() == Successors.size() && "Async probability list!");
1355 const size_t index = std::distance(Successors.begin(), I);
1356 assert(index < Probs.size() && "Not a current successor!");
1357 return Probs.begin() + index;
1358}
1359
Cong Hou51550212015-12-01 05:29:22 +00001360/// Return probability iterator corresonding to the I successor iterator.
1361MachineBasicBlock::probability_iterator
1362MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1363 assert(Probs.size() == Successors.size() && "Async probability list!");
1364 const size_t index = std::distance(Successors.begin(), I);
1365 assert(index < Probs.size() && "Not a current successor!");
1366 return Probs.begin() + index;
1367}
1368
James Molloyc4f70d42012-09-12 10:18:23 +00001369/// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1370/// as of just before "MI".
Junmo Park75ad35c2016-01-07 10:26:32 +00001371///
James Molloyc4f70d42012-09-12 10:18:23 +00001372/// Search is localised to a neighborhood of
1373/// Neighborhood instructions before (searching for defs or kills) and N
1374/// instructions after (searching just for defs) MI.
1375MachineBasicBlock::LivenessQueryResult
1376MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
Matthias Braunf5b42732015-05-27 05:12:39 +00001377 unsigned Reg, const_iterator Before,
1378 unsigned Neighborhood) const {
James Molloyc4f70d42012-09-12 10:18:23 +00001379 unsigned N = Neighborhood;
James Molloyc4f70d42012-09-12 10:18:23 +00001380
Matt Arsenaultf29f15e2018-08-30 07:18:10 +00001381 // Try searching forwards from Before, looking for reads or defs.
Matthias Braunf5b42732015-05-27 05:12:39 +00001382 const_iterator I(Before);
Eli Friedman7a455512018-11-14 00:39:29 +00001383 for (; I != end() && N > 0; ++I) {
1384 if (I->isDebugInstr())
1385 continue;
Matt Arsenaultda1abaa2018-08-30 07:18:19 +00001386
Eli Friedman7a455512018-11-14 00:39:29 +00001387 --N;
Matt Arsenaultda1abaa2018-08-30 07:18:19 +00001388
Eli Friedman7a455512018-11-14 00:39:29 +00001389 MachineOperandIteratorBase::PhysRegInfo Info =
1390 ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
Matt Arsenaultf29f15e2018-08-30 07:18:10 +00001391
Eli Friedman7a455512018-11-14 00:39:29 +00001392 // Register is live when we read it here.
1393 if (Info.Read)
1394 return LQR_Live;
1395 // Register is dead if we can fully overwrite or clobber it here.
1396 if (Info.FullyDefined || Info.Clobbered)
1397 return LQR_Dead;
Matt Arsenaultf29f15e2018-08-30 07:18:10 +00001398 }
1399
1400 // If we reached the end, it is safe to clobber Reg at the end of a block of
1401 // no successor has it live in.
1402 if (I == end()) {
1403 for (MachineBasicBlock *S : successors()) {
Mikael Holmen556673f2018-09-25 06:10:04 +00001404 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) {
1405 if (TRI->regsOverlap(LI.PhysReg, Reg))
Matt Arsenaultf29f15e2018-08-30 07:18:10 +00001406 return LQR_Live;
1407 }
1408 }
1409
1410 return LQR_Dead;
1411 }
1412
1413
1414 N = Neighborhood;
1415
1416 // Start by searching backwards from Before, looking for kills, reads or defs.
1417 I = const_iterator(Before);
James Molloyc4f70d42012-09-12 10:18:23 +00001418 // If this is the first insn in the block, don't search backwards.
Matthias Braunf5b42732015-05-27 05:12:39 +00001419 if (I != begin()) {
James Molloyc4f70d42012-09-12 10:18:23 +00001420 do {
1421 --I;
1422
Matt Arsenaultda1abaa2018-08-30 07:18:19 +00001423 if (I->isDebugInstr())
1424 continue;
1425
1426 --N;
1427
Matthias Braunf43272c2015-12-11 19:42:09 +00001428 MachineOperandIteratorBase::PhysRegInfo Info =
Duncan P. N. Exon Smith63ec7f02016-02-27 17:05:33 +00001429 ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
James Molloyc4f70d42012-09-12 10:18:23 +00001430
Matthias Braunf43272c2015-12-11 19:42:09 +00001431 // Defs happen after uses so they take precedence if both are present.
Tim Northover310f2482012-11-20 09:56:11 +00001432
Matthias Braunf43272c2015-12-11 19:42:09 +00001433 // Register is dead after a dead def of the full register.
1434 if (Info.DeadDef)
James Molloyc4f70d42012-09-12 10:18:23 +00001435 return LQR_Dead;
Matthias Braunf43272c2015-12-11 19:42:09 +00001436 // Register is (at least partially) live after a def.
Quentin Colombet1b369e42016-04-26 23:14:29 +00001437 if (Info.Defined) {
1438 if (!Info.PartialDeadDef)
1439 return LQR_Live;
1440 // As soon as we saw a partial definition (dead or not),
1441 // we cannot tell if the value is partial live without
1442 // tracking the lanemasks. We are not going to do this,
1443 // so fall back on the remaining of the analysis.
1444 break;
1445 }
Matthias Braunf43272c2015-12-11 19:42:09 +00001446 // Register is dead after a full kill or clobber and no def.
1447 if (Info.Killed || Info.Clobbered)
1448 return LQR_Dead;
1449 // Register must be live if we read it.
1450 if (Info.Read)
1451 return LQR_Live;
Matt Arsenaultda1abaa2018-08-30 07:18:19 +00001452
1453 } while (I != begin() && N > 0);
James Molloyc4f70d42012-09-12 10:18:23 +00001454 }
1455
1456 // Did we get to the start of the block?
Matthias Braunf5b42732015-05-27 05:12:39 +00001457 if (I == begin()) {
James Molloyc4f70d42012-09-12 10:18:23 +00001458 // If so, the register's state is definitely defined by the live-in state.
Mikael Holmen556673f2018-09-25 06:10:04 +00001459 for (const MachineBasicBlock::RegisterMaskPair &LI : liveins())
1460 if (TRI->regsOverlap(LI.PhysReg, Reg))
Matthias Braunf43272c2015-12-11 19:42:09 +00001461 return LQR_Live;
James Molloyc4f70d42012-09-12 10:18:23 +00001462
1463 return LQR_Dead;
1464 }
1465
James Molloyc4f70d42012-09-12 10:18:23 +00001466 // At this point we have no idea of the liveness of the register.
1467 return LQR_Unknown;
1468}
Reid Klecknerf0a04c02015-11-06 17:06:38 +00001469
1470const uint32_t *
1471MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1472 // EH funclet entry does not preserve any registers.
1473 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1474}
1475
1476const uint32_t *
1477MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1478 // If we see a return block with successors, this must be a funclet return,
1479 // which does not preserve any registers. If there are no successors, we don't
1480 // care what kind of return it is, putting a mask after it is a no-op.
1481 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
1482}
Matthias Braunfe82f4a2016-12-16 23:55:37 +00001483
1484void MachineBasicBlock::clearLiveIns() {
1485 LiveIns.clear();
1486}
Matthias Braun47004632017-01-05 20:01:19 +00001487
1488MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const {
1489 assert(getParent()->getProperties().hasProperty(
1490 MachineFunctionProperties::Property::TracksLiveness) &&
1491 "Liveness information is accurate");
1492 return LiveIns.begin();
1493}