MachineBasicBlock.cpp 51 KB

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