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::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     if (Reg < 0)
134       continue;
135 
136     // Intersection between the bits we already emitted and the bits
137     // covered by this subregister.
138     SmallBitVector CurSubReg(RegSize, false);
139     CurSubReg.set(Offset, Offset + Size);
140 
141     // If this sub-register has a DWARF number and we haven't covered
142     // its range, emit a DWARF piece for it.
143     if (CurSubReg.test(Coverage)) {
144       // Emit a piece for any gap in the coverage.
145       if (Offset > CurPos)
146         DwarfRegs.push_back({-1, Offset - CurPos, nullptr});
147       DwarfRegs.push_back(
148           {Reg, std::min<unsigned>(Size, MaxSize - Offset), "sub-register"});
149       if (Offset >= MaxSize)
150         break;
151 
152       // Mark it as emitted.
153       Coverage.set(Offset, Offset + Size);
154       CurPos = Offset + Size;
155     }
156   }
157 
158   return CurPos;
159 }
160 
161 void DwarfExpression::addStackValue() {
162   if (DwarfVersion >= 4)
163     emitOp(dwarf::DW_OP_stack_value);
164 }
165 
166 void DwarfExpression::addSignedConstant(int64_t Value) {
167   assert(LocationKind == Implicit || LocationKind == Unknown);
168   LocationKind = Implicit;
169   emitOp(dwarf::DW_OP_consts);
170   emitSigned(Value);
171 }
172 
173 void DwarfExpression::addUnsignedConstant(uint64_t Value) {
174   assert(LocationKind == Implicit || LocationKind == Unknown);
175   LocationKind = Implicit;
176   emitOp(dwarf::DW_OP_constu);
177   emitUnsigned(Value);
178 }
179 
180 void DwarfExpression::addUnsignedConstant(const APInt &Value) {
181   assert(LocationKind == Implicit || LocationKind == Unknown);
182   LocationKind = Implicit;
183 
184   unsigned Size = Value.getBitWidth();
185   const uint64_t *Data = Value.getRawData();
186 
187   // Chop it up into 64-bit pieces, because that's the maximum that
188   // addUnsignedConstant takes.
189   unsigned Offset = 0;
190   while (Offset < Size) {
191     addUnsignedConstant(*Data++);
192     if (Offset == 0 && Size <= 64)
193       break;
194     addStackValue();
195     addOpPiece(std::min(Size - Offset, 64u), Offset);
196     Offset += 64;
197   }
198 }
199 
200 bool DwarfExpression::addMachineRegExpression(const TargetRegisterInfo &TRI,
201                                               DIExpressionCursor &ExprCursor,
202                                               unsigned MachineReg,
203                                               unsigned FragmentOffsetInBits) {
204   auto Fragment = ExprCursor.getFragmentInfo();
205   if (!addMachineReg(TRI, MachineReg, Fragment ? Fragment->SizeInBits : ~1U)) {
206     LocationKind = Unknown;
207     return false;
208   }
209 
210   bool HasComplexExpression = false;
211   auto Op = ExprCursor.peek();
212   if (Op && Op->getOp() != dwarf::DW_OP_LLVM_fragment)
213     HasComplexExpression = true;
214 
215   // If the register can only be described by a complex expression (i.e.,
216   // multiple subregisters) it doesn't safely compose with another complex
217   // expression. For example, it is not possible to apply a DW_OP_deref
218   // operation to multiple DW_OP_pieces.
219   if (HasComplexExpression && DwarfRegs.size() > 1) {
220     DwarfRegs.clear();
221     LocationKind = Unknown;
222     return false;
223   }
224 
225   // Handle simple register locations.
226   if (LocationKind != Memory && !HasComplexExpression) {
227     for (auto &Reg : DwarfRegs) {
228       if (Reg.DwarfRegNo >= 0)
229         addReg(Reg.DwarfRegNo, Reg.Comment);
230       addOpPiece(Reg.Size);
231     }
232     DwarfRegs.clear();
233     return true;
234   }
235 
236   // Don't emit locations that cannot be expressed without DW_OP_stack_value.
237   if (DwarfVersion < 4)
238     if (std::any_of(ExprCursor.begin(), ExprCursor.end(),
239                     [](DIExpression::ExprOperand Op) -> bool {
240                       return Op.getOp() == dwarf::DW_OP_stack_value;
241                     })) {
242       DwarfRegs.clear();
243       LocationKind = Unknown;
244       return false;
245     }
246 
247   assert(DwarfRegs.size() == 1);
248   auto Reg = DwarfRegs[0];
249   bool FBReg = isFrameRegister(TRI, MachineReg);
250   int SignedOffset = 0;
251   assert(Reg.Size == 0 && "subregister has same size as superregister");
252 
253   // Pattern-match combinations for which more efficient representations exist.
254   // [Reg, DW_OP_plus_uconst, Offset] --> [DW_OP_breg, Offset].
255   if (Op && (Op->getOp() == dwarf::DW_OP_plus_uconst)) {
256     SignedOffset = Op->getArg(0);
257     ExprCursor.take();
258   }
259 
260   // [Reg, DW_OP_constu, Offset, DW_OP_plus]  --> [DW_OP_breg, Offset]
261   // [Reg, DW_OP_constu, Offset, DW_OP_minus] --> [DW_OP_breg,-Offset]
262   // If Reg is a subregister we need to mask it out before subtracting.
263   if (Op && Op->getOp() == dwarf::DW_OP_constu) {
264     auto N = ExprCursor.peekNext();
265     if (N && (N->getOp() == dwarf::DW_OP_plus ||
266              (N->getOp() == dwarf::DW_OP_minus && !SubRegisterSizeInBits))) {
267       int Offset = Op->getArg(0);
268       SignedOffset = (N->getOp() == dwarf::DW_OP_minus) ? -Offset : Offset;
269       ExprCursor.consume(2);
270     }
271   }
272 
273   if (FBReg)
274     addFBReg(SignedOffset);
275   else
276     addBReg(Reg.DwarfRegNo, SignedOffset);
277   DwarfRegs.clear();
278   return true;
279 }
280 
281 /// Assuming a well-formed expression, match "DW_OP_deref* DW_OP_LLVM_fragment?".
282 static bool isMemoryLocation(DIExpressionCursor ExprCursor) {
283   while (ExprCursor) {
284     auto Op = ExprCursor.take();
285     switch (Op->getOp()) {
286     case dwarf::DW_OP_deref:
287     case dwarf::DW_OP_LLVM_fragment:
288       break;
289     default:
290       return false;
291     }
292   }
293   return true;
294 }
295 
296 void DwarfExpression::addExpression(DIExpressionCursor &&ExprCursor,
297                                     unsigned FragmentOffsetInBits) {
298   // If we need to mask out a subregister, do it now, unless the next
299   // operation would emit an OpPiece anyway.
300   auto N = ExprCursor.peek();
301   if (SubRegisterSizeInBits && N && (N->getOp() != dwarf::DW_OP_LLVM_fragment))
302     maskSubRegister();
303 
304   while (ExprCursor) {
305     auto Op = ExprCursor.take();
306     switch (Op->getOp()) {
307     case dwarf::DW_OP_LLVM_fragment: {
308       unsigned SizeInBits = Op->getArg(1);
309       unsigned FragmentOffset = Op->getArg(0);
310       // The fragment offset must have already been adjusted by emitting an
311       // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
312       // location.
313       assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
314 
315       // If addMachineReg already emitted DW_OP_piece operations to represent
316       // a super-register by splicing together sub-registers, subtract the size
317       // of the pieces that was already emitted.
318       SizeInBits -= OffsetInBits - FragmentOffset;
319 
320       // If addMachineReg requested a DW_OP_bit_piece to stencil out a
321       // sub-register that is smaller than the current fragment's size, use it.
322       if (SubRegisterSizeInBits)
323         SizeInBits = std::min<unsigned>(SizeInBits, SubRegisterSizeInBits);
324 
325       // Emit a DW_OP_stack_value for implicit location descriptions.
326       if (LocationKind == Implicit)
327         addStackValue();
328 
329       // Emit the DW_OP_piece.
330       addOpPiece(SizeInBits, SubRegisterOffsetInBits);
331       setSubRegisterPiece(0, 0);
332       // Reset the location description kind.
333       LocationKind = Unknown;
334       return;
335     }
336     case dwarf::DW_OP_plus_uconst:
337       assert(LocationKind != Register);
338       emitOp(dwarf::DW_OP_plus_uconst);
339       emitUnsigned(Op->getArg(0));
340       break;
341     case dwarf::DW_OP_plus:
342     case dwarf::DW_OP_minus:
343     case dwarf::DW_OP_mul:
344       emitOp(Op->getOp());
345       break;
346     case dwarf::DW_OP_deref:
347       assert(LocationKind != Register);
348       if (LocationKind != Memory && isMemoryLocation(ExprCursor))
349         // Turning this into a memory location description makes the deref
350         // implicit.
351         LocationKind = Memory;
352       else
353         emitOp(dwarf::DW_OP_deref);
354       break;
355     case dwarf::DW_OP_constu:
356       assert(LocationKind != Register);
357       emitOp(dwarf::DW_OP_constu);
358       emitUnsigned(Op->getArg(0));
359       break;
360     case dwarf::DW_OP_stack_value:
361       LocationKind = Implicit;
362       break;
363     case dwarf::DW_OP_swap:
364       assert(LocationKind != Register);
365       emitOp(dwarf::DW_OP_swap);
366       break;
367     case dwarf::DW_OP_xderef:
368       assert(LocationKind != Register);
369       emitOp(dwarf::DW_OP_xderef);
370       break;
371     default:
372       llvm_unreachable("unhandled opcode found in expression");
373     }
374   }
375 
376   if (LocationKind == Implicit)
377     // Turn this into an implicit location description.
378     addStackValue();
379 }
380 
381 /// add masking operations to stencil out a subregister.
382 void DwarfExpression::maskSubRegister() {
383   assert(SubRegisterSizeInBits && "no subregister was registered");
384   if (SubRegisterOffsetInBits > 0)
385     addShr(SubRegisterOffsetInBits);
386   uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
387   addAnd(Mask);
388 }
389 
390 void DwarfExpression::finalize() {
391   assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
392   // Emit any outstanding DW_OP_piece operations to mask out subregisters.
393   if (SubRegisterSizeInBits == 0)
394     return;
395   // Don't emit a DW_OP_piece for a subregister at offset 0.
396   if (SubRegisterOffsetInBits == 0)
397     return;
398   addOpPiece(SubRegisterSizeInBits, SubRegisterOffsetInBits);
399 }
400 
401 void DwarfExpression::addFragmentOffset(const DIExpression *Expr) {
402   if (!Expr || !Expr->isFragment())
403     return;
404 
405   uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
406   assert(FragmentOffset >= OffsetInBits &&
407          "overlapping or duplicate fragments");
408   if (FragmentOffset > OffsetInBits)
409     addOpPiece(FragmentOffset - OffsetInBits);
410   OffsetInBits = FragmentOffset;
411 }
412