StackColoring.cpp 29 KB

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