RegAllocLinearScan.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
  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 a linear scan register allocator.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #define DEBUG_TYPE "regalloc"
  14. #include "VirtRegMap.h"
  15. #include "VirtRegRewriter.h"
  16. #include "Spiller.h"
  17. #include "llvm/Function.h"
  18. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  19. #include "llvm/CodeGen/LiveStackAnalysis.h"
  20. #include "llvm/CodeGen/MachineFunctionPass.h"
  21. #include "llvm/CodeGen/MachineInstr.h"
  22. #include "llvm/CodeGen/MachineLoopInfo.h"
  23. #include "llvm/CodeGen/MachineRegisterInfo.h"
  24. #include "llvm/CodeGen/Passes.h"
  25. #include "llvm/CodeGen/RegAllocRegistry.h"
  26. #include "llvm/CodeGen/RegisterCoalescer.h"
  27. #include "llvm/Target/TargetRegisterInfo.h"
  28. #include "llvm/Target/TargetMachine.h"
  29. #include "llvm/Target/TargetOptions.h"
  30. #include "llvm/Target/TargetInstrInfo.h"
  31. #include "llvm/ADT/EquivalenceClasses.h"
  32. #include "llvm/ADT/SmallSet.h"
  33. #include "llvm/ADT/Statistic.h"
  34. #include "llvm/ADT/STLExtras.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <algorithm>
  39. #include <set>
  40. #include <queue>
  41. #include <memory>
  42. #include <cmath>
  43. using namespace llvm;
  44. STATISTIC(NumIters , "Number of iterations performed");
  45. STATISTIC(NumBacktracks, "Number of times we had to backtrack");
  46. STATISTIC(NumCoalesce, "Number of copies coalesced");
  47. STATISTIC(NumDowngrade, "Number of registers downgraded");
  48. static cl::opt<bool>
  49. NewHeuristic("new-spilling-heuristic",
  50. cl::desc("Use new spilling heuristic"),
  51. cl::init(false), cl::Hidden);
  52. static cl::opt<bool>
  53. PreSplitIntervals("pre-alloc-split",
  54. cl::desc("Pre-register allocation live interval splitting"),
  55. cl::init(false), cl::Hidden);
  56. static cl::opt<bool>
  57. NewSpillFramework("new-spill-framework",
  58. cl::desc("New spilling framework"),
  59. cl::init(false), cl::Hidden);
  60. static RegisterRegAlloc
  61. linearscanRegAlloc("linearscan", "linear scan register allocator",
  62. createLinearScanRegisterAllocator);
  63. namespace {
  64. struct RALinScan : public MachineFunctionPass {
  65. static char ID;
  66. RALinScan() : MachineFunctionPass(&ID) {}
  67. typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
  68. typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
  69. private:
  70. /// RelatedRegClasses - This structure is built the first time a function is
  71. /// compiled, and keeps track of which register classes have registers that
  72. /// belong to multiple classes or have aliases that are in other classes.
  73. EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
  74. DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
  75. // NextReloadMap - For each register in the map, it maps to the another
  76. // register which is defined by a reload from the same stack slot and
  77. // both reloads are in the same basic block.
  78. DenseMap<unsigned, unsigned> NextReloadMap;
  79. // DowngradedRegs - A set of registers which are being "downgraded", i.e.
  80. // un-favored for allocation.
  81. SmallSet<unsigned, 8> DowngradedRegs;
  82. // DowngradeMap - A map from virtual registers to physical registers being
  83. // downgraded for the virtual registers.
  84. DenseMap<unsigned, unsigned> DowngradeMap;
  85. MachineFunction* mf_;
  86. MachineRegisterInfo* mri_;
  87. const TargetMachine* tm_;
  88. const TargetRegisterInfo* tri_;
  89. const TargetInstrInfo* tii_;
  90. BitVector allocatableRegs_;
  91. LiveIntervals* li_;
  92. LiveStacks* ls_;
  93. const MachineLoopInfo *loopInfo;
  94. /// handled_ - Intervals are added to the handled_ set in the order of their
  95. /// start value. This is uses for backtracking.
  96. std::vector<LiveInterval*> handled_;
  97. /// fixed_ - Intervals that correspond to machine registers.
  98. ///
  99. IntervalPtrs fixed_;
  100. /// active_ - Intervals that are currently being processed, and which have a
  101. /// live range active for the current point.
  102. IntervalPtrs active_;
  103. /// inactive_ - Intervals that are currently being processed, but which have
  104. /// a hold at the current point.
  105. IntervalPtrs inactive_;
  106. typedef std::priority_queue<LiveInterval*,
  107. SmallVector<LiveInterval*, 64>,
  108. greater_ptr<LiveInterval> > IntervalHeap;
  109. IntervalHeap unhandled_;
  110. /// regUse_ - Tracks register usage.
  111. SmallVector<unsigned, 32> regUse_;
  112. SmallVector<unsigned, 32> regUseBackUp_;
  113. /// vrm_ - Tracks register assignments.
  114. VirtRegMap* vrm_;
  115. std::auto_ptr<VirtRegRewriter> rewriter_;
  116. std::auto_ptr<Spiller> spiller_;
  117. public:
  118. virtual const char* getPassName() const {
  119. return "Linear Scan Register Allocator";
  120. }
  121. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  122. AU.setPreservesCFG();
  123. AU.addRequired<LiveIntervals>();
  124. if (StrongPHIElim)
  125. AU.addRequiredID(StrongPHIEliminationID);
  126. // Make sure PassManager knows which analyses to make available
  127. // to coalescing and which analyses coalescing invalidates.
  128. AU.addRequiredTransitive<RegisterCoalescer>();
  129. if (PreSplitIntervals)
  130. AU.addRequiredID(PreAllocSplittingID);
  131. AU.addRequired<LiveStacks>();
  132. AU.addPreserved<LiveStacks>();
  133. AU.addRequired<MachineLoopInfo>();
  134. AU.addPreserved<MachineLoopInfo>();
  135. AU.addRequired<VirtRegMap>();
  136. AU.addPreserved<VirtRegMap>();
  137. AU.addPreservedID(MachineDominatorsID);
  138. MachineFunctionPass::getAnalysisUsage(AU);
  139. }
  140. /// runOnMachineFunction - register allocate the whole function
  141. bool runOnMachineFunction(MachineFunction&);
  142. private:
  143. /// linearScan - the linear scan algorithm
  144. void linearScan();
  145. /// initIntervalSets - initialize the interval sets.
  146. ///
  147. void initIntervalSets();
  148. /// processActiveIntervals - expire old intervals and move non-overlapping
  149. /// ones to the inactive list.
  150. void processActiveIntervals(LiveIndex CurPoint);
  151. /// processInactiveIntervals - expire old intervals and move overlapping
  152. /// ones to the active list.
  153. void processInactiveIntervals(LiveIndex CurPoint);
  154. /// hasNextReloadInterval - Return the next liveinterval that's being
  155. /// defined by a reload from the same SS as the specified one.
  156. LiveInterval *hasNextReloadInterval(LiveInterval *cur);
  157. /// DowngradeRegister - Downgrade a register for allocation.
  158. void DowngradeRegister(LiveInterval *li, unsigned Reg);
  159. /// UpgradeRegister - Upgrade a register for allocation.
  160. void UpgradeRegister(unsigned Reg);
  161. /// assignRegOrStackSlotAtInterval - assign a register if one
  162. /// is available, or spill.
  163. void assignRegOrStackSlotAtInterval(LiveInterval* cur);
  164. void updateSpillWeights(std::vector<float> &Weights,
  165. unsigned reg, float weight,
  166. const TargetRegisterClass *RC);
  167. /// findIntervalsToSpill - Determine the intervals to spill for the
  168. /// specified interval. It's passed the physical registers whose spill
  169. /// weight is the lowest among all the registers whose live intervals
  170. /// conflict with the interval.
  171. void findIntervalsToSpill(LiveInterval *cur,
  172. std::vector<std::pair<unsigned,float> > &Candidates,
  173. unsigned NumCands,
  174. SmallVector<LiveInterval*, 8> &SpillIntervals);
  175. /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
  176. /// try allocate the definition the same register as the source register
  177. /// if the register is not defined during live time of the interval. This
  178. /// eliminate a copy. This is used to coalesce copies which were not
  179. /// coalesced away before allocation either due to dest and src being in
  180. /// different register classes or because the coalescer was overly
  181. /// conservative.
  182. unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
  183. ///
  184. /// Register usage / availability tracking helpers.
  185. ///
  186. void initRegUses() {
  187. regUse_.resize(tri_->getNumRegs(), 0);
  188. regUseBackUp_.resize(tri_->getNumRegs(), 0);
  189. }
  190. void finalizeRegUses() {
  191. #ifndef NDEBUG
  192. // Verify all the registers are "freed".
  193. bool Error = false;
  194. for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
  195. if (regUse_[i] != 0) {
  196. errs() << tri_->getName(i) << " is still in use!\n";
  197. Error = true;
  198. }
  199. }
  200. if (Error)
  201. llvm_unreachable(0);
  202. #endif
  203. regUse_.clear();
  204. regUseBackUp_.clear();
  205. }
  206. void addRegUse(unsigned physReg) {
  207. assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
  208. "should be physical register!");
  209. ++regUse_[physReg];
  210. for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
  211. ++regUse_[*as];
  212. }
  213. void delRegUse(unsigned physReg) {
  214. assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
  215. "should be physical register!");
  216. assert(regUse_[physReg] != 0);
  217. --regUse_[physReg];
  218. for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
  219. assert(regUse_[*as] != 0);
  220. --regUse_[*as];
  221. }
  222. }
  223. bool isRegAvail(unsigned physReg) const {
  224. assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
  225. "should be physical register!");
  226. return regUse_[physReg] == 0;
  227. }
  228. void backUpRegUses() {
  229. regUseBackUp_ = regUse_;
  230. }
  231. void restoreRegUses() {
  232. regUse_ = regUseBackUp_;
  233. }
  234. ///
  235. /// Register handling helpers.
  236. ///
  237. /// getFreePhysReg - return a free physical register for this virtual
  238. /// register interval if we have one, otherwise return 0.
  239. unsigned getFreePhysReg(LiveInterval* cur);
  240. unsigned getFreePhysReg(LiveInterval* cur,
  241. const TargetRegisterClass *RC,
  242. unsigned MaxInactiveCount,
  243. SmallVector<unsigned, 256> &inactiveCounts,
  244. bool SkipDGRegs);
  245. /// assignVirt2StackSlot - assigns this virtual register to a
  246. /// stack slot. returns the stack slot
  247. int assignVirt2StackSlot(unsigned virtReg);
  248. void ComputeRelatedRegClasses();
  249. template <typename ItTy>
  250. void printIntervals(const char* const str, ItTy i, ItTy e) const {
  251. DEBUG({
  252. if (str)
  253. errs() << str << " intervals:\n";
  254. for (; i != e; ++i) {
  255. errs() << "\t" << *i->first << " -> ";
  256. unsigned reg = i->first->reg;
  257. if (TargetRegisterInfo::isVirtualRegister(reg))
  258. reg = vrm_->getPhys(reg);
  259. errs() << tri_->getName(reg) << '\n';
  260. }
  261. });
  262. }
  263. };
  264. char RALinScan::ID = 0;
  265. }
  266. static RegisterPass<RALinScan>
  267. X("linearscan-regalloc", "Linear Scan Register Allocator");
  268. void RALinScan::ComputeRelatedRegClasses() {
  269. // First pass, add all reg classes to the union, and determine at least one
  270. // reg class that each register is in.
  271. bool HasAliases = false;
  272. for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
  273. E = tri_->regclass_end(); RCI != E; ++RCI) {
  274. RelatedRegClasses.insert(*RCI);
  275. for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
  276. I != E; ++I) {
  277. HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
  278. const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
  279. if (PRC) {
  280. // Already processed this register. Just make sure we know that
  281. // multiple register classes share a register.
  282. RelatedRegClasses.unionSets(PRC, *RCI);
  283. } else {
  284. PRC = *RCI;
  285. }
  286. }
  287. }
  288. // Second pass, now that we know conservatively what register classes each reg
  289. // belongs to, add info about aliases. We don't need to do this for targets
  290. // without register aliases.
  291. if (HasAliases)
  292. for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
  293. I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
  294. I != E; ++I)
  295. for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
  296. RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
  297. }
  298. /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
  299. /// try allocate the definition the same register as the source register
  300. /// if the register is not defined during live time of the interval. This
  301. /// eliminate a copy. This is used to coalesce copies which were not
  302. /// coalesced away before allocation either due to dest and src being in
  303. /// different register classes or because the coalescer was overly
  304. /// conservative.
  305. unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
  306. unsigned Preference = vrm_->getRegAllocPref(cur.reg);
  307. if ((Preference && Preference == Reg) || !cur.containsOneValue())
  308. return Reg;
  309. VNInfo *vni = cur.begin()->valno;
  310. if ((vni->def == LiveIndex()) ||
  311. vni->isUnused() || !vni->isDefAccurate())
  312. return Reg;
  313. MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
  314. unsigned SrcReg, DstReg, SrcSubReg, DstSubReg, PhysReg;
  315. if (!CopyMI ||
  316. !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
  317. return Reg;
  318. PhysReg = SrcReg;
  319. if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
  320. if (!vrm_->isAssignedReg(SrcReg))
  321. return Reg;
  322. PhysReg = vrm_->getPhys(SrcReg);
  323. }
  324. if (Reg == PhysReg)
  325. return Reg;
  326. const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
  327. if (!RC->contains(PhysReg))
  328. return Reg;
  329. // Try to coalesce.
  330. if (!li_->conflictsWithPhysRegDef(cur, *vrm_, PhysReg)) {
  331. DEBUG(errs() << "Coalescing: " << cur << " -> " << tri_->getName(PhysReg)
  332. << '\n');
  333. vrm_->clearVirt(cur.reg);
  334. vrm_->assignVirt2Phys(cur.reg, PhysReg);
  335. // Remove unnecessary kills since a copy does not clobber the register.
  336. if (li_->hasInterval(SrcReg)) {
  337. LiveInterval &SrcLI = li_->getInterval(SrcReg);
  338. for (MachineRegisterInfo::use_iterator I = mri_->use_begin(cur.reg),
  339. E = mri_->use_end(); I != E; ++I) {
  340. MachineOperand &O = I.getOperand();
  341. if (!O.isKill())
  342. continue;
  343. MachineInstr *MI = &*I;
  344. if (SrcLI.liveAt(li_->getDefIndex(li_->getInstructionIndex(MI))))
  345. O.setIsKill(false);
  346. }
  347. }
  348. ++NumCoalesce;
  349. return PhysReg;
  350. }
  351. return Reg;
  352. }
  353. bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
  354. mf_ = &fn;
  355. mri_ = &fn.getRegInfo();
  356. tm_ = &fn.getTarget();
  357. tri_ = tm_->getRegisterInfo();
  358. tii_ = tm_->getInstrInfo();
  359. allocatableRegs_ = tri_->getAllocatableSet(fn);
  360. li_ = &getAnalysis<LiveIntervals>();
  361. ls_ = &getAnalysis<LiveStacks>();
  362. loopInfo = &getAnalysis<MachineLoopInfo>();
  363. // We don't run the coalescer here because we have no reason to
  364. // interact with it. If the coalescer requires interaction, it
  365. // won't do anything. If it doesn't require interaction, we assume
  366. // it was run as a separate pass.
  367. // If this is the first function compiled, compute the related reg classes.
  368. if (RelatedRegClasses.empty())
  369. ComputeRelatedRegClasses();
  370. // Also resize register usage trackers.
  371. initRegUses();
  372. vrm_ = &getAnalysis<VirtRegMap>();
  373. if (!rewriter_.get()) rewriter_.reset(createVirtRegRewriter());
  374. if (NewSpillFramework) {
  375. spiller_.reset(createSpiller(mf_, li_, ls_, vrm_));
  376. }
  377. initIntervalSets();
  378. linearScan();
  379. // Rewrite spill code and update the PhysRegsUsed set.
  380. rewriter_->runOnMachineFunction(*mf_, *vrm_, li_);
  381. assert(unhandled_.empty() && "Unhandled live intervals remain!");
  382. finalizeRegUses();
  383. fixed_.clear();
  384. active_.clear();
  385. inactive_.clear();
  386. handled_.clear();
  387. NextReloadMap.clear();
  388. DowngradedRegs.clear();
  389. DowngradeMap.clear();
  390. spiller_.reset(0);
  391. return true;
  392. }
  393. /// initIntervalSets - initialize the interval sets.
  394. ///
  395. void RALinScan::initIntervalSets()
  396. {
  397. assert(unhandled_.empty() && fixed_.empty() &&
  398. active_.empty() && inactive_.empty() &&
  399. "interval sets should be empty on initialization");
  400. handled_.reserve(li_->getNumIntervals());
  401. for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
  402. if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
  403. mri_->setPhysRegUsed(i->second->reg);
  404. fixed_.push_back(std::make_pair(i->second, i->second->begin()));
  405. } else
  406. unhandled_.push(i->second);
  407. }
  408. }
  409. void RALinScan::linearScan() {
  410. // linear scan algorithm
  411. DEBUG({
  412. errs() << "********** LINEAR SCAN **********\n"
  413. << "********** Function: "
  414. << mf_->getFunction()->getName() << '\n';
  415. printIntervals("fixed", fixed_.begin(), fixed_.end());
  416. });
  417. while (!unhandled_.empty()) {
  418. // pick the interval with the earliest start point
  419. LiveInterval* cur = unhandled_.top();
  420. unhandled_.pop();
  421. ++NumIters;
  422. DEBUG(errs() << "\n*** CURRENT ***: " << *cur << '\n');
  423. if (!cur->empty()) {
  424. processActiveIntervals(cur->beginIndex());
  425. processInactiveIntervals(cur->beginIndex());
  426. assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
  427. "Can only allocate virtual registers!");
  428. }
  429. // Allocating a virtual register. try to find a free
  430. // physical register or spill an interval (possibly this one) in order to
  431. // assign it one.
  432. assignRegOrStackSlotAtInterval(cur);
  433. DEBUG({
  434. printIntervals("active", active_.begin(), active_.end());
  435. printIntervals("inactive", inactive_.begin(), inactive_.end());
  436. });
  437. }
  438. // Expire any remaining active intervals
  439. while (!active_.empty()) {
  440. IntervalPtr &IP = active_.back();
  441. unsigned reg = IP.first->reg;
  442. DEBUG(errs() << "\tinterval " << *IP.first << " expired\n");
  443. assert(TargetRegisterInfo::isVirtualRegister(reg) &&
  444. "Can only allocate virtual registers!");
  445. reg = vrm_->getPhys(reg);
  446. delRegUse(reg);
  447. active_.pop_back();
  448. }
  449. // Expire any remaining inactive intervals
  450. DEBUG({
  451. for (IntervalPtrs::reverse_iterator
  452. i = inactive_.rbegin(); i != inactive_.rend(); ++i)
  453. errs() << "\tinterval " << *i->first << " expired\n";
  454. });
  455. inactive_.clear();
  456. // Add live-ins to every BB except for entry. Also perform trivial coalescing.
  457. MachineFunction::iterator EntryMBB = mf_->begin();
  458. SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
  459. for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
  460. LiveInterval &cur = *i->second;
  461. unsigned Reg = 0;
  462. bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
  463. if (isPhys)
  464. Reg = cur.reg;
  465. else if (vrm_->isAssignedReg(cur.reg))
  466. Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
  467. if (!Reg)
  468. continue;
  469. // Ignore splited live intervals.
  470. if (!isPhys && vrm_->getPreSplitReg(cur.reg))
  471. continue;
  472. for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
  473. I != E; ++I) {
  474. const LiveRange &LR = *I;
  475. if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
  476. for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
  477. if (LiveInMBBs[i] != EntryMBB) {
  478. assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
  479. "Adding a virtual register to livein set?");
  480. LiveInMBBs[i]->addLiveIn(Reg);
  481. }
  482. LiveInMBBs.clear();
  483. }
  484. }
  485. }
  486. DEBUG(errs() << *vrm_);
  487. // Look for physical registers that end up not being allocated even though
  488. // register allocator had to spill other registers in its register class.
  489. if (ls_->getNumIntervals() == 0)
  490. return;
  491. if (!vrm_->FindUnusedRegisters(li_))
  492. return;
  493. }
  494. /// processActiveIntervals - expire old intervals and move non-overlapping ones
  495. /// to the inactive list.
  496. void RALinScan::processActiveIntervals(LiveIndex CurPoint)
  497. {
  498. DEBUG(errs() << "\tprocessing active intervals:\n");
  499. for (unsigned i = 0, e = active_.size(); i != e; ++i) {
  500. LiveInterval *Interval = active_[i].first;
  501. LiveInterval::iterator IntervalPos = active_[i].second;
  502. unsigned reg = Interval->reg;
  503. IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
  504. if (IntervalPos == Interval->end()) { // Remove expired intervals.
  505. DEBUG(errs() << "\t\tinterval " << *Interval << " expired\n");
  506. assert(TargetRegisterInfo::isVirtualRegister(reg) &&
  507. "Can only allocate virtual registers!");
  508. reg = vrm_->getPhys(reg);
  509. delRegUse(reg);
  510. // Pop off the end of the list.
  511. active_[i] = active_.back();
  512. active_.pop_back();
  513. --i; --e;
  514. } else if (IntervalPos->start > CurPoint) {
  515. // Move inactive intervals to inactive list.
  516. DEBUG(errs() << "\t\tinterval " << *Interval << " inactive\n");
  517. assert(TargetRegisterInfo::isVirtualRegister(reg) &&
  518. "Can only allocate virtual registers!");
  519. reg = vrm_->getPhys(reg);
  520. delRegUse(reg);
  521. // add to inactive.
  522. inactive_.push_back(std::make_pair(Interval, IntervalPos));
  523. // Pop off the end of the list.
  524. active_[i] = active_.back();
  525. active_.pop_back();
  526. --i; --e;
  527. } else {
  528. // Otherwise, just update the iterator position.
  529. active_[i].second = IntervalPos;
  530. }
  531. }
  532. }
  533. /// processInactiveIntervals - expire old intervals and move overlapping
  534. /// ones to the active list.
  535. void RALinScan::processInactiveIntervals(LiveIndex CurPoint)
  536. {
  537. DEBUG(errs() << "\tprocessing inactive intervals:\n");
  538. for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
  539. LiveInterval *Interval = inactive_[i].first;
  540. LiveInterval::iterator IntervalPos = inactive_[i].second;
  541. unsigned reg = Interval->reg;
  542. IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
  543. if (IntervalPos == Interval->end()) { // remove expired intervals.
  544. DEBUG(errs() << "\t\tinterval " << *Interval << " expired\n");
  545. // Pop off the end of the list.
  546. inactive_[i] = inactive_.back();
  547. inactive_.pop_back();
  548. --i; --e;
  549. } else if (IntervalPos->start <= CurPoint) {
  550. // move re-activated intervals in active list
  551. DEBUG(errs() << "\t\tinterval " << *Interval << " active\n");
  552. assert(TargetRegisterInfo::isVirtualRegister(reg) &&
  553. "Can only allocate virtual registers!");
  554. reg = vrm_->getPhys(reg);
  555. addRegUse(reg);
  556. // add to active
  557. active_.push_back(std::make_pair(Interval, IntervalPos));
  558. // Pop off the end of the list.
  559. inactive_[i] = inactive_.back();
  560. inactive_.pop_back();
  561. --i; --e;
  562. } else {
  563. // Otherwise, just update the iterator position.
  564. inactive_[i].second = IntervalPos;
  565. }
  566. }
  567. }
  568. /// updateSpillWeights - updates the spill weights of the specifed physical
  569. /// register and its weight.
  570. void RALinScan::updateSpillWeights(std::vector<float> &Weights,
  571. unsigned reg, float weight,
  572. const TargetRegisterClass *RC) {
  573. SmallSet<unsigned, 4> Processed;
  574. SmallSet<unsigned, 4> SuperAdded;
  575. SmallVector<unsigned, 4> Supers;
  576. Weights[reg] += weight;
  577. Processed.insert(reg);
  578. for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
  579. Weights[*as] += weight;
  580. Processed.insert(*as);
  581. if (tri_->isSubRegister(*as, reg) &&
  582. SuperAdded.insert(*as) &&
  583. RC->contains(*as)) {
  584. Supers.push_back(*as);
  585. }
  586. }
  587. // If the alias is a super-register, and the super-register is in the
  588. // register class we are trying to allocate. Then add the weight to all
  589. // sub-registers of the super-register even if they are not aliases.
  590. // e.g. allocating for GR32, bh is not used, updating bl spill weight.
  591. // bl should get the same spill weight otherwise it will be choosen
  592. // as a spill candidate since spilling bh doesn't make ebx available.
  593. for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
  594. for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
  595. if (!Processed.count(*sr))
  596. Weights[*sr] += weight;
  597. }
  598. }
  599. static
  600. RALinScan::IntervalPtrs::iterator
  601. FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
  602. for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
  603. I != E; ++I)
  604. if (I->first == LI) return I;
  605. return IP.end();
  606. }
  607. static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, LiveIndex Point){
  608. for (unsigned i = 0, e = V.size(); i != e; ++i) {
  609. RALinScan::IntervalPtr &IP = V[i];
  610. LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
  611. IP.second, Point);
  612. if (I != IP.first->begin()) --I;
  613. IP.second = I;
  614. }
  615. }
  616. /// addStackInterval - Create a LiveInterval for stack if the specified live
  617. /// interval has been spilled.
  618. static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
  619. LiveIntervals *li_,
  620. MachineRegisterInfo* mri_, VirtRegMap &vrm_) {
  621. int SS = vrm_.getStackSlot(cur->reg);
  622. if (SS == VirtRegMap::NO_STACK_SLOT)
  623. return;
  624. const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
  625. LiveInterval &SI = ls_->getOrCreateInterval(SS, RC);
  626. VNInfo *VNI;
  627. if (SI.hasAtLeastOneValue())
  628. VNI = SI.getValNumInfo(0);
  629. else
  630. VNI = SI.getNextValue(LiveIndex(), 0, false,
  631. ls_->getVNInfoAllocator());
  632. LiveInterval &RI = li_->getInterval(cur->reg);
  633. // FIXME: This may be overly conservative.
  634. SI.MergeRangesInAsValue(RI, VNI);
  635. }
  636. /// getConflictWeight - Return the number of conflicts between cur
  637. /// live interval and defs and uses of Reg weighted by loop depthes.
  638. static
  639. float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
  640. MachineRegisterInfo *mri_,
  641. const MachineLoopInfo *loopInfo) {
  642. float Conflicts = 0;
  643. for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
  644. E = mri_->reg_end(); I != E; ++I) {
  645. MachineInstr *MI = &*I;
  646. if (cur->liveAt(li_->getInstructionIndex(MI))) {
  647. unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
  648. Conflicts += powf(10.0f, (float)loopDepth);
  649. }
  650. }
  651. return Conflicts;
  652. }
  653. /// findIntervalsToSpill - Determine the intervals to spill for the
  654. /// specified interval. It's passed the physical registers whose spill
  655. /// weight is the lowest among all the registers whose live intervals
  656. /// conflict with the interval.
  657. void RALinScan::findIntervalsToSpill(LiveInterval *cur,
  658. std::vector<std::pair<unsigned,float> > &Candidates,
  659. unsigned NumCands,
  660. SmallVector<LiveInterval*, 8> &SpillIntervals) {
  661. // We have figured out the *best* register to spill. But there are other
  662. // registers that are pretty good as well (spill weight within 3%). Spill
  663. // the one that has fewest defs and uses that conflict with cur.
  664. float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
  665. SmallVector<LiveInterval*, 8> SLIs[3];
  666. DEBUG({
  667. errs() << "\tConsidering " << NumCands << " candidates: ";
  668. for (unsigned i = 0; i != NumCands; ++i)
  669. errs() << tri_->getName(Candidates[i].first) << " ";
  670. errs() << "\n";
  671. });
  672. // Calculate the number of conflicts of each candidate.
  673. for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
  674. unsigned Reg = i->first->reg;
  675. unsigned PhysReg = vrm_->getPhys(Reg);
  676. if (!cur->overlapsFrom(*i->first, i->second))
  677. continue;
  678. for (unsigned j = 0; j < NumCands; ++j) {
  679. unsigned Candidate = Candidates[j].first;
  680. if (tri_->regsOverlap(PhysReg, Candidate)) {
  681. if (NumCands > 1)
  682. Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
  683. SLIs[j].push_back(i->first);
  684. }
  685. }
  686. }
  687. for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
  688. unsigned Reg = i->first->reg;
  689. unsigned PhysReg = vrm_->getPhys(Reg);
  690. if (!cur->overlapsFrom(*i->first, i->second-1))
  691. continue;
  692. for (unsigned j = 0; j < NumCands; ++j) {
  693. unsigned Candidate = Candidates[j].first;
  694. if (tri_->regsOverlap(PhysReg, Candidate)) {
  695. if (NumCands > 1)
  696. Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
  697. SLIs[j].push_back(i->first);
  698. }
  699. }
  700. }
  701. // Which is the best candidate?
  702. unsigned BestCandidate = 0;
  703. float MinConflicts = Conflicts[0];
  704. for (unsigned i = 1; i != NumCands; ++i) {
  705. if (Conflicts[i] < MinConflicts) {
  706. BestCandidate = i;
  707. MinConflicts = Conflicts[i];
  708. }
  709. }
  710. std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
  711. std::back_inserter(SpillIntervals));
  712. }
  713. namespace {
  714. struct WeightCompare {
  715. typedef std::pair<unsigned, float> RegWeightPair;
  716. bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
  717. return LHS.second < RHS.second;
  718. }
  719. };
  720. }
  721. static bool weightsAreClose(float w1, float w2) {
  722. if (!NewHeuristic)
  723. return false;
  724. float diff = w1 - w2;
  725. if (diff <= 0.02f) // Within 0.02f
  726. return true;
  727. return (diff / w2) <= 0.05f; // Within 5%.
  728. }
  729. LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
  730. DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
  731. if (I == NextReloadMap.end())
  732. return 0;
  733. return &li_->getInterval(I->second);
  734. }
  735. void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
  736. bool isNew = DowngradedRegs.insert(Reg);
  737. isNew = isNew; // Silence compiler warning.
  738. assert(isNew && "Multiple reloads holding the same register?");
  739. DowngradeMap.insert(std::make_pair(li->reg, Reg));
  740. for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
  741. isNew = DowngradedRegs.insert(*AS);
  742. isNew = isNew; // Silence compiler warning.
  743. assert(isNew && "Multiple reloads holding the same register?");
  744. DowngradeMap.insert(std::make_pair(li->reg, *AS));
  745. }
  746. ++NumDowngrade;
  747. }
  748. void RALinScan::UpgradeRegister(unsigned Reg) {
  749. if (Reg) {
  750. DowngradedRegs.erase(Reg);
  751. for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
  752. DowngradedRegs.erase(*AS);
  753. }
  754. }
  755. namespace {
  756. struct LISorter {
  757. bool operator()(LiveInterval* A, LiveInterval* B) {
  758. return A->beginIndex() < B->beginIndex();
  759. }
  760. };
  761. }
  762. /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
  763. /// spill.
  764. void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur) {
  765. DEBUG(errs() << "\tallocating current interval: ");
  766. // This is an implicitly defined live interval, just assign any register.
  767. const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
  768. if (cur->empty()) {
  769. unsigned physReg = vrm_->getRegAllocPref(cur->reg);
  770. if (!physReg)
  771. physReg = *RC->allocation_order_begin(*mf_);
  772. DEBUG(errs() << tri_->getName(physReg) << '\n');
  773. // Note the register is not really in use.
  774. vrm_->assignVirt2Phys(cur->reg, physReg);
  775. return;
  776. }
  777. backUpRegUses();
  778. std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
  779. LiveIndex StartPosition = cur->beginIndex();
  780. const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
  781. // If start of this live interval is defined by a move instruction and its
  782. // source is assigned a physical register that is compatible with the target
  783. // register class, then we should try to assign it the same register.
  784. // This can happen when the move is from a larger register class to a smaller
  785. // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
  786. if (!vrm_->getRegAllocPref(cur->reg) && cur->hasAtLeastOneValue()) {
  787. VNInfo *vni = cur->begin()->valno;
  788. if ((vni->def != LiveIndex()) && !vni->isUnused() &&
  789. vni->isDefAccurate()) {
  790. MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
  791. unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
  792. if (CopyMI &&
  793. tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
  794. unsigned Reg = 0;
  795. if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
  796. Reg = SrcReg;
  797. else if (vrm_->isAssignedReg(SrcReg))
  798. Reg = vrm_->getPhys(SrcReg);
  799. if (Reg) {
  800. if (SrcSubReg)
  801. Reg = tri_->getSubReg(Reg, SrcSubReg);
  802. if (DstSubReg)
  803. Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
  804. if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
  805. mri_->setRegAllocationHint(cur->reg, 0, Reg);
  806. }
  807. }
  808. }
  809. }
  810. // For every interval in inactive we overlap with, mark the
  811. // register as not free and update spill weights.
  812. for (IntervalPtrs::const_iterator i = inactive_.begin(),
  813. e = inactive_.end(); i != e; ++i) {
  814. unsigned Reg = i->first->reg;
  815. assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
  816. "Can only allocate virtual registers!");
  817. const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
  818. // If this is not in a related reg class to the register we're allocating,
  819. // don't check it.
  820. if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
  821. cur->overlapsFrom(*i->first, i->second-1)) {
  822. Reg = vrm_->getPhys(Reg);
  823. addRegUse(Reg);
  824. SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
  825. }
  826. }
  827. // Speculatively check to see if we can get a register right now. If not,
  828. // we know we won't be able to by adding more constraints. If so, we can
  829. // check to see if it is valid. Doing an exhaustive search of the fixed_ list
  830. // is very bad (it contains all callee clobbered registers for any functions
  831. // with a call), so we want to avoid doing that if possible.
  832. unsigned physReg = getFreePhysReg(cur);
  833. unsigned BestPhysReg = physReg;
  834. if (physReg) {
  835. // We got a register. However, if it's in the fixed_ list, we might
  836. // conflict with it. Check to see if we conflict with it or any of its
  837. // aliases.
  838. SmallSet<unsigned, 8> RegAliases;
  839. for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
  840. RegAliases.insert(*AS);
  841. bool ConflictsWithFixed = false;
  842. for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
  843. IntervalPtr &IP = fixed_[i];
  844. if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
  845. // Okay, this reg is on the fixed list. Check to see if we actually
  846. // conflict.
  847. LiveInterval *I = IP.first;
  848. if (I->endIndex() > StartPosition) {
  849. LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
  850. IP.second = II;
  851. if (II != I->begin() && II->start > StartPosition)
  852. --II;
  853. if (cur->overlapsFrom(*I, II)) {
  854. ConflictsWithFixed = true;
  855. break;
  856. }
  857. }
  858. }
  859. }
  860. // Okay, the register picked by our speculative getFreePhysReg call turned
  861. // out to be in use. Actually add all of the conflicting fixed registers to
  862. // regUse_ so we can do an accurate query.
  863. if (ConflictsWithFixed) {
  864. // For every interval in fixed we overlap with, mark the register as not
  865. // free and update spill weights.
  866. for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
  867. IntervalPtr &IP = fixed_[i];
  868. LiveInterval *I = IP.first;
  869. const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
  870. if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
  871. I->endIndex() > StartPosition) {
  872. LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
  873. IP.second = II;
  874. if (II != I->begin() && II->start > StartPosition)
  875. --II;
  876. if (cur->overlapsFrom(*I, II)) {
  877. unsigned reg = I->reg;
  878. addRegUse(reg);
  879. SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
  880. }
  881. }
  882. }
  883. // Using the newly updated regUse_ object, which includes conflicts in the
  884. // future, see if there are any registers available.
  885. physReg = getFreePhysReg(cur);
  886. }
  887. }
  888. // Restore the physical register tracker, removing information about the
  889. // future.
  890. restoreRegUses();
  891. // If we find a free register, we are done: assign this virtual to
  892. // the free physical register and add this interval to the active
  893. // list.
  894. if (physReg) {
  895. DEBUG(errs() << tri_->getName(physReg) << '\n');
  896. vrm_->assignVirt2Phys(cur->reg, physReg);
  897. addRegUse(physReg);
  898. active_.push_back(std::make_pair(cur, cur->begin()));
  899. handled_.push_back(cur);
  900. // "Upgrade" the physical register since it has been allocated.
  901. UpgradeRegister(physReg);
  902. if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
  903. // "Downgrade" physReg to try to keep physReg from being allocated until
  904. // the next reload from the same SS is allocated.
  905. mri_->setRegAllocationHint(NextReloadLI->reg, 0, physReg);
  906. DowngradeRegister(cur, physReg);
  907. }
  908. return;
  909. }
  910. DEBUG(errs() << "no free registers\n");
  911. // Compile the spill weights into an array that is better for scanning.
  912. std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
  913. for (std::vector<std::pair<unsigned, float> >::iterator
  914. I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
  915. updateSpillWeights(SpillWeights, I->first, I->second, RC);
  916. // for each interval in active, update spill weights.
  917. for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
  918. i != e; ++i) {
  919. unsigned reg = i->first->reg;
  920. assert(TargetRegisterInfo::isVirtualRegister(reg) &&
  921. "Can only allocate virtual registers!");
  922. reg = vrm_->getPhys(reg);
  923. updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
  924. }
  925. DEBUG(errs() << "\tassigning stack slot at interval "<< *cur << ":\n");
  926. // Find a register to spill.
  927. float minWeight = HUGE_VALF;
  928. unsigned minReg = 0;
  929. bool Found = false;
  930. std::vector<std::pair<unsigned,float> > RegsWeights;
  931. if (!minReg || SpillWeights[minReg] == HUGE_VALF)
  932. for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
  933. e = RC->allocation_order_end(*mf_); i != e; ++i) {
  934. unsigned reg = *i;
  935. float regWeight = SpillWeights[reg];
  936. if (minWeight > regWeight)
  937. Found = true;
  938. RegsWeights.push_back(std::make_pair(reg, regWeight));
  939. }
  940. // If we didn't find a register that is spillable, try aliases?
  941. if (!Found) {
  942. for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
  943. e = RC->allocation_order_end(*mf_); i != e; ++i) {
  944. unsigned reg = *i;
  945. // No need to worry about if the alias register size < regsize of RC.
  946. // We are going to spill all registers that alias it anyway.
  947. for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
  948. RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
  949. }
  950. }
  951. // Sort all potential spill candidates by weight.
  952. std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
  953. minReg = RegsWeights[0].first;
  954. minWeight = RegsWeights[0].second;
  955. if (minWeight == HUGE_VALF) {
  956. // All registers must have inf weight. Just grab one!
  957. minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
  958. if (cur->weight == HUGE_VALF ||
  959. li_->getApproximateInstructionCount(*cur) == 0) {
  960. // Spill a physical register around defs and uses.
  961. if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
  962. // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
  963. // in fixed_. Reset them.
  964. for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
  965. IntervalPtr &IP = fixed_[i];
  966. LiveInterval *I = IP.first;
  967. if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
  968. IP.second = I->advanceTo(I->begin(), StartPosition);
  969. }
  970. DowngradedRegs.clear();
  971. assignRegOrStackSlotAtInterval(cur);
  972. } else {
  973. llvm_report_error("Ran out of registers during register allocation!");
  974. }
  975. return;
  976. }
  977. }
  978. // Find up to 3 registers to consider as spill candidates.
  979. unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
  980. while (LastCandidate > 1) {
  981. if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
  982. break;
  983. --LastCandidate;
  984. }
  985. DEBUG({
  986. errs() << "\t\tregister(s) with min weight(s): ";
  987. for (unsigned i = 0; i != LastCandidate; ++i)
  988. errs() << tri_->getName(RegsWeights[i].first)
  989. << " (" << RegsWeights[i].second << ")\n";
  990. });
  991. // If the current has the minimum weight, we need to spill it and
  992. // add any added intervals back to unhandled, and restart
  993. // linearscan.
  994. if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
  995. DEBUG(errs() << "\t\t\tspilling(c): " << *cur << '\n');
  996. SmallVector<LiveInterval*, 8> spillIs;
  997. std::vector<LiveInterval*> added;
  998. if (!NewSpillFramework) {
  999. added = li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_);
  1000. } else {
  1001. added = spiller_->spill(cur);
  1002. }
  1003. std::sort(added.begin(), added.end(), LISorter());
  1004. addStackInterval(cur, ls_, li_, mri_, *vrm_);
  1005. if (added.empty())
  1006. return; // Early exit if all spills were folded.
  1007. // Merge added with unhandled. Note that we have already sorted
  1008. // intervals returned by addIntervalsForSpills by their starting
  1009. // point.
  1010. // This also update the NextReloadMap. That is, it adds mapping from a
  1011. // register defined by a reload from SS to the next reload from SS in the
  1012. // same basic block.
  1013. MachineBasicBlock *LastReloadMBB = 0;
  1014. LiveInterval *LastReload = 0;
  1015. int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
  1016. for (unsigned i = 0, e = added.size(); i != e; ++i) {
  1017. LiveInterval *ReloadLi = added[i];
  1018. if (ReloadLi->weight == HUGE_VALF &&
  1019. li_->getApproximateInstructionCount(*ReloadLi) == 0) {
  1020. LiveIndex ReloadIdx = ReloadLi->beginIndex();
  1021. MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
  1022. int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
  1023. if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
  1024. // Last reload of same SS is in the same MBB. We want to try to
  1025. // allocate both reloads the same register and make sure the reg
  1026. // isn't clobbered in between if at all possible.
  1027. assert(LastReload->beginIndex() < ReloadIdx);
  1028. NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
  1029. }
  1030. LastReloadMBB = ReloadMBB;
  1031. LastReload = ReloadLi;
  1032. LastReloadSS = ReloadSS;
  1033. }
  1034. unhandled_.push(ReloadLi);
  1035. }
  1036. return;
  1037. }
  1038. ++NumBacktracks;
  1039. // Push the current interval back to unhandled since we are going
  1040. // to re-run at least this iteration. Since we didn't modify it it
  1041. // should go back right in the front of the list
  1042. unhandled_.push(cur);
  1043. assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
  1044. "did not choose a register to spill?");
  1045. // We spill all intervals aliasing the register with
  1046. // minimum weight, rollback to the interval with the earliest
  1047. // start point and let the linear scan algorithm run again
  1048. SmallVector<LiveInterval*, 8> spillIs;
  1049. // Determine which intervals have to be spilled.
  1050. findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
  1051. // Set of spilled vregs (used later to rollback properly)
  1052. SmallSet<unsigned, 8> spilled;
  1053. // The earliest start of a Spilled interval indicates up to where
  1054. // in handled we need to roll back
  1055. LiveInterval *earliestStartInterval = cur;
  1056. // Spill live intervals of virtual regs mapped to the physical register we
  1057. // want to clear (and its aliases). We only spill those that overlap with the
  1058. // current interval as the rest do not affect its allocation. we also keep
  1059. // track of the earliest start of all spilled live intervals since this will
  1060. // mark our rollback point.
  1061. std::vector<LiveInterval*> added;
  1062. while (!spillIs.empty()) {
  1063. LiveInterval *sli = spillIs.back();
  1064. spillIs.pop_back();
  1065. DEBUG(errs() << "\t\t\tspilling(a): " << *sli << '\n');
  1066. earliestStartInterval =
  1067. (earliestStartInterval->beginIndex() < sli->beginIndex()) ?
  1068. earliestStartInterval : sli;
  1069. std::vector<LiveInterval*> newIs;
  1070. if (!NewSpillFramework) {
  1071. newIs = li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_);
  1072. } else {
  1073. newIs = spiller_->spill(sli);
  1074. }
  1075. addStackInterval(sli, ls_, li_, mri_, *vrm_);
  1076. std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
  1077. spilled.insert(sli->reg);
  1078. }
  1079. LiveIndex earliestStart = earliestStartInterval->beginIndex();
  1080. DEBUG(errs() << "\t\trolling back to: " << earliestStart << '\n');
  1081. // Scan handled in reverse order up to the earliest start of a
  1082. // spilled live interval and undo each one, restoring the state of
  1083. // unhandled.
  1084. while (!handled_.empty()) {
  1085. LiveInterval* i = handled_.back();
  1086. // If this interval starts before t we are done.
  1087. if (i->beginIndex() < earliestStart)
  1088. break;
  1089. DEBUG(errs() << "\t\t\tundo changes for: " << *i << '\n');
  1090. handled_.pop_back();
  1091. // When undoing a live interval allocation we must know if it is active or
  1092. // inactive to properly update regUse_ and the VirtRegMap.
  1093. IntervalPtrs::iterator it;
  1094. if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
  1095. active_.erase(it);
  1096. assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
  1097. if (!spilled.count(i->reg))
  1098. unhandled_.push(i);
  1099. delRegUse(vrm_->getPhys(i->reg));
  1100. vrm_->clearVirt(i->reg);
  1101. } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
  1102. inactive_.erase(it);
  1103. assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
  1104. if (!spilled.count(i->reg))
  1105. unhandled_.push(i);
  1106. vrm_->clearVirt(i->reg);
  1107. } else {
  1108. assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
  1109. "Can only allocate virtual registers!");
  1110. vrm_->clearVirt(i->reg);
  1111. unhandled_.push(i);
  1112. }
  1113. DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
  1114. if (ii == DowngradeMap.end())
  1115. // It interval has a preference, it must be defined by a copy. Clear the
  1116. // preference now since the source interval allocation may have been
  1117. // undone as well.
  1118. mri_->setRegAllocationHint(i->reg, 0, 0);
  1119. else {
  1120. UpgradeRegister(ii->second);
  1121. }
  1122. }
  1123. // Rewind the iterators in the active, inactive, and fixed lists back to the
  1124. // point we reverted to.
  1125. RevertVectorIteratorsTo(active_, earliestStart);
  1126. RevertVectorIteratorsTo(inactive_, earliestStart);
  1127. RevertVectorIteratorsTo(fixed_, earliestStart);
  1128. // Scan the rest and undo each interval that expired after t and
  1129. // insert it in active (the next iteration of the algorithm will
  1130. // put it in inactive if required)
  1131. for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
  1132. LiveInterval *HI = handled_[i];
  1133. if (!HI->expiredAt(earliestStart) &&
  1134. HI->expiredAt(cur->beginIndex())) {
  1135. DEBUG(errs() << "\t\t\tundo changes for: " << *HI << '\n');
  1136. active_.push_back(std::make_pair(HI, HI->begin()));
  1137. assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
  1138. addRegUse(vrm_->getPhys(HI->reg));
  1139. }
  1140. }
  1141. // Merge added with unhandled.
  1142. // This also update the NextReloadMap. That is, it adds mapping from a
  1143. // register defined by a reload from SS to the next reload from SS in the
  1144. // same basic block.
  1145. MachineBasicBlock *LastReloadMBB = 0;
  1146. LiveInterval *LastReload = 0;
  1147. int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
  1148. std::sort(added.begin(), added.end(), LISorter());
  1149. for (unsigned i = 0, e = added.size(); i != e; ++i) {
  1150. LiveInterval *ReloadLi = added[i];
  1151. if (ReloadLi->weight == HUGE_VALF &&
  1152. li_->getApproximateInstructionCount(*ReloadLi) == 0) {
  1153. LiveIndex ReloadIdx = ReloadLi->beginIndex();
  1154. MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
  1155. int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
  1156. if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
  1157. // Last reload of same SS is in the same MBB. We want to try to
  1158. // allocate both reloads the same register and make sure the reg
  1159. // isn't clobbered in between if at all possible.
  1160. assert(LastReload->beginIndex() < ReloadIdx);
  1161. NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
  1162. }
  1163. LastReloadMBB = ReloadMBB;
  1164. LastReload = ReloadLi;
  1165. LastReloadSS = ReloadSS;
  1166. }
  1167. unhandled_.push(ReloadLi);
  1168. }
  1169. }
  1170. unsigned RALinScan::getFreePhysReg(LiveInterval* cur,
  1171. const TargetRegisterClass *RC,
  1172. unsigned MaxInactiveCount,
  1173. SmallVector<unsigned, 256> &inactiveCounts,
  1174. bool SkipDGRegs) {
  1175. unsigned FreeReg = 0;
  1176. unsigned FreeRegInactiveCount = 0;
  1177. std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(cur->reg);
  1178. // Resolve second part of the hint (if possible) given the current allocation.
  1179. unsigned physReg = Hint.second;
  1180. if (physReg &&
  1181. TargetRegisterInfo::isVirtualRegister(physReg) && vrm_->hasPhys(physReg))
  1182. physReg = vrm_->getPhys(physReg);
  1183. TargetRegisterClass::iterator I, E;
  1184. tie(I, E) = tri_->getAllocationOrder(RC, Hint.first, physReg, *mf_);
  1185. assert(I != E && "No allocatable register in this register class!");
  1186. // Scan for the first available register.
  1187. for (; I != E; ++I) {
  1188. unsigned Reg = *I;
  1189. // Ignore "downgraded" registers.
  1190. if (SkipDGRegs && DowngradedRegs.count(Reg))
  1191. continue;
  1192. if (isRegAvail(Reg)) {
  1193. FreeReg = Reg;
  1194. if (FreeReg < inactiveCounts.size())
  1195. FreeRegInactiveCount = inactiveCounts[FreeReg];
  1196. else
  1197. FreeRegInactiveCount = 0;
  1198. break;
  1199. }
  1200. }
  1201. // If there are no free regs, or if this reg has the max inactive count,
  1202. // return this register.
  1203. if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount)
  1204. return FreeReg;
  1205. // Continue scanning the registers, looking for the one with the highest
  1206. // inactive count. Alkis found that this reduced register pressure very
  1207. // slightly on X86 (in rev 1.94 of this file), though this should probably be
  1208. // reevaluated now.
  1209. for (; I != E; ++I) {
  1210. unsigned Reg = *I;
  1211. // Ignore "downgraded" registers.
  1212. if (SkipDGRegs && DowngradedRegs.count(Reg))
  1213. continue;
  1214. if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
  1215. FreeRegInactiveCount < inactiveCounts[Reg]) {
  1216. FreeReg = Reg;
  1217. FreeRegInactiveCount = inactiveCounts[Reg];
  1218. if (FreeRegInactiveCount == MaxInactiveCount)
  1219. break; // We found the one with the max inactive count.
  1220. }
  1221. }
  1222. return FreeReg;
  1223. }
  1224. /// getFreePhysReg - return a free physical register for this virtual register
  1225. /// interval if we have one, otherwise return 0.
  1226. unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
  1227. SmallVector<unsigned, 256> inactiveCounts;
  1228. unsigned MaxInactiveCount = 0;
  1229. const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
  1230. const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
  1231. for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
  1232. i != e; ++i) {
  1233. unsigned reg = i->first->reg;
  1234. assert(TargetRegisterInfo::isVirtualRegister(reg) &&
  1235. "Can only allocate virtual registers!");
  1236. // If this is not in a related reg class to the register we're allocating,
  1237. // don't check it.
  1238. const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
  1239. if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
  1240. reg = vrm_->getPhys(reg);
  1241. if (inactiveCounts.size() <= reg)
  1242. inactiveCounts.resize(reg+1);
  1243. ++inactiveCounts[reg];
  1244. MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
  1245. }
  1246. }
  1247. // If copy coalescer has assigned a "preferred" register, check if it's
  1248. // available first.
  1249. unsigned Preference = vrm_->getRegAllocPref(cur->reg);
  1250. if (Preference) {
  1251. DEBUG(errs() << "(preferred: " << tri_->getName(Preference) << ") ");
  1252. if (isRegAvail(Preference) &&
  1253. RC->contains(Preference))
  1254. return Preference;
  1255. }
  1256. if (!DowngradedRegs.empty()) {
  1257. unsigned FreeReg = getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts,
  1258. true);
  1259. if (FreeReg)
  1260. return FreeReg;
  1261. }
  1262. return getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts, false);
  1263. }
  1264. FunctionPass* llvm::createLinearScanRegisterAllocator() {
  1265. return new RALinScan();
  1266. }