StackSlotColoring.cpp 25 KB

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