StackSlotColoring.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. //===-- StackSlotColoring.cpp - Stack slot coloring pass. -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the stack slot coloring pass.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #define DEBUG_TYPE "stackcoloring"
  14. #include "VirtRegMap.h"
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  17. #include "llvm/CodeGen/LiveStackAnalysis.h"
  18. #include "llvm/CodeGen/MachineFrameInfo.h"
  19. #include "llvm/CodeGen/MachineLoopInfo.h"
  20. #include "llvm/CodeGen/MachineMemOperand.h"
  21. #include "llvm/CodeGen/MachineRegisterInfo.h"
  22. #include "llvm/CodeGen/PseudoSourceValue.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Target/TargetInstrInfo.h"
  26. #include "llvm/Target/TargetMachine.h"
  27. #include "llvm/ADT/BitVector.h"
  28. #include "llvm/ADT/SmallSet.h"
  29. #include "llvm/ADT/SmallVector.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include <vector>
  32. using namespace llvm;
  33. static cl::opt<bool>
  34. DisableSharing("no-stack-slot-sharing",
  35. cl::init(false), cl::Hidden,
  36. cl::desc("Suppress slot sharing during stack coloring"));
  37. static cl::opt<bool>
  38. ColorWithRegsOpt("color-ss-with-regs",
  39. cl::init(false), cl::Hidden,
  40. cl::desc("Color stack slots with free registers"));
  41. static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
  42. STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
  43. STATISTIC(NumRegRepl, "Number of stack slot refs replaced with reg refs");
  44. STATISTIC(NumLoadElim, "Number of loads eliminated");
  45. STATISTIC(NumStoreElim, "Number of stores eliminated");
  46. STATISTIC(NumDead, "Number of trivially dead stack accesses eliminated");
  47. namespace {
  48. class StackSlotColoring : public MachineFunctionPass {
  49. bool ColorWithRegs;
  50. LiveStacks* LS;
  51. VirtRegMap* VRM;
  52. MachineFrameInfo *MFI;
  53. MachineRegisterInfo *MRI;
  54. const TargetInstrInfo *TII;
  55. const TargetRegisterInfo *TRI;
  56. const MachineLoopInfo *loopInfo;
  57. // SSIntervals - Spill slot intervals.
  58. std::vector<LiveInterval*> SSIntervals;
  59. // SSRefs - Keep a list of frame index references for each spill slot.
  60. SmallVector<SmallVector<MachineInstr*, 8>, 16> SSRefs;
  61. // OrigAlignments - Alignments of stack objects before coloring.
  62. SmallVector<unsigned, 16> OrigAlignments;
  63. // OrigSizes - Sizess of stack objects before coloring.
  64. SmallVector<unsigned, 16> OrigSizes;
  65. // AllColors - If index is set, it's a spill slot, i.e. color.
  66. // FIXME: This assumes PEI locate spill slot with smaller indices
  67. // closest to stack pointer / frame pointer. Therefore, smaller
  68. // index == better color.
  69. BitVector AllColors;
  70. // NextColor - Next "color" that's not yet used.
  71. int NextColor;
  72. // UsedColors - "Colors" that have been assigned.
  73. BitVector UsedColors;
  74. // Assignments - Color to intervals mapping.
  75. SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
  76. public:
  77. static char ID; // Pass identification
  78. StackSlotColoring() :
  79. MachineFunctionPass(&ID), ColorWithRegs(false), NextColor(-1) {}
  80. StackSlotColoring(bool RegColor) :
  81. MachineFunctionPass(&ID), ColorWithRegs(RegColor), NextColor(-1) {}
  82. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  83. AU.setPreservesCFG();
  84. AU.addRequired<SlotIndexes>();
  85. AU.addPreserved<SlotIndexes>();
  86. AU.addRequired<LiveStacks>();
  87. AU.addRequired<VirtRegMap>();
  88. AU.addPreserved<VirtRegMap>();
  89. AU.addRequired<MachineLoopInfo>();
  90. AU.addPreserved<MachineLoopInfo>();
  91. AU.addPreservedID(MachineDominatorsID);
  92. MachineFunctionPass::getAnalysisUsage(AU);
  93. }
  94. virtual bool runOnMachineFunction(MachineFunction &MF);
  95. virtual const char* getPassName() const {
  96. return "Stack Slot Coloring";
  97. }
  98. private:
  99. void InitializeSlots();
  100. void ScanForSpillSlotRefs(MachineFunction &MF);
  101. bool OverlapWithAssignments(LiveInterval *li, int Color) const;
  102. int ColorSlot(LiveInterval *li);
  103. bool ColorSlots(MachineFunction &MF);
  104. bool ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMapping,
  105. SmallVector<SmallVector<int, 4>, 16> &RevMap,
  106. BitVector &SlotIsReg);
  107. void RewriteInstruction(MachineInstr *MI, int OldFI, int NewFI,
  108. MachineFunction &MF);
  109. bool PropagateBackward(MachineBasicBlock::iterator MII,
  110. MachineBasicBlock *MBB,
  111. unsigned OldReg, unsigned NewReg);
  112. bool PropagateForward(MachineBasicBlock::iterator MII,
  113. MachineBasicBlock *MBB,
  114. unsigned OldReg, unsigned NewReg);
  115. void UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
  116. unsigned Reg, const TargetRegisterClass *RC,
  117. SmallSet<unsigned, 4> &Defs,
  118. MachineFunction &MF);
  119. bool AllMemRefsCanBeUnfolded(int SS);
  120. bool RemoveDeadStores(MachineBasicBlock* MBB);
  121. };
  122. } // end anonymous namespace
  123. char StackSlotColoring::ID = 0;
  124. static RegisterPass<StackSlotColoring>
  125. X("stack-slot-coloring", "Stack Slot Coloring");
  126. FunctionPass *llvm::createStackSlotColoringPass(bool RegColor) {
  127. return new StackSlotColoring(RegColor);
  128. }
  129. namespace {
  130. // IntervalSorter - Comparison predicate that sort live intervals by
  131. // their weight.
  132. struct IntervalSorter {
  133. bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
  134. return LHS->weight > RHS->weight;
  135. }
  136. };
  137. }
  138. /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
  139. /// references and update spill slot weights.
  140. void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
  141. SSRefs.resize(MFI->getObjectIndexEnd());
  142. // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
  143. for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
  144. MBBI != E; ++MBBI) {
  145. MachineBasicBlock *MBB = &*MBBI;
  146. unsigned loopDepth = loopInfo->getLoopDepth(MBB);
  147. for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
  148. MII != EE; ++MII) {
  149. MachineInstr *MI = &*MII;
  150. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  151. MachineOperand &MO = MI->getOperand(i);
  152. if (!MO.isFI())
  153. continue;
  154. int FI = MO.getIndex();
  155. if (FI < 0)
  156. continue;
  157. if (!LS->hasInterval(FI))
  158. continue;
  159. LiveInterval &li = LS->getInterval(FI);
  160. li.weight += LiveIntervals::getSpillWeight(false, true, loopDepth);
  161. SSRefs[FI].push_back(MI);
  162. }
  163. }
  164. }
  165. }
  166. /// InitializeSlots - Process all spill stack slot liveintervals and add them
  167. /// to a sorted (by weight) list.
  168. void StackSlotColoring::InitializeSlots() {
  169. int LastFI = MFI->getObjectIndexEnd();
  170. OrigAlignments.resize(LastFI);
  171. OrigSizes.resize(LastFI);
  172. AllColors.resize(LastFI);
  173. UsedColors.resize(LastFI);
  174. Assignments.resize(LastFI);
  175. // Gather all spill slots into a list.
  176. DEBUG(dbgs() << "Spill slot intervals:\n");
  177. for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
  178. LiveInterval &li = i->second;
  179. DEBUG(li.dump());
  180. int FI = li.getStackSlotIndex();
  181. if (MFI->isDeadObjectIndex(FI))
  182. continue;
  183. SSIntervals.push_back(&li);
  184. OrigAlignments[FI] = MFI->getObjectAlignment(FI);
  185. OrigSizes[FI] = MFI->getObjectSize(FI);
  186. AllColors.set(FI);
  187. }
  188. DEBUG(dbgs() << '\n');
  189. // Sort them by weight.
  190. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  191. // Get first "color".
  192. NextColor = AllColors.find_first();
  193. }
  194. /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
  195. /// LiveIntervals that have already been assigned to the specified color.
  196. bool
  197. StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
  198. const SmallVector<LiveInterval*,4> &OtherLIs = Assignments[Color];
  199. for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
  200. LiveInterval *OtherLI = OtherLIs[i];
  201. if (OtherLI->overlaps(*li))
  202. return true;
  203. }
  204. return false;
  205. }
  206. /// ColorSlotsWithFreeRegs - If there are any free registers available, try
  207. /// replacing spill slots references with registers instead.
  208. bool
  209. StackSlotColoring::ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMapping,
  210. SmallVector<SmallVector<int, 4>, 16> &RevMap,
  211. BitVector &SlotIsReg) {
  212. if (!(ColorWithRegs || ColorWithRegsOpt) || !VRM->HasUnusedRegisters())
  213. return false;
  214. bool Changed = false;
  215. DEBUG(dbgs() << "Assigning unused registers to spill slots:\n");
  216. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  217. LiveInterval *li = SSIntervals[i];
  218. int SS = li->getStackSlotIndex();
  219. if (!UsedColors[SS] || li->weight < 20)
  220. // If the weight is < 20, i.e. two references in a loop with depth 1,
  221. // don't bother with it.
  222. continue;
  223. // These slots allow to share the same registers.
  224. bool AllColored = true;
  225. SmallVector<unsigned, 4> ColoredRegs;
  226. for (unsigned j = 0, ee = RevMap[SS].size(); j != ee; ++j) {
  227. int RSS = RevMap[SS][j];
  228. const TargetRegisterClass *RC = LS->getIntervalRegClass(RSS);
  229. // If it's not colored to another stack slot, try coloring it
  230. // to a "free" register.
  231. if (!RC) {
  232. AllColored = false;
  233. continue;
  234. }
  235. unsigned Reg = VRM->getFirstUnusedRegister(RC);
  236. if (!Reg) {
  237. AllColored = false;
  238. continue;
  239. }
  240. if (!AllMemRefsCanBeUnfolded(RSS)) {
  241. AllColored = false;
  242. continue;
  243. } else {
  244. DEBUG(dbgs() << "Assigning fi#" << RSS << " to "
  245. << TRI->getName(Reg) << '\n');
  246. ColoredRegs.push_back(Reg);
  247. SlotMapping[RSS] = Reg;
  248. SlotIsReg.set(RSS);
  249. Changed = true;
  250. }
  251. }
  252. // Register and its sub-registers are no longer free.
  253. while (!ColoredRegs.empty()) {
  254. unsigned Reg = ColoredRegs.back();
  255. ColoredRegs.pop_back();
  256. VRM->setRegisterUsed(Reg);
  257. // If reg is a callee-saved register, it will have to be spilled in
  258. // the prologue.
  259. MRI->setPhysRegUsed(Reg);
  260. for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
  261. VRM->setRegisterUsed(*AS);
  262. MRI->setPhysRegUsed(*AS);
  263. }
  264. }
  265. // This spill slot is dead after the rewrites
  266. if (AllColored) {
  267. MFI->RemoveStackObject(SS);
  268. ++NumEliminated;
  269. }
  270. }
  271. DEBUG(dbgs() << '\n');
  272. return Changed;
  273. }
  274. /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
  275. ///
  276. int StackSlotColoring::ColorSlot(LiveInterval *li) {
  277. int Color = -1;
  278. bool Share = false;
  279. if (!DisableSharing) {
  280. // Check if it's possible to reuse any of the used colors.
  281. Color = UsedColors.find_first();
  282. while (Color != -1) {
  283. if (!OverlapWithAssignments(li, Color)) {
  284. Share = true;
  285. ++NumEliminated;
  286. break;
  287. }
  288. Color = UsedColors.find_next(Color);
  289. }
  290. }
  291. // Assign it to the first available color (assumed to be the best) if it's
  292. // not possible to share a used color with other objects.
  293. if (!Share) {
  294. assert(NextColor != -1 && "No more spill slots?");
  295. Color = NextColor;
  296. UsedColors.set(Color);
  297. NextColor = AllColors.find_next(NextColor);
  298. }
  299. // Record the assignment.
  300. Assignments[Color].push_back(li);
  301. int FI = li->getStackSlotIndex();
  302. DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
  303. // Change size and alignment of the allocated slot. If there are multiple
  304. // objects sharing the same slot, then make sure the size and alignment
  305. // are large enough for all.
  306. unsigned Align = OrigAlignments[FI];
  307. if (!Share || Align > MFI->getObjectAlignment(Color))
  308. MFI->setObjectAlignment(Color, Align);
  309. int64_t Size = OrigSizes[FI];
  310. if (!Share || Size > MFI->getObjectSize(Color))
  311. MFI->setObjectSize(Color, Size);
  312. return Color;
  313. }
  314. /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
  315. /// operands in the function.
  316. bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
  317. unsigned NumObjs = MFI->getObjectIndexEnd();
  318. SmallVector<int, 16> SlotMapping(NumObjs, -1);
  319. SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
  320. SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
  321. BitVector SlotIsReg(NumObjs);
  322. BitVector UsedColors(NumObjs);
  323. DEBUG(dbgs() << "Color spill slot intervals:\n");
  324. bool Changed = false;
  325. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  326. LiveInterval *li = SSIntervals[i];
  327. int SS = li->getStackSlotIndex();
  328. int NewSS = ColorSlot(li);
  329. assert(NewSS >= 0 && "Stack coloring failed?");
  330. SlotMapping[SS] = NewSS;
  331. RevMap[NewSS].push_back(SS);
  332. SlotWeights[NewSS] += li->weight;
  333. UsedColors.set(NewSS);
  334. Changed |= (SS != NewSS);
  335. }
  336. DEBUG(dbgs() << "\nSpill slots after coloring:\n");
  337. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  338. LiveInterval *li = SSIntervals[i];
  339. int SS = li->getStackSlotIndex();
  340. li->weight = SlotWeights[SS];
  341. }
  342. // Sort them by new weight.
  343. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  344. #ifndef NDEBUG
  345. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
  346. DEBUG(SSIntervals[i]->dump());
  347. DEBUG(dbgs() << '\n');
  348. #endif
  349. // Can we "color" a stack slot with a unused register?
  350. Changed |= ColorSlotsWithFreeRegs(SlotMapping, RevMap, SlotIsReg);
  351. if (!Changed)
  352. return false;
  353. // Rewrite all MO_FrameIndex operands.
  354. SmallVector<SmallSet<unsigned, 4>, 4> NewDefs(MF.getNumBlockIDs());
  355. for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
  356. bool isReg = SlotIsReg[SS];
  357. int NewFI = SlotMapping[SS];
  358. if (NewFI == -1 || (NewFI == (int)SS && !isReg))
  359. continue;
  360. const TargetRegisterClass *RC = LS->getIntervalRegClass(SS);
  361. SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
  362. for (unsigned i = 0, e = RefMIs.size(); i != e; ++i)
  363. if (!isReg)
  364. RewriteInstruction(RefMIs[i], SS, NewFI, MF);
  365. else {
  366. // Rewrite to use a register instead.
  367. unsigned MBBId = RefMIs[i]->getParent()->getNumber();
  368. SmallSet<unsigned, 4> &Defs = NewDefs[MBBId];
  369. UnfoldAndRewriteInstruction(RefMIs[i], SS, NewFI, RC, Defs, MF);
  370. }
  371. }
  372. // Delete unused stack slots.
  373. while (NextColor != -1) {
  374. DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
  375. MFI->RemoveStackObject(NextColor);
  376. NextColor = AllColors.find_next(NextColor);
  377. }
  378. return true;
  379. }
  380. /// AllMemRefsCanBeUnfolded - Return true if all references of the specified
  381. /// spill slot index can be unfolded.
  382. bool StackSlotColoring::AllMemRefsCanBeUnfolded(int SS) {
  383. SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
  384. for (unsigned i = 0, e = RefMIs.size(); i != e; ++i) {
  385. MachineInstr *MI = RefMIs[i];
  386. if (TII->isLoadFromStackSlot(MI, SS) ||
  387. TII->isStoreToStackSlot(MI, SS))
  388. // Restore and spill will become copies.
  389. return true;
  390. if (!TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(), false, false))
  391. return false;
  392. for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
  393. MachineOperand &MO = MI->getOperand(j);
  394. if (MO.isFI() && MO.getIndex() != SS)
  395. // If it uses another frameindex, we can, currently* unfold it.
  396. return false;
  397. }
  398. }
  399. return true;
  400. }
  401. /// RewriteInstruction - Rewrite specified instruction by replacing references
  402. /// to old frame index with new one.
  403. void StackSlotColoring::RewriteInstruction(MachineInstr *MI, int OldFI,
  404. int NewFI, MachineFunction &MF) {
  405. // Update the operands.
  406. for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
  407. MachineOperand &MO = MI->getOperand(i);
  408. if (!MO.isFI())
  409. continue;
  410. int FI = MO.getIndex();
  411. if (FI != OldFI)
  412. continue;
  413. MO.setIndex(NewFI);
  414. }
  415. // Update the memory references. This changes the MachineMemOperands
  416. // directly. They may be in use by multiple instructions, however all
  417. // instructions using OldFI are being rewritten to use NewFI.
  418. const Value *OldSV = PseudoSourceValue::getFixedStack(OldFI);
  419. const Value *NewSV = PseudoSourceValue::getFixedStack(NewFI);
  420. for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
  421. E = MI->memoperands_end(); I != E; ++I)
  422. if ((*I)->getValue() == OldSV)
  423. (*I)->setValue(NewSV);
  424. }
  425. /// PropagateBackward - Traverse backward and look for the definition of
  426. /// OldReg. If it can successfully update all of the references with NewReg,
  427. /// do so and return true.
  428. bool StackSlotColoring::PropagateBackward(MachineBasicBlock::iterator MII,
  429. MachineBasicBlock *MBB,
  430. unsigned OldReg, unsigned NewReg) {
  431. if (MII == MBB->begin())
  432. return false;
  433. SmallVector<MachineOperand*, 4> Uses;
  434. SmallVector<MachineOperand*, 4> Refs;
  435. while (--MII != MBB->begin()) {
  436. bool FoundDef = false; // Not counting 2address def.
  437. Uses.clear();
  438. const TargetInstrDesc &TID = MII->getDesc();
  439. for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
  440. MachineOperand &MO = MII->getOperand(i);
  441. if (!MO.isReg())
  442. continue;
  443. unsigned Reg = MO.getReg();
  444. if (Reg == 0)
  445. continue;
  446. if (Reg == OldReg) {
  447. if (MO.isImplicit())
  448. return false;
  449. // Abort the use is actually a sub-register def. We don't have enough
  450. // information to figure out if it is really legal.
  451. if (MO.getSubReg() || MII->isExtractSubreg() ||
  452. MII->isInsertSubreg() || MII->isSubregToReg())
  453. return false;
  454. const TargetRegisterClass *RC = TID.OpInfo[i].getRegClass(TRI);
  455. if (RC && !RC->contains(NewReg))
  456. return false;
  457. if (MO.isUse()) {
  458. Uses.push_back(&MO);
  459. } else {
  460. Refs.push_back(&MO);
  461. if (!MII->isRegTiedToUseOperand(i))
  462. FoundDef = true;
  463. }
  464. } else if (TRI->regsOverlap(Reg, NewReg)) {
  465. return false;
  466. } else if (TRI->regsOverlap(Reg, OldReg)) {
  467. if (!MO.isUse() || !MO.isKill())
  468. return false;
  469. }
  470. }
  471. if (FoundDef) {
  472. // Found non-two-address def. Stop here.
  473. for (unsigned i = 0, e = Refs.size(); i != e; ++i)
  474. Refs[i]->setReg(NewReg);
  475. return true;
  476. }
  477. // Two-address uses must be updated as well.
  478. for (unsigned i = 0, e = Uses.size(); i != e; ++i)
  479. Refs.push_back(Uses[i]);
  480. }
  481. return false;
  482. }
  483. /// PropagateForward - Traverse forward and look for the kill of OldReg. If
  484. /// it can successfully update all of the uses with NewReg, do so and
  485. /// return true.
  486. bool StackSlotColoring::PropagateForward(MachineBasicBlock::iterator MII,
  487. MachineBasicBlock *MBB,
  488. unsigned OldReg, unsigned NewReg) {
  489. if (MII == MBB->end())
  490. return false;
  491. SmallVector<MachineOperand*, 4> Uses;
  492. while (++MII != MBB->end()) {
  493. bool FoundKill = false;
  494. const TargetInstrDesc &TID = MII->getDesc();
  495. for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
  496. MachineOperand &MO = MII->getOperand(i);
  497. if (!MO.isReg())
  498. continue;
  499. unsigned Reg = MO.getReg();
  500. if (Reg == 0)
  501. continue;
  502. if (Reg == OldReg) {
  503. if (MO.isDef() || MO.isImplicit())
  504. return false;
  505. // Abort the use is actually a sub-register use. We don't have enough
  506. // information to figure out if it is really legal.
  507. if (MO.getSubReg() || MII->isExtractSubreg())
  508. return false;
  509. const TargetRegisterClass *RC = TID.OpInfo[i].getRegClass(TRI);
  510. if (RC && !RC->contains(NewReg))
  511. return false;
  512. if (MO.isKill())
  513. FoundKill = true;
  514. Uses.push_back(&MO);
  515. } else if (TRI->regsOverlap(Reg, NewReg) ||
  516. TRI->regsOverlap(Reg, OldReg))
  517. return false;
  518. }
  519. if (FoundKill) {
  520. for (unsigned i = 0, e = Uses.size(); i != e; ++i)
  521. Uses[i]->setReg(NewReg);
  522. return true;
  523. }
  524. }
  525. return false;
  526. }
  527. /// UnfoldAndRewriteInstruction - Rewrite specified instruction by unfolding
  528. /// folded memory references and replacing those references with register
  529. /// references instead.
  530. void
  531. StackSlotColoring::UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
  532. unsigned Reg,
  533. const TargetRegisterClass *RC,
  534. SmallSet<unsigned, 4> &Defs,
  535. MachineFunction &MF) {
  536. MachineBasicBlock *MBB = MI->getParent();
  537. if (unsigned DstReg = TII->isLoadFromStackSlot(MI, OldFI)) {
  538. if (PropagateForward(MI, MBB, DstReg, Reg)) {
  539. DEBUG(dbgs() << "Eliminated load: ");
  540. DEBUG(MI->dump());
  541. ++NumLoadElim;
  542. } else {
  543. TII->copyRegToReg(*MBB, MI, DstReg, Reg, RC, RC);
  544. ++NumRegRepl;
  545. }
  546. if (!Defs.count(Reg)) {
  547. // If this is the first use of Reg in this MBB and it wasn't previously
  548. // defined in MBB, add it to livein.
  549. MBB->addLiveIn(Reg);
  550. Defs.insert(Reg);
  551. }
  552. } else if (unsigned SrcReg = TII->isStoreToStackSlot(MI, OldFI)) {
  553. if (MI->killsRegister(SrcReg) && PropagateBackward(MI, MBB, SrcReg, Reg)) {
  554. DEBUG(dbgs() << "Eliminated store: ");
  555. DEBUG(MI->dump());
  556. ++NumStoreElim;
  557. } else {
  558. TII->copyRegToReg(*MBB, MI, Reg, SrcReg, RC, RC);
  559. ++NumRegRepl;
  560. }
  561. // Remember reg has been defined in MBB.
  562. Defs.insert(Reg);
  563. } else {
  564. SmallVector<MachineInstr*, 4> NewMIs;
  565. bool Success = TII->unfoldMemoryOperand(MF, MI, Reg, false, false, NewMIs);
  566. Success = Success; // Silence compiler warning.
  567. assert(Success && "Failed to unfold!");
  568. MachineInstr *NewMI = NewMIs[0];
  569. MBB->insert(MI, NewMI);
  570. ++NumRegRepl;
  571. if (NewMI->readsRegister(Reg)) {
  572. if (!Defs.count(Reg))
  573. // If this is the first use of Reg in this MBB and it wasn't previously
  574. // defined in MBB, add it to livein.
  575. MBB->addLiveIn(Reg);
  576. Defs.insert(Reg);
  577. }
  578. }
  579. MBB->erase(MI);
  580. }
  581. /// RemoveDeadStores - Scan through a basic block and look for loads followed
  582. /// by stores. If they're both using the same stack slot, then the store is
  583. /// definitely dead. This could obviously be much more aggressive (consider
  584. /// pairs with instructions between them), but such extensions might have a
  585. /// considerable compile time impact.
  586. bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
  587. // FIXME: This could be much more aggressive, but we need to investigate
  588. // the compile time impact of doing so.
  589. bool changed = false;
  590. SmallVector<MachineInstr*, 4> toErase;
  591. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  592. I != E; ++I) {
  593. if (DCELimit != -1 && (int)NumDead >= DCELimit)
  594. break;
  595. MachineBasicBlock::iterator NextMI = llvm::next(I);
  596. if (NextMI == MBB->end()) continue;
  597. int FirstSS, SecondSS;
  598. unsigned LoadReg = 0;
  599. unsigned StoreReg = 0;
  600. if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
  601. if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
  602. if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
  603. ++NumDead;
  604. changed = true;
  605. if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
  606. ++NumDead;
  607. toErase.push_back(I);
  608. }
  609. toErase.push_back(NextMI);
  610. ++I;
  611. }
  612. for (SmallVector<MachineInstr*, 4>::iterator I = toErase.begin(),
  613. E = toErase.end(); I != E; ++I)
  614. (*I)->eraseFromParent();
  615. return changed;
  616. }
  617. bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
  618. DEBUG(dbgs() << "********** Stack Slot Coloring **********\n");
  619. MFI = MF.getFrameInfo();
  620. MRI = &MF.getRegInfo();
  621. TII = MF.getTarget().getInstrInfo();
  622. TRI = MF.getTarget().getRegisterInfo();
  623. LS = &getAnalysis<LiveStacks>();
  624. VRM = &getAnalysis<VirtRegMap>();
  625. loopInfo = &getAnalysis<MachineLoopInfo>();
  626. bool Changed = false;
  627. unsigned NumSlots = LS->getNumIntervals();
  628. if (NumSlots < 2) {
  629. if (NumSlots == 0 || !VRM->HasUnusedRegisters())
  630. // Nothing to do!
  631. return false;
  632. }
  633. // Gather spill slot references
  634. ScanForSpillSlotRefs(MF);
  635. InitializeSlots();
  636. Changed = ColorSlots(MF);
  637. NextColor = -1;
  638. SSIntervals.clear();
  639. for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
  640. SSRefs[i].clear();
  641. SSRefs.clear();
  642. OrigAlignments.clear();
  643. OrigSizes.clear();
  644. AllColors.clear();
  645. UsedColors.clear();
  646. for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
  647. Assignments[i].clear();
  648. Assignments.clear();
  649. if (Changed) {
  650. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
  651. Changed |= RemoveDeadStores(I);
  652. }
  653. return Changed;
  654. }