StackColoring.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. //===-- StackColoring.cpp -------------------------------------------------===//
  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 pass implements the stack-coloring optimization that looks for
  11. // lifetime markers machine instructions (LIFESTART_BEGIN and LIFESTART_END),
  12. // which represent the possible lifetime of stack slots. It attempts to
  13. // merge disjoint stack slots and reduce the used stack space.
  14. // NOTE: This pass is not StackSlotColoring, which optimizes spill slots.
  15. //
  16. // TODO: In the future we plan to improve stack coloring in the following ways:
  17. // 1. Allow merging multiple small slots into a single larger slot at different
  18. // offsets.
  19. // 2. Merge this pass with StackSlotColoring and allow merging of allocas with
  20. // spill slots.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/CodeGen/Passes.h"
  24. #include "llvm/ADT/BitVector.h"
  25. #include "llvm/ADT/DepthFirstIterator.h"
  26. #include "llvm/ADT/PostOrderIterator.h"
  27. #include "llvm/ADT/SetVector.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/ADT/SparseSet.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include "llvm/Analysis/ValueTracking.h"
  32. #include "llvm/CodeGen/LiveInterval.h"
  33. #include "llvm/CodeGen/MachineBasicBlock.h"
  34. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  35. #include "llvm/CodeGen/MachineDominators.h"
  36. #include "llvm/CodeGen/MachineFrameInfo.h"
  37. #include "llvm/CodeGen/MachineFunctionPass.h"
  38. #include "llvm/CodeGen/MachineLoopInfo.h"
  39. #include "llvm/CodeGen/MachineMemOperand.h"
  40. #include "llvm/CodeGen/MachineModuleInfo.h"
  41. #include "llvm/CodeGen/MachineRegisterInfo.h"
  42. #include "llvm/CodeGen/PseudoSourceValue.h"
  43. #include "llvm/CodeGen/SlotIndexes.h"
  44. #include "llvm/CodeGen/StackProtector.h"
  45. #include "llvm/IR/DebugInfo.h"
  46. #include "llvm/IR/Dominators.h"
  47. #include "llvm/IR/Function.h"
  48. #include "llvm/IR/Instructions.h"
  49. #include "llvm/IR/Module.h"
  50. #include "llvm/Support/CommandLine.h"
  51. #include "llvm/Support/Debug.h"
  52. #include "llvm/Support/raw_ostream.h"
  53. #include "llvm/Target/TargetInstrInfo.h"
  54. #include "llvm/Target/TargetRegisterInfo.h"
  55. using namespace llvm;
  56. #define DEBUG_TYPE "stackcoloring"
  57. static cl::opt<bool>
  58. DisableColoring("no-stack-coloring",
  59. cl::init(false), cl::Hidden,
  60. cl::desc("Disable stack coloring"));
  61. /// The user may write code that uses allocas outside of the declared lifetime
  62. /// zone. This can happen when the user returns a reference to a local
  63. /// data-structure. We can detect these cases and decide not to optimize the
  64. /// code. If this flag is enabled, we try to save the user.
  65. static cl::opt<bool>
  66. ProtectFromEscapedAllocas("protect-from-escaped-allocas",
  67. cl::init(false), cl::Hidden,
  68. cl::desc("Do not optimize lifetime zones that "
  69. "are broken"));
  70. STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
  71. STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
  72. STATISTIC(StackSlotMerged, "Number of stack slot merged.");
  73. STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region");
  74. //===----------------------------------------------------------------------===//
  75. // StackColoring Pass
  76. //===----------------------------------------------------------------------===//
  77. namespace {
  78. /// StackColoring - A machine pass for merging disjoint stack allocations,
  79. /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
  80. class StackColoring : public MachineFunctionPass {
  81. MachineFrameInfo *MFI;
  82. MachineFunction *MF;
  83. /// A class representing liveness information for a single basic block.
  84. /// Each bit in the BitVector represents the liveness property
  85. /// for a different stack slot.
  86. struct BlockLifetimeInfo {
  87. /// Which slots BEGINs in each basic block.
  88. BitVector Begin;
  89. /// Which slots ENDs in each basic block.
  90. BitVector End;
  91. /// Which slots are marked as LIVE_IN, coming into each basic block.
  92. BitVector LiveIn;
  93. /// Which slots are marked as LIVE_OUT, coming out of each basic block.
  94. BitVector LiveOut;
  95. };
  96. /// Maps active slots (per bit) for each basic block.
  97. typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap;
  98. LivenessMap BlockLiveness;
  99. /// Maps serial numbers to basic blocks.
  100. DenseMap<const MachineBasicBlock*, int> BasicBlocks;
  101. /// Maps basic blocks to a serial number.
  102. SmallVector<const MachineBasicBlock*, 8> BasicBlockNumbering;
  103. /// Maps liveness intervals for each slot.
  104. SmallVector<std::unique_ptr<LiveInterval>, 16> Intervals;
  105. /// VNInfo is used for the construction of LiveIntervals.
  106. VNInfo::Allocator VNInfoAllocator;
  107. /// SlotIndex analysis object.
  108. SlotIndexes *Indexes;
  109. /// The stack protector object.
  110. StackProtector *SP;
  111. /// The list of lifetime markers found. These markers are to be removed
  112. /// once the coloring is done.
  113. SmallVector<MachineInstr*, 8> Markers;
  114. public:
  115. static char ID;
  116. StackColoring() : MachineFunctionPass(ID) {
  117. initializeStackColoringPass(*PassRegistry::getPassRegistry());
  118. }
  119. void getAnalysisUsage(AnalysisUsage &AU) const override;
  120. bool runOnMachineFunction(MachineFunction &MF) override;
  121. private:
  122. /// Debug.
  123. void dump() const;
  124. /// Removes all of the lifetime marker instructions from the function.
  125. /// \returns true if any markers were removed.
  126. bool removeAllMarkers();
  127. /// Scan the machine function and find all of the lifetime markers.
  128. /// Record the findings in the BEGIN and END vectors.
  129. /// \returns the number of markers found.
  130. unsigned collectMarkers(unsigned NumSlot);
  131. /// Perform the dataflow calculation and calculate the lifetime for each of
  132. /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
  133. /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
  134. /// in and out blocks.
  135. void calculateLocalLiveness();
  136. /// Construct the LiveIntervals for the slots.
  137. void calculateLiveIntervals(unsigned NumSlots);
  138. /// Go over the machine function and change instructions which use stack
  139. /// slots to use the joint slots.
  140. void remapInstructions(DenseMap<int, int> &SlotRemap);
  141. /// The input program may contain instructions which are not inside lifetime
  142. /// markers. This can happen due to a bug in the compiler or due to a bug in
  143. /// user code (for example, returning a reference to a local variable).
  144. /// This procedure checks all of the instructions in the function and
  145. /// invalidates lifetime ranges which do not contain all of the instructions
  146. /// which access that frame slot.
  147. void removeInvalidSlotRanges();
  148. /// Map entries which point to other entries to their destination.
  149. /// A->B->C becomes A->C.
  150. void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
  151. };
  152. } // end anonymous namespace
  153. char StackColoring::ID = 0;
  154. char &llvm::StackColoringID = StackColoring::ID;
  155. INITIALIZE_PASS_BEGIN(StackColoring,
  156. "stack-coloring", "Merge disjoint stack slots", false, false)
  157. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  158. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  159. INITIALIZE_PASS_DEPENDENCY(StackProtector)
  160. INITIALIZE_PASS_END(StackColoring,
  161. "stack-coloring", "Merge disjoint stack slots", false, false)
  162. void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
  163. AU.addRequired<MachineDominatorTree>();
  164. AU.addPreserved<MachineDominatorTree>();
  165. AU.addRequired<SlotIndexes>();
  166. AU.addRequired<StackProtector>();
  167. MachineFunctionPass::getAnalysisUsage(AU);
  168. }
  169. void StackColoring::dump() const {
  170. for (MachineBasicBlock *MBB : depth_first(MF)) {
  171. DEBUG(dbgs() << "Inspecting block #" << BasicBlocks.lookup(MBB) << " ["
  172. << MBB->getName() << "]\n");
  173. LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
  174. assert(BI != BlockLiveness.end() && "Block not found");
  175. const BlockLifetimeInfo &BlockInfo = BI->second;
  176. DEBUG(dbgs()<<"BEGIN : {");
  177. for (unsigned i=0; i < BlockInfo.Begin.size(); ++i)
  178. DEBUG(dbgs()<<BlockInfo.Begin.test(i)<<" ");
  179. DEBUG(dbgs()<<"}\n");
  180. DEBUG(dbgs()<<"END : {");
  181. for (unsigned i=0; i < BlockInfo.End.size(); ++i)
  182. DEBUG(dbgs()<<BlockInfo.End.test(i)<<" ");
  183. DEBUG(dbgs()<<"}\n");
  184. DEBUG(dbgs()<<"LIVE_IN: {");
  185. for (unsigned i=0; i < BlockInfo.LiveIn.size(); ++i)
  186. DEBUG(dbgs()<<BlockInfo.LiveIn.test(i)<<" ");
  187. DEBUG(dbgs()<<"}\n");
  188. DEBUG(dbgs()<<"LIVEOUT: {");
  189. for (unsigned i=0; i < BlockInfo.LiveOut.size(); ++i)
  190. DEBUG(dbgs()<<BlockInfo.LiveOut.test(i)<<" ");
  191. DEBUG(dbgs()<<"}\n");
  192. }
  193. }
  194. unsigned StackColoring::collectMarkers(unsigned NumSlot) {
  195. unsigned MarkersFound = 0;
  196. // Scan the function to find all lifetime markers.
  197. // NOTE: We use a reverse-post-order iteration to ensure that we obtain a
  198. // deterministic numbering, and because we'll need a post-order iteration
  199. // later for solving the liveness dataflow problem.
  200. for (MachineBasicBlock *MBB : depth_first(MF)) {
  201. // Assign a serial number to this basic block.
  202. BasicBlocks[MBB] = BasicBlockNumbering.size();
  203. BasicBlockNumbering.push_back(MBB);
  204. // Keep a reference to avoid repeated lookups.
  205. BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
  206. BlockInfo.Begin.resize(NumSlot);
  207. BlockInfo.End.resize(NumSlot);
  208. for (MachineInstr &MI : *MBB) {
  209. if (MI.getOpcode() != TargetOpcode::LIFETIME_START &&
  210. MI.getOpcode() != TargetOpcode::LIFETIME_END)
  211. continue;
  212. Markers.push_back(&MI);
  213. bool IsStart = MI.getOpcode() == TargetOpcode::LIFETIME_START;
  214. const MachineOperand &MO = MI.getOperand(0);
  215. unsigned Slot = MO.getIndex();
  216. MarkersFound++;
  217. const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
  218. if (Allocation) {
  219. DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
  220. " with allocation: "<< Allocation->getName()<<"\n");
  221. }
  222. if (IsStart) {
  223. BlockInfo.Begin.set(Slot);
  224. } else {
  225. if (BlockInfo.Begin.test(Slot)) {
  226. // Allocas that start and end within a single block are handled
  227. // specially when computing the LiveIntervals to avoid pessimizing
  228. // the liveness propagation.
  229. BlockInfo.Begin.reset(Slot);
  230. } else {
  231. BlockInfo.End.set(Slot);
  232. }
  233. }
  234. }
  235. }
  236. // Update statistics.
  237. NumMarkerSeen += MarkersFound;
  238. return MarkersFound;
  239. }
  240. void StackColoring::calculateLocalLiveness() {
  241. // Perform a standard reverse dataflow computation to solve for
  242. // global liveness. The BEGIN set here is equivalent to KILL in the standard
  243. // formulation, and END is equivalent to GEN. The result of this computation
  244. // is a map from blocks to bitvectors where the bitvectors represent which
  245. // allocas are live in/out of that block.
  246. SmallPtrSet<const MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
  247. BasicBlockNumbering.end());
  248. unsigned NumSSMIters = 0;
  249. bool changed = true;
  250. while (changed) {
  251. changed = false;
  252. ++NumSSMIters;
  253. SmallPtrSet<const MachineBasicBlock*, 8> NextBBSet;
  254. for (const MachineBasicBlock *BB : BasicBlockNumbering) {
  255. if (!BBSet.count(BB)) continue;
  256. // Use an iterator to avoid repeated lookups.
  257. LivenessMap::iterator BI = BlockLiveness.find(BB);
  258. assert(BI != BlockLiveness.end() && "Block not found");
  259. BlockLifetimeInfo &BlockInfo = BI->second;
  260. BitVector LocalLiveIn;
  261. BitVector LocalLiveOut;
  262. // Forward propagation from begins to ends.
  263. for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
  264. PE = BB->pred_end(); PI != PE; ++PI) {
  265. LivenessMap::const_iterator I = BlockLiveness.find(*PI);
  266. assert(I != BlockLiveness.end() && "Predecessor not found");
  267. LocalLiveIn |= I->second.LiveOut;
  268. }
  269. LocalLiveIn |= BlockInfo.End;
  270. LocalLiveIn.reset(BlockInfo.Begin);
  271. // Reverse propagation from ends to begins.
  272. for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
  273. SE = BB->succ_end(); SI != SE; ++SI) {
  274. LivenessMap::const_iterator I = BlockLiveness.find(*SI);
  275. assert(I != BlockLiveness.end() && "Successor not found");
  276. LocalLiveOut |= I->second.LiveIn;
  277. }
  278. LocalLiveOut |= BlockInfo.Begin;
  279. LocalLiveOut.reset(BlockInfo.End);
  280. LocalLiveIn |= LocalLiveOut;
  281. LocalLiveOut |= LocalLiveIn;
  282. // After adopting the live bits, we need to turn-off the bits which
  283. // are de-activated in this block.
  284. LocalLiveOut.reset(BlockInfo.End);
  285. LocalLiveIn.reset(BlockInfo.Begin);
  286. // If we have both BEGIN and END markers in the same basic block then
  287. // we know that the BEGIN marker comes after the END, because we already
  288. // handle the case where the BEGIN comes before the END when collecting
  289. // the markers (and building the BEGIN/END vectore).
  290. // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
  291. // BEGIN and END because it means that the value lives before and after
  292. // this basic block.
  293. BitVector LocalEndBegin = BlockInfo.End;
  294. LocalEndBegin &= BlockInfo.Begin;
  295. LocalLiveIn |= LocalEndBegin;
  296. LocalLiveOut |= LocalEndBegin;
  297. if (LocalLiveIn.test(BlockInfo.LiveIn)) {
  298. changed = true;
  299. BlockInfo.LiveIn |= LocalLiveIn;
  300. NextBBSet.insert(BB->pred_begin(), BB->pred_end());
  301. }
  302. if (LocalLiveOut.test(BlockInfo.LiveOut)) {
  303. changed = true;
  304. BlockInfo.LiveOut |= LocalLiveOut;
  305. NextBBSet.insert(BB->succ_begin(), BB->succ_end());
  306. }
  307. }
  308. BBSet = std::move(NextBBSet);
  309. }// while changed.
  310. }
  311. void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
  312. SmallVector<SlotIndex, 16> Starts;
  313. SmallVector<SlotIndex, 16> Finishes;
  314. // For each block, find which slots are active within this block
  315. // and update the live intervals.
  316. for (const MachineBasicBlock &MBB : *MF) {
  317. Starts.clear();
  318. Starts.resize(NumSlots);
  319. Finishes.clear();
  320. Finishes.resize(NumSlots);
  321. // Create the interval for the basic blocks with lifetime markers in them.
  322. for (const MachineInstr *MI : Markers) {
  323. if (MI->getParent() != &MBB)
  324. continue;
  325. assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
  326. MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
  327. "Invalid Lifetime marker");
  328. bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
  329. const MachineOperand &Mo = MI->getOperand(0);
  330. int Slot = Mo.getIndex();
  331. assert(Slot >= 0 && "Invalid slot");
  332. SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
  333. if (IsStart) {
  334. if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
  335. Starts[Slot] = ThisIndex;
  336. } else {
  337. if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
  338. Finishes[Slot] = ThisIndex;
  339. }
  340. }
  341. // Create the interval of the blocks that we previously found to be 'alive'.
  342. BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
  343. for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
  344. pos = MBBLiveness.LiveIn.find_next(pos)) {
  345. Starts[pos] = Indexes->getMBBStartIdx(&MBB);
  346. }
  347. for (int pos = MBBLiveness.LiveOut.find_first(); pos != -1;
  348. pos = MBBLiveness.LiveOut.find_next(pos)) {
  349. Finishes[pos] = Indexes->getMBBEndIdx(&MBB);
  350. }
  351. for (unsigned i = 0; i < NumSlots; ++i) {
  352. assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
  353. if (!Starts[i].isValid())
  354. continue;
  355. assert(Starts[i] && Finishes[i] && "Invalid interval");
  356. VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
  357. SlotIndex S = Starts[i];
  358. SlotIndex F = Finishes[i];
  359. if (S < F) {
  360. // We have a single consecutive region.
  361. Intervals[i]->addSegment(LiveInterval::Segment(S, F, ValNum));
  362. } else {
  363. // We have two non-consecutive regions. This happens when
  364. // LIFETIME_START appears after the LIFETIME_END marker.
  365. SlotIndex NewStart = Indexes->getMBBStartIdx(&MBB);
  366. SlotIndex NewFin = Indexes->getMBBEndIdx(&MBB);
  367. Intervals[i]->addSegment(LiveInterval::Segment(NewStart, F, ValNum));
  368. Intervals[i]->addSegment(LiveInterval::Segment(S, NewFin, ValNum));
  369. }
  370. }
  371. }
  372. }
  373. bool StackColoring::removeAllMarkers() {
  374. unsigned Count = 0;
  375. for (MachineInstr *MI : Markers) {
  376. MI->eraseFromParent();
  377. Count++;
  378. }
  379. Markers.clear();
  380. DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
  381. return Count;
  382. }
  383. void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
  384. unsigned FixedInstr = 0;
  385. unsigned FixedMemOp = 0;
  386. unsigned FixedDbg = 0;
  387. MachineModuleInfo *MMI = &MF->getMMI();
  388. // Remap debug information that refers to stack slots.
  389. for (auto &VI : MMI->getVariableDbgInfo()) {
  390. if (!VI.Var)
  391. continue;
  392. if (SlotRemap.count(VI.Slot)) {
  393. DEBUG(dbgs() << "Remapping debug info for ["
  394. << cast<DILocalVariable>(VI.Var)->getName() << "].\n");
  395. VI.Slot = SlotRemap[VI.Slot];
  396. FixedDbg++;
  397. }
  398. }
  399. // Keep a list of *allocas* which need to be remapped.
  400. DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
  401. for (const std::pair<int, int> &SI : SlotRemap) {
  402. const AllocaInst *From = MFI->getObjectAllocation(SI.first);
  403. const AllocaInst *To = MFI->getObjectAllocation(SI.second);
  404. assert(To && From && "Invalid allocation object");
  405. Allocas[From] = To;
  406. // AA might be used later for instruction scheduling, and we need it to be
  407. // able to deduce the correct aliasing releationships between pointers
  408. // derived from the alloca being remapped and the target of that remapping.
  409. // The only safe way, without directly informing AA about the remapping
  410. // somehow, is to directly update the IR to reflect the change being made
  411. // here.
  412. Instruction *Inst = const_cast<AllocaInst *>(To);
  413. if (From->getType() != To->getType()) {
  414. BitCastInst *Cast = new BitCastInst(Inst, From->getType());
  415. Cast->insertAfter(Inst);
  416. Inst = Cast;
  417. }
  418. // Allow the stack protector to adjust its value map to account for the
  419. // upcoming replacement.
  420. SP->adjustForColoring(From, To);
  421. // Note that this will not replace uses in MMOs (which we'll update below),
  422. // or anywhere else (which is why we won't delete the original
  423. // instruction).
  424. const_cast<AllocaInst *>(From)->replaceAllUsesWith(Inst);
  425. }
  426. // Remap all instructions to the new stack slots.
  427. for (MachineBasicBlock &BB : *MF)
  428. for (MachineInstr &I : BB) {
  429. // Skip lifetime markers. We'll remove them soon.
  430. if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
  431. I.getOpcode() == TargetOpcode::LIFETIME_END)
  432. continue;
  433. // Update the MachineMemOperand to use the new alloca.
  434. for (MachineMemOperand *MMO : I.memoperands()) {
  435. // FIXME: In order to enable the use of TBAA when using AA in CodeGen,
  436. // we'll also need to update the TBAA nodes in MMOs with values
  437. // derived from the merged allocas. When doing this, we'll need to use
  438. // the same variant of GetUnderlyingObjects that is used by the
  439. // instruction scheduler (that can look through ptrtoint/inttoptr
  440. // pairs).
  441. // We've replaced IR-level uses of the remapped allocas, so we only
  442. // need to replace direct uses here.
  443. const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
  444. if (!AI)
  445. continue;
  446. if (!Allocas.count(AI))
  447. continue;
  448. MMO->setValue(Allocas[AI]);
  449. FixedMemOp++;
  450. }
  451. // Update all of the machine instruction operands.
  452. for (MachineOperand &MO : I.operands()) {
  453. if (!MO.isFI())
  454. continue;
  455. int FromSlot = MO.getIndex();
  456. // Don't touch arguments.
  457. if (FromSlot<0)
  458. continue;
  459. // Only look at mapped slots.
  460. if (!SlotRemap.count(FromSlot))
  461. continue;
  462. // In a debug build, check that the instruction that we are modifying is
  463. // inside the expected live range. If the instruction is not inside
  464. // the calculated range then it means that the alloca usage moved
  465. // outside of the lifetime markers, or that the user has a bug.
  466. // NOTE: Alloca address calculations which happen outside the lifetime
  467. // zone are are okay, despite the fact that we don't have a good way
  468. // for validating all of the usages of the calculation.
  469. #ifndef NDEBUG
  470. bool TouchesMemory = I.mayLoad() || I.mayStore();
  471. // If we *don't* protect the user from escaped allocas, don't bother
  472. // validating the instructions.
  473. if (!I.isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
  474. SlotIndex Index = Indexes->getInstructionIndex(&I);
  475. const LiveInterval *Interval = &*Intervals[FromSlot];
  476. assert(Interval->find(Index) != Interval->end() &&
  477. "Found instruction usage outside of live range.");
  478. }
  479. #endif
  480. // Fix the machine instructions.
  481. int ToSlot = SlotRemap[FromSlot];
  482. MO.setIndex(ToSlot);
  483. FixedInstr++;
  484. }
  485. }
  486. DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
  487. DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
  488. DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
  489. }
  490. void StackColoring::removeInvalidSlotRanges() {
  491. for (MachineBasicBlock &BB : *MF)
  492. for (MachineInstr &I : BB) {
  493. if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
  494. I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugValue())
  495. continue;
  496. // Some intervals are suspicious! In some cases we find address
  497. // calculations outside of the lifetime zone, but not actual memory
  498. // read or write. Memory accesses outside of the lifetime zone are a clear
  499. // violation, but address calculations are okay. This can happen when
  500. // GEPs are hoisted outside of the lifetime zone.
  501. // So, in here we only check instructions which can read or write memory.
  502. if (!I.mayLoad() && !I.mayStore())
  503. continue;
  504. // Check all of the machine operands.
  505. for (const MachineOperand &MO : I.operands()) {
  506. if (!MO.isFI())
  507. continue;
  508. int Slot = MO.getIndex();
  509. if (Slot<0)
  510. continue;
  511. if (Intervals[Slot]->empty())
  512. continue;
  513. // Check that the used slot is inside the calculated lifetime range.
  514. // If it is not, warn about it and invalidate the range.
  515. LiveInterval *Interval = &*Intervals[Slot];
  516. SlotIndex Index = Indexes->getInstructionIndex(&I);
  517. if (Interval->find(Index) == Interval->end()) {
  518. Interval->clear();
  519. DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
  520. EscapedAllocas++;
  521. }
  522. }
  523. }
  524. }
  525. void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
  526. unsigned NumSlots) {
  527. // Expunge slot remap map.
  528. for (unsigned i=0; i < NumSlots; ++i) {
  529. // If we are remapping i
  530. if (SlotRemap.count(i)) {
  531. int Target = SlotRemap[i];
  532. // As long as our target is mapped to something else, follow it.
  533. while (SlotRemap.count(Target)) {
  534. Target = SlotRemap[Target];
  535. SlotRemap[i] = Target;
  536. }
  537. }
  538. }
  539. }
  540. bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
  541. if (skipOptnoneFunction(*Func.getFunction()))
  542. return false;
  543. DEBUG(dbgs() << "********** Stack Coloring **********\n"
  544. << "********** Function: "
  545. << ((const Value*)Func.getFunction())->getName() << '\n');
  546. MF = &Func;
  547. MFI = MF->getFrameInfo();
  548. Indexes = &getAnalysis<SlotIndexes>();
  549. SP = &getAnalysis<StackProtector>();
  550. BlockLiveness.clear();
  551. BasicBlocks.clear();
  552. BasicBlockNumbering.clear();
  553. Markers.clear();
  554. Intervals.clear();
  555. VNInfoAllocator.Reset();
  556. unsigned NumSlots = MFI->getObjectIndexEnd();
  557. // If there are no stack slots then there are no markers to remove.
  558. if (!NumSlots)
  559. return false;
  560. SmallVector<int, 8> SortedSlots;
  561. SortedSlots.reserve(NumSlots);
  562. Intervals.reserve(NumSlots);
  563. unsigned NumMarkers = collectMarkers(NumSlots);
  564. unsigned TotalSize = 0;
  565. DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
  566. DEBUG(dbgs()<<"Slot structure:\n");
  567. for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
  568. DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
  569. TotalSize += MFI->getObjectSize(i);
  570. }
  571. DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
  572. // Don't continue because there are not enough lifetime markers, or the
  573. // stack is too small, or we are told not to optimize the slots.
  574. if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
  575. DEBUG(dbgs()<<"Will not try to merge slots.\n");
  576. return removeAllMarkers();
  577. }
  578. for (unsigned i=0; i < NumSlots; ++i) {
  579. std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0));
  580. LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
  581. Intervals.push_back(std::move(LI));
  582. SortedSlots.push_back(i);
  583. }
  584. // Calculate the liveness of each block.
  585. calculateLocalLiveness();
  586. // Propagate the liveness information.
  587. calculateLiveIntervals(NumSlots);
  588. // Search for allocas which are used outside of the declared lifetime
  589. // markers.
  590. if (ProtectFromEscapedAllocas)
  591. removeInvalidSlotRanges();
  592. // Maps old slots to new slots.
  593. DenseMap<int, int> SlotRemap;
  594. unsigned RemovedSlots = 0;
  595. unsigned ReducedSize = 0;
  596. // Do not bother looking at empty intervals.
  597. for (unsigned I = 0; I < NumSlots; ++I) {
  598. if (Intervals[SortedSlots[I]]->empty())
  599. SortedSlots[I] = -1;
  600. }
  601. // This is a simple greedy algorithm for merging allocas. First, sort the
  602. // slots, placing the largest slots first. Next, perform an n^2 scan and look
  603. // for disjoint slots. When you find disjoint slots, merge the samller one
  604. // into the bigger one and update the live interval. Remove the small alloca
  605. // and continue.
  606. // Sort the slots according to their size. Place unused slots at the end.
  607. // Use stable sort to guarantee deterministic code generation.
  608. std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
  609. [this](int LHS, int RHS) {
  610. // We use -1 to denote a uninteresting slot. Place these slots at the end.
  611. if (LHS == -1) return false;
  612. if (RHS == -1) return true;
  613. // Sort according to size.
  614. return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
  615. });
  616. bool Changed = true;
  617. while (Changed) {
  618. Changed = false;
  619. for (unsigned I = 0; I < NumSlots; ++I) {
  620. if (SortedSlots[I] == -1)
  621. continue;
  622. for (unsigned J=I+1; J < NumSlots; ++J) {
  623. if (SortedSlots[J] == -1)
  624. continue;
  625. int FirstSlot = SortedSlots[I];
  626. int SecondSlot = SortedSlots[J];
  627. LiveInterval *First = &*Intervals[FirstSlot];
  628. LiveInterval *Second = &*Intervals[SecondSlot];
  629. assert (!First->empty() && !Second->empty() && "Found an empty range");
  630. // Merge disjoint slots.
  631. if (!First->overlaps(*Second)) {
  632. Changed = true;
  633. First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
  634. SlotRemap[SecondSlot] = FirstSlot;
  635. SortedSlots[J] = -1;
  636. DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
  637. SecondSlot<<" together.\n");
  638. unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
  639. MFI->getObjectAlignment(SecondSlot));
  640. assert(MFI->getObjectSize(FirstSlot) >=
  641. MFI->getObjectSize(SecondSlot) &&
  642. "Merging a small object into a larger one");
  643. RemovedSlots+=1;
  644. ReducedSize += MFI->getObjectSize(SecondSlot);
  645. MFI->setObjectAlignment(FirstSlot, MaxAlignment);
  646. MFI->RemoveStackObject(SecondSlot);
  647. }
  648. }
  649. }
  650. }// While changed.
  651. // Record statistics.
  652. StackSpaceSaved += ReducedSize;
  653. StackSlotMerged += RemovedSlots;
  654. DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
  655. ReducedSize<<" bytes\n");
  656. // Scan the entire function and update all machine operands that use frame
  657. // indices to use the remapped frame index.
  658. expungeSlotMap(SlotRemap, NumSlots);
  659. remapInstructions(SlotRemap);
  660. return removeAllMarkers();
  661. }