StackSlotColoring.cpp 16 KB

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