LiveIntervals.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. //===- LiveIntervals.cpp - Live Interval Analysis -------------------------===//
  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. /// \file This file implements the LiveInterval analysis pass which is used
  10. /// by the Linear Scan Register allocator. This pass linearizes the
  11. /// basic blocks of the function in DFS order and computes live intervals for
  12. /// each virtual and physical register.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/LiveIntervals.h"
  16. #include "LiveRangeCalc.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/DepthFirstIterator.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/iterator_range.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/CodeGen/LiveInterval.h"
  24. #include "llvm/CodeGen/LiveVariables.h"
  25. #include "llvm/CodeGen/MachineBasicBlock.h"
  26. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  27. #include "llvm/CodeGen/MachineDominators.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineInstr.h"
  30. #include "llvm/CodeGen/MachineInstrBundle.h"
  31. #include "llvm/CodeGen/MachineOperand.h"
  32. #include "llvm/CodeGen/MachineRegisterInfo.h"
  33. #include "llvm/CodeGen/Passes.h"
  34. #include "llvm/CodeGen/SlotIndexes.h"
  35. #include "llvm/CodeGen/TargetRegisterInfo.h"
  36. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  37. #include "llvm/CodeGen/VirtRegMap.h"
  38. #include "llvm/Config/llvm-config.h"
  39. #include "llvm/MC/LaneBitmask.h"
  40. #include "llvm/MC/MCRegisterInfo.h"
  41. #include "llvm/Pass.h"
  42. #include "llvm/Support/BlockFrequency.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/Compiler.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/MathExtras.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <cstdint>
  51. #include <iterator>
  52. #include <tuple>
  53. #include <utility>
  54. using namespace llvm;
  55. #define DEBUG_TYPE "regalloc"
  56. char LiveIntervals::ID = 0;
  57. char &llvm::LiveIntervalsID = LiveIntervals::ID;
  58. INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
  59. "Live Interval Analysis", false, false)
  60. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  61. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  62. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  63. INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
  64. "Live Interval Analysis", false, false)
  65. #ifndef NDEBUG
  66. static cl::opt<bool> EnablePrecomputePhysRegs(
  67. "precompute-phys-liveness", cl::Hidden,
  68. cl::desc("Eagerly compute live intervals for all physreg units."));
  69. #else
  70. static bool EnablePrecomputePhysRegs = false;
  71. #endif // NDEBUG
  72. namespace llvm {
  73. cl::opt<bool> UseSegmentSetForPhysRegs(
  74. "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
  75. cl::desc(
  76. "Use segment set for the computation of the live ranges of physregs."));
  77. } // end namespace llvm
  78. void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
  79. AU.setPreservesCFG();
  80. AU.addRequired<AAResultsWrapperPass>();
  81. AU.addPreserved<AAResultsWrapperPass>();
  82. AU.addPreserved<LiveVariables>();
  83. AU.addPreservedID(MachineLoopInfoID);
  84. AU.addRequiredTransitiveID(MachineDominatorsID);
  85. AU.addPreservedID(MachineDominatorsID);
  86. AU.addPreserved<SlotIndexes>();
  87. AU.addRequiredTransitive<SlotIndexes>();
  88. MachineFunctionPass::getAnalysisUsage(AU);
  89. }
  90. LiveIntervals::LiveIntervals() : MachineFunctionPass(ID) {
  91. initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
  92. }
  93. LiveIntervals::~LiveIntervals() {
  94. delete LRCalc;
  95. }
  96. void LiveIntervals::releaseMemory() {
  97. // Free the live intervals themselves.
  98. for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
  99. delete VirtRegIntervals[Register::index2VirtReg(i)];
  100. VirtRegIntervals.clear();
  101. RegMaskSlots.clear();
  102. RegMaskBits.clear();
  103. RegMaskBlocks.clear();
  104. for (LiveRange *LR : RegUnitRanges)
  105. delete LR;
  106. RegUnitRanges.clear();
  107. // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
  108. VNInfoAllocator.Reset();
  109. }
  110. bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
  111. MF = &fn;
  112. MRI = &MF->getRegInfo();
  113. TRI = MF->getSubtarget().getRegisterInfo();
  114. TII = MF->getSubtarget().getInstrInfo();
  115. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  116. Indexes = &getAnalysis<SlotIndexes>();
  117. DomTree = &getAnalysis<MachineDominatorTree>();
  118. if (!LRCalc)
  119. LRCalc = new LiveRangeCalc();
  120. // Allocate space for all virtual registers.
  121. VirtRegIntervals.resize(MRI->getNumVirtRegs());
  122. computeVirtRegs();
  123. computeRegMasks();
  124. computeLiveInRegUnits();
  125. if (EnablePrecomputePhysRegs) {
  126. // For stress testing, precompute live ranges of all physical register
  127. // units, including reserved registers.
  128. for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
  129. getRegUnit(i);
  130. }
  131. LLVM_DEBUG(dump());
  132. return true;
  133. }
  134. void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
  135. OS << "********** INTERVALS **********\n";
  136. // Dump the regunits.
  137. for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
  138. if (LiveRange *LR = RegUnitRanges[Unit])
  139. OS << printRegUnit(Unit, TRI) << ' ' << *LR << '\n';
  140. // Dump the virtregs.
  141. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  142. unsigned Reg = Register::index2VirtReg(i);
  143. if (hasInterval(Reg))
  144. OS << getInterval(Reg) << '\n';
  145. }
  146. OS << "RegMasks:";
  147. for (SlotIndex Idx : RegMaskSlots)
  148. OS << ' ' << Idx;
  149. OS << '\n';
  150. printInstrs(OS);
  151. }
  152. void LiveIntervals::printInstrs(raw_ostream &OS) const {
  153. OS << "********** MACHINEINSTRS **********\n";
  154. MF->print(OS, Indexes);
  155. }
  156. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  157. LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
  158. printInstrs(dbgs());
  159. }
  160. #endif
  161. LiveInterval* LiveIntervals::createInterval(unsigned reg) {
  162. float Weight = Register::isPhysicalRegister(reg) ? huge_valf : 0.0F;
  163. return new LiveInterval(reg, Weight);
  164. }
  165. /// Compute the live interval of a virtual register, based on defs and uses.
  166. void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
  167. assert(LRCalc && "LRCalc not initialized.");
  168. assert(LI.empty() && "Should only compute empty intervals.");
  169. LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
  170. LRCalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg));
  171. computeDeadValues(LI, nullptr);
  172. }
  173. void LiveIntervals::computeVirtRegs() {
  174. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  175. unsigned Reg = Register::index2VirtReg(i);
  176. if (MRI->reg_nodbg_empty(Reg))
  177. continue;
  178. createAndComputeVirtRegInterval(Reg);
  179. }
  180. }
  181. void LiveIntervals::computeRegMasks() {
  182. RegMaskBlocks.resize(MF->getNumBlockIDs());
  183. // Find all instructions with regmask operands.
  184. for (const MachineBasicBlock &MBB : *MF) {
  185. std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
  186. RMB.first = RegMaskSlots.size();
  187. // Some block starts, such as EH funclets, create masks.
  188. if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
  189. RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
  190. RegMaskBits.push_back(Mask);
  191. }
  192. for (const MachineInstr &MI : MBB) {
  193. for (const MachineOperand &MO : MI.operands()) {
  194. if (!MO.isRegMask())
  195. continue;
  196. RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
  197. RegMaskBits.push_back(MO.getRegMask());
  198. }
  199. }
  200. // Some block ends, such as funclet returns, create masks. Put the mask on
  201. // the last instruction of the block, because MBB slot index intervals are
  202. // half-open.
  203. if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
  204. assert(!MBB.empty() && "empty return block?");
  205. RegMaskSlots.push_back(
  206. Indexes->getInstructionIndex(MBB.back()).getRegSlot());
  207. RegMaskBits.push_back(Mask);
  208. }
  209. // Compute the number of register mask instructions in this block.
  210. RMB.second = RegMaskSlots.size() - RMB.first;
  211. }
  212. }
  213. //===----------------------------------------------------------------------===//
  214. // Register Unit Liveness
  215. //===----------------------------------------------------------------------===//
  216. //
  217. // Fixed interference typically comes from ABI boundaries: Function arguments
  218. // and return values are passed in fixed registers, and so are exception
  219. // pointers entering landing pads. Certain instructions require values to be
  220. // present in specific registers. That is also represented through fixed
  221. // interference.
  222. //
  223. /// Compute the live range of a register unit, based on the uses and defs of
  224. /// aliasing registers. The range should be empty, or contain only dead
  225. /// phi-defs from ABI blocks.
  226. void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
  227. assert(LRCalc && "LRCalc not initialized.");
  228. LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
  229. // The physregs aliasing Unit are the roots and their super-registers.
  230. // Create all values as dead defs before extending to uses. Note that roots
  231. // may share super-registers. That's OK because createDeadDefs() is
  232. // idempotent. It is very rare for a register unit to have multiple roots, so
  233. // uniquing super-registers is probably not worthwhile.
  234. bool IsReserved = false;
  235. for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
  236. bool IsRootReserved = true;
  237. for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
  238. Super.isValid(); ++Super) {
  239. unsigned Reg = *Super;
  240. if (!MRI->reg_empty(Reg))
  241. LRCalc->createDeadDefs(LR, Reg);
  242. // A register unit is considered reserved if all its roots and all their
  243. // super registers are reserved.
  244. if (!MRI->isReserved(Reg))
  245. IsRootReserved = false;
  246. }
  247. IsReserved |= IsRootReserved;
  248. }
  249. assert(IsReserved == MRI->isReservedRegUnit(Unit) &&
  250. "reserved computation mismatch");
  251. // Now extend LR to reach all uses.
  252. // Ignore uses of reserved registers. We only track defs of those.
  253. if (!IsReserved) {
  254. for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
  255. for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
  256. Super.isValid(); ++Super) {
  257. unsigned Reg = *Super;
  258. if (!MRI->reg_empty(Reg))
  259. LRCalc->extendToUses(LR, Reg);
  260. }
  261. }
  262. }
  263. // Flush the segment set to the segment vector.
  264. if (UseSegmentSetForPhysRegs)
  265. LR.flushSegmentSet();
  266. }
  267. /// Precompute the live ranges of any register units that are live-in to an ABI
  268. /// block somewhere. Register values can appear without a corresponding def when
  269. /// entering the entry block or a landing pad.
  270. void LiveIntervals::computeLiveInRegUnits() {
  271. RegUnitRanges.resize(TRI->getNumRegUnits());
  272. LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
  273. // Keep track of the live range sets allocated.
  274. SmallVector<unsigned, 8> NewRanges;
  275. // Check all basic blocks for live-ins.
  276. for (const MachineBasicBlock &MBB : *MF) {
  277. // We only care about ABI blocks: Entry + landing pads.
  278. if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
  279. continue;
  280. // Create phi-defs at Begin for all live-in registers.
  281. SlotIndex Begin = Indexes->getMBBStartIdx(&MBB);
  282. LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB));
  283. for (const auto &LI : MBB.liveins()) {
  284. for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
  285. unsigned Unit = *Units;
  286. LiveRange *LR = RegUnitRanges[Unit];
  287. if (!LR) {
  288. // Use segment set to speed-up initial computation of the live range.
  289. LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
  290. NewRanges.push_back(Unit);
  291. }
  292. VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
  293. (void)VNI;
  294. LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id);
  295. }
  296. }
  297. LLVM_DEBUG(dbgs() << '\n');
  298. }
  299. LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
  300. // Compute the 'normal' part of the ranges.
  301. for (unsigned Unit : NewRanges)
  302. computeRegUnitRange(*RegUnitRanges[Unit], Unit);
  303. }
  304. static void createSegmentsForValues(LiveRange &LR,
  305. iterator_range<LiveInterval::vni_iterator> VNIs) {
  306. for (VNInfo *VNI : VNIs) {
  307. if (VNI->isUnused())
  308. continue;
  309. SlotIndex Def = VNI->def;
  310. LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
  311. }
  312. }
  313. void LiveIntervals::extendSegmentsToUses(LiveRange &Segments,
  314. ShrinkToUsesWorkList &WorkList,
  315. unsigned Reg, LaneBitmask LaneMask) {
  316. // Keep track of the PHIs that are in use.
  317. SmallPtrSet<VNInfo*, 8> UsedPHIs;
  318. // Blocks that have already been added to WorkList as live-out.
  319. SmallPtrSet<const MachineBasicBlock*, 16> LiveOut;
  320. auto getSubRange = [](const LiveInterval &I, LaneBitmask M)
  321. -> const LiveRange& {
  322. if (M.none())
  323. return I;
  324. for (const LiveInterval::SubRange &SR : I.subranges()) {
  325. if ((SR.LaneMask & M).any()) {
  326. assert(SR.LaneMask == M && "Expecting lane masks to match exactly");
  327. return SR;
  328. }
  329. }
  330. llvm_unreachable("Subrange for mask not found");
  331. };
  332. const LiveInterval &LI = getInterval(Reg);
  333. const LiveRange &OldRange = getSubRange(LI, LaneMask);
  334. // Extend intervals to reach all uses in WorkList.
  335. while (!WorkList.empty()) {
  336. SlotIndex Idx = WorkList.back().first;
  337. VNInfo *VNI = WorkList.back().second;
  338. WorkList.pop_back();
  339. const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot());
  340. SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB);
  341. // Extend the live range for VNI to be live at Idx.
  342. if (VNInfo *ExtVNI = Segments.extendInBlock(BlockStart, Idx)) {
  343. assert(ExtVNI == VNI && "Unexpected existing value number");
  344. (void)ExtVNI;
  345. // Is this a PHIDef we haven't seen before?
  346. if (!VNI->isPHIDef() || VNI->def != BlockStart ||
  347. !UsedPHIs.insert(VNI).second)
  348. continue;
  349. // The PHI is live, make sure the predecessors are live-out.
  350. for (const MachineBasicBlock *Pred : MBB->predecessors()) {
  351. if (!LiveOut.insert(Pred).second)
  352. continue;
  353. SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
  354. // A predecessor is not required to have a live-out value for a PHI.
  355. if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
  356. WorkList.push_back(std::make_pair(Stop, PVNI));
  357. }
  358. continue;
  359. }
  360. // VNI is live-in to MBB.
  361. LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
  362. Segments.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
  363. // Make sure VNI is live-out from the predecessors.
  364. for (const MachineBasicBlock *Pred : MBB->predecessors()) {
  365. if (!LiveOut.insert(Pred).second)
  366. continue;
  367. SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
  368. if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Stop)) {
  369. assert(OldVNI == VNI && "Wrong value out of predecessor");
  370. (void)OldVNI;
  371. WorkList.push_back(std::make_pair(Stop, VNI));
  372. } else {
  373. #ifndef NDEBUG
  374. // There was no old VNI. Verify that Stop is jointly dominated
  375. // by <undef>s for this live range.
  376. assert(LaneMask.any() &&
  377. "Missing value out of predecessor for main range");
  378. SmallVector<SlotIndex,8> Undefs;
  379. LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
  380. assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) &&
  381. "Missing value out of predecessor for subrange");
  382. #endif
  383. }
  384. }
  385. }
  386. }
  387. bool LiveIntervals::shrinkToUses(LiveInterval *li,
  388. SmallVectorImpl<MachineInstr*> *dead) {
  389. LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n');
  390. assert(Register::isVirtualRegister(li->reg) &&
  391. "Can only shrink virtual registers");
  392. // Shrink subregister live ranges.
  393. bool NeedsCleanup = false;
  394. for (LiveInterval::SubRange &S : li->subranges()) {
  395. shrinkToUses(S, li->reg);
  396. if (S.empty())
  397. NeedsCleanup = true;
  398. }
  399. if (NeedsCleanup)
  400. li->removeEmptySubRanges();
  401. // Find all the values used, including PHI kills.
  402. ShrinkToUsesWorkList WorkList;
  403. // Visit all instructions reading li->reg.
  404. unsigned Reg = li->reg;
  405. for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) {
  406. if (UseMI.isDebugValue() || !UseMI.readsVirtualRegister(Reg))
  407. continue;
  408. SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
  409. LiveQueryResult LRQ = li->Query(Idx);
  410. VNInfo *VNI = LRQ.valueIn();
  411. if (!VNI) {
  412. // This shouldn't happen: readsVirtualRegister returns true, but there is
  413. // no live value. It is likely caused by a target getting <undef> flags
  414. // wrong.
  415. LLVM_DEBUG(
  416. dbgs() << Idx << '\t' << UseMI
  417. << "Warning: Instr claims to read non-existent value in "
  418. << *li << '\n');
  419. continue;
  420. }
  421. // Special case: An early-clobber tied operand reads and writes the
  422. // register one slot early.
  423. if (VNInfo *DefVNI = LRQ.valueDefined())
  424. Idx = DefVNI->def;
  425. WorkList.push_back(std::make_pair(Idx, VNI));
  426. }
  427. // Create new live ranges with only minimal live segments per def.
  428. LiveRange NewLR;
  429. createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
  430. extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone());
  431. // Move the trimmed segments back.
  432. li->segments.swap(NewLR.segments);
  433. // Handle dead values.
  434. bool CanSeparate = computeDeadValues(*li, dead);
  435. LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n');
  436. return CanSeparate;
  437. }
  438. bool LiveIntervals::computeDeadValues(LiveInterval &LI,
  439. SmallVectorImpl<MachineInstr*> *dead) {
  440. bool MayHaveSplitComponents = false;
  441. for (VNInfo *VNI : LI.valnos) {
  442. if (VNI->isUnused())
  443. continue;
  444. SlotIndex Def = VNI->def;
  445. LiveRange::iterator I = LI.FindSegmentContaining(Def);
  446. assert(I != LI.end() && "Missing segment for VNI");
  447. // Is the register live before? Otherwise we may have to add a read-undef
  448. // flag for subregister defs.
  449. unsigned VReg = LI.reg;
  450. if (MRI->shouldTrackSubRegLiveness(VReg)) {
  451. if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
  452. MachineInstr *MI = getInstructionFromIndex(Def);
  453. MI->setRegisterDefReadUndef(VReg);
  454. }
  455. }
  456. if (I->end != Def.getDeadSlot())
  457. continue;
  458. if (VNI->isPHIDef()) {
  459. // This is a dead PHI. Remove it.
  460. VNI->markUnused();
  461. LI.removeSegment(I);
  462. LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
  463. MayHaveSplitComponents = true;
  464. } else {
  465. // This is a dead def. Make sure the instruction knows.
  466. MachineInstr *MI = getInstructionFromIndex(Def);
  467. assert(MI && "No instruction defining live value");
  468. MI->addRegisterDead(LI.reg, TRI);
  469. if (dead && MI->allDefsAreDead()) {
  470. LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
  471. dead->push_back(MI);
  472. }
  473. }
  474. }
  475. return MayHaveSplitComponents;
  476. }
  477. void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg) {
  478. LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n');
  479. assert(Register::isVirtualRegister(Reg) &&
  480. "Can only shrink virtual registers");
  481. // Find all the values used, including PHI kills.
  482. ShrinkToUsesWorkList WorkList;
  483. // Visit all instructions reading Reg.
  484. SlotIndex LastIdx;
  485. for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
  486. // Skip "undef" uses.
  487. if (!MO.readsReg())
  488. continue;
  489. // Maybe the operand is for a subregister we don't care about.
  490. unsigned SubReg = MO.getSubReg();
  491. if (SubReg != 0) {
  492. LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
  493. if ((LaneMask & SR.LaneMask).none())
  494. continue;
  495. }
  496. // We only need to visit each instruction once.
  497. MachineInstr *UseMI = MO.getParent();
  498. SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
  499. if (Idx == LastIdx)
  500. continue;
  501. LastIdx = Idx;
  502. LiveQueryResult LRQ = SR.Query(Idx);
  503. VNInfo *VNI = LRQ.valueIn();
  504. // For Subranges it is possible that only undef values are left in that
  505. // part of the subregister, so there is no real liverange at the use
  506. if (!VNI)
  507. continue;
  508. // Special case: An early-clobber tied operand reads and writes the
  509. // register one slot early.
  510. if (VNInfo *DefVNI = LRQ.valueDefined())
  511. Idx = DefVNI->def;
  512. WorkList.push_back(std::make_pair(Idx, VNI));
  513. }
  514. // Create a new live ranges with only minimal live segments per def.
  515. LiveRange NewLR;
  516. createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end()));
  517. extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask);
  518. // Move the trimmed ranges back.
  519. SR.segments.swap(NewLR.segments);
  520. // Remove dead PHI value numbers
  521. for (VNInfo *VNI : SR.valnos) {
  522. if (VNI->isUnused())
  523. continue;
  524. const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
  525. assert(Segment != nullptr && "Missing segment for VNI");
  526. if (Segment->end != VNI->def.getDeadSlot())
  527. continue;
  528. if (VNI->isPHIDef()) {
  529. // This is a dead PHI. Remove it.
  530. LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def
  531. << " may separate interval\n");
  532. VNI->markUnused();
  533. SR.removeSegment(*Segment);
  534. }
  535. }
  536. LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n');
  537. }
  538. void LiveIntervals::extendToIndices(LiveRange &LR,
  539. ArrayRef<SlotIndex> Indices,
  540. ArrayRef<SlotIndex> Undefs) {
  541. assert(LRCalc && "LRCalc not initialized.");
  542. LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
  543. for (SlotIndex Idx : Indices)
  544. LRCalc->extend(LR, Idx, /*PhysReg=*/0, Undefs);
  545. }
  546. void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill,
  547. SmallVectorImpl<SlotIndex> *EndPoints) {
  548. LiveQueryResult LRQ = LR.Query(Kill);
  549. VNInfo *VNI = LRQ.valueOutOrDead();
  550. if (!VNI)
  551. return;
  552. MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
  553. SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
  554. // If VNI isn't live out from KillMBB, the value is trivially pruned.
  555. if (LRQ.endPoint() < MBBEnd) {
  556. LR.removeSegment(Kill, LRQ.endPoint());
  557. if (EndPoints) EndPoints->push_back(LRQ.endPoint());
  558. return;
  559. }
  560. // VNI is live out of KillMBB.
  561. LR.removeSegment(Kill, MBBEnd);
  562. if (EndPoints) EndPoints->push_back(MBBEnd);
  563. // Find all blocks that are reachable from KillMBB without leaving VNI's live
  564. // range. It is possible that KillMBB itself is reachable, so start a DFS
  565. // from each successor.
  566. using VisitedTy = df_iterator_default_set<MachineBasicBlock*,9>;
  567. VisitedTy Visited;
  568. for (MachineBasicBlock *Succ : KillMBB->successors()) {
  569. for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
  570. I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited);
  571. I != E;) {
  572. MachineBasicBlock *MBB = *I;
  573. // Check if VNI is live in to MBB.
  574. SlotIndex MBBStart, MBBEnd;
  575. std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
  576. LiveQueryResult LRQ = LR.Query(MBBStart);
  577. if (LRQ.valueIn() != VNI) {
  578. // This block isn't part of the VNI segment. Prune the search.
  579. I.skipChildren();
  580. continue;
  581. }
  582. // Prune the search if VNI is killed in MBB.
  583. if (LRQ.endPoint() < MBBEnd) {
  584. LR.removeSegment(MBBStart, LRQ.endPoint());
  585. if (EndPoints) EndPoints->push_back(LRQ.endPoint());
  586. I.skipChildren();
  587. continue;
  588. }
  589. // VNI is live through MBB.
  590. LR.removeSegment(MBBStart, MBBEnd);
  591. if (EndPoints) EndPoints->push_back(MBBEnd);
  592. ++I;
  593. }
  594. }
  595. }
  596. //===----------------------------------------------------------------------===//
  597. // Register allocator hooks.
  598. //
  599. void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
  600. // Keep track of regunit ranges.
  601. SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU;
  602. // Keep track of subregister ranges.
  603. SmallVector<std::pair<const LiveInterval::SubRange*,
  604. LiveRange::const_iterator>, 4> SRs;
  605. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  606. unsigned Reg = Register::index2VirtReg(i);
  607. if (MRI->reg_nodbg_empty(Reg))
  608. continue;
  609. const LiveInterval &LI = getInterval(Reg);
  610. if (LI.empty())
  611. continue;
  612. // Find the regunit intervals for the assigned register. They may overlap
  613. // the virtual register live range, cancelling any kills.
  614. RU.clear();
  615. for (MCRegUnitIterator Unit(VRM->getPhys(Reg), TRI); Unit.isValid();
  616. ++Unit) {
  617. const LiveRange &RURange = getRegUnit(*Unit);
  618. if (RURange.empty())
  619. continue;
  620. RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
  621. }
  622. if (MRI->subRegLivenessEnabled()) {
  623. SRs.clear();
  624. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  625. SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
  626. }
  627. }
  628. // Every instruction that kills Reg corresponds to a segment range end
  629. // point.
  630. for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
  631. ++RI) {
  632. // A block index indicates an MBB edge.
  633. if (RI->end.isBlock())
  634. continue;
  635. MachineInstr *MI = getInstructionFromIndex(RI->end);
  636. if (!MI)
  637. continue;
  638. // Check if any of the regunits are live beyond the end of RI. That could
  639. // happen when a physreg is defined as a copy of a virtreg:
  640. //
  641. // %eax = COPY %5
  642. // FOO %5 <--- MI, cancel kill because %eax is live.
  643. // BAR killed %eax
  644. //
  645. // There should be no kill flag on FOO when %5 is rewritten as %eax.
  646. for (auto &RUP : RU) {
  647. const LiveRange &RURange = *RUP.first;
  648. LiveRange::const_iterator &I = RUP.second;
  649. if (I == RURange.end())
  650. continue;
  651. I = RURange.advanceTo(I, RI->end);
  652. if (I == RURange.end() || I->start >= RI->end)
  653. continue;
  654. // I is overlapping RI.
  655. goto CancelKill;
  656. }
  657. if (MRI->subRegLivenessEnabled()) {
  658. // When reading a partial undefined value we must not add a kill flag.
  659. // The regalloc might have used the undef lane for something else.
  660. // Example:
  661. // %1 = ... ; R32: %1
  662. // %2:high16 = ... ; R64: %2
  663. // = read killed %2 ; R64: %2
  664. // = read %1 ; R32: %1
  665. // The <kill> flag is correct for %2, but the register allocator may
  666. // assign R0L to %1, and R0 to %2 because the low 32bits of R0
  667. // are actually never written by %2. After assignment the <kill>
  668. // flag at the read instruction is invalid.
  669. LaneBitmask DefinedLanesMask;
  670. if (!SRs.empty()) {
  671. // Compute a mask of lanes that are defined.
  672. DefinedLanesMask = LaneBitmask::getNone();
  673. for (auto &SRP : SRs) {
  674. const LiveInterval::SubRange &SR = *SRP.first;
  675. LiveRange::const_iterator &I = SRP.second;
  676. if (I == SR.end())
  677. continue;
  678. I = SR.advanceTo(I, RI->end);
  679. if (I == SR.end() || I->start >= RI->end)
  680. continue;
  681. // I is overlapping RI
  682. DefinedLanesMask |= SR.LaneMask;
  683. }
  684. } else
  685. DefinedLanesMask = LaneBitmask::getAll();
  686. bool IsFullWrite = false;
  687. for (const MachineOperand &MO : MI->operands()) {
  688. if (!MO.isReg() || MO.getReg() != Reg)
  689. continue;
  690. if (MO.isUse()) {
  691. // Reading any undefined lanes?
  692. LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
  693. if ((UseMask & ~DefinedLanesMask).any())
  694. goto CancelKill;
  695. } else if (MO.getSubReg() == 0) {
  696. // Writing to the full register?
  697. assert(MO.isDef());
  698. IsFullWrite = true;
  699. }
  700. }
  701. // If an instruction writes to a subregister, a new segment starts in
  702. // the LiveInterval. But as this is only overriding part of the register
  703. // adding kill-flags is not correct here after registers have been
  704. // assigned.
  705. if (!IsFullWrite) {
  706. // Next segment has to be adjacent in the subregister write case.
  707. LiveRange::const_iterator N = std::next(RI);
  708. if (N != LI.end() && N->start == RI->end)
  709. goto CancelKill;
  710. }
  711. }
  712. MI->addRegisterKilled(Reg, nullptr);
  713. continue;
  714. CancelKill:
  715. MI->clearRegisterKills(Reg, nullptr);
  716. }
  717. }
  718. }
  719. MachineBasicBlock*
  720. LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
  721. // A local live range must be fully contained inside the block, meaning it is
  722. // defined and killed at instructions, not at block boundaries. It is not
  723. // live in or out of any block.
  724. //
  725. // It is technically possible to have a PHI-defined live range identical to a
  726. // single block, but we are going to return false in that case.
  727. SlotIndex Start = LI.beginIndex();
  728. if (Start.isBlock())
  729. return nullptr;
  730. SlotIndex Stop = LI.endIndex();
  731. if (Stop.isBlock())
  732. return nullptr;
  733. // getMBBFromIndex doesn't need to search the MBB table when both indexes
  734. // belong to proper instructions.
  735. MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
  736. MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
  737. return MBB1 == MBB2 ? MBB1 : nullptr;
  738. }
  739. bool
  740. LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
  741. for (const VNInfo *PHI : LI.valnos) {
  742. if (PHI->isUnused() || !PHI->isPHIDef())
  743. continue;
  744. const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
  745. // Conservatively return true instead of scanning huge predecessor lists.
  746. if (PHIMBB->pred_size() > 100)
  747. return true;
  748. for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
  749. if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred)))
  750. return true;
  751. }
  752. return false;
  753. }
  754. float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
  755. const MachineBlockFrequencyInfo *MBFI,
  756. const MachineInstr &MI) {
  757. return getSpillWeight(isDef, isUse, MBFI, MI.getParent());
  758. }
  759. float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
  760. const MachineBlockFrequencyInfo *MBFI,
  761. const MachineBasicBlock *MBB) {
  762. BlockFrequency Freq = MBFI->getBlockFreq(MBB);
  763. const float Scale = 1.0f / MBFI->getEntryFreq();
  764. return (isDef + isUse) * (Freq.getFrequency() * Scale);
  765. }
  766. LiveRange::Segment
  767. LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr &startInst) {
  768. LiveInterval& Interval = createEmptyInterval(reg);
  769. VNInfo *VN = Interval.getNextValue(
  770. SlotIndex(getInstructionIndex(startInst).getRegSlot()),
  771. getVNInfoAllocator());
  772. LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
  773. getMBBEndIdx(startInst.getParent()), VN);
  774. Interval.addSegment(S);
  775. return S;
  776. }
  777. //===----------------------------------------------------------------------===//
  778. // Register mask functions
  779. //===----------------------------------------------------------------------===//
  780. bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
  781. BitVector &UsableRegs) {
  782. if (LI.empty())
  783. return false;
  784. LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
  785. // Use a smaller arrays for local live ranges.
  786. ArrayRef<SlotIndex> Slots;
  787. ArrayRef<const uint32_t*> Bits;
  788. if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
  789. Slots = getRegMaskSlotsInBlock(MBB->getNumber());
  790. Bits = getRegMaskBitsInBlock(MBB->getNumber());
  791. } else {
  792. Slots = getRegMaskSlots();
  793. Bits = getRegMaskBits();
  794. }
  795. // We are going to enumerate all the register mask slots contained in LI.
  796. // Start with a binary search of RegMaskSlots to find a starting point.
  797. ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start);
  798. ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
  799. // No slots in range, LI begins after the last call.
  800. if (SlotI == SlotE)
  801. return false;
  802. bool Found = false;
  803. while (true) {
  804. assert(*SlotI >= LiveI->start);
  805. // Loop over all slots overlapping this segment.
  806. while (*SlotI < LiveI->end) {
  807. // *SlotI overlaps LI. Collect mask bits.
  808. if (!Found) {
  809. // This is the first overlap. Initialize UsableRegs to all ones.
  810. UsableRegs.clear();
  811. UsableRegs.resize(TRI->getNumRegs(), true);
  812. Found = true;
  813. }
  814. // Remove usable registers clobbered by this mask.
  815. UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
  816. if (++SlotI == SlotE)
  817. return Found;
  818. }
  819. // *SlotI is beyond the current LI segment.
  820. LiveI = LI.advanceTo(LiveI, *SlotI);
  821. if (LiveI == LiveE)
  822. return Found;
  823. // Advance SlotI until it overlaps.
  824. while (*SlotI < LiveI->start)
  825. if (++SlotI == SlotE)
  826. return Found;
  827. }
  828. }
  829. //===----------------------------------------------------------------------===//
  830. // IntervalUpdate class.
  831. //===----------------------------------------------------------------------===//
  832. /// Toolkit used by handleMove to trim or extend live intervals.
  833. class LiveIntervals::HMEditor {
  834. private:
  835. LiveIntervals& LIS;
  836. const MachineRegisterInfo& MRI;
  837. const TargetRegisterInfo& TRI;
  838. SlotIndex OldIdx;
  839. SlotIndex NewIdx;
  840. SmallPtrSet<LiveRange*, 8> Updated;
  841. bool UpdateFlags;
  842. public:
  843. HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
  844. const TargetRegisterInfo& TRI,
  845. SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
  846. : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
  847. UpdateFlags(UpdateFlags) {}
  848. // FIXME: UpdateFlags is a workaround that creates live intervals for all
  849. // physregs, even those that aren't needed for regalloc, in order to update
  850. // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
  851. // flags, and postRA passes will use a live register utility instead.
  852. LiveRange *getRegUnitLI(unsigned Unit) {
  853. if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
  854. return &LIS.getRegUnit(Unit);
  855. return LIS.getCachedRegUnit(Unit);
  856. }
  857. /// Update all live ranges touched by MI, assuming a move from OldIdx to
  858. /// NewIdx.
  859. void updateAllRanges(MachineInstr *MI) {
  860. LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
  861. << *MI);
  862. bool hasRegMask = false;
  863. for (MachineOperand &MO : MI->operands()) {
  864. if (MO.isRegMask())
  865. hasRegMask = true;
  866. if (!MO.isReg())
  867. continue;
  868. if (MO.isUse()) {
  869. if (!MO.readsReg())
  870. continue;
  871. // Aggressively clear all kill flags.
  872. // They are reinserted by VirtRegRewriter.
  873. MO.setIsKill(false);
  874. }
  875. Register Reg = MO.getReg();
  876. if (!Reg)
  877. continue;
  878. if (Register::isVirtualRegister(Reg)) {
  879. LiveInterval &LI = LIS.getInterval(Reg);
  880. if (LI.hasSubRanges()) {
  881. unsigned SubReg = MO.getSubReg();
  882. LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
  883. : MRI.getMaxLaneMaskForVReg(Reg);
  884. for (LiveInterval::SubRange &S : LI.subranges()) {
  885. if ((S.LaneMask & LaneMask).none())
  886. continue;
  887. updateRange(S, Reg, S.LaneMask);
  888. }
  889. }
  890. updateRange(LI, Reg, LaneBitmask::getNone());
  891. continue;
  892. }
  893. // For physregs, only update the regunits that actually have a
  894. // precomputed live range.
  895. for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
  896. if (LiveRange *LR = getRegUnitLI(*Units))
  897. updateRange(*LR, *Units, LaneBitmask::getNone());
  898. }
  899. if (hasRegMask)
  900. updateRegMaskSlots();
  901. }
  902. private:
  903. /// Update a single live range, assuming an instruction has been moved from
  904. /// OldIdx to NewIdx.
  905. void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
  906. if (!Updated.insert(&LR).second)
  907. return;
  908. LLVM_DEBUG({
  909. dbgs() << " ";
  910. if (Register::isVirtualRegister(Reg)) {
  911. dbgs() << printReg(Reg);
  912. if (LaneMask.any())
  913. dbgs() << " L" << PrintLaneMask(LaneMask);
  914. } else {
  915. dbgs() << printRegUnit(Reg, &TRI);
  916. }
  917. dbgs() << ":\t" << LR << '\n';
  918. });
  919. if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
  920. handleMoveDown(LR);
  921. else
  922. handleMoveUp(LR, Reg, LaneMask);
  923. LLVM_DEBUG(dbgs() << " -->\t" << LR << '\n');
  924. LR.verify();
  925. }
  926. /// Update LR to reflect an instruction has been moved downwards from OldIdx
  927. /// to NewIdx (OldIdx < NewIdx).
  928. void handleMoveDown(LiveRange &LR) {
  929. LiveRange::iterator E = LR.end();
  930. // Segment going into OldIdx.
  931. LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
  932. // No value live before or after OldIdx? Nothing to do.
  933. if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
  934. return;
  935. LiveRange::iterator OldIdxOut;
  936. // Do we have a value live-in to OldIdx?
  937. if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
  938. // If the live-in value already extends to NewIdx, there is nothing to do.
  939. if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
  940. return;
  941. // Aggressively remove all kill flags from the old kill point.
  942. // Kill flags shouldn't be used while live intervals exist, they will be
  943. // reinserted by VirtRegRewriter.
  944. if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
  945. for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
  946. if (MO->isReg() && MO->isUse())
  947. MO->setIsKill(false);
  948. // Is there a def before NewIdx which is not OldIdx?
  949. LiveRange::iterator Next = std::next(OldIdxIn);
  950. if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
  951. SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
  952. // If we are here then OldIdx was just a use but not a def. We only have
  953. // to ensure liveness extends to NewIdx.
  954. LiveRange::iterator NewIdxIn =
  955. LR.advanceTo(Next, NewIdx.getBaseIndex());
  956. // Extend the segment before NewIdx if necessary.
  957. if (NewIdxIn == E ||
  958. !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
  959. LiveRange::iterator Prev = std::prev(NewIdxIn);
  960. Prev->end = NewIdx.getRegSlot();
  961. }
  962. // Extend OldIdxIn.
  963. OldIdxIn->end = Next->start;
  964. return;
  965. }
  966. // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
  967. // invalid by overlapping ranges.
  968. bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
  969. OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
  970. // If this was not a kill, then there was no def and we're done.
  971. if (!isKill)
  972. return;
  973. // Did we have a Def at OldIdx?
  974. OldIdxOut = Next;
  975. if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
  976. return;
  977. } else {
  978. OldIdxOut = OldIdxIn;
  979. }
  980. // If we are here then there is a Definition at OldIdx. OldIdxOut points
  981. // to the segment starting there.
  982. assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
  983. "No def?");
  984. VNInfo *OldIdxVNI = OldIdxOut->valno;
  985. assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
  986. // If the defined value extends beyond NewIdx, just move the beginning
  987. // of the segment to NewIdx.
  988. SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
  989. if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
  990. OldIdxVNI->def = NewIdxDef;
  991. OldIdxOut->start = OldIdxVNI->def;
  992. return;
  993. }
  994. // If we are here then we have a Definition at OldIdx which ends before
  995. // NewIdx.
  996. // Is there an existing Def at NewIdx?
  997. LiveRange::iterator AfterNewIdx
  998. = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
  999. bool OldIdxDefIsDead = OldIdxOut->end.isDead();
  1000. if (!OldIdxDefIsDead &&
  1001. SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
  1002. // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
  1003. VNInfo *DefVNI;
  1004. if (OldIdxOut != LR.begin() &&
  1005. !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
  1006. OldIdxOut->start)) {
  1007. // There is no gap between OldIdxOut and its predecessor anymore,
  1008. // merge them.
  1009. LiveRange::iterator IPrev = std::prev(OldIdxOut);
  1010. DefVNI = OldIdxVNI;
  1011. IPrev->end = OldIdxOut->end;
  1012. } else {
  1013. // The value is live in to OldIdx
  1014. LiveRange::iterator INext = std::next(OldIdxOut);
  1015. assert(INext != E && "Must have following segment");
  1016. // We merge OldIdxOut and its successor. As we're dealing with subreg
  1017. // reordering, there is always a successor to OldIdxOut in the same BB
  1018. // We don't need INext->valno anymore and will reuse for the new segment
  1019. // we create later.
  1020. DefVNI = OldIdxVNI;
  1021. INext->start = OldIdxOut->end;
  1022. INext->valno->def = INext->start;
  1023. }
  1024. // If NewIdx is behind the last segment, extend that and append a new one.
  1025. if (AfterNewIdx == E) {
  1026. // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
  1027. // one position.
  1028. // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
  1029. // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
  1030. std::copy(std::next(OldIdxOut), E, OldIdxOut);
  1031. // The last segment is undefined now, reuse it for a dead def.
  1032. LiveRange::iterator NewSegment = std::prev(E);
  1033. *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
  1034. DefVNI);
  1035. DefVNI->def = NewIdxDef;
  1036. LiveRange::iterator Prev = std::prev(NewSegment);
  1037. Prev->end = NewIdxDef;
  1038. } else {
  1039. // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
  1040. // one position.
  1041. // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
  1042. // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
  1043. std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
  1044. LiveRange::iterator Prev = std::prev(AfterNewIdx);
  1045. // We have two cases:
  1046. if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
  1047. // Case 1: NewIdx is inside a liverange. Split this liverange at
  1048. // NewIdxDef into the segment "Prev" followed by "NewSegment".
  1049. LiveRange::iterator NewSegment = AfterNewIdx;
  1050. *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
  1051. Prev->valno->def = NewIdxDef;
  1052. *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
  1053. DefVNI->def = Prev->start;
  1054. } else {
  1055. // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
  1056. // turn Prev into a segment from NewIdx to AfterNewIdx->start.
  1057. *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
  1058. DefVNI->def = NewIdxDef;
  1059. assert(DefVNI != AfterNewIdx->valno);
  1060. }
  1061. }
  1062. return;
  1063. }
  1064. if (AfterNewIdx != E &&
  1065. SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
  1066. // There is an existing def at NewIdx. The def at OldIdx is coalesced into
  1067. // that value.
  1068. assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
  1069. LR.removeValNo(OldIdxVNI);
  1070. } else {
  1071. // There was no existing def at NewIdx. We need to create a dead def
  1072. // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
  1073. // a new segment at the place where we want to construct the dead def.
  1074. // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
  1075. // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
  1076. assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
  1077. std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
  1078. // We can reuse OldIdxVNI now.
  1079. LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
  1080. VNInfo *NewSegmentVNI = OldIdxVNI;
  1081. NewSegmentVNI->def = NewIdxDef;
  1082. *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
  1083. NewSegmentVNI);
  1084. }
  1085. }
  1086. /// Update LR to reflect an instruction has been moved upwards from OldIdx
  1087. /// to NewIdx (NewIdx < OldIdx).
  1088. void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
  1089. LiveRange::iterator E = LR.end();
  1090. // Segment going into OldIdx.
  1091. LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
  1092. // No value live before or after OldIdx? Nothing to do.
  1093. if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
  1094. return;
  1095. LiveRange::iterator OldIdxOut;
  1096. // Do we have a value live-in to OldIdx?
  1097. if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
  1098. // If the live-in value isn't killed here, then we have no Def at
  1099. // OldIdx, moreover the value must be live at NewIdx so there is nothing
  1100. // to do.
  1101. bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
  1102. if (!isKill)
  1103. return;
  1104. // At this point we have to move OldIdxIn->end back to the nearest
  1105. // previous use or (dead-)def but no further than NewIdx.
  1106. SlotIndex DefBeforeOldIdx
  1107. = std::max(OldIdxIn->start.getDeadSlot(),
  1108. NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
  1109. OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
  1110. // Did we have a Def at OldIdx? If not we are done now.
  1111. OldIdxOut = std::next(OldIdxIn);
  1112. if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
  1113. return;
  1114. } else {
  1115. OldIdxOut = OldIdxIn;
  1116. OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
  1117. }
  1118. // If we are here then there is a Definition at OldIdx. OldIdxOut points
  1119. // to the segment starting there.
  1120. assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
  1121. "No def?");
  1122. VNInfo *OldIdxVNI = OldIdxOut->valno;
  1123. assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
  1124. bool OldIdxDefIsDead = OldIdxOut->end.isDead();
  1125. // Is there an existing def at NewIdx?
  1126. SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
  1127. LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
  1128. if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
  1129. assert(NewIdxOut->valno != OldIdxVNI &&
  1130. "Same value defined more than once?");
  1131. // If OldIdx was a dead def remove it.
  1132. if (!OldIdxDefIsDead) {
  1133. // Remove segment starting at NewIdx and move begin of OldIdxOut to
  1134. // NewIdx so it can take its place.
  1135. OldIdxVNI->def = NewIdxDef;
  1136. OldIdxOut->start = NewIdxDef;
  1137. LR.removeValNo(NewIdxOut->valno);
  1138. } else {
  1139. // Simply remove the dead def at OldIdx.
  1140. LR.removeValNo(OldIdxVNI);
  1141. }
  1142. } else {
  1143. // Previously nothing was live after NewIdx, so all we have to do now is
  1144. // move the begin of OldIdxOut to NewIdx.
  1145. if (!OldIdxDefIsDead) {
  1146. // Do we have any intermediate Defs between OldIdx and NewIdx?
  1147. if (OldIdxIn != E &&
  1148. SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
  1149. // OldIdx is not a dead def and NewIdx is before predecessor start.
  1150. LiveRange::iterator NewIdxIn = NewIdxOut;
  1151. assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
  1152. const SlotIndex SplitPos = NewIdxDef;
  1153. OldIdxVNI = OldIdxIn->valno;
  1154. // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
  1155. OldIdxOut->valno->def = OldIdxIn->start;
  1156. *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
  1157. OldIdxOut->valno);
  1158. // OldIdxIn and OldIdxVNI are now undef and can be overridden.
  1159. // We Slide [NewIdxIn, OldIdxIn) down one position.
  1160. // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
  1161. // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
  1162. std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
  1163. // NewIdxIn is now considered undef so we can reuse it for the moved
  1164. // value.
  1165. LiveRange::iterator NewSegment = NewIdxIn;
  1166. LiveRange::iterator Next = std::next(NewSegment);
  1167. if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
  1168. // There is no gap between NewSegment and its predecessor.
  1169. *NewSegment = LiveRange::Segment(Next->start, SplitPos,
  1170. Next->valno);
  1171. *Next = LiveRange::Segment(SplitPos, Next->end, OldIdxVNI);
  1172. Next->valno->def = SplitPos;
  1173. } else {
  1174. // There is a gap between NewSegment and its predecessor
  1175. // Value becomes live in.
  1176. *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
  1177. NewSegment->valno->def = SplitPos;
  1178. }
  1179. } else {
  1180. // Leave the end point of a live def.
  1181. OldIdxOut->start = NewIdxDef;
  1182. OldIdxVNI->def = NewIdxDef;
  1183. if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
  1184. OldIdxIn->end = NewIdx.getRegSlot();
  1185. }
  1186. } else if (OldIdxIn != E
  1187. && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx)
  1188. && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) {
  1189. // OldIdxVNI is a dead def that has been moved into the middle of
  1190. // another value in LR. That can happen when LR is a whole register,
  1191. // but the dead def is a write to a subreg that is dead at NewIdx.
  1192. // The dead def may have been moved across other values
  1193. // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
  1194. // down one position.
  1195. // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
  1196. // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
  1197. std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
  1198. // Modify the segment at NewIdxOut and the following segment to meet at
  1199. // the point of the dead def, with the following segment getting
  1200. // OldIdxVNI as its value number.
  1201. *NewIdxOut = LiveRange::Segment(
  1202. NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
  1203. *(NewIdxOut + 1) = LiveRange::Segment(
  1204. NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
  1205. OldIdxVNI->def = NewIdxDef;
  1206. // Modify subsequent segments to be defined by the moved def OldIdxVNI.
  1207. for (auto Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx)
  1208. Idx->valno = OldIdxVNI;
  1209. // Aggressively remove all dead flags from the former dead definition.
  1210. // Kill/dead flags shouldn't be used while live intervals exist; they
  1211. // will be reinserted by VirtRegRewriter.
  1212. if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx))
  1213. for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
  1214. if (MO->isReg() && !MO->isUse())
  1215. MO->setIsDead(false);
  1216. } else {
  1217. // OldIdxVNI is a dead def. It may have been moved across other values
  1218. // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
  1219. // down one position.
  1220. // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
  1221. // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
  1222. std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
  1223. // OldIdxVNI can be reused now to build a new dead def segment.
  1224. LiveRange::iterator NewSegment = NewIdxOut;
  1225. VNInfo *NewSegmentVNI = OldIdxVNI;
  1226. *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
  1227. NewSegmentVNI);
  1228. NewSegmentVNI->def = NewIdxDef;
  1229. }
  1230. }
  1231. }
  1232. void updateRegMaskSlots() {
  1233. SmallVectorImpl<SlotIndex>::iterator RI =
  1234. llvm::lower_bound(LIS.RegMaskSlots, OldIdx);
  1235. assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
  1236. "No RegMask at OldIdx.");
  1237. *RI = NewIdx.getRegSlot();
  1238. assert((RI == LIS.RegMaskSlots.begin() ||
  1239. SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
  1240. "Cannot move regmask instruction above another call");
  1241. assert((std::next(RI) == LIS.RegMaskSlots.end() ||
  1242. SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
  1243. "Cannot move regmask instruction below another call");
  1244. }
  1245. // Return the last use of reg between NewIdx and OldIdx.
  1246. SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg,
  1247. LaneBitmask LaneMask) {
  1248. if (Register::isVirtualRegister(Reg)) {
  1249. SlotIndex LastUse = Before;
  1250. for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
  1251. if (MO.isUndef())
  1252. continue;
  1253. unsigned SubReg = MO.getSubReg();
  1254. if (SubReg != 0 && LaneMask.any()
  1255. && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
  1256. continue;
  1257. const MachineInstr &MI = *MO.getParent();
  1258. SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
  1259. if (InstSlot > LastUse && InstSlot < OldIdx)
  1260. LastUse = InstSlot.getRegSlot();
  1261. }
  1262. return LastUse;
  1263. }
  1264. // This is a regunit interval, so scanning the use list could be very
  1265. // expensive. Scan upwards from OldIdx instead.
  1266. assert(Before < OldIdx && "Expected upwards move");
  1267. SlotIndexes *Indexes = LIS.getSlotIndexes();
  1268. MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
  1269. // OldIdx may not correspond to an instruction any longer, so set MII to
  1270. // point to the next instruction after OldIdx, or MBB->end().
  1271. MachineBasicBlock::iterator MII = MBB->end();
  1272. if (MachineInstr *MI = Indexes->getInstructionFromIndex(
  1273. Indexes->getNextNonNullIndex(OldIdx)))
  1274. if (MI->getParent() == MBB)
  1275. MII = MI;
  1276. MachineBasicBlock::iterator Begin = MBB->begin();
  1277. while (MII != Begin) {
  1278. if ((--MII)->isDebugInstr())
  1279. continue;
  1280. SlotIndex Idx = Indexes->getInstructionIndex(*MII);
  1281. // Stop searching when Before is reached.
  1282. if (!SlotIndex::isEarlierInstr(Before, Idx))
  1283. return Before;
  1284. // Check if MII uses Reg.
  1285. for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
  1286. if (MO->isReg() && !MO->isUndef() &&
  1287. Register::isPhysicalRegister(MO->getReg()) &&
  1288. TRI.hasRegUnit(MO->getReg(), Reg))
  1289. return Idx.getRegSlot();
  1290. }
  1291. // Didn't reach Before. It must be the first instruction in the block.
  1292. return Before;
  1293. }
  1294. };
  1295. void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
  1296. // It is fine to move a bundle as a whole, but not an individual instruction
  1297. // inside it.
  1298. assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) &&
  1299. "Cannot move instruction in bundle");
  1300. SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
  1301. Indexes->removeMachineInstrFromMaps(MI);
  1302. SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
  1303. assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
  1304. OldIndex < getMBBEndIdx(MI.getParent()) &&
  1305. "Cannot handle moves across basic block boundaries.");
  1306. HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
  1307. HME.updateAllRanges(&MI);
  1308. }
  1309. void LiveIntervals::handleMoveIntoBundle(MachineInstr &MI,
  1310. MachineInstr &BundleStart,
  1311. bool UpdateFlags) {
  1312. SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
  1313. SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
  1314. HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
  1315. HME.updateAllRanges(&MI);
  1316. }
  1317. void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
  1318. const MachineBasicBlock::iterator End,
  1319. const SlotIndex endIdx,
  1320. LiveRange &LR, const unsigned Reg,
  1321. LaneBitmask LaneMask) {
  1322. LiveInterval::iterator LII = LR.find(endIdx);
  1323. SlotIndex lastUseIdx;
  1324. if (LII == LR.begin()) {
  1325. // This happens when the function is called for a subregister that only
  1326. // occurs _after_ the range that is to be repaired.
  1327. return;
  1328. }
  1329. if (LII != LR.end() && LII->start < endIdx)
  1330. lastUseIdx = LII->end;
  1331. else
  1332. --LII;
  1333. for (MachineBasicBlock::iterator I = End; I != Begin;) {
  1334. --I;
  1335. MachineInstr &MI = *I;
  1336. if (MI.isDebugInstr())
  1337. continue;
  1338. SlotIndex instrIdx = getInstructionIndex(MI);
  1339. bool isStartValid = getInstructionFromIndex(LII->start);
  1340. bool isEndValid = getInstructionFromIndex(LII->end);
  1341. // FIXME: This doesn't currently handle early-clobber or multiple removed
  1342. // defs inside of the region to repair.
  1343. for (MachineInstr::mop_iterator OI = MI.operands_begin(),
  1344. OE = MI.operands_end();
  1345. OI != OE; ++OI) {
  1346. const MachineOperand &MO = *OI;
  1347. if (!MO.isReg() || MO.getReg() != Reg)
  1348. continue;
  1349. unsigned SubReg = MO.getSubReg();
  1350. LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
  1351. if ((Mask & LaneMask).none())
  1352. continue;
  1353. if (MO.isDef()) {
  1354. if (!isStartValid) {
  1355. if (LII->end.isDead()) {
  1356. SlotIndex prevStart;
  1357. if (LII != LR.begin())
  1358. prevStart = std::prev(LII)->start;
  1359. // FIXME: This could be more efficient if there was a
  1360. // removeSegment method that returned an iterator.
  1361. LR.removeSegment(*LII, true);
  1362. if (prevStart.isValid())
  1363. LII = LR.find(prevStart);
  1364. else
  1365. LII = LR.begin();
  1366. } else {
  1367. LII->start = instrIdx.getRegSlot();
  1368. LII->valno->def = instrIdx.getRegSlot();
  1369. if (MO.getSubReg() && !MO.isUndef())
  1370. lastUseIdx = instrIdx.getRegSlot();
  1371. else
  1372. lastUseIdx = SlotIndex();
  1373. continue;
  1374. }
  1375. }
  1376. if (!lastUseIdx.isValid()) {
  1377. VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
  1378. LiveRange::Segment S(instrIdx.getRegSlot(),
  1379. instrIdx.getDeadSlot(), VNI);
  1380. LII = LR.addSegment(S);
  1381. } else if (LII->start != instrIdx.getRegSlot()) {
  1382. VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
  1383. LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
  1384. LII = LR.addSegment(S);
  1385. }
  1386. if (MO.getSubReg() && !MO.isUndef())
  1387. lastUseIdx = instrIdx.getRegSlot();
  1388. else
  1389. lastUseIdx = SlotIndex();
  1390. } else if (MO.isUse()) {
  1391. // FIXME: This should probably be handled outside of this branch,
  1392. // either as part of the def case (for defs inside of the region) or
  1393. // after the loop over the region.
  1394. if (!isEndValid && !LII->end.isBlock())
  1395. LII->end = instrIdx.getRegSlot();
  1396. if (!lastUseIdx.isValid())
  1397. lastUseIdx = instrIdx.getRegSlot();
  1398. }
  1399. }
  1400. }
  1401. }
  1402. void
  1403. LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB,
  1404. MachineBasicBlock::iterator Begin,
  1405. MachineBasicBlock::iterator End,
  1406. ArrayRef<unsigned> OrigRegs) {
  1407. // Find anchor points, which are at the beginning/end of blocks or at
  1408. // instructions that already have indexes.
  1409. while (Begin != MBB->begin() && !Indexes->hasIndex(*Begin))
  1410. --Begin;
  1411. while (End != MBB->end() && !Indexes->hasIndex(*End))
  1412. ++End;
  1413. SlotIndex endIdx;
  1414. if (End == MBB->end())
  1415. endIdx = getMBBEndIdx(MBB).getPrevSlot();
  1416. else
  1417. endIdx = getInstructionIndex(*End);
  1418. Indexes->repairIndexesInRange(MBB, Begin, End);
  1419. for (MachineBasicBlock::iterator I = End; I != Begin;) {
  1420. --I;
  1421. MachineInstr &MI = *I;
  1422. if (MI.isDebugInstr())
  1423. continue;
  1424. for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
  1425. MOE = MI.operands_end();
  1426. MOI != MOE; ++MOI) {
  1427. if (MOI->isReg() && Register::isVirtualRegister(MOI->getReg()) &&
  1428. !hasInterval(MOI->getReg())) {
  1429. createAndComputeVirtRegInterval(MOI->getReg());
  1430. }
  1431. }
  1432. }
  1433. for (unsigned Reg : OrigRegs) {
  1434. if (!Register::isVirtualRegister(Reg))
  1435. continue;
  1436. LiveInterval &LI = getInterval(Reg);
  1437. // FIXME: Should we support undefs that gain defs?
  1438. if (!LI.hasAtLeastOneValue())
  1439. continue;
  1440. for (LiveInterval::SubRange &S : LI.subranges())
  1441. repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
  1442. repairOldRegInRange(Begin, End, endIdx, LI, Reg);
  1443. }
  1444. }
  1445. void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) {
  1446. for (MCRegUnitIterator Unit(Reg, TRI); Unit.isValid(); ++Unit) {
  1447. if (LiveRange *LR = getCachedRegUnit(*Unit))
  1448. if (VNInfo *VNI = LR->getVNInfoAt(Pos))
  1449. LR->removeValNo(VNI);
  1450. }
  1451. }
  1452. void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) {
  1453. // LI may not have the main range computed yet, but its subranges may
  1454. // be present.
  1455. VNInfo *VNI = LI.getVNInfoAt(Pos);
  1456. if (VNI != nullptr) {
  1457. assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
  1458. LI.removeValNo(VNI);
  1459. }
  1460. // Also remove the value defined in subranges.
  1461. for (LiveInterval::SubRange &S : LI.subranges()) {
  1462. if (VNInfo *SVNI = S.getVNInfoAt(Pos))
  1463. if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
  1464. S.removeValNo(SVNI);
  1465. }
  1466. LI.removeEmptySubRanges();
  1467. }
  1468. void LiveIntervals::splitSeparateComponents(LiveInterval &LI,
  1469. SmallVectorImpl<LiveInterval*> &SplitLIs) {
  1470. ConnectedVNInfoEqClasses ConEQ(*this);
  1471. unsigned NumComp = ConEQ.Classify(LI);
  1472. if (NumComp <= 1)
  1473. return;
  1474. LLVM_DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n');
  1475. unsigned Reg = LI.reg;
  1476. const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
  1477. for (unsigned I = 1; I < NumComp; ++I) {
  1478. Register NewVReg = MRI->createVirtualRegister(RegClass);
  1479. LiveInterval &NewLI = createEmptyInterval(NewVReg);
  1480. SplitLIs.push_back(&NewLI);
  1481. }
  1482. ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
  1483. }
  1484. void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) {
  1485. assert(LRCalc && "LRCalc not initialized.");
  1486. LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
  1487. LRCalc->constructMainRangeFromSubranges(LI);
  1488. }