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/CodeGen/AsmPrinter.h" |
16 | #include "llvm/CodeGen/MachineFunction.h" |
17 | #include "llvm/CodeGen/MachineInstr.h" |
18 | #include "llvm/CodeGen/MachineModuleInfo.h" |
19 | #include "llvm/CodeGen/TargetSubtargetInfo.h" |
20 | #include "llvm/IR/DebugInfo.h" |
21 | #include "llvm/MC/MCStreamer.h" |
22 | #include "llvm/Support/CommandLine.h" |
23 | |
24 | using namespace llvm; |
25 | |
26 | #define DEBUG_TYPE "dwarfdebug" |
27 | |
28 | /// If true, we drop variable location ranges which exist entirely outside the |
29 | /// variable's lexical scope instruction ranges. |
30 | static cl::opt<bool> TrimVarLocs("trim-var-locs" , cl::Hidden, cl::init(Val: true)); |
31 | |
32 | std::optional<DbgVariableLocation> |
33 | DbgVariableLocation::( |
34 | const MachineInstr &Instruction) { |
35 | DbgVariableLocation Location; |
36 | // Variables calculated from multiple locations can't be represented here. |
37 | if (Instruction.getNumDebugOperands() != 1) |
38 | return std::nullopt; |
39 | if (!Instruction.getDebugOperand(Index: 0).isReg()) |
40 | return std::nullopt; |
41 | Location.Register = Instruction.getDebugOperand(Index: 0).getReg(); |
42 | Location.FragmentInfo.reset(); |
43 | // We only handle expressions generated by DIExpression::appendOffset, |
44 | // which doesn't require a full stack machine. |
45 | int64_t Offset = 0; |
46 | const DIExpression *DIExpr = Instruction.getDebugExpression(); |
47 | auto Op = DIExpr->expr_op_begin(); |
48 | // We can handle a DBG_VALUE_LIST iff it has exactly one location operand that |
49 | // appears exactly once at the start of the expression. |
50 | if (Instruction.isDebugValueList()) { |
51 | if (Instruction.getNumDebugOperands() == 1 && |
52 | Op->getOp() == dwarf::DW_OP_LLVM_arg) |
53 | ++Op; |
54 | else |
55 | return std::nullopt; |
56 | } |
57 | while (Op != DIExpr->expr_op_end()) { |
58 | switch (Op->getOp()) { |
59 | case dwarf::DW_OP_constu: { |
60 | int Value = Op->getArg(I: 0); |
61 | ++Op; |
62 | if (Op != DIExpr->expr_op_end()) { |
63 | switch (Op->getOp()) { |
64 | case dwarf::DW_OP_minus: |
65 | Offset -= Value; |
66 | break; |
67 | case dwarf::DW_OP_plus: |
68 | Offset += Value; |
69 | break; |
70 | default: |
71 | continue; |
72 | } |
73 | } |
74 | } break; |
75 | case dwarf::DW_OP_plus_uconst: |
76 | Offset += Op->getArg(I: 0); |
77 | break; |
78 | case dwarf::DW_OP_LLVM_fragment: |
79 | Location.FragmentInfo = {Op->getArg(I: 1), Op->getArg(I: 0)}; |
80 | break; |
81 | case dwarf::DW_OP_deref: |
82 | Location.LoadChain.push_back(Elt: Offset); |
83 | Offset = 0; |
84 | break; |
85 | default: |
86 | return std::nullopt; |
87 | } |
88 | ++Op; |
89 | } |
90 | |
91 | // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE |
92 | // instruction. |
93 | // FIXME: Replace these with DIExpression. |
94 | if (Instruction.isIndirectDebugValue()) |
95 | Location.LoadChain.push_back(Elt: Offset); |
96 | |
97 | return Location; |
98 | } |
99 | |
100 | DebugHandlerBase::DebugHandlerBase(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {} |
101 | |
102 | void DebugHandlerBase::beginModule(Module *M) { |
103 | if (M->debug_compile_units().empty()) |
104 | Asm = nullptr; |
105 | } |
106 | |
107 | // Each LexicalScope has first instruction and last instruction to mark |
108 | // beginning and end of a scope respectively. Create an inverse map that list |
109 | // scopes starts (and ends) with an instruction. One instruction may start (or |
110 | // end) multiple scopes. Ignore scopes that are not reachable. |
111 | void DebugHandlerBase::identifyScopeMarkers() { |
112 | SmallVector<LexicalScope *, 4> WorkList; |
113 | WorkList.push_back(Elt: LScopes.getCurrentFunctionScope()); |
114 | while (!WorkList.empty()) { |
115 | LexicalScope *S = WorkList.pop_back_val(); |
116 | |
117 | const SmallVectorImpl<LexicalScope *> &Children = S->getChildren(); |
118 | if (!Children.empty()) |
119 | WorkList.append(in_start: Children.begin(), in_end: Children.end()); |
120 | |
121 | if (S->isAbstractScope()) |
122 | continue; |
123 | |
124 | for (const InsnRange &R : S->getRanges()) { |
125 | assert(R.first && "InsnRange does not have first instruction!" ); |
126 | assert(R.second && "InsnRange does not have second instruction!" ); |
127 | requestLabelBeforeInsn(MI: R.first); |
128 | requestLabelAfterInsn(MI: R.second); |
129 | } |
130 | } |
131 | } |
132 | |
133 | // Return Label preceding the instruction. |
134 | MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) { |
135 | MCSymbol *Label = LabelsBeforeInsn.lookup(Val: MI); |
136 | assert(Label && "Didn't insert label before instruction" ); |
137 | return Label; |
138 | } |
139 | |
140 | // Return Label immediately following the instruction. |
141 | MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) { |
142 | return LabelsAfterInsn.lookup(Val: MI); |
143 | } |
144 | |
145 | /// If this type is derived from a base type then return base type size. |
146 | uint64_t DebugHandlerBase::getBaseTypeSize(const DIType *Ty) { |
147 | assert(Ty); |
148 | const DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Val: Ty); |
149 | if (!DDTy) |
150 | return Ty->getSizeInBits(); |
151 | |
152 | unsigned Tag = DDTy->getTag(); |
153 | |
154 | if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef && |
155 | Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type && |
156 | Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type && |
157 | Tag != dwarf::DW_TAG_immutable_type && |
158 | Tag != dwarf::DW_TAG_template_alias) |
159 | return DDTy->getSizeInBits(); |
160 | |
161 | DIType *BaseType = DDTy->getBaseType(); |
162 | |
163 | if (!BaseType) |
164 | return 0; |
165 | |
166 | // If this is a derived type, go ahead and get the base type, unless it's a |
167 | // reference then it's just the size of the field. Pointer types have no need |
168 | // of this since they're a different type of qualification on the type. |
169 | if (BaseType->getTag() == dwarf::DW_TAG_reference_type || |
170 | BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type) |
171 | return Ty->getSizeInBits(); |
172 | |
173 | return getBaseTypeSize(Ty: BaseType); |
174 | } |
175 | |
176 | bool DebugHandlerBase::isUnsignedDIType(const DIType *Ty) { |
177 | if (isa<DIStringType>(Val: Ty)) { |
178 | // Some transformations (e.g. instcombine) may decide to turn a Fortran |
179 | // character object into an integer, and later ones (e.g. SROA) may |
180 | // further inject a constant integer in a llvm.dbg.value call to track |
181 | // the object's value. Here we trust the transformations are doing the |
182 | // right thing, and treat the constant as unsigned to preserve that value |
183 | // (i.e. avoid sign extension). |
184 | return true; |
185 | } |
186 | |
187 | if (auto *CTy = dyn_cast<DICompositeType>(Val: Ty)) { |
188 | if (CTy->getTag() == dwarf::DW_TAG_enumeration_type) { |
189 | if (!(Ty = CTy->getBaseType())) |
190 | // FIXME: Enums without a fixed underlying type have unknown signedness |
191 | // here, leading to incorrectly emitted constants. |
192 | return false; |
193 | } else |
194 | // (Pieces of) aggregate types that get hacked apart by SROA may be |
195 | // represented by a constant. Encode them as unsigned bytes. |
196 | return true; |
197 | } |
198 | |
199 | if (auto *DTy = dyn_cast<DIDerivedType>(Val: Ty)) { |
200 | dwarf::Tag T = (dwarf::Tag)Ty->getTag(); |
201 | // Encode pointer constants as unsigned bytes. This is used at least for |
202 | // null pointer constant emission. |
203 | // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed |
204 | // here, but accept them for now due to a bug in SROA producing bogus |
205 | // dbg.values. |
206 | if (T == dwarf::DW_TAG_pointer_type || |
207 | T == dwarf::DW_TAG_ptr_to_member_type || |
208 | T == dwarf::DW_TAG_reference_type || |
209 | T == dwarf::DW_TAG_rvalue_reference_type) |
210 | return true; |
211 | assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type || |
212 | T == dwarf::DW_TAG_volatile_type || |
213 | T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type || |
214 | T == dwarf::DW_TAG_immutable_type || |
215 | T == dwarf::DW_TAG_template_alias); |
216 | assert(DTy->getBaseType() && "Expected valid base type" ); |
217 | return isUnsignedDIType(Ty: DTy->getBaseType()); |
218 | } |
219 | |
220 | auto *BTy = cast<DIBasicType>(Val: Ty); |
221 | unsigned Encoding = BTy->getEncoding(); |
222 | assert((Encoding == dwarf::DW_ATE_unsigned || |
223 | Encoding == dwarf::DW_ATE_unsigned_char || |
224 | Encoding == dwarf::DW_ATE_signed || |
225 | Encoding == dwarf::DW_ATE_signed_char || |
226 | Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF || |
227 | Encoding == dwarf::DW_ATE_boolean || |
228 | Encoding == dwarf::DW_ATE_complex_float || |
229 | Encoding == dwarf::DW_ATE_signed_fixed || |
230 | Encoding == dwarf::DW_ATE_unsigned_fixed || |
231 | (Ty->getTag() == dwarf::DW_TAG_unspecified_type && |
232 | Ty->getName() == "decltype(nullptr)" )) && |
233 | "Unsupported encoding" ); |
234 | return Encoding == dwarf::DW_ATE_unsigned || |
235 | Encoding == dwarf::DW_ATE_unsigned_char || |
236 | Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean || |
237 | Encoding == llvm::dwarf::DW_ATE_unsigned_fixed || |
238 | Ty->getTag() == dwarf::DW_TAG_unspecified_type; |
239 | } |
240 | |
241 | static bool hasDebugInfo(const MachineModuleInfo *MMI, |
242 | const MachineFunction *MF) { |
243 | if (!MMI->hasDebugInfo()) |
244 | return false; |
245 | auto *SP = MF->getFunction().getSubprogram(); |
246 | if (!SP) |
247 | return false; |
248 | assert(SP->getUnit()); |
249 | auto EK = SP->getUnit()->getEmissionKind(); |
250 | if (EK == DICompileUnit::NoDebug) |
251 | return false; |
252 | return true; |
253 | } |
254 | |
255 | void DebugHandlerBase::beginFunction(const MachineFunction *MF) { |
256 | PrevInstBB = nullptr; |
257 | |
258 | if (!Asm || !hasDebugInfo(MMI, MF)) { |
259 | skippedNonDebugFunction(); |
260 | return; |
261 | } |
262 | |
263 | // Grab the lexical scopes for the function, if we don't have any of those |
264 | // then we're not going to be able to do anything. |
265 | LScopes.initialize(*MF); |
266 | if (LScopes.empty()) { |
267 | beginFunctionImpl(MF); |
268 | return; |
269 | } |
270 | |
271 | // Make sure that each lexical scope will have a begin/end label. |
272 | identifyScopeMarkers(); |
273 | |
274 | // Calculate history for local variables. |
275 | assert(DbgValues.empty() && "DbgValues map wasn't cleaned!" ); |
276 | assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!" ); |
277 | calculateDbgEntityHistory(MF, TRI: Asm->MF->getSubtarget().getRegisterInfo(), |
278 | DbgValues, DbgLabels); |
279 | InstOrdering.initialize(MF: *MF); |
280 | if (TrimVarLocs) |
281 | DbgValues.trimLocationRanges(MF: *MF, LScopes, Ordering: InstOrdering); |
282 | LLVM_DEBUG(DbgValues.dump(MF->getName())); |
283 | |
284 | // Request labels for the full history. |
285 | for (const auto &I : DbgValues) { |
286 | const auto &Entries = I.second; |
287 | if (Entries.empty()) |
288 | continue; |
289 | |
290 | auto IsDescribedByReg = [](const MachineInstr *MI) { |
291 | return any_of(Range: MI->debug_operands(), |
292 | P: [](auto &MO) { return MO.isReg() && MO.getReg(); }); |
293 | }; |
294 | |
295 | // The first mention of a function argument gets the CurrentFnBegin label, |
296 | // so arguments are visible when breaking at function entry. |
297 | // |
298 | // We do not change the label for values that are described by registers, |
299 | // as that could place them above their defining instructions. We should |
300 | // ideally not change the labels for constant debug values either, since |
301 | // doing that violates the ranges that are calculated in the history map. |
302 | // However, we currently do not emit debug values for constant arguments |
303 | // directly at the start of the function, so this code is still useful. |
304 | const DILocalVariable *DIVar = |
305 | Entries.front().getInstr()->getDebugVariable(); |
306 | if (DIVar->isParameter() && |
307 | getDISubprogram(Scope: DIVar->getScope())->describes(F: &MF->getFunction())) { |
308 | if (!IsDescribedByReg(Entries.front().getInstr())) |
309 | LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin(); |
310 | if (Entries.front().getInstr()->getDebugExpression()->isFragment()) { |
311 | // Mark all non-overlapping initial fragments. |
312 | for (const auto *I = Entries.begin(); I != Entries.end(); ++I) { |
313 | if (!I->isDbgValue()) |
314 | continue; |
315 | const DIExpression *Fragment = I->getInstr()->getDebugExpression(); |
316 | if (std::any_of(first: Entries.begin(), last: I, |
317 | pred: [&](DbgValueHistoryMap::Entry Pred) { |
318 | return Pred.isDbgValue() && |
319 | Fragment->fragmentsOverlap( |
320 | Other: Pred.getInstr()->getDebugExpression()); |
321 | })) |
322 | break; |
323 | // The code that generates location lists for DWARF assumes that the |
324 | // entries' start labels are monotonically increasing, and since we |
325 | // don't change the label for fragments that are described by |
326 | // registers, we must bail out when encountering such a fragment. |
327 | if (IsDescribedByReg(I->getInstr())) |
328 | break; |
329 | LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin(); |
330 | } |
331 | } |
332 | } |
333 | |
334 | for (const auto &Entry : Entries) { |
335 | if (Entry.isDbgValue()) |
336 | requestLabelBeforeInsn(MI: Entry.getInstr()); |
337 | else |
338 | requestLabelAfterInsn(MI: Entry.getInstr()); |
339 | } |
340 | } |
341 | |
342 | // Ensure there is a symbol before DBG_LABEL. |
343 | for (const auto &I : DbgLabels) { |
344 | const MachineInstr *MI = I.second; |
345 | requestLabelBeforeInsn(MI); |
346 | } |
347 | |
348 | PrevInstLoc = DebugLoc(); |
349 | PrevLabel = Asm->getFunctionBegin(); |
350 | beginFunctionImpl(MF); |
351 | } |
352 | |
353 | void DebugHandlerBase::beginInstruction(const MachineInstr *MI) { |
354 | if (!Asm || !MMI->hasDebugInfo()) |
355 | return; |
356 | |
357 | assert(CurMI == nullptr); |
358 | CurMI = MI; |
359 | |
360 | // Insert labels where requested. |
361 | DenseMap<const MachineInstr *, MCSymbol *>::iterator I = |
362 | LabelsBeforeInsn.find(Val: MI); |
363 | |
364 | // No label needed. |
365 | if (I == LabelsBeforeInsn.end()) |
366 | return; |
367 | |
368 | // Label already assigned. |
369 | if (I->second) |
370 | return; |
371 | |
372 | if (!PrevLabel) { |
373 | PrevLabel = MMI->getContext().createTempSymbol(); |
374 | Asm->OutStreamer->emitLabel(Symbol: PrevLabel); |
375 | } |
376 | I->second = PrevLabel; |
377 | } |
378 | |
379 | void DebugHandlerBase::endInstruction() { |
380 | if (!Asm || !MMI->hasDebugInfo()) |
381 | return; |
382 | |
383 | assert(CurMI != nullptr); |
384 | // Don't create a new label after DBG_VALUE and other instructions that don't |
385 | // generate code. |
386 | if (!CurMI->isMetaInstruction()) { |
387 | PrevLabel = nullptr; |
388 | PrevInstBB = CurMI->getParent(); |
389 | } |
390 | |
391 | DenseMap<const MachineInstr *, MCSymbol *>::iterator I = |
392 | LabelsAfterInsn.find(Val: CurMI); |
393 | |
394 | // No label needed or label already assigned. |
395 | if (I == LabelsAfterInsn.end() || I->second) { |
396 | CurMI = nullptr; |
397 | return; |
398 | } |
399 | |
400 | // We need a label after this instruction. With basic block sections, just |
401 | // use the end symbol of the section if this is the last instruction of the |
402 | // section. This reduces the need for an additional label and also helps |
403 | // merging ranges. |
404 | if (CurMI->getParent()->isEndSection() && CurMI->getNextNode() == nullptr) { |
405 | PrevLabel = CurMI->getParent()->getEndSymbol(); |
406 | } else if (!PrevLabel) { |
407 | PrevLabel = MMI->getContext().createTempSymbol(); |
408 | Asm->OutStreamer->emitLabel(Symbol: PrevLabel); |
409 | } |
410 | I->second = PrevLabel; |
411 | CurMI = nullptr; |
412 | } |
413 | |
414 | void DebugHandlerBase::endFunction(const MachineFunction *MF) { |
415 | if (Asm && hasDebugInfo(MMI, MF)) |
416 | endFunctionImpl(MF); |
417 | DbgValues.clear(); |
418 | DbgLabels.clear(); |
419 | LabelsBeforeInsn.clear(); |
420 | LabelsAfterInsn.clear(); |
421 | InstOrdering.clear(); |
422 | } |
423 | |
424 | void DebugHandlerBase::beginBasicBlockSection(const MachineBasicBlock &MBB) { |
425 | EpilogBeginBlock = nullptr; |
426 | if (!MBB.isEntryBlock()) |
427 | PrevLabel = MBB.getSymbol(); |
428 | } |
429 | |
430 | void DebugHandlerBase::endBasicBlockSection(const MachineBasicBlock &MBB) { |
431 | PrevLabel = nullptr; |
432 | } |
433 | |