1 //===- llvm/CodeGen/DwarfExpression.cpp - Dwarf Debug Framework -----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains support for writing dwarf debug info into asm files.
11 //===----------------------------------------------------------------------===//
13 #include "DwarfExpression.h"
14 #include "DwarfCompileUnit.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"
27 void DwarfExpression::emitConstu(uint64_t Value) {
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);
36 emitOp(dwarf::DW_OP_constu);
41 void DwarfExpression::addReg(int DwarfReg, const char *Comment) {
42 assert(DwarfReg >= 0 && "invalid negative dwarf register number");
43 assert((isUnknownLocation() || isRegisterLocation()) &&
44 "location description already locked down");
45 LocationKind = Register;
47 emitOp(dwarf::DW_OP_reg0 + DwarfReg, Comment);
49 emitOp(dwarf::DW_OP_regx, Comment);
50 emitUnsigned(DwarfReg);
54 void DwarfExpression::addBReg(int DwarfReg, int Offset) {
55 assert(DwarfReg >= 0 && "invalid negative dwarf register number");
56 assert(!isRegisterLocation() && "location description already locked down");
58 emitOp(dwarf::DW_OP_breg0 + DwarfReg);
60 emitOp(dwarf::DW_OP_bregx);
61 emitUnsigned(DwarfReg);
66 void DwarfExpression::addFBReg(int Offset) {
67 emitOp(dwarf::DW_OP_fbreg);
71 void DwarfExpression::addOpPiece(unsigned SizeInBits, unsigned OffsetInBits) {
75 const unsigned SizeOfByte = 8;
76 if (OffsetInBits > 0 || SizeInBits % SizeOfByte) {
77 emitOp(dwarf::DW_OP_bit_piece);
78 emitUnsigned(SizeInBits);
79 emitUnsigned(OffsetInBits);
81 emitOp(dwarf::DW_OP_piece);
82 unsigned ByteSize = SizeInBits / SizeOfByte;
83 emitUnsigned(ByteSize);
85 this->OffsetInBits += SizeInBits;
88 void DwarfExpression::addShr(unsigned ShiftBy) {
90 emitOp(dwarf::DW_OP_shr);
93 void DwarfExpression::addAnd(unsigned Mask) {
95 emitOp(dwarf::DW_OP_and);
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});
108 int Reg = TRI.getDwarfRegNum(MachineReg, false);
110 // If this is a valid register number, emit it.
112 DwarfRegs.push_back({Reg, 0, nullptr});
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);
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);
131 // Otherwise, attempt to find a covering set of sub-register numbers.
132 // For example, Q0 on ARM is a composition of D0+D1.
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);
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);
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.
161 DwarfRegs.push_back({-1, Offset - CurPos, "no DWARF register encoding"});
163 {Reg, std::min<unsigned>(Size, MaxSize - Offset), "sub-register"});
164 if (Offset >= MaxSize)
167 // Mark it as emitted.
168 Coverage.set(Offset, Offset + Size);
169 CurPos = Offset + Size;
172 // Failed to find any DWARF encoding.
175 // Found a partial or complete DWARF encoding.
176 if (CurPos < RegSize)
177 DwarfRegs.push_back({-1, RegSize - CurPos, "no DWARF register encoding"});
181 void DwarfExpression::addStackValue() {
182 if (DwarfVersion >= 4)
183 emitOp(dwarf::DW_OP_stack_value);
186 void DwarfExpression::addSignedConstant(int64_t Value) {
187 assert(isImplicitLocation() || isUnknownLocation());
188 LocationKind = Implicit;
189 emitOp(dwarf::DW_OP_consts);
193 void DwarfExpression::addUnsignedConstant(uint64_t Value) {
194 assert(isImplicitLocation() || isUnknownLocation());
195 LocationKind = Implicit;
199 void DwarfExpression::addUnsignedConstant(const APInt &Value) {
200 assert(isImplicitLocation() || isUnknownLocation());
201 LocationKind = Implicit;
203 unsigned Size = Value.getBitWidth();
204 const uint64_t *Data = Value.getRawData();
206 // Chop it up into 64-bit pieces, because that's the maximum that
207 // addUnsignedConstant takes.
209 while (Offset < Size) {
210 addUnsignedConstant(*Data++);
211 if (Offset == 0 && Size <= 64)
214 addOpPiece(std::min(Size - Offset, 64u), Offset);
219 bool DwarfExpression::addMachineRegExpression(const TargetRegisterInfo &TRI,
220 DIExpressionCursor &ExprCursor,
222 unsigned FragmentOffsetInBits) {
223 auto Fragment = ExprCursor.getFragmentInfo();
224 if (!addMachineReg(TRI, MachineReg, Fragment ? Fragment->SizeInBits : ~1U)) {
225 LocationKind = Unknown;
229 bool HasComplexExpression = false;
230 auto Op = ExprCursor.peek();
231 if (Op && Op->getOp() != dwarf::DW_OP_LLVM_fragment)
232 HasComplexExpression = true;
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) {
240 LocationKind = Unknown;
244 // Handle simple register locations.
245 if (!isMemoryLocation() && !HasComplexExpression) {
246 for (auto &Reg : DwarfRegs) {
247 if (Reg.DwarfRegNo >= 0)
248 addReg(Reg.DwarfRegNo, Reg.Comment);
249 addOpPiece(Reg.Size);
252 if (isEntryValue() && DwarfVersion >= 4)
253 emitOp(dwarf::DW_OP_stack_value);
259 // Don't emit locations that cannot be expressed without DW_OP_stack_value.
260 if (DwarfVersion < 4)
261 if (any_of(ExprCursor, [](DIExpression::ExprOperand Op) -> bool {
262 return Op.getOp() == dwarf::DW_OP_stack_value;
265 LocationKind = Unknown;
269 assert(DwarfRegs.size() == 1);
270 auto Reg = DwarfRegs[0];
271 bool FBReg = isFrameRegister(TRI, MachineReg);
272 int SignedOffset = 0;
273 assert(Reg.Size == 0 && "subregister has same size as superregister");
275 // Pattern-match combinations for which more efficient representations exist.
276 // [Reg, DW_OP_plus_uconst, Offset] --> [DW_OP_breg, Offset].
277 if (Op && (Op->getOp() == dwarf::DW_OP_plus_uconst)) {
278 SignedOffset = Op->getArg(0);
282 // [Reg, DW_OP_constu, Offset, DW_OP_plus] --> [DW_OP_breg, Offset]
283 // [Reg, DW_OP_constu, Offset, DW_OP_minus] --> [DW_OP_breg,-Offset]
284 // If Reg is a subregister we need to mask it out before subtracting.
285 if (Op && Op->getOp() == dwarf::DW_OP_constu) {
286 auto N = ExprCursor.peekNext();
287 if (N && (N->getOp() == dwarf::DW_OP_plus ||
288 (N->getOp() == dwarf::DW_OP_minus && !SubRegisterSizeInBits))) {
289 int Offset = Op->getArg(0);
290 SignedOffset = (N->getOp() == dwarf::DW_OP_minus) ? -Offset : Offset;
291 ExprCursor.consume(2);
296 addFBReg(SignedOffset);
298 addBReg(Reg.DwarfRegNo, SignedOffset);
303 void DwarfExpression::addEntryValueExpression(DIExpressionCursor &ExprCursor) {
304 auto Op = ExprCursor.take();
305 assert(Op && Op->getOp() == dwarf::DW_OP_entry_value);
306 assert(!isMemoryLocation() &&
307 "We don't support entry values of memory locations yet");
309 if (DwarfVersion >= 5)
310 emitOp(dwarf::DW_OP_entry_value);
312 emitOp(dwarf::DW_OP_GNU_entry_value);
313 emitUnsigned(Op->getArg(0));
316 /// Assuming a well-formed expression, match "DW_OP_deref* DW_OP_LLVM_fragment?".
317 static bool isMemoryLocation(DIExpressionCursor ExprCursor) {
319 auto Op = ExprCursor.take();
320 switch (Op->getOp()) {
321 case dwarf::DW_OP_deref:
322 case dwarf::DW_OP_LLVM_fragment:
331 void DwarfExpression::addExpression(DIExpressionCursor &&ExprCursor,
332 unsigned FragmentOffsetInBits) {
333 // If we need to mask out a subregister, do it now, unless the next
334 // operation would emit an OpPiece anyway.
335 auto N = ExprCursor.peek();
336 if (SubRegisterSizeInBits && N && (N->getOp() != dwarf::DW_OP_LLVM_fragment))
339 Optional<DIExpression::ExprOperand> PrevConvertOp = None;
342 auto Op = ExprCursor.take();
343 switch (Op->getOp()) {
344 case dwarf::DW_OP_LLVM_fragment: {
345 unsigned SizeInBits = Op->getArg(1);
346 unsigned FragmentOffset = Op->getArg(0);
347 // The fragment offset must have already been adjusted by emitting an
348 // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
350 assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
352 // If addMachineReg already emitted DW_OP_piece operations to represent
353 // a super-register by splicing together sub-registers, subtract the size
354 // of the pieces that was already emitted.
355 SizeInBits -= OffsetInBits - FragmentOffset;
357 // If addMachineReg requested a DW_OP_bit_piece to stencil out a
358 // sub-register that is smaller than the current fragment's size, use it.
359 if (SubRegisterSizeInBits)
360 SizeInBits = std::min<unsigned>(SizeInBits, SubRegisterSizeInBits);
362 // Emit a DW_OP_stack_value for implicit location descriptions.
363 if (isImplicitLocation())
366 // Emit the DW_OP_piece.
367 addOpPiece(SizeInBits, SubRegisterOffsetInBits);
368 setSubRegisterPiece(0, 0);
369 // Reset the location description kind.
370 LocationKind = Unknown;
373 case dwarf::DW_OP_plus_uconst:
374 assert(!isRegisterLocation());
375 emitOp(dwarf::DW_OP_plus_uconst);
376 emitUnsigned(Op->getArg(0));
378 case dwarf::DW_OP_plus:
379 case dwarf::DW_OP_minus:
380 case dwarf::DW_OP_mul:
381 case dwarf::DW_OP_div:
382 case dwarf::DW_OP_mod:
383 case dwarf::DW_OP_or:
384 case dwarf::DW_OP_and:
385 case dwarf::DW_OP_xor:
386 case dwarf::DW_OP_shl:
387 case dwarf::DW_OP_shr:
388 case dwarf::DW_OP_shra:
389 case dwarf::DW_OP_lit0:
390 case dwarf::DW_OP_not:
391 case dwarf::DW_OP_dup:
394 case dwarf::DW_OP_deref:
395 assert(!isRegisterLocation());
396 if (!isMemoryLocation() && ::isMemoryLocation(ExprCursor))
397 // Turning this into a memory location description makes the deref
399 LocationKind = Memory;
401 emitOp(dwarf::DW_OP_deref);
403 case dwarf::DW_OP_constu:
404 assert(!isRegisterLocation());
405 emitConstu(Op->getArg(0));
407 case dwarf::DW_OP_LLVM_convert: {
408 unsigned BitSize = Op->getArg(0);
409 dwarf::TypeKind Encoding = static_cast<dwarf::TypeKind>(Op->getArg(1));
410 if (DwarfVersion >= 5) {
411 emitOp(dwarf::DW_OP_convert);
412 // Reuse the base_type if we already have one in this CU otherwise we
414 unsigned I = 0, E = CU.ExprRefedBaseTypes.size();
416 if (CU.ExprRefedBaseTypes[I].BitSize == BitSize &&
417 CU.ExprRefedBaseTypes[I].Encoding == Encoding)
421 CU.ExprRefedBaseTypes.emplace_back(BitSize, Encoding);
423 // If targeting a location-list; simply emit the index into the raw
424 // byte stream as ULEB128, DwarfDebug::emitDebugLocEntry has been
425 // fitted with means to extract it later.
426 // If targeting a inlined DW_AT_location; insert a DIEBaseTypeRef
427 // (containing the index and a resolve mechanism during emit) into the
431 if (PrevConvertOp && PrevConvertOp->getArg(0) < BitSize) {
432 if (Encoding == dwarf::DW_ATE_signed)
433 emitLegacySExt(PrevConvertOp->getArg(0));
434 else if (Encoding == dwarf::DW_ATE_unsigned)
435 emitLegacyZExt(PrevConvertOp->getArg(0));
436 PrevConvertOp = None;
443 case dwarf::DW_OP_stack_value:
444 LocationKind = Implicit;
446 case dwarf::DW_OP_swap:
447 assert(!isRegisterLocation());
448 emitOp(dwarf::DW_OP_swap);
450 case dwarf::DW_OP_xderef:
451 assert(!isRegisterLocation());
452 emitOp(dwarf::DW_OP_xderef);
454 case dwarf::DW_OP_deref_size:
455 emitOp(dwarf::DW_OP_deref_size);
456 emitData1(Op->getArg(0));
458 case dwarf::DW_OP_LLVM_tag_offset:
459 TagOffset = Op->getArg(0);
462 llvm_unreachable("unhandled opcode found in expression");
466 if (isImplicitLocation())
467 // Turn this into an implicit location description.
471 /// add masking operations to stencil out a subregister.
472 void DwarfExpression::maskSubRegister() {
473 assert(SubRegisterSizeInBits && "no subregister was registered");
474 if (SubRegisterOffsetInBits > 0)
475 addShr(SubRegisterOffsetInBits);
476 uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
480 void DwarfExpression::finalize() {
481 assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
482 // Emit any outstanding DW_OP_piece operations to mask out subregisters.
483 if (SubRegisterSizeInBits == 0)
485 // Don't emit a DW_OP_piece for a subregister at offset 0.
486 if (SubRegisterOffsetInBits == 0)
488 addOpPiece(SubRegisterSizeInBits, SubRegisterOffsetInBits);
491 void DwarfExpression::addFragmentOffset(const DIExpression *Expr) {
492 if (!Expr || !Expr->isFragment())
495 uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
496 assert(FragmentOffset >= OffsetInBits &&
497 "overlapping or duplicate fragments");
498 if (FragmentOffset > OffsetInBits)
499 addOpPiece(FragmentOffset - OffsetInBits);
500 OffsetInBits = FragmentOffset;
503 void DwarfExpression::emitLegacySExt(unsigned FromBits) {
504 // (((X >> (FromBits - 1)) * (~0)) << FromBits) | X
505 emitOp(dwarf::DW_OP_dup);
506 emitOp(dwarf::DW_OP_constu);
507 emitUnsigned(FromBits - 1);
508 emitOp(dwarf::DW_OP_shr);
509 emitOp(dwarf::DW_OP_lit0);
510 emitOp(dwarf::DW_OP_not);
511 emitOp(dwarf::DW_OP_mul);
512 emitOp(dwarf::DW_OP_constu);
513 emitUnsigned(FromBits);
514 emitOp(dwarf::DW_OP_shl);
515 emitOp(dwarf::DW_OP_or);
518 void DwarfExpression::emitLegacyZExt(unsigned FromBits) {
519 // (X & (1 << FromBits - 1))
520 emitOp(dwarf::DW_OP_constu);
521 emitUnsigned((1ULL << FromBits) - 1);
522 emitOp(dwarf::DW_OP_and);