LiveIntervalAnalysis.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by the LLVM research group and is distributed under
  6. // the University of Illinois Open Source 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/Analysis/LoopInfo.h"
  22. #include "llvm/CodeGen/LiveVariables.h"
  23. #include "llvm/CodeGen/MachineFrameInfo.h"
  24. #include "llvm/CodeGen/MachineInstr.h"
  25. #include "llvm/CodeGen/Passes.h"
  26. #include "llvm/CodeGen/SSARegMap.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. #include <iostream>
  37. using namespace llvm;
  38. namespace {
  39. RegisterAnalysis<LiveIntervals> X("liveintervals", "Live Interval Analysis");
  40. Statistic<> numIntervals
  41. ("liveintervals", "Number of original intervals");
  42. Statistic<> numIntervalsAfter
  43. ("liveintervals", "Number of intervals after coalescing");
  44. Statistic<> numJoins
  45. ("liveintervals", "Number of interval joins performed");
  46. Statistic<> numPeep
  47. ("liveintervals", "Number of identity moves eliminated after coalescing");
  48. Statistic<> numFolded
  49. ("liveintervals", "Number of loads/stores folded into instructions");
  50. cl::opt<bool>
  51. EnableJoining("join-liveintervals",
  52. cl::desc("Join compatible live intervals"),
  53. cl::init(true));
  54. }
  55. void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
  56. {
  57. AU.addRequired<LiveVariables>();
  58. AU.addPreservedID(PHIEliminationID);
  59. AU.addRequiredID(PHIEliminationID);
  60. AU.addRequiredID(TwoAddressInstructionPassID);
  61. AU.addRequired<LoopInfo>();
  62. MachineFunctionPass::getAnalysisUsage(AU);
  63. }
  64. void LiveIntervals::releaseMemory()
  65. {
  66. mi2iMap_.clear();
  67. i2miMap_.clear();
  68. r2iMap_.clear();
  69. r2rMap_.clear();
  70. }
  71. static bool isZeroLengthInterval(LiveInterval *li) {
  72. for (LiveInterval::Ranges::const_iterator
  73. i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
  74. if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
  75. return false;
  76. return true;
  77. }
  78. /// runOnMachineFunction - Register allocate the whole function
  79. ///
  80. bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
  81. mf_ = &fn;
  82. tm_ = &fn.getTarget();
  83. mri_ = tm_->getRegisterInfo();
  84. tii_ = tm_->getInstrInfo();
  85. lv_ = &getAnalysis<LiveVariables>();
  86. allocatableRegs_ = mri_->getAllocatableSet(fn);
  87. r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
  88. // If this function has any live ins, insert a dummy instruction at the
  89. // beginning of the function that we will pretend "defines" the values. This
  90. // is to make the interval analysis simpler by providing a number.
  91. if (fn.livein_begin() != fn.livein_end()) {
  92. unsigned FirstLiveIn = fn.livein_begin()->first;
  93. // Find a reg class that contains this live in.
  94. const TargetRegisterClass *RC = 0;
  95. for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
  96. E = mri_->regclass_end(); RCI != E; ++RCI)
  97. if ((*RCI)->contains(FirstLiveIn)) {
  98. RC = *RCI;
  99. break;
  100. }
  101. MachineInstr *OldFirstMI = fn.begin()->begin();
  102. mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
  103. FirstLiveIn, FirstLiveIn, RC);
  104. assert(OldFirstMI != fn.begin()->begin() &&
  105. "copyRetToReg didn't insert anything!");
  106. }
  107. // number MachineInstrs
  108. unsigned miIndex = 0;
  109. for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
  110. mbb != mbbEnd; ++mbb)
  111. for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
  112. mi != miEnd; ++mi) {
  113. bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
  114. assert(inserted && "multiple MachineInstr -> index mappings");
  115. i2miMap_.push_back(mi);
  116. miIndex += InstrSlots::NUM;
  117. }
  118. // Note intervals due to live-in values.
  119. if (fn.livein_begin() != fn.livein_end()) {
  120. MachineBasicBlock *Entry = fn.begin();
  121. for (MachineFunction::livein_iterator I = fn.livein_begin(),
  122. E = fn.livein_end(); I != E; ++I) {
  123. handlePhysicalRegisterDef(Entry, Entry->begin(),
  124. getOrCreateInterval(I->first), 0, 0, true);
  125. for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
  126. handlePhysicalRegisterDef(Entry, Entry->begin(),
  127. getOrCreateInterval(*AS), 0, 0, true);
  128. }
  129. }
  130. computeIntervals();
  131. numIntervals += getNumIntervals();
  132. DEBUG(std::cerr << "********** INTERVALS **********\n";
  133. for (iterator I = begin(), E = end(); I != E; ++I) {
  134. I->second.print(std::cerr, mri_);
  135. std::cerr << "\n";
  136. });
  137. // join intervals if requested
  138. if (EnableJoining) joinIntervals();
  139. numIntervalsAfter += getNumIntervals();
  140. // perform a final pass over the instructions and compute spill
  141. // weights, coalesce virtual registers and remove identity moves
  142. const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
  143. for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
  144. mbbi != mbbe; ++mbbi) {
  145. MachineBasicBlock* mbb = mbbi;
  146. unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
  147. for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
  148. mii != mie; ) {
  149. // if the move will be an identity move delete it
  150. unsigned srcReg, dstReg, RegRep;
  151. if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
  152. (RegRep = rep(srcReg)) == rep(dstReg)) {
  153. // remove from def list
  154. LiveInterval &interval = getOrCreateInterval(RegRep);
  155. // remove index -> MachineInstr and
  156. // MachineInstr -> index mappings
  157. Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
  158. if (mi2i != mi2iMap_.end()) {
  159. i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
  160. mi2iMap_.erase(mi2i);
  161. }
  162. mii = mbbi->erase(mii);
  163. ++numPeep;
  164. }
  165. else {
  166. for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
  167. const MachineOperand& mop = mii->getOperand(i);
  168. if (mop.isRegister() && mop.getReg() &&
  169. MRegisterInfo::isVirtualRegister(mop.getReg())) {
  170. // replace register with representative register
  171. unsigned reg = rep(mop.getReg());
  172. mii->getOperand(i).setReg(reg);
  173. LiveInterval &RegInt = getInterval(reg);
  174. RegInt.weight +=
  175. (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
  176. }
  177. }
  178. ++mii;
  179. }
  180. }
  181. }
  182. for (iterator I = begin(), E = end(); I != E; ++I) {
  183. LiveInterval &li = I->second;
  184. if (MRegisterInfo::isVirtualRegister(li.reg))
  185. // If the live interval legnth is essentially zero, i.e. in every live
  186. // range the use follows def immediately, it doesn't make sense to spill
  187. // it and hope it will be easier to allocate for this li.
  188. if (isZeroLengthInterval(&li))
  189. li.weight = float(HUGE_VAL);
  190. }
  191. DEBUG(dump());
  192. return true;
  193. }
  194. /// print - Implement the dump method.
  195. void LiveIntervals::print(std::ostream &O, const Module* ) const {
  196. O << "********** INTERVALS **********\n";
  197. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  198. I->second.print(std::cerr, mri_);
  199. std::cerr << "\n";
  200. }
  201. O << "********** MACHINEINSTRS **********\n";
  202. for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
  203. mbbi != mbbe; ++mbbi) {
  204. O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
  205. for (MachineBasicBlock::iterator mii = mbbi->begin(),
  206. mie = mbbi->end(); mii != mie; ++mii) {
  207. O << getInstructionIndex(mii) << '\t' << *mii;
  208. }
  209. }
  210. }
  211. std::vector<LiveInterval*> LiveIntervals::
  212. addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
  213. // since this is called after the analysis is done we don't know if
  214. // LiveVariables is available
  215. lv_ = getAnalysisToUpdate<LiveVariables>();
  216. std::vector<LiveInterval*> added;
  217. assert(li.weight != HUGE_VAL &&
  218. "attempt to spill already spilled interval!");
  219. DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
  220. << li << '\n');
  221. const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
  222. for (LiveInterval::Ranges::const_iterator
  223. i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
  224. unsigned index = getBaseIndex(i->start);
  225. unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
  226. for (; index != end; index += InstrSlots::NUM) {
  227. // skip deleted instructions
  228. while (index != end && !getInstructionFromIndex(index))
  229. index += InstrSlots::NUM;
  230. if (index == end) break;
  231. MachineInstr *MI = getInstructionFromIndex(index);
  232. // NewRegLiveIn - This instruction might have multiple uses of the spilled
  233. // register. In this case, for the first use, keep track of the new vreg
  234. // that we reload it into. If we see a second use, reuse this vreg
  235. // instead of creating live ranges for two reloads.
  236. unsigned NewRegLiveIn = 0;
  237. for_operand:
  238. for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
  239. MachineOperand& mop = MI->getOperand(i);
  240. if (mop.isRegister() && mop.getReg() == li.reg) {
  241. if (NewRegLiveIn && mop.isUse()) {
  242. // We already emitted a reload of this value, reuse it for
  243. // subsequent operands.
  244. MI->getOperand(i).setReg(NewRegLiveIn);
  245. DEBUG(std::cerr << "\t\t\t\treused reload into reg" << NewRegLiveIn
  246. << " for operand #" << i << '\n');
  247. } else if (MachineInstr* fmi = mri_->foldMemoryOperand(MI, i, slot)) {
  248. // Attempt to fold the memory reference into the instruction. If we
  249. // can do this, we don't need to insert spill code.
  250. if (lv_)
  251. lv_->instructionChanged(MI, fmi);
  252. MachineBasicBlock &MBB = *MI->getParent();
  253. vrm.virtFolded(li.reg, MI, i, fmi);
  254. mi2iMap_.erase(MI);
  255. i2miMap_[index/InstrSlots::NUM] = fmi;
  256. mi2iMap_[fmi] = index;
  257. MI = MBB.insert(MBB.erase(MI), fmi);
  258. ++numFolded;
  259. // Folding the load/store can completely change the instruction in
  260. // unpredictable ways, rescan it from the beginning.
  261. goto for_operand;
  262. } else {
  263. // This is tricky. We need to add information in the interval about
  264. // the spill code so we have to use our extra load/store slots.
  265. //
  266. // If we have a use we are going to have a load so we start the
  267. // interval from the load slot onwards. Otherwise we start from the
  268. // def slot.
  269. unsigned start = (mop.isUse() ?
  270. getLoadIndex(index) :
  271. getDefIndex(index));
  272. // If we have a def we are going to have a store right after it so
  273. // we end the interval after the use of the next
  274. // instruction. Otherwise we end after the use of this instruction.
  275. unsigned end = 1 + (mop.isDef() ?
  276. getStoreIndex(index) :
  277. getUseIndex(index));
  278. // create a new register for this spill
  279. NewRegLiveIn = mf_->getSSARegMap()->createVirtualRegister(rc);
  280. MI->getOperand(i).setReg(NewRegLiveIn);
  281. vrm.grow();
  282. vrm.assignVirt2StackSlot(NewRegLiveIn, slot);
  283. LiveInterval& nI = getOrCreateInterval(NewRegLiveIn);
  284. assert(nI.empty());
  285. // the spill weight is now infinity as it
  286. // cannot be spilled again
  287. nI.weight = float(HUGE_VAL);
  288. LiveRange LR(start, end, nI.getNextValue());
  289. DEBUG(std::cerr << " +" << LR);
  290. nI.addRange(LR);
  291. added.push_back(&nI);
  292. // update live variables if it is available
  293. if (lv_)
  294. lv_->addVirtualRegisterKilled(NewRegLiveIn, MI);
  295. // If this is a live in, reuse it for subsequent live-ins. If it's
  296. // a def, we can't do this.
  297. if (!mop.isUse()) NewRegLiveIn = 0;
  298. DEBUG(std::cerr << "\t\t\t\tadded new interval: " << nI << '\n');
  299. }
  300. }
  301. }
  302. }
  303. }
  304. return added;
  305. }
  306. void LiveIntervals::printRegName(unsigned reg) const
  307. {
  308. if (MRegisterInfo::isPhysicalRegister(reg))
  309. std::cerr << mri_->getName(reg);
  310. else
  311. std::cerr << "%reg" << reg;
  312. }
  313. void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
  314. MachineBasicBlock::iterator mi,
  315. LiveInterval& interval)
  316. {
  317. DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
  318. LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
  319. // Virtual registers may be defined multiple times (due to phi
  320. // elimination and 2-addr elimination). Much of what we do only has to be
  321. // done once for the vreg. We use an empty interval to detect the first
  322. // time we see a vreg.
  323. if (interval.empty()) {
  324. // Get the Idx of the defining instructions.
  325. unsigned defIndex = getDefIndex(getInstructionIndex(mi));
  326. unsigned ValNum = interval.getNextValue();
  327. assert(ValNum == 0 && "First value in interval is not 0?");
  328. ValNum = 0; // Clue in the optimizer.
  329. // Loop over all of the blocks that the vreg is defined in. There are
  330. // two cases we have to handle here. The most common case is a vreg
  331. // whose lifetime is contained within a basic block. In this case there
  332. // will be a single kill, in MBB, which comes after the definition.
  333. if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
  334. // FIXME: what about dead vars?
  335. unsigned killIdx;
  336. if (vi.Kills[0] != mi)
  337. killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
  338. else
  339. killIdx = defIndex+1;
  340. // If the kill happens after the definition, we have an intra-block
  341. // live range.
  342. if (killIdx > defIndex) {
  343. assert(vi.AliveBlocks.empty() &&
  344. "Shouldn't be alive across any blocks!");
  345. LiveRange LR(defIndex, killIdx, ValNum);
  346. interval.addRange(LR);
  347. DEBUG(std::cerr << " +" << LR << "\n");
  348. return;
  349. }
  350. }
  351. // The other case we handle is when a virtual register lives to the end
  352. // of the defining block, potentially live across some blocks, then is
  353. // live into some number of blocks, but gets killed. Start by adding a
  354. // range that goes from this definition to the end of the defining block.
  355. LiveRange NewLR(defIndex,
  356. getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
  357. ValNum);
  358. DEBUG(std::cerr << " +" << NewLR);
  359. interval.addRange(NewLR);
  360. // Iterate over all of the blocks that the variable is completely
  361. // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
  362. // live interval.
  363. for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
  364. if (vi.AliveBlocks[i]) {
  365. MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
  366. if (!mbb->empty()) {
  367. LiveRange LR(getInstructionIndex(&mbb->front()),
  368. getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
  369. ValNum);
  370. interval.addRange(LR);
  371. DEBUG(std::cerr << " +" << LR);
  372. }
  373. }
  374. }
  375. // Finally, this virtual register is live from the start of any killing
  376. // block to the 'use' slot of the killing instruction.
  377. for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
  378. MachineInstr *Kill = vi.Kills[i];
  379. LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
  380. getUseIndex(getInstructionIndex(Kill))+1,
  381. ValNum);
  382. interval.addRange(LR);
  383. DEBUG(std::cerr << " +" << LR);
  384. }
  385. } else {
  386. // If this is the second time we see a virtual register definition, it
  387. // must be due to phi elimination or two addr elimination. If this is
  388. // the result of two address elimination, then the vreg is the first
  389. // operand, and is a def-and-use.
  390. if (mi->getOperand(0).isRegister() &&
  391. mi->getOperand(0).getReg() == interval.reg &&
  392. mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
  393. // If this is a two-address definition, then we have already processed
  394. // the live range. The only problem is that we didn't realize there
  395. // are actually two values in the live interval. Because of this we
  396. // need to take the LiveRegion that defines this register and split it
  397. // into two values.
  398. unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
  399. unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
  400. // Delete the initial value, which should be short and continuous,
  401. // becuase the 2-addr copy must be in the same MBB as the redef.
  402. interval.removeRange(DefIndex, RedefIndex);
  403. LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
  404. DEBUG(std::cerr << " replace range with " << LR);
  405. interval.addRange(LR);
  406. // If this redefinition is dead, we need to add a dummy unit live
  407. // range covering the def slot.
  408. if (lv_->RegisterDefIsDead(mi, interval.reg))
  409. interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
  410. DEBUG(std::cerr << "RESULT: " << interval);
  411. } else {
  412. // Otherwise, this must be because of phi elimination. If this is the
  413. // first redefinition of the vreg that we have seen, go back and change
  414. // the live range in the PHI block to be a different value number.
  415. if (interval.containsOneValue()) {
  416. assert(vi.Kills.size() == 1 &&
  417. "PHI elimination vreg should have one kill, the PHI itself!");
  418. // Remove the old range that we now know has an incorrect number.
  419. MachineInstr *Killer = vi.Kills[0];
  420. unsigned Start = getInstructionIndex(Killer->getParent()->begin());
  421. unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
  422. DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
  423. << interval << "\n");
  424. interval.removeRange(Start, End);
  425. DEBUG(std::cerr << "RESULT: " << interval);
  426. // Replace the interval with one of a NEW value number.
  427. LiveRange LR(Start, End, interval.getNextValue());
  428. DEBUG(std::cerr << " replace range with " << LR);
  429. interval.addRange(LR);
  430. DEBUG(std::cerr << "RESULT: " << interval);
  431. }
  432. // In the case of PHI elimination, each variable definition is only
  433. // live until the end of the block. We've already taken care of the
  434. // rest of the live range.
  435. unsigned defIndex = getDefIndex(getInstructionIndex(mi));
  436. LiveRange LR(defIndex,
  437. getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
  438. interval.getNextValue());
  439. interval.addRange(LR);
  440. DEBUG(std::cerr << " +" << LR);
  441. }
  442. }
  443. DEBUG(std::cerr << '\n');
  444. }
  445. void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
  446. MachineBasicBlock::iterator mi,
  447. LiveInterval& interval,
  448. unsigned SrcReg, unsigned DestReg,
  449. bool isLiveIn)
  450. {
  451. // A physical register cannot be live across basic block, so its
  452. // lifetime must end somewhere in its defining basic block.
  453. DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
  454. typedef LiveVariables::killed_iterator KillIter;
  455. unsigned baseIndex = getInstructionIndex(mi);
  456. unsigned start = getDefIndex(baseIndex);
  457. unsigned end = start;
  458. // If it is not used after definition, it is considered dead at
  459. // the instruction defining it. Hence its interval is:
  460. // [defSlot(def), defSlot(def)+1)
  461. if (lv_->RegisterDefIsDead(mi, interval.reg)) {
  462. DEBUG(std::cerr << " dead");
  463. end = getDefIndex(start) + 1;
  464. goto exit;
  465. }
  466. // If it is not dead on definition, it must be killed by a
  467. // subsequent instruction. Hence its interval is:
  468. // [defSlot(def), useSlot(kill)+1)
  469. while (++mi != MBB->end()) {
  470. baseIndex += InstrSlots::NUM;
  471. if (lv_->KillsRegister(mi, interval.reg)) {
  472. DEBUG(std::cerr << " killed");
  473. end = getUseIndex(baseIndex) + 1;
  474. goto exit;
  475. }
  476. }
  477. // The only case we should have a dead physreg here without a killing or
  478. // instruction where we know it's dead is if it is live-in to the function
  479. // and never used.
  480. assert(isLiveIn && "physreg was not killed in defining block!");
  481. end = getDefIndex(start) + 1; // It's dead.
  482. exit:
  483. assert(start < end && "did not find end of interval?");
  484. // Finally, if this is defining a new range for the physical register, and if
  485. // that physreg is just a copy from a vreg, and if THAT vreg was a copy from
  486. // the physreg, then the new fragment has the same value as the one copied
  487. // into the vreg.
  488. if (interval.reg == DestReg && !interval.empty() &&
  489. MRegisterInfo::isVirtualRegister(SrcReg)) {
  490. // Get the live interval for the vreg, see if it is defined by a copy.
  491. LiveInterval &SrcInterval = getOrCreateInterval(SrcReg);
  492. if (SrcInterval.containsOneValue()) {
  493. assert(!SrcInterval.empty() && "Can't contain a value and be empty!");
  494. // Get the first index of the first range. Though the interval may have
  495. // multiple liveranges in it, we only check the first.
  496. unsigned StartIdx = SrcInterval.begin()->start;
  497. MachineInstr *SrcDefMI = getInstructionFromIndex(StartIdx);
  498. // Check to see if the vreg was defined by a copy instruction, and that
  499. // the source was this physreg.
  500. unsigned VRegSrcSrc, VRegSrcDest;
  501. if (tii_->isMoveInstr(*SrcDefMI, VRegSrcSrc, VRegSrcDest) &&
  502. SrcReg == VRegSrcDest && VRegSrcSrc == DestReg) {
  503. // Okay, now we know that the vreg was defined by a copy from this
  504. // physreg. Find the value number being copied and use it as the value
  505. // for this range.
  506. const LiveRange *DefRange = interval.getLiveRangeContaining(StartIdx-1);
  507. if (DefRange) {
  508. LiveRange LR(start, end, DefRange->ValId);
  509. interval.addRange(LR);
  510. DEBUG(std::cerr << " +" << LR << '\n');
  511. return;
  512. }
  513. }
  514. }
  515. }
  516. LiveRange LR(start, end, interval.getNextValue());
  517. interval.addRange(LR);
  518. DEBUG(std::cerr << " +" << LR << '\n');
  519. }
  520. void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
  521. MachineBasicBlock::iterator MI,
  522. unsigned reg) {
  523. if (MRegisterInfo::isVirtualRegister(reg))
  524. handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
  525. else if (allocatableRegs_[reg]) {
  526. unsigned SrcReg = 0, DestReg = 0;
  527. if (!tii_->isMoveInstr(*MI, SrcReg, DestReg))
  528. SrcReg = DestReg = 0;
  529. handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg),
  530. SrcReg, DestReg);
  531. for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
  532. handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS),
  533. SrcReg, DestReg);
  534. }
  535. }
  536. /// computeIntervals - computes the live intervals for virtual
  537. /// registers. for some ordering of the machine instructions [1,N] a
  538. /// live interval is an interval [i, j) where 1 <= i <= j < N for
  539. /// which a variable is live
  540. void LiveIntervals::computeIntervals()
  541. {
  542. DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
  543. DEBUG(std::cerr << "********** Function: "
  544. << ((Value*)mf_->getFunction())->getName() << '\n');
  545. bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
  546. for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
  547. I != E; ++I) {
  548. MachineBasicBlock* mbb = I;
  549. DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
  550. MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
  551. if (IgnoreFirstInstr) { ++mi; IgnoreFirstInstr = false; }
  552. for (; mi != miEnd; ++mi) {
  553. const TargetInstrDescriptor& tid =
  554. tm_->getInstrInfo()->get(mi->getOpcode());
  555. DEBUG(std::cerr << getInstructionIndex(mi) << "\t" << *mi);
  556. // handle implicit defs
  557. for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
  558. handleRegisterDef(mbb, mi, *id);
  559. // handle explicit defs
  560. for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
  561. MachineOperand& mop = mi->getOperand(i);
  562. // handle register defs - build intervals
  563. if (mop.isRegister() && mop.getReg() && mop.isDef())
  564. handleRegisterDef(mbb, mi, mop.getReg());
  565. }
  566. }
  567. }
  568. }
  569. /// IntA is defined as a copy from IntB and we know it only has one value
  570. /// number. If all of the places that IntA and IntB overlap are defined by
  571. /// copies from IntA to IntB, we know that these two ranges can really be
  572. /// merged if we adjust the value numbers. If it is safe, adjust the value
  573. /// numbers and return true, allowing coalescing to occur.
  574. bool LiveIntervals::
  575. AdjustIfAllOverlappingRangesAreCopiesFrom(LiveInterval &IntA,
  576. LiveInterval &IntB,
  577. unsigned CopyIdx) {
  578. std::vector<LiveRange*> Ranges;
  579. IntA.getOverlapingRanges(IntB, CopyIdx, Ranges);
  580. assert(!Ranges.empty() && "Why didn't we do a simple join of this?");
  581. unsigned IntBRep = rep(IntB.reg);
  582. // Check to see if all of the overlaps (entries in Ranges) are defined by a
  583. // copy from IntA. If not, exit.
  584. for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
  585. unsigned Idx = Ranges[i]->start;
  586. MachineInstr *MI = getInstructionFromIndex(Idx);
  587. unsigned SrcReg, DestReg;
  588. if (!tii_->isMoveInstr(*MI, SrcReg, DestReg)) return false;
  589. // If this copy isn't actually defining this range, it must be a live
  590. // range spanning basic blocks or something.
  591. if (rep(DestReg) != rep(IntA.reg)) return false;
  592. // Check to see if this is coming from IntB. If not, bail out.
  593. if (rep(SrcReg) != IntBRep) return false;
  594. }
  595. // Okay, we can change this one. Get the IntB value number that IntA is
  596. // copied from.
  597. unsigned ActualValNo = IntA.getLiveRangeContaining(CopyIdx-1)->ValId;
  598. // Change all of the value numbers to the same as what we IntA is copied from.
  599. for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
  600. Ranges[i]->ValId = ActualValNo;
  601. return true;
  602. }
  603. void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
  604. DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
  605. for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
  606. mi != mie; ++mi) {
  607. DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
  608. // we only join virtual registers with allocatable
  609. // physical registers since we do not have liveness information
  610. // on not allocatable physical registers
  611. unsigned SrcReg, DestReg;
  612. if (tii_->isMoveInstr(*mi, SrcReg, DestReg) &&
  613. (MRegisterInfo::isVirtualRegister(SrcReg) || allocatableRegs_[SrcReg])&&
  614. (MRegisterInfo::isVirtualRegister(DestReg)||allocatableRegs_[DestReg])){
  615. // Get representative registers.
  616. SrcReg = rep(SrcReg);
  617. DestReg = rep(DestReg);
  618. // If they are already joined we continue.
  619. if (SrcReg == DestReg)
  620. continue;
  621. // If they are both physical registers, we cannot join them.
  622. if (MRegisterInfo::isPhysicalRegister(SrcReg) &&
  623. MRegisterInfo::isPhysicalRegister(DestReg))
  624. continue;
  625. // If they are not of the same register class, we cannot join them.
  626. if (differingRegisterClasses(SrcReg, DestReg))
  627. continue;
  628. LiveInterval &SrcInt = getInterval(SrcReg);
  629. LiveInterval &DestInt = getInterval(DestReg);
  630. assert(SrcInt.reg == SrcReg && DestInt.reg == DestReg &&
  631. "Register mapping is horribly broken!");
  632. DEBUG(std::cerr << "\t\tInspecting " << SrcInt << " and " << DestInt
  633. << ": ");
  634. // If two intervals contain a single value and are joined by a copy, it
  635. // does not matter if the intervals overlap, they can always be joined.
  636. bool Joinable = SrcInt.containsOneValue() && DestInt.containsOneValue();
  637. unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
  638. // If the intervals think that this is joinable, do so now.
  639. if (!Joinable && DestInt.joinable(SrcInt, MIDefIdx))
  640. Joinable = true;
  641. // If DestInt is actually a copy from SrcInt (which we know) that is used
  642. // to define another value of SrcInt, we can change the other range of
  643. // SrcInt to be the value of the range that defines DestInt, allowing a
  644. // coalesce.
  645. if (!Joinable && DestInt.containsOneValue() &&
  646. AdjustIfAllOverlappingRangesAreCopiesFrom(SrcInt, DestInt, MIDefIdx))
  647. Joinable = true;
  648. if (!Joinable || overlapsAliases(&SrcInt, &DestInt)) {
  649. DEBUG(std::cerr << "Interference!\n");
  650. } else {
  651. DestInt.join(SrcInt, MIDefIdx);
  652. DEBUG(std::cerr << "Joined. Result = " << DestInt << "\n");
  653. if (!MRegisterInfo::isPhysicalRegister(SrcReg)) {
  654. r2iMap_.erase(SrcReg);
  655. r2rMap_[SrcReg] = DestReg;
  656. } else {
  657. // Otherwise merge the data structures the other way so we don't lose
  658. // the physreg information.
  659. r2rMap_[DestReg] = SrcReg;
  660. DestInt.reg = SrcReg;
  661. SrcInt.swap(DestInt);
  662. r2iMap_.erase(DestReg);
  663. }
  664. ++numJoins;
  665. }
  666. }
  667. }
  668. }
  669. namespace {
  670. // DepthMBBCompare - Comparison predicate that sort first based on the loop
  671. // depth of the basic block (the unsigned), and then on the MBB number.
  672. struct DepthMBBCompare {
  673. typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
  674. bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
  675. if (LHS.first > RHS.first) return true; // Deeper loops first
  676. return LHS.first == RHS.first &&
  677. LHS.second->getNumber() < RHS.second->getNumber();
  678. }
  679. };
  680. }
  681. void LiveIntervals::joinIntervals() {
  682. DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
  683. const LoopInfo &LI = getAnalysis<LoopInfo>();
  684. if (LI.begin() == LI.end()) {
  685. // If there are no loops in the function, join intervals in function order.
  686. for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
  687. I != E; ++I)
  688. joinIntervalsInMachineBB(I);
  689. } else {
  690. // Otherwise, join intervals in inner loops before other intervals.
  691. // Unfortunately we can't just iterate over loop hierarchy here because
  692. // there may be more MBB's than BB's. Collect MBB's for sorting.
  693. std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
  694. for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
  695. I != E; ++I)
  696. MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
  697. // Sort by loop depth.
  698. std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
  699. // Finally, join intervals in loop nest order.
  700. for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
  701. joinIntervalsInMachineBB(MBBs[i].second);
  702. }
  703. DEBUG(std::cerr << "*** Register mapping ***\n");
  704. DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
  705. if (r2rMap_[i])
  706. std::cerr << " reg " << i << " -> reg " << r2rMap_[i] << "\n");
  707. }
  708. /// Return true if the two specified registers belong to different register
  709. /// classes. The registers may be either phys or virt regs.
  710. bool LiveIntervals::differingRegisterClasses(unsigned RegA,
  711. unsigned RegB) const {
  712. // Get the register classes for the first reg.
  713. if (MRegisterInfo::isPhysicalRegister(RegA)) {
  714. assert(MRegisterInfo::isVirtualRegister(RegB) &&
  715. "Shouldn't consider two physregs!");
  716. return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
  717. }
  718. // Compare against the regclass for the second reg.
  719. const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
  720. if (MRegisterInfo::isVirtualRegister(RegB))
  721. return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
  722. else
  723. return !RegClass->contains(RegB);
  724. }
  725. bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
  726. const LiveInterval *RHS) const {
  727. if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
  728. if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
  729. return false; // vreg-vreg merge has no aliases!
  730. std::swap(LHS, RHS);
  731. }
  732. assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
  733. MRegisterInfo::isVirtualRegister(RHS->reg) &&
  734. "first interval must describe a physical register");
  735. for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
  736. if (RHS->overlaps(getInterval(*AS)))
  737. return true;
  738. return false;
  739. }
  740. LiveInterval LiveIntervals::createInterval(unsigned reg) {
  741. float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
  742. (float)HUGE_VAL :0.0F;
  743. return LiveInterval(reg, Weight);
  744. }