LLVM 24.0.0git
DWARFExpressionPrinter.cpp
Go to the documentation of this file.
1//===-- DWARFExpression.cpp -----------------------------------------------===//
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
14#include "llvm/Support/Endian.h"
16#include <cassert>
17#include <cstdint>
18
19using namespace llvm;
20using namespace dwarf;
21
22namespace llvm {
23
26
27/// Some backends (e.g. NVPTX) encode virtual register names as the DWARF
28/// register number: the ASCII bytes of the name are concatenated into a
29/// uint64_t (see NVPTXRegisterInfo::encodeRegisterForDwarf). When the object
30/// file is not the target backend, MCRegisterInfo cannot map these numbers, so
31/// recover the string for dumping.
32/// Returns true if the register name was decoded successfully, false otherwise.
33static bool decodeVirtualRegisterName(uint64_t DwarfRegNum,
34 SmallString<8> &Out) {
35 if (DwarfRegNum == 0)
36 return false;
37
38 uint64_t DwarfRegNumBE =
40 const char *Data = reinterpret_cast<const char *>(&DwarfRegNumBE);
41 const char *Begin = std::find_if(Data, Data + sizeof(DwarfRegNumBE),
42 [](char c) { return c != '\0'; });
43 SmallString<8> Tmp(Begin, Data + sizeof(DwarfRegNumBE));
44
45 if (Tmp.size() < 2)
46 return false;
47
48 if (!llvm::isAlnum(Tmp[0]) && Tmp[0] != '%')
49 return false;
50
51 for (size_t I = 1; I < Tmp.size(); ++I)
52 if (!llvm::isAlnum(Tmp[I]))
53 return false;
54
55 Out = Tmp;
56 return true;
57}
58
59/// Resolves a DWARF register number to a display name: first via \p
60/// GetNameForDWARFReg (MC register names), otherwise try decoding
61/// ASCII-encoded virtual register names (NVPTX-specific).
62/// Returns empty if neither applies.
63static std::string resolveRegName(
64 uint64_t DwarfRegNum, bool IsEH,
65 const std::function<StringRef(uint64_t, bool)> &GetNameForDWARFReg) {
66 if (GetNameForDWARFReg) {
67 StringRef R = GetNameForDWARFReg(DwarfRegNum, IsEH);
68 if (!R.empty())
69 return R.str();
70 }
71 SmallString<8> Decoded;
72 if (decodeVirtualRegisterName(DwarfRegNum, Decoded))
73 return Decoded.str().str();
74 return "";
75}
76
78 DIDumpOptions DumpOpts,
80 unsigned Operand) {
81 assert(Operand < Operands.size() && "operand out of bounds");
82 if (!U) {
83 OS << formatv(" <base_type ref: {0:x}>", Operands[Operand]);
84 return;
85 }
86 auto Die = U->getDIEForOffset(U->getOffset() + Operands[Operand]);
87 if (Die && Die.getTag() == dwarf::DW_TAG_base_type) {
88 OS << " (";
89 if (DumpOpts.Verbose)
90 OS << formatv("{0:x8} -> ", Operands[Operand]);
91 OS << formatv("{0:x8})", U->getOffset() + Operands[Operand]);
92 if (auto Name = dwarf::toString(Die.find(dwarf::DW_AT_name)))
93 OS << " \"" << *Name << "\"";
94 } else {
95 OS << formatv(" <invalid base_type ref: {0:x}>", Operands[Operand]);
96 }
97}
98
100 DIDumpOptions DumpOpts, const DWARFExpression *Expr,
101 DWARFUnit *U) {
102 if (Op->isError()) {
103 if (!DumpOpts.PrintRegisterOnly)
104 OS << "<decoding error>";
105 return false;
106 }
107
108 std::optional<unsigned> SubOpcode = Op->getSubCode();
109
110 // In "register-only" mode, still show simple constant-valued locations.
111 // This lets clients print annotations like "i = 0" when the location is
112 // a constant (e.g. DW_OP_constu/consts ... DW_OP_stack_value).
113 // We continue to suppress all other non-register ops in this mode.
114 if (DumpOpts.PrintRegisterOnly) {
115 // First, try pretty-printing registers (existing behavior below also does
116 // this, but we need to short-circuit here to avoid printing opcode names).
117 if ((Op->getCode() >= DW_OP_breg0 && Op->getCode() <= DW_OP_breg31) ||
118 (Op->getCode() >= DW_OP_reg0 && Op->getCode() <= DW_OP_reg31) ||
119 Op->getCode() == DW_OP_bregx || Op->getCode() == DW_OP_regx ||
120 Op->getCode() == DW_OP_regval_type ||
121 SubOpcode == DW_OP_LLVM_call_frame_entry_reg ||
122 SubOpcode == DW_OP_LLVM_aspace_bregx) {
123 if (prettyPrintRegisterOp(U, OS, DumpOpts, Op->getCode(),
124 Op->getRawOperands()))
125 return true;
126 // If we couldn't pretty-print, fall through and suppress.
127 }
128
129 // Show constants (decimal), suppress everything else.
130 if (Op->getCode() == DW_OP_constu) {
131 OS << (uint64_t)Op->getRawOperand(0);
132 return true;
133 }
134 if (Op->getCode() == DW_OP_consts) {
135 OS << (int64_t)Op->getRawOperand(0);
136 return true;
137 }
138 if (Op->getCode() >= DW_OP_lit0 && Op->getCode() <= DW_OP_lit31) {
139 OS << (unsigned)(Op->getCode() - DW_OP_lit0);
140 return true;
141 }
142 if (Op->getCode() == DW_OP_stack_value)
143 return true; // metadata; don't print a token
144
145 return true; // suppress other opcodes silently in register-only mode
146 }
147
148 if (!DumpOpts.PrintRegisterOnly) {
149 StringRef Name = OperationEncodingString(Op->getCode());
150 assert(!Name.empty() && "DW_OP has no name!");
151 OS << Name;
152
153 if (SubOpcode) {
154 StringRef SubName = SubOperationEncodingString(Op->getCode(), *SubOpcode);
155 assert(!SubName.empty() && "DW_OP SubOp has no name!");
156 OS << ' ' << SubName;
157 }
158 }
159
160 if ((Op->getCode() >= DW_OP_breg0 && Op->getCode() <= DW_OP_breg31) ||
161 (Op->getCode() >= DW_OP_reg0 && Op->getCode() <= DW_OP_reg31) ||
162 Op->getCode() == DW_OP_bregx || Op->getCode() == DW_OP_regx ||
163 Op->getCode() == DW_OP_regval_type ||
164 SubOpcode == DW_OP_LLVM_call_frame_entry_reg ||
165 SubOpcode == DW_OP_LLVM_aspace_bregx)
166 if (prettyPrintRegisterOp(U, OS, DumpOpts, Op->getCode(),
167 Op->getRawOperands()))
168 return true;
169
170 if (!DumpOpts.PrintRegisterOnly) {
171 for (unsigned Operand = 0; Operand < Op->getDescription().Op.size();
172 ++Operand) {
173 unsigned Size = Op->getDescription().Op[Operand];
175
177 assert(Operand == 0 && "DW_OP SubOp must be the first operand");
178 assert(SubOpcode && "DW_OP SubOp description is inconsistent");
180 // For DW_OP_convert the operand may be 0 to indicate that conversion to
181 // the generic type should be done. The same holds for
182 // DW_OP_reinterpret, which is currently not supported.
183 if (Op->getCode() == DW_OP_convert && Op->getRawOperand(Operand) == 0)
184 OS << " 0x0";
185 else
186 prettyPrintBaseTypeRef(U, OS, DumpOpts, Op->getRawOperands(),
187 Operand);
189 assert(Operand == 1);
190 switch (Op->getRawOperand(0)) {
191 case 0:
192 case 1:
193 case 2:
194 case 3: // global as uint32
195 case 4:
196 OS << formatv(" {0:x}", Op->getRawOperand(Operand));
197 break;
198 default:
199 assert(false);
200 }
202 uint64_t Offset = Op->getRawOperand(Operand);
203 for (unsigned i = 0; i < Op->getRawOperand(Operand - 1); ++i)
204 OS << formatv(" {0:x2}",
205 static_cast<uint8_t>(Expr->getData()[Offset++]));
206 } else {
207 if (Signed)
208 OS << formatv(" {0:+d}", (int64_t)Op->getRawOperand(Operand));
209 else if (Op->getCode() != DW_OP_entry_value &&
210 Op->getCode() != DW_OP_GNU_entry_value)
211 OS << formatv(" {0:x}", Op->getRawOperand(Operand));
212 }
213 }
214 }
215 return true;
216}
217
219 DIDumpOptions DumpOpts, DWARFUnit *U, bool IsEH) {
220 uint32_t EntryValExprSize = 0;
221 uint64_t EntryValStartOffset = 0;
222 if (E->getData().empty())
223 OS << "<empty>";
224
225 for (auto &Op : *E) {
226 DumpOpts.IsEH = IsEH;
227 if (!printOp(&Op, OS, DumpOpts, E, U) && !DumpOpts.PrintRegisterOnly) {
228 uint64_t FailOffset = Op.getEndOffset();
229 while (FailOffset < E->getData().size())
230 OS << formatv(" {0:x-2}",
231 static_cast<uint8_t>(E->getData()[FailOffset++]));
232 return;
233 }
234 if (!DumpOpts.PrintRegisterOnly) {
235 if (Op.getCode() == DW_OP_entry_value ||
236 Op.getCode() == DW_OP_GNU_entry_value) {
237 OS << "(";
238 EntryValExprSize = Op.getRawOperand(0);
239 EntryValStartOffset = Op.getEndOffset();
240 continue;
241 }
242
243 if (EntryValExprSize) {
244 EntryValExprSize -= Op.getEndOffset() - EntryValStartOffset;
245 if (EntryValExprSize == 0)
246 OS << ")";
247 }
248
249 if (Op.getEndOffset() < E->getData().size())
250 OS << ", ";
251 }
252 }
253}
254
255/// A user-facing string representation of a DWARF expression. This might be an
256/// Address expression, in which case it will be implicitly dereferenced, or a
257/// Value expression.
268
272 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg =
273 nullptr) {
275
276 auto UnknownOpcode = [](raw_ostream &OS, uint8_t Opcode,
277 std::optional<unsigned> SubOpcode) -> bool {
278 // If we hit an unknown operand, we don't know its effect on the stack,
279 // so bail out on the whole expression.
280 OS << "<unknown op " << dwarf::OperationEncodingString(Opcode) << " ("
281 << (int)Opcode;
282 if (SubOpcode)
283 OS << ") subop " << dwarf::SubOperationEncodingString(Opcode, *SubOpcode)
284 << " (" << *SubOpcode;
285 OS << ")>";
286 return false;
287 };
288
289 // Keep the diagnostic in the compact printer so every register form reports
290 // failure only after resolveRegName has tried to get a target name and decode
291 // an ASCII-packed name.
292 auto UnknownRegister = [](raw_ostream &OS, uint64_t DwarfRegNum) -> bool {
293 OS << "<unknown register " << DwarfRegNum << ">";
294 return false;
295 };
296
297 while (I != E) {
299 uint8_t Opcode = Op.getCode();
300 switch (Opcode) {
301 case dwarf::DW_OP_regx: {
302 // DW_OP_regx: A register, with the register num given as an operand.
303 // Printed as the plain register name.
304 const uint64_t DwarfRegNum = Op.getRawOperand(0);
305 std::string RegName =
306 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
307 if (RegName.empty())
308 return UnknownRegister(OS, DwarfRegNum);
309 raw_svector_ostream S(Stack.emplace_back(PrintedExpr::Value).String);
310 S << RegName;
311 break;
312 }
313 case dwarf::DW_OP_bregx: {
314 const uint64_t DwarfRegNum = Op.getRawOperand(0);
315 const uint64_t Offset = Op.getRawOperand(1);
316 std::string RegName =
317 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
318 if (RegName.empty())
319 return UnknownRegister(OS, DwarfRegNum);
320 raw_svector_ostream S(Stack.emplace_back().String);
321 S << RegName;
322 if (Offset)
323 S << formatv("{0:+d}", Offset);
324 break;
325 }
326 case dwarf::DW_OP_entry_value:
327 case dwarf::DW_OP_GNU_entry_value: {
328 // DW_OP_entry_value contains a sub-expression which must be rendered
329 // separately.
330 uint64_t SubExprLength = Op.getRawOperand(0);
331 DWARFExpression::iterator SubExprEnd = I.skipBytes(SubExprLength);
332 ++I;
333
334 SmallString<16> SubExpr;
335 raw_svector_ostream SubExprOS(SubExpr);
336 // Keep the subexpression separate so we can copy its diagnostic on
337 // failure without leaving a partial entry(...) in the output.
338 if (!printCompactDWARFExpr(SubExprOS, I, SubExprEnd,
339 GetNameForDWARFReg)) {
340 OS << SubExprOS.str();
341 return false;
342 }
343
344 raw_svector_ostream S(Stack.emplace_back().String);
345 S << "entry(" << SubExprOS.str() << ")";
346 I = SubExprEnd;
347 continue;
348 }
349 case dwarf::DW_OP_stack_value: {
350 // The top stack entry should be treated as the actual value of tne
351 // variable, rather than the address of the variable in memory.
352 assert(!Stack.empty());
353 Stack.back().Kind = PrintedExpr::Value;
354 break;
355 }
356 case dwarf::DW_OP_nop: {
357 break;
358 }
359 case dwarf::DW_OP_LLVM_user: {
360 std::optional<unsigned> SubOpcode = Op.getSubCode();
361 if (SubOpcode == dwarf::DW_OP_LLVM_nop)
362 break;
363 return UnknownOpcode(OS, Opcode, SubOpcode);
364 }
365 default:
366 if (Opcode >= dwarf::DW_OP_reg0 && Opcode <= dwarf::DW_OP_reg31) {
367 // DW_OP_reg<N>: A register, with the register num implied by the
368 // opcode. Printed as the plain register name.
369 uint64_t DwarfRegNum = Opcode - dwarf::DW_OP_reg0;
370 std::string RegName =
371 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
372 if (RegName.empty())
373 return UnknownRegister(OS, DwarfRegNum);
374 raw_svector_ostream S(Stack.emplace_back(PrintedExpr::Value).String);
375 S << RegName;
376 } else if (Opcode >= dwarf::DW_OP_breg0 &&
377 Opcode <= dwarf::DW_OP_breg31) {
378 int DwarfRegNum = Opcode - dwarf::DW_OP_breg0;
379 int64_t Offset = Op.getRawOperand(0);
380 std::string RegName =
381 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
382 if (RegName.empty())
383 return UnknownRegister(OS, DwarfRegNum);
384 raw_svector_ostream S(Stack.emplace_back().String);
385 S << RegName;
386 if (Offset)
387 S << formatv("{0:+d}", Offset);
388 } else {
389 return UnknownOpcode(OS, Opcode, std::nullopt);
390 }
391 break;
392 }
393 ++I;
394 }
395
396 if (Stack.size() != 1) {
397 OS << "<stack of size " << Stack.size() << ", expected 1>";
398 return false;
399 }
400
401 if (Stack.front().Kind == PrintedExpr::Address)
402 OS << "[" << Stack.front().String << "]";
403 else
404 OS << Stack.front().String;
405
406 return true;
407}
408
410 const DWARFExpression *E, raw_ostream &OS,
411 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg) {
412 return printCompactDWARFExpr(OS, E->begin(), E->end(), GetNameForDWARFReg);
413}
414
416 DIDumpOptions DumpOpts, uint8_t Opcode,
418 uint64_t DwarfRegNum;
419 unsigned OpNum = 0;
420
421 std::optional<unsigned> SubOpcode;
422 if (Opcode == DW_OP_LLVM_user)
423 SubOpcode = Operands[OpNum++];
424
425 const bool RegNumFromOperand =
426 Opcode == DW_OP_bregx || Opcode == DW_OP_regx ||
427 Opcode == DW_OP_regval_type || SubOpcode == DW_OP_LLVM_aspace_bregx ||
428 SubOpcode == DW_OP_LLVM_call_frame_entry_reg;
429
430 if (RegNumFromOperand)
431 DwarfRegNum = Operands[OpNum++];
432 else if (Opcode >= DW_OP_breg0 && Opcode < DW_OP_bregx)
433 DwarfRegNum = Opcode - DW_OP_breg0;
434 else
435 DwarfRegNum = Opcode - DW_OP_reg0;
436
437 std::string RegName =
438 resolveRegName(DwarfRegNum, DumpOpts.IsEH, DumpOpts.GetNameForDWARFReg);
439
440 if (!RegName.empty()) {
441 if ((Opcode >= DW_OP_breg0 && Opcode <= DW_OP_breg31) ||
442 Opcode == DW_OP_bregx || SubOpcode == DW_OP_LLVM_aspace_bregx)
443 OS << ' ' << RegName << formatv("{0:+d}", int64_t(Operands[OpNum]));
444 else
445 OS << ' ' << RegName;
446
447 if (Opcode == DW_OP_regval_type)
448 prettyPrintBaseTypeRef(U, OS, DumpOpts, Operands, 1);
449 return true;
450 }
451
452 return false;
453}
454
455} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define RegName(no)
#define I(x, y, z)
Definition MD5.cpp:57
SI Fold Operands
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class represents an Operation in the Expression.
@ SizeSubOpLEB
The operand is a ULEB128 encoded SubOpcode.
@ SizeBlock
Preceding operand contains block size.
An iterator to go through the expression operations.
StringRef getData() const
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
LLVM_ABI StringRef SubOperationEncodingString(unsigned OpEncoding, unsigned SubOpEncoding)
Definition Dwarf.cpp:203
LLVM_ABI StringRef OperationEncodingString(unsigned Encoding)
Definition Dwarf.cpp:138
Calculates the starting offsets for various sections within the .debug_names section.
Definition Dwarf.h:35
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
value_type byte_swap(value_type value, endianness endian)
Swap the bytes of value to match the given endianness.
Definition Endian.h:45
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
static bool printOp(const DWARFExpression::Operation *Op, raw_ostream &OS, DIDumpOptions DumpOpts, const DWARFExpression *Expr, DWARFUnit *U)
LLVM_ABI void printDwarfExpression(const DWARFExpression *E, raw_ostream &OS, DIDumpOptions DumpOpts, DWARFUnit *U, bool IsEH=false)
Print a Dwarf expression/.
Op::Description Desc
static bool printCompactDWARFExpr(raw_ostream &OS, DWARFExpression::iterator I, const DWARFExpression::iterator E, std::function< StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg=nullptr)
static void prettyPrintBaseTypeRef(DWARFUnit *U, raw_ostream &OS, DIDumpOptions DumpOpts, ArrayRef< uint64_t > Operands, unsigned Operand)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
static bool decodeVirtualRegisterName(uint64_t DwarfRegNum, SmallString< 8 > &Out)
Some backends (e.g.
bool isAlnum(char C)
Checks whether character C is either a decimal digit or an uppercase or lowercase letter as classifie...
static std::string resolveRegName(uint64_t DwarfRegNum, bool IsEH, const std::function< StringRef(uint64_t, bool)> &GetNameForDWARFReg)
Resolves a DWARF register number to a display name: first via GetNameForDWARFReg (MC register names),...
DWARFExpression::Operation Op
LLVM_ABI bool prettyPrintRegisterOp(DWARFUnit *U, raw_ostream &OS, DIDumpOptions DumpOpts, uint8_t Opcode, ArrayRef< uint64_t > Operands)
Pretty print a register opcode and operands.
LLVM_ABI bool printDwarfExpressionCompact(const DWARFExpression *E, raw_ostream &OS, std::function< StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg=nullptr)
Print the expression in a format intended to be compact and useful to a user, but not perfectly unamb...
Container for dump options that control which debug information will be dumped.
Definition DIContext.h:196
std::function< llvm::StringRef(uint64_t DwarfRegNum, bool IsEH)> GetNameForDWARFReg
Definition DIContext.h:217
Description of the encoding of one expression Op.
PrintedExpr(ExprKind K=Address)