StackSlotColoring.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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 "stackslotcoloring"
  14. #include "llvm/CodeGen/Passes.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  19. #include "llvm/CodeGen/LiveStackAnalysis.h"
  20. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  21. #include "llvm/CodeGen/MachineFrameInfo.h"
  22. #include "llvm/CodeGen/MachineInstrBuilder.h"
  23. #include "llvm/CodeGen/MachineMemOperand.h"
  24. #include "llvm/CodeGen/MachineRegisterInfo.h"
  25. #include "llvm/CodeGen/PseudoSourceValue.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Target/TargetInstrInfo.h"
  31. #include "llvm/Target/TargetMachine.h"
  32. #include <vector>
  33. using namespace llvm;
  34. static cl::opt<bool>
  35. DisableSharing("no-stack-slot-sharing",
  36. cl::init(false), cl::Hidden,
  37. cl::desc("Suppress slot sharing during stack coloring"));
  38. static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
  39. STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
  40. STATISTIC(NumDead, "Number of trivially dead stack accesses eliminated");
  41. namespace {
  42. class StackSlotColoring : public MachineFunctionPass {
  43. LiveStacks* LS;
  44. MachineFrameInfo *MFI;
  45. const TargetInstrInfo *TII;
  46. const MachineBlockFrequencyInfo *MBFI;
  47. // SSIntervals - Spill slot intervals.
  48. std::vector<LiveInterval*> SSIntervals;
  49. // SSRefs - Keep a list of MachineMemOperands for each spill slot.
  50. // MachineMemOperands can be shared between instructions, so we need
  51. // to be careful that renames like [FI0, FI1] -> [FI1, FI2] do not
  52. // become FI0 -> FI1 -> FI2.
  53. SmallVector<SmallVector<MachineMemOperand *, 8>, 16> SSRefs;
  54. // OrigAlignments - Alignments of stack objects before coloring.
  55. SmallVector<unsigned, 16> OrigAlignments;
  56. // OrigSizes - Sizess of stack objects before coloring.
  57. SmallVector<unsigned, 16> OrigSizes;
  58. // AllColors - If index is set, it's a spill slot, i.e. color.
  59. // FIXME: This assumes PEI locate spill slot with smaller indices
  60. // closest to stack pointer / frame pointer. Therefore, smaller
  61. // index == better color.
  62. BitVector AllColors;
  63. // NextColor - Next "color" that's not yet used.
  64. int NextColor;
  65. // UsedColors - "Colors" that have been assigned.
  66. BitVector UsedColors;
  67. // Assignments - Color to intervals mapping.
  68. SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
  69. public:
  70. static char ID; // Pass identification
  71. StackSlotColoring() :
  72. MachineFunctionPass(ID), NextColor(-1) {
  73. initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
  74. }
  75. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  76. AU.setPreservesCFG();
  77. AU.addRequired<SlotIndexes>();
  78. AU.addPreserved<SlotIndexes>();
  79. AU.addRequired<LiveStacks>();
  80. AU.addRequired<MachineBlockFrequencyInfo>();
  81. AU.addPreserved<MachineBlockFrequencyInfo>();
  82. AU.addPreservedID(MachineDominatorsID);
  83. MachineFunctionPass::getAnalysisUsage(AU);
  84. }
  85. virtual bool runOnMachineFunction(MachineFunction &MF);
  86. private:
  87. void InitializeSlots();
  88. void ScanForSpillSlotRefs(MachineFunction &MF);
  89. bool OverlapWithAssignments(LiveInterval *li, int Color) const;
  90. int ColorSlot(LiveInterval *li);
  91. bool ColorSlots(MachineFunction &MF);
  92. void RewriteInstruction(MachineInstr *MI, SmallVectorImpl<int> &SlotMapping,
  93. MachineFunction &MF);
  94. bool RemoveDeadStores(MachineBasicBlock* MBB);
  95. };
  96. } // end anonymous namespace
  97. char StackSlotColoring::ID = 0;
  98. char &llvm::StackSlotColoringID = StackSlotColoring::ID;
  99. INITIALIZE_PASS_BEGIN(StackSlotColoring, "stack-slot-coloring",
  100. "Stack Slot Coloring", false, false)
  101. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  102. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  103. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  104. INITIALIZE_PASS_END(StackSlotColoring, "stack-slot-coloring",
  105. "Stack Slot Coloring", false, false)
  106. namespace {
  107. // IntervalSorter - Comparison predicate that sort live intervals by
  108. // their weight.
  109. struct IntervalSorter {
  110. bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
  111. return LHS->weight > RHS->weight;
  112. }
  113. };
  114. }
  115. /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
  116. /// references and update spill slot weights.
  117. void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
  118. SSRefs.resize(MFI->getObjectIndexEnd());
  119. // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
  120. for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
  121. MBBI != E; ++MBBI) {
  122. MachineBasicBlock *MBB = &*MBBI;
  123. for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
  124. MII != EE; ++MII) {
  125. MachineInstr *MI = &*MII;
  126. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  127. MachineOperand &MO = MI->getOperand(i);
  128. if (!MO.isFI())
  129. continue;
  130. int FI = MO.getIndex();
  131. if (FI < 0)
  132. continue;
  133. if (!LS->hasInterval(FI))
  134. continue;
  135. LiveInterval &li = LS->getInterval(FI);
  136. if (!MI->isDebugValue())
  137. li.weight += LiveIntervals::getSpillWeight(false, true, MBFI, MI);
  138. }
  139. for (MachineInstr::mmo_iterator MMOI = MI->memoperands_begin(),
  140. EE = MI->memoperands_end(); MMOI != EE; ++MMOI) {
  141. MachineMemOperand *MMO = *MMOI;
  142. if (const Value *V = MMO->getValue()) {
  143. if (const FixedStackPseudoSourceValue *FSV =
  144. dyn_cast<FixedStackPseudoSourceValue>(V)) {
  145. int FI = FSV->getFrameIndex();
  146. if (FI >= 0)
  147. SSRefs[FI].push_back(MMO);
  148. }
  149. }
  150. }
  151. }
  152. }
  153. }
  154. /// InitializeSlots - Process all spill stack slot liveintervals and add them
  155. /// to a sorted (by weight) list.
  156. void StackSlotColoring::InitializeSlots() {
  157. int LastFI = MFI->getObjectIndexEnd();
  158. OrigAlignments.resize(LastFI);
  159. OrigSizes.resize(LastFI);
  160. AllColors.resize(LastFI);
  161. UsedColors.resize(LastFI);
  162. Assignments.resize(LastFI);
  163. // Gather all spill slots into a list.
  164. DEBUG(dbgs() << "Spill slot intervals:\n");
  165. for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
  166. LiveInterval &li = i->second;
  167. DEBUG(li.dump());
  168. int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
  169. if (MFI->isDeadObjectIndex(FI))
  170. continue;
  171. SSIntervals.push_back(&li);
  172. OrigAlignments[FI] = MFI->getObjectAlignment(FI);
  173. OrigSizes[FI] = MFI->getObjectSize(FI);
  174. AllColors.set(FI);
  175. }
  176. DEBUG(dbgs() << '\n');
  177. // Sort them by weight.
  178. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  179. // Get first "color".
  180. NextColor = AllColors.find_first();
  181. }
  182. /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
  183. /// LiveIntervals that have already been assigned to the specified color.
  184. bool
  185. StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
  186. const SmallVectorImpl<LiveInterval *> &OtherLIs = Assignments[Color];
  187. for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
  188. LiveInterval *OtherLI = OtherLIs[i];
  189. if (OtherLI->overlaps(*li))
  190. return true;
  191. }
  192. return false;
  193. }
  194. /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
  195. ///
  196. int StackSlotColoring::ColorSlot(LiveInterval *li) {
  197. int Color = -1;
  198. bool Share = false;
  199. if (!DisableSharing) {
  200. // Check if it's possible to reuse any of the used colors.
  201. Color = UsedColors.find_first();
  202. while (Color != -1) {
  203. if (!OverlapWithAssignments(li, Color)) {
  204. Share = true;
  205. ++NumEliminated;
  206. break;
  207. }
  208. Color = UsedColors.find_next(Color);
  209. }
  210. }
  211. // Assign it to the first available color (assumed to be the best) if it's
  212. // not possible to share a used color with other objects.
  213. if (!Share) {
  214. assert(NextColor != -1 && "No more spill slots?");
  215. Color = NextColor;
  216. UsedColors.set(Color);
  217. NextColor = AllColors.find_next(NextColor);
  218. }
  219. // Record the assignment.
  220. Assignments[Color].push_back(li);
  221. int FI = TargetRegisterInfo::stackSlot2Index(li->reg);
  222. DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
  223. // Change size and alignment of the allocated slot. If there are multiple
  224. // objects sharing the same slot, then make sure the size and alignment
  225. // are large enough for all.
  226. unsigned Align = OrigAlignments[FI];
  227. if (!Share || Align > MFI->getObjectAlignment(Color))
  228. MFI->setObjectAlignment(Color, Align);
  229. int64_t Size = OrigSizes[FI];
  230. if (!Share || Size > MFI->getObjectSize(Color))
  231. MFI->setObjectSize(Color, Size);
  232. return Color;
  233. }
  234. /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
  235. /// operands in the function.
  236. bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
  237. unsigned NumObjs = MFI->getObjectIndexEnd();
  238. SmallVector<int, 16> SlotMapping(NumObjs, -1);
  239. SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
  240. SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
  241. BitVector UsedColors(NumObjs);
  242. DEBUG(dbgs() << "Color spill slot intervals:\n");
  243. bool Changed = false;
  244. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  245. LiveInterval *li = SSIntervals[i];
  246. int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
  247. int NewSS = ColorSlot(li);
  248. assert(NewSS >= 0 && "Stack coloring failed?");
  249. SlotMapping[SS] = NewSS;
  250. RevMap[NewSS].push_back(SS);
  251. SlotWeights[NewSS] += li->weight;
  252. UsedColors.set(NewSS);
  253. Changed |= (SS != NewSS);
  254. }
  255. DEBUG(dbgs() << "\nSpill slots after coloring:\n");
  256. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  257. LiveInterval *li = SSIntervals[i];
  258. int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
  259. li->weight = SlotWeights[SS];
  260. }
  261. // Sort them by new weight.
  262. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  263. #ifndef NDEBUG
  264. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
  265. DEBUG(SSIntervals[i]->dump());
  266. DEBUG(dbgs() << '\n');
  267. #endif
  268. if (!Changed)
  269. return false;
  270. // Rewrite all MachineMemOperands.
  271. for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
  272. int NewFI = SlotMapping[SS];
  273. if (NewFI == -1 || (NewFI == (int)SS))
  274. continue;
  275. const Value *NewSV = PseudoSourceValue::getFixedStack(NewFI);
  276. SmallVectorImpl<MachineMemOperand *> &RefMMOs = SSRefs[SS];
  277. for (unsigned i = 0, e = RefMMOs.size(); i != e; ++i)
  278. RefMMOs[i]->setValue(NewSV);
  279. }
  280. // Rewrite all MO_FrameIndex operands. Look for dead stores.
  281. for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
  282. MBBI != E; ++MBBI) {
  283. MachineBasicBlock *MBB = &*MBBI;
  284. for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
  285. MII != EE; ++MII)
  286. RewriteInstruction(MII, SlotMapping, MF);
  287. RemoveDeadStores(MBB);
  288. }
  289. // Delete unused stack slots.
  290. while (NextColor != -1) {
  291. DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
  292. MFI->RemoveStackObject(NextColor);
  293. NextColor = AllColors.find_next(NextColor);
  294. }
  295. return true;
  296. }
  297. /// RewriteInstruction - Rewrite specified instruction by replacing references
  298. /// to old frame index with new one.
  299. void StackSlotColoring::RewriteInstruction(MachineInstr *MI,
  300. SmallVectorImpl<int> &SlotMapping,
  301. MachineFunction &MF) {
  302. // Update the operands.
  303. for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
  304. MachineOperand &MO = MI->getOperand(i);
  305. if (!MO.isFI())
  306. continue;
  307. int OldFI = MO.getIndex();
  308. if (OldFI < 0)
  309. continue;
  310. int NewFI = SlotMapping[OldFI];
  311. if (NewFI == -1 || NewFI == OldFI)
  312. continue;
  313. MO.setIndex(NewFI);
  314. }
  315. // The MachineMemOperands have already been updated.
  316. }
  317. /// RemoveDeadStores - Scan through a basic block and look for loads followed
  318. /// by stores. If they're both using the same stack slot, then the store is
  319. /// definitely dead. This could obviously be much more aggressive (consider
  320. /// pairs with instructions between them), but such extensions might have a
  321. /// considerable compile time impact.
  322. bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
  323. // FIXME: This could be much more aggressive, but we need to investigate
  324. // the compile time impact of doing so.
  325. bool changed = false;
  326. SmallVector<MachineInstr*, 4> toErase;
  327. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  328. I != E; ++I) {
  329. if (DCELimit != -1 && (int)NumDead >= DCELimit)
  330. break;
  331. int FirstSS, SecondSS;
  332. if (TII->isStackSlotCopy(I, FirstSS, SecondSS) &&
  333. FirstSS == SecondSS &&
  334. FirstSS != -1) {
  335. ++NumDead;
  336. changed = true;
  337. toErase.push_back(I);
  338. continue;
  339. }
  340. MachineBasicBlock::iterator NextMI = std::next(I);
  341. if (NextMI == MBB->end()) continue;
  342. unsigned LoadReg = 0;
  343. unsigned StoreReg = 0;
  344. if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
  345. if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
  346. if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
  347. ++NumDead;
  348. changed = true;
  349. if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
  350. ++NumDead;
  351. toErase.push_back(I);
  352. }
  353. toErase.push_back(NextMI);
  354. ++I;
  355. }
  356. for (SmallVectorImpl<MachineInstr *>::iterator I = toErase.begin(),
  357. E = toErase.end(); I != E; ++I)
  358. (*I)->eraseFromParent();
  359. return changed;
  360. }
  361. bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
  362. DEBUG({
  363. dbgs() << "********** Stack Slot Coloring **********\n"
  364. << "********** Function: " << MF.getName() << '\n';
  365. });
  366. MFI = MF.getFrameInfo();
  367. TII = MF.getTarget().getInstrInfo();
  368. LS = &getAnalysis<LiveStacks>();
  369. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  370. bool Changed = false;
  371. unsigned NumSlots = LS->getNumIntervals();
  372. if (NumSlots == 0)
  373. // Nothing to do!
  374. return false;
  375. // If there are calls to setjmp or sigsetjmp, don't perform stack slot
  376. // coloring. The stack could be modified before the longjmp is executed,
  377. // resulting in the wrong value being used afterwards. (See
  378. // <rdar://problem/8007500>.)
  379. if (MF.exposesReturnsTwice())
  380. return false;
  381. // Gather spill slot references
  382. ScanForSpillSlotRefs(MF);
  383. InitializeSlots();
  384. Changed = ColorSlots(MF);
  385. NextColor = -1;
  386. SSIntervals.clear();
  387. for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
  388. SSRefs[i].clear();
  389. SSRefs.clear();
  390. OrigAlignments.clear();
  391. OrigSizes.clear();
  392. AllColors.clear();
  393. UsedColors.clear();
  394. for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
  395. Assignments[i].clear();
  396. Assignments.clear();
  397. return Changed;
  398. }