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