MachineBasicBlock.cpp 47 KB

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