LiveRangeCalc.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. //===- LiveRangeCalc.cpp - Calculate live ranges -------------------------===//
  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. // Implementation of the LiveRangeCalc class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/LiveRangeCalc.h"
  13. #include "llvm/ADT/BitVector.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/CodeGen/LiveInterval.h"
  18. #include "llvm/CodeGen/MachineBasicBlock.h"
  19. #include "llvm/CodeGen/MachineDominators.h"
  20. #include "llvm/CodeGen/MachineFunction.h"
  21. #include "llvm/CodeGen/MachineInstr.h"
  22. #include "llvm/CodeGen/MachineOperand.h"
  23. #include "llvm/CodeGen/MachineRegisterInfo.h"
  24. #include "llvm/CodeGen/SlotIndexes.h"
  25. #include "llvm/CodeGen/TargetRegisterInfo.h"
  26. #include "llvm/MC/LaneBitmask.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include <algorithm>
  30. #include <cassert>
  31. #include <iterator>
  32. #include <tuple>
  33. #include <utility>
  34. using namespace llvm;
  35. #define DEBUG_TYPE "regalloc"
  36. // Reserve an address that indicates a value that is known to be "undef".
  37. static VNInfo UndefVNI(0xbad, SlotIndex());
  38. void LiveRangeCalc::resetLiveOutMap() {
  39. unsigned NumBlocks = MF->getNumBlockIDs();
  40. Seen.clear();
  41. Seen.resize(NumBlocks);
  42. EntryInfos.clear();
  43. Map.resize(NumBlocks);
  44. }
  45. void LiveRangeCalc::reset(const MachineFunction *mf,
  46. SlotIndexes *SI,
  47. MachineDominatorTree *MDT,
  48. VNInfo::Allocator *VNIA) {
  49. MF = mf;
  50. MRI = &MF->getRegInfo();
  51. Indexes = SI;
  52. DomTree = MDT;
  53. Alloc = VNIA;
  54. resetLiveOutMap();
  55. LiveIn.clear();
  56. }
  57. void LiveRangeCalc::updateFromLiveIns() {
  58. LiveRangeUpdater Updater;
  59. for (const LiveInBlock &I : LiveIn) {
  60. if (!I.DomNode)
  61. continue;
  62. MachineBasicBlock *MBB = I.DomNode->getBlock();
  63. assert(I.Value && "No live-in value found");
  64. SlotIndex Start, End;
  65. std::tie(Start, End) = Indexes->getMBBRange(MBB);
  66. if (I.Kill.isValid())
  67. // Value is killed inside this block.
  68. End = I.Kill;
  69. else {
  70. // The value is live-through, update LiveOut as well.
  71. // Defer the Domtree lookup until it is needed.
  72. assert(Seen.test(MBB->getNumber()));
  73. Map[MBB] = LiveOutPair(I.Value, nullptr);
  74. }
  75. Updater.setDest(&I.LR);
  76. Updater.add(Start, End, I.Value);
  77. }
  78. LiveIn.clear();
  79. }
  80. void LiveRangeCalc::extend(LiveRange &LR, SlotIndex Use, unsigned PhysReg,
  81. ArrayRef<SlotIndex> Undefs) {
  82. assert(Use.isValid() && "Invalid SlotIndex");
  83. assert(Indexes && "Missing SlotIndexes");
  84. assert(DomTree && "Missing dominator tree");
  85. MachineBasicBlock *UseMBB = Indexes->getMBBFromIndex(Use.getPrevSlot());
  86. assert(UseMBB && "No MBB at Use");
  87. // Is there a def in the same MBB we can extend?
  88. auto EP = LR.extendInBlock(Undefs, Indexes->getMBBStartIdx(UseMBB), Use);
  89. if (EP.first != nullptr || EP.second)
  90. return;
  91. // Find the single reaching def, or determine if Use is jointly dominated by
  92. // multiple values, and we may need to create even more phi-defs to preserve
  93. // VNInfo SSA form. Perform a search for all predecessor blocks where we
  94. // know the dominating VNInfo.
  95. if (findReachingDefs(LR, *UseMBB, Use, PhysReg, Undefs))
  96. return;
  97. // When there were multiple different values, we may need new PHIs.
  98. calculateValues();
  99. }
  100. // This function is called by a client after using the low-level API to add
  101. // live-out and live-in blocks. The unique value optimization is not
  102. // available, SplitEditor::transferValues handles that case directly anyway.
  103. void LiveRangeCalc::calculateValues() {
  104. assert(Indexes && "Missing SlotIndexes");
  105. assert(DomTree && "Missing dominator tree");
  106. updateSSA();
  107. updateFromLiveIns();
  108. }
  109. bool LiveRangeCalc::isDefOnEntry(LiveRange &LR, ArrayRef<SlotIndex> Undefs,
  110. MachineBasicBlock &MBB, BitVector &DefOnEntry,
  111. BitVector &UndefOnEntry) {
  112. unsigned BN = MBB.getNumber();
  113. if (DefOnEntry[BN])
  114. return true;
  115. if (UndefOnEntry[BN])
  116. return false;
  117. auto MarkDefined = [BN, &DefOnEntry](MachineBasicBlock &B) -> bool {
  118. for (MachineBasicBlock *S : B.successors())
  119. DefOnEntry[S->getNumber()] = true;
  120. DefOnEntry[BN] = true;
  121. return true;
  122. };
  123. SetVector<unsigned> WorkList;
  124. // Checking if the entry of MBB is reached by some def: add all predecessors
  125. // that are potentially defined-on-exit to the work list.
  126. for (MachineBasicBlock *P : MBB.predecessors())
  127. WorkList.insert(P->getNumber());
  128. for (unsigned i = 0; i != WorkList.size(); ++i) {
  129. // Determine if the exit from the block is reached by some def.
  130. unsigned N = WorkList[i];
  131. MachineBasicBlock &B = *MF->getBlockNumbered(N);
  132. if (Seen[N]) {
  133. const LiveOutPair &LOB = Map[&B];
  134. if (LOB.first != nullptr && LOB.first != &UndefVNI)
  135. return MarkDefined(B);
  136. }
  137. SlotIndex Begin, End;
  138. std::tie(Begin, End) = Indexes->getMBBRange(&B);
  139. // Treat End as not belonging to B.
  140. // If LR has a segment S that starts at the next block, i.e. [End, ...),
  141. // std::upper_bound will return the segment following S. Instead,
  142. // S should be treated as the first segment that does not overlap B.
  143. LiveRange::iterator UB = upper_bound(LR, End.getPrevSlot());
  144. if (UB != LR.begin()) {
  145. LiveRange::Segment &Seg = *std::prev(UB);
  146. if (Seg.end > Begin) {
  147. // There is a segment that overlaps B. If the range is not explicitly
  148. // undefined between the end of the segment and the end of the block,
  149. // treat the block as defined on exit. If it is, go to the next block
  150. // on the work list.
  151. if (LR.isUndefIn(Undefs, Seg.end, End))
  152. continue;
  153. return MarkDefined(B);
  154. }
  155. }
  156. // No segment overlaps with this block. If this block is not defined on
  157. // entry, or it undefines the range, do not process its predecessors.
  158. if (UndefOnEntry[N] || LR.isUndefIn(Undefs, Begin, End)) {
  159. UndefOnEntry[N] = true;
  160. continue;
  161. }
  162. if (DefOnEntry[N])
  163. return MarkDefined(B);
  164. // Still don't know: add all predecessors to the work list.
  165. for (MachineBasicBlock *P : B.predecessors())
  166. WorkList.insert(P->getNumber());
  167. }
  168. UndefOnEntry[BN] = true;
  169. return false;
  170. }
  171. bool LiveRangeCalc::findReachingDefs(LiveRange &LR, MachineBasicBlock &UseMBB,
  172. SlotIndex Use, unsigned PhysReg,
  173. ArrayRef<SlotIndex> Undefs) {
  174. unsigned UseMBBNum = UseMBB.getNumber();
  175. // Block numbers where LR should be live-in.
  176. SmallVector<unsigned, 16> WorkList(1, UseMBBNum);
  177. // Remember if we have seen more than one value.
  178. bool UniqueVNI = true;
  179. VNInfo *TheVNI = nullptr;
  180. bool FoundUndef = false;
  181. // Using Seen as a visited set, perform a BFS for all reaching defs.
  182. for (unsigned i = 0; i != WorkList.size(); ++i) {
  183. MachineBasicBlock *MBB = MF->getBlockNumbered(WorkList[i]);
  184. #ifndef NDEBUG
  185. if (MBB->pred_empty()) {
  186. MBB->getParent()->verify();
  187. errs() << "Use of " << printReg(PhysReg, MRI->getTargetRegisterInfo())
  188. << " does not have a corresponding definition on every path:\n";
  189. const MachineInstr *MI = Indexes->getInstructionFromIndex(Use);
  190. if (MI != nullptr)
  191. errs() << Use << " " << *MI;
  192. report_fatal_error("Use not jointly dominated by defs.");
  193. }
  194. if (Register::isPhysicalRegister(PhysReg) && !MBB->isLiveIn(PhysReg)) {
  195. MBB->getParent()->verify();
  196. const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
  197. errs() << "The register " << printReg(PhysReg, TRI)
  198. << " needs to be live in to " << printMBBReference(*MBB)
  199. << ", but is missing from the live-in list.\n";
  200. report_fatal_error("Invalid global physical register");
  201. }
  202. #endif
  203. FoundUndef |= MBB->pred_empty();
  204. for (MachineBasicBlock *Pred : MBB->predecessors()) {
  205. // Is this a known live-out block?
  206. if (Seen.test(Pred->getNumber())) {
  207. if (VNInfo *VNI = Map[Pred].first) {
  208. if (TheVNI && TheVNI != VNI)
  209. UniqueVNI = false;
  210. TheVNI = VNI;
  211. }
  212. continue;
  213. }
  214. SlotIndex Start, End;
  215. std::tie(Start, End) = Indexes->getMBBRange(Pred);
  216. // First time we see Pred. Try to determine the live-out value, but set
  217. // it as null if Pred is live-through with an unknown value.
  218. auto EP = LR.extendInBlock(Undefs, Start, End);
  219. VNInfo *VNI = EP.first;
  220. FoundUndef |= EP.second;
  221. setLiveOutValue(Pred, EP.second ? &UndefVNI : VNI);
  222. if (VNI) {
  223. if (TheVNI && TheVNI != VNI)
  224. UniqueVNI = false;
  225. TheVNI = VNI;
  226. }
  227. if (VNI || EP.second)
  228. continue;
  229. // No, we need a live-in value for Pred as well
  230. if (Pred != &UseMBB)
  231. WorkList.push_back(Pred->getNumber());
  232. else
  233. // Loopback to UseMBB, so value is really live through.
  234. Use = SlotIndex();
  235. }
  236. }
  237. LiveIn.clear();
  238. FoundUndef |= (TheVNI == nullptr || TheVNI == &UndefVNI);
  239. if (!Undefs.empty() && FoundUndef)
  240. UniqueVNI = false;
  241. // Both updateSSA() and LiveRangeUpdater benefit from ordered blocks, but
  242. // neither require it. Skip the sorting overhead for small updates.
  243. if (WorkList.size() > 4)
  244. array_pod_sort(WorkList.begin(), WorkList.end());
  245. // If a unique reaching def was found, blit in the live ranges immediately.
  246. if (UniqueVNI) {
  247. assert(TheVNI != nullptr && TheVNI != &UndefVNI);
  248. LiveRangeUpdater Updater(&LR);
  249. for (unsigned BN : WorkList) {
  250. SlotIndex Start, End;
  251. std::tie(Start, End) = Indexes->getMBBRange(BN);
  252. // Trim the live range in UseMBB.
  253. if (BN == UseMBBNum && Use.isValid())
  254. End = Use;
  255. else
  256. Map[MF->getBlockNumbered(BN)] = LiveOutPair(TheVNI, nullptr);
  257. Updater.add(Start, End, TheVNI);
  258. }
  259. return true;
  260. }
  261. // Prepare the defined/undefined bit vectors.
  262. EntryInfoMap::iterator Entry;
  263. bool DidInsert;
  264. std::tie(Entry, DidInsert) = EntryInfos.insert(
  265. std::make_pair(&LR, std::make_pair(BitVector(), BitVector())));
  266. if (DidInsert) {
  267. // Initialize newly inserted entries.
  268. unsigned N = MF->getNumBlockIDs();
  269. Entry->second.first.resize(N);
  270. Entry->second.second.resize(N);
  271. }
  272. BitVector &DefOnEntry = Entry->second.first;
  273. BitVector &UndefOnEntry = Entry->second.second;
  274. // Multiple values were found, so transfer the work list to the LiveIn array
  275. // where UpdateSSA will use it as a work list.
  276. LiveIn.reserve(WorkList.size());
  277. for (unsigned BN : WorkList) {
  278. MachineBasicBlock *MBB = MF->getBlockNumbered(BN);
  279. if (!Undefs.empty() &&
  280. !isDefOnEntry(LR, Undefs, *MBB, DefOnEntry, UndefOnEntry))
  281. continue;
  282. addLiveInBlock(LR, DomTree->getNode(MBB));
  283. if (MBB == &UseMBB)
  284. LiveIn.back().Kill = Use;
  285. }
  286. return false;
  287. }
  288. // This is essentially the same iterative algorithm that SSAUpdater uses,
  289. // except we already have a dominator tree, so we don't have to recompute it.
  290. void LiveRangeCalc::updateSSA() {
  291. assert(Indexes && "Missing SlotIndexes");
  292. assert(DomTree && "Missing dominator tree");
  293. // Interate until convergence.
  294. bool Changed;
  295. do {
  296. Changed = false;
  297. // Propagate live-out values down the dominator tree, inserting phi-defs
  298. // when necessary.
  299. for (LiveInBlock &I : LiveIn) {
  300. MachineDomTreeNode *Node = I.DomNode;
  301. // Skip block if the live-in value has already been determined.
  302. if (!Node)
  303. continue;
  304. MachineBasicBlock *MBB = Node->getBlock();
  305. MachineDomTreeNode *IDom = Node->getIDom();
  306. LiveOutPair IDomValue;
  307. // We need a live-in value to a block with no immediate dominator?
  308. // This is probably an unreachable block that has survived somehow.
  309. bool needPHI = !IDom || !Seen.test(IDom->getBlock()->getNumber());
  310. // IDom dominates all of our predecessors, but it may not be their
  311. // immediate dominator. Check if any of them have live-out values that are
  312. // properly dominated by IDom. If so, we need a phi-def here.
  313. if (!needPHI) {
  314. IDomValue = Map[IDom->getBlock()];
  315. // Cache the DomTree node that defined the value.
  316. if (IDomValue.first && IDomValue.first != &UndefVNI &&
  317. !IDomValue.second) {
  318. Map[IDom->getBlock()].second = IDomValue.second =
  319. DomTree->getNode(Indexes->getMBBFromIndex(IDomValue.first->def));
  320. }
  321. for (MachineBasicBlock *Pred : MBB->predecessors()) {
  322. LiveOutPair &Value = Map[Pred];
  323. if (!Value.first || Value.first == IDomValue.first)
  324. continue;
  325. if (Value.first == &UndefVNI) {
  326. needPHI = true;
  327. break;
  328. }
  329. // Cache the DomTree node that defined the value.
  330. if (!Value.second)
  331. Value.second =
  332. DomTree->getNode(Indexes->getMBBFromIndex(Value.first->def));
  333. // This predecessor is carrying something other than IDomValue.
  334. // It could be because IDomValue hasn't propagated yet, or it could be
  335. // because MBB is in the dominance frontier of that value.
  336. if (DomTree->dominates(IDom, Value.second)) {
  337. needPHI = true;
  338. break;
  339. }
  340. }
  341. }
  342. // The value may be live-through even if Kill is set, as can happen when
  343. // we are called from extendRange. In that case LiveOutSeen is true, and
  344. // LiveOut indicates a foreign or missing value.
  345. LiveOutPair &LOP = Map[MBB];
  346. // Create a phi-def if required.
  347. if (needPHI) {
  348. Changed = true;
  349. assert(Alloc && "Need VNInfo allocator to create PHI-defs");
  350. SlotIndex Start, End;
  351. std::tie(Start, End) = Indexes->getMBBRange(MBB);
  352. LiveRange &LR = I.LR;
  353. VNInfo *VNI = LR.getNextValue(Start, *Alloc);
  354. I.Value = VNI;
  355. // This block is done, we know the final value.
  356. I.DomNode = nullptr;
  357. // Add liveness since updateFromLiveIns now skips this node.
  358. if (I.Kill.isValid()) {
  359. if (VNI)
  360. LR.addSegment(LiveInterval::Segment(Start, I.Kill, VNI));
  361. } else {
  362. if (VNI)
  363. LR.addSegment(LiveInterval::Segment(Start, End, VNI));
  364. LOP = LiveOutPair(VNI, Node);
  365. }
  366. } else if (IDomValue.first && IDomValue.first != &UndefVNI) {
  367. // No phi-def here. Remember incoming value.
  368. I.Value = IDomValue.first;
  369. // If the IDomValue is killed in the block, don't propagate through.
  370. if (I.Kill.isValid())
  371. continue;
  372. // Propagate IDomValue if it isn't killed:
  373. // MBB is live-out and doesn't define its own value.
  374. if (LOP.first == IDomValue.first)
  375. continue;
  376. Changed = true;
  377. LOP = IDomValue;
  378. }
  379. }
  380. } while (Changed);
  381. }
  382. bool LiveRangeCalc::isJointlyDominated(const MachineBasicBlock *MBB,
  383. ArrayRef<SlotIndex> Defs,
  384. const SlotIndexes &Indexes) {
  385. const MachineFunction &MF = *MBB->getParent();
  386. BitVector DefBlocks(MF.getNumBlockIDs());
  387. for (SlotIndex I : Defs)
  388. DefBlocks.set(Indexes.getMBBFromIndex(I)->getNumber());
  389. SetVector<unsigned> PredQueue;
  390. PredQueue.insert(MBB->getNumber());
  391. for (unsigned i = 0; i != PredQueue.size(); ++i) {
  392. unsigned BN = PredQueue[i];
  393. if (DefBlocks[BN])
  394. return true;
  395. const MachineBasicBlock *B = MF.getBlockNumbered(BN);
  396. for (const MachineBasicBlock *P : B->predecessors())
  397. PredQueue.insert(P->getNumber());
  398. }
  399. return false;
  400. }