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