1 //===------ LiveDebugValues.cpp - Tracking Debug Value MIs ----------------===//
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 a data flow analysis that propagates debug location
11 /// information by inserting additional DBG_VALUE instructions into the machine
12 /// instruction stream. The pass internally builds debug location liveness
13 /// ranges to determine the points where additional DBG_VALUEs need to be
14 /// inserted.
15 ///
16 /// This is a separate pass from DbgValueHistoryCalculator to facilitate
17 /// testing and improve modularity.
18 ///
19 //===----------------------------------------------------------------------===//
20 
21 #include "llvm/ADT/PostOrderIterator.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SparseBitVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/UniqueVector.h"
26 #include "llvm/CodeGen/LexicalScopes.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <list>
42 #include <queue>
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "livedebugvalues"
47 
48 STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
49 
50 namespace {
51 
52 // \brief If @MI is a DBG_VALUE with debug value described by a defined
53 // register, returns the number of this register. In the other case, returns 0.
54 static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) {
55   assert(MI.isDebugValue() && "expected a DBG_VALUE");
56   assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
57   // If location of variable is described using a register (directly
58   // or indirectly), this register is always a first operand.
59   return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
60 }
61 
62 class LiveDebugValues : public MachineFunctionPass {
63 
64 private:
65   const TargetRegisterInfo *TRI;
66   const TargetInstrInfo *TII;
67   const TargetFrameLowering *TFI;
68   LexicalScopes LS;
69 
70   /// Keeps track of lexical scopes associated with a user value's source
71   /// location.
72   class UserValueScopes {
73     DebugLoc DL;
74     LexicalScopes &LS;
75     SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
76 
77   public:
78     UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
79 
80     /// Return true if current scope dominates at least one machine
81     /// instruction in a given machine basic block.
82     bool dominates(MachineBasicBlock *MBB) {
83       if (LBlocks.empty())
84         LS.getMachineBasicBlocks(DL, LBlocks);
85       return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
86     }
87   };
88 
89   /// Based on std::pair so it can be used as an index into a DenseMap.
90   typedef std::pair<const DILocalVariable *, const DILocation *>
91       DebugVariableBase;
92   /// A potentially inlined instance of a variable.
93   struct DebugVariable : public DebugVariableBase {
94     DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt)
95         : DebugVariableBase(Var, InlinedAt) {}
96 
97     const DILocalVariable *getVar() const { return this->first; };
98     const DILocation *getInlinedAt() const { return this->second; };
99 
100     bool operator<(const DebugVariable &DV) const {
101       if (getVar() == DV.getVar())
102         return getInlinedAt() < DV.getInlinedAt();
103       return getVar() < DV.getVar();
104     }
105   };
106 
107   /// A pair of debug variable and value location.
108   struct VarLoc {
109     const DebugVariable Var;
110     const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
111     mutable UserValueScopes UVS;
112     enum { InvalidKind = 0, RegisterKind } Kind;
113 
114     /// The value location. Stored separately to avoid repeatedly
115     /// extracting it from MI.
116     union {
117       struct {
118         uint32_t RegNo;
119         uint32_t Offset;
120       } RegisterLoc;
121       uint64_t Hash;
122     } Loc;
123 
124     VarLoc(const MachineInstr &MI, LexicalScopes &LS)
125         : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
126           UVS(MI.getDebugLoc(), LS), Kind(InvalidKind) {
127       static_assert((sizeof(Loc) == sizeof(uint64_t)),
128                     "hash does not cover all members of Loc");
129       assert(MI.isDebugValue() && "not a DBG_VALUE");
130       assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
131       if (int RegNo = isDbgValueDescribedByReg(MI)) {
132         Kind = RegisterKind;
133         Loc.RegisterLoc.RegNo = RegNo;
134         int64_t Offset =
135             MI.isIndirectDebugValue() ? MI.getOperand(1).getImm() : 0;
136         // We don't support offsets larger than 4GiB here. They are
137         // slated to be replaced with DIExpressions anyway.
138         // With indirect debug values used for spill locations, Offset
139         // can be negative.
140         if (Offset == INT64_MIN || std::abs(Offset) >= (1LL << 32))
141           Kind = InvalidKind;
142         else
143           Loc.RegisterLoc.Offset = Offset;
144       }
145     }
146 
147     /// If this variable is described by a register, return it,
148     /// otherwise return 0.
149     unsigned isDescribedByReg() const {
150       if (Kind == RegisterKind)
151         return Loc.RegisterLoc.RegNo;
152       return 0;
153     }
154 
155     /// Determine whether the lexical scope of this value's debug location
156     /// dominates MBB.
157     bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
158 
159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160     LLVM_DUMP_METHOD void dump() const { MI.dump(); }
161 #endif
162 
163     bool operator==(const VarLoc &Other) const {
164       return Var == Other.Var && Loc.Hash == Other.Loc.Hash;
165     }
166 
167     /// This operator guarantees that VarLocs are sorted by Variable first.
168     bool operator<(const VarLoc &Other) const {
169       if (Var == Other.Var)
170         return Loc.Hash < Other.Loc.Hash;
171       return Var < Other.Var;
172     }
173   };
174 
175   typedef UniqueVector<VarLoc> VarLocMap;
176   typedef SparseBitVector<> VarLocSet;
177   typedef SmallDenseMap<const MachineBasicBlock *, VarLocSet> VarLocInMBB;
178   struct SpillDebugPair {
179     MachineInstr *SpillInst;
180     MachineInstr *DebugInst;
181   };
182   typedef SmallVector<SpillDebugPair, 4> SpillMap;
183 
184   /// This holds the working set of currently open ranges. For fast
185   /// access, this is done both as a set of VarLocIDs, and a map of
186   /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
187   /// previous open ranges for the same variable.
188   class OpenRangesSet {
189     VarLocSet VarLocs;
190     SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
191 
192   public:
193     const VarLocSet &getVarLocs() const { return VarLocs; }
194 
195     /// Terminate all open ranges for Var by removing it from the set.
196     void erase(DebugVariable Var) {
197       auto It = Vars.find(Var);
198       if (It != Vars.end()) {
199         unsigned ID = It->second;
200         VarLocs.reset(ID);
201         Vars.erase(It);
202       }
203     }
204 
205     /// Terminate all open ranges listed in \c KillSet by removing
206     /// them from the set.
207     void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
208       VarLocs.intersectWithComplement(KillSet);
209       for (unsigned ID : KillSet)
210         Vars.erase(VarLocIDs[ID].Var);
211     }
212 
213     /// Insert a new range into the set.
214     void insert(unsigned VarLocID, DebugVariableBase Var) {
215       VarLocs.set(VarLocID);
216       Vars.insert({Var, VarLocID});
217     }
218 
219     /// Empty the set.
220     void clear() {
221       VarLocs.clear();
222       Vars.clear();
223     }
224 
225     /// Return whether the set is empty or not.
226     bool empty() const {
227       assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
228       return VarLocs.empty();
229     }
230   };
231 
232   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF,
233                           unsigned &Reg);
234   int extractSpillBaseRegAndOffset(const MachineInstr &MI, unsigned &Reg);
235 
236   void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
237                           VarLocMap &VarLocIDs);
238   void transferSpillInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
239                          VarLocMap &VarLocIDs, SpillMap &Spills);
240   void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
241                            const VarLocMap &VarLocIDs);
242   bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
243                               VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
244   bool transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
245                 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs, SpillMap &Spills,
246                 bool transferSpills);
247 
248   bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
249             const VarLocMap &VarLocIDs,
250             SmallPtrSet<const MachineBasicBlock *, 16> &Visited);
251 
252   bool ExtendRanges(MachineFunction &MF);
253 
254 public:
255   static char ID;
256 
257   /// Default construct and initialize the pass.
258   LiveDebugValues();
259 
260   /// Tell the pass manager which passes we depend on and what
261   /// information we preserve.
262   void getAnalysisUsage(AnalysisUsage &AU) const override;
263 
264   MachineFunctionProperties getRequiredProperties() const override {
265     return MachineFunctionProperties().set(
266         MachineFunctionProperties::Property::NoVRegs);
267   }
268 
269   /// Print to ostream with a message.
270   void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
271                         const VarLocMap &VarLocIDs, const char *msg,
272                         raw_ostream &Out) const;
273 
274   /// Calculate the liveness information for the given machine function.
275   bool runOnMachineFunction(MachineFunction &MF) override;
276 };
277 
278 } // namespace
279 
280 //===----------------------------------------------------------------------===//
281 //            Implementation
282 //===----------------------------------------------------------------------===//
283 
284 char LiveDebugValues::ID = 0;
285 char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
286 INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
287                 false, false)
288 
289 /// Default construct and initialize the pass.
290 LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
291   initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
292 }
293 
294 /// Tell the pass manager which passes we depend on and what information we
295 /// preserve.
296 void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
297   AU.setPreservesCFG();
298   MachineFunctionPass::getAnalysisUsage(AU);
299 }
300 
301 //===----------------------------------------------------------------------===//
302 //            Debug Range Extension Implementation
303 //===----------------------------------------------------------------------===//
304 
305 #ifndef NDEBUG
306 void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
307                                        const VarLocInMBB &V,
308                                        const VarLocMap &VarLocIDs,
309                                        const char *msg,
310                                        raw_ostream &Out) const {
311   Out << '\n' << msg << '\n';
312   for (const MachineBasicBlock &BB : MF) {
313     const auto &L = V.lookup(&BB);
314     Out << "MBB: " << BB.getName() << ":\n";
315     for (unsigned VLL : L) {
316       const VarLoc &VL = VarLocIDs[VLL];
317       Out << " Var: " << VL.Var.getVar()->getName();
318       Out << " MI: ";
319       VL.dump();
320     }
321   }
322   Out << "\n";
323 }
324 #endif
325 
326 /// Given a spill instruction, extract the register and offset used to
327 /// address the spill location in a target independent way.
328 int LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI,
329                                                   unsigned &Reg) {
330   assert(MI.hasOneMemOperand() &&
331          "Spill instruction does not have exactly one memory operand?");
332   auto MMOI = MI.memoperands_begin();
333   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
334   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
335          "Inconsistent memory operand in spill instruction");
336   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
337   const MachineBasicBlock *MBB = MI.getParent();
338   return TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
339 }
340 
341 /// End all previous ranges related to @MI and start a new range from @MI
342 /// if it is a DBG_VALUE instr.
343 void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
344                                          OpenRangesSet &OpenRanges,
345                                          VarLocMap &VarLocIDs) {
346   if (!MI.isDebugValue())
347     return;
348   const DILocalVariable *Var = MI.getDebugVariable();
349   const DILocation *DebugLoc = MI.getDebugLoc();
350   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
351   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
352          "Expected inlined-at fields to agree");
353 
354   // End all previous ranges of Var.
355   DebugVariable V(Var, InlinedAt);
356   OpenRanges.erase(V);
357 
358   // Add the VarLoc to OpenRanges from this DBG_VALUE.
359   // TODO: Currently handles DBG_VALUE which has only reg as location.
360   if (isDbgValueDescribedByReg(MI)) {
361     VarLoc VL(MI, LS);
362     unsigned ID = VarLocIDs.insert(VL);
363     OpenRanges.insert(ID, VL.Var);
364   }
365 }
366 
367 /// A definition of a register may mark the end of a range.
368 void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
369                                           OpenRangesSet &OpenRanges,
370                                           const VarLocMap &VarLocIDs) {
371   MachineFunction *MF = MI.getParent()->getParent();
372   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
373   unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
374   SparseBitVector<> KillSet;
375   for (const MachineOperand &MO : MI.operands()) {
376     // Determine whether the operand is a register def.  Assume that call
377     // instructions never clobber SP, because some backends (e.g., AArch64)
378     // never list SP in the regmask.
379     if (MO.isReg() && MO.isDef() && MO.getReg() &&
380         TRI->isPhysicalRegister(MO.getReg()) &&
381         !(MI.isCall() && MO.getReg() == SP)) {
382       // Remove ranges of all aliased registers.
383       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
384         for (unsigned ID : OpenRanges.getVarLocs())
385           if (VarLocIDs[ID].isDescribedByReg() == *RAI)
386             KillSet.set(ID);
387     } else if (MO.isRegMask()) {
388       // Remove ranges of all clobbered registers. Register masks don't usually
389       // list SP as preserved.  While the debug info may be off for an
390       // instruction or two around callee-cleanup calls, transferring the
391       // DEBUG_VALUE across the call is still a better user experience.
392       for (unsigned ID : OpenRanges.getVarLocs()) {
393         unsigned Reg = VarLocIDs[ID].isDescribedByReg();
394         if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
395           KillSet.set(ID);
396       }
397     }
398   }
399   OpenRanges.erase(KillSet, VarLocIDs);
400 }
401 
402 /// Decide if @MI is a spill instruction and return true if it is. We use 2
403 /// criteria to make this decision:
404 /// - Is this instruction a store to a spill slot?
405 /// - Is there a register operand that is both used and killed?
406 /// TODO: Store optimization can fold spills into other stores (including
407 /// other spills). We do not handle this yet (more than one memory operand).
408 bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
409                                          MachineFunction *MF, unsigned &Reg) {
410   const MachineFrameInfo &FrameInfo = MF->getFrameInfo();
411   int FI;
412   const MachineMemOperand *MMO;
413 
414   // TODO: Handle multiple stores folded into one.
415   if (!MI.hasOneMemOperand())
416     return false;
417 
418   // To identify a spill instruction, use the same criteria as in AsmPrinter.
419   if (!((TII->isStoreToStackSlotPostFE(MI, FI) ||
420          TII->hasStoreToStackSlot(MI, MMO, FI)) &&
421         FrameInfo.isSpillSlotObjectIndex(FI)))
422     return false;
423 
424   // In a spill instruction generated by the InlineSpiller the spilled register
425   // has its kill flag set. Return false if we don't find such a register.
426   Reg = 0;
427   for (const MachineOperand &MO : MI.operands()) {
428     if (MO.isReg() && MO.isUse() && MO.isKill()) {
429       Reg = MO.getReg();
430       break;
431     }
432   }
433   return Reg != 0;
434 }
435 
436 /// A spilled register may indicate that we have to end the current range of
437 /// a variable and create a new one for the spill location.
438 /// We don't want to insert any instructions in transfer(), so we just create
439 /// the DBG_VALUE witout inserting it and keep track of it in @Spills.
440 /// It will be inserted into the BB when we're done iterating over the
441 /// instructions.
442 void LiveDebugValues::transferSpillInst(MachineInstr &MI,
443                                         OpenRangesSet &OpenRanges,
444                                         VarLocMap &VarLocIDs,
445                                         SpillMap &Spills) {
446   unsigned Reg;
447   MachineFunction *MF = MI.getParent()->getParent();
448   if (!isSpillInstruction(MI, MF, Reg))
449     return;
450 
451   // Check if the register is the location of a debug value.
452   for (unsigned ID : OpenRanges.getVarLocs()) {
453     if (VarLocIDs[ID].isDescribedByReg() == Reg) {
454       DEBUG(dbgs() << "Spilling Register " << PrintReg(Reg, TRI) << '('
455                    << VarLocIDs[ID].Var.getVar()->getName() << ")\n");
456 
457       // Create a DBG_VALUE instruction to describe the Var in its spilled
458       // location, but don't insert it yet to avoid invalidating the
459       // iterator in our caller.
460       unsigned SpillBase;
461       int SpillOffset = extractSpillBaseRegAndOffset(MI, SpillBase);
462       const MachineInstr *DMI = &VarLocIDs[ID].MI;
463       MachineInstr *SpDMI =
464           BuildMI(*MF, DMI->getDebugLoc(), DMI->getDesc(), true, SpillBase, 0,
465                   DMI->getDebugVariable(), DMI->getDebugExpression());
466       SpDMI->getOperand(1).setImm(SpillOffset);
467       DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
468             SpDMI->print(dbgs(), false, TII));
469 
470       // The newly created DBG_VALUE instruction SpDMI must be inserted after
471       // MI. Keep track of the pairing.
472       SpillDebugPair MIP = {&MI, SpDMI};
473       Spills.push_back(MIP);
474 
475       // End all previous ranges of Var.
476       OpenRanges.erase(VarLocIDs[ID].Var);
477 
478       // Add the VarLoc to OpenRanges.
479       VarLoc VL(*SpDMI, LS);
480       unsigned SpillLocID = VarLocIDs.insert(VL);
481       OpenRanges.insert(SpillLocID, VL.Var);
482       return;
483     }
484   }
485 }
486 
487 /// Terminate all open ranges at the end of the current basic block.
488 bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
489                                              OpenRangesSet &OpenRanges,
490                                              VarLocInMBB &OutLocs,
491                                              const VarLocMap &VarLocIDs) {
492   bool Changed = false;
493   const MachineBasicBlock *CurMBB = MI.getParent();
494   if (!(MI.isTerminator() || (&MI == &CurMBB->instr_back())))
495     return false;
496 
497   if (OpenRanges.empty())
498     return false;
499 
500   DEBUG(for (unsigned ID : OpenRanges.getVarLocs()) {
501           // Copy OpenRanges to OutLocs, if not already present.
502           dbgs() << "Add to OutLocs: "; VarLocIDs[ID].dump();
503         });
504   VarLocSet &VLS = OutLocs[CurMBB];
505   Changed = VLS |= OpenRanges.getVarLocs();
506   OpenRanges.clear();
507   return Changed;
508 }
509 
510 /// This routine creates OpenRanges and OutLocs.
511 bool LiveDebugValues::transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
512                                VarLocInMBB &OutLocs, VarLocMap &VarLocIDs,
513                                SpillMap &Spills, bool transferSpills) {
514   bool Changed = false;
515   transferDebugValue(MI, OpenRanges, VarLocIDs);
516   transferRegisterDef(MI, OpenRanges, VarLocIDs);
517   if (transferSpills)
518     transferSpillInst(MI, OpenRanges, VarLocIDs, Spills);
519   Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
520   return Changed;
521 }
522 
523 /// This routine joins the analysis results of all incoming edges in @MBB by
524 /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
525 /// source variable in all the predecessors of @MBB reside in the same location.
526 bool LiveDebugValues::join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs,
527                            VarLocInMBB &InLocs, const VarLocMap &VarLocIDs,
528                            SmallPtrSet<const MachineBasicBlock *, 16> &Visited) {
529   DEBUG(dbgs() << "join MBB: " << MBB.getName() << "\n");
530   bool Changed = false;
531 
532   VarLocSet InLocsT; // Temporary incoming locations.
533 
534   // For all predecessors of this MBB, find the set of VarLocs that
535   // can be joined.
536   int NumVisited = 0;
537   for (auto p : MBB.predecessors()) {
538     // Ignore unvisited predecessor blocks.  As we are processing
539     // the blocks in reverse post-order any unvisited block can
540     // be considered to not remove any incoming values.
541     if (!Visited.count(p))
542       continue;
543     auto OL = OutLocs.find(p);
544     // Join is null in case of empty OutLocs from any of the pred.
545     if (OL == OutLocs.end())
546       return false;
547 
548     // Just copy over the Out locs to incoming locs for the first visited
549     // predecessor, and for all other predecessors join the Out locs.
550     if (!NumVisited)
551       InLocsT = OL->second;
552     else
553       InLocsT &= OL->second;
554     NumVisited++;
555   }
556 
557   // Filter out DBG_VALUES that are out of scope.
558   VarLocSet KillSet;
559   for (auto ID : InLocsT)
560     if (!VarLocIDs[ID].dominates(MBB))
561       KillSet.set(ID);
562   InLocsT.intersectWithComplement(KillSet);
563 
564   // As we are processing blocks in reverse post-order we
565   // should have processed at least one predecessor, unless it
566   // is the entry block which has no predecessor.
567   assert((NumVisited || MBB.pred_empty()) &&
568          "Should have processed at least one predecessor");
569   if (InLocsT.empty())
570     return false;
571 
572   VarLocSet &ILS = InLocs[&MBB];
573 
574   // Insert DBG_VALUE instructions, if not already inserted.
575   VarLocSet Diff = InLocsT;
576   Diff.intersectWithComplement(ILS);
577   for (auto ID : Diff) {
578     // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
579     // new range is started for the var from the mbb's beginning by inserting
580     // a new DBG_VALUE. transfer() will end this range however appropriate.
581     const VarLoc &DiffIt = VarLocIDs[ID];
582     const MachineInstr *DMI = &DiffIt.MI;
583     MachineInstr *MI =
584         BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
585                 DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(), 0,
586                 DMI->getDebugVariable(), DMI->getDebugExpression());
587     if (DMI->isIndirectDebugValue())
588       MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
589     DEBUG(dbgs() << "Inserted: "; MI->dump(););
590     ILS.set(ID);
591     ++NumInserted;
592     Changed = true;
593   }
594   return Changed;
595 }
596 
597 /// Calculate the liveness information for the given machine function and
598 /// extend ranges across basic blocks.
599 bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
600 
601   DEBUG(dbgs() << "\nDebug Range Extension\n");
602 
603   bool Changed = false;
604   bool OLChanged = false;
605   bool MBBJoined = false;
606 
607   VarLocMap VarLocIDs;      // Map VarLoc<>unique ID for use in bitvectors.
608   OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
609   VarLocInMBB OutLocs;      // Ranges that exist beyond bb.
610   VarLocInMBB InLocs;       // Ranges that are incoming after joining.
611   SpillMap Spills;          // DBG_VALUEs associated with spills.
612 
613   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
614   DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
615   std::priority_queue<unsigned int, std::vector<unsigned int>,
616                       std::greater<unsigned int>>
617       Worklist;
618   std::priority_queue<unsigned int, std::vector<unsigned int>,
619                       std::greater<unsigned int>>
620       Pending;
621 
622   // Initialize every mbb with OutLocs.
623   // We are not looking at any spill instructions during the initial pass
624   // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
625   // instructions for spills of registers that are known to be user variables
626   // within the BB in which the spill occurs.
627   for (auto &MBB : MF)
628     for (auto &MI : MBB)
629       transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
630                /*transferSpills=*/false);
631 
632   DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "OutLocs after initialization",
633                          dbgs()));
634 
635   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
636   unsigned int RPONumber = 0;
637   for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
638     OrderToBB[RPONumber] = *RI;
639     BBToOrder[*RI] = RPONumber;
640     Worklist.push(RPONumber);
641     ++RPONumber;
642   }
643   // This is a standard "union of predecessor outs" dataflow problem.
644   // To solve it, we perform join() and transfer() using the two worklist method
645   // until the ranges converge.
646   // Ranges have converged when both worklists are empty.
647   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
648   while (!Worklist.empty() || !Pending.empty()) {
649     // We track what is on the pending worklist to avoid inserting the same
650     // thing twice.  We could avoid this with a custom priority queue, but this
651     // is probably not worth it.
652     SmallPtrSet<MachineBasicBlock *, 16> OnPending;
653     DEBUG(dbgs() << "Processing Worklist\n");
654     while (!Worklist.empty()) {
655       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
656       Worklist.pop();
657       MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited);
658       Visited.insert(MBB);
659       if (MBBJoined) {
660         MBBJoined = false;
661         Changed = true;
662         // Now that we have started to extend ranges across BBs we need to
663         // examine spill instructions to see whether they spill registers that
664         // correspond to user variables.
665         for (auto &MI : *MBB)
666           OLChanged |= transfer(MI, OpenRanges, OutLocs, VarLocIDs, Spills,
667                                 /*transferSpills=*/true);
668 
669         // Add any DBG_VALUE instructions necessitated by spills.
670         for (auto &SP : Spills)
671           MBB->insertAfter(MachineBasicBlock::iterator(*SP.SpillInst),
672                            SP.DebugInst);
673         Spills.clear();
674 
675         DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
676                                "OutLocs after propagating", dbgs()));
677         DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
678                                "InLocs after propagating", dbgs()));
679 
680         if (OLChanged) {
681           OLChanged = false;
682           for (auto s : MBB->successors())
683             if (OnPending.insert(s).second) {
684               Pending.push(BBToOrder[s]);
685             }
686         }
687       }
688     }
689     Worklist.swap(Pending);
690     // At this point, pending must be empty, since it was just the empty
691     // worklist
692     assert(Pending.empty() && "Pending should be empty");
693   }
694 
695   DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
696   DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
697   return Changed;
698 }
699 
700 bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
701   if (!MF.getFunction()->getSubprogram())
702     // LiveDebugValues will already have removed all DBG_VALUEs.
703     return false;
704 
705   TRI = MF.getSubtarget().getRegisterInfo();
706   TII = MF.getSubtarget().getInstrInfo();
707   TFI = MF.getSubtarget().getFrameLowering();
708   LS.initialize(MF);
709 
710   bool Changed = ExtendRanges(MF);
711   return Changed;
712 }
713