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 
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"
58 
59 using namespace llvm;
60 
61 #define DEBUG_TYPE "stackcoloring"
62 
63 static cl::opt<bool>
64 DisableColoring("no-stack-coloring",
65         cl::init(false), cl::Hidden,
66         cl::desc("Disable stack coloring"));
67 
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.
72 static cl::opt<bool>
73 ProtectFromEscapedAllocas("protect-from-escaped-allocas",
74                           cl::init(false), cl::Hidden,
75                           cl::desc("Do not optimize lifetime zones that "
76                                    "are broken"));
77 
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");
82 
83 //===----------------------------------------------------------------------===//
84 //                           StackColoring Pass
85 //===----------------------------------------------------------------------===//
86 
87 namespace {
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;
92   MachineFunction *MF;
93 
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.
99     BitVector Begin;
100     /// Which slots ENDs in each basic block.
101     BitVector End;
102     /// Which slots are marked as LIVE_IN, coming into each basic block.
103     BitVector LiveIn;
104     /// Which slots are marked as LIVE_OUT, coming out of each basic block.
105     BitVector LiveOut;
106   };
107 
108   /// Maps active slots (per bit) for each basic block.
109   typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap;
110   LivenessMap BlockLiveness;
111 
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;
116 
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.
124   StackProtector *SP;
125 
126   /// The list of lifetime markers found. These markers are to be removed
127   /// once the coloring is done.
128   SmallVector<MachineInstr*, 8> Markers;
129 
130 public:
131   static char ID;
132   StackColoring() : MachineFunctionPass(ID) {
133     initializeStackColoringPass(*PassRegistry::getPassRegistry());
134   }
135   void getAnalysisUsage(AnalysisUsage &AU) const override;
136   bool runOnMachineFunction(MachineFunction &MF) override;
137 
138 private:
139   /// Debug.
140   void dump() const;
141 
142   /// Removes all of the lifetime marker instructions from the function.
143   /// \returns true if any markers were removed.
144   bool removeAllMarkers();
145 
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);
150 
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();
156 
157   /// Construct the LiveIntervals for the slots.
158   void calculateLiveIntervals(unsigned NumSlots);
159 
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);
163 
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();
171 
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);
175 };
176 } // end anonymous namespace
177 
178 char StackColoring::ID = 0;
179 char &llvm::StackColoringID = StackColoring::ID;
180 
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)
188 
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);
195 }
196 
197 LLVM_DUMP_METHOD void StackColoring::dump() const {
198   for (MachineBasicBlock *MBB : depth_first(MF)) {
199     DEBUG(dbgs() << "Inspecting block #" << BasicBlocks.lookup(MBB) << " ["
200                  << MBB->getName() << "]\n");
201 
202     LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
203     assert(BI != BlockLiveness.end() && "Block not found");
204     const BlockLifetimeInfo &BlockInfo = BI->second;
205 
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");
210 
211     DEBUG(dbgs()<<"END    : {");
212     for (unsigned i=0; i < BlockInfo.End.size(); ++i)
213       DEBUG(dbgs()<<BlockInfo.End.test(i)<<" ");
214 
215     DEBUG(dbgs()<<"}\n");
216 
217     DEBUG(dbgs()<<"LIVE_IN: {");
218     for (unsigned i=0; i < BlockInfo.LiveIn.size(); ++i)
219       DEBUG(dbgs()<<BlockInfo.LiveIn.test(i)<<" ");
220 
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");
226   }
227 }
228 
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)) {
236 
237     // Assign a serial number to this basic block.
238     BasicBlocks[MBB] = BasicBlockNumbering.size();
239     BasicBlockNumbering.push_back(MBB);
240 
241     // Keep a reference to avoid repeated lookups.
242     BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
243 
244     BlockInfo.Begin.resize(NumSlot);
245     BlockInfo.End.resize(NumSlot);
246 
247     for (MachineInstr &MI : *MBB) {
248       if (MI.getOpcode() != TargetOpcode::LIFETIME_START &&
249           MI.getOpcode() != TargetOpcode::LIFETIME_END)
250         continue;
251 
252       bool IsStart = MI.getOpcode() == TargetOpcode::LIFETIME_START;
253       const MachineOperand &MO = MI.getOperand(0);
254       int Slot = MO.getIndex();
255       if (Slot < 0)
256         continue;
257 
258       Markers.push_back(&MI);
259 
260       MarkersFound++;
261 
262       const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
263       if (Allocation) {
264         DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
265               " with allocation: "<< Allocation->getName()<<"\n");
266       }
267 
268       if (IsStart) {
269         BlockInfo.Begin.set(Slot);
270       } else {
271         if (BlockInfo.Begin.test(Slot)) {
272           // Allocas that start and end within a single block are handled
273           // specially when computing the LiveIntervals to avoid pessimizing
274           // the liveness propagation.
275           BlockInfo.Begin.reset(Slot);
276         } else {
277           BlockInfo.End.set(Slot);
278         }
279       }
280     }
281   }
282 
283   // Update statistics.
284   NumMarkerSeen += MarkersFound;
285   return MarkersFound;
286 }
287 
288 void StackColoring::calculateLocalLiveness() {
289   // Perform a standard reverse dataflow computation to solve for
290   // global liveness.  The BEGIN set here is equivalent to KILL in the standard
291   // formulation, and END is equivalent to GEN.  The result of this computation
292   // is a map from blocks to bitvectors where the bitvectors represent which
293   // allocas are live in/out of that block.
294   SmallPtrSet<const MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
295                                                  BasicBlockNumbering.end());
296   unsigned NumSSMIters = 0;
297   bool changed = true;
298   while (changed) {
299     changed = false;
300     ++NumSSMIters;
301 
302     SmallPtrSet<const MachineBasicBlock*, 8> NextBBSet;
303 
304     for (const MachineBasicBlock *BB : BasicBlockNumbering) {
305       if (!BBSet.count(BB)) continue;
306 
307       // Use an iterator to avoid repeated lookups.
308       LivenessMap::iterator BI = BlockLiveness.find(BB);
309       assert(BI != BlockLiveness.end() && "Block not found");
310       BlockLifetimeInfo &BlockInfo = BI->second;
311 
312       BitVector LocalLiveIn;
313       BitVector LocalLiveOut;
314 
315       // Forward propagation from begins to ends.
316       for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
317            PE = BB->pred_end(); PI != PE; ++PI) {
318         LivenessMap::const_iterator I = BlockLiveness.find(*PI);
319         assert(I != BlockLiveness.end() && "Predecessor not found");
320         LocalLiveIn |= I->second.LiveOut;
321       }
322       LocalLiveIn |= BlockInfo.End;
323       LocalLiveIn.reset(BlockInfo.Begin);
324 
325       // Reverse propagation from ends to begins.
326       for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
327            SE = BB->succ_end(); SI != SE; ++SI) {
328         LivenessMap::const_iterator I = BlockLiveness.find(*SI);
329         assert(I != BlockLiveness.end() && "Successor not found");
330         LocalLiveOut |= I->second.LiveIn;
331       }
332       LocalLiveOut |= BlockInfo.Begin;
333       LocalLiveOut.reset(BlockInfo.End);
334 
335       LocalLiveIn |= LocalLiveOut;
336       LocalLiveOut |= LocalLiveIn;
337 
338       // After adopting the live bits, we need to turn-off the bits which
339       // are de-activated in this block.
340       LocalLiveOut.reset(BlockInfo.End);
341       LocalLiveIn.reset(BlockInfo.Begin);
342 
343       // If we have both BEGIN and END markers in the same basic block then
344       // we know that the BEGIN marker comes after the END, because we already
345       // handle the case where the BEGIN comes before the END when collecting
346       // the markers (and building the BEGIN/END vectore).
347       // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
348       // BEGIN and END because it means that the value lives before and after
349       // this basic block.
350       BitVector LocalEndBegin = BlockInfo.End;
351       LocalEndBegin &= BlockInfo.Begin;
352       LocalLiveIn |= LocalEndBegin;
353       LocalLiveOut |= LocalEndBegin;
354 
355       if (LocalLiveIn.test(BlockInfo.LiveIn)) {
356         changed = true;
357         BlockInfo.LiveIn |= LocalLiveIn;
358 
359         NextBBSet.insert(BB->pred_begin(), BB->pred_end());
360       }
361 
362       if (LocalLiveOut.test(BlockInfo.LiveOut)) {
363         changed = true;
364         BlockInfo.LiveOut |= LocalLiveOut;
365 
366         NextBBSet.insert(BB->succ_begin(), BB->succ_end());
367       }
368     }
369 
370     BBSet = std::move(NextBBSet);
371   }// while changed.
372 }
373 
374 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
375   SmallVector<SlotIndex, 16> Starts;
376   SmallVector<SlotIndex, 16> Finishes;
377 
378   // For each block, find which slots are active within this block
379   // and update the live intervals.
380   for (const MachineBasicBlock &MBB : *MF) {
381     Starts.clear();
382     Starts.resize(NumSlots);
383     Finishes.clear();
384     Finishes.resize(NumSlots);
385 
386     // Create the interval for the basic blocks with lifetime markers in them.
387     for (const MachineInstr *MI : Markers) {
388       if (MI->getParent() != &MBB)
389         continue;
390 
391       assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
392               MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
393              "Invalid Lifetime marker");
394 
395       bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
396       const MachineOperand &Mo = MI->getOperand(0);
397       int Slot = Mo.getIndex();
398       if (Slot < 0)
399         continue;
400 
401       SlotIndex ThisIndex = Indexes->getInstructionIndex(*MI);
402 
403       if (IsStart) {
404         if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
405           Starts[Slot] = ThisIndex;
406       } else {
407         if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
408           Finishes[Slot] = ThisIndex;
409       }
410     }
411 
412     // Create the interval of the blocks that we previously found to be 'alive'.
413     BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
414     for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
415          pos = MBBLiveness.LiveIn.find_next(pos)) {
416       Starts[pos] = Indexes->getMBBStartIdx(&MBB);
417     }
418     for (int pos = MBBLiveness.LiveOut.find_first(); pos != -1;
419          pos = MBBLiveness.LiveOut.find_next(pos)) {
420       Finishes[pos] = Indexes->getMBBEndIdx(&MBB);
421     }
422 
423     for (unsigned i = 0; i < NumSlots; ++i) {
424       assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
425       if (!Starts[i].isValid())
426         continue;
427 
428       assert(Starts[i] && Finishes[i] && "Invalid interval");
429       VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
430       SlotIndex S = Starts[i];
431       SlotIndex F = Finishes[i];
432       if (S < F) {
433         // We have a single consecutive region.
434         Intervals[i]->addSegment(LiveInterval::Segment(S, F, ValNum));
435       } else {
436         // We have two non-consecutive regions. This happens when
437         // LIFETIME_START appears after the LIFETIME_END marker.
438         SlotIndex NewStart = Indexes->getMBBStartIdx(&MBB);
439         SlotIndex NewFin = Indexes->getMBBEndIdx(&MBB);
440         Intervals[i]->addSegment(LiveInterval::Segment(NewStart, F, ValNum));
441         Intervals[i]->addSegment(LiveInterval::Segment(S, NewFin, ValNum));
442       }
443     }
444   }
445 }
446 
447 bool StackColoring::removeAllMarkers() {
448   unsigned Count = 0;
449   for (MachineInstr *MI : Markers) {
450     MI->eraseFromParent();
451     Count++;
452   }
453   Markers.clear();
454 
455   DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
456   return Count;
457 }
458 
459 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
460   unsigned FixedInstr = 0;
461   unsigned FixedMemOp = 0;
462   unsigned FixedDbg = 0;
463   MachineModuleInfo *MMI = &MF->getMMI();
464 
465   // Remap debug information that refers to stack slots.
466   for (auto &VI : MMI->getVariableDbgInfo()) {
467     if (!VI.Var)
468       continue;
469     if (SlotRemap.count(VI.Slot)) {
470       DEBUG(dbgs() << "Remapping debug info for ["
471                    << cast<DILocalVariable>(VI.Var)->getName() << "].\n");
472       VI.Slot = SlotRemap[VI.Slot];
473       FixedDbg++;
474     }
475   }
476 
477   // Keep a list of *allocas* which need to be remapped.
478   DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
479   for (const std::pair<int, int> &SI : SlotRemap) {
480     const AllocaInst *From = MFI->getObjectAllocation(SI.first);
481     const AllocaInst *To = MFI->getObjectAllocation(SI.second);
482     assert(To && From && "Invalid allocation object");
483     Allocas[From] = To;
484 
485     // AA might be used later for instruction scheduling, and we need it to be
486     // able to deduce the correct aliasing releationships between pointers
487     // derived from the alloca being remapped and the target of that remapping.
488     // The only safe way, without directly informing AA about the remapping
489     // somehow, is to directly update the IR to reflect the change being made
490     // here.
491     Instruction *Inst = const_cast<AllocaInst *>(To);
492     if (From->getType() != To->getType()) {
493       BitCastInst *Cast = new BitCastInst(Inst, From->getType());
494       Cast->insertAfter(Inst);
495       Inst = Cast;
496     }
497 
498     // Allow the stack protector to adjust its value map to account for the
499     // upcoming replacement.
500     SP->adjustForColoring(From, To);
501 
502     // The new alloca might not be valid in a llvm.dbg.declare for this
503     // variable, so undef out the use to make the verifier happy.
504     AllocaInst *FromAI = const_cast<AllocaInst *>(From);
505     if (FromAI->isUsedByMetadata())
506       ValueAsMetadata::handleRAUW(FromAI, UndefValue::get(FromAI->getType()));
507     for (auto &Use : FromAI->uses()) {
508       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Use.get()))
509         if (BCI->isUsedByMetadata())
510           ValueAsMetadata::handleRAUW(BCI, UndefValue::get(BCI->getType()));
511     }
512 
513     // Note that this will not replace uses in MMOs (which we'll update below),
514     // or anywhere else (which is why we won't delete the original
515     // instruction).
516     FromAI->replaceAllUsesWith(Inst);
517   }
518 
519   // Remap all instructions to the new stack slots.
520   for (MachineBasicBlock &BB : *MF)
521     for (MachineInstr &I : BB) {
522       // Skip lifetime markers. We'll remove them soon.
523       if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
524           I.getOpcode() == TargetOpcode::LIFETIME_END)
525         continue;
526 
527       // Update the MachineMemOperand to use the new alloca.
528       for (MachineMemOperand *MMO : I.memoperands()) {
529         // FIXME: In order to enable the use of TBAA when using AA in CodeGen,
530         // we'll also need to update the TBAA nodes in MMOs with values
531         // derived from the merged allocas. When doing this, we'll need to use
532         // the same variant of GetUnderlyingObjects that is used by the
533         // instruction scheduler (that can look through ptrtoint/inttoptr
534         // pairs).
535 
536         // We've replaced IR-level uses of the remapped allocas, so we only
537         // need to replace direct uses here.
538         const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
539         if (!AI)
540           continue;
541 
542         if (!Allocas.count(AI))
543           continue;
544 
545         MMO->setValue(Allocas[AI]);
546         FixedMemOp++;
547       }
548 
549       // Update all of the machine instruction operands.
550       for (MachineOperand &MO : I.operands()) {
551         if (!MO.isFI())
552           continue;
553         int FromSlot = MO.getIndex();
554 
555         // Don't touch arguments.
556         if (FromSlot<0)
557           continue;
558 
559         // Only look at mapped slots.
560         if (!SlotRemap.count(FromSlot))
561           continue;
562 
563         // In a debug build, check that the instruction that we are modifying is
564         // inside the expected live range. If the instruction is not inside
565         // the calculated range then it means that the alloca usage moved
566         // outside of the lifetime markers, or that the user has a bug.
567         // NOTE: Alloca address calculations which happen outside the lifetime
568         // zone are are okay, despite the fact that we don't have a good way
569         // for validating all of the usages of the calculation.
570 #ifndef NDEBUG
571         bool TouchesMemory = I.mayLoad() || I.mayStore();
572         // If we *don't* protect the user from escaped allocas, don't bother
573         // validating the instructions.
574         if (!I.isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) {
575           SlotIndex Index = Indexes->getInstructionIndex(I);
576           const LiveInterval *Interval = &*Intervals[FromSlot];
577           assert(Interval->find(Index) != Interval->end() &&
578                  "Found instruction usage outside of live range.");
579         }
580 #endif
581 
582         // Fix the machine instructions.
583         int ToSlot = SlotRemap[FromSlot];
584         MO.setIndex(ToSlot);
585         FixedInstr++;
586       }
587     }
588 
589   // Update the location of C++ catch objects for the MSVC personality routine.
590   if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo())
591     for (WinEHTryBlockMapEntry &TBME : EHInfo->TryBlockMap)
592       for (WinEHHandlerType &H : TBME.HandlerArray)
593         if (H.CatchObj.FrameIndex != INT_MAX &&
594             SlotRemap.count(H.CatchObj.FrameIndex))
595           H.CatchObj.FrameIndex = SlotRemap[H.CatchObj.FrameIndex];
596 
597   DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
598   DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
599   DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
600 }
601 
602 void StackColoring::removeInvalidSlotRanges() {
603   for (MachineBasicBlock &BB : *MF)
604     for (MachineInstr &I : BB) {
605       if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
606           I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugValue())
607         continue;
608 
609       // Some intervals are suspicious! In some cases we find address
610       // calculations outside of the lifetime zone, but not actual memory
611       // read or write. Memory accesses outside of the lifetime zone are a clear
612       // violation, but address calculations are okay. This can happen when
613       // GEPs are hoisted outside of the lifetime zone.
614       // So, in here we only check instructions which can read or write memory.
615       if (!I.mayLoad() && !I.mayStore())
616         continue;
617 
618       // Check all of the machine operands.
619       for (const MachineOperand &MO : I.operands()) {
620         if (!MO.isFI())
621           continue;
622 
623         int Slot = MO.getIndex();
624 
625         if (Slot<0)
626           continue;
627 
628         if (Intervals[Slot]->empty())
629           continue;
630 
631         // Check that the used slot is inside the calculated lifetime range.
632         // If it is not, warn about it and invalidate the range.
633         LiveInterval *Interval = &*Intervals[Slot];
634         SlotIndex Index = Indexes->getInstructionIndex(I);
635         if (Interval->find(Index) == Interval->end()) {
636           Interval->clear();
637           DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
638           EscapedAllocas++;
639         }
640       }
641     }
642 }
643 
644 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
645                                    unsigned NumSlots) {
646   // Expunge slot remap map.
647   for (unsigned i=0; i < NumSlots; ++i) {
648     // If we are remapping i
649     if (SlotRemap.count(i)) {
650       int Target = SlotRemap[i];
651       // As long as our target is mapped to something else, follow it.
652       while (SlotRemap.count(Target)) {
653         Target = SlotRemap[Target];
654         SlotRemap[i] = Target;
655       }
656     }
657   }
658 }
659 
660 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
661   if (skipOptnoneFunction(*Func.getFunction()))
662     return false;
663 
664   DEBUG(dbgs() << "********** Stack Coloring **********\n"
665                << "********** Function: "
666                << ((const Value*)Func.getFunction())->getName() << '\n');
667   MF = &Func;
668   MFI = MF->getFrameInfo();
669   Indexes = &getAnalysis<SlotIndexes>();
670   SP = &getAnalysis<StackProtector>();
671   BlockLiveness.clear();
672   BasicBlocks.clear();
673   BasicBlockNumbering.clear();
674   Markers.clear();
675   Intervals.clear();
676   VNInfoAllocator.Reset();
677 
678   unsigned NumSlots = MFI->getObjectIndexEnd();
679 
680   // If there are no stack slots then there are no markers to remove.
681   if (!NumSlots)
682     return false;
683 
684   SmallVector<int, 8> SortedSlots;
685 
686   SortedSlots.reserve(NumSlots);
687   Intervals.reserve(NumSlots);
688 
689   unsigned NumMarkers = collectMarkers(NumSlots);
690 
691   unsigned TotalSize = 0;
692   DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
693   DEBUG(dbgs()<<"Slot structure:\n");
694 
695   for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
696     DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
697     TotalSize += MFI->getObjectSize(i);
698   }
699 
700   DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
701 
702   // Don't continue because there are not enough lifetime markers, or the
703   // stack is too small, or we are told not to optimize the slots.
704   if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
705     DEBUG(dbgs()<<"Will not try to merge slots.\n");
706     return removeAllMarkers();
707   }
708 
709   for (unsigned i=0; i < NumSlots; ++i) {
710     std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0));
711     LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
712     Intervals.push_back(std::move(LI));
713     SortedSlots.push_back(i);
714   }
715 
716   // Calculate the liveness of each block.
717   calculateLocalLiveness();
718 
719   // Propagate the liveness information.
720   calculateLiveIntervals(NumSlots);
721 
722   // Search for allocas which are used outside of the declared lifetime
723   // markers.
724   if (ProtectFromEscapedAllocas)
725     removeInvalidSlotRanges();
726 
727   // Maps old slots to new slots.
728   DenseMap<int, int> SlotRemap;
729   unsigned RemovedSlots = 0;
730   unsigned ReducedSize = 0;
731 
732   // Do not bother looking at empty intervals.
733   for (unsigned I = 0; I < NumSlots; ++I) {
734     if (Intervals[SortedSlots[I]]->empty())
735       SortedSlots[I] = -1;
736   }
737 
738   // This is a simple greedy algorithm for merging allocas. First, sort the
739   // slots, placing the largest slots first. Next, perform an n^2 scan and look
740   // for disjoint slots. When you find disjoint slots, merge the samller one
741   // into the bigger one and update the live interval. Remove the small alloca
742   // and continue.
743 
744   // Sort the slots according to their size. Place unused slots at the end.
745   // Use stable sort to guarantee deterministic code generation.
746   std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
747                    [this](int LHS, int RHS) {
748     // We use -1 to denote a uninteresting slot. Place these slots at the end.
749     if (LHS == -1) return false;
750     if (RHS == -1) return true;
751     // Sort according to size.
752     return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
753   });
754 
755   bool Changed = true;
756   while (Changed) {
757     Changed = false;
758     for (unsigned I = 0; I < NumSlots; ++I) {
759       if (SortedSlots[I] == -1)
760         continue;
761 
762       for (unsigned J=I+1; J < NumSlots; ++J) {
763         if (SortedSlots[J] == -1)
764           continue;
765 
766         int FirstSlot = SortedSlots[I];
767         int SecondSlot = SortedSlots[J];
768         LiveInterval *First = &*Intervals[FirstSlot];
769         LiveInterval *Second = &*Intervals[SecondSlot];
770         assert (!First->empty() && !Second->empty() && "Found an empty range");
771 
772         // Merge disjoint slots.
773         if (!First->overlaps(*Second)) {
774           Changed = true;
775           First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
776           SlotRemap[SecondSlot] = FirstSlot;
777           SortedSlots[J] = -1;
778           DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
779                 SecondSlot<<" together.\n");
780           unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
781                                            MFI->getObjectAlignment(SecondSlot));
782 
783           assert(MFI->getObjectSize(FirstSlot) >=
784                  MFI->getObjectSize(SecondSlot) &&
785                  "Merging a small object into a larger one");
786 
787           RemovedSlots+=1;
788           ReducedSize += MFI->getObjectSize(SecondSlot);
789           MFI->setObjectAlignment(FirstSlot, MaxAlignment);
790           MFI->RemoveStackObject(SecondSlot);
791         }
792       }
793     }
794   }// While changed.
795 
796   // Record statistics.
797   StackSpaceSaved += ReducedSize;
798   StackSlotMerged += RemovedSlots;
799   DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
800         ReducedSize<<" bytes\n");
801 
802   // Scan the entire function and update all machine operands that use frame
803   // indices to use the remapped frame index.
804   expungeSlotMap(SlotRemap, NumSlots);
805   remapInstructions(SlotRemap);
806 
807   return removeAllMarkers();
808 }
809