LiveIntervalAnalysis.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the LiveInterval analysis pass which is used
  11. // by the Linear Scan Register allocator. This pass linearizes the
  12. // basic blocks of the function in DFS order and uses the
  13. // LiveVariables pass to conservatively compute live intervals for
  14. // each virtual and physical register.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #define DEBUG_TYPE "liveintervals"
  18. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  19. #include "VirtRegMap.h"
  20. #include "llvm/Value.h"
  21. #include "llvm/CodeGen/LiveVariables.h"
  22. #include "llvm/CodeGen/MachineFrameInfo.h"
  23. #include "llvm/CodeGen/MachineInstr.h"
  24. #include "llvm/CodeGen/MachineLoopInfo.h"
  25. #include "llvm/CodeGen/MachineRegisterInfo.h"
  26. #include "llvm/CodeGen/Passes.h"
  27. #include "llvm/Target/MRegisterInfo.h"
  28. #include "llvm/Target/TargetInstrInfo.h"
  29. #include "llvm/Target/TargetMachine.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/ADT/Statistic.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include <algorithm>
  35. #include <cmath>
  36. using namespace llvm;
  37. namespace {
  38. // Hidden options for help debugging.
  39. cl::opt<bool> DisableReMat("disable-rematerialization",
  40. cl::init(false), cl::Hidden);
  41. cl::opt<bool> SplitAtBB("split-intervals-at-bb",
  42. cl::init(true), cl::Hidden);
  43. cl::opt<int> SplitLimit("split-limit",
  44. cl::init(-1), cl::Hidden);
  45. }
  46. STATISTIC(numIntervals, "Number of original intervals");
  47. STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
  48. STATISTIC(numFolds , "Number of loads/stores folded into instructions");
  49. STATISTIC(numSplits , "Number of intervals split");
  50. char LiveIntervals::ID = 0;
  51. namespace {
  52. RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
  53. }
  54. void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
  55. AU.addPreserved<LiveVariables>();
  56. AU.addRequired<LiveVariables>();
  57. AU.addPreservedID(MachineLoopInfoID);
  58. AU.addPreservedID(MachineDominatorsID);
  59. AU.addPreservedID(PHIEliminationID);
  60. AU.addRequiredID(PHIEliminationID);
  61. AU.addRequiredID(TwoAddressInstructionPassID);
  62. MachineFunctionPass::getAnalysisUsage(AU);
  63. }
  64. void LiveIntervals::releaseMemory() {
  65. Idx2MBBMap.clear();
  66. mi2iMap_.clear();
  67. i2miMap_.clear();
  68. r2iMap_.clear();
  69. // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
  70. VNInfoAllocator.Reset();
  71. for (unsigned i = 0, e = ClonedMIs.size(); i != e; ++i)
  72. delete ClonedMIs[i];
  73. }
  74. namespace llvm {
  75. inline bool operator<(unsigned V, const IdxMBBPair &IM) {
  76. return V < IM.first;
  77. }
  78. inline bool operator<(const IdxMBBPair &IM, unsigned V) {
  79. return IM.first < V;
  80. }
  81. struct Idx2MBBCompare {
  82. bool operator()(const IdxMBBPair &LHS, const IdxMBBPair &RHS) const {
  83. return LHS.first < RHS.first;
  84. }
  85. };
  86. }
  87. /// runOnMachineFunction - Register allocate the whole function
  88. ///
  89. bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
  90. mf_ = &fn;
  91. tm_ = &fn.getTarget();
  92. mri_ = tm_->getRegisterInfo();
  93. tii_ = tm_->getInstrInfo();
  94. lv_ = &getAnalysis<LiveVariables>();
  95. allocatableRegs_ = mri_->getAllocatableSet(fn);
  96. // Number MachineInstrs and MachineBasicBlocks.
  97. // Initialize MBB indexes to a sentinal.
  98. MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
  99. unsigned MIIndex = 0;
  100. for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
  101. MBB != E; ++MBB) {
  102. unsigned StartIdx = MIIndex;
  103. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  104. I != E; ++I) {
  105. bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
  106. assert(inserted && "multiple MachineInstr -> index mappings");
  107. i2miMap_.push_back(I);
  108. MIIndex += InstrSlots::NUM;
  109. }
  110. // Set the MBB2IdxMap entry for this MBB.
  111. MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
  112. Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
  113. }
  114. std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
  115. computeIntervals();
  116. numIntervals += getNumIntervals();
  117. DOUT << "********** INTERVALS **********\n";
  118. for (iterator I = begin(), E = end(); I != E; ++I) {
  119. I->second.print(DOUT, mri_);
  120. DOUT << "\n";
  121. }
  122. numIntervalsAfter += getNumIntervals();
  123. DEBUG(dump());
  124. return true;
  125. }
  126. /// print - Implement the dump method.
  127. void LiveIntervals::print(std::ostream &O, const Module* ) const {
  128. O << "********** INTERVALS **********\n";
  129. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  130. I->second.print(DOUT, mri_);
  131. DOUT << "\n";
  132. }
  133. O << "********** MACHINEINSTRS **********\n";
  134. for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
  135. mbbi != mbbe; ++mbbi) {
  136. O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
  137. for (MachineBasicBlock::iterator mii = mbbi->begin(),
  138. mie = mbbi->end(); mii != mie; ++mii) {
  139. O << getInstructionIndex(mii) << '\t' << *mii;
  140. }
  141. }
  142. }
  143. /// conflictsWithPhysRegDef - Returns true if the specified register
  144. /// is defined during the duration of the specified interval.
  145. bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
  146. VirtRegMap &vrm, unsigned reg) {
  147. for (LiveInterval::Ranges::const_iterator
  148. I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
  149. for (unsigned index = getBaseIndex(I->start),
  150. end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
  151. index += InstrSlots::NUM) {
  152. // skip deleted instructions
  153. while (index != end && !getInstructionFromIndex(index))
  154. index += InstrSlots::NUM;
  155. if (index == end) break;
  156. MachineInstr *MI = getInstructionFromIndex(index);
  157. unsigned SrcReg, DstReg;
  158. if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
  159. if (SrcReg == li.reg || DstReg == li.reg)
  160. continue;
  161. for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
  162. MachineOperand& mop = MI->getOperand(i);
  163. if (!mop.isRegister())
  164. continue;
  165. unsigned PhysReg = mop.getReg();
  166. if (PhysReg == 0 || PhysReg == li.reg)
  167. continue;
  168. if (MRegisterInfo::isVirtualRegister(PhysReg)) {
  169. if (!vrm.hasPhys(PhysReg))
  170. continue;
  171. PhysReg = vrm.getPhys(PhysReg);
  172. }
  173. if (PhysReg && mri_->regsOverlap(PhysReg, reg))
  174. return true;
  175. }
  176. }
  177. }
  178. return false;
  179. }
  180. void LiveIntervals::printRegName(unsigned reg) const {
  181. if (MRegisterInfo::isPhysicalRegister(reg))
  182. cerr << mri_->getName(reg);
  183. else
  184. cerr << "%reg" << reg;
  185. }
  186. void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
  187. MachineBasicBlock::iterator mi,
  188. unsigned MIIdx,
  189. LiveInterval &interval) {
  190. DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
  191. LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
  192. // Virtual registers may be defined multiple times (due to phi
  193. // elimination and 2-addr elimination). Much of what we do only has to be
  194. // done once for the vreg. We use an empty interval to detect the first
  195. // time we see a vreg.
  196. if (interval.empty()) {
  197. // Get the Idx of the defining instructions.
  198. unsigned defIndex = getDefIndex(MIIdx);
  199. VNInfo *ValNo;
  200. unsigned SrcReg, DstReg;
  201. if (tii_->isMoveInstr(*mi, SrcReg, DstReg))
  202. ValNo = interval.getNextValue(defIndex, SrcReg, VNInfoAllocator);
  203. else if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
  204. ValNo = interval.getNextValue(defIndex, mi->getOperand(1).getReg(),
  205. VNInfoAllocator);
  206. else
  207. ValNo = interval.getNextValue(defIndex, 0, VNInfoAllocator);
  208. assert(ValNo->id == 0 && "First value in interval is not 0?");
  209. // Loop over all of the blocks that the vreg is defined in. There are
  210. // two cases we have to handle here. The most common case is a vreg
  211. // whose lifetime is contained within a basic block. In this case there
  212. // will be a single kill, in MBB, which comes after the definition.
  213. if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
  214. // FIXME: what about dead vars?
  215. unsigned killIdx;
  216. if (vi.Kills[0] != mi)
  217. killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
  218. else
  219. killIdx = defIndex+1;
  220. // If the kill happens after the definition, we have an intra-block
  221. // live range.
  222. if (killIdx > defIndex) {
  223. assert(vi.AliveBlocks.none() &&
  224. "Shouldn't be alive across any blocks!");
  225. LiveRange LR(defIndex, killIdx, ValNo);
  226. interval.addRange(LR);
  227. DOUT << " +" << LR << "\n";
  228. interval.addKill(ValNo, killIdx);
  229. return;
  230. }
  231. }
  232. // The other case we handle is when a virtual register lives to the end
  233. // of the defining block, potentially live across some blocks, then is
  234. // live into some number of blocks, but gets killed. Start by adding a
  235. // range that goes from this definition to the end of the defining block.
  236. LiveRange NewLR(defIndex,
  237. getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
  238. ValNo);
  239. DOUT << " +" << NewLR;
  240. interval.addRange(NewLR);
  241. // Iterate over all of the blocks that the variable is completely
  242. // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
  243. // live interval.
  244. for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
  245. if (vi.AliveBlocks[i]) {
  246. MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
  247. if (!MBB->empty()) {
  248. LiveRange LR(getMBBStartIdx(i),
  249. getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
  250. ValNo);
  251. interval.addRange(LR);
  252. DOUT << " +" << LR;
  253. }
  254. }
  255. }
  256. // Finally, this virtual register is live from the start of any killing
  257. // block to the 'use' slot of the killing instruction.
  258. for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
  259. MachineInstr *Kill = vi.Kills[i];
  260. unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
  261. LiveRange LR(getMBBStartIdx(Kill->getParent()),
  262. killIdx, ValNo);
  263. interval.addRange(LR);
  264. interval.addKill(ValNo, killIdx);
  265. DOUT << " +" << LR;
  266. }
  267. } else {
  268. // If this is the second time we see a virtual register definition, it
  269. // must be due to phi elimination or two addr elimination. If this is
  270. // the result of two address elimination, then the vreg is one of the
  271. // def-and-use register operand.
  272. if (mi->isRegReDefinedByTwoAddr(interval.reg)) {
  273. // If this is a two-address definition, then we have already processed
  274. // the live range. The only problem is that we didn't realize there
  275. // are actually two values in the live interval. Because of this we
  276. // need to take the LiveRegion that defines this register and split it
  277. // into two values.
  278. unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
  279. unsigned RedefIndex = getDefIndex(MIIdx);
  280. const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
  281. VNInfo *OldValNo = OldLR->valno;
  282. unsigned OldEnd = OldLR->end;
  283. // Delete the initial value, which should be short and continuous,
  284. // because the 2-addr copy must be in the same MBB as the redef.
  285. interval.removeRange(DefIndex, RedefIndex);
  286. // Two-address vregs should always only be redefined once. This means
  287. // that at this point, there should be exactly one value number in it.
  288. assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
  289. // The new value number (#1) is defined by the instruction we claimed
  290. // defined value #0.
  291. VNInfo *ValNo = interval.getNextValue(0, 0, VNInfoAllocator);
  292. interval.copyValNumInfo(ValNo, OldValNo);
  293. // Value#0 is now defined by the 2-addr instruction.
  294. OldValNo->def = RedefIndex;
  295. OldValNo->reg = 0;
  296. // Add the new live interval which replaces the range for the input copy.
  297. LiveRange LR(DefIndex, RedefIndex, ValNo);
  298. DOUT << " replace range with " << LR;
  299. interval.addRange(LR);
  300. interval.addKill(ValNo, RedefIndex);
  301. interval.removeKills(ValNo, RedefIndex, OldEnd);
  302. // If this redefinition is dead, we need to add a dummy unit live
  303. // range covering the def slot.
  304. if (lv_->RegisterDefIsDead(mi, interval.reg))
  305. interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
  306. DOUT << " RESULT: ";
  307. interval.print(DOUT, mri_);
  308. } else {
  309. // Otherwise, this must be because of phi elimination. If this is the
  310. // first redefinition of the vreg that we have seen, go back and change
  311. // the live range in the PHI block to be a different value number.
  312. if (interval.containsOneValue()) {
  313. assert(vi.Kills.size() == 1 &&
  314. "PHI elimination vreg should have one kill, the PHI itself!");
  315. // Remove the old range that we now know has an incorrect number.
  316. VNInfo *VNI = interval.getValNumInfo(0);
  317. MachineInstr *Killer = vi.Kills[0];
  318. unsigned Start = getMBBStartIdx(Killer->getParent());
  319. unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
  320. DOUT << " Removing [" << Start << "," << End << "] from: ";
  321. interval.print(DOUT, mri_); DOUT << "\n";
  322. interval.removeRange(Start, End);
  323. interval.addKill(VNI, Start);
  324. VNI->hasPHIKill = true;
  325. DOUT << " RESULT: "; interval.print(DOUT, mri_);
  326. // Replace the interval with one of a NEW value number. Note that this
  327. // value number isn't actually defined by an instruction, weird huh? :)
  328. LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
  329. DOUT << " replace range with " << LR;
  330. interval.addRange(LR);
  331. interval.addKill(LR.valno, End);
  332. DOUT << " RESULT: "; interval.print(DOUT, mri_);
  333. }
  334. // In the case of PHI elimination, each variable definition is only
  335. // live until the end of the block. We've already taken care of the
  336. // rest of the live range.
  337. unsigned defIndex = getDefIndex(MIIdx);
  338. VNInfo *ValNo;
  339. unsigned SrcReg, DstReg;
  340. if (tii_->isMoveInstr(*mi, SrcReg, DstReg))
  341. ValNo = interval.getNextValue(defIndex, SrcReg, VNInfoAllocator);
  342. else if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
  343. ValNo = interval.getNextValue(defIndex, mi->getOperand(1).getReg(),
  344. VNInfoAllocator);
  345. else
  346. ValNo = interval.getNextValue(defIndex, 0, VNInfoAllocator);
  347. unsigned killIndex = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
  348. LiveRange LR(defIndex, killIndex, ValNo);
  349. interval.addRange(LR);
  350. interval.addKill(ValNo, killIndex);
  351. ValNo->hasPHIKill = true;
  352. DOUT << " +" << LR;
  353. }
  354. }
  355. DOUT << '\n';
  356. }
  357. void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
  358. MachineBasicBlock::iterator mi,
  359. unsigned MIIdx,
  360. LiveInterval &interval,
  361. unsigned SrcReg) {
  362. // A physical register cannot be live across basic block, so its
  363. // lifetime must end somewhere in its defining basic block.
  364. DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
  365. unsigned baseIndex = MIIdx;
  366. unsigned start = getDefIndex(baseIndex);
  367. unsigned end = start;
  368. // If it is not used after definition, it is considered dead at
  369. // the instruction defining it. Hence its interval is:
  370. // [defSlot(def), defSlot(def)+1)
  371. if (lv_->RegisterDefIsDead(mi, interval.reg)) {
  372. DOUT << " dead";
  373. end = getDefIndex(start) + 1;
  374. goto exit;
  375. }
  376. // If it is not dead on definition, it must be killed by a
  377. // subsequent instruction. Hence its interval is:
  378. // [defSlot(def), useSlot(kill)+1)
  379. while (++mi != MBB->end()) {
  380. baseIndex += InstrSlots::NUM;
  381. if (lv_->KillsRegister(mi, interval.reg)) {
  382. DOUT << " killed";
  383. end = getUseIndex(baseIndex) + 1;
  384. goto exit;
  385. } else if (lv_->ModifiesRegister(mi, interval.reg)) {
  386. // Another instruction redefines the register before it is ever read.
  387. // Then the register is essentially dead at the instruction that defines
  388. // it. Hence its interval is:
  389. // [defSlot(def), defSlot(def)+1)
  390. DOUT << " dead";
  391. end = getDefIndex(start) + 1;
  392. goto exit;
  393. }
  394. }
  395. // The only case we should have a dead physreg here without a killing or
  396. // instruction where we know it's dead is if it is live-in to the function
  397. // and never used.
  398. assert(!SrcReg && "physreg was not killed in defining block!");
  399. end = getDefIndex(start) + 1; // It's dead.
  400. exit:
  401. assert(start < end && "did not find end of interval?");
  402. // Already exists? Extend old live interval.
  403. LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
  404. VNInfo *ValNo = (OldLR != interval.end())
  405. ? OldLR->valno : interval.getNextValue(start, SrcReg, VNInfoAllocator);
  406. LiveRange LR(start, end, ValNo);
  407. interval.addRange(LR);
  408. interval.addKill(LR.valno, end);
  409. DOUT << " +" << LR << '\n';
  410. }
  411. void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
  412. MachineBasicBlock::iterator MI,
  413. unsigned MIIdx,
  414. unsigned reg) {
  415. if (MRegisterInfo::isVirtualRegister(reg))
  416. handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
  417. else if (allocatableRegs_[reg]) {
  418. unsigned SrcReg, DstReg;
  419. if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
  420. SrcReg = MI->getOperand(1).getReg();
  421. else if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
  422. SrcReg = 0;
  423. handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
  424. // Def of a register also defines its sub-registers.
  425. for (const unsigned* AS = mri_->getSubRegisters(reg); *AS; ++AS)
  426. // Avoid processing some defs more than once.
  427. if (!MI->findRegisterDefOperand(*AS))
  428. handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
  429. }
  430. }
  431. void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
  432. unsigned MIIdx,
  433. LiveInterval &interval, bool isAlias) {
  434. DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
  435. // Look for kills, if it reaches a def before it's killed, then it shouldn't
  436. // be considered a livein.
  437. MachineBasicBlock::iterator mi = MBB->begin();
  438. unsigned baseIndex = MIIdx;
  439. unsigned start = baseIndex;
  440. unsigned end = start;
  441. while (mi != MBB->end()) {
  442. if (lv_->KillsRegister(mi, interval.reg)) {
  443. DOUT << " killed";
  444. end = getUseIndex(baseIndex) + 1;
  445. goto exit;
  446. } else if (lv_->ModifiesRegister(mi, interval.reg)) {
  447. // Another instruction redefines the register before it is ever read.
  448. // Then the register is essentially dead at the instruction that defines
  449. // it. Hence its interval is:
  450. // [defSlot(def), defSlot(def)+1)
  451. DOUT << " dead";
  452. end = getDefIndex(start) + 1;
  453. goto exit;
  454. }
  455. baseIndex += InstrSlots::NUM;
  456. ++mi;
  457. }
  458. exit:
  459. // Live-in register might not be used at all.
  460. if (end == MIIdx) {
  461. if (isAlias) {
  462. DOUT << " dead";
  463. end = getDefIndex(MIIdx) + 1;
  464. } else {
  465. DOUT << " live through";
  466. end = baseIndex;
  467. }
  468. }
  469. LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
  470. interval.addRange(LR);
  471. interval.addKill(LR.valno, end);
  472. DOUT << " +" << LR << '\n';
  473. }
  474. /// computeIntervals - computes the live intervals for virtual
  475. /// registers. for some ordering of the machine instructions [1,N] a
  476. /// live interval is an interval [i, j) where 1 <= i <= j < N for
  477. /// which a variable is live
  478. void LiveIntervals::computeIntervals() {
  479. DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
  480. << "********** Function: "
  481. << ((Value*)mf_->getFunction())->getName() << '\n';
  482. // Track the index of the current machine instr.
  483. unsigned MIIndex = 0;
  484. for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
  485. MBBI != E; ++MBBI) {
  486. MachineBasicBlock *MBB = MBBI;
  487. DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
  488. MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
  489. // Create intervals for live-ins to this BB first.
  490. for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
  491. LE = MBB->livein_end(); LI != LE; ++LI) {
  492. handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
  493. // Multiple live-ins can alias the same register.
  494. for (const unsigned* AS = mri_->getSubRegisters(*LI); *AS; ++AS)
  495. if (!hasInterval(*AS))
  496. handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
  497. true);
  498. }
  499. for (; MI != miEnd; ++MI) {
  500. DOUT << MIIndex << "\t" << *MI;
  501. // Handle defs.
  502. for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
  503. MachineOperand &MO = MI->getOperand(i);
  504. // handle register defs - build intervals
  505. if (MO.isRegister() && MO.getReg() && MO.isDef())
  506. handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
  507. }
  508. MIIndex += InstrSlots::NUM;
  509. }
  510. }
  511. }
  512. bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
  513. SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
  514. std::vector<IdxMBBPair>::const_iterator I =
  515. std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
  516. bool ResVal = false;
  517. while (I != Idx2MBBMap.end()) {
  518. if (LR.end <= I->first)
  519. break;
  520. MBBs.push_back(I->second);
  521. ResVal = true;
  522. ++I;
  523. }
  524. return ResVal;
  525. }
  526. LiveInterval LiveIntervals::createInterval(unsigned reg) {
  527. float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
  528. HUGE_VALF : 0.0F;
  529. return LiveInterval(reg, Weight);
  530. }
  531. //===----------------------------------------------------------------------===//
  532. // Register allocator hooks.
  533. //
  534. /// isReMaterializable - Returns true if the definition MI of the specified
  535. /// val# of the specified interval is re-materializable.
  536. bool LiveIntervals::isReMaterializable(const LiveInterval &li,
  537. const VNInfo *ValNo, MachineInstr *MI,
  538. bool &isLoad) {
  539. if (DisableReMat)
  540. return false;
  541. isLoad = false;
  542. const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
  543. if ((TID->Flags & M_IMPLICIT_DEF_FLAG) ||
  544. tii_->isTriviallyReMaterializable(MI)) {
  545. isLoad = TID->Flags & M_LOAD_FLAG;
  546. return true;
  547. }
  548. int FrameIdx = 0;
  549. if (!tii_->isLoadFromStackSlot(MI, FrameIdx) ||
  550. !mf_->getFrameInfo()->isFixedObjectIndex(FrameIdx))
  551. return false;
  552. // This is a load from fixed stack slot. It can be rematerialized unless it's
  553. // re-defined by a two-address instruction.
  554. isLoad = true;
  555. for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
  556. i != e; ++i) {
  557. const VNInfo *VNI = *i;
  558. if (VNI == ValNo)
  559. continue;
  560. unsigned DefIdx = VNI->def;
  561. if (DefIdx == ~1U)
  562. continue; // Dead val#.
  563. MachineInstr *DefMI = (DefIdx == ~0u)
  564. ? NULL : getInstructionFromIndex(DefIdx);
  565. if (DefMI && DefMI->isRegReDefinedByTwoAddr(li.reg)) {
  566. isLoad = false;
  567. return false;
  568. }
  569. }
  570. return true;
  571. }
  572. /// isReMaterializable - Returns true if every definition of MI of every
  573. /// val# of the specified interval is re-materializable.
  574. bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
  575. isLoad = false;
  576. for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
  577. i != e; ++i) {
  578. const VNInfo *VNI = *i;
  579. unsigned DefIdx = VNI->def;
  580. if (DefIdx == ~1U)
  581. continue; // Dead val#.
  582. // Is the def for the val# rematerializable?
  583. if (DefIdx == ~0u)
  584. return false;
  585. MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
  586. bool DefIsLoad = false;
  587. if (!ReMatDefMI || !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
  588. return false;
  589. isLoad |= DefIsLoad;
  590. }
  591. return true;
  592. }
  593. /// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
  594. /// slot / to reg or any rematerialized load into ith operand of specified
  595. /// MI. If it is successul, MI is updated with the newly created MI and
  596. /// returns true.
  597. bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
  598. VirtRegMap &vrm, MachineInstr *DefMI,
  599. unsigned InstrIdx,
  600. SmallVector<unsigned, 2> &Ops,
  601. bool isSS, int Slot, unsigned Reg) {
  602. unsigned MRInfo = 0;
  603. const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
  604. // If it is an implicit def instruction, just delete it.
  605. if (TID->Flags & M_IMPLICIT_DEF_FLAG) {
  606. RemoveMachineInstrFromMaps(MI);
  607. vrm.RemoveMachineInstrFromMaps(MI);
  608. MI->eraseFromParent();
  609. ++numFolds;
  610. return true;
  611. }
  612. SmallVector<unsigned, 2> FoldOps;
  613. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  614. unsigned OpIdx = Ops[i];
  615. // FIXME: fold subreg use.
  616. if (MI->getOperand(OpIdx).getSubReg())
  617. return false;
  618. if (MI->getOperand(OpIdx).isDef())
  619. MRInfo |= (unsigned)VirtRegMap::isMod;
  620. else {
  621. // Filter out two-address use operand(s).
  622. if (TID->getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
  623. MRInfo = VirtRegMap::isModRef;
  624. continue;
  625. }
  626. MRInfo |= (unsigned)VirtRegMap::isRef;
  627. }
  628. FoldOps.push_back(OpIdx);
  629. }
  630. MachineInstr *fmi = isSS ? mri_->foldMemoryOperand(MI, FoldOps, Slot)
  631. : mri_->foldMemoryOperand(MI, FoldOps, DefMI);
  632. if (fmi) {
  633. // Attempt to fold the memory reference into the instruction. If
  634. // we can do this, we don't need to insert spill code.
  635. if (lv_)
  636. lv_->instructionChanged(MI, fmi);
  637. else
  638. LiveVariables::transferKillDeadInfo(MI, fmi, mri_);
  639. MachineBasicBlock &MBB = *MI->getParent();
  640. if (isSS && !mf_->getFrameInfo()->isFixedObjectIndex(Slot))
  641. vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
  642. vrm.transferSpillPts(MI, fmi);
  643. vrm.transferRestorePts(MI, fmi);
  644. mi2iMap_.erase(MI);
  645. i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
  646. mi2iMap_[fmi] = InstrIdx;
  647. MI = MBB.insert(MBB.erase(MI), fmi);
  648. ++numFolds;
  649. return true;
  650. }
  651. return false;
  652. }
  653. /// canFoldMemoryOperand - Returns true if the specified load / store
  654. /// folding is possible.
  655. bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
  656. SmallVector<unsigned, 2> &Ops) const {
  657. SmallVector<unsigned, 2> FoldOps;
  658. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  659. unsigned OpIdx = Ops[i];
  660. // FIXME: fold subreg use.
  661. if (MI->getOperand(OpIdx).getSubReg())
  662. return false;
  663. FoldOps.push_back(OpIdx);
  664. }
  665. return mri_->canFoldMemoryOperand(MI, FoldOps);
  666. }
  667. bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
  668. SmallPtrSet<MachineBasicBlock*, 4> MBBs;
  669. for (LiveInterval::Ranges::const_iterator
  670. I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
  671. std::vector<IdxMBBPair>::const_iterator II =
  672. std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
  673. if (II == Idx2MBBMap.end())
  674. continue;
  675. if (I->end > II->first) // crossing a MBB.
  676. return false;
  677. MBBs.insert(II->second);
  678. if (MBBs.size() > 1)
  679. return false;
  680. }
  681. return true;
  682. }
  683. /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
  684. /// for addIntervalsForSpills to rewrite uses / defs for the given live range.
  685. bool LiveIntervals::
  686. rewriteInstructionForSpills(const LiveInterval &li, bool TrySplit,
  687. unsigned id, unsigned index, unsigned end, MachineInstr *MI,
  688. MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
  689. unsigned Slot, int LdSlot,
  690. bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
  691. VirtRegMap &vrm, MachineRegisterInfo &RegInfo,
  692. const TargetRegisterClass* rc,
  693. SmallVector<int, 4> &ReMatIds,
  694. unsigned &NewVReg, bool &HasDef, bool &HasUse,
  695. const MachineLoopInfo *loopInfo,
  696. std::map<unsigned,unsigned> &MBBVRegsMap,
  697. std::vector<LiveInterval*> &NewLIs) {
  698. bool CanFold = false;
  699. RestartInstruction:
  700. for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
  701. MachineOperand& mop = MI->getOperand(i);
  702. if (!mop.isRegister())
  703. continue;
  704. unsigned Reg = mop.getReg();
  705. unsigned RegI = Reg;
  706. if (Reg == 0 || MRegisterInfo::isPhysicalRegister(Reg))
  707. continue;
  708. if (Reg != li.reg)
  709. continue;
  710. bool TryFold = !DefIsReMat;
  711. bool FoldSS = true; // Default behavior unless it's a remat.
  712. int FoldSlot = Slot;
  713. if (DefIsReMat) {
  714. // If this is the rematerializable definition MI itself and
  715. // all of its uses are rematerialized, simply delete it.
  716. if (MI == ReMatOrigDefMI && CanDelete) {
  717. DOUT << "\t\t\t\tErasing re-materlizable def: ";
  718. DOUT << MI << '\n';
  719. RemoveMachineInstrFromMaps(MI);
  720. vrm.RemoveMachineInstrFromMaps(MI);
  721. MI->eraseFromParent();
  722. break;
  723. }
  724. // If def for this use can't be rematerialized, then try folding.
  725. // If def is rematerializable and it's a load, also try folding.
  726. TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
  727. if (isLoad) {
  728. // Try fold loads (from stack slot, constant pool, etc.) into uses.
  729. FoldSS = isLoadSS;
  730. FoldSlot = LdSlot;
  731. }
  732. }
  733. // Scan all of the operands of this instruction rewriting operands
  734. // to use NewVReg instead of li.reg as appropriate. We do this for
  735. // two reasons:
  736. //
  737. // 1. If the instr reads the same spilled vreg multiple times, we
  738. // want to reuse the NewVReg.
  739. // 2. If the instr is a two-addr instruction, we are required to
  740. // keep the src/dst regs pinned.
  741. //
  742. // Keep track of whether we replace a use and/or def so that we can
  743. // create the spill interval with the appropriate range.
  744. HasUse = mop.isUse();
  745. HasDef = mop.isDef();
  746. SmallVector<unsigned, 2> Ops;
  747. Ops.push_back(i);
  748. for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
  749. const MachineOperand &MOj = MI->getOperand(j);
  750. if (!MOj.isRegister())
  751. continue;
  752. unsigned RegJ = MOj.getReg();
  753. if (RegJ == 0 || MRegisterInfo::isPhysicalRegister(RegJ))
  754. continue;
  755. if (RegJ == RegI) {
  756. Ops.push_back(j);
  757. HasUse |= MOj.isUse();
  758. HasDef |= MOj.isDef();
  759. }
  760. }
  761. if (TryFold) {
  762. // Do not fold load / store here if we are splitting. We'll find an
  763. // optimal point to insert a load / store later.
  764. if (!TrySplit) {
  765. if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
  766. Ops, FoldSS, FoldSlot, Reg)) {
  767. // Folding the load/store can completely change the instruction in
  768. // unpredictable ways, rescan it from the beginning.
  769. HasUse = false;
  770. HasDef = false;
  771. CanFold = false;
  772. goto RestartInstruction;
  773. }
  774. } else {
  775. CanFold = canFoldMemoryOperand(MI, Ops);
  776. }
  777. } else
  778. CanFold = false;
  779. // Create a new virtual register for the spill interval.
  780. bool CreatedNewVReg = false;
  781. if (NewVReg == 0) {
  782. NewVReg = RegInfo.createVirtualRegister(rc);
  783. vrm.grow();
  784. CreatedNewVReg = true;
  785. }
  786. mop.setReg(NewVReg);
  787. // Reuse NewVReg for other reads.
  788. for (unsigned j = 0, e = Ops.size(); j != e; ++j)
  789. MI->getOperand(Ops[j]).setReg(NewVReg);
  790. if (CreatedNewVReg) {
  791. if (DefIsReMat) {
  792. vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
  793. if (ReMatIds[id] == VirtRegMap::MAX_STACK_SLOT) {
  794. // Each valnum may have its own remat id.
  795. ReMatIds[id] = vrm.assignVirtReMatId(NewVReg);
  796. } else {
  797. vrm.assignVirtReMatId(NewVReg, ReMatIds[id]);
  798. }
  799. if (!CanDelete || (HasUse && HasDef)) {
  800. // If this is a two-addr instruction then its use operands are
  801. // rematerializable but its def is not. It should be assigned a
  802. // stack slot.
  803. vrm.assignVirt2StackSlot(NewVReg, Slot);
  804. }
  805. } else {
  806. vrm.assignVirt2StackSlot(NewVReg, Slot);
  807. }
  808. } else if (HasUse && HasDef &&
  809. vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
  810. // If this interval hasn't been assigned a stack slot (because earlier
  811. // def is a deleted remat def), do it now.
  812. assert(Slot != VirtRegMap::NO_STACK_SLOT);
  813. vrm.assignVirt2StackSlot(NewVReg, Slot);
  814. }
  815. // create a new register interval for this spill / remat.
  816. LiveInterval &nI = getOrCreateInterval(NewVReg);
  817. if (CreatedNewVReg) {
  818. NewLIs.push_back(&nI);
  819. MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
  820. if (TrySplit)
  821. vrm.setIsSplitFromReg(NewVReg, li.reg);
  822. }
  823. if (HasUse) {
  824. if (CreatedNewVReg) {
  825. LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
  826. nI.getNextValue(~0U, 0, VNInfoAllocator));
  827. DOUT << " +" << LR;
  828. nI.addRange(LR);
  829. } else {
  830. // Extend the split live interval to this def / use.
  831. unsigned End = getUseIndex(index)+1;
  832. LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
  833. nI.getValNumInfo(nI.getNumValNums()-1));
  834. DOUT << " +" << LR;
  835. nI.addRange(LR);
  836. }
  837. }
  838. if (HasDef) {
  839. LiveRange LR(getDefIndex(index), getStoreIndex(index),
  840. nI.getNextValue(~0U, 0, VNInfoAllocator));
  841. DOUT << " +" << LR;
  842. nI.addRange(LR);
  843. }
  844. DOUT << "\t\t\t\tAdded new interval: ";
  845. nI.print(DOUT, mri_);
  846. DOUT << '\n';
  847. }
  848. return CanFold;
  849. }
  850. bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
  851. const VNInfo *VNI,
  852. MachineBasicBlock *MBB, unsigned Idx) const {
  853. unsigned End = getMBBEndIdx(MBB);
  854. for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
  855. unsigned KillIdx = VNI->kills[j];
  856. if (KillIdx > Idx && KillIdx < End)
  857. return true;
  858. }
  859. return false;
  860. }
  861. static const VNInfo *findDefinedVNInfo(const LiveInterval &li, unsigned DefIdx) {
  862. const VNInfo *VNI = NULL;
  863. for (LiveInterval::const_vni_iterator i = li.vni_begin(),
  864. e = li.vni_end(); i != e; ++i)
  865. if ((*i)->def == DefIdx) {
  866. VNI = *i;
  867. break;
  868. }
  869. return VNI;
  870. }
  871. void LiveIntervals::
  872. rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
  873. LiveInterval::Ranges::const_iterator &I,
  874. MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
  875. unsigned Slot, int LdSlot,
  876. bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
  877. VirtRegMap &vrm, MachineRegisterInfo &RegInfo,
  878. const TargetRegisterClass* rc,
  879. SmallVector<int, 4> &ReMatIds,
  880. const MachineLoopInfo *loopInfo,
  881. BitVector &SpillMBBs,
  882. std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
  883. BitVector &RestoreMBBs,
  884. std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
  885. std::map<unsigned,unsigned> &MBBVRegsMap,
  886. std::vector<LiveInterval*> &NewLIs) {
  887. bool AllCanFold = true;
  888. unsigned NewVReg = 0;
  889. unsigned index = getBaseIndex(I->start);
  890. unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
  891. for (; index != end; index += InstrSlots::NUM) {
  892. // skip deleted instructions
  893. while (index != end && !getInstructionFromIndex(index))
  894. index += InstrSlots::NUM;
  895. if (index == end) break;
  896. MachineInstr *MI = getInstructionFromIndex(index);
  897. MachineBasicBlock *MBB = MI->getParent();
  898. unsigned ThisVReg = 0;
  899. if (TrySplit) {
  900. std::map<unsigned,unsigned>::const_iterator NVI =
  901. MBBVRegsMap.find(MBB->getNumber());
  902. if (NVI != MBBVRegsMap.end()) {
  903. ThisVReg = NVI->second;
  904. // One common case:
  905. // x = use
  906. // ...
  907. // ...
  908. // def = ...
  909. // = use
  910. // It's better to start a new interval to avoid artifically
  911. // extend the new interval.
  912. // FIXME: Too slow? Can we fix it after rewriteInstructionsForSpills?
  913. bool MIHasUse = false;
  914. bool MIHasDef = false;
  915. for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
  916. MachineOperand& mop = MI->getOperand(i);
  917. if (!mop.isRegister() || mop.getReg() != li.reg)
  918. continue;
  919. if (mop.isUse())
  920. MIHasUse = true;
  921. else
  922. MIHasDef = true;
  923. }
  924. if (MIHasDef && !MIHasUse) {
  925. MBBVRegsMap.erase(MBB->getNumber());
  926. ThisVReg = 0;
  927. }
  928. }
  929. }
  930. bool IsNew = ThisVReg == 0;
  931. if (IsNew) {
  932. // This ends the previous live interval. If all of its def / use
  933. // can be folded, give it a low spill weight.
  934. if (NewVReg && TrySplit && AllCanFold) {
  935. LiveInterval &nI = getOrCreateInterval(NewVReg);
  936. nI.weight /= 10.0F;
  937. }
  938. AllCanFold = true;
  939. }
  940. NewVReg = ThisVReg;
  941. bool HasDef = false;
  942. bool HasUse = false;
  943. bool CanFold = rewriteInstructionForSpills(li, TrySplit, I->valno->id,
  944. index, end, MI, ReMatOrigDefMI, ReMatDefMI,
  945. Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
  946. CanDelete, vrm, RegInfo, rc, ReMatIds, NewVReg,
  947. HasDef, HasUse, loopInfo, MBBVRegsMap, NewLIs);
  948. if (!HasDef && !HasUse)
  949. continue;
  950. AllCanFold &= CanFold;
  951. // Update weight of spill interval.
  952. LiveInterval &nI = getOrCreateInterval(NewVReg);
  953. if (!TrySplit) {
  954. // The spill weight is now infinity as it cannot be spilled again.
  955. nI.weight = HUGE_VALF;
  956. continue;
  957. }
  958. // Keep track of the last def and first use in each MBB.
  959. unsigned MBBId = MBB->getNumber();
  960. if (HasDef) {
  961. if (MI != ReMatOrigDefMI || !CanDelete) {
  962. bool HasKill = false;
  963. if (!HasUse)
  964. HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
  965. else {
  966. // If this is a two-address code, then this index starts a new VNInfo.
  967. const VNInfo *VNI = findDefinedVNInfo(li, getDefIndex(index));
  968. if (VNI)
  969. HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
  970. }
  971. std::map<unsigned, std::vector<SRInfo> >::iterator SII =
  972. SpillIdxes.find(MBBId);
  973. if (!HasKill) {
  974. if (SII == SpillIdxes.end()) {
  975. std::vector<SRInfo> S;
  976. S.push_back(SRInfo(index, NewVReg, true));
  977. SpillIdxes.insert(std::make_pair(MBBId, S));
  978. } else if (SII->second.back().vreg != NewVReg) {
  979. SII->second.push_back(SRInfo(index, NewVReg, true));
  980. } else if ((int)index > SII->second.back().index) {
  981. // If there is an earlier def and this is a two-address
  982. // instruction, then it's not possible to fold the store (which
  983. // would also fold the load).
  984. SRInfo &Info = SII->second.back();
  985. Info.index = index;
  986. Info.canFold = !HasUse;
  987. }
  988. SpillMBBs.set(MBBId);
  989. } else if (SII != SpillIdxes.end() &&
  990. SII->second.back().vreg == NewVReg &&
  991. (int)index > SII->second.back().index) {
  992. // There is an earlier def that's not killed (must be two-address).
  993. // The spill is no longer needed.
  994. SII->second.pop_back();
  995. if (SII->second.empty()) {
  996. SpillIdxes.erase(MBBId);
  997. SpillMBBs.reset(MBBId);
  998. }
  999. }
  1000. }
  1001. }
  1002. if (HasUse) {
  1003. std::map<unsigned, std::vector<SRInfo> >::iterator SII =
  1004. SpillIdxes.find(MBBId);
  1005. if (SII != SpillIdxes.end() &&
  1006. SII->second.back().vreg == NewVReg &&
  1007. (int)index > SII->second.back().index)
  1008. // Use(s) following the last def, it's not safe to fold the spill.
  1009. SII->second.back().canFold = false;
  1010. std::map<unsigned, std::vector<SRInfo> >::iterator RII =
  1011. RestoreIdxes.find(MBBId);
  1012. if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
  1013. // If we are splitting live intervals, only fold if it's the first
  1014. // use and there isn't another use later in the MBB.
  1015. RII->second.back().canFold = false;
  1016. else if (IsNew) {
  1017. // Only need a reload if there isn't an earlier def / use.
  1018. if (RII == RestoreIdxes.end()) {
  1019. std::vector<SRInfo> Infos;
  1020. Infos.push_back(SRInfo(index, NewVReg, true));
  1021. RestoreIdxes.insert(std::make_pair(MBBId, Infos));
  1022. } else {
  1023. RII->second.push_back(SRInfo(index, NewVReg, true));
  1024. }
  1025. RestoreMBBs.set(MBBId);
  1026. }
  1027. }
  1028. // Update spill weight.
  1029. unsigned loopDepth = loopInfo->getLoopDepth(MBB);
  1030. nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
  1031. }
  1032. if (NewVReg && TrySplit && AllCanFold) {
  1033. // If all of its def / use can be folded, give it a low spill weight.
  1034. LiveInterval &nI = getOrCreateInterval(NewVReg);
  1035. nI.weight /= 10.0F;
  1036. }
  1037. }
  1038. bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
  1039. BitVector &RestoreMBBs,
  1040. std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
  1041. if (!RestoreMBBs[Id])
  1042. return false;
  1043. std::vector<SRInfo> &Restores = RestoreIdxes[Id];
  1044. for (unsigned i = 0, e = Restores.size(); i != e; ++i)
  1045. if (Restores[i].index == index &&
  1046. Restores[i].vreg == vr &&
  1047. Restores[i].canFold)
  1048. return true;
  1049. return false;
  1050. }
  1051. void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
  1052. BitVector &RestoreMBBs,
  1053. std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
  1054. if (!RestoreMBBs[Id])
  1055. return;
  1056. std::vector<SRInfo> &Restores = RestoreIdxes[Id];
  1057. for (unsigned i = 0, e = Restores.size(); i != e; ++i)
  1058. if (Restores[i].index == index && Restores[i].vreg)
  1059. Restores[i].index = -1;
  1060. }
  1061. std::vector<LiveInterval*> LiveIntervals::
  1062. addIntervalsForSpills(const LiveInterval &li,
  1063. const MachineLoopInfo *loopInfo, VirtRegMap &vrm) {
  1064. // Since this is called after the analysis is done we don't know if
  1065. // LiveVariables is available
  1066. lv_ = getAnalysisToUpdate<LiveVariables>();
  1067. assert(li.weight != HUGE_VALF &&
  1068. "attempt to spill already spilled interval!");
  1069. DOUT << "\t\t\t\tadding intervals for spills for interval: ";
  1070. li.print(DOUT, mri_);
  1071. DOUT << '\n';
  1072. // Each bit specify whether it a spill is required in the MBB.
  1073. BitVector SpillMBBs(mf_->getNumBlockIDs());
  1074. std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
  1075. BitVector RestoreMBBs(mf_->getNumBlockIDs());
  1076. std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
  1077. std::map<unsigned,unsigned> MBBVRegsMap;
  1078. std::vector<LiveInterval*> NewLIs;
  1079. MachineRegisterInfo &RegInfo = mf_->getRegInfo();
  1080. const TargetRegisterClass* rc = RegInfo.getRegClass(li.reg);
  1081. unsigned NumValNums = li.getNumValNums();
  1082. SmallVector<MachineInstr*, 4> ReMatDefs;
  1083. ReMatDefs.resize(NumValNums, NULL);
  1084. SmallVector<MachineInstr*, 4> ReMatOrigDefs;
  1085. ReMatOrigDefs.resize(NumValNums, NULL);
  1086. SmallVector<int, 4> ReMatIds;
  1087. ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
  1088. BitVector ReMatDelete(NumValNums);
  1089. unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
  1090. // Spilling a split live interval. It cannot be split any further. Also,
  1091. // it's also guaranteed to be a single val# / range interval.
  1092. if (vrm.getPreSplitReg(li.reg)) {
  1093. vrm.setIsSplitFromReg(li.reg, 0);
  1094. // Unset the split kill marker on the last use.
  1095. unsigned KillIdx = vrm.getKillPoint(li.reg);
  1096. if (KillIdx) {
  1097. MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
  1098. assert(KillMI && "Last use disappeared?");
  1099. int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
  1100. assert(KillOp != -1 && "Last use disappeared?");
  1101. KillMI->getOperand(KillOp).setIsKill(false);
  1102. }
  1103. vrm.removeKillPoint(li.reg);
  1104. bool DefIsReMat = vrm.isReMaterialized(li.reg);
  1105. Slot = vrm.getStackSlot(li.reg);
  1106. assert(Slot != VirtRegMap::MAX_STACK_SLOT);
  1107. MachineInstr *ReMatDefMI = DefIsReMat ?
  1108. vrm.getReMaterializedMI(li.reg) : NULL;
  1109. int LdSlot = 0;
  1110. bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
  1111. bool isLoad = isLoadSS ||
  1112. (DefIsReMat && (ReMatDefMI->getInstrDescriptor()->Flags & M_LOAD_FLAG));
  1113. bool IsFirstRange = true;
  1114. for (LiveInterval::Ranges::const_iterator
  1115. I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
  1116. // If this is a split live interval with multiple ranges, it means there
  1117. // are two-address instructions that re-defined the value. Only the
  1118. // first def can be rematerialized!
  1119. if (IsFirstRange) {
  1120. // Note ReMatOrigDefMI has already been deleted.
  1121. rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
  1122. Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
  1123. false, vrm, RegInfo, rc, ReMatIds, loopInfo,
  1124. SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
  1125. MBBVRegsMap, NewLIs);
  1126. } else {
  1127. rewriteInstructionsForSpills(li, false, I, NULL, 0,
  1128. Slot, 0, false, false, false,
  1129. false, vrm, RegInfo, rc, ReMatIds, loopInfo,
  1130. SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
  1131. MBBVRegsMap, NewLIs);
  1132. }
  1133. IsFirstRange = false;
  1134. }
  1135. return NewLIs;
  1136. }
  1137. bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
  1138. if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
  1139. TrySplit = false;
  1140. if (TrySplit)
  1141. ++numSplits;
  1142. bool NeedStackSlot = false;
  1143. for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
  1144. i != e; ++i) {
  1145. const VNInfo *VNI = *i;
  1146. unsigned VN = VNI->id;
  1147. unsigned DefIdx = VNI->def;
  1148. if (DefIdx == ~1U)
  1149. continue; // Dead val#.
  1150. // Is the def for the val# rematerializable?
  1151. MachineInstr *ReMatDefMI = (DefIdx == ~0u)
  1152. ? 0 : getInstructionFromIndex(DefIdx);
  1153. bool dummy;
  1154. if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
  1155. // Remember how to remat the def of this val#.
  1156. ReMatOrigDefs[VN] = ReMatDefMI;
  1157. // Original def may be modified so we have to make a copy here. vrm must
  1158. // delete these!
  1159. ReMatDefs[VN] = ReMatDefMI = ReMatDefMI->clone();
  1160. bool CanDelete = true;
  1161. if (VNI->hasPHIKill) {
  1162. // A kill is a phi node, not all of its uses can be rematerialized.
  1163. // It must not be deleted.
  1164. CanDelete = false;
  1165. // Need a stack slot if there is any live range where uses cannot be
  1166. // rematerialized.
  1167. NeedStackSlot = true;
  1168. }
  1169. if (CanDelete)
  1170. ReMatDelete.set(VN);
  1171. } else {
  1172. // Need a stack slot if there is any live range where uses cannot be
  1173. // rematerialized.
  1174. NeedStackSlot = true;
  1175. }
  1176. }
  1177. // One stack slot per live interval.
  1178. if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
  1179. Slot = vrm.assignVirt2StackSlot(li.reg);
  1180. // Create new intervals and rewrite defs and uses.
  1181. for (LiveInterval::Ranges::const_iterator
  1182. I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
  1183. MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
  1184. MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
  1185. bool DefIsReMat = ReMatDefMI != NULL;
  1186. bool CanDelete = ReMatDelete[I->valno->id];
  1187. int LdSlot = 0;
  1188. bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
  1189. bool isLoad = isLoadSS ||
  1190. (DefIsReMat && (ReMatDefMI->getInstrDescriptor()->Flags & M_LOAD_FLAG));
  1191. rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
  1192. Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
  1193. CanDelete, vrm, RegInfo, rc, ReMatIds, loopInfo,
  1194. SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
  1195. MBBVRegsMap, NewLIs);
  1196. }
  1197. // Insert spills / restores if we are splitting.
  1198. if (!TrySplit)
  1199. return NewLIs;
  1200. SmallPtrSet<LiveInterval*, 4> AddedKill;
  1201. SmallVector<unsigned, 2> Ops;
  1202. if (NeedStackSlot) {
  1203. int Id = SpillMBBs.find_first();
  1204. while (Id != -1) {
  1205. std::vector<SRInfo> &spills = SpillIdxes[Id];
  1206. for (unsigned i = 0, e = spills.size(); i != e; ++i) {
  1207. int index = spills[i].index;
  1208. unsigned VReg = spills[i].vreg;
  1209. LiveInterval &nI = getOrCreateInterval(VReg);
  1210. bool isReMat = vrm.isReMaterialized(VReg);
  1211. MachineInstr *MI = getInstructionFromIndex(index);
  1212. bool CanFold = false;
  1213. bool FoundUse = false;
  1214. Ops.clear();
  1215. if (spills[i].canFold) {
  1216. CanFold = true;
  1217. for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
  1218. MachineOperand &MO = MI->getOperand(j);
  1219. if (!MO.isRegister() || MO.getReg() != VReg)
  1220. continue;
  1221. Ops.push_back(j);
  1222. if (MO.isDef())
  1223. continue;
  1224. if (isReMat ||
  1225. (!FoundUse && !alsoFoldARestore(Id, index, VReg,
  1226. RestoreMBBs, RestoreIdxes))) {
  1227. // MI has two-address uses of the same register. If the use
  1228. // isn't the first and only use in the BB, then we can't fold
  1229. // it. FIXME: Move this to rewriteInstructionsForSpills.
  1230. CanFold = false;
  1231. break;
  1232. }
  1233. FoundUse = true;
  1234. }
  1235. }
  1236. // Fold the store into the def if possible.
  1237. bool Folded = false;
  1238. if (CanFold && !Ops.empty()) {
  1239. if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
  1240. Folded = true;
  1241. if (FoundUse > 0) {
  1242. // Also folded uses, do not issue a load.
  1243. eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
  1244. nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
  1245. }
  1246. nI.removeRange(getDefIndex(index), getStoreIndex(index));
  1247. }
  1248. }
  1249. // Else tell the spiller to issue a spill.
  1250. if (!Folded) {
  1251. LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
  1252. bool isKill = LR->end == getStoreIndex(index);
  1253. vrm.addSpillPoint(VReg, isKill, MI);
  1254. if (isKill)
  1255. AddedKill.insert(&nI);
  1256. }
  1257. }
  1258. Id = SpillMBBs.find_next(Id);
  1259. }
  1260. }
  1261. int Id = RestoreMBBs.find_first();
  1262. while (Id != -1) {
  1263. std::vector<SRInfo> &restores = RestoreIdxes[Id];
  1264. for (unsigned i = 0, e = restores.size(); i != e; ++i) {
  1265. int index = restores[i].index;
  1266. if (index == -1)
  1267. continue;
  1268. unsigned VReg = restores[i].vreg;
  1269. LiveInterval &nI = getOrCreateInterval(VReg);
  1270. MachineInstr *MI = getInstructionFromIndex(index);
  1271. bool CanFold = false;
  1272. Ops.clear();
  1273. if (restores[i].canFold) {
  1274. CanFold = true;
  1275. for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
  1276. MachineOperand &MO = MI->getOperand(j);
  1277. if (!MO.isRegister() || MO.getReg() != VReg)
  1278. continue;
  1279. if (MO.isDef()) {
  1280. // If this restore were to be folded, it would have been folded
  1281. // already.
  1282. CanFold = false;
  1283. break;
  1284. }
  1285. Ops.push_back(j);
  1286. }
  1287. }
  1288. // Fold the load into the use if possible.
  1289. bool Folded = false;
  1290. if (CanFold && !Ops.empty()) {
  1291. if (!vrm.isReMaterialized(VReg))
  1292. Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
  1293. else {
  1294. MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
  1295. int LdSlot = 0;
  1296. bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
  1297. // If the rematerializable def is a load, also try to fold it.
  1298. if (isLoadSS ||
  1299. (ReMatDefMI->getInstrDescriptor()->Flags & M_LOAD_FLAG))
  1300. Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
  1301. Ops, isLoadSS, LdSlot, VReg);
  1302. }
  1303. }
  1304. // If folding is not possible / failed, then tell the spiller to issue a
  1305. // load / rematerialization for us.
  1306. if (Folded)
  1307. nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
  1308. else
  1309. vrm.addRestorePoint(VReg, MI);
  1310. }
  1311. Id = RestoreMBBs.find_next(Id);
  1312. }
  1313. // Finalize intervals: add kills, finalize spill weights, and filter out
  1314. // dead intervals.
  1315. std::vector<LiveInterval*> RetNewLIs;
  1316. for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
  1317. LiveInterval *LI = NewLIs[i];
  1318. if (!LI->empty()) {
  1319. LI->weight /= LI->getSize();
  1320. if (!AddedKill.count(LI)) {
  1321. LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
  1322. unsigned LastUseIdx = getBaseIndex(LR->end);
  1323. MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
  1324. int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg);
  1325. assert(UseIdx != -1);
  1326. if (LastUse->getInstrDescriptor()->
  1327. getOperandConstraint(UseIdx, TOI::TIED_TO) == -1) {
  1328. LastUse->getOperand(UseIdx).setIsKill();
  1329. vrm.addKillPoint(LI->reg, LastUseIdx);
  1330. }
  1331. }
  1332. RetNewLIs.push_back(LI);
  1333. }
  1334. }
  1335. return RetNewLIs;
  1336. }