1 //===- llvm/CodeGen/AsmPrinter/DbgEntityHistoryCalculator.cpp -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/CodeGen/DbgEntityHistoryCalculator.h"
10 #include "llvm/ADT/BitVector.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/CodeGen/MachineBasicBlock.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineOperand.h"
17 #include "llvm/CodeGen/TargetLowering.h"
18 #include "llvm/CodeGen/TargetRegisterInfo.h"
19 #include "llvm/CodeGen/TargetSubtargetInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DebugLoc.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <cassert>
26 #include <map>
27 #include <utility>
28 
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "dwarfdebug"
32 
33 // If @MI is a DBG_VALUE with debug value described by a
34 // defined register, returns the number of this register.
35 // In the other case, returns 0.
36 static unsigned isDescribedByReg(const MachineInstr &MI) {
37   assert(MI.isDebugValue());
38   assert(MI.getNumOperands() == 4);
39   // If location of variable is described using a register (directly or
40   // indirectly), this register is always a first operand.
41   return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
42 }
43 
44 void DbgValueHistoryMap::startInstrRange(InlinedEntity Var,
45                                          const MachineInstr &MI) {
46   // Instruction range should start with a DBG_VALUE instruction for the
47   // variable.
48   assert(MI.isDebugValue() && "not a DBG_VALUE");
49   auto &Ranges = VarInstrRanges[Var];
50   if (!Ranges.empty() && Ranges.back().second == nullptr &&
51       Ranges.back().first->isIdenticalTo(MI)) {
52     LLVM_DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
53                       << "\t" << Ranges.back().first << "\t" << MI << "\n");
54     return;
55   }
56   Ranges.push_back(std::make_pair(&MI, nullptr));
57 }
58 
59 void DbgValueHistoryMap::endInstrRange(InlinedEntity Var,
60                                        const MachineInstr &MI) {
61   auto &Ranges = VarInstrRanges[Var];
62   // Verify that the current instruction range is not yet closed.
63   assert(!Ranges.empty() && Ranges.back().second == nullptr);
64   // For now, instruction ranges are not allowed to cross basic block
65   // boundaries.
66   assert(Ranges.back().first->getParent() == MI.getParent());
67   Ranges.back().second = &MI;
68 }
69 
70 unsigned DbgValueHistoryMap::getRegisterForVar(InlinedEntity Var) const {
71   const auto &I = VarInstrRanges.find(Var);
72   if (I == VarInstrRanges.end())
73     return 0;
74   const auto &Ranges = I->second;
75   if (Ranges.empty() || Ranges.back().second != nullptr)
76     return 0;
77   return isDescribedByReg(*Ranges.back().first);
78 }
79 
80 void DbgLabelInstrMap::addInstr(InlinedEntity Label, const MachineInstr &MI) {
81   assert(MI.isDebugLabel() && "not a DBG_LABEL");
82   LabelInstr[Label] = &MI;
83 }
84 
85 namespace {
86 
87 // Maps physreg numbers to the variables they describe.
88 using InlinedEntity = DbgValueHistoryMap::InlinedEntity;
89 using RegDescribedVarsMap = std::map<unsigned, SmallVector<InlinedEntity, 1>>;
90 
91 } // end anonymous namespace
92 
93 // Claim that @Var is not described by @RegNo anymore.
94 static void dropRegDescribedVar(RegDescribedVarsMap &RegVars, unsigned RegNo,
95                                 InlinedEntity Var) {
96   const auto &I = RegVars.find(RegNo);
97   assert(RegNo != 0U && I != RegVars.end());
98   auto &VarSet = I->second;
99   const auto &VarPos = llvm::find(VarSet, Var);
100   assert(VarPos != VarSet.end());
101   VarSet.erase(VarPos);
102   // Don't keep empty sets in a map to keep it as small as possible.
103   if (VarSet.empty())
104     RegVars.erase(I);
105 }
106 
107 // Claim that @Var is now described by @RegNo.
108 static void addRegDescribedVar(RegDescribedVarsMap &RegVars, unsigned RegNo,
109                                InlinedEntity Var) {
110   assert(RegNo != 0U);
111   auto &VarSet = RegVars[RegNo];
112   assert(!is_contained(VarSet, Var));
113   VarSet.push_back(Var);
114 }
115 
116 // Terminate the location range for variables described by register at
117 // @I by inserting @ClobberingInstr to their history.
118 static void clobberRegisterUses(RegDescribedVarsMap &RegVars,
119                                 RegDescribedVarsMap::iterator I,
120                                 DbgValueHistoryMap &HistMap,
121                                 const MachineInstr &ClobberingInstr) {
122   // Iterate over all variables described by this register and add this
123   // instruction to their history, clobbering it.
124   for (const auto &Var : I->second)
125     HistMap.endInstrRange(Var, ClobberingInstr);
126   RegVars.erase(I);
127 }
128 
129 // Terminate the location range for variables described by register
130 // @RegNo by inserting @ClobberingInstr to their history.
131 static void clobberRegisterUses(RegDescribedVarsMap &RegVars, unsigned RegNo,
132                                 DbgValueHistoryMap &HistMap,
133                                 const MachineInstr &ClobberingInstr) {
134   const auto &I = RegVars.find(RegNo);
135   if (I == RegVars.end())
136     return;
137   clobberRegisterUses(RegVars, I, HistMap, ClobberingInstr);
138 }
139 
140 // Returns the first instruction in @MBB which corresponds to
141 // the function epilogue, or nullptr if @MBB doesn't contain an epilogue.
142 static const MachineInstr *getFirstEpilogueInst(const MachineBasicBlock &MBB) {
143   auto LastMI = MBB.getLastNonDebugInstr();
144   if (LastMI == MBB.end() || !LastMI->isReturn())
145     return nullptr;
146   // Assume that epilogue starts with instruction having the same debug location
147   // as the return instruction.
148   DebugLoc LastLoc = LastMI->getDebugLoc();
149   auto Res = LastMI;
150   for (MachineBasicBlock::const_reverse_iterator I = LastMI.getReverse(),
151                                                  E = MBB.rend();
152        I != E; ++I) {
153     if (I->getDebugLoc() != LastLoc)
154       return &*Res;
155     Res = &*I;
156   }
157   // If all instructions have the same debug location, assume whole MBB is
158   // an epilogue.
159   return &*MBB.begin();
160 }
161 
162 // Collect registers that are modified in the function body (their
163 // contents is changed outside of the prologue and epilogue).
164 static void collectChangingRegs(const MachineFunction *MF,
165                                 const TargetRegisterInfo *TRI,
166                                 BitVector &Regs) {
167   for (const auto &MBB : *MF) {
168     auto FirstEpilogueInst = getFirstEpilogueInst(MBB);
169 
170     for (const auto &MI : MBB) {
171       // Avoid looking at prologue or epilogue instructions.
172       if (&MI == FirstEpilogueInst)
173         break;
174       if (MI.getFlag(MachineInstr::FrameSetup))
175         continue;
176 
177       // Look for register defs and register masks. Register masks are
178       // typically on calls and they clobber everything not in the mask.
179       for (const MachineOperand &MO : MI.operands()) {
180         // Skip virtual registers since they are handled by the parent.
181         if (MO.isReg() && MO.isDef() && MO.getReg() &&
182             !TRI->isVirtualRegister(MO.getReg())) {
183           for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
184                ++AI)
185             Regs.set(*AI);
186         } else if (MO.isRegMask()) {
187           Regs.setBitsNotInMask(MO.getRegMask());
188         }
189       }
190     }
191   }
192 }
193 
194 void llvm::calculateDbgEntityHistory(const MachineFunction *MF,
195                                      const TargetRegisterInfo *TRI,
196                                      DbgValueHistoryMap &DbgValues,
197                                      DbgLabelInstrMap &DbgLabels) {
198   BitVector ChangingRegs(TRI->getNumRegs());
199   collectChangingRegs(MF, TRI, ChangingRegs);
200 
201   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
202   unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
203   RegDescribedVarsMap RegVars;
204   for (const auto &MBB : *MF) {
205     for (const auto &MI : MBB) {
206       if (!MI.isDebugInstr()) {
207         // Not a DBG_VALUE instruction. It may clobber registers which describe
208         // some variables.
209         for (const MachineOperand &MO : MI.operands()) {
210           if (MO.isReg() && MO.isDef() && MO.getReg()) {
211             // Ignore call instructions that claim to clobber SP. The AArch64
212             // backend does this for aggregate function arguments.
213             if (MI.isCall() && MO.getReg() == SP)
214               continue;
215             // If this is a virtual register, only clobber it since it doesn't
216             // have aliases.
217             if (TRI->isVirtualRegister(MO.getReg()))
218               clobberRegisterUses(RegVars, MO.getReg(), DbgValues, MI);
219             // If this is a register def operand, it may end a debug value
220             // range.
221             else {
222               for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
223                    ++AI)
224                 if (ChangingRegs.test(*AI))
225                   clobberRegisterUses(RegVars, *AI, DbgValues, MI);
226             }
227           } else if (MO.isRegMask()) {
228             // If this is a register mask operand, clobber all debug values in
229             // non-CSRs.
230             for (unsigned I : ChangingRegs.set_bits()) {
231               // Don't consider SP to be clobbered by register masks.
232               if (unsigned(I) != SP && TRI->isPhysicalRegister(I) &&
233                   MO.clobbersPhysReg(I)) {
234                 clobberRegisterUses(RegVars, I, DbgValues, MI);
235               }
236             }
237           }
238         }
239         continue;
240       }
241 
242       if (MI.isDebugValue()) {
243         assert(MI.getNumOperands() > 1 && "Invalid DBG_VALUE instruction!");
244         // Use the base variable (without any DW_OP_piece expressions)
245         // as index into History. The full variables including the
246         // piece expressions are attached to the MI.
247         const DILocalVariable *RawVar = MI.getDebugVariable();
248         assert(RawVar->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
249                "Expected inlined-at fields to agree");
250         InlinedEntity Var(RawVar, MI.getDebugLoc()->getInlinedAt());
251 
252         if (unsigned PrevReg = DbgValues.getRegisterForVar(Var))
253           dropRegDescribedVar(RegVars, PrevReg, Var);
254 
255         DbgValues.startInstrRange(Var, MI);
256 
257         if (unsigned NewReg = isDescribedByReg(MI))
258           addRegDescribedVar(RegVars, NewReg, Var);
259       } else if (MI.isDebugLabel()) {
260         assert(MI.getNumOperands() == 1 && "Invalid DBG_LABEL instruction!");
261         const DILabel *RawLabel = MI.getDebugLabel();
262         assert(RawLabel->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
263             "Expected inlined-at fields to agree");
264         // When collecting debug information for labels, there is no MCSymbol
265         // generated for it. So, we keep MachineInstr in DbgLabels in order
266         // to query MCSymbol afterward.
267         InlinedEntity L(RawLabel, MI.getDebugLoc()->getInlinedAt());
268         DbgLabels.addInstr(L, MI);
269       }
270     }
271 
272     // Make sure locations for register-described variables are valid only
273     // until the end of the basic block (unless it's the last basic block, in
274     // which case let their liveness run off to the end of the function).
275     if (!MBB.empty() && &MBB != &MF->back()) {
276       for (auto I = RegVars.begin(), E = RegVars.end(); I != E;) {
277         auto CurElem = I++; // CurElem can be erased below.
278         if (TRI->isVirtualRegister(CurElem->first) ||
279             ChangingRegs.test(CurElem->first))
280           clobberRegisterUses(RegVars, CurElem, DbgValues, MBB.back());
281       }
282     }
283   }
284 }
285 
286 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
287 LLVM_DUMP_METHOD void DbgValueHistoryMap::dump() const {
288   dbgs() << "DbgValueHistoryMap:\n";
289   for (const auto &VarRangePair : *this) {
290     const InlinedEntity &Var = VarRangePair.first;
291     const InstrRanges &Ranges = VarRangePair.second;
292 
293     const DILocalVariable *LocalVar = cast<DILocalVariable>(Var.first);
294     const DILocation *Location = Var.second;
295 
296     dbgs() << " - " << LocalVar->getName() << " at ";
297 
298     if (Location)
299       dbgs() << Location->getFilename() << ":" << Location->getLine() << ":"
300              << Location->getColumn();
301     else
302       dbgs() << "<unknown location>";
303 
304     dbgs() << " --\n";
305 
306     for (const InstrRange &Range : Ranges) {
307       dbgs() << "   Begin: " << *Range.first;
308       if (Range.second)
309         dbgs() << "   End  : " << *Range.second;
310       dbgs() << "\n";
311     }
312   }
313 }
314 #endif
315