1 //===-- StackColoring.cpp -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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
19 // 2. Merge this pass with StackSlotColoring and allow merging of allocas with
22 //===----------------------------------------------------------------------===//
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/Passes.h"
43 #include "llvm/CodeGen/PseudoSourceValue.h"
44 #include "llvm/CodeGen/SlotIndexes.h"
45 #include "llvm/CodeGen/StackProtector.h"
46 #include "llvm/CodeGen/WinEHFuncInfo.h"
47 #include "llvm/IR/DebugInfo.h"
48 #include "llvm/IR/Dominators.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/IntrinsicInst.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetInstrInfo.h"
57 #include "llvm/Target/TargetRegisterInfo.h"
61 #define DEBUG_TYPE "stackcoloring"
64 DisableColoring("no-stack-coloring",
65 cl::init(false), cl::Hidden,
66 cl::desc("Disable stack coloring"));
68 /// The user may write code that uses allocas outside of the declared lifetime
69 /// zone. This can happen when the user returns a reference to a local
70 /// data-structure. We can detect these cases and decide not to optimize the
71 /// code. If this flag is enabled, we try to save the user.
73 ProtectFromEscapedAllocas("protect-from-escaped-allocas",
74 cl::init(false), cl::Hidden,
75 cl::desc("Do not optimize lifetime zones that "
78 STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
79 STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
80 STATISTIC(StackSlotMerged, "Number of stack slot merged.");
81 STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region");
83 //===----------------------------------------------------------------------===//
85 //===----------------------------------------------------------------------===//
88 /// StackColoring - A machine pass for merging disjoint stack allocations,
89 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
90 class StackColoring : public MachineFunctionPass {
91 MachineFrameInfo *MFI;
94 /// A class representing liveness information for a single basic block.
95 /// Each bit in the BitVector represents the liveness property
96 /// for a different stack slot.
97 struct BlockLifetimeInfo {
98 /// Which slots BEGINs in each basic block.
100 /// Which slots ENDs in each basic block.
102 /// Which slots are marked as LIVE_IN, coming into each basic block.
104 /// Which slots are marked as LIVE_OUT, coming out of each basic block.
108 /// Maps active slots (per bit) for each basic block.
109 typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap;
110 LivenessMap BlockLiveness;
112 /// Maps serial numbers to basic blocks.
113 DenseMap<const MachineBasicBlock*, int> BasicBlocks;
114 /// Maps basic blocks to a serial number.
115 SmallVector<const MachineBasicBlock*, 8> BasicBlockNumbering;
117 /// Maps liveness intervals for each slot.
118 SmallVector<std::unique_ptr<LiveInterval>, 16> Intervals;
119 /// VNInfo is used for the construction of LiveIntervals.
120 VNInfo::Allocator VNInfoAllocator;
121 /// SlotIndex analysis object.
122 SlotIndexes *Indexes;
123 /// The stack protector object.
126 /// The list of lifetime markers found. These markers are to be removed
127 /// once the coloring is done.
128 SmallVector<MachineInstr*, 8> Markers;
132 StackColoring() : MachineFunctionPass(ID) {
133 initializeStackColoringPass(*PassRegistry::getPassRegistry());
135 void getAnalysisUsage(AnalysisUsage &AU) const override;
136 bool runOnMachineFunction(MachineFunction &MF) override;
142 /// Removes all of the lifetime marker instructions from the function.
143 /// \returns true if any markers were removed.
144 bool removeAllMarkers();
146 /// Scan the machine function and find all of the lifetime markers.
147 /// Record the findings in the BEGIN and END vectors.
148 /// \returns the number of markers found.
149 unsigned collectMarkers(unsigned NumSlot);
151 /// Perform the dataflow calculation and calculate the lifetime for each of
152 /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
153 /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
154 /// in and out blocks.
155 void calculateLocalLiveness();
157 /// Construct the LiveIntervals for the slots.
158 void calculateLiveIntervals(unsigned NumSlots);
160 /// Go over the machine function and change instructions which use stack
161 /// slots to use the joint slots.
162 void remapInstructions(DenseMap<int, int> &SlotRemap);
164 /// The input program may contain instructions which are not inside lifetime
165 /// markers. This can happen due to a bug in the compiler or due to a bug in
166 /// user code (for example, returning a reference to a local variable).
167 /// This procedure checks all of the instructions in the function and
168 /// invalidates lifetime ranges which do not contain all of the instructions
169 /// which access that frame slot.
170 void removeInvalidSlotRanges();
172 /// Map entries which point to other entries to their destination.
173 /// A->B->C becomes A->C.
174 void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
176 } // end anonymous namespace
178 char StackColoring::ID = 0;
179 char &llvm::StackColoringID = StackColoring::ID;
181 INITIALIZE_PASS_BEGIN(StackColoring,
182 "stack-coloring", "Merge disjoint stack slots", false, false)
183 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
184 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
185 INITIALIZE_PASS_DEPENDENCY(StackProtector)
186 INITIALIZE_PASS_END(StackColoring,
187 "stack-coloring", "Merge disjoint stack slots", false, false)
189 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
190 AU.addRequired<MachineDominatorTree>();
191 AU.addPreserved<MachineDominatorTree>();
192 AU.addRequired<SlotIndexes>();
193 AU.addRequired<StackProtector>();
194 MachineFunctionPass::getAnalysisUsage(AU);
197 void StackColoring::dump() const {
198 for (MachineBasicBlock *MBB : depth_first(MF)) {
199 DEBUG(dbgs() << "Inspecting block #" << BasicBlocks.lookup(MBB) << " ["
200 << MBB->getName() << "]\n");
202 LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
203 assert(BI != BlockLiveness.end() && "Block not found");
204 const BlockLifetimeInfo &BlockInfo = BI->second;
206 DEBUG(dbgs()<<"BEGIN : {");
207 for (unsigned i=0; i < BlockInfo.Begin.size(); ++i)
208 DEBUG(dbgs()<<BlockInfo.Begin.test(i)<<" ");
209 DEBUG(dbgs()<<"}\n");
211 DEBUG(dbgs()<<"END : {");
212 for (unsigned i=0; i < BlockInfo.End.size(); ++i)
213 DEBUG(dbgs()<<BlockInfo.End.test(i)<<" ");
215 DEBUG(dbgs()<<"}\n");
217 DEBUG(dbgs()<<"LIVE_IN: {");
218 for (unsigned i=0; i < BlockInfo.LiveIn.size(); ++i)
219 DEBUG(dbgs()<<BlockInfo.LiveIn.test(i)<<" ");
221 DEBUG(dbgs()<<"}\n");
222 DEBUG(dbgs()<<"LIVEOUT: {");
223 for (unsigned i=0; i < BlockInfo.LiveOut.size(); ++i)
224 DEBUG(dbgs()<<BlockInfo.LiveOut.test(i)<<" ");
225 DEBUG(dbgs()<<"}\n");
229 unsigned StackColoring::collectMarkers(unsigned NumSlot) {
230 unsigned MarkersFound = 0;
231 // Scan the function to find all lifetime markers.
232 // NOTE: We use a reverse-post-order iteration to ensure that we obtain a
233 // deterministic numbering, and because we'll need a post-order iteration
234 // later for solving the liveness dataflow problem.
235 for (MachineBasicBlock *MBB : depth_first(MF)) {
237 // Assign a serial number to this basic block.
238 BasicBlocks[MBB] = BasicBlockNumbering.size();
239 BasicBlockNumbering.push_back(MBB);
241 // Keep a reference to avoid repeated lookups.
242 BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
244 BlockInfo.Begin.resize(NumSlot);
245 BlockInfo.End.resize(NumSlot);
247 for (MachineInstr &MI : *MBB) {
248 if (MI.getOpcode() != TargetOpcode::LIFETIME_START &&
249 MI.getOpcode() != TargetOpcode::LIFETIME_END)
252 Markers.push_back(&MI);
254 bool IsStart = MI.getOpcode() == TargetOpcode::LIFETIME_START;
255 const MachineOperand &MO = MI.getOperand(0);
256 unsigned Slot = MO.getIndex();
260 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
262 DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
263 " with allocation: "<< Allocation->getName()<<"\n");
267 BlockInfo.Begin.set(Slot);
269 if (BlockInfo.Begin.test(Slot)) {
270 // Allocas that start and end within a single block are handled
271 // specially when computing the LiveIntervals to avoid pessimizing
272 // the liveness propagation.
273 BlockInfo.Begin.reset(Slot);
275 BlockInfo.End.set(Slot);
281 // Update statistics.
282 NumMarkerSeen += MarkersFound;
286 void StackColoring::calculateLocalLiveness() {
287 // Perform a standard reverse dataflow computation to solve for
288 // global liveness. The BEGIN set here is equivalent to KILL in the standard
289 // formulation, and END is equivalent to GEN. The result of this computation
290 // is a map from blocks to bitvectors where the bitvectors represent which
291 // allocas are live in/out of that block.
292 SmallPtrSet<const MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
293 BasicBlockNumbering.end());
294 unsigned NumSSMIters = 0;
300 SmallPtrSet<const MachineBasicBlock*, 8> NextBBSet;
302 for (const MachineBasicBlock *BB : BasicBlockNumbering) {
303 if (!BBSet.count(BB)) continue;
305 // Use an iterator to avoid repeated lookups.
306 LivenessMap::iterator BI = BlockLiveness.find(BB);
307 assert(BI != BlockLiveness.end() && "Block not found");
308 BlockLifetimeInfo &BlockInfo = BI->second;
310 BitVector LocalLiveIn;
311 BitVector LocalLiveOut;
313 // Forward propagation from begins to ends.
314 for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
315 PE = BB->pred_end(); PI != PE; ++PI) {
316 LivenessMap::const_iterator I = BlockLiveness.find(*PI);
317 assert(I != BlockLiveness.end() && "Predecessor not found");
318 LocalLiveIn |= I->second.LiveOut;
320 LocalLiveIn |= BlockInfo.End;
321 LocalLiveIn.reset(BlockInfo.Begin);
323 // Reverse propagation from ends to begins.
324 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
325 SE = BB->succ_end(); SI != SE; ++SI) {
326 LivenessMap::const_iterator I = BlockLiveness.find(*SI);
327 assert(I != BlockLiveness.end() && "Successor not found");
328 LocalLiveOut |= I->second.LiveIn;
330 LocalLiveOut |= BlockInfo.Begin;
331 LocalLiveOut.reset(BlockInfo.End);
333 LocalLiveIn |= LocalLiveOut;
334 LocalLiveOut |= LocalLiveIn;
336 // After adopting the live bits, we need to turn-off the bits which
337 // are de-activated in this block.
338 LocalLiveOut.reset(BlockInfo.End);
339 LocalLiveIn.reset(BlockInfo.Begin);
341 // If we have both BEGIN and END markers in the same basic block then
342 // we know that the BEGIN marker comes after the END, because we already
343 // handle the case where the BEGIN comes before the END when collecting
344 // the markers (and building the BEGIN/END vectore).
345 // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
346 // BEGIN and END because it means that the value lives before and after
348 BitVector LocalEndBegin = BlockInfo.End;
349 LocalEndBegin &= BlockInfo.Begin;
350 LocalLiveIn |= LocalEndBegin;
351 LocalLiveOut |= LocalEndBegin;
353 if (LocalLiveIn.test(BlockInfo.LiveIn)) {
355 BlockInfo.LiveIn |= LocalLiveIn;
357 NextBBSet.insert(BB->pred_begin(), BB->pred_end());
360 if (LocalLiveOut.test(BlockInfo.LiveOut)) {
362 BlockInfo.LiveOut |= LocalLiveOut;
364 NextBBSet.insert(BB->succ_begin(), BB->succ_end());
368 BBSet = std::move(NextBBSet);
372 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
373 SmallVector<SlotIndex, 16> Starts;
374 SmallVector<SlotIndex, 16> Finishes;
376 // For each block, find which slots are active within this block
377 // and update the live intervals.
378 for (const MachineBasicBlock &MBB : *MF) {
380 Starts.resize(NumSlots);
382 Finishes.resize(NumSlots);
384 // Create the interval for the basic blocks with lifetime markers in them.
385 for (const MachineInstr *MI : Markers) {
386 if (MI->getParent() != &MBB)
389 assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
390 MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
391 "Invalid Lifetime marker");
393 bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
394 const MachineOperand &Mo = MI->getOperand(0);
395 int Slot = Mo.getIndex();
396 assert(Slot >= 0 && "Invalid slot");
398 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
401 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
402 Starts[Slot] = ThisIndex;
404 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
405 Finishes[Slot] = ThisIndex;
409 // Create the interval of the blocks that we previously found to be 'alive'.
410 BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
411 for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
412 pos = MBBLiveness.LiveIn.find_next(pos)) {
413 Starts[pos] = Indexes->getMBBStartIdx(&MBB);
415 for (int pos = MBBLiveness.LiveOut.find_first(); pos != -1;
416 pos = MBBLiveness.LiveOut.find_next(pos)) {
417 Finishes[pos] = Indexes->getMBBEndIdx(&MBB);
420 for (unsigned i = 0; i < NumSlots; ++i) {
421 assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
422 if (!Starts[i].isValid())
425 assert(Starts[i] && Finishes[i] && "Invalid interval");
426 VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
427 SlotIndex S = Starts[i];
428 SlotIndex F = Finishes[i];
430 // We have a single consecutive region.
431 Intervals[i]->addSegment(LiveInterval::Segment(S, F, ValNum));
433 // We have two non-consecutive regions. This happens when
434 // LIFETIME_START appears after the LIFETIME_END marker.
435 SlotIndex NewStart = Indexes->getMBBStartIdx(&MBB);
436 SlotIndex NewFin = Indexes->getMBBEndIdx(&MBB);
437 Intervals[i]->addSegment(LiveInterval::Segment(NewStart, F, ValNum));
438 Intervals[i]->addSegment(LiveInterval::Segment(S, NewFin, ValNum));
444 bool StackColoring::removeAllMarkers() {
446 for (MachineInstr *MI : Markers) {
447 MI->eraseFromParent();
452 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
456 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
457 unsigned FixedInstr = 0;
458 unsigned FixedMemOp = 0;
459 unsigned FixedDbg = 0;
460 MachineModuleInfo *MMI = &MF->getMMI();
462 // Remap debug information that refers to stack slots.
463 for (auto &VI : MMI->getVariableDbgInfo()) {
466 if (SlotRemap.count(VI.Slot)) {
467 DEBUG(dbgs() << "Remapping debug info for ["
468 << cast<DILocalVariable>(VI.Var)->getName() << "].\n");
469 VI.Slot = SlotRemap[VI.Slot];
474 // Keep a list of *allocas* which need to be remapped.
475 DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
476 for (const std::pair<int, int> &SI : SlotRemap) {
477 const AllocaInst *From = MFI->getObjectAllocation(SI.first);
478 const AllocaInst *To = MFI->getObjectAllocation(SI.second);
479 assert(To && From && "Invalid allocation object");
482 // AA might be used later for instruction scheduling, and we need it to be
483 // able to deduce the correct aliasing releationships between pointers
484 // derived from the alloca being remapped and the target of that remapping.
485 // The only safe way, without directly informing AA about the remapping
486 // somehow, is to directly update the IR to reflect the change being made
488 Instruction *Inst = const_cast<AllocaInst *>(To);
489 if (From->getType() != To->getType()) {
490 BitCastInst *Cast = new BitCastInst(Inst, From->getType());
491 Cast->insertAfter(Inst);
495 // Allow the stack protector to adjust its value map to account for the
496 // upcoming replacement.
497 SP->adjustForColoring(From, To);
499 // The new alloca might not be valid in a llvm.dbg.declare for this
500 // variable, so undef out the use to make the verifier happy.
501 AllocaInst *FromAI = const_cast<AllocaInst *>(From);
502 if (FromAI->isUsedByMetadata())
503 ValueAsMetadata::handleRAUW(FromAI, UndefValue::get(FromAI->getType()));
504 for (auto &Use : FromAI->uses()) {
505 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Use.get()))
506 if (BCI->isUsedByMetadata())
507 ValueAsMetadata::handleRAUW(BCI, UndefValue::get(BCI->getType()));
510 // Note that this will not replace uses in MMOs (which we'll update below),
511 // or anywhere else (which is why we won't delete the original
513 FromAI->replaceAllUsesWith(Inst);
516 // Remap all instructions to the new stack slots.
517 for (MachineBasicBlock &BB : *MF)
518 for (MachineInstr &I : BB) {
519 // Skip lifetime markers. We'll remove them soon.
520 if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
521 I.getOpcode() == TargetOpcode::LIFETIME_END)
524 // Update the MachineMemOperand to use the new alloca.
525 for (MachineMemOperand *MMO : I.memoperands()) {
526 // FIXME: In order to enable the use of TBAA when using AA in CodeGen,
527 // we'll also need to update the TBAA nodes in MMOs with values
528 // derived from the merged allocas. When doing this, we'll need to use
529 // the same variant of GetUnderlyingObjects that is used by the
530 // instruction scheduler (that can look through ptrtoint/inttoptr
533 // We've replaced IR-level uses of the remapped allocas, so we only
534 // need to replace direct uses here.
535 const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
539 if (!Allocas.count(AI))
542 MMO->setValue(Allocas[AI]);
546 // Update all of the machine instruction operands.
547 for (MachineOperand &MO : I.operands()) {
550 int FromSlot = MO.getIndex();
552 // Don't touch arguments.
556 // Only look at mapped slots.
557 if (!SlotRemap.count(FromSlot))
560 // In a debug build, check that the instruction that we are modifying is
561 // inside the expected live range. If the instruction is not inside
562 // the calculated range then it means that the alloca usage moved
563 // outside of the lifetime markers, or that the user has a bug.
564 // NOTE: Alloca address calculations which happen outside the lifetime
565 // zone are are okay, despite the fact that we don't have a good way
566 // for validating all of the usages of the calculation.
568 bool TouchesMemory = I.mayLoad() || I.mayStore();
569 // If we *don't* protect the user from escaped allocas, don't bother
570 // validating the instructions.
571 if (!I.isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
572 SlotIndex Index = Indexes->getInstructionIndex(&I);
573 const LiveInterval *Interval = &*Intervals[FromSlot];
574 assert(Interval->find(Index) != Interval->end() &&
575 "Found instruction usage outside of live range.");
579 // Fix the machine instructions.
580 int ToSlot = SlotRemap[FromSlot];
586 // Update the location of C++ catch objects for the MSVC personality routine.
587 if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo())
588 for (WinEHTryBlockMapEntry &TBME : EHInfo->TryBlockMap)
589 for (WinEHHandlerType &H : TBME.HandlerArray)
590 if (H.CatchObj.FrameIndex != INT_MAX &&
591 SlotRemap.count(H.CatchObj.FrameIndex))
592 H.CatchObj.FrameIndex = SlotRemap[H.CatchObj.FrameIndex];
594 DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
595 DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
596 DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
599 void StackColoring::removeInvalidSlotRanges() {
600 for (MachineBasicBlock &BB : *MF)
601 for (MachineInstr &I : BB) {
602 if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
603 I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugValue())
606 // Some intervals are suspicious! In some cases we find address
607 // calculations outside of the lifetime zone, but not actual memory
608 // read or write. Memory accesses outside of the lifetime zone are a clear
609 // violation, but address calculations are okay. This can happen when
610 // GEPs are hoisted outside of the lifetime zone.
611 // So, in here we only check instructions which can read or write memory.
612 if (!I.mayLoad() && !I.mayStore())
615 // Check all of the machine operands.
616 for (const MachineOperand &MO : I.operands()) {
620 int Slot = MO.getIndex();
625 if (Intervals[Slot]->empty())
628 // Check that the used slot is inside the calculated lifetime range.
629 // If it is not, warn about it and invalidate the range.
630 LiveInterval *Interval = &*Intervals[Slot];
631 SlotIndex Index = Indexes->getInstructionIndex(&I);
632 if (Interval->find(Index) == Interval->end()) {
634 DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
641 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
643 // Expunge slot remap map.
644 for (unsigned i=0; i < NumSlots; ++i) {
645 // If we are remapping i
646 if (SlotRemap.count(i)) {
647 int Target = SlotRemap[i];
648 // As long as our target is mapped to something else, follow it.
649 while (SlotRemap.count(Target)) {
650 Target = SlotRemap[Target];
651 SlotRemap[i] = Target;
657 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
658 if (skipOptnoneFunction(*Func.getFunction()))
661 DEBUG(dbgs() << "********** Stack Coloring **********\n"
662 << "********** Function: "
663 << ((const Value*)Func.getFunction())->getName() << '\n');
665 MFI = MF->getFrameInfo();
666 Indexes = &getAnalysis<SlotIndexes>();
667 SP = &getAnalysis<StackProtector>();
668 BlockLiveness.clear();
670 BasicBlockNumbering.clear();
673 VNInfoAllocator.Reset();
675 unsigned NumSlots = MFI->getObjectIndexEnd();
677 // If there are no stack slots then there are no markers to remove.
681 SmallVector<int, 8> SortedSlots;
683 SortedSlots.reserve(NumSlots);
684 Intervals.reserve(NumSlots);
686 unsigned NumMarkers = collectMarkers(NumSlots);
688 unsigned TotalSize = 0;
689 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
690 DEBUG(dbgs()<<"Slot structure:\n");
692 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
693 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
694 TotalSize += MFI->getObjectSize(i);
697 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
699 // Don't continue because there are not enough lifetime markers, or the
700 // stack is too small, or we are told not to optimize the slots.
701 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
702 DEBUG(dbgs()<<"Will not try to merge slots.\n");
703 return removeAllMarkers();
706 for (unsigned i=0; i < NumSlots; ++i) {
707 std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0));
708 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
709 Intervals.push_back(std::move(LI));
710 SortedSlots.push_back(i);
713 // Calculate the liveness of each block.
714 calculateLocalLiveness();
716 // Propagate the liveness information.
717 calculateLiveIntervals(NumSlots);
719 // Search for allocas which are used outside of the declared lifetime
721 if (ProtectFromEscapedAllocas)
722 removeInvalidSlotRanges();
724 // Maps old slots to new slots.
725 DenseMap<int, int> SlotRemap;
726 unsigned RemovedSlots = 0;
727 unsigned ReducedSize = 0;
729 // Do not bother looking at empty intervals.
730 for (unsigned I = 0; I < NumSlots; ++I) {
731 if (Intervals[SortedSlots[I]]->empty())
735 // This is a simple greedy algorithm for merging allocas. First, sort the
736 // slots, placing the largest slots first. Next, perform an n^2 scan and look
737 // for disjoint slots. When you find disjoint slots, merge the samller one
738 // into the bigger one and update the live interval. Remove the small alloca
741 // Sort the slots according to their size. Place unused slots at the end.
742 // Use stable sort to guarantee deterministic code generation.
743 std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
744 [this](int LHS, int RHS) {
745 // We use -1 to denote a uninteresting slot. Place these slots at the end.
746 if (LHS == -1) return false;
747 if (RHS == -1) return true;
748 // Sort according to size.
749 return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
755 for (unsigned I = 0; I < NumSlots; ++I) {
756 if (SortedSlots[I] == -1)
759 for (unsigned J=I+1; J < NumSlots; ++J) {
760 if (SortedSlots[J] == -1)
763 int FirstSlot = SortedSlots[I];
764 int SecondSlot = SortedSlots[J];
765 LiveInterval *First = &*Intervals[FirstSlot];
766 LiveInterval *Second = &*Intervals[SecondSlot];
767 assert (!First->empty() && !Second->empty() && "Found an empty range");
769 // Merge disjoint slots.
770 if (!First->overlaps(*Second)) {
772 First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
773 SlotRemap[SecondSlot] = FirstSlot;
775 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
776 SecondSlot<<" together.\n");
777 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
778 MFI->getObjectAlignment(SecondSlot));
780 assert(MFI->getObjectSize(FirstSlot) >=
781 MFI->getObjectSize(SecondSlot) &&
782 "Merging a small object into a larger one");
785 ReducedSize += MFI->getObjectSize(SecondSlot);
786 MFI->setObjectAlignment(FirstSlot, MaxAlignment);
787 MFI->RemoveStackObject(SecondSlot);
793 // Record statistics.
794 StackSpaceSaved += ReducedSize;
795 StackSlotMerged += RemovedSlots;
796 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
797 ReducedSize<<" bytes\n");
799 // Scan the entire function and update all machine operands that use frame
800 // indices to use the remapped frame index.
801 expungeSlotMap(SlotRemap, NumSlots);
802 remapInstructions(SlotRemap);
804 return removeAllMarkers();