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