1//===- llvm/CodeGen/DwarfExpression.h - Dwarf Compile Unit ------*- 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// This file contains support for writing dwarf compile unit.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DWARFEXPRESSION_H
14#define LLVM_LIB_CODEGEN_ASMPRINTER_DWARFEXPRESSION_H
15
16#include "ByteStreamer.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/IR/DebugInfoMetadata.h"
20#include <cassert>
21#include <cstdint>
22#include <optional>
23
24namespace llvm {
25
26class AsmPrinter;
27class APInt;
28class DwarfCompileUnit;
29class DIELoc;
30class GlobalValue;
31class TargetRegisterInfo;
32class MachineLocation;
33
34/// Base class containing the logic for constructing DWARF expressions
35/// independently of whether they are emitted into a DIE or into a .debug_loc
36/// entry.
37///
38/// Some DWARF operations, e.g. DW_OP_entry_value, need to calculate the size
39/// of a succeeding DWARF block before the latter is emitted to the output.
40/// To handle such cases, data can conditionally be emitted to a temporary
41/// buffer, which can later on be committed to the main output. The size of the
42/// temporary buffer is queryable, allowing for the size of the data to be
43/// emitted before the data is committed.
44class DwarfExpression {
45protected:
46 /// Holds information about all subregisters comprising a register location.
47 struct Register {
48 int64_t DwarfRegNo;
49 unsigned SubRegSize;
50 const char *Comment;
51
52 /// Create a full register, no extra DW_OP_piece operators necessary.
53 static Register createRegister(int64_t RegNo, const char *Comment) {
54 return {.DwarfRegNo: RegNo, .SubRegSize: 0, .Comment: Comment};
55 }
56
57 /// Create a subregister that needs a DW_OP_piece operator with SizeInBits.
58 static Register createSubRegister(int64_t RegNo, unsigned SizeInBits,
59 const char *Comment) {
60 return {.DwarfRegNo: RegNo, .SubRegSize: SizeInBits, .Comment: Comment};
61 }
62
63 bool isSubRegister() const { return SubRegSize; }
64 };
65
66 /// Whether we are currently emitting an entry value operation.
67 bool IsEmittingEntryValue = false;
68
69 DwarfCompileUnit &CU;
70
71 /// The register location, if any.
72 SmallVector<Register, 2> DwarfRegs;
73
74 /// Current Fragment Offset in Bits.
75 uint64_t OffsetInBits = 0;
76
77 /// Sometimes we need to add a DW_OP_bit_piece to describe a subregister.
78 unsigned SubRegisterSizeInBits : 16;
79 unsigned SubRegisterOffsetInBits : 16;
80
81 /// The kind of location description being produced.
82 enum { Unknown = 0, Register, Memory, Implicit };
83
84 /// Additional location flags which may be combined with any location kind.
85 /// Currently, entry values are not supported for the Memory location kind.
86 enum { EntryValue = 1 << 0, Indirect = 1 << 1, CallSiteParamValue = 1 << 2 };
87
88 unsigned LocationKind : 3;
89 unsigned SavedLocationKind : 3;
90 unsigned LocationFlags : 3;
91 unsigned DwarfVersion : 4;
92
93public:
94 /// Set the location (\p Loc) and \ref DIExpression (\p DIExpr) to describe.
95 void setLocation(const MachineLocation &Loc, const DIExpression *DIExpr);
96
97 bool isUnknownLocation() const { return LocationKind == Unknown; }
98
99 bool isMemoryLocation() const { return LocationKind == Memory; }
100
101 bool isRegisterLocation() const { return LocationKind == Register; }
102
103 bool isImplicitLocation() const { return LocationKind == Implicit; }
104
105 bool isEntryValue() const { return LocationFlags & EntryValue; }
106
107 bool isIndirect() const { return LocationFlags & Indirect; }
108
109 bool isParameterValue() { return LocationFlags & CallSiteParamValue; }
110
111 std::optional<uint8_t> TagOffset;
112
113protected:
114 /// Push a DW_OP_piece / DW_OP_bit_piece for emitting later, if one is needed
115 /// to represent a subregister.
116 void setSubRegisterPiece(unsigned SizeInBits, unsigned OffsetInBits) {
117 assert(SizeInBits < 65536 && OffsetInBits < 65536);
118 SubRegisterSizeInBits = SizeInBits;
119 SubRegisterOffsetInBits = OffsetInBits;
120 }
121
122 /// Emit shift/mask operations for the pending subregister. After the
123 /// operations are emitted, consume the pending subregister description by
124 /// clearing SubRegisterSizeInBits and SubRegisterOffsetInBits.
125 void maskSubRegister();
126
127 /// Output a dwarf operand and an optional assembler comment.
128 virtual void emitOp(uint8_t Op, const char *Comment = nullptr) = 0;
129
130 /// Emit a raw signed value.
131 virtual void emitSigned(int64_t Value) = 0;
132
133 /// Emit a raw unsigned value.
134 virtual void emitUnsigned(uint64_t Value) = 0;
135
136 virtual void emitData1(uint8_t Value) = 0;
137
138 virtual void emitBaseTypeRef(uint64_t Idx) = 0;
139
140 /// Whether a relocated address operand, as needed by DW_OP_addr, can be
141 /// emitted into this output form. A location list is backed by a plain byte
142 /// buffer, which cannot carry a relocation.
143 virtual bool supportsRelocatedAddress() const { return false; }
144
145 /// Whether a global's address is spelled through the address pool, whose
146 /// index is plain data, rather than as a relocated address.
147 bool usesAddressPool() const;
148
149 /// Emit a relocated address operand. Only called when
150 /// supportsRelocatedAddress() returns true.
151 virtual void emitRelocatedAddress(const MCSymbol *Sym) {
152 llvm_unreachable("relocated address unsupported by this output form");
153 }
154
155 /// Start emitting data to the temporary buffer. The data stored in the
156 /// temporary buffer can be committed to the main output using
157 /// commitTemporaryBuffer().
158 virtual void enableTemporaryBuffer() = 0;
159
160 /// Disable emission to the temporary buffer. This does not commit data
161 /// in the temporary buffer to the main output.
162 virtual void disableTemporaryBuffer() = 0;
163
164 /// Return the emitted size, in number of bytes, for the data stored in the
165 /// temporary buffer.
166 virtual unsigned getTemporaryBufferSize() = 0;
167
168 /// Commit the data stored in the temporary buffer to the main output.
169 virtual void commitTemporaryBuffer() = 0;
170
171 /// Emit a normalized unsigned constant.
172 void emitConstu(uint64_t Value);
173
174 /// Return whether the given machine register is the frame register in the
175 /// current function.
176 virtual bool isFrameRegister(const TargetRegisterInfo &TRI,
177 llvm::Register MachineReg) = 0;
178
179 /// Emit a DW_OP_reg operation. Note that this is only legal inside a DWARF
180 /// register location description.
181 void addReg(int64_t DwarfReg, const char *Comment = nullptr);
182
183 /// Emit a DW_OP_breg operation.
184 void addBReg(int64_t DwarfReg, int64_t Offset);
185
186 /// Emit DW_OP_fbreg <Offset>.
187 void addFBReg(int64_t Offset);
188
189 /// Emit a partial DWARF register operation.
190 ///
191 /// \param MachineReg The register number.
192 /// \param MaxSize If the register must be composed from
193 /// sub-registers this is an upper bound
194 /// for how many bits the emitted DW_OP_piece
195 /// may cover.
196 ///
197 /// If size and offset is zero an operation for the entire register is
198 /// emitted: Some targets do not provide a DWARF register number for every
199 /// register. If this is the case, this function will attempt to emit a DWARF
200 /// register by emitting a fragment of a super-register or by piecing together
201 /// multiple subregisters that alias the register.
202 ///
203 /// \return false if no DWARF register exists for MachineReg.
204 bool addMachineReg(const TargetRegisterInfo &TRI, llvm::Register MachineReg,
205 unsigned MaxSize = ~1U);
206
207 /// Emit a DW_OP_piece or DW_OP_bit_piece operation for a variable fragment.
208 /// \param OffsetInBits This is an optional offset into the location that
209 /// is at the top of the DWARF stack.
210 void addOpPiece(unsigned SizeInBits, unsigned OffsetInBits = 0);
211
212 /// Emit a shift-right dwarf operation.
213 void addShr(unsigned ShiftBy);
214
215 /// Emit a bitwise and dwarf operation.
216 void addAnd(unsigned Mask);
217
218 /// Emit a DW_OP_stack_value, if supported.
219 ///
220 /// The proper way to describe a constant value is DW_OP_constu <const>,
221 /// DW_OP_stack_value. Unfortunately, DW_OP_stack_value was not available
222 /// until DWARF 4, so we will continue to generate DW_OP_constu <const> for
223 /// DWARF 2 and DWARF 3. Technically, this is incorrect since DW_OP_const
224 /// <const> actually describes a value at a constant address, not a constant
225 /// value. However, in the past there was no better way to describe a
226 /// constant value, so the producers and consumers started to rely on
227 /// heuristics to disambiguate the value vs. location status of the
228 /// expression. See PR21176 for more details.
229 void addStackValue();
230
231 /// Finalize an entry value by emitting its size operand, and committing the
232 /// DWARF block which has been emitted to the temporary buffer.
233 void finalizeEntryValue();
234
235 /// Cancel the emission of an entry value.
236 void cancelEntryValue();
237
238 ~DwarfExpression() = default;
239
240public:
241 DwarfExpression(unsigned DwarfVersion, DwarfCompileUnit &CU)
242 : CU(CU), SubRegisterSizeInBits(0), SubRegisterOffsetInBits(0),
243 LocationKind(Unknown), SavedLocationKind(Unknown),
244 LocationFlags(Unknown), DwarfVersion(DwarfVersion) {}
245
246 /// This needs to be called last to commit any pending changes.
247 void finalize();
248
249 /// Emit a boolean constant.
250 void addBooleanConstant(int64_t Value);
251
252 /// Emit a signed constant.
253 void addSignedConstant(int64_t Value);
254
255 /// Emit an unsigned constant.
256 void addUnsignedConstant(uint64_t Value);
257
258 /// Emit an unsigned constant.
259 void addUnsignedConstant(const APInt &Value);
260
261 /// Emit an implicit value.
262 void addImplicitValue(const APInt &Value, const AsmPrinter &AP);
263
264 /// Emit an floating point constant.
265 void addConstantFP(const APFloat &Value, const AsmPrinter &AP);
266
267 /// Lock this down to become a memory location description.
268 void setMemoryLocationKind() {
269 assert(isUnknownLocation());
270 LocationKind = Memory;
271 }
272
273 /// Lock this down to become an entry value location.
274 void setEntryValueFlags(const MachineLocation &Loc);
275
276 /// Lock this down to become a call site parameter location.
277 void setCallSiteParamValueFlag() { LocationFlags |= CallSiteParamValue; }
278
279 /// Emit a machine register location. As an optimization this may also consume
280 /// the prefix of a DwarfExpression if a more efficient representation for
281 /// combining the register location and the first operation exists.
282 ///
283 /// \param FragmentOffsetInBits If this is one fragment out of a
284 /// fragmented
285 /// location, this is the offset of the
286 /// fragment inside the entire variable.
287 /// \return false if no DWARF register exists
288 /// for MachineReg.
289 bool addMachineRegExpression(const TargetRegisterInfo &TRI,
290 DIExpressionCursor &Expr,
291 llvm::Register MachineReg,
292 unsigned FragmentOffsetInBits = 0);
293
294 /// Begin emission of an entry value dwarf operation. The entry value's
295 /// first operand is the size of the DWARF block (its second operand),
296 /// which needs to be calculated at time of emission, so we don't emit
297 /// any operands here.
298 void beginEntryValueExpression(DIExpressionCursor &ExprCursor);
299
300 /// Return the index of a base type with the given properties and
301 /// create one if necessary.
302 unsigned getOrCreateBaseType(unsigned BitSize, dwarf::TypeKind Encoding);
303
304 /// Emit all remaining operations in the DIExpressionCursor. The
305 /// cursor must not contain any DW_OP_LLVM_arg operations. Returns false if
306 /// an operation could not be emitted, in which case the caller is
307 /// responsible for discarding the partial expression.
308 bool addExpression(DIExpressionCursor &&Expr);
309
310 /// Emit all remaining operations in the DIExpressionCursor.
311 /// DW_OP_LLVM_arg operations are resolved by calling (\p InsertArg).
312 //
313 /// \return false if any call to (\p InsertArg) returns false.
314 bool addExpression(
315 DIExpressionCursor &&Expr,
316 llvm::function_ref<bool(unsigned, DIExpressionCursor &)> InsertArg);
317
318 /// If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to
319 /// the fragment described by \c Expr.
320 void addFragmentOffset(const DIExpression *Expr);
321
322 void emitLegacySExt(unsigned FromBits);
323 void emitLegacyZExt(unsigned FromBits);
324
325 /// Emit location information expressed via WebAssembly location + offset
326 /// The Index is an identifier for locals, globals or operand stack.
327 void addWasmLocation(unsigned Index, uint64_t Offset);
328
329 /// Emit the address of \p GV displaced by \p Offset as an implicit location
330 /// description, i.e. as the value of the described entity rather than as the
331 /// address of its storage. Returns false if the address cannot be spelled in
332 /// this unit's DWARF.
333 bool addGlobalAddress(const GlobalValue *GV, int64_t Offset);
334
335 /// Whether addGlobalAddress() can spell a global's address at all. This
336 /// depends only on the DWARF version and the output form, not on the global,
337 /// so callers that cannot take back what they have already emitted can
338 /// settle it before emitting anything.
339 bool canAddGlobalAddress() const;
340};
341
342/// DwarfExpression implementation for .debug_loc entries.
343class DebugLocDwarfExpression final : public DwarfExpression {
344
345 struct TempBuffer {
346 SmallString<32> Bytes;
347 std::vector<std::string> Comments;
348 BufferByteStreamer BS;
349
350 TempBuffer(bool GenerateComments) : BS(Bytes, Comments, GenerateComments) {}
351 };
352
353 std::unique_ptr<TempBuffer> TmpBuf;
354 BufferByteStreamer &OutBS;
355 bool IsBuffering = false;
356
357 /// Return the byte streamer that currently is being emitted to.
358 ByteStreamer &getActiveStreamer() { return IsBuffering ? TmpBuf->BS : OutBS; }
359
360 void emitOp(uint8_t Op, const char *Comment = nullptr) override;
361 void emitSigned(int64_t Value) override;
362 void emitUnsigned(uint64_t Value) override;
363 void emitData1(uint8_t Value) override;
364 void emitBaseTypeRef(uint64_t Idx) override;
365
366 void enableTemporaryBuffer() override;
367 void disableTemporaryBuffer() override;
368 unsigned getTemporaryBufferSize() override;
369 void commitTemporaryBuffer() override;
370
371 bool isFrameRegister(const TargetRegisterInfo &TRI,
372 llvm::Register MachineReg) override;
373
374public:
375 DebugLocDwarfExpression(unsigned DwarfVersion, BufferByteStreamer &BS,
376 DwarfCompileUnit &CU)
377 : DwarfExpression(DwarfVersion, CU), OutBS(BS) {}
378};
379
380/// DwarfExpression implementation for singular DW_AT_location.
381class DIEDwarfExpression final : public DwarfExpression {
382 const AsmPrinter &AP;
383 DIELoc &OutDIE;
384 DIELoc TmpDIE;
385 bool IsBuffering = false;
386
387 /// Return the DIE that currently is being emitted to.
388 DIELoc &getActiveDIE() { return IsBuffering ? TmpDIE : OutDIE; }
389
390 void emitOp(uint8_t Op, const char *Comment = nullptr) override;
391 void emitSigned(int64_t Value) override;
392 void emitUnsigned(uint64_t Value) override;
393 void emitData1(uint8_t Value) override;
394 void emitBaseTypeRef(uint64_t Idx) override;
395
396 bool supportsRelocatedAddress() const override { return true; }
397 void emitRelocatedAddress(const MCSymbol *Sym) override;
398
399 void enableTemporaryBuffer() override;
400 void disableTemporaryBuffer() override;
401 unsigned getTemporaryBufferSize() override;
402 void commitTemporaryBuffer() override;
403
404 bool isFrameRegister(const TargetRegisterInfo &TRI,
405 llvm::Register MachineReg) override;
406
407public:
408 DIEDwarfExpression(const AsmPrinter &AP, DwarfCompileUnit &CU, DIELoc &DIE);
409
410 DIELoc *finalize() {
411 DwarfExpression::finalize();
412 return &OutDIE;
413 }
414};
415
416} // end namespace llvm
417
418#endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFEXPRESSION_H
419