xref: /llvm-project/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp (revision ce6de3747bce66b122134d02bb6d25827730d498)
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   if (TrimVarLocs)
200     DbgValues.trimLocationRanges(*MF, LScopes);
201   LLVM_DEBUG(DbgValues.dump());
202 
203   // Request labels for the full history.
204   for (const auto &I : DbgValues) {
205     const auto &Entries = I.second;
206     if (Entries.empty())
207       continue;
208 
209     auto IsDescribedByReg = [](const MachineInstr *MI) {
210       return MI->getDebugOperand(0).isReg() && MI->getDebugOperand(0).getReg();
211     };
212 
213     // The first mention of a function argument gets the CurrentFnBegin label,
214     // so arguments are visible when breaking at function entry.
215     //
216     // We do not change the label for values that are described by registers,
217     // as that could place them above their defining instructions. We should
218     // ideally not change the labels for constant debug values either, since
219     // doing that violates the ranges that are calculated in the history map.
220     // However, we currently do not emit debug values for constant arguments
221     // directly at the start of the function, so this code is still useful.
222     const DILocalVariable *DIVar =
223         Entries.front().getInstr()->getDebugVariable();
224     if (DIVar->isParameter() &&
225         getDISubprogram(DIVar->getScope())->describes(&MF->getFunction())) {
226       if (!IsDescribedByReg(Entries.front().getInstr()))
227         LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin();
228       if (Entries.front().getInstr()->getDebugExpression()->isFragment()) {
229         // Mark all non-overlapping initial fragments.
230         for (auto I = Entries.begin(); I != Entries.end(); ++I) {
231           if (!I->isDbgValue())
232             continue;
233           const DIExpression *Fragment = I->getInstr()->getDebugExpression();
234           if (std::any_of(Entries.begin(), I,
235                           [&](DbgValueHistoryMap::Entry Pred) {
236                             return Pred.isDbgValue() &&
237                                    Fragment->fragmentsOverlap(
238                                        Pred.getInstr()->getDebugExpression());
239                           }))
240             break;
241           // The code that generates location lists for DWARF assumes that the
242           // entries' start labels are monotonically increasing, and since we
243           // don't change the label for fragments that are described by
244           // registers, we must bail out when encountering such a fragment.
245           if (IsDescribedByReg(I->getInstr()))
246             break;
247           LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin();
248         }
249       }
250     }
251 
252     for (const auto &Entry : Entries) {
253       if (Entry.isDbgValue())
254         requestLabelBeforeInsn(Entry.getInstr());
255       else
256         requestLabelAfterInsn(Entry.getInstr());
257     }
258   }
259 
260   // Ensure there is a symbol before DBG_LABEL.
261   for (const auto &I : DbgLabels) {
262     const MachineInstr *MI = I.second;
263     requestLabelBeforeInsn(MI);
264   }
265 
266   PrevInstLoc = DebugLoc();
267   PrevLabel = Asm->getFunctionBegin();
268   beginFunctionImpl(MF);
269 }
270 
271 void DebugHandlerBase::beginInstruction(const MachineInstr *MI) {
272   if (!MMI->hasDebugInfo())
273     return;
274 
275   assert(CurMI == nullptr);
276   CurMI = MI;
277 
278   // Insert labels where requested.
279   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
280       LabelsBeforeInsn.find(MI);
281 
282   // No label needed.
283   if (I == LabelsBeforeInsn.end())
284     return;
285 
286   // Label already assigned.
287   if (I->second)
288     return;
289 
290   if (!PrevLabel) {
291     PrevLabel = MMI->getContext().createTempSymbol();
292     Asm->OutStreamer->emitLabel(PrevLabel);
293   }
294   I->second = PrevLabel;
295 }
296 
297 void DebugHandlerBase::endInstruction() {
298   if (!MMI->hasDebugInfo())
299     return;
300 
301   assert(CurMI != nullptr);
302   // Don't create a new label after DBG_VALUE and other instructions that don't
303   // generate code.
304   if (!CurMI->isMetaInstruction()) {
305     PrevLabel = nullptr;
306     PrevInstBB = CurMI->getParent();
307   }
308 
309   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
310       LabelsAfterInsn.find(CurMI);
311   CurMI = nullptr;
312 
313   // No label needed.
314   if (I == LabelsAfterInsn.end())
315     return;
316 
317   // Label already assigned.
318   if (I->second)
319     return;
320 
321   // We need a label after this instruction.
322   if (!PrevLabel) {
323     PrevLabel = MMI->getContext().createTempSymbol();
324     Asm->OutStreamer->emitLabel(PrevLabel);
325   }
326   I->second = PrevLabel;
327 }
328 
329 void DebugHandlerBase::endFunction(const MachineFunction *MF) {
330   if (hasDebugInfo(MMI, MF))
331     endFunctionImpl(MF);
332   DbgValues.clear();
333   DbgLabels.clear();
334   LabelsBeforeInsn.clear();
335   LabelsAfterInsn.clear();
336 }
337 
338 void DebugHandlerBase::beginBasicBlock(const MachineBasicBlock &MBB) {
339   if (!MBB.isBeginSection())
340     return;
341 
342   PrevLabel = MBB.getSymbol();
343 }
344 
345 void DebugHandlerBase::endBasicBlock(const MachineBasicBlock &MBB) {
346   if (!MBB.isEndSection())
347     return;
348 
349   PrevLabel = nullptr;
350 }
351