1 //===- llvm/CodeGen/DwarfExpression.cpp - Dwarf Debug Framework -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "DwarfExpression.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/SmallBitVector.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/IR/DebugInfoMetadata.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include <algorithm>
22 #include <cassert>
23 #include <cstdint>
24 
25 using namespace llvm;
26 
27 void DwarfExpression::addReg(int DwarfReg, const char *Comment) {
28  assert(DwarfReg >= 0 && "invalid negative dwarf register number");
29  assert((LocationKind == Unknown || LocationKind == Register) &&
30         "location description already locked down");
31  LocationKind = Register;
32  if (DwarfReg < 32) {
33    emitOp(dwarf::DW_OP_reg0 + DwarfReg, Comment);
34   } else {
35     emitOp(dwarf::DW_OP_regx, Comment);
36     emitUnsigned(DwarfReg);
37   }
38 }
39 
40 void DwarfExpression::addBReg(int DwarfReg, int Offset) {
41   assert(DwarfReg >= 0 && "invalid negative dwarf register number");
42   assert(LocationKind != Register && "location description already locked down");
43   if (DwarfReg < 32) {
44     emitOp(dwarf::DW_OP_breg0 + DwarfReg);
45   } else {
46     emitOp(dwarf::DW_OP_bregx);
47     emitUnsigned(DwarfReg);
48   }
49   emitSigned(Offset);
50 }
51 
52 void DwarfExpression::addFBReg(int Offset) {
53   emitOp(dwarf::DW_OP_fbreg);
54   emitSigned(Offset);
55 }
56 
57 void DwarfExpression::addOpPiece(unsigned SizeInBits, unsigned OffsetInBits) {
58   if (!SizeInBits)
59     return;
60 
61   const unsigned SizeOfByte = 8;
62   if (OffsetInBits > 0 || SizeInBits % SizeOfByte) {
63     emitOp(dwarf::DW_OP_bit_piece);
64     emitUnsigned(SizeInBits);
65     emitUnsigned(OffsetInBits);
66   } else {
67     emitOp(dwarf::DW_OP_piece);
68     unsigned ByteSize = SizeInBits / SizeOfByte;
69     emitUnsigned(ByteSize);
70   }
71   this->OffsetInBits += SizeInBits;
72 }
73 
74 void DwarfExpression::addShr(unsigned ShiftBy) {
75   emitOp(dwarf::DW_OP_constu);
76   emitUnsigned(ShiftBy);
77   emitOp(dwarf::DW_OP_shr);
78 }
79 
80 void DwarfExpression::addAnd(unsigned Mask) {
81   emitOp(dwarf::DW_OP_constu);
82   emitUnsigned(Mask);
83   emitOp(dwarf::DW_OP_and);
84 }
85 
86 bool DwarfExpression::addMachineReg(const TargetRegisterInfo &TRI,
87                                     unsigned MachineReg, unsigned MaxSize) {
88   if (!TRI.isPhysicalRegister(MachineReg)) {
89     if (isFrameRegister(TRI, MachineReg)) {
90       DwarfRegs.push_back({-1, 0, nullptr});
91       return true;
92     }
93     return false;
94   }
95 
96   int Reg = TRI.getDwarfRegNum(MachineReg, false);
97 
98   // If this is a valid register number, emit it.
99   if (Reg >= 0) {
100     DwarfRegs.push_back({Reg, 0, nullptr});
101     return true;
102   }
103 
104   // Walk up the super-register chain until we find a valid number.
105   // For example, EAX on x86_64 is a 32-bit fragment of RAX with offset 0.
106   for (MCSuperRegIterator SR(MachineReg, &TRI); SR.isValid(); ++SR) {
107     Reg = TRI.getDwarfRegNum(*SR, false);
108     if (Reg >= 0) {
109       unsigned Idx = TRI.getSubRegIndex(*SR, MachineReg);
110       unsigned Size = TRI.getSubRegIdxSize(Idx);
111       unsigned RegOffset = TRI.getSubRegIdxOffset(Idx);
112       DwarfRegs.push_back({Reg, 0, "super-register"});
113       // Use a DW_OP_bit_piece to describe the sub-register.
114       setSubRegisterPiece(Size, RegOffset);
115       return true;
116     }
117   }
118 
119   // Otherwise, attempt to find a covering set of sub-register numbers.
120   // For example, Q0 on ARM is a composition of D0+D1.
121   unsigned CurPos = 0;
122   // The size of the register in bits.
123   const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(MachineReg);
124   unsigned RegSize = TRI.getRegSizeInBits(*RC);
125   // Keep track of the bits in the register we already emitted, so we
126   // can avoid emitting redundant aliasing subregs.
127   SmallBitVector Coverage(RegSize, false);
128   for (MCSubRegIterator SR(MachineReg, &TRI); SR.isValid(); ++SR) {
129     unsigned Idx = TRI.getSubRegIndex(MachineReg, *SR);
130     unsigned Size = TRI.getSubRegIdxSize(Idx);
131     unsigned Offset = TRI.getSubRegIdxOffset(Idx);
132     Reg = TRI.getDwarfRegNum(*SR, false);
133 
134     // Intersection between the bits we already emitted and the bits
135     // covered by this subregister.
136     SmallBitVector CurSubReg(RegSize, false);
137     CurSubReg.set(Offset, Offset + Size);
138 
139     // If this sub-register has a DWARF number and we haven't covered
140     // its range, emit a DWARF piece for it.
141     if (Reg >= 0 && CurSubReg.test(Coverage)) {
142       // Emit a piece for any gap in the coverage.
143       if (Offset > CurPos)
144         DwarfRegs.push_back({-1, Offset - CurPos, nullptr});
145       DwarfRegs.push_back(
146           {Reg, std::min<unsigned>(Size, MaxSize - Offset), "sub-register"});
147       if (Offset >= MaxSize)
148         break;
149 
150       // Mark it as emitted.
151       Coverage.set(Offset, Offset + Size);
152       CurPos = Offset + Size;
153     }
154   }
155 
156   return CurPos;
157 }
158 
159 void DwarfExpression::addStackValue() {
160   if (DwarfVersion >= 4)
161     emitOp(dwarf::DW_OP_stack_value);
162 }
163 
164 void DwarfExpression::addSignedConstant(int64_t Value) {
165   assert(LocationKind == Implicit || LocationKind == Unknown);
166   LocationKind = Implicit;
167   emitOp(dwarf::DW_OP_consts);
168   emitSigned(Value);
169 }
170 
171 void DwarfExpression::addUnsignedConstant(uint64_t Value) {
172   assert(LocationKind == Implicit || LocationKind == Unknown);
173   LocationKind = Implicit;
174   emitOp(dwarf::DW_OP_constu);
175   emitUnsigned(Value);
176 }
177 
178 void DwarfExpression::addUnsignedConstant(const APInt &Value) {
179   assert(LocationKind == Implicit || LocationKind == Unknown);
180   LocationKind = Implicit;
181 
182   unsigned Size = Value.getBitWidth();
183   const uint64_t *Data = Value.getRawData();
184 
185   // Chop it up into 64-bit pieces, because that's the maximum that
186   // addUnsignedConstant takes.
187   unsigned Offset = 0;
188   while (Offset < Size) {
189     addUnsignedConstant(*Data++);
190     if (Offset == 0 && Size <= 64)
191       break;
192     addStackValue();
193     addOpPiece(std::min(Size - Offset, 64u), Offset);
194     Offset += 64;
195   }
196 }
197 
198 bool DwarfExpression::addMachineRegExpression(const TargetRegisterInfo &TRI,
199                                               DIExpressionCursor &ExprCursor,
200                                               unsigned MachineReg,
201                                               unsigned FragmentOffsetInBits) {
202   auto Fragment = ExprCursor.getFragmentInfo();
203   if (!addMachineReg(TRI, MachineReg, Fragment ? Fragment->SizeInBits : ~1U)) {
204     LocationKind = Unknown;
205     return false;
206   }
207 
208   bool HasComplexExpression = false;
209   auto Op = ExprCursor.peek();
210   if (Op && Op->getOp() != dwarf::DW_OP_LLVM_fragment)
211     HasComplexExpression = true;
212 
213   // If the register can only be described by a complex expression (i.e.,
214   // multiple subregisters) it doesn't safely compose with another complex
215   // expression. For example, it is not possible to apply a DW_OP_deref
216   // operation to multiple DW_OP_pieces.
217   if (HasComplexExpression && DwarfRegs.size() > 1) {
218     DwarfRegs.clear();
219     LocationKind = Unknown;
220     return false;
221   }
222 
223   // Handle simple register locations.
224   if (LocationKind != Memory && !HasComplexExpression) {
225     for (auto &Reg : DwarfRegs) {
226       if (Reg.DwarfRegNo >= 0)
227         addReg(Reg.DwarfRegNo, Reg.Comment);
228       addOpPiece(Reg.Size);
229     }
230     DwarfRegs.clear();
231     return true;
232   }
233 
234   // Don't emit locations that cannot be expressed without DW_OP_stack_value.
235   if (DwarfVersion < 4)
236     if (std::any_of(ExprCursor.begin(), ExprCursor.end(),
237                     [](DIExpression::ExprOperand Op) -> bool {
238                       return Op.getOp() == dwarf::DW_OP_stack_value;
239                     })) {
240       DwarfRegs.clear();
241       LocationKind = Unknown;
242       return false;
243     }
244 
245   assert(DwarfRegs.size() == 1);
246   auto Reg = DwarfRegs[0];
247   bool FBReg = isFrameRegister(TRI, MachineReg);
248   int SignedOffset = 0;
249   assert(Reg.Size == 0 && "subregister has same size as superregister");
250 
251   // Pattern-match combinations for which more efficient representations exist.
252   // [Reg, DW_OP_plus_uconst, Offset] --> [DW_OP_breg, Offset].
253   if (Op && (Op->getOp() == dwarf::DW_OP_plus_uconst)) {
254     SignedOffset = Op->getArg(0);
255     ExprCursor.take();
256   }
257 
258   // [Reg, DW_OP_constu, Offset, DW_OP_plus]  --> [DW_OP_breg, Offset]
259   // [Reg, DW_OP_constu, Offset, DW_OP_minus] --> [DW_OP_breg,-Offset]
260   // If Reg is a subregister we need to mask it out before subtracting.
261   if (Op && Op->getOp() == dwarf::DW_OP_constu) {
262     auto N = ExprCursor.peekNext();
263     if (N && (N->getOp() == dwarf::DW_OP_plus ||
264              (N->getOp() == dwarf::DW_OP_minus && !SubRegisterSizeInBits))) {
265       int Offset = Op->getArg(0);
266       SignedOffset = (N->getOp() == dwarf::DW_OP_minus) ? -Offset : Offset;
267       ExprCursor.consume(2);
268     }
269   }
270 
271   if (FBReg)
272     addFBReg(SignedOffset);
273   else
274     addBReg(Reg.DwarfRegNo, SignedOffset);
275   DwarfRegs.clear();
276   return true;
277 }
278 
279 /// Assuming a well-formed expression, match "DW_OP_deref* DW_OP_LLVM_fragment?".
280 static bool isMemoryLocation(DIExpressionCursor ExprCursor) {
281   while (ExprCursor) {
282     auto Op = ExprCursor.take();
283     switch (Op->getOp()) {
284     case dwarf::DW_OP_deref:
285     case dwarf::DW_OP_LLVM_fragment:
286       break;
287     default:
288       return false;
289     }
290   }
291   return true;
292 }
293 
294 void DwarfExpression::addExpression(DIExpressionCursor &&ExprCursor,
295                                     unsigned FragmentOffsetInBits) {
296   // If we need to mask out a subregister, do it now, unless the next
297   // operation would emit an OpPiece anyway.
298   auto N = ExprCursor.peek();
299   if (SubRegisterSizeInBits && N && (N->getOp() != dwarf::DW_OP_LLVM_fragment))
300     maskSubRegister();
301 
302   while (ExprCursor) {
303     auto Op = ExprCursor.take();
304     switch (Op->getOp()) {
305     case dwarf::DW_OP_LLVM_fragment: {
306       unsigned SizeInBits = Op->getArg(1);
307       unsigned FragmentOffset = Op->getArg(0);
308       // The fragment offset must have already been adjusted by emitting an
309       // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
310       // location.
311       assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
312 
313       // If addMachineReg already emitted DW_OP_piece operations to represent
314       // a super-register by splicing together sub-registers, subtract the size
315       // of the pieces that was already emitted.
316       SizeInBits -= OffsetInBits - FragmentOffset;
317 
318       // If addMachineReg requested a DW_OP_bit_piece to stencil out a
319       // sub-register that is smaller than the current fragment's size, use it.
320       if (SubRegisterSizeInBits)
321         SizeInBits = std::min<unsigned>(SizeInBits, SubRegisterSizeInBits);
322 
323       // Emit a DW_OP_stack_value for implicit location descriptions.
324       if (LocationKind == Implicit)
325         addStackValue();
326 
327       // Emit the DW_OP_piece.
328       addOpPiece(SizeInBits, SubRegisterOffsetInBits);
329       setSubRegisterPiece(0, 0);
330       // Reset the location description kind.
331       LocationKind = Unknown;
332       return;
333     }
334     case dwarf::DW_OP_plus_uconst:
335       assert(LocationKind != Register);
336       emitOp(dwarf::DW_OP_plus_uconst);
337       emitUnsigned(Op->getArg(0));
338       break;
339     case dwarf::DW_OP_plus:
340     case dwarf::DW_OP_minus:
341       emitOp(Op->getOp());
342       break;
343     case dwarf::DW_OP_deref:
344       assert(LocationKind != Register);
345       if (LocationKind != Memory && isMemoryLocation(ExprCursor))
346         // Turning this into a memory location description makes the deref
347         // implicit.
348         LocationKind = Memory;
349       else
350         emitOp(dwarf::DW_OP_deref);
351       break;
352     case dwarf::DW_OP_constu:
353       assert(LocationKind != Register);
354       emitOp(dwarf::DW_OP_constu);
355       emitUnsigned(Op->getArg(0));
356       break;
357     case dwarf::DW_OP_stack_value:
358       LocationKind = Implicit;
359       break;
360     case dwarf::DW_OP_swap:
361       assert(LocationKind != Register);
362       emitOp(dwarf::DW_OP_swap);
363       break;
364     case dwarf::DW_OP_xderef:
365       assert(LocationKind != Register);
366       emitOp(dwarf::DW_OP_xderef);
367       break;
368     default:
369       llvm_unreachable("unhandled opcode found in expression");
370     }
371   }
372 
373   if (LocationKind == Implicit)
374     // Turn this into an implicit location description.
375     addStackValue();
376 }
377 
378 /// add masking operations to stencil out a subregister.
379 void DwarfExpression::maskSubRegister() {
380   assert(SubRegisterSizeInBits && "no subregister was registered");
381   if (SubRegisterOffsetInBits > 0)
382     addShr(SubRegisterOffsetInBits);
383   uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
384   addAnd(Mask);
385 }
386 
387 void DwarfExpression::finalize() {
388   assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
389   // Emit any outstanding DW_OP_piece operations to mask out subregisters.
390   if (SubRegisterSizeInBits == 0)
391     return;
392   // Don't emit a DW_OP_piece for a subregister at offset 0.
393   if (SubRegisterOffsetInBits == 0)
394     return;
395   addOpPiece(SubRegisterSizeInBits, SubRegisterOffsetInBits);
396 }
397 
398 void DwarfExpression::addFragmentOffset(const DIExpression *Expr) {
399   if (!Expr || !Expr->isFragment())
400     return;
401 
402   uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
403   assert(FragmentOffset >= OffsetInBits &&
404          "overlapping or duplicate fragments");
405   if (FragmentOffset > OffsetInBits)
406     addOpPiece(FragmentOffset - OffsetInBits);
407   OffsetInBits = FragmentOffset;
408 }
409