xref: /llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp (revision 4242df14708cb84b3732ba1a22fb77146833340b)
1 //===-- llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp -------*- C++ -*--===//
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 // Common functionality for different debug information format backends.
10 // LLVM currently supports DWARF and CodeView.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/DebugHandlerBase.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/CodeGen/AsmPrinter.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/TargetSubtargetInfo.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/Support/CommandLine.h"
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "dwarfdebug"
29 
30 /// If true, we drop variable location ranges which exist entirely outside the
31 /// variable's lexical scope instruction ranges.
32 static cl::opt<bool> TrimVarLocs("trim-var-locs", cl::Hidden, cl::init(true));
33 
34 Optional<DbgVariableLocation>
35 DbgVariableLocation::extractFromMachineInstruction(
36     const MachineInstr &Instruction) {
37   DbgVariableLocation Location;
38   if (!Instruction.isDebugValue())
39     return None;
40   if (!Instruction.getDebugOperand(0).isReg())
41     return None;
42   Location.Register = Instruction.getDebugOperand(0).getReg();
43   Location.FragmentInfo.reset();
44   // We only handle expressions generated by DIExpression::appendOffset,
45   // which doesn't require a full stack machine.
46   int64_t Offset = 0;
47   const DIExpression *DIExpr = Instruction.getDebugExpression();
48   auto Op = DIExpr->expr_op_begin();
49   while (Op != DIExpr->expr_op_end()) {
50     switch (Op->getOp()) {
51     case dwarf::DW_OP_constu: {
52       int Value = Op->getArg(0);
53       ++Op;
54       if (Op != DIExpr->expr_op_end()) {
55         switch (Op->getOp()) {
56         case dwarf::DW_OP_minus:
57           Offset -= Value;
58           break;
59         case dwarf::DW_OP_plus:
60           Offset += Value;
61           break;
62         default:
63           continue;
64         }
65       }
66     } break;
67     case dwarf::DW_OP_plus_uconst:
68       Offset += Op->getArg(0);
69       break;
70     case dwarf::DW_OP_LLVM_fragment:
71       Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)};
72       break;
73     case dwarf::DW_OP_deref:
74       Location.LoadChain.push_back(Offset);
75       Offset = 0;
76       break;
77     default:
78       return None;
79     }
80     ++Op;
81   }
82 
83   // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE
84   // instruction.
85   // FIXME: Replace these with DIExpression.
86   if (Instruction.isIndirectDebugValue())
87     Location.LoadChain.push_back(Offset);
88 
89   return Location;
90 }
91 
92 DebugHandlerBase::DebugHandlerBase(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
93 
94 // Each LexicalScope has first instruction and last instruction to mark
95 // beginning and end of a scope respectively. Create an inverse map that list
96 // scopes starts (and ends) with an instruction. One instruction may start (or
97 // end) multiple scopes. Ignore scopes that are not reachable.
98 void DebugHandlerBase::identifyScopeMarkers() {
99   SmallVector<LexicalScope *, 4> WorkList;
100   WorkList.push_back(LScopes.getCurrentFunctionScope());
101   while (!WorkList.empty()) {
102     LexicalScope *S = WorkList.pop_back_val();
103 
104     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
105     if (!Children.empty())
106       WorkList.append(Children.begin(), Children.end());
107 
108     if (S->isAbstractScope())
109       continue;
110 
111     for (const InsnRange &R : S->getRanges()) {
112       assert(R.first && "InsnRange does not have first instruction!");
113       assert(R.second && "InsnRange does not have second instruction!");
114       requestLabelBeforeInsn(R.first);
115       requestLabelAfterInsn(R.second);
116     }
117   }
118 }
119 
120 // Return Label preceding the instruction.
121 MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) {
122   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
123   assert(Label && "Didn't insert label before instruction");
124   return Label;
125 }
126 
127 // Return Label immediately following the instruction.
128 MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) {
129   return LabelsAfterInsn.lookup(MI);
130 }
131 
132 /// If this type is derived from a base type then return base type size.
133 uint64_t DebugHandlerBase::getBaseTypeSize(const DIType *Ty) {
134   assert(Ty);
135   const DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty);
136   if (!DDTy)
137     return Ty->getSizeInBits();
138 
139   unsigned Tag = DDTy->getTag();
140 
141   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
142       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
143       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type)
144     return DDTy->getSizeInBits();
145 
146   DIType *BaseType = DDTy->getBaseType();
147 
148   if (!BaseType)
149     return 0;
150 
151   // If this is a derived type, go ahead and get the base type, unless it's a
152   // reference then it's just the size of the field. Pointer types have no need
153   // of this since they're a different type of qualification on the type.
154   if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
155       BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
156     return Ty->getSizeInBits();
157 
158   return getBaseTypeSize(BaseType);
159 }
160 
161 static bool hasDebugInfo(const MachineModuleInfo *MMI,
162                          const MachineFunction *MF) {
163   if (!MMI->hasDebugInfo())
164     return false;
165   auto *SP = MF->getFunction().getSubprogram();
166   if (!SP)
167     return false;
168   assert(SP->getUnit());
169   auto EK = SP->getUnit()->getEmissionKind();
170   if (EK == DICompileUnit::NoDebug)
171     return false;
172   return true;
173 }
174 
175 void DebugHandlerBase::beginFunction(const MachineFunction *MF) {
176   PrevInstBB = nullptr;
177 
178   if (!Asm || !hasDebugInfo(MMI, MF)) {
179     skippedNonDebugFunction();
180     return;
181   }
182 
183   // Grab the lexical scopes for the function, if we don't have any of those
184   // then we're not going to be able to do anything.
185   LScopes.initialize(*MF);
186   if (LScopes.empty()) {
187     beginFunctionImpl(MF);
188     return;
189   }
190 
191   // Make sure that each lexical scope will have a begin/end label.
192   identifyScopeMarkers();
193 
194   // Calculate history for local variables.
195   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
196   assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!");
197   calculateDbgEntityHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
198                             DbgValues, DbgLabels);
199   InstOrdering.initialize(*MF);
200   if (TrimVarLocs)
201     DbgValues.trimLocationRanges(*MF, LScopes, InstOrdering);
202   LLVM_DEBUG(DbgValues.dump());
203 
204   // Request labels for the full history.
205   for (const auto &I : DbgValues) {
206     const auto &Entries = I.second;
207     if (Entries.empty())
208       continue;
209 
210     auto IsDescribedByReg = [](const MachineInstr *MI) {
211       return MI->getDebugOperand(0).isReg() && MI->getDebugOperand(0).getReg();
212     };
213 
214     // The first mention of a function argument gets the CurrentFnBegin label,
215     // so arguments are visible when breaking at function entry.
216     //
217     // We do not change the label for values that are described by registers,
218     // as that could place them above their defining instructions. We should
219     // ideally not change the labels for constant debug values either, since
220     // doing that violates the ranges that are calculated in the history map.
221     // However, we currently do not emit debug values for constant arguments
222     // directly at the start of the function, so this code is still useful.
223     // FIXME: If the first mention of an argument is in a unique section basic
224     // block, we cannot always assign the CurrentFnBeginLabel as it lies in a
225     // different section.  Temporarily, we disable generating loc list
226     // information or DW_AT_const_value when the block is in a different
227     // section.
228     const DILocalVariable *DIVar =
229         Entries.front().getInstr()->getDebugVariable();
230     if (DIVar->isParameter() &&
231         getDISubprogram(DIVar->getScope())->describes(&MF->getFunction()) &&
232         Entries.front().getInstr()->getParent()->sameSection(&MF->front())) {
233       if (!IsDescribedByReg(Entries.front().getInstr()))
234         LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin();
235       if (Entries.front().getInstr()->getDebugExpression()->isFragment()) {
236         // Mark all non-overlapping initial fragments.
237         for (auto I = Entries.begin(); I != Entries.end(); ++I) {
238           if (!I->isDbgValue())
239             continue;
240           const DIExpression *Fragment = I->getInstr()->getDebugExpression();
241           if (std::any_of(Entries.begin(), I,
242                           [&](DbgValueHistoryMap::Entry Pred) {
243                             return Pred.isDbgValue() &&
244                                    Fragment->fragmentsOverlap(
245                                        Pred.getInstr()->getDebugExpression());
246                           }))
247             break;
248           // The code that generates location lists for DWARF assumes that the
249           // entries' start labels are monotonically increasing, and since we
250           // don't change the label for fragments that are described by
251           // registers, we must bail out when encountering such a fragment.
252           if (IsDescribedByReg(I->getInstr()))
253             break;
254           LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin();
255         }
256       }
257     }
258 
259     for (const auto &Entry : Entries) {
260       if (Entry.isDbgValue())
261         requestLabelBeforeInsn(Entry.getInstr());
262       else
263         requestLabelAfterInsn(Entry.getInstr());
264     }
265   }
266 
267   // Ensure there is a symbol before DBG_LABEL.
268   for (const auto &I : DbgLabels) {
269     const MachineInstr *MI = I.second;
270     requestLabelBeforeInsn(MI);
271   }
272 
273   PrevInstLoc = DebugLoc();
274   PrevLabel = Asm->getFunctionBegin();
275   beginFunctionImpl(MF);
276 }
277 
278 void DebugHandlerBase::beginInstruction(const MachineInstr *MI) {
279   if (!MMI->hasDebugInfo())
280     return;
281 
282   assert(CurMI == nullptr);
283   CurMI = MI;
284 
285   // Insert labels where requested.
286   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
287       LabelsBeforeInsn.find(MI);
288 
289   // No label needed.
290   if (I == LabelsBeforeInsn.end())
291     return;
292 
293   // Label already assigned.
294   if (I->second)
295     return;
296 
297   if (!PrevLabel) {
298     PrevLabel = MMI->getContext().createTempSymbol();
299     Asm->OutStreamer->emitLabel(PrevLabel);
300   }
301   I->second = PrevLabel;
302 }
303 
304 void DebugHandlerBase::endInstruction() {
305   if (!MMI->hasDebugInfo())
306     return;
307 
308   assert(CurMI != nullptr);
309   // Don't create a new label after DBG_VALUE and other instructions that don't
310   // generate code.
311   if (!CurMI->isMetaInstruction()) {
312     PrevLabel = nullptr;
313     PrevInstBB = CurMI->getParent();
314   }
315 
316   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
317       LabelsAfterInsn.find(CurMI);
318   CurMI = nullptr;
319 
320   // No label needed.
321   if (I == LabelsAfterInsn.end())
322     return;
323 
324   // Label already assigned.
325   if (I->second)
326     return;
327 
328   // We need a label after this instruction.
329   if (!PrevLabel) {
330     PrevLabel = MMI->getContext().createTempSymbol();
331     Asm->OutStreamer->emitLabel(PrevLabel);
332   }
333   I->second = PrevLabel;
334 }
335 
336 void DebugHandlerBase::endFunction(const MachineFunction *MF) {
337   if (hasDebugInfo(MMI, MF))
338     endFunctionImpl(MF);
339   DbgValues.clear();
340   DbgLabels.clear();
341   LabelsBeforeInsn.clear();
342   LabelsAfterInsn.clear();
343   InstOrdering.clear();
344 }
345 
346 void DebugHandlerBase::beginBasicBlock(const MachineBasicBlock &MBB) {
347   if (!MBB.isBeginSection())
348     return;
349 
350   PrevLabel = MBB.getSymbol();
351 }
352 
353 void DebugHandlerBase::endBasicBlock(const MachineBasicBlock &MBB) {
354   if (!MBB.isEndSection())
355     return;
356 
357   PrevLabel = nullptr;
358 }
359