StackColoring.cpp 29 KB

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