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
15#include "llvm/Support/Endian.h"
17#include <cassert>
18#include <cstdint>
19
20using namespace llvm;
21using namespace dwarf;
22
23namespace llvm {
24
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, const DWARFExpression *Expr,
79 detail::BaseTypeRefPrinter PrintBaseTypeRef) {
80 if (Op->isError()) {
81 if (!DumpOpts.PrintRegisterOnly)
82 OS << "<decoding error>";
83 return false;
84 }
85
86 std::optional<unsigned> SubOpcode = Op->getSubCode();
87
88 // In "register-only" mode, still show simple constant-valued locations.
89 // This lets clients print annotations like "i = 0" when the location is
90 // a constant (e.g. DW_OP_constu/consts ... DW_OP_stack_value).
91 // We continue to suppress all other non-register ops in this mode.
92 if (DumpOpts.PrintRegisterOnly) {
93 // First, try pretty-printing registers (existing behavior below also does
94 // this, but we need to short-circuit here to avoid printing opcode names).
95 if ((Op->getCode() >= DW_OP_breg0 && Op->getCode() <= DW_OP_breg31) ||
96 (Op->getCode() >= DW_OP_reg0 && Op->getCode() <= DW_OP_reg31) ||
97 Op->getCode() == DW_OP_bregx || Op->getCode() == DW_OP_regx ||
98 Op->getCode() == DW_OP_regval_type ||
99 SubOpcode == DW_OP_LLVM_call_frame_entry_reg ||
100 SubOpcode == DW_OP_LLVM_aspace_bregx) {
101 if (detail::prettyPrintRegisterOp(PrintBaseTypeRef, OS, DumpOpts,
102 Op->getCode(), Op->getRawOperands()))
103 return true;
104 // If we couldn't pretty-print, fall through and suppress.
105 }
106
107 // Show constants (decimal), suppress everything else.
108 if (Op->getCode() == DW_OP_constu) {
109 OS << (uint64_t)Op->getRawOperand(0);
110 return true;
111 }
112 if (Op->getCode() == DW_OP_consts) {
113 OS << (int64_t)Op->getRawOperand(0);
114 return true;
115 }
116 if (Op->getCode() >= DW_OP_lit0 && Op->getCode() <= DW_OP_lit31) {
117 OS << (unsigned)(Op->getCode() - DW_OP_lit0);
118 return true;
119 }
120 if (Op->getCode() == DW_OP_stack_value)
121 return true; // metadata; don't print a token
122
123 return true; // suppress other opcodes silently in register-only mode
124 }
125
126 if (!DumpOpts.PrintRegisterOnly) {
127 StringRef Name = OperationEncodingString(Op->getCode());
128 assert(!Name.empty() && "DW_OP has no name!");
129 OS << Name;
130
131 if (SubOpcode) {
132 StringRef SubName = SubOperationEncodingString(Op->getCode(), *SubOpcode);
133 assert(!SubName.empty() && "DW_OP SubOp has no name!");
134 OS << ' ' << SubName;
135 }
136 }
137
138 if ((Op->getCode() >= DW_OP_breg0 && Op->getCode() <= DW_OP_breg31) ||
139 (Op->getCode() >= DW_OP_reg0 && Op->getCode() <= DW_OP_reg31) ||
140 Op->getCode() == DW_OP_bregx || Op->getCode() == DW_OP_regx ||
141 Op->getCode() == DW_OP_regval_type ||
142 SubOpcode == DW_OP_LLVM_call_frame_entry_reg ||
143 SubOpcode == DW_OP_LLVM_aspace_bregx)
144 if (detail::prettyPrintRegisterOp(PrintBaseTypeRef, OS, DumpOpts,
145 Op->getCode(), Op->getRawOperands()))
146 return true;
147
148 if (!DumpOpts.PrintRegisterOnly) {
149 for (unsigned Operand = 0; Operand < Op->getDescription().Op.size();
150 ++Operand) {
151 unsigned Size = Op->getDescription().Op[Operand];
153
155 assert(Operand == 0 && "DW_OP SubOp must be the first operand");
156 assert(SubOpcode && "DW_OP SubOp description is inconsistent");
158 PrintBaseTypeRef) {
159 // For DW_OP_convert the operand may be 0 to indicate that conversion to
160 // the generic type should be done. The same holds for
161 // DW_OP_reinterpret, which is currently not supported.
162 if (Op->getCode() == DW_OP_convert && Op->getRawOperand(Operand) == 0)
163 OS << " 0x0";
164 else
165 PrintBaseTypeRef(OS, DumpOpts, Op->getRawOperands(), Operand);
167 assert(Operand == 1);
168 switch (Op->getRawOperand(0)) {
169 case 0:
170 case 1:
171 case 2:
172 case 3: // global as uint32
173 case 4:
174 OS << formatv(" {0:x}", Op->getRawOperand(Operand));
175 break;
176 default:
177 assert(false);
178 }
180 uint64_t Offset = Op->getRawOperand(Operand);
181 for (unsigned i = 0; i < Op->getRawOperand(Operand - 1); ++i)
182 OS << formatv(" {0:x2}",
183 static_cast<uint8_t>(Expr->getData()[Offset++]));
184 } else {
185 if (Signed)
186 OS << formatv(" {0:+d}", (int64_t)Op->getRawOperand(Operand));
187 else if (Op->getCode() != DW_OP_entry_value &&
188 Op->getCode() != DW_OP_GNU_entry_value)
189 OS << formatv(" {0:x}", Op->getRawOperand(Operand));
190 }
191 }
192 }
193 return true;
194}
195
197 DIDumpOptions DumpOpts,
198 BaseTypeRefPrinter PrintBaseTypeRef,
199 bool IsEH) {
200 uint32_t EntryValExprSize = 0;
201 uint64_t EntryValStartOffset = 0;
202 if (E->getData().empty())
203 OS << "<empty>";
204
205 for (auto &Op : *E) {
206 DumpOpts.IsEH = IsEH;
207 if (!printOp(&Op, OS, DumpOpts, E, PrintBaseTypeRef) &&
208 !DumpOpts.PrintRegisterOnly) {
209 uint64_t FailOffset = Op.getEndOffset();
210 while (FailOffset < E->getData().size())
211 OS << formatv(" {0:x-2}",
212 static_cast<uint8_t>(E->getData()[FailOffset++]));
213 return;
214 }
215 if (!DumpOpts.PrintRegisterOnly) {
216 if (Op.getCode() == DW_OP_entry_value ||
217 Op.getCode() == DW_OP_GNU_entry_value) {
218 OS << "(";
219 EntryValExprSize = Op.getRawOperand(0);
220 EntryValStartOffset = Op.getEndOffset();
221 continue;
222 }
223
224 if (EntryValExprSize) {
225 EntryValExprSize -= Op.getEndOffset() - EntryValStartOffset;
226 if (EntryValExprSize == 0)
227 OS << ")";
228 }
229
230 if (Op.getEndOffset() < E->getData().size())
231 OS << ", ";
232 }
233 }
234}
235
236/// A user-facing string representation of a DWARF expression. This might be an
237/// Address expression, in which case it will be implicitly dereferenced, or a
238/// Value expression.
249
253 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg =
254 nullptr) {
256
257 auto UnknownOpcode = [](raw_ostream &OS, uint8_t Opcode,
258 std::optional<unsigned> SubOpcode) -> bool {
259 // If we hit an unknown operand, we don't know its effect on the stack,
260 // so bail out on the whole expression.
261 OS << "<unknown op " << dwarf::OperationEncodingString(Opcode) << " ("
262 << (int)Opcode;
263 if (SubOpcode)
264 OS << ") subop " << dwarf::SubOperationEncodingString(Opcode, *SubOpcode)
265 << " (" << *SubOpcode;
266 OS << ")>";
267 return false;
268 };
269
270 // Keep the diagnostic in the compact printer so every register form reports
271 // failure only after resolveRegName has tried to get a target name and decode
272 // an ASCII-packed name.
273 auto UnknownRegister = [](raw_ostream &OS, uint64_t DwarfRegNum) -> bool {
274 OS << "<unknown register " << DwarfRegNum << ">";
275 return false;
276 };
277
278 while (I != E) {
280 uint8_t Opcode = Op.getCode();
281 switch (Opcode) {
282 case dwarf::DW_OP_regx: {
283 // DW_OP_regx: A register, with the register num given as an operand.
284 // Printed as the plain register name.
285 const uint64_t DwarfRegNum = Op.getRawOperand(0);
286 std::string RegName =
287 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
288 if (RegName.empty())
289 return UnknownRegister(OS, DwarfRegNum);
290 raw_svector_ostream S(Stack.emplace_back(PrintedExpr::Value).String);
291 S << RegName;
292 break;
293 }
294 case dwarf::DW_OP_bregx: {
295 const uint64_t DwarfRegNum = Op.getRawOperand(0);
296 const uint64_t Offset = Op.getRawOperand(1);
297 std::string RegName =
298 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
299 if (RegName.empty())
300 return UnknownRegister(OS, DwarfRegNum);
301 raw_svector_ostream S(Stack.emplace_back().String);
302 S << RegName;
303 if (Offset)
304 S << formatv("{0:+d}", Offset);
305 break;
306 }
307 case dwarf::DW_OP_entry_value:
308 case dwarf::DW_OP_GNU_entry_value: {
309 // DW_OP_entry_value contains a sub-expression which must be rendered
310 // separately.
311 uint64_t SubExprLength = Op.getRawOperand(0);
312 DWARFExpression::iterator SubExprEnd = I.skipBytes(SubExprLength);
313 ++I;
314
315 SmallString<16> SubExpr;
316 raw_svector_ostream SubExprOS(SubExpr);
317 // Keep the subexpression separate so we can copy its diagnostic on
318 // failure without leaving a partial entry(...) in the output.
319 if (!printCompactDWARFExpr(SubExprOS, I, SubExprEnd,
320 GetNameForDWARFReg)) {
321 OS << SubExprOS.str();
322 return false;
323 }
324
325 raw_svector_ostream S(Stack.emplace_back().String);
326 S << "entry(" << SubExprOS.str() << ")";
327 I = SubExprEnd;
328 continue;
329 }
330 case dwarf::DW_OP_stack_value: {
331 // The top stack entry should be treated as the actual value of tne
332 // variable, rather than the address of the variable in memory.
333 assert(!Stack.empty());
334 Stack.back().Kind = PrintedExpr::Value;
335 break;
336 }
337 case dwarf::DW_OP_nop: {
338 break;
339 }
340 case dwarf::DW_OP_LLVM_user: {
341 std::optional<unsigned> SubOpcode = Op.getSubCode();
342 if (SubOpcode == dwarf::DW_OP_LLVM_nop)
343 break;
344 return UnknownOpcode(OS, Opcode, SubOpcode);
345 }
346 default:
347 if (Opcode >= dwarf::DW_OP_reg0 && Opcode <= dwarf::DW_OP_reg31) {
348 // DW_OP_reg<N>: A register, with the register num implied by the
349 // opcode. Printed as the plain register name.
350 uint64_t DwarfRegNum = Opcode - dwarf::DW_OP_reg0;
351 std::string RegName =
352 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
353 if (RegName.empty())
354 return UnknownRegister(OS, DwarfRegNum);
355 raw_svector_ostream S(Stack.emplace_back(PrintedExpr::Value).String);
356 S << RegName;
357 } else if (Opcode >= dwarf::DW_OP_breg0 &&
358 Opcode <= dwarf::DW_OP_breg31) {
359 int DwarfRegNum = Opcode - dwarf::DW_OP_breg0;
360 int64_t Offset = Op.getRawOperand(0);
361 std::string RegName =
362 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
363 if (RegName.empty())
364 return UnknownRegister(OS, DwarfRegNum);
365 raw_svector_ostream S(Stack.emplace_back().String);
366 S << RegName;
367 if (Offset)
368 S << formatv("{0:+d}", Offset);
369 } else {
370 return UnknownOpcode(OS, Opcode, std::nullopt);
371 }
372 break;
373 }
374 ++I;
375 }
376
377 if (Stack.size() != 1) {
378 OS << "<stack of size " << Stack.size() << ", expected 1>";
379 return false;
380 }
381
382 if (Stack.front().Kind == PrintedExpr::Address)
383 OS << "[" << Stack.front().String << "]";
384 else
385 OS << Stack.front().String;
386
387 return true;
388}
389
391 DIDumpOptions DumpOpts, bool IsEH) {
392 detail::printDwarfExpression(E, OS, DumpOpts, nullptr, IsEH);
393}
394
396 const DWARFExpression *E, raw_ostream &OS,
397 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg) {
398 return printCompactDWARFExpr(OS, E->begin(), E->end(), GetNameForDWARFReg);
399}
400
402 raw_ostream &OS, DIDumpOptions DumpOpts,
403 uint8_t Opcode,
405 uint64_t DwarfRegNum;
406 unsigned OpNum = 0;
407
408 std::optional<unsigned> SubOpcode;
409 if (Opcode == DW_OP_LLVM_user)
410 SubOpcode = Operands[OpNum++];
411
412 const bool RegNumFromOperand =
413 Opcode == DW_OP_bregx || Opcode == DW_OP_regx ||
414 Opcode == DW_OP_regval_type || SubOpcode == DW_OP_LLVM_aspace_bregx ||
415 SubOpcode == DW_OP_LLVM_call_frame_entry_reg;
416
417 if (RegNumFromOperand)
418 DwarfRegNum = Operands[OpNum++];
419 else if (Opcode >= DW_OP_breg0 && Opcode < DW_OP_bregx)
420 DwarfRegNum = Opcode - DW_OP_breg0;
421 else
422 DwarfRegNum = Opcode - DW_OP_reg0;
423
424 std::string RegName =
425 resolveRegName(DwarfRegNum, DumpOpts.IsEH, DumpOpts.GetNameForDWARFReg);
426
427 if (!RegName.empty()) {
428 if ((Opcode >= DW_OP_breg0 && Opcode <= DW_OP_breg31) ||
429 Opcode == DW_OP_bregx || SubOpcode == DW_OP_LLVM_aspace_bregx)
430 OS << ' ' << RegName << formatv("{0:+d}", int64_t(Operands[OpNum]));
431 else
432 OS << ' ' << RegName;
433
434 if (Opcode == DW_OP_regval_type) {
435 if (PrintBaseTypeRef)
436 PrintBaseTypeRef(OS, DumpOpts, Operands, 1);
437 else
438 OS << formatv(" <base_type ref: {0:x}>", Operands[1]);
439 }
440 return true;
441 }
442
443 return false;
444}
445
446} // 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
bool prettyPrintRegisterOp(BaseTypeRefPrinter PrintBaseTypeRef, raw_ostream &OS, DIDumpOptions DumpOpts, uint8_t Opcode, ArrayRef< uint64_t > Operands)
function_ref< void(raw_ostream &OS, DIDumpOptions DumpOpts, ArrayRef< uint64_t > Operands, unsigned Operand)> BaseTypeRefPrinter
Prints the base type DIE that operand Operand of Operands refers to.
void printDwarfExpression(const DWARFExpression *E, raw_ostream &OS, DIDumpOptions DumpOpts, BaseTypeRefPrinter PrintBaseTypeRef, bool IsEH)
Calculates the starting offsets for various sections within the .debug_names section.
Definition Dwarf.h:35
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.
LLVM_ABI void printDwarfExpression(const DWARFExpression *E, raw_ostream &OS, DIDumpOptions DumpOpts, bool IsEH=false)
Print a Dwarf expression.
@ 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:1685
static bool printOp(const DWARFExpression::Operation *Op, raw_ostream &OS, DIDumpOptions DumpOpts, const DWARFExpression *Expr, detail::BaseTypeRefPrinter PrintBaseTypeRef)
static bool printCompactDWARFExpr(raw_ostream &OS, DWARFExpression::iterator I, const DWARFExpression::iterator E, std::function< StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg=nullptr)
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 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:197
std::function< llvm::StringRef(uint64_t DwarfRegNum, bool IsEH)> GetNameForDWARFReg
Definition DIContext.h:218
PrintedExpr(ExprKind K=Address)