MachineBasicBlock.cpp 48 KB

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