MachineBasicBlock.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Collect the sequence of machine instructions for a basic block.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/MachineBasicBlock.h"
  14. #include "llvm/ADT/SmallPtrSet.h"
  15. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  16. #include "llvm/CodeGen/LiveVariables.h"
  17. #include "llvm/CodeGen/MachineDominators.h"
  18. #include "llvm/CodeGen/MachineFunction.h"
  19. #include "llvm/CodeGen/MachineInstrBuilder.h"
  20. #include "llvm/CodeGen/MachineLoopInfo.h"
  21. #include "llvm/CodeGen/MachineRegisterInfo.h"
  22. #include "llvm/CodeGen/SlotIndexes.h"
  23. #include "llvm/IR/BasicBlock.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/ModuleSlotTracker.h"
  26. #include "llvm/MC/MCAsmInfo.h"
  27. #include "llvm/MC/MCContext.h"
  28. #include "llvm/Support/DataTypes.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include "llvm/Target/TargetInstrInfo.h"
  32. #include "llvm/Target/TargetMachine.h"
  33. #include "llvm/Target/TargetRegisterInfo.h"
  34. #include "llvm/Target/TargetSubtargetInfo.h"
  35. #include <algorithm>
  36. using namespace llvm;
  37. #define DEBUG_TYPE "codegen"
  38. MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
  39. : BB(B), Number(-1), xParent(&MF) {
  40. Insts.Parent = this;
  41. }
  42. MachineBasicBlock::~MachineBasicBlock() {
  43. }
  44. /// Return the MCSymbol for this basic block.
  45. MCSymbol *MachineBasicBlock::getSymbol() const {
  46. if (!CachedMCSymbol) {
  47. const MachineFunction *MF = getParent();
  48. MCContext &Ctx = MF->getContext();
  49. const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
  50. assert(getNumber() >= 0 && "cannot get label for unreachable MBB");
  51. CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
  52. Twine(MF->getFunctionNumber()) +
  53. "_" + Twine(getNumber()));
  54. }
  55. return CachedMCSymbol;
  56. }
  57. raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
  58. MBB.print(OS);
  59. return OS;
  60. }
  61. /// When an MBB is added to an MF, we need to update the parent pointer of the
  62. /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
  63. /// operand list for registers.
  64. ///
  65. /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
  66. /// gets the next available unique MBB number. If it is removed from a
  67. /// MachineFunction, it goes back to being #-1.
  68. void ilist_callback_traits<MachineBasicBlock>::addNodeToList(
  69. MachineBasicBlock *N) {
  70. MachineFunction &MF = *N->getParent();
  71. N->Number = MF.addToMBBNumbering(N);
  72. // Make sure the instructions have their operands in the reginfo lists.
  73. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  74. for (MachineBasicBlock::instr_iterator
  75. I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
  76. I->AddRegOperandsToUseLists(RegInfo);
  77. }
  78. void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList(
  79. MachineBasicBlock *N) {
  80. N->getParent()->removeFromMBBNumbering(N->Number);
  81. N->Number = -1;
  82. }
  83. /// When we add an instruction to a basic block list, we update its parent
  84. /// pointer and add its operands from reg use/def lists if appropriate.
  85. void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
  86. assert(!N->getParent() && "machine instruction already in a basic block");
  87. N->setParent(Parent);
  88. // Add the instruction's register operands to their corresponding
  89. // use/def lists.
  90. MachineFunction *MF = Parent->getParent();
  91. N->AddRegOperandsToUseLists(MF->getRegInfo());
  92. }
  93. /// When we remove an instruction from a basic block list, we update its parent
  94. /// pointer and remove its operands from reg use/def lists if appropriate.
  95. void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
  96. assert(N->getParent() && "machine instruction not in a basic block");
  97. // Remove from the use/def lists.
  98. if (MachineFunction *MF = N->getParent()->getParent())
  99. N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
  100. N->setParent(nullptr);
  101. }
  102. /// When moving a range of instructions from one MBB list to another, we need to
  103. /// update the parent pointers and the use/def lists.
  104. void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList,
  105. instr_iterator First,
  106. instr_iterator Last) {
  107. assert(Parent->getParent() == FromList.Parent->getParent() &&
  108. "MachineInstr parent mismatch!");
  109. assert(this != &FromList && "Called without a real transfer...");
  110. assert(Parent != FromList.Parent && "Two lists have the same parent?");
  111. // If splicing between two blocks within the same function, just update the
  112. // parent pointers.
  113. for (; First != Last; ++First)
  114. First->setParent(Parent);
  115. }
  116. void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) {
  117. assert(!MI->getParent() && "MI is still in a block!");
  118. Parent->getParent()->DeleteMachineInstr(MI);
  119. }
  120. MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
  121. instr_iterator I = instr_begin(), E = instr_end();
  122. while (I != E && I->isPHI())
  123. ++I;
  124. assert((I == E || !I->isInsideBundle()) &&
  125. "First non-phi MI cannot be inside a bundle!");
  126. return I;
  127. }
  128. MachineBasicBlock::iterator
  129. MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
  130. iterator E = end();
  131. while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
  132. ++I;
  133. // FIXME: This needs to change if we wish to bundle labels / dbg_values
  134. // inside the bundle.
  135. assert((I == E || !I->isInsideBundle()) &&
  136. "First non-phi / non-label instruction is inside a bundle!");
  137. return I;
  138. }
  139. MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
  140. iterator B = begin(), E = end(), I = E;
  141. while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
  142. ; /*noop */
  143. while (I != E && !I->isTerminator())
  144. ++I;
  145. return I;
  146. }
  147. MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
  148. instr_iterator B = instr_begin(), E = instr_end(), I = E;
  149. while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
  150. ; /*noop */
  151. while (I != E && !I->isTerminator())
  152. ++I;
  153. return I;
  154. }
  155. MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
  156. // Skip over begin-of-block dbg_value instructions.
  157. iterator I = begin(), E = end();
  158. while (I != E && I->isDebugValue())
  159. ++I;
  160. return I;
  161. }
  162. MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
  163. // Skip over end-of-block dbg_value instructions.
  164. instr_iterator B = instr_begin(), I = instr_end();
  165. while (I != B) {
  166. --I;
  167. // Return instruction that starts a bundle.
  168. if (I->isDebugValue() || I->isInsideBundle())
  169. continue;
  170. return I;
  171. }
  172. // The block is all debug values.
  173. return end();
  174. }
  175. bool MachineBasicBlock::hasEHPadSuccessor() const {
  176. for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
  177. if ((*I)->isEHPad())
  178. return true;
  179. return false;
  180. }
  181. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  182. LLVM_DUMP_METHOD void MachineBasicBlock::dump() const {
  183. print(dbgs());
  184. }
  185. #endif
  186. StringRef MachineBasicBlock::getName() const {
  187. if (const BasicBlock *LBB = getBasicBlock())
  188. return LBB->getName();
  189. else
  190. return "(null)";
  191. }
  192. /// Return a hopefully unique identifier for this block.
  193. std::string MachineBasicBlock::getFullName() const {
  194. std::string Name;
  195. if (getParent())
  196. Name = (getParent()->getName() + ":").str();
  197. if (getBasicBlock())
  198. Name += getBasicBlock()->getName();
  199. else
  200. Name += ("BB" + Twine(getNumber())).str();
  201. return Name;
  202. }
  203. void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes)
  204. const {
  205. const MachineFunction *MF = getParent();
  206. if (!MF) {
  207. OS << "Can't print out MachineBasicBlock because parent MachineFunction"
  208. << " is null\n";
  209. return;
  210. }
  211. const Function *F = MF->getFunction();
  212. const Module *M = F ? F->getParent() : nullptr;
  213. ModuleSlotTracker MST(M);
  214. print(OS, MST, Indexes);
  215. }
  216. void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
  217. const SlotIndexes *Indexes) const {
  218. const MachineFunction *MF = getParent();
  219. if (!MF) {
  220. OS << "Can't print out MachineBasicBlock because parent MachineFunction"
  221. << " is null\n";
  222. return;
  223. }
  224. if (Indexes)
  225. OS << Indexes->getMBBStartIdx(this) << '\t';
  226. OS << "BB#" << getNumber() << ": ";
  227. const char *Comma = "";
  228. if (const BasicBlock *LBB = getBasicBlock()) {
  229. OS << Comma << "derived from LLVM BB ";
  230. LBB->printAsOperand(OS, /*PrintType=*/false, MST);
  231. Comma = ", ";
  232. }
  233. if (isEHPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
  234. if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
  235. if (Alignment)
  236. OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
  237. << " bytes)";
  238. OS << '\n';
  239. const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
  240. if (!livein_empty()) {
  241. if (Indexes) OS << '\t';
  242. OS << " Live Ins:";
  243. for (const auto &LI : make_range(livein_begin(), livein_end())) {
  244. OS << ' ' << PrintReg(LI.PhysReg, TRI);
  245. if (LI.LaneMask != ~0u)
  246. OS << ':' << PrintLaneMask(LI.LaneMask);
  247. }
  248. OS << '\n';
  249. }
  250. // Print the preds of this block according to the CFG.
  251. if (!pred_empty()) {
  252. if (Indexes) OS << '\t';
  253. OS << " Predecessors according to CFG:";
  254. for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
  255. OS << " BB#" << (*PI)->getNumber();
  256. OS << '\n';
  257. }
  258. for (auto &I : instrs()) {
  259. if (Indexes) {
  260. if (Indexes->hasIndex(I))
  261. OS << Indexes->getInstructionIndex(I);
  262. OS << '\t';
  263. }
  264. OS << '\t';
  265. if (I.isInsideBundle())
  266. OS << " * ";
  267. I.print(OS, MST);
  268. }
  269. // Print the successors of this block according to the CFG.
  270. if (!succ_empty()) {
  271. if (Indexes) OS << '\t';
  272. OS << " Successors according to CFG:";
  273. for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
  274. OS << " BB#" << (*SI)->getNumber();
  275. if (!Probs.empty())
  276. OS << '(' << *getProbabilityIterator(SI) << ')';
  277. }
  278. OS << '\n';
  279. }
  280. }
  281. void MachineBasicBlock::printAsOperand(raw_ostream &OS,
  282. bool /*PrintType*/) const {
  283. OS << "BB#" << getNumber();
  284. }
  285. void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
  286. LiveInVector::iterator I = find_if(
  287. LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
  288. if (I == LiveIns.end())
  289. return;
  290. I->LaneMask &= ~LaneMask;
  291. if (I->LaneMask == 0)
  292. LiveIns.erase(I);
  293. }
  294. bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
  295. livein_iterator I = find_if(
  296. LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
  297. return I != livein_end() && (I->LaneMask & LaneMask) != 0;
  298. }
  299. void MachineBasicBlock::sortUniqueLiveIns() {
  300. std::sort(LiveIns.begin(), LiveIns.end(),
  301. [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
  302. return LI0.PhysReg < LI1.PhysReg;
  303. });
  304. // Liveins are sorted by physreg now we can merge their lanemasks.
  305. LiveInVector::const_iterator I = LiveIns.begin();
  306. LiveInVector::const_iterator J;
  307. LiveInVector::iterator Out = LiveIns.begin();
  308. for (; I != LiveIns.end(); ++Out, I = J) {
  309. unsigned PhysReg = I->PhysReg;
  310. LaneBitmask LaneMask = I->LaneMask;
  311. for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
  312. LaneMask |= J->LaneMask;
  313. Out->PhysReg = PhysReg;
  314. Out->LaneMask = LaneMask;
  315. }
  316. LiveIns.erase(Out, LiveIns.end());
  317. }
  318. unsigned
  319. MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
  320. assert(getParent() && "MBB must be inserted in function");
  321. assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
  322. assert(RC && "Register class is required");
  323. assert((isEHPad() || this == &getParent()->front()) &&
  324. "Only the entry block and landing pads can have physreg live ins");
  325. bool LiveIn = isLiveIn(PhysReg);
  326. iterator I = SkipPHIsAndLabels(begin()), E = end();
  327. MachineRegisterInfo &MRI = getParent()->getRegInfo();
  328. const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
  329. // Look for an existing copy.
  330. if (LiveIn)
  331. for (;I != E && I->isCopy(); ++I)
  332. if (I->getOperand(1).getReg() == PhysReg) {
  333. unsigned VirtReg = I->getOperand(0).getReg();
  334. if (!MRI.constrainRegClass(VirtReg, RC))
  335. llvm_unreachable("Incompatible live-in register class.");
  336. return VirtReg;
  337. }
  338. // No luck, create a virtual register.
  339. unsigned VirtReg = MRI.createVirtualRegister(RC);
  340. BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
  341. .addReg(PhysReg, RegState::Kill);
  342. if (!LiveIn)
  343. addLiveIn(PhysReg);
  344. return VirtReg;
  345. }
  346. void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
  347. getParent()->splice(NewAfter->getIterator(), getIterator());
  348. }
  349. void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
  350. getParent()->splice(++NewBefore->getIterator(), getIterator());
  351. }
  352. void MachineBasicBlock::updateTerminator() {
  353. const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
  354. // A block with no successors has no concerns with fall-through edges.
  355. if (this->succ_empty())
  356. return;
  357. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  358. SmallVector<MachineOperand, 4> Cond;
  359. DebugLoc DL; // FIXME: this is nowhere
  360. bool B = TII->analyzeBranch(*this, TBB, FBB, Cond);
  361. (void) B;
  362. assert(!B && "UpdateTerminators requires analyzable predecessors!");
  363. if (Cond.empty()) {
  364. if (TBB) {
  365. // The block has an unconditional branch. If its successor is now its
  366. // layout successor, delete the branch.
  367. if (isLayoutSuccessor(TBB))
  368. TII->RemoveBranch(*this);
  369. } else {
  370. // The block has an unconditional fallthrough. If its successor is not its
  371. // layout successor, insert a branch. First we have to locate the only
  372. // non-landing-pad successor, as that is the fallthrough block.
  373. for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
  374. if ((*SI)->isEHPad())
  375. continue;
  376. assert(!TBB && "Found more than one non-landing-pad successor!");
  377. TBB = *SI;
  378. }
  379. // If there is no non-landing-pad successor, the block has no fall-through
  380. // edges to be concerned with.
  381. if (!TBB)
  382. return;
  383. // Finally update the unconditional successor to be reached via a branch
  384. // if it would not be reached by fallthrough.
  385. if (!isLayoutSuccessor(TBB))
  386. TII->insertBranch(*this, TBB, nullptr, Cond, DL);
  387. }
  388. return;
  389. }
  390. if (FBB) {
  391. // The block has a non-fallthrough conditional branch. If one of its
  392. // successors is its layout successor, rewrite it to a fallthrough
  393. // conditional branch.
  394. if (isLayoutSuccessor(TBB)) {
  395. if (TII->ReverseBranchCondition(Cond))
  396. return;
  397. TII->RemoveBranch(*this);
  398. TII->insertBranch(*this, FBB, nullptr, Cond, DL);
  399. } else if (isLayoutSuccessor(FBB)) {
  400. TII->RemoveBranch(*this);
  401. TII->insertBranch(*this, TBB, nullptr, Cond, DL);
  402. }
  403. return;
  404. }
  405. // Walk through the successors and find the successor which is not a landing
  406. // pad and is not the conditional branch destination (in TBB) as the
  407. // fallthrough successor.
  408. MachineBasicBlock *FallthroughBB = nullptr;
  409. for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
  410. if ((*SI)->isEHPad() || *SI == TBB)
  411. continue;
  412. assert(!FallthroughBB && "Found more than one fallthrough successor.");
  413. FallthroughBB = *SI;
  414. }
  415. if (!FallthroughBB) {
  416. if (canFallThrough()) {
  417. // We fallthrough to the same basic block as the conditional jump targets.
  418. // Remove the conditional jump, leaving unconditional fallthrough.
  419. // FIXME: This does not seem like a reasonable pattern to support, but it
  420. // has been seen in the wild coming out of degenerate ARM test cases.
  421. TII->RemoveBranch(*this);
  422. // Finally update the unconditional successor to be reached via a branch if
  423. // it would not be reached by fallthrough.
  424. if (!isLayoutSuccessor(TBB))
  425. TII->insertBranch(*this, TBB, nullptr, Cond, DL);
  426. return;
  427. }
  428. // We enter here iff exactly one successor is TBB which cannot fallthrough
  429. // and the rest successors if any are EHPads. In this case, we need to
  430. // change the conditional branch into unconditional branch.
  431. TII->RemoveBranch(*this);
  432. Cond.clear();
  433. TII->insertBranch(*this, TBB, nullptr, Cond, DL);
  434. return;
  435. }
  436. // The block has a fallthrough conditional branch.
  437. if (isLayoutSuccessor(TBB)) {
  438. if (TII->ReverseBranchCondition(Cond)) {
  439. // We can't reverse the condition, add an unconditional branch.
  440. Cond.clear();
  441. TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
  442. return;
  443. }
  444. TII->RemoveBranch(*this);
  445. TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL);
  446. } else if (!isLayoutSuccessor(FallthroughBB)) {
  447. TII->RemoveBranch(*this);
  448. TII->insertBranch(*this, TBB, FallthroughBB, Cond, DL);
  449. }
  450. }
  451. void MachineBasicBlock::validateSuccProbs() const {
  452. #ifndef NDEBUG
  453. int64_t Sum = 0;
  454. for (auto Prob : Probs)
  455. Sum += Prob.getNumerator();
  456. // Due to precision issue, we assume that the sum of probabilities is one if
  457. // the difference between the sum of their numerators and the denominator is
  458. // no greater than the number of successors.
  459. assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <=
  460. Probs.size() &&
  461. "The sum of successors's probabilities exceeds one.");
  462. #endif // NDEBUG
  463. }
  464. void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
  465. BranchProbability Prob) {
  466. // Probability list is either empty (if successor list isn't empty, this means
  467. // disabled optimization) or has the same size as successor list.
  468. if (!(Probs.empty() && !Successors.empty()))
  469. Probs.push_back(Prob);
  470. Successors.push_back(Succ);
  471. Succ->addPredecessor(this);
  472. }
  473. void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
  474. // We need to make sure probability list is either empty or has the same size
  475. // of successor list. When this function is called, we can safely delete all
  476. // probability in the list.
  477. Probs.clear();
  478. Successors.push_back(Succ);
  479. Succ->addPredecessor(this);
  480. }
  481. void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ,
  482. bool NormalizeSuccProbs) {
  483. succ_iterator I = find(Successors, Succ);
  484. removeSuccessor(I, NormalizeSuccProbs);
  485. }
  486. MachineBasicBlock::succ_iterator
  487. MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) {
  488. assert(I != Successors.end() && "Not a current successor!");
  489. // If probability list is empty it means we don't use it (disabled
  490. // optimization).
  491. if (!Probs.empty()) {
  492. probability_iterator WI = getProbabilityIterator(I);
  493. Probs.erase(WI);
  494. if (NormalizeSuccProbs)
  495. normalizeSuccProbs();
  496. }
  497. (*I)->removePredecessor(this);
  498. return Successors.erase(I);
  499. }
  500. void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
  501. MachineBasicBlock *New) {
  502. if (Old == New)
  503. return;
  504. succ_iterator E = succ_end();
  505. succ_iterator NewI = E;
  506. succ_iterator OldI = E;
  507. for (succ_iterator I = succ_begin(); I != E; ++I) {
  508. if (*I == Old) {
  509. OldI = I;
  510. if (NewI != E)
  511. break;
  512. }
  513. if (*I == New) {
  514. NewI = I;
  515. if (OldI != E)
  516. break;
  517. }
  518. }
  519. assert(OldI != E && "Old is not a successor of this block");
  520. // If New isn't already a successor, let it take Old's place.
  521. if (NewI == E) {
  522. Old->removePredecessor(this);
  523. New->addPredecessor(this);
  524. *OldI = New;
  525. return;
  526. }
  527. // New is already a successor.
  528. // Update its probability instead of adding a duplicate edge.
  529. if (!Probs.empty()) {
  530. auto ProbIter = getProbabilityIterator(NewI);
  531. if (!ProbIter->isUnknown())
  532. *ProbIter += *getProbabilityIterator(OldI);
  533. }
  534. removeSuccessor(OldI);
  535. }
  536. void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
  537. Predecessors.push_back(Pred);
  538. }
  539. void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
  540. pred_iterator I = find(Predecessors, Pred);
  541. assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
  542. Predecessors.erase(I);
  543. }
  544. void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
  545. if (this == FromMBB)
  546. return;
  547. while (!FromMBB->succ_empty()) {
  548. MachineBasicBlock *Succ = *FromMBB->succ_begin();
  549. // If probability list is empty it means we don't use it (disabled optimization).
  550. if (!FromMBB->Probs.empty()) {
  551. auto Prob = *FromMBB->Probs.begin();
  552. addSuccessor(Succ, Prob);
  553. } else
  554. addSuccessorWithoutProb(Succ);
  555. FromMBB->removeSuccessor(Succ);
  556. }
  557. }
  558. void
  559. MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
  560. if (this == FromMBB)
  561. return;
  562. while (!FromMBB->succ_empty()) {
  563. MachineBasicBlock *Succ = *FromMBB->succ_begin();
  564. if (!FromMBB->Probs.empty()) {
  565. auto Prob = *FromMBB->Probs.begin();
  566. addSuccessor(Succ, Prob);
  567. } else
  568. addSuccessorWithoutProb(Succ);
  569. FromMBB->removeSuccessor(Succ);
  570. // Fix up any PHI nodes in the successor.
  571. for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
  572. ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
  573. for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
  574. MachineOperand &MO = MI->getOperand(i);
  575. if (MO.getMBB() == FromMBB)
  576. MO.setMBB(this);
  577. }
  578. }
  579. normalizeSuccProbs();
  580. }
  581. bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
  582. return is_contained(predecessors(), MBB);
  583. }
  584. bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
  585. return is_contained(successors(), MBB);
  586. }
  587. bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
  588. MachineFunction::const_iterator I(this);
  589. return std::next(I) == MachineFunction::const_iterator(MBB);
  590. }
  591. bool MachineBasicBlock::canFallThrough() {
  592. MachineFunction::iterator Fallthrough = getIterator();
  593. ++Fallthrough;
  594. // If FallthroughBlock is off the end of the function, it can't fall through.
  595. if (Fallthrough == getParent()->end())
  596. return false;
  597. // If FallthroughBlock isn't a successor, no fallthrough is possible.
  598. if (!isSuccessor(&*Fallthrough))
  599. return false;
  600. // Analyze the branches, if any, at the end of the block.
  601. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  602. SmallVector<MachineOperand, 4> Cond;
  603. const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
  604. if (TII->analyzeBranch(*this, TBB, FBB, Cond)) {
  605. // If we couldn't analyze the branch, examine the last instruction.
  606. // If the block doesn't end in a known control barrier, assume fallthrough
  607. // is possible. The isPredicated check is needed because this code can be
  608. // called during IfConversion, where an instruction which is normally a
  609. // Barrier is predicated and thus no longer an actual control barrier.
  610. return empty() || !back().isBarrier() || TII->isPredicated(back());
  611. }
  612. // If there is no branch, control always falls through.
  613. if (!TBB) return true;
  614. // If there is some explicit branch to the fallthrough block, it can obviously
  615. // reach, even though the branch should get folded to fall through implicitly.
  616. if (MachineFunction::iterator(TBB) == Fallthrough ||
  617. MachineFunction::iterator(FBB) == Fallthrough)
  618. return true;
  619. // If it's an unconditional branch to some block not the fall through, it
  620. // doesn't fall through.
  621. if (Cond.empty()) return false;
  622. // Otherwise, if it is conditional and has no explicit false block, it falls
  623. // through.
  624. return FBB == nullptr;
  625. }
  626. MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ,
  627. Pass &P) {
  628. if (!canSplitCriticalEdge(Succ))
  629. return nullptr;
  630. MachineFunction *MF = getParent();
  631. DebugLoc DL; // FIXME: this is nowhere
  632. MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
  633. MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
  634. DEBUG(dbgs() << "Splitting critical edge:"
  635. " BB#" << getNumber()
  636. << " -- BB#" << NMBB->getNumber()
  637. << " -- BB#" << Succ->getNumber() << '\n');
  638. LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>();
  639. SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>();
  640. if (LIS)
  641. LIS->insertMBBInMaps(NMBB);
  642. else if (Indexes)
  643. Indexes->insertMBBInMaps(NMBB);
  644. // On some targets like Mips, branches may kill virtual registers. Make sure
  645. // that LiveVariables is properly updated after updateTerminator replaces the
  646. // terminators.
  647. LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>();
  648. // Collect a list of virtual registers killed by the terminators.
  649. SmallVector<unsigned, 4> KilledRegs;
  650. if (LV)
  651. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  652. I != E; ++I) {
  653. MachineInstr *MI = &*I;
  654. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  655. OE = MI->operands_end(); OI != OE; ++OI) {
  656. if (!OI->isReg() || OI->getReg() == 0 ||
  657. !OI->isUse() || !OI->isKill() || OI->isUndef())
  658. continue;
  659. unsigned Reg = OI->getReg();
  660. if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
  661. LV->getVarInfo(Reg).removeKill(*MI)) {
  662. KilledRegs.push_back(Reg);
  663. DEBUG(dbgs() << "Removing terminator kill: " << *MI);
  664. OI->setIsKill(false);
  665. }
  666. }
  667. }
  668. SmallVector<unsigned, 4> UsedRegs;
  669. if (LIS) {
  670. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  671. I != E; ++I) {
  672. MachineInstr *MI = &*I;
  673. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  674. OE = MI->operands_end(); OI != OE; ++OI) {
  675. if (!OI->isReg() || OI->getReg() == 0)
  676. continue;
  677. unsigned Reg = OI->getReg();
  678. if (!is_contained(UsedRegs, Reg))
  679. UsedRegs.push_back(Reg);
  680. }
  681. }
  682. }
  683. ReplaceUsesOfBlockWith(Succ, NMBB);
  684. // If updateTerminator() removes instructions, we need to remove them from
  685. // SlotIndexes.
  686. SmallVector<MachineInstr*, 4> Terminators;
  687. if (Indexes) {
  688. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  689. I != E; ++I)
  690. Terminators.push_back(&*I);
  691. }
  692. updateTerminator();
  693. if (Indexes) {
  694. SmallVector<MachineInstr*, 4> NewTerminators;
  695. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  696. I != E; ++I)
  697. NewTerminators.push_back(&*I);
  698. for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
  699. E = Terminators.end(); I != E; ++I) {
  700. if (!is_contained(NewTerminators, *I))
  701. Indexes->removeMachineInstrFromMaps(**I);
  702. }
  703. }
  704. // Insert unconditional "jump Succ" instruction in NMBB if necessary.
  705. NMBB->addSuccessor(Succ);
  706. if (!NMBB->isLayoutSuccessor(Succ)) {
  707. SmallVector<MachineOperand, 4> Cond;
  708. const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
  709. TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL);
  710. if (Indexes) {
  711. for (MachineInstr &MI : NMBB->instrs()) {
  712. // Some instructions may have been moved to NMBB by updateTerminator(),
  713. // so we first remove any instruction that already has an index.
  714. if (Indexes->hasIndex(MI))
  715. Indexes->removeMachineInstrFromMaps(MI);
  716. Indexes->insertMachineInstrInMaps(MI);
  717. }
  718. }
  719. }
  720. // Fix PHI nodes in Succ so they refer to NMBB instead of this
  721. for (MachineBasicBlock::instr_iterator
  722. i = Succ->instr_begin(),e = Succ->instr_end();
  723. i != e && i->isPHI(); ++i)
  724. for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
  725. if (i->getOperand(ni+1).getMBB() == this)
  726. i->getOperand(ni+1).setMBB(NMBB);
  727. // Inherit live-ins from the successor
  728. for (const auto &LI : Succ->liveins())
  729. NMBB->addLiveIn(LI);
  730. // Update LiveVariables.
  731. const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
  732. if (LV) {
  733. // Restore kills of virtual registers that were killed by the terminators.
  734. while (!KilledRegs.empty()) {
  735. unsigned Reg = KilledRegs.pop_back_val();
  736. for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
  737. if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
  738. continue;
  739. if (TargetRegisterInfo::isVirtualRegister(Reg))
  740. LV->getVarInfo(Reg).Kills.push_back(&*I);
  741. DEBUG(dbgs() << "Restored terminator kill: " << *I);
  742. break;
  743. }
  744. }
  745. // Update relevant live-through information.
  746. LV->addNewBlock(NMBB, this, Succ);
  747. }
  748. if (LIS) {
  749. // After splitting the edge and updating SlotIndexes, live intervals may be
  750. // in one of two situations, depending on whether this block was the last in
  751. // the function. If the original block was the last in the function, all
  752. // live intervals will end prior to the beginning of the new split block. If
  753. // the original block was not at the end of the function, all live intervals
  754. // will extend to the end of the new split block.
  755. bool isLastMBB =
  756. std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
  757. SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
  758. SlotIndex PrevIndex = StartIndex.getPrevSlot();
  759. SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
  760. // Find the registers used from NMBB in PHIs in Succ.
  761. SmallSet<unsigned, 8> PHISrcRegs;
  762. for (MachineBasicBlock::instr_iterator
  763. I = Succ->instr_begin(), E = Succ->instr_end();
  764. I != E && I->isPHI(); ++I) {
  765. for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
  766. if (I->getOperand(ni+1).getMBB() == NMBB) {
  767. MachineOperand &MO = I->getOperand(ni);
  768. unsigned Reg = MO.getReg();
  769. PHISrcRegs.insert(Reg);
  770. if (MO.isUndef())
  771. continue;
  772. LiveInterval &LI = LIS->getInterval(Reg);
  773. VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
  774. assert(VNI &&
  775. "PHI sources should be live out of their predecessors.");
  776. LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
  777. }
  778. }
  779. }
  780. MachineRegisterInfo *MRI = &getParent()->getRegInfo();
  781. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  782. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  783. if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
  784. continue;
  785. LiveInterval &LI = LIS->getInterval(Reg);
  786. if (!LI.liveAt(PrevIndex))
  787. continue;
  788. bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
  789. if (isLiveOut && isLastMBB) {
  790. VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
  791. assert(VNI && "LiveInterval should have VNInfo where it is live.");
  792. LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
  793. } else if (!isLiveOut && !isLastMBB) {
  794. LI.removeSegment(StartIndex, EndIndex);
  795. }
  796. }
  797. // Update all intervals for registers whose uses may have been modified by
  798. // updateTerminator().
  799. LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
  800. }
  801. if (MachineDominatorTree *MDT =
  802. P.getAnalysisIfAvailable<MachineDominatorTree>())
  803. MDT->recordSplitCriticalEdge(this, Succ, NMBB);
  804. if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>())
  805. if (MachineLoop *TIL = MLI->getLoopFor(this)) {
  806. // If one or the other blocks were not in a loop, the new block is not
  807. // either, and thus LI doesn't need to be updated.
  808. if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
  809. if (TIL == DestLoop) {
  810. // Both in the same loop, the NMBB joins loop.
  811. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  812. } else if (TIL->contains(DestLoop)) {
  813. // Edge from an outer loop to an inner loop. Add to the outer loop.
  814. TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
  815. } else if (DestLoop->contains(TIL)) {
  816. // Edge from an inner loop to an outer loop. Add to the outer loop.
  817. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  818. } else {
  819. // Edge from two loops with no containment relation. Because these
  820. // are natural loops, we know that the destination block must be the
  821. // header of its loop (adding a branch into a loop elsewhere would
  822. // create an irreducible loop).
  823. assert(DestLoop->getHeader() == Succ &&
  824. "Should not create irreducible loops!");
  825. if (MachineLoop *P = DestLoop->getParentLoop())
  826. P->addBasicBlockToLoop(NMBB, MLI->getBase());
  827. }
  828. }
  829. }
  830. return NMBB;
  831. }
  832. bool MachineBasicBlock::canSplitCriticalEdge(
  833. const MachineBasicBlock *Succ) const {
  834. // Splitting the critical edge to a landing pad block is non-trivial. Don't do
  835. // it in this generic function.
  836. if (Succ->isEHPad())
  837. return false;
  838. const MachineFunction *MF = getParent();
  839. // Performance might be harmed on HW that implements branching using exec mask
  840. // where both sides of the branches are always executed.
  841. if (MF->getTarget().requiresStructuredCFG())
  842. return false;
  843. // We may need to update this's terminator, but we can't do that if
  844. // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
  845. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  846. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  847. SmallVector<MachineOperand, 4> Cond;
  848. // AnalyzeBanch should modify this, since we did not allow modification.
  849. if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond,
  850. /*AllowModify*/ false))
  851. return false;
  852. // Avoid bugpoint weirdness: A block may end with a conditional branch but
  853. // jumps to the same MBB is either case. We have duplicate CFG edges in that
  854. // case that we can't handle. Since this never happens in properly optimized
  855. // code, just skip those edges.
  856. if (TBB && TBB == FBB) {
  857. DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
  858. << getNumber() << '\n');
  859. return false;
  860. }
  861. return true;
  862. }
  863. /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
  864. /// neighboring instructions so the bundle won't be broken by removing MI.
  865. static void unbundleSingleMI(MachineInstr *MI) {
  866. // Removing the first instruction in a bundle.
  867. if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
  868. MI->unbundleFromSucc();
  869. // Removing the last instruction in a bundle.
  870. if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
  871. MI->unbundleFromPred();
  872. // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
  873. // are already fine.
  874. }
  875. MachineBasicBlock::instr_iterator
  876. MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
  877. unbundleSingleMI(&*I);
  878. return Insts.erase(I);
  879. }
  880. MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
  881. unbundleSingleMI(MI);
  882. MI->clearFlag(MachineInstr::BundledPred);
  883. MI->clearFlag(MachineInstr::BundledSucc);
  884. return Insts.remove(MI);
  885. }
  886. MachineBasicBlock::instr_iterator
  887. MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
  888. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  889. "Cannot insert instruction with bundle flags");
  890. // Set the bundle flags when inserting inside a bundle.
  891. if (I != instr_end() && I->isBundledWithPred()) {
  892. MI->setFlag(MachineInstr::BundledPred);
  893. MI->setFlag(MachineInstr::BundledSucc);
  894. }
  895. return Insts.insert(I, MI);
  896. }
  897. /// This method unlinks 'this' from the containing function, and returns it, but
  898. /// does not delete it.
  899. MachineBasicBlock *MachineBasicBlock::removeFromParent() {
  900. assert(getParent() && "Not embedded in a function!");
  901. getParent()->remove(this);
  902. return this;
  903. }
  904. /// This method unlinks 'this' from the containing function, and deletes it.
  905. void MachineBasicBlock::eraseFromParent() {
  906. assert(getParent() && "Not embedded in a function!");
  907. getParent()->erase(this);
  908. }
  909. /// Given a machine basic block that branched to 'Old', change the code and CFG
  910. /// so that it branches to 'New' instead.
  911. void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
  912. MachineBasicBlock *New) {
  913. assert(Old != New && "Cannot replace self with self!");
  914. MachineBasicBlock::instr_iterator I = instr_end();
  915. while (I != instr_begin()) {
  916. --I;
  917. if (!I->isTerminator()) break;
  918. // Scan the operands of this machine instruction, replacing any uses of Old
  919. // with New.
  920. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  921. if (I->getOperand(i).isMBB() &&
  922. I->getOperand(i).getMBB() == Old)
  923. I->getOperand(i).setMBB(New);
  924. }
  925. // Update the successor information.
  926. replaceSuccessor(Old, New);
  927. }
  928. /// Various pieces of code can cause excess edges in the CFG to be inserted. If
  929. /// we have proven that MBB can only branch to DestA and DestB, remove any other
  930. /// MBB successors from the CFG. DestA and DestB can be null.
  931. ///
  932. /// Besides DestA and DestB, retain other edges leading to LandingPads
  933. /// (currently there can be only one; we don't check or require that here).
  934. /// Note it is possible that DestA and/or DestB are LandingPads.
  935. bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
  936. MachineBasicBlock *DestB,
  937. bool IsCond) {
  938. // The values of DestA and DestB frequently come from a call to the
  939. // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
  940. // values from there.
  941. //
  942. // 1. If both DestA and DestB are null, then the block ends with no branches
  943. // (it falls through to its successor).
  944. // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
  945. // with only an unconditional branch.
  946. // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
  947. // with a conditional branch that falls through to a successor (DestB).
  948. // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
  949. // conditional branch followed by an unconditional branch. DestA is the
  950. // 'true' destination and DestB is the 'false' destination.
  951. bool Changed = false;
  952. MachineBasicBlock *FallThru = getNextNode();
  953. if (!DestA && !DestB) {
  954. // Block falls through to successor.
  955. DestA = FallThru;
  956. DestB = FallThru;
  957. } else if (DestA && !DestB) {
  958. if (IsCond)
  959. // Block ends in conditional jump that falls through to successor.
  960. DestB = FallThru;
  961. } else {
  962. assert(DestA && DestB && IsCond &&
  963. "CFG in a bad state. Cannot correct CFG edges");
  964. }
  965. // Remove superfluous edges. I.e., those which aren't destinations of this
  966. // basic block, duplicate edges, or landing pads.
  967. SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
  968. MachineBasicBlock::succ_iterator SI = succ_begin();
  969. while (SI != succ_end()) {
  970. const MachineBasicBlock *MBB = *SI;
  971. if (!SeenMBBs.insert(MBB).second ||
  972. (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
  973. // This is a superfluous edge, remove it.
  974. SI = removeSuccessor(SI);
  975. Changed = true;
  976. } else {
  977. ++SI;
  978. }
  979. }
  980. if (Changed)
  981. normalizeSuccProbs();
  982. return Changed;
  983. }
  984. /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
  985. /// instructions. Return UnknownLoc if there is none.
  986. DebugLoc
  987. MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
  988. DebugLoc DL;
  989. instr_iterator E = instr_end();
  990. if (MBBI == E)
  991. return DL;
  992. // Skip debug declarations, we don't want a DebugLoc from them.
  993. while (MBBI != E && MBBI->isDebugValue())
  994. MBBI++;
  995. if (MBBI != E)
  996. DL = MBBI->getDebugLoc();
  997. return DL;
  998. }
  999. /// Return probability of the edge from this block to MBB.
  1000. BranchProbability
  1001. MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
  1002. if (Probs.empty())
  1003. return BranchProbability(1, succ_size());
  1004. const auto &Prob = *getProbabilityIterator(Succ);
  1005. if (Prob.isUnknown()) {
  1006. // For unknown probabilities, collect the sum of all known ones, and evenly
  1007. // ditribute the complemental of the sum to each unknown probability.
  1008. unsigned KnownProbNum = 0;
  1009. auto Sum = BranchProbability::getZero();
  1010. for (auto &P : Probs) {
  1011. if (!P.isUnknown()) {
  1012. Sum += P;
  1013. KnownProbNum++;
  1014. }
  1015. }
  1016. return Sum.getCompl() / (Probs.size() - KnownProbNum);
  1017. } else
  1018. return Prob;
  1019. }
  1020. /// Set successor probability of a given iterator.
  1021. void MachineBasicBlock::setSuccProbability(succ_iterator I,
  1022. BranchProbability Prob) {
  1023. assert(!Prob.isUnknown());
  1024. if (Probs.empty())
  1025. return;
  1026. *getProbabilityIterator(I) = Prob;
  1027. }
  1028. /// Return probability iterator corresonding to the I successor iterator
  1029. MachineBasicBlock::const_probability_iterator
  1030. MachineBasicBlock::getProbabilityIterator(
  1031. MachineBasicBlock::const_succ_iterator I) const {
  1032. assert(Probs.size() == Successors.size() && "Async probability list!");
  1033. const size_t index = std::distance(Successors.begin(), I);
  1034. assert(index < Probs.size() && "Not a current successor!");
  1035. return Probs.begin() + index;
  1036. }
  1037. /// Return probability iterator corresonding to the I successor iterator.
  1038. MachineBasicBlock::probability_iterator
  1039. MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
  1040. assert(Probs.size() == Successors.size() && "Async probability list!");
  1041. const size_t index = std::distance(Successors.begin(), I);
  1042. assert(index < Probs.size() && "Not a current successor!");
  1043. return Probs.begin() + index;
  1044. }
  1045. /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
  1046. /// as of just before "MI".
  1047. ///
  1048. /// Search is localised to a neighborhood of
  1049. /// Neighborhood instructions before (searching for defs or kills) and N
  1050. /// instructions after (searching just for defs) MI.
  1051. MachineBasicBlock::LivenessQueryResult
  1052. MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
  1053. unsigned Reg, const_iterator Before,
  1054. unsigned Neighborhood) const {
  1055. unsigned N = Neighborhood;
  1056. // Start by searching backwards from Before, looking for kills, reads or defs.
  1057. const_iterator I(Before);
  1058. // If this is the first insn in the block, don't search backwards.
  1059. if (I != begin()) {
  1060. do {
  1061. --I;
  1062. MachineOperandIteratorBase::PhysRegInfo Info =
  1063. ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
  1064. // Defs happen after uses so they take precedence if both are present.
  1065. // Register is dead after a dead def of the full register.
  1066. if (Info.DeadDef)
  1067. return LQR_Dead;
  1068. // Register is (at least partially) live after a def.
  1069. if (Info.Defined) {
  1070. if (!Info.PartialDeadDef)
  1071. return LQR_Live;
  1072. // As soon as we saw a partial definition (dead or not),
  1073. // we cannot tell if the value is partial live without
  1074. // tracking the lanemasks. We are not going to do this,
  1075. // so fall back on the remaining of the analysis.
  1076. break;
  1077. }
  1078. // Register is dead after a full kill or clobber and no def.
  1079. if (Info.Killed || Info.Clobbered)
  1080. return LQR_Dead;
  1081. // Register must be live if we read it.
  1082. if (Info.Read)
  1083. return LQR_Live;
  1084. } while (I != begin() && --N > 0);
  1085. }
  1086. // Did we get to the start of the block?
  1087. if (I == begin()) {
  1088. // If so, the register's state is definitely defined by the live-in state.
  1089. for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); RAI.isValid();
  1090. ++RAI)
  1091. if (isLiveIn(*RAI))
  1092. return LQR_Live;
  1093. return LQR_Dead;
  1094. }
  1095. N = Neighborhood;
  1096. // Try searching forwards from Before, looking for reads or defs.
  1097. I = const_iterator(Before);
  1098. // If this is the last insn in the block, don't search forwards.
  1099. if (I != end()) {
  1100. for (++I; I != end() && N > 0; ++I, --N) {
  1101. MachineOperandIteratorBase::PhysRegInfo Info =
  1102. ConstMIOperands(*I).analyzePhysReg(Reg, TRI);
  1103. // Register is live when we read it here.
  1104. if (Info.Read)
  1105. return LQR_Live;
  1106. // Register is dead if we can fully overwrite or clobber it here.
  1107. if (Info.FullyDefined || Info.Clobbered)
  1108. return LQR_Dead;
  1109. }
  1110. }
  1111. // At this point we have no idea of the liveness of the register.
  1112. return LQR_Unknown;
  1113. }
  1114. const uint32_t *
  1115. MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
  1116. // EH funclet entry does not preserve any registers.
  1117. return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
  1118. }
  1119. const uint32_t *
  1120. MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
  1121. // If we see a return block with successors, this must be a funclet return,
  1122. // which does not preserve any registers. If there are no successors, we don't
  1123. // care what kind of return it is, putting a mask after it is a no-op.
  1124. return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;
  1125. }