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 void DebugHandlerBase::beginModule(Module *M) {
95   if (M->debug_compile_units().empty())
96     Asm = nullptr;
97 }
98 
99 // Each LexicalScope has first instruction and last instruction to mark
100 // beginning and end of a scope respectively. Create an inverse map that list
101 // scopes starts (and ends) with an instruction. One instruction may start (or
102 // end) multiple scopes. Ignore scopes that are not reachable.
103 void DebugHandlerBase::identifyScopeMarkers() {
104   SmallVector<LexicalScope *, 4> WorkList;
105   WorkList.push_back(LScopes.getCurrentFunctionScope());
106   while (!WorkList.empty()) {
107     LexicalScope *S = WorkList.pop_back_val();
108 
109     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
110     if (!Children.empty())
111       WorkList.append(Children.begin(), Children.end());
112 
113     if (S->isAbstractScope())
114       continue;
115 
116     for (const InsnRange &R : S->getRanges()) {
117       assert(R.first && "InsnRange does not have first instruction!");
118       assert(R.second && "InsnRange does not have second instruction!");
119       requestLabelBeforeInsn(R.first);
120       requestLabelAfterInsn(R.second);
121     }
122   }
123 }
124 
125 // Return Label preceding the instruction.
126 MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) {
127   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
128   assert(Label && "Didn't insert label before instruction");
129   return Label;
130 }
131 
132 // Return Label immediately following the instruction.
133 MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) {
134   return LabelsAfterInsn.lookup(MI);
135 }
136 
137 /// If this type is derived from a base type then return base type size.
138 uint64_t DebugHandlerBase::getBaseTypeSize(const DIType *Ty) {
139   assert(Ty);
140   const DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty);
141   if (!DDTy)
142     return Ty->getSizeInBits();
143 
144   unsigned Tag = DDTy->getTag();
145 
146   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
147       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
148       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type)
149     return DDTy->getSizeInBits();
150 
151   DIType *BaseType = DDTy->getBaseType();
152 
153   if (!BaseType)
154     return 0;
155 
156   // If this is a derived type, go ahead and get the base type, unless it's a
157   // reference then it's just the size of the field. Pointer types have no need
158   // of this since they're a different type of qualification on the type.
159   if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
160       BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
161     return Ty->getSizeInBits();
162 
163   return getBaseTypeSize(BaseType);
164 }
165 
166 static bool hasDebugInfo(const MachineModuleInfo *MMI,
167                          const MachineFunction *MF) {
168   if (!MMI->hasDebugInfo())
169     return false;
170   auto *SP = MF->getFunction().getSubprogram();
171   if (!SP)
172     return false;
173   assert(SP->getUnit());
174   auto EK = SP->getUnit()->getEmissionKind();
175   if (EK == DICompileUnit::NoDebug)
176     return false;
177   return true;
178 }
179 
180 void DebugHandlerBase::beginFunction(const MachineFunction *MF) {
181   PrevInstBB = nullptr;
182 
183   if (!Asm || !hasDebugInfo(MMI, MF)) {
184     skippedNonDebugFunction();
185     return;
186   }
187 
188   // Grab the lexical scopes for the function, if we don't have any of those
189   // then we're not going to be able to do anything.
190   LScopes.initialize(*MF);
191   if (LScopes.empty()) {
192     beginFunctionImpl(MF);
193     return;
194   }
195 
196   // Make sure that each lexical scope will have a begin/end label.
197   identifyScopeMarkers();
198 
199   // Calculate history for local variables.
200   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
201   assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!");
202   calculateDbgEntityHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
203                             DbgValues, DbgLabels);
204   InstOrdering.initialize(*MF);
205   if (TrimVarLocs)
206     DbgValues.trimLocationRanges(*MF, LScopes, InstOrdering);
207   LLVM_DEBUG(DbgValues.dump());
208 
209   // Request labels for the full history.
210   for (const auto &I : DbgValues) {
211     const auto &Entries = I.second;
212     if (Entries.empty())
213       continue;
214 
215     auto IsDescribedByReg = [](const MachineInstr *MI) {
216       return MI->getDebugOperand(0).isReg() && MI->getDebugOperand(0).getReg();
217     };
218 
219     // The first mention of a function argument gets the CurrentFnBegin label,
220     // so arguments are visible when breaking at function entry.
221     //
222     // We do not change the label for values that are described by registers,
223     // as that could place them above their defining instructions. We should
224     // ideally not change the labels for constant debug values either, since
225     // doing that violates the ranges that are calculated in the history map.
226     // However, we currently do not emit debug values for constant arguments
227     // directly at the start of the function, so this code is still useful.
228     // FIXME: If the first mention of an argument is in a unique section basic
229     // block, we cannot always assign the CurrentFnBeginLabel as it lies in a
230     // different section.  Temporarily, we disable generating loc list
231     // information or DW_AT_const_value when the block is in a different
232     // section.
233     const DILocalVariable *DIVar =
234         Entries.front().getInstr()->getDebugVariable();
235     if (DIVar->isParameter() &&
236         getDISubprogram(DIVar->getScope())->describes(&MF->getFunction()) &&
237         Entries.front().getInstr()->getParent()->sameSection(&MF->front())) {
238       if (!IsDescribedByReg(Entries.front().getInstr()))
239         LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin();
240       if (Entries.front().getInstr()->getDebugExpression()->isFragment()) {
241         // Mark all non-overlapping initial fragments.
242         for (auto I = Entries.begin(); I != Entries.end(); ++I) {
243           if (!I->isDbgValue())
244             continue;
245           const DIExpression *Fragment = I->getInstr()->getDebugExpression();
246           if (std::any_of(Entries.begin(), I,
247                           [&](DbgValueHistoryMap::Entry Pred) {
248                             return Pred.isDbgValue() &&
249                                    Fragment->fragmentsOverlap(
250                                        Pred.getInstr()->getDebugExpression());
251                           }))
252             break;
253           // The code that generates location lists for DWARF assumes that the
254           // entries' start labels are monotonically increasing, and since we
255           // don't change the label for fragments that are described by
256           // registers, we must bail out when encountering such a fragment.
257           if (IsDescribedByReg(I->getInstr()))
258             break;
259           LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin();
260         }
261       }
262     }
263 
264     for (const auto &Entry : Entries) {
265       if (Entry.isDbgValue())
266         requestLabelBeforeInsn(Entry.getInstr());
267       else
268         requestLabelAfterInsn(Entry.getInstr());
269     }
270   }
271 
272   // Ensure there is a symbol before DBG_LABEL.
273   for (const auto &I : DbgLabels) {
274     const MachineInstr *MI = I.second;
275     requestLabelBeforeInsn(MI);
276   }
277 
278   PrevInstLoc = DebugLoc();
279   PrevLabel = Asm->getFunctionBegin();
280   beginFunctionImpl(MF);
281 }
282 
283 void DebugHandlerBase::beginInstruction(const MachineInstr *MI) {
284   if (!Asm || !MMI->hasDebugInfo())
285     return;
286 
287   assert(CurMI == nullptr);
288   CurMI = MI;
289 
290   // Insert labels where requested.
291   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
292       LabelsBeforeInsn.find(MI);
293 
294   // No label needed.
295   if (I == LabelsBeforeInsn.end())
296     return;
297 
298   // Label already assigned.
299   if (I->second)
300     return;
301 
302   if (!PrevLabel) {
303     PrevLabel = MMI->getContext().createTempSymbol();
304     Asm->OutStreamer->emitLabel(PrevLabel);
305   }
306   I->second = PrevLabel;
307 }
308 
309 void DebugHandlerBase::endInstruction() {
310   if (!Asm || !MMI->hasDebugInfo())
311     return;
312 
313   assert(CurMI != nullptr);
314   // Don't create a new label after DBG_VALUE and other instructions that don't
315   // generate code.
316   if (!CurMI->isMetaInstruction()) {
317     PrevLabel = nullptr;
318     PrevInstBB = CurMI->getParent();
319   }
320 
321   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
322       LabelsAfterInsn.find(CurMI);
323   CurMI = nullptr;
324 
325   // No label needed.
326   if (I == LabelsAfterInsn.end())
327     return;
328 
329   // Label already assigned.
330   if (I->second)
331     return;
332 
333   // We need a label after this instruction.
334   if (!PrevLabel) {
335     PrevLabel = MMI->getContext().createTempSymbol();
336     Asm->OutStreamer->emitLabel(PrevLabel);
337   }
338   I->second = PrevLabel;
339 }
340 
341 void DebugHandlerBase::endFunction(const MachineFunction *MF) {
342   if (Asm && hasDebugInfo(MMI, MF))
343     endFunctionImpl(MF);
344   DbgValues.clear();
345   DbgLabels.clear();
346   LabelsBeforeInsn.clear();
347   LabelsAfterInsn.clear();
348   InstOrdering.clear();
349 }
350 
351 void DebugHandlerBase::beginBasicBlock(const MachineBasicBlock &MBB) {
352   if (!MBB.isBeginSection())
353     return;
354 
355   PrevLabel = MBB.getSymbol();
356 }
357 
358 void DebugHandlerBase::endBasicBlock(const MachineBasicBlock &MBB) {
359   if (!MBB.isEndSection())
360     return;
361 
362   PrevLabel = nullptr;
363 }
364