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 "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include <cassert>
22 #include <cstdint>
23 #include <iterator>
24 
25 namespace llvm {
26 
27 class AsmPrinter;
28 class APInt;
29 class ByteStreamer;
30 class DwarfCompileUnit;
31 class DIELoc;
32 class TargetRegisterInfo;
33 
34 /// Holds a DIExpression and keeps track of how many operands have been consumed
35 /// so far.
36 class DIExpressionCursor {
37   DIExpression::expr_op_iterator Start, End;
38 
39 public:
40   DIExpressionCursor(const DIExpression *Expr) {
41     if (!Expr) {
42       assert(Start == End);
43       return;
44     }
45     Start = Expr->expr_op_begin();
46     End = Expr->expr_op_end();
47   }
48 
49   DIExpressionCursor(ArrayRef<uint64_t> Expr)
50       : Start(Expr.begin()), End(Expr.end()) {}
51 
52   DIExpressionCursor(const DIExpressionCursor &) = default;
53 
54   /// Consume one operation.
55   Optional<DIExpression::ExprOperand> take() {
56     if (Start == End)
57       return None;
58     return *(Start++);
59   }
60 
61   /// Consume N operations.
62   void consume(unsigned N) { std::advance(Start, N); }
63 
64   /// Return the current operation.
65   Optional<DIExpression::ExprOperand> peek() const {
66     if (Start == End)
67       return None;
68     return *(Start);
69   }
70 
71   /// Return the next operation.
72   Optional<DIExpression::ExprOperand> peekNext() const {
73     if (Start == End)
74       return None;
75 
76     auto Next = Start.getNext();
77     if (Next == End)
78       return None;
79 
80     return *Next;
81   }
82 
83   /// Determine whether there are any operations left in this expression.
84   operator bool() const { return Start != End; }
85 
86   DIExpression::expr_op_iterator begin() const { return Start; }
87   DIExpression::expr_op_iterator end() const { return End; }
88 
89   /// Retrieve the fragment information, if any.
90   Optional<DIExpression::FragmentInfo> getFragmentInfo() const {
91     return DIExpression::getFragmentInfo(Start, End);
92   }
93 };
94 
95 /// Base class containing the logic for constructing DWARF expressions
96 /// independently of whether they are emitted into a DIE or into a .debug_loc
97 /// entry.
98 class DwarfExpression {
99 protected:
100   /// Holds information about all subregisters comprising a register location.
101   struct Register {
102     int DwarfRegNo;
103     unsigned Size;
104     const char *Comment;
105   };
106 
107   DwarfCompileUnit &CU;
108 
109   /// The register location, if any.
110   SmallVector<Register, 2> DwarfRegs;
111 
112   /// Current Fragment Offset in Bits.
113   uint64_t OffsetInBits = 0;
114 
115   /// Sometimes we need to add a DW_OP_bit_piece to describe a subregister.
116   unsigned SubRegisterSizeInBits : 16;
117   unsigned SubRegisterOffsetInBits : 16;
118 
119   /// The kind of location description being produced.
120   enum { Unknown = 0, Register, Memory, Implicit };
121 
122   unsigned LocationKind : 3;
123   unsigned LocationFlags : 2;
124   unsigned DwarfVersion : 4;
125 
126 public:
127   bool isUnknownLocation() const {
128     return LocationKind == Unknown;
129   }
130 
131   bool isMemoryLocation() const {
132     return LocationKind == Memory;
133   }
134 
135   bool isRegisterLocation() const {
136     return LocationKind == Register;
137   }
138 
139   bool isImplicitLocation() const {
140     return LocationKind == Implicit;
141   }
142 
143   Optional<uint8_t> TagOffset;
144 
145 protected:
146   /// Push a DW_OP_piece / DW_OP_bit_piece for emitting later, if one is needed
147   /// to represent a subregister.
148   void setSubRegisterPiece(unsigned SizeInBits, unsigned OffsetInBits) {
149     assert(SizeInBits < 65536 && OffsetInBits < 65536);
150     SubRegisterSizeInBits = SizeInBits;
151     SubRegisterOffsetInBits = OffsetInBits;
152   }
153 
154   /// Add masking operations to stencil out a subregister.
155   void maskSubRegister();
156 
157   /// Output a dwarf operand and an optional assembler comment.
158   virtual void emitOp(uint8_t Op, const char *Comment = nullptr) = 0;
159 
160   /// Emit a raw signed value.
161   virtual void emitSigned(int64_t Value) = 0;
162 
163   /// Emit a raw unsigned value.
164   virtual void emitUnsigned(uint64_t Value) = 0;
165 
166   virtual void emitData1(uint8_t Value) = 0;
167 
168   virtual void emitBaseTypeRef(uint64_t Idx) = 0;
169 
170   /// Emit a normalized unsigned constant.
171   void emitConstu(uint64_t Value);
172 
173   /// Return whether the given machine register is the frame register in the
174   /// current function.
175   virtual bool isFrameRegister(const TargetRegisterInfo &TRI, unsigned MachineReg) = 0;
176 
177   /// Emit a DW_OP_reg operation. Note that this is only legal inside a DWARF
178   /// register location description.
179   void addReg(int DwarfReg, const char *Comment = nullptr);
180 
181   /// Emit a DW_OP_breg operation.
182   void addBReg(int DwarfReg, int Offset);
183 
184   /// Emit DW_OP_fbreg <Offset>.
185   void addFBReg(int Offset);
186 
187   /// Emit a partial DWARF register operation.
188   ///
189   /// \param MachineReg           The register number.
190   /// \param MaxSize              If the register must be composed from
191   ///                             sub-registers this is an upper bound
192   ///                             for how many bits the emitted DW_OP_piece
193   ///                             may cover.
194   ///
195   /// If size and offset is zero an operation for the entire register is
196   /// emitted: Some targets do not provide a DWARF register number for every
197   /// register.  If this is the case, this function will attempt to emit a DWARF
198   /// register by emitting a fragment of a super-register or by piecing together
199   /// multiple subregisters that alias the register.
200   ///
201   /// \return false if no DWARF register exists for MachineReg.
202   bool addMachineReg(const TargetRegisterInfo &TRI, unsigned MachineReg,
203                      unsigned MaxSize = ~1U);
204 
205   /// Emit a DW_OP_piece or DW_OP_bit_piece operation for a variable fragment.
206   /// \param OffsetInBits    This is an optional offset into the location that
207   /// is at the top of the DWARF stack.
208   void addOpPiece(unsigned SizeInBits, unsigned OffsetInBits = 0);
209 
210   /// Emit a shift-right dwarf operation.
211   void addShr(unsigned ShiftBy);
212 
213   /// Emit a bitwise and dwarf operation.
214   void addAnd(unsigned Mask);
215 
216   /// Emit a DW_OP_stack_value, if supported.
217   ///
218   /// The proper way to describe a constant value is DW_OP_constu <const>,
219   /// DW_OP_stack_value.  Unfortunately, DW_OP_stack_value was not available
220   /// until DWARF 4, so we will continue to generate DW_OP_constu <const> for
221   /// DWARF 2 and DWARF 3. Technically, this is incorrect since DW_OP_const
222   /// <const> actually describes a value at a constant address, not a constant
223   /// value.  However, in the past there was no better way to describe a
224   /// constant value, so the producers and consumers started to rely on
225   /// heuristics to disambiguate the value vs. location status of the
226   /// expression.  See PR21176 for more details.
227   void addStackValue();
228 
229   ~DwarfExpression() = default;
230 
231 public:
232   DwarfExpression(unsigned DwarfVersion, DwarfCompileUnit &CU)
233       : CU(CU), SubRegisterSizeInBits(0), SubRegisterOffsetInBits(0),
234         LocationKind(Unknown), LocationFlags(Unknown),
235         DwarfVersion(DwarfVersion) {}
236 
237   /// This needs to be called last to commit any pending changes.
238   void finalize();
239 
240   /// Emit a signed constant.
241   void addSignedConstant(int64_t Value);
242 
243   /// Emit an unsigned constant.
244   void addUnsignedConstant(uint64_t Value);
245 
246   /// Emit an unsigned constant.
247   void addUnsignedConstant(const APInt &Value);
248 
249   /// Lock this down to become a memory location description.
250   void setMemoryLocationKind() {
251     assert(isUnknownLocation());
252     LocationKind = Memory;
253   }
254 
255   /// Emit a machine register location. As an optimization this may also consume
256   /// the prefix of a DwarfExpression if a more efficient representation for
257   /// combining the register location and the first operation exists.
258   ///
259   /// \param FragmentOffsetInBits     If this is one fragment out of a
260   /// fragmented
261   ///                                 location, this is the offset of the
262   ///                                 fragment inside the entire variable.
263   /// \return                         false if no DWARF register exists
264   ///                                 for MachineReg.
265   bool addMachineRegExpression(const TargetRegisterInfo &TRI,
266                                DIExpressionCursor &Expr, unsigned MachineReg,
267                                unsigned FragmentOffsetInBits = 0);
268 
269   /// Emit all remaining operations in the DIExpressionCursor.
270   ///
271   /// \param FragmentOffsetInBits     If this is one fragment out of multiple
272   ///                                 locations, this is the offset of the
273   ///                                 fragment inside the entire variable.
274   void addExpression(DIExpressionCursor &&Expr,
275                      unsigned FragmentOffsetInBits = 0);
276 
277   /// If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to
278   /// the fragment described by \c Expr.
279   void addFragmentOffset(const DIExpression *Expr);
280 
281   void emitLegacySExt(unsigned FromBits);
282   void emitLegacyZExt(unsigned FromBits);
283 };
284 
285 /// DwarfExpression implementation for .debug_loc entries.
286 class DebugLocDwarfExpression final : public DwarfExpression {
287   ByteStreamer &BS;
288 
289   void emitOp(uint8_t Op, const char *Comment = nullptr) override;
290   void emitSigned(int64_t Value) override;
291   void emitUnsigned(uint64_t Value) override;
292   void emitData1(uint8_t Value) override;
293   void emitBaseTypeRef(uint64_t Idx) override;
294   bool isFrameRegister(const TargetRegisterInfo &TRI,
295                        unsigned MachineReg) override;
296 
297 public:
298   DebugLocDwarfExpression(unsigned DwarfVersion, ByteStreamer &BS, DwarfCompileUnit &CU)
299       : DwarfExpression(DwarfVersion, CU), BS(BS) {}
300 };
301 
302 /// DwarfExpression implementation for singular DW_AT_location.
303 class DIEDwarfExpression final : public DwarfExpression {
304 const AsmPrinter &AP;
305   DIELoc &DIE;
306 
307   void emitOp(uint8_t Op, const char *Comment = nullptr) override;
308   void emitSigned(int64_t Value) override;
309   void emitUnsigned(uint64_t Value) override;
310   void emitData1(uint8_t Value) override;
311   void emitBaseTypeRef(uint64_t Idx) override;
312   bool isFrameRegister(const TargetRegisterInfo &TRI,
313                        unsigned MachineReg) override;
314 public:
315   DIEDwarfExpression(const AsmPrinter &AP, DwarfCompileUnit &CU, DIELoc &DIE);
316 
317   DIELoc *finalize() {
318     DwarfExpression::finalize();
319     return &DIE;
320   }
321 };
322 
323 } // end namespace llvm
324 
325 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFEXPRESSION_H
326