2
0

StackSlotColoring.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. #include "llvm/CodeGen/Passes.h"
  14. #include "llvm/ADT/BitVector.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/CodeGen/LiveIntervalAnalysis.h"
  18. #include "llvm/CodeGen/LiveStackAnalysis.h"
  19. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  20. #include "llvm/CodeGen/MachineFrameInfo.h"
  21. #include "llvm/CodeGen/MachineInstrBuilder.h"
  22. #include "llvm/CodeGen/MachineMemOperand.h"
  23. #include "llvm/CodeGen/MachineRegisterInfo.h"
  24. #include "llvm/CodeGen/PseudoSourceValue.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Target/TargetInstrInfo.h"
  30. #include "llvm/Target/TargetSubtargetInfo.h"
  31. #include <vector>
  32. using namespace llvm;
  33. #define DEBUG_TYPE "stackslotcoloring"
  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. void getAnalysisUsage(AnalysisUsage &AU) const override {
  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. bool runOnMachineFunction(MachineFunction &MF) override;
  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 FixedStackPseudoSourceValue *FSV =
  143. dyn_cast_or_null<FixedStackPseudoSourceValue>(
  144. MMO->getPseudoValue())) {
  145. int FI = FSV->getFrameIndex();
  146. if (FI >= 0)
  147. SSRefs[FI].push_back(MMO);
  148. }
  149. }
  150. }
  151. }
  152. }
  153. /// InitializeSlots - Process all spill stack slot liveintervals and add them
  154. /// to a sorted (by weight) list.
  155. void StackSlotColoring::InitializeSlots() {
  156. int LastFI = MFI->getObjectIndexEnd();
  157. OrigAlignments.resize(LastFI);
  158. OrigSizes.resize(LastFI);
  159. AllColors.resize(LastFI);
  160. UsedColors.resize(LastFI);
  161. Assignments.resize(LastFI);
  162. typedef std::iterator_traits<LiveStacks::iterator>::value_type Pair;
  163. SmallVector<Pair *, 16> Intervals;
  164. Intervals.reserve(LS->getNumIntervals());
  165. for (auto &I : *LS)
  166. Intervals.push_back(&I);
  167. std::sort(Intervals.begin(), Intervals.end(),
  168. [](Pair *LHS, Pair *RHS) { return LHS->first < RHS->first; });
  169. // Gather all spill slots into a list.
  170. DEBUG(dbgs() << "Spill slot intervals:\n");
  171. for (auto *I : Intervals) {
  172. LiveInterval &li = I->second;
  173. DEBUG(li.dump());
  174. int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
  175. if (MFI->isDeadObjectIndex(FI))
  176. continue;
  177. SSIntervals.push_back(&li);
  178. OrigAlignments[FI] = MFI->getObjectAlignment(FI);
  179. OrigSizes[FI] = MFI->getObjectSize(FI);
  180. AllColors.set(FI);
  181. }
  182. DEBUG(dbgs() << '\n');
  183. // Sort them by weight.
  184. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  185. // Get first "color".
  186. NextColor = AllColors.find_first();
  187. }
  188. /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
  189. /// LiveIntervals that have already been assigned to the specified color.
  190. bool
  191. StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
  192. const SmallVectorImpl<LiveInterval *> &OtherLIs = Assignments[Color];
  193. for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
  194. LiveInterval *OtherLI = OtherLIs[i];
  195. if (OtherLI->overlaps(*li))
  196. return true;
  197. }
  198. return false;
  199. }
  200. /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
  201. ///
  202. int StackSlotColoring::ColorSlot(LiveInterval *li) {
  203. int Color = -1;
  204. bool Share = false;
  205. if (!DisableSharing) {
  206. // Check if it's possible to reuse any of the used colors.
  207. Color = UsedColors.find_first();
  208. while (Color != -1) {
  209. if (!OverlapWithAssignments(li, Color)) {
  210. Share = true;
  211. ++NumEliminated;
  212. break;
  213. }
  214. Color = UsedColors.find_next(Color);
  215. }
  216. }
  217. // Assign it to the first available color (assumed to be the best) if it's
  218. // not possible to share a used color with other objects.
  219. if (!Share) {
  220. assert(NextColor != -1 && "No more spill slots?");
  221. Color = NextColor;
  222. UsedColors.set(Color);
  223. NextColor = AllColors.find_next(NextColor);
  224. }
  225. // Record the assignment.
  226. Assignments[Color].push_back(li);
  227. int FI = TargetRegisterInfo::stackSlot2Index(li->reg);
  228. DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
  229. // Change size and alignment of the allocated slot. If there are multiple
  230. // objects sharing the same slot, then make sure the size and alignment
  231. // are large enough for all.
  232. unsigned Align = OrigAlignments[FI];
  233. if (!Share || Align > MFI->getObjectAlignment(Color))
  234. MFI->setObjectAlignment(Color, Align);
  235. int64_t Size = OrigSizes[FI];
  236. if (!Share || Size > MFI->getObjectSize(Color))
  237. MFI->setObjectSize(Color, Size);
  238. return Color;
  239. }
  240. /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
  241. /// operands in the function.
  242. bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
  243. unsigned NumObjs = MFI->getObjectIndexEnd();
  244. SmallVector<int, 16> SlotMapping(NumObjs, -1);
  245. SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
  246. SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
  247. BitVector UsedColors(NumObjs);
  248. DEBUG(dbgs() << "Color spill slot intervals:\n");
  249. bool Changed = false;
  250. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  251. LiveInterval *li = SSIntervals[i];
  252. int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
  253. int NewSS = ColorSlot(li);
  254. assert(NewSS >= 0 && "Stack coloring failed?");
  255. SlotMapping[SS] = NewSS;
  256. RevMap[NewSS].push_back(SS);
  257. SlotWeights[NewSS] += li->weight;
  258. UsedColors.set(NewSS);
  259. Changed |= (SS != NewSS);
  260. }
  261. DEBUG(dbgs() << "\nSpill slots after coloring:\n");
  262. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  263. LiveInterval *li = SSIntervals[i];
  264. int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
  265. li->weight = SlotWeights[SS];
  266. }
  267. // Sort them by new weight.
  268. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  269. #ifndef NDEBUG
  270. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
  271. DEBUG(SSIntervals[i]->dump());
  272. DEBUG(dbgs() << '\n');
  273. #endif
  274. if (!Changed)
  275. return false;
  276. // Rewrite all MachineMemOperands.
  277. for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
  278. int NewFI = SlotMapping[SS];
  279. if (NewFI == -1 || (NewFI == (int)SS))
  280. continue;
  281. const PseudoSourceValue *NewSV = PseudoSourceValue::getFixedStack(NewFI);
  282. SmallVectorImpl<MachineMemOperand *> &RefMMOs = SSRefs[SS];
  283. for (unsigned i = 0, e = RefMMOs.size(); i != e; ++i)
  284. RefMMOs[i]->setValue(NewSV);
  285. }
  286. // Rewrite all MO_FrameIndex operands. Look for dead stores.
  287. for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
  288. MBBI != E; ++MBBI) {
  289. MachineBasicBlock *MBB = &*MBBI;
  290. for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
  291. MII != EE; ++MII)
  292. RewriteInstruction(MII, SlotMapping, MF);
  293. RemoveDeadStores(MBB);
  294. }
  295. // Delete unused stack slots.
  296. while (NextColor != -1) {
  297. DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
  298. MFI->RemoveStackObject(NextColor);
  299. NextColor = AllColors.find_next(NextColor);
  300. }
  301. return true;
  302. }
  303. /// RewriteInstruction - Rewrite specified instruction by replacing references
  304. /// to old frame index with new one.
  305. void StackSlotColoring::RewriteInstruction(MachineInstr *MI,
  306. SmallVectorImpl<int> &SlotMapping,
  307. MachineFunction &MF) {
  308. // Update the operands.
  309. for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
  310. MachineOperand &MO = MI->getOperand(i);
  311. if (!MO.isFI())
  312. continue;
  313. int OldFI = MO.getIndex();
  314. if (OldFI < 0)
  315. continue;
  316. int NewFI = SlotMapping[OldFI];
  317. if (NewFI == -1 || NewFI == OldFI)
  318. continue;
  319. MO.setIndex(NewFI);
  320. }
  321. // The MachineMemOperands have already been updated.
  322. }
  323. /// RemoveDeadStores - Scan through a basic block and look for loads followed
  324. /// by stores. If they're both using the same stack slot, then the store is
  325. /// definitely dead. This could obviously be much more aggressive (consider
  326. /// pairs with instructions between them), but such extensions might have a
  327. /// considerable compile time impact.
  328. bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
  329. // FIXME: This could be much more aggressive, but we need to investigate
  330. // the compile time impact of doing so.
  331. bool changed = false;
  332. SmallVector<MachineInstr*, 4> toErase;
  333. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  334. I != E; ++I) {
  335. if (DCELimit != -1 && (int)NumDead >= DCELimit)
  336. break;
  337. int FirstSS, SecondSS;
  338. if (TII->isStackSlotCopy(I, FirstSS, SecondSS) &&
  339. FirstSS == SecondSS &&
  340. FirstSS != -1) {
  341. ++NumDead;
  342. changed = true;
  343. toErase.push_back(I);
  344. continue;
  345. }
  346. MachineBasicBlock::iterator NextMI = std::next(I);
  347. if (NextMI == MBB->end()) continue;
  348. unsigned LoadReg = 0;
  349. unsigned StoreReg = 0;
  350. if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
  351. if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
  352. if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
  353. ++NumDead;
  354. changed = true;
  355. if (NextMI->findRegisterUseOperandIdx(LoadReg, true, nullptr) != -1) {
  356. ++NumDead;
  357. toErase.push_back(I);
  358. }
  359. toErase.push_back(NextMI);
  360. ++I;
  361. }
  362. for (SmallVectorImpl<MachineInstr *>::iterator I = toErase.begin(),
  363. E = toErase.end(); I != E; ++I)
  364. (*I)->eraseFromParent();
  365. return changed;
  366. }
  367. bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
  368. DEBUG({
  369. dbgs() << "********** Stack Slot Coloring **********\n"
  370. << "********** Function: " << MF.getName() << '\n';
  371. });
  372. MFI = MF.getFrameInfo();
  373. TII = MF.getSubtarget().getInstrInfo();
  374. LS = &getAnalysis<LiveStacks>();
  375. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  376. bool Changed = false;
  377. unsigned NumSlots = LS->getNumIntervals();
  378. if (NumSlots == 0)
  379. // Nothing to do!
  380. return false;
  381. // If there are calls to setjmp or sigsetjmp, don't perform stack slot
  382. // coloring. The stack could be modified before the longjmp is executed,
  383. // resulting in the wrong value being used afterwards. (See
  384. // <rdar://problem/8007500>.)
  385. if (MF.exposesReturnsTwice())
  386. return false;
  387. // Gather spill slot references
  388. ScanForSpillSlotRefs(MF);
  389. InitializeSlots();
  390. Changed = ColorSlots(MF);
  391. NextColor = -1;
  392. SSIntervals.clear();
  393. for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
  394. SSRefs[i].clear();
  395. SSRefs.clear();
  396. OrigAlignments.clear();
  397. OrigSizes.clear();
  398. AllColors.clear();
  399. UsedColors.clear();
  400. for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
  401. Assignments[i].clear();
  402. Assignments.clear();
  403. return Changed;
  404. }