MachineBasicBlock.cpp 55 KB

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