StackSlotColoring.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. This is per stack ID.
  73. SmallVector<BitVector, 2> AllColors;
  74. // NextColor - Next "color" that's not yet used. This is per stack ID.
  75. SmallVector<int, 2> NextColors = { -1 };
  76. // UsedColors - "Colors" that have been assigned. This is per stack ID
  77. SmallVector<BitVector, 2> 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. // There is always at least one stack ID.
  169. AllColors.resize(1);
  170. UsedColors.resize(1);
  171. OrigAlignments.resize(LastFI);
  172. OrigSizes.resize(LastFI);
  173. AllColors[0].resize(LastFI);
  174. UsedColors[0].resize(LastFI);
  175. Assignments.resize(LastFI);
  176. using Pair = std::iterator_traits<LiveStacks::iterator>::value_type;
  177. SmallVector<Pair *, 16> Intervals;
  178. Intervals.reserve(LS->getNumIntervals());
  179. for (auto &I : *LS)
  180. Intervals.push_back(&I);
  181. llvm::sort(Intervals.begin(), Intervals.end(),
  182. [](Pair *LHS, Pair *RHS) { return LHS->first < RHS->first; });
  183. // Gather all spill slots into a list.
  184. LLVM_DEBUG(dbgs() << "Spill slot intervals:\n");
  185. for (auto *I : Intervals) {
  186. LiveInterval &li = I->second;
  187. LLVM_DEBUG(li.dump());
  188. int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
  189. if (MFI->isDeadObjectIndex(FI))
  190. continue;
  191. SSIntervals.push_back(&li);
  192. OrigAlignments[FI] = MFI->getObjectAlignment(FI);
  193. OrigSizes[FI] = MFI->getObjectSize(FI);
  194. auto StackID = MFI->getStackID(FI);
  195. if (StackID != 0) {
  196. AllColors.resize(StackID + 1);
  197. UsedColors.resize(StackID + 1);
  198. AllColors[StackID].resize(LastFI);
  199. UsedColors[StackID].resize(LastFI);
  200. }
  201. AllColors[StackID].set(FI);
  202. }
  203. LLVM_DEBUG(dbgs() << '\n');
  204. // Sort them by weight.
  205. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  206. NextColors.resize(AllColors.size());
  207. // Get first "color".
  208. for (unsigned I = 0, E = AllColors.size(); I != E; ++I)
  209. NextColors[I] = AllColors[I].find_first();
  210. }
  211. /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
  212. /// LiveIntervals that have already been assigned to the specified color.
  213. bool
  214. StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
  215. const SmallVectorImpl<LiveInterval *> &OtherLIs = Assignments[Color];
  216. for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
  217. LiveInterval *OtherLI = OtherLIs[i];
  218. if (OtherLI->overlaps(*li))
  219. return true;
  220. }
  221. return false;
  222. }
  223. /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
  224. int StackSlotColoring::ColorSlot(LiveInterval *li) {
  225. int Color = -1;
  226. bool Share = false;
  227. int FI = TargetRegisterInfo::stackSlot2Index(li->reg);
  228. uint8_t StackID = MFI->getStackID(FI);
  229. if (!DisableSharing) {
  230. // Check if it's possible to reuse any of the used colors.
  231. Color = UsedColors[StackID].find_first();
  232. while (Color != -1) {
  233. if (!OverlapWithAssignments(li, Color)) {
  234. Share = true;
  235. ++NumEliminated;
  236. break;
  237. }
  238. Color = UsedColors[StackID].find_next(Color);
  239. }
  240. }
  241. if (Color != -1 && MFI->getStackID(Color) != MFI->getStackID(FI)) {
  242. LLVM_DEBUG(dbgs() << "cannot share FIs with different stack IDs\n");
  243. Share = false;
  244. }
  245. // Assign it to the first available color (assumed to be the best) if it's
  246. // not possible to share a used color with other objects.
  247. if (!Share) {
  248. assert(NextColors[StackID] != -1 && "No more spill slots?");
  249. Color = NextColors[StackID];
  250. UsedColors[StackID].set(Color);
  251. NextColors[StackID] = AllColors[StackID].find_next(NextColors[StackID]);
  252. }
  253. assert(MFI->getStackID(Color) == MFI->getStackID(FI));
  254. // Record the assignment.
  255. Assignments[Color].push_back(li);
  256. LLVM_DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
  257. // Change size and alignment of the allocated slot. If there are multiple
  258. // objects sharing the same slot, then make sure the size and alignment
  259. // are large enough for all.
  260. unsigned Align = OrigAlignments[FI];
  261. if (!Share || Align > MFI->getObjectAlignment(Color))
  262. MFI->setObjectAlignment(Color, Align);
  263. int64_t Size = OrigSizes[FI];
  264. if (!Share || Size > MFI->getObjectSize(Color))
  265. MFI->setObjectSize(Color, Size);
  266. return Color;
  267. }
  268. /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
  269. /// operands in the function.
  270. bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
  271. unsigned NumObjs = MFI->getObjectIndexEnd();
  272. SmallVector<int, 16> SlotMapping(NumObjs, -1);
  273. SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
  274. SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
  275. BitVector UsedColors(NumObjs);
  276. LLVM_DEBUG(dbgs() << "Color spill slot intervals:\n");
  277. bool Changed = false;
  278. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  279. LiveInterval *li = SSIntervals[i];
  280. int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
  281. int NewSS = ColorSlot(li);
  282. assert(NewSS >= 0 && "Stack coloring failed?");
  283. SlotMapping[SS] = NewSS;
  284. RevMap[NewSS].push_back(SS);
  285. SlotWeights[NewSS] += li->weight;
  286. UsedColors.set(NewSS);
  287. Changed |= (SS != NewSS);
  288. }
  289. LLVM_DEBUG(dbgs() << "\nSpill slots after coloring:\n");
  290. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
  291. LiveInterval *li = SSIntervals[i];
  292. int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
  293. li->weight = SlotWeights[SS];
  294. }
  295. // Sort them by new weight.
  296. std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
  297. #ifndef NDEBUG
  298. for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
  299. LLVM_DEBUG(SSIntervals[i]->dump());
  300. LLVM_DEBUG(dbgs() << '\n');
  301. #endif
  302. if (!Changed)
  303. return false;
  304. // Rewrite all MachineMemOperands.
  305. for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
  306. int NewFI = SlotMapping[SS];
  307. if (NewFI == -1 || (NewFI == (int)SS))
  308. continue;
  309. const PseudoSourceValue *NewSV = MF.getPSVManager().getFixedStack(NewFI);
  310. SmallVectorImpl<MachineMemOperand *> &RefMMOs = SSRefs[SS];
  311. for (unsigned i = 0, e = RefMMOs.size(); i != e; ++i)
  312. RefMMOs[i]->setValue(NewSV);
  313. }
  314. // Rewrite all MO_FrameIndex operands. Look for dead stores.
  315. for (MachineBasicBlock &MBB : MF) {
  316. for (MachineInstr &MI : MBB)
  317. RewriteInstruction(MI, SlotMapping, MF);
  318. RemoveDeadStores(&MBB);
  319. }
  320. // Delete unused stack slots.
  321. for (int StackID = 0, E = AllColors.size(); StackID != E; ++StackID) {
  322. int NextColor = NextColors[StackID];
  323. while (NextColor != -1) {
  324. LLVM_DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
  325. MFI->RemoveStackObject(NextColor);
  326. NextColor = AllColors[StackID].find_next(NextColor);
  327. }
  328. }
  329. return true;
  330. }
  331. /// RewriteInstruction - Rewrite specified instruction by replacing references
  332. /// to old frame index with new one.
  333. void StackSlotColoring::RewriteInstruction(MachineInstr &MI,
  334. SmallVectorImpl<int> &SlotMapping,
  335. MachineFunction &MF) {
  336. // Update the operands.
  337. for (unsigned i = 0, ee = MI.getNumOperands(); i != ee; ++i) {
  338. MachineOperand &MO = MI.getOperand(i);
  339. if (!MO.isFI())
  340. continue;
  341. int OldFI = MO.getIndex();
  342. if (OldFI < 0)
  343. continue;
  344. int NewFI = SlotMapping[OldFI];
  345. if (NewFI == -1 || NewFI == OldFI)
  346. continue;
  347. assert(MFI->getStackID(OldFI) == MFI->getStackID(NewFI));
  348. MO.setIndex(NewFI);
  349. }
  350. // The MachineMemOperands have already been updated.
  351. }
  352. /// RemoveDeadStores - Scan through a basic block and look for loads followed
  353. /// by stores. If they're both using the same stack slot, then the store is
  354. /// definitely dead. This could obviously be much more aggressive (consider
  355. /// pairs with instructions between them), but such extensions might have a
  356. /// considerable compile time impact.
  357. bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
  358. // FIXME: This could be much more aggressive, but we need to investigate
  359. // the compile time impact of doing so.
  360. bool changed = false;
  361. SmallVector<MachineInstr*, 4> toErase;
  362. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
  363. I != E; ++I) {
  364. if (DCELimit != -1 && (int)NumDead >= DCELimit)
  365. break;
  366. int FirstSS, SecondSS;
  367. if (TII->isStackSlotCopy(*I, FirstSS, SecondSS) && FirstSS == SecondSS &&
  368. FirstSS != -1) {
  369. ++NumDead;
  370. changed = true;
  371. toErase.push_back(&*I);
  372. continue;
  373. }
  374. MachineBasicBlock::iterator NextMI = std::next(I);
  375. MachineBasicBlock::iterator ProbableLoadMI = I;
  376. unsigned LoadReg = 0;
  377. unsigned StoreReg = 0;
  378. unsigned LoadSize = 0;
  379. unsigned StoreSize = 0;
  380. if (!(LoadReg = TII->isLoadFromStackSlot(*I, FirstSS, LoadSize)))
  381. continue;
  382. // Skip the ...pseudo debugging... instructions between a load and store.
  383. while ((NextMI != E) && NextMI->isDebugInstr()) {
  384. ++NextMI;
  385. ++I;
  386. }
  387. if (NextMI == E) continue;
  388. if (!(StoreReg = TII->isStoreToStackSlot(*NextMI, SecondSS, StoreSize)))
  389. continue;
  390. if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1 ||
  391. LoadSize != StoreSize)
  392. continue;
  393. ++NumDead;
  394. changed = true;
  395. if (NextMI->findRegisterUseOperandIdx(LoadReg, true, nullptr) != -1) {
  396. ++NumDead;
  397. toErase.push_back(&*ProbableLoadMI);
  398. }
  399. toErase.push_back(&*NextMI);
  400. ++I;
  401. }
  402. for (SmallVectorImpl<MachineInstr *>::iterator I = toErase.begin(),
  403. E = toErase.end(); I != E; ++I)
  404. (*I)->eraseFromParent();
  405. return changed;
  406. }
  407. bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
  408. LLVM_DEBUG({
  409. dbgs() << "********** Stack Slot Coloring **********\n"
  410. << "********** Function: " << MF.getName() << '\n';
  411. });
  412. if (skipFunction(MF.getFunction()))
  413. return false;
  414. MFI = &MF.getFrameInfo();
  415. TII = MF.getSubtarget().getInstrInfo();
  416. LS = &getAnalysis<LiveStacks>();
  417. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  418. bool Changed = false;
  419. unsigned NumSlots = LS->getNumIntervals();
  420. if (NumSlots == 0)
  421. // Nothing to do!
  422. return false;
  423. // If there are calls to setjmp or sigsetjmp, don't perform stack slot
  424. // coloring. The stack could be modified before the longjmp is executed,
  425. // resulting in the wrong value being used afterwards. (See
  426. // <rdar://problem/8007500>.)
  427. if (MF.exposesReturnsTwice())
  428. return false;
  429. // Gather spill slot references
  430. ScanForSpillSlotRefs(MF);
  431. InitializeSlots();
  432. Changed = ColorSlots(MF);
  433. for (int &Next : NextColors)
  434. Next = -1;
  435. SSIntervals.clear();
  436. for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
  437. SSRefs[i].clear();
  438. SSRefs.clear();
  439. OrigAlignments.clear();
  440. OrigSizes.clear();
  441. AllColors.clear();
  442. UsedColors.clear();
  443. for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
  444. Assignments[i].clear();
  445. Assignments.clear();
  446. return Changed;
  447. }