MachineBasicBlock.cpp 50 KB

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