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   /// The flags of location description being produced.
123   enum { EntryValue = 1, CallSiteParamValue };
124 
125   unsigned LocationKind : 3;
126   unsigned LocationFlags : 2;
127   unsigned DwarfVersion : 4;
128 
129 public:
130   bool isUnknownLocation() const {
131     return LocationKind == Unknown;
132   }
133 
134   bool isMemoryLocation() const {
135     return LocationKind == Memory;
136   }
137 
138   bool isRegisterLocation() const {
139     return LocationKind == Register;
140   }
141 
142   bool isImplicitLocation() const {
143     return LocationKind == Implicit;
144   }
145 
146   bool isEntryValue() const {
147     return LocationFlags & EntryValue;
148   }
149 
150   bool isParameterValue() {
151     return LocationFlags & CallSiteParamValue;
152   }
153 
154   Optional<uint8_t> TagOffset;
155 
156 protected:
157   /// Push a DW_OP_piece / DW_OP_bit_piece for emitting later, if one is needed
158   /// to represent a subregister.
159   void setSubRegisterPiece(unsigned SizeInBits, unsigned OffsetInBits) {
160     assert(SizeInBits < 65536 && OffsetInBits < 65536);
161     SubRegisterSizeInBits = SizeInBits;
162     SubRegisterOffsetInBits = OffsetInBits;
163   }
164 
165   /// Add masking operations to stencil out a subregister.
166   void maskSubRegister();
167 
168   /// Output a dwarf operand and an optional assembler comment.
169   virtual void emitOp(uint8_t Op, const char *Comment = nullptr) = 0;
170 
171   /// Emit a raw signed value.
172   virtual void emitSigned(int64_t Value) = 0;
173 
174   /// Emit a raw unsigned value.
175   virtual void emitUnsigned(uint64_t Value) = 0;
176 
177   virtual void emitData1(uint8_t Value) = 0;
178 
179   virtual void emitBaseTypeRef(uint64_t Idx) = 0;
180 
181   /// Emit a normalized unsigned constant.
182   void emitConstu(uint64_t Value);
183 
184   /// Return whether the given machine register is the frame register in the
185   /// current function.
186   virtual bool isFrameRegister(const TargetRegisterInfo &TRI, unsigned MachineReg) = 0;
187 
188   /// Emit a DW_OP_reg operation. Note that this is only legal inside a DWARF
189   /// register location description.
190   void addReg(int DwarfReg, const char *Comment = nullptr);
191 
192   /// Emit a DW_OP_breg operation.
193   void addBReg(int DwarfReg, int Offset);
194 
195   /// Emit DW_OP_fbreg <Offset>.
196   void addFBReg(int Offset);
197 
198   /// Emit a partial DWARF register operation.
199   ///
200   /// \param MachineReg           The register number.
201   /// \param MaxSize              If the register must be composed from
202   ///                             sub-registers this is an upper bound
203   ///                             for how many bits the emitted DW_OP_piece
204   ///                             may cover.
205   ///
206   /// If size and offset is zero an operation for the entire register is
207   /// emitted: Some targets do not provide a DWARF register number for every
208   /// register.  If this is the case, this function will attempt to emit a DWARF
209   /// register by emitting a fragment of a super-register or by piecing together
210   /// multiple subregisters that alias the register.
211   ///
212   /// \return false if no DWARF register exists for MachineReg.
213   bool addMachineReg(const TargetRegisterInfo &TRI, unsigned MachineReg,
214                      unsigned MaxSize = ~1U);
215 
216   /// Emit a DW_OP_piece or DW_OP_bit_piece operation for a variable fragment.
217   /// \param OffsetInBits    This is an optional offset into the location that
218   /// is at the top of the DWARF stack.
219   void addOpPiece(unsigned SizeInBits, unsigned OffsetInBits = 0);
220 
221   /// Emit a shift-right dwarf operation.
222   void addShr(unsigned ShiftBy);
223 
224   /// Emit a bitwise and dwarf operation.
225   void addAnd(unsigned Mask);
226 
227   /// Emit a DW_OP_stack_value, if supported.
228   ///
229   /// The proper way to describe a constant value is DW_OP_constu <const>,
230   /// DW_OP_stack_value.  Unfortunately, DW_OP_stack_value was not available
231   /// until DWARF 4, so we will continue to generate DW_OP_constu <const> for
232   /// DWARF 2 and DWARF 3. Technically, this is incorrect since DW_OP_const
233   /// <const> actually describes a value at a constant address, not a constant
234   /// value.  However, in the past there was no better way to describe a
235   /// constant value, so the producers and consumers started to rely on
236   /// heuristics to disambiguate the value vs. location status of the
237   /// expression.  See PR21176 for more details.
238   void addStackValue();
239 
240   ~DwarfExpression() = default;
241 
242 public:
243   DwarfExpression(unsigned DwarfVersion, DwarfCompileUnit &CU)
244       : CU(CU), SubRegisterSizeInBits(0), SubRegisterOffsetInBits(0),
245         LocationKind(Unknown), LocationFlags(Unknown),
246         DwarfVersion(DwarfVersion) {}
247 
248   /// This needs to be called last to commit any pending changes.
249   void finalize();
250 
251   /// Emit a signed constant.
252   void addSignedConstant(int64_t Value);
253 
254   /// Emit an unsigned constant.
255   void addUnsignedConstant(uint64_t Value);
256 
257   /// Emit an unsigned constant.
258   void addUnsignedConstant(const APInt &Value);
259 
260   /// Lock this down to become a memory location description.
261   void setMemoryLocationKind() {
262     assert(isUnknownLocation());
263     LocationKind = Memory;
264   }
265 
266   /// Lock this down to become an entry value location.
267   void setEntryValueFlag() {
268     LocationFlags |= EntryValue;
269   }
270 
271   /// Lock this down to become a call site parameter location.
272   void setCallSiteParamValueFlag() {
273     LocationFlags |= CallSiteParamValue;
274   }
275 
276   /// Emit a machine register location. As an optimization this may also consume
277   /// the prefix of a DwarfExpression if a more efficient representation for
278   /// combining the register location and the first operation exists.
279   ///
280   /// \param FragmentOffsetInBits     If this is one fragment out of a
281   /// fragmented
282   ///                                 location, this is the offset of the
283   ///                                 fragment inside the entire variable.
284   /// \return                         false if no DWARF register exists
285   ///                                 for MachineReg.
286   bool addMachineRegExpression(const TargetRegisterInfo &TRI,
287                                DIExpressionCursor &Expr, unsigned MachineReg,
288                                unsigned FragmentOffsetInBits = 0);
289 
290   /// Emit entry value dwarf operation.
291   void addEntryValueExpression(DIExpressionCursor &ExprCursor);
292 
293   /// Emit all remaining operations in the DIExpressionCursor.
294   ///
295   /// \param FragmentOffsetInBits     If this is one fragment out of multiple
296   ///                                 locations, this is the offset of the
297   ///                                 fragment inside the entire variable.
298   void addExpression(DIExpressionCursor &&Expr,
299                      unsigned FragmentOffsetInBits = 0);
300 
301   /// If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to
302   /// the fragment described by \c Expr.
303   void addFragmentOffset(const DIExpression *Expr);
304 
305   void emitLegacySExt(unsigned FromBits);
306   void emitLegacyZExt(unsigned FromBits);
307 };
308 
309 /// DwarfExpression implementation for .debug_loc entries.
310 class DebugLocDwarfExpression final : public DwarfExpression {
311   ByteStreamer &BS;
312 
313   void emitOp(uint8_t Op, const char *Comment = nullptr) override;
314   void emitSigned(int64_t Value) override;
315   void emitUnsigned(uint64_t Value) override;
316   void emitData1(uint8_t Value) override;
317   void emitBaseTypeRef(uint64_t Idx) override;
318   bool isFrameRegister(const TargetRegisterInfo &TRI,
319                        unsigned MachineReg) override;
320 
321 public:
322   DebugLocDwarfExpression(unsigned DwarfVersion, ByteStreamer &BS, DwarfCompileUnit &CU)
323       : DwarfExpression(DwarfVersion, CU), BS(BS) {}
324 };
325 
326 /// DwarfExpression implementation for singular DW_AT_location.
327 class DIEDwarfExpression final : public DwarfExpression {
328 const AsmPrinter &AP;
329   DIELoc &DIE;
330 
331   void emitOp(uint8_t Op, const char *Comment = nullptr) override;
332   void emitSigned(int64_t Value) override;
333   void emitUnsigned(uint64_t Value) override;
334   void emitData1(uint8_t Value) override;
335   void emitBaseTypeRef(uint64_t Idx) override;
336   bool isFrameRegister(const TargetRegisterInfo &TRI,
337                        unsigned MachineReg) override;
338 public:
339   DIEDwarfExpression(const AsmPrinter &AP, DwarfCompileUnit &CU, DIELoc &DIE);
340 
341   DIELoc *finalize() {
342     DwarfExpression::finalize();
343     return &DIE;
344   }
345 };
346 
347 } // end namespace llvm
348 
349 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DWARFEXPRESSION_H
350