LLVM 24.0.0git
DwarfExpression.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/DwarfExpression.cpp - Dwarf Debug Framework -----------===//
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 debug info into asm files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DwarfExpression.h"
14#include "DwarfCompileUnit.h"
15#include "llvm/ADT/APInt.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/MC/MCAsmInfo.h"
23#include <algorithm>
24
25using namespace llvm;
26
27#define DEBUG_TYPE "dwarfdebug"
28
29/// Return whether the rest of the expression needs the complex register path.
30/// We use this to decide whether we can emit a simple register location and
31/// whether a subregister needs to be masked. Non-emitting operations don't
32/// affect either decision, so look past them.
33static bool isRemainingExpressionComplex(const DIExpressionCursor &ExprCursor) {
34 for (DIExpression::ExprOperand Op : ExprCursor) {
35 if (Op.isNonEmitting())
36 continue;
37 return Op.getOp() != dwarf::DW_OP_LLVM_fragment;
38 }
39 return false;
40}
41
43 if (Value < 32)
44 emitOp(dwarf::DW_OP_lit0 + Value);
45 else if (Value == std::numeric_limits<uint64_t>::max()) {
46 // Only do this for 64-bit values as the DWARF expression stack uses
47 // target-address-size values.
48 emitOp(dwarf::DW_OP_lit0);
49 emitOp(dwarf::DW_OP_not);
50 } else {
51 emitOp(dwarf::DW_OP_constu);
53 }
54}
55
56void DwarfExpression::addReg(int64_t DwarfReg, const char *Comment) {
57 assert(DwarfReg >= 0 && "invalid negative dwarf register number");
59 "location description already locked down");
61 if (DwarfReg < 32) {
62 emitOp(dwarf::DW_OP_reg0 + DwarfReg, Comment);
63 } else {
64 emitOp(dwarf::DW_OP_regx, Comment);
65 emitUnsigned(DwarfReg);
66 }
67}
68
69void DwarfExpression::addBReg(int64_t DwarfReg, int64_t Offset) {
70 assert(DwarfReg >= 0 && "invalid negative dwarf register number");
71 assert(!isRegisterLocation() && "location description already locked down");
72 if (DwarfReg < 32) {
73 emitOp(dwarf::DW_OP_breg0 + DwarfReg);
74 } else {
75 emitOp(dwarf::DW_OP_bregx);
76 emitUnsigned(DwarfReg);
77 }
79}
80
82 emitOp(dwarf::DW_OP_fbreg);
84}
85
86void DwarfExpression::addOpPiece(unsigned SizeInBits, unsigned OffsetInBits) {
87 if (!SizeInBits)
88 return;
89
90 const unsigned SizeOfByte = 8;
91 if (OffsetInBits > 0 || SizeInBits % SizeOfByte) {
92 emitOp(dwarf::DW_OP_bit_piece);
93 emitUnsigned(SizeInBits);
95 } else {
96 emitOp(dwarf::DW_OP_piece);
97 unsigned ByteSize = SizeInBits / SizeOfByte;
98 emitUnsigned(ByteSize);
99 }
100 this->OffsetInBits += SizeInBits;
101}
102
103void DwarfExpression::addShr(unsigned ShiftBy) {
104 emitConstu(ShiftBy);
105 emitOp(dwarf::DW_OP_shr);
106}
107
108void DwarfExpression::addAnd(unsigned Mask) {
109 emitConstu(Mask);
110 emitOp(dwarf::DW_OP_and);
111}
112
114 llvm::Register MachineReg,
115 unsigned MaxSize) {
116 if (!MachineReg.isPhysical()) {
117 if (isFrameRegister(TRI, MachineReg)) {
118 DwarfRegs.push_back(Register::createRegister(-1, nullptr));
119 return true;
120 }
121 // Try getting dwarf register for targets that use virtual registers.
122 int64_t Reg = TRI.getDwarfRegNumForVirtReg(MachineReg, false);
123 if (Reg > 0) {
124 DwarfRegs.push_back(Register::createRegister(Reg, nullptr));
125 return true;
126 }
127 return false;
128 }
129
130 int64_t Reg = TRI.getDwarfRegNum(MachineReg, false);
131
132 // If this is a valid register number, emit it.
133 if (Reg >= 0) {
134 DwarfRegs.push_back(Register::createRegister(Reg, nullptr));
135 return true;
136 }
137
138 // The frame register is referenced through DW_OP_fbreg relative to
139 // DW_AT_frame_base, so it needs no DWARF register number of its own.
140 if (isFrameRegister(TRI, MachineReg)) {
141 DwarfRegs.push_back(Register::createRegister(-1, nullptr));
142 return true;
143 }
144
145 // Walk up the super-register chain until we find a valid number.
146 // For example, EAX on x86_64 is a 32-bit fragment of RAX with offset 0.
147 for (MCPhysReg SR : TRI.superregs(MachineReg)) {
148 Reg = TRI.getDwarfRegNum(SR, false);
149 if (Reg >= 0) {
150 unsigned Idx = TRI.getSubRegIndex(SR, MachineReg);
151 unsigned Size = TRI.getSubRegIdxSize(Idx);
152 unsigned RegOffset = TRI.getSubRegIdxOffset(Idx);
153 DwarfRegs.push_back(Register::createRegister(Reg, "super-register"));
154 // Use a DW_OP_bit_piece to describe the sub-register.
155 setSubRegisterPiece(Size, RegOffset);
156 return true;
157 }
158 }
159
160 // Otherwise, attempt to find a covering set of sub-register numbers.
161 // For example, Q0 on ARM is a composition of D0+D1.
162 unsigned CurPos = 0;
163 // The size of the register in bits.
164 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(MachineReg);
165 unsigned RegSize = TRI.getRegSizeInBits(*RC);
166 // Keep track of the bits in the register we already emitted, so we
167 // can avoid emitting redundant aliasing subregs. Because this is
168 // just doing a greedy scan of all subregisters, it is possible that
169 // this doesn't find a combination of subregisters that fully cover
170 // the register (even though one may exist).
171 SmallBitVector Coverage(RegSize, false);
172 for (MCPhysReg SR : TRI.subregs(MachineReg)) {
173 unsigned Idx = TRI.getSubRegIndex(MachineReg, SR);
174 unsigned Size = TRI.getSubRegIdxSize(Idx);
175 unsigned Offset = TRI.getSubRegIdxOffset(Idx);
176 Reg = TRI.getDwarfRegNum(SR, false);
178 continue;
179
180 // Used to build the intersection between the bits we already
181 // emitted and the bits covered by this subregister.
182 SmallBitVector CurSubReg(RegSize, false);
183 CurSubReg.set(Offset, Offset + Size);
184
185 // If this sub-register has a DWARF number and we haven't covered
186 // its range, and its range covers the value, emit a DWARF piece for it.
187 if (Offset < MaxSize && !CurSubReg.subsetOf(Coverage)) {
188 // Emit a piece for any gap in the coverage.
189 if (Offset > CurPos)
191 -1, Offset - CurPos, "no DWARF register encoding"));
192 if (Offset == 0 && Size >= MaxSize)
193 DwarfRegs.push_back(Register::createRegister(Reg, "sub-register"));
194 else
196 Reg, std::min<unsigned>(Size, MaxSize - Offset), "sub-register"));
197 }
198 // Mark it as emitted.
199 Coverage.set(Offset, Offset + Size);
200 CurPos = Offset + Size;
201 }
202 // Failed to find any DWARF encoding.
203 if (CurPos == 0)
204 return false;
205 // Found a partial or complete DWARF encoding.
206 if (CurPos < RegSize)
208 -1, RegSize - CurPos, "no DWARF register encoding"));
209 return true;
210}
211
213 if (DwarfVersion >= 4)
214 emitOp(dwarf::DW_OP_stack_value);
215}
216
220 if (Value == 0)
221 emitOp(dwarf::DW_OP_lit0);
222 else
223 emitOp(dwarf::DW_OP_lit1);
224}
225
232
238
242
243 unsigned Size = Value.getBitWidth();
244 const uint64_t *Data = Value.getRawData();
245
246 // Chop it up into 64-bit pieces, because that's the maximum that
247 // addUnsignedConstant takes.
248 unsigned Offset = 0;
249 while (Offset < Size) {
251 if (Offset == 0 && Size <= 64)
252 break;
254 addOpPiece(std::min(Size - Offset, 64u), Offset);
255 Offset += 64;
256 }
257}
258
260 const AsmPrinter &AP) {
262 assert(DwarfVersion >= 4);
263
264 APInt API = Value;
265 unsigned NumBytes = API.getBitWidth() / 8;
266 assert(API.getBitWidth() == NumBytes * 8 &&
267 "implicit value must be byte-sized");
268
269 emitOp(dwarf::DW_OP_implicit_value);
270 emitUnsigned(NumBytes);
271
272 // The loop below is emitting the value starting at the least significant
273 // byte, so byte-swap first for big-endian targets.
274 if (AP.getDataLayout().isBigEndian())
275 API = API.byteSwap();
276
277 for (unsigned I = 0; I < NumBytes; ++I)
278 emitData1(API.extractBits(8, I * 8).getZExtValue());
279}
280
283 APInt API = APF.bitcastToAPInt();
284 int NumBytes = API.getBitWidth() / 8;
285 if (NumBytes == 4 /*float*/ || NumBytes == 8 /*double*/) {
286 // FIXME: Add support for `long double`.
287 emitOp(dwarf::DW_OP_implicit_value);
288 emitUnsigned(NumBytes /*Size of the block in bytes*/);
289
290 // The loop below is emitting the value starting at least significant byte,
291 // so we need to perform a byte-swap to get the byte order correct in case
292 // of a big-endian target.
293 if (AP.getDataLayout().isBigEndian())
294 API = API.byteSwap();
295
296 for (int i = 0; i < NumBytes; ++i) {
297 emitData1(API.getZExtValue() & 0xFF);
298 API = API.lshr(8);
299 }
300
301 return;
302 }
304 dbgs() << "Skipped DW_OP_implicit_value creation for ConstantFP of size: "
305 << API.getBitWidth() << " bits\n");
306}
307
309 DIExpressionCursor &ExprCursor,
310 llvm::Register MachineReg,
311 unsigned FragmentOffsetInBits) {
312 auto Fragment = ExprCursor.getFragmentInfo();
313 if (!addMachineReg(TRI, MachineReg, Fragment ? Fragment->SizeInBits : ~1U)) {
315 return false;
316 }
317
318 bool HasComplexExpression = isRemainingExpressionComplex(ExprCursor);
319
320 // If the register can only be described by a complex expression (i.e.,
321 // multiple subregisters) it doesn't safely compose with another complex
322 // expression. For example, it is not possible to apply a DW_OP_deref
323 // operation to multiple DW_OP_pieces, since composite location descriptions
324 // do not push anything on the DWARF stack.
325 //
326 // DW_OP_entry_value operations can only hold a DWARF expression or a
327 // register location description, so we can't emit a single entry value
328 // covering a composite location description. In the future we may want to
329 // emit entry value operations for each register location in the composite
330 // location, but until that is supported do not emit anything.
331 if ((HasComplexExpression || IsEmittingEntryValue) && DwarfRegs.size() > 1) {
334 DwarfRegs.clear();
336 return false;
337 }
338
339 // Handle simple register locations. If we are supposed to emit
340 // a call site parameter expression and if that expression is just a register
341 // location, emit it with addBReg and offset 0, because we should emit a DWARF
342 // expression representing a value, rather than a location.
343 if ((!isParameterValue() && !isMemoryLocation() && !HasComplexExpression) ||
344 isEntryValue()) {
345 unsigned RegSize = 0;
346 for (auto &Reg : DwarfRegs) {
347 RegSize += Reg.SubRegSize;
348 if (Reg.DwarfRegNo >= 0)
349 addReg(Reg.DwarfRegNo, Reg.Comment);
350 if (Fragment && RegSize > Fragment->SizeInBits)
351 // If the register is larger than the current fragment stop
352 // once the fragment is covered.
353 break;
354 addOpPiece(Reg.SubRegSize);
355 }
356
357 if (isEntryValue()) {
359
360 if (!isIndirect() && !isParameterValue() && !HasComplexExpression &&
361 DwarfVersion >= 4)
362 emitOp(dwarf::DW_OP_stack_value);
363 }
364
365 DwarfRegs.clear();
366 // If we need to mask out a subregister, do it now, unless the next
367 // operation would emit an OpPiece anyway.
370 return true;
371 }
372
373 // Don't emit locations that cannot be expressed without DW_OP_stack_value.
374 if (DwarfVersion < 4)
375 if (any_of(ExprCursor, [](DIExpression::ExprOperand Op) -> bool {
376 return Op.getOp() == dwarf::DW_OP_stack_value;
377 })) {
378 DwarfRegs.clear();
380 return false;
381 }
382
383 // TODO: We should not give up here but the following code needs to be changed
384 // to deal with multiple (sub)registers first.
385 if (DwarfRegs.size() > 1) {
386 LLVM_DEBUG(dbgs() << "TODO: giving up on debug information due to "
387 "multi-register usage.\n");
388 DwarfRegs.clear();
390 return false;
391 }
392
393 // Consume leading tag offsets before matching the register expression.
394 // Record the tag offset here because addExpression won't see a consumed
395 // operation.
396 while (auto Op = ExprCursor.peek()) {
398 if (!Tag)
399 break;
400 TagOffset = Tag.getTagOffset();
401 ExprCursor.take();
402 }
403
404 auto Op = ExprCursor.peek();
405 auto Reg = DwarfRegs[0];
406 int SignedOffset = 0;
407 assert(!Reg.isSubRegister() && "full register expected");
408
409 // Pattern-match combinations for which more efficient representations exist.
410 if (Op) {
411 const uint64_t IntMax =
412 static_cast<uint64_t>(std::numeric_limits<int>::max());
413 // [Reg, DW_OP_plus_uconst, Offset] --> [DW_OP_breg, Offset].
414 if (auto PlusUconst = dyn_cast<DIExpression::PlusUconstOp>(*Op)) {
415 uint64_t Offset = PlusUconst.getOffset();
416 if (Offset <= IntMax) {
417 SignedOffset = Offset;
418 ExprCursor.take();
419 }
420 } else if (auto Constant = dyn_cast<DIExpression::ConstuOp>(*Op)) {
421 // [Reg, DW_OP_constu, Offset, DW_OP_plus] --> [DW_OP_breg, Offset]
422 // [Reg, DW_OP_constu, Offset, DW_OP_minus] --> [DW_OP_breg,-Offset]
423 // If Reg is a subregister we need to mask it out before subtracting.
424 uint64_t Offset = Constant.getValue();
425 auto N = ExprCursor.peekNext();
426 if (N && N->getOp() == dwarf::DW_OP_plus && Offset <= IntMax) {
427 SignedOffset = Offset;
428 ExprCursor.consume(2);
429 } else if (N && N->getOp() == dwarf::DW_OP_minus &&
430 !SubRegisterSizeInBits && Offset <= IntMax + 1) {
431 SignedOffset = -static_cast<int64_t>(Offset);
432 ExprCursor.consume(2);
433 }
434 }
435 }
436
437 if (isFrameRegister(TRI, MachineReg))
438 addFBReg(SignedOffset);
439 else
440 addBReg(Reg.DwarfRegNo, SignedOffset);
441 DwarfRegs.clear();
442
443 // If we need to mask out a subregister, do it now, unless the next
444 // operation would emit an OpPiece anyway.
447
448 return true;
449}
450
456
458 const DIExpression *DIExpr) {
459 if (Loc.isIndirect())
461
462 if (DIExpr->isEntryValue())
464}
465
467 DIExpressionCursor &ExprCursor) {
468 auto Op = ExprCursor.take();
469 (void)Op;
471 assert(!IsEmittingEntryValue && "Already emitting entry value?");
472 assert(cast<DIExpression::EntryValueOp>(*Op).getNumOperations() == 1 &&
473 "Can currently only emit entry values covering a single operation");
474
480}
481
483 assert(IsEmittingEntryValue && "Entry value not open?");
485
486 emitOp(CU.getDwarf5OrGNULocationAtom(dwarf::DW_OP_entry_value));
487
488 // Emit the entry value's size operand.
489 unsigned Size = getTemporaryBufferSize();
491
492 // Emit the entry value's DWARF block operand.
494
497 IsEmittingEntryValue = false;
498}
499
501 assert(IsEmittingEntryValue && "Entry value not open?");
503
504 // The temporary buffer can't be emptied, so for now just assert that nothing
505 // has been emitted to it.
507 "Began emitting entry value block before cancelling entry value");
508
510 IsEmittingEntryValue = false;
511}
512
513unsigned DwarfExpression::getOrCreateBaseType(unsigned BitSize,
514 dwarf::TypeKind Encoding) {
515 // Reuse the base_type if we already have one in this CU otherwise we
516 // create a new one.
517 unsigned I = 0, E = CU.ExprRefedBaseTypes.size();
518 for (; I != E; ++I)
519 if (CU.ExprRefedBaseTypes[I].BitSize == BitSize &&
520 CU.ExprRefedBaseTypes[I].Encoding == Encoding)
521 break;
522
523 if (I == E)
524 CU.ExprRefedBaseTypes.emplace_back(BitSize, Encoding);
525 return I;
526}
527
528/// Assuming a well-formed expression, match "DW_OP_deref*
529/// DW_OP_LLVM_fragment?".
530static bool isMemoryLocation(DIExpressionCursor ExprCursor) {
531 while (ExprCursor) {
532 auto Op = ExprCursor.take();
533 switch (Op->getOp()) {
534 case dwarf::DW_OP_deref:
536 break;
537 default:
538 return false;
539 }
540 }
541 return true;
542}
543
545 addExpression(std::move(ExprCursor),
546 [](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
547 llvm_unreachable("unhandled opcode found in expression");
548 });
549}
550
552 DIExpressionCursor &&ExprCursor,
553 llvm::function_ref<bool(unsigned, DIExpressionCursor &)> InsertArg) {
554 // Entry values can currently only cover the initial register location,
555 // and not any other parts of the following DWARF expression.
556 assert(!IsEmittingEntryValue && "Can't emit entry value around expression");
557
558 std::optional<DIExpression::ConvertOp> PrevConvertOp;
559
560 while (ExprCursor) {
561 auto Op = ExprCursor.take();
562 uint64_t OpNum = Op->getOp();
563
564 if (OpNum >= dwarf::DW_OP_reg0 && OpNum <= dwarf::DW_OP_reg31) {
565 emitOp(OpNum);
566 continue;
567 } else if (OpNum >= dwarf::DW_OP_breg0 && OpNum <= dwarf::DW_OP_breg31) {
568 addBReg(OpNum - dwarf::DW_OP_breg0, Op->getArg(0));
569 continue;
570 }
571
572 switch (OpNum) {
574 if (!InsertArg(cast<DIExpression::ArgOp>(*Op).getIndex(), ExprCursor)) {
576 return false;
577 }
578 break;
580 auto Fragment = cast<DIExpression::FragmentOp>(*Op);
581 unsigned SizeInBits = Fragment.getSizeInBits();
582 unsigned FragmentOffset = Fragment.getOffsetInBits();
583 // The fragment offset must have already been adjusted by emitting an
584 // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
585 // location.
586 assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
587 assert(SizeInBits >= OffsetInBits - FragmentOffset && "size underflow");
588
589 // If addMachineReg already emitted DW_OP_piece operations to represent
590 // a super-register by splicing together sub-registers, subtract the size
591 // of the pieces that was already emitted.
592 SizeInBits -= OffsetInBits - FragmentOffset;
593
594 // If addMachineReg requested a DW_OP_bit_piece to stencil out a
595 // sub-register that is smaller than the current fragment's size, use it.
597 SizeInBits = std::min<unsigned>(SizeInBits, SubRegisterSizeInBits);
598
599 // Emit a DW_OP_stack_value for implicit location descriptions.
600 if (isImplicitLocation())
602
603 // Emit the DW_OP_piece.
606 // Reset the location description kind.
608 return true;
609 }
612 auto Extract = cast<DIExpression::ExtractBitsOp>(*Op);
613 unsigned SizeInBits = Extract.getSizeInBits();
614 unsigned BitOffset = Extract.getOffsetInBits();
615 bool IsSigned = Extract.isSigned();
616 unsigned DerefSize = 0;
617 // Operations are done in the DWARF "generic type" whose size
618 // is the size of a pointer.
619 unsigned PtrSizeInBytes = CU.getAsmPrinter()->MAI.getCodePointerSize();
620
621 // If we have a memory location then dereference to get the value, though
622 // we have to make sure we don't dereference any bytes past the end of the
623 // object.
624 if (isMemoryLocation()) {
625 DerefSize = alignTo(BitOffset + SizeInBits, 8) / 8;
626 if (DerefSize == PtrSizeInBytes) {
627 emitOp(dwarf::DW_OP_deref);
628 } else {
629 emitOp(dwarf::DW_OP_deref_size);
630 emitUnsigned(DerefSize);
631 }
632 }
633
634 // If a dereference was emitted for an unsigned value, and
635 // there's no bit offset, then a bit of optimization is
636 // possible.
637 if (!IsSigned && BitOffset == 0) {
638 if (8 * DerefSize == SizeInBits) {
639 // The correct value is already on the stack.
640 } else {
641 // No need to shift, we can just mask off the desired bits.
642 emitOp(dwarf::DW_OP_constu);
643 emitUnsigned((1u << SizeInBits) - 1);
644 emitOp(dwarf::DW_OP_and);
645 }
646 } else {
647 // Extract the bits by a shift left (to shift out the bits after what we
648 // want to extract) followed by shift right (to shift the bits to
649 // position 0 and also sign/zero extend).
650 unsigned LeftShift = PtrSizeInBytes * 8 - (SizeInBits + BitOffset);
651 unsigned RightShift = LeftShift + BitOffset;
652 if (LeftShift) {
653 emitOp(dwarf::DW_OP_constu);
654 emitUnsigned(LeftShift);
655 emitOp(dwarf::DW_OP_shl);
656 }
657 if (RightShift) {
658 emitOp(dwarf::DW_OP_constu);
659 emitUnsigned(RightShift);
660 emitOp(IsSigned ? dwarf::DW_OP_shra : dwarf::DW_OP_shr);
661 }
662 }
663
664 // The value is now at the top of the stack, so set the location to
665 // implicit so that we get a stack_value at the end.
667 break;
668 }
669 case dwarf::DW_OP_plus_uconst:
671 emitOp(dwarf::DW_OP_plus_uconst);
673 break;
674 case dwarf::DW_OP_plus:
675 case dwarf::DW_OP_minus:
676 case dwarf::DW_OP_mul:
677 case dwarf::DW_OP_div:
678 case dwarf::DW_OP_mod:
679 case dwarf::DW_OP_or:
680 case dwarf::DW_OP_and:
681 case dwarf::DW_OP_xor:
682 case dwarf::DW_OP_shl:
683 case dwarf::DW_OP_shr:
684 case dwarf::DW_OP_shra:
685 case dwarf::DW_OP_lit0:
686 case dwarf::DW_OP_not:
687 case dwarf::DW_OP_dup:
688 case dwarf::DW_OP_push_object_address:
689 case dwarf::DW_OP_over:
690 case dwarf::DW_OP_rot:
691 case dwarf::DW_OP_eq:
692 case dwarf::DW_OP_ne:
693 case dwarf::DW_OP_gt:
694 case dwarf::DW_OP_ge:
695 case dwarf::DW_OP_lt:
696 case dwarf::DW_OP_le:
697 case dwarf::DW_OP_neg:
698 case dwarf::DW_OP_abs:
699 emitOp(OpNum);
700 break;
701 case dwarf::DW_OP_deref:
703 if (!isMemoryLocation() && ::isMemoryLocation(ExprCursor))
704 // Turning this into a memory location description makes the deref
705 // implicit.
707 else
708 emitOp(dwarf::DW_OP_deref);
709 break;
710 case dwarf::DW_OP_constu:
713 break;
714 case dwarf::DW_OP_consts:
716 emitOp(dwarf::DW_OP_consts);
717 emitSigned(Op->getArg(0));
718 break;
720 auto Convert = cast<DIExpression::ConvertOp>(*Op);
721 unsigned BitSize = Convert.getBitSize();
722 dwarf::TypeKind Encoding =
723 static_cast<dwarf::TypeKind>(Convert.getEncoding());
724 if (DwarfVersion >= 5 && CU.getDwarfDebug().useOpConvert()) {
725 emitOp(dwarf::DW_OP_convert);
726 // If targeting a location-list; simply emit the index into the raw
727 // byte stream as ULEB128, DwarfDebug::emitDebugLocEntry has been
728 // fitted with means to extract it later.
729 // If targeting a inlined DW_AT_location; insert a DIEBaseTypeRef
730 // (containing the index and a resolve mechanism during emit) into the
731 // DIE value list.
732 emitBaseTypeRef(getOrCreateBaseType(BitSize, Encoding));
733 } else {
734 if (PrevConvertOp && PrevConvertOp->getBitSize() < BitSize) {
735 if (Encoding == dwarf::DW_ATE_signed)
736 emitLegacySExt(PrevConvertOp->getBitSize());
737 else if (Encoding == dwarf::DW_ATE_unsigned)
738 emitLegacyZExt(PrevConvertOp->getBitSize());
739 PrevConvertOp = std::nullopt;
740 } else {
741 PrevConvertOp = Convert;
742 }
743 }
744 break;
745 }
746 case dwarf::DW_OP_stack_value:
748 break;
749 case dwarf::DW_OP_swap:
751 emitOp(dwarf::DW_OP_swap);
752 break;
753 case dwarf::DW_OP_xderef:
755 emitOp(dwarf::DW_OP_xderef);
756 break;
757 case dwarf::DW_OP_deref_size:
758 emitOp(dwarf::DW_OP_deref_size);
759 emitData1(Op->getArg(0));
760 break;
762 TagOffset = cast<DIExpression::TagOffsetOp>(*Op).getTagOffset();
763 break;
764 case dwarf::DW_OP_regx:
765 emitOp(dwarf::DW_OP_regx);
766 emitUnsigned(Op->getArg(0));
767 break;
768 case dwarf::DW_OP_bregx:
769 emitOp(dwarf::DW_OP_bregx);
770 emitUnsigned(Op->getArg(0));
771 emitSigned(Op->getArg(1));
772 break;
774 // Handled in DwarfCompileUnit::emitImplicitPointerLocation for
775 // Loc::Single variables. If we reach here, the variable has a
776 // location list or other unsupported path. Drop the
777 // location rather than crashing.
778 return false;
779 default:
780 llvm_unreachable("unhandled opcode found in expression");
781 }
782 }
783
785 // Turn this into an implicit location description.
787
788 return true;
789}
790
791/// Emit shift/mask operations for the pending subregister. After the operations
792/// are emitted, consume the pending subregister description by clearing
793/// SubRegisterSizeInBits and SubRegisterOffsetInBits.
795 assert(SubRegisterSizeInBits && "no subregister was registered");
798 uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
799 addAnd(Mask);
800 // The mask consumes the pending subregister description.
802}
803
805 assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
806 // Emit any outstanding DW_OP_piece operations to mask out subregisters.
807 if (SubRegisterSizeInBits == 0)
808 return;
809 // Don't emit a DW_OP_piece for a subregister at offset 0.
811 return;
813}
814
816 if (!Expr || !Expr->isFragment())
817 return;
818
819 uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
820 assert(FragmentOffset >= OffsetInBits &&
821 "overlapping or duplicate fragments");
822 if (FragmentOffset > OffsetInBits)
823 addOpPiece(FragmentOffset - OffsetInBits);
824 OffsetInBits = FragmentOffset;
825}
826
827void DwarfExpression::emitLegacySExt(unsigned FromBits) {
828 // (((X >> (FromBits - 1)) * (~0)) << FromBits) | X
829 emitOp(dwarf::DW_OP_dup);
830 emitOp(dwarf::DW_OP_constu);
831 emitUnsigned(FromBits - 1);
832 emitOp(dwarf::DW_OP_shr);
833 emitOp(dwarf::DW_OP_lit0);
834 emitOp(dwarf::DW_OP_not);
835 emitOp(dwarf::DW_OP_mul);
836 emitOp(dwarf::DW_OP_constu);
837 emitUnsigned(FromBits);
838 emitOp(dwarf::DW_OP_shl);
839 emitOp(dwarf::DW_OP_or);
840}
841
842void DwarfExpression::emitLegacyZExt(unsigned FromBits) {
843 // Heuristic to decide the most efficient encoding.
844 // A ULEB can encode 7 1-bits per byte.
845 if (FromBits / 7 < 1+1+1+1+1) {
846 // (X & (1 << FromBits - 1))
847 emitOp(dwarf::DW_OP_constu);
848 emitUnsigned((1ULL << FromBits) - 1);
849 } else {
850 // Note that the DWARF 4 stack consists of pointer-sized elements,
851 // so technically it doesn't make sense to shift left more than 64
852 // bits. We leave that for the consumer to decide though. LLDB for
853 // example uses APInt for the stack elements and can still deal
854 // with this.
855 emitOp(dwarf::DW_OP_lit1);
856 emitOp(dwarf::DW_OP_constu);
857 emitUnsigned(FromBits);
858 emitOp(dwarf::DW_OP_shl);
859 emitOp(dwarf::DW_OP_lit1);
860 emitOp(dwarf::DW_OP_minus);
861 }
862 emitOp(dwarf::DW_OP_and);
863}
864
866 emitOp(dwarf::DW_OP_WASM_location);
867 emitUnsigned(Index == 4/*TI_LOCAL_INDIRECT*/ ? 0/*TI_LOCAL*/ : Index);
869 if (Index == 4 /*TI_LOCAL_INDIRECT*/) {
872 } else {
875 }
876}
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static bool isRemainingExpressionComplex(const DIExpressionCursor &ExprCursor)
Return whether the rest of the expression needs the complex register path.
static bool isMemoryLocation(DIExpressionCursor ExprCursor)
Assuming a well-formed expression, match "DW_OP_deref* DW_OP_LLVM_fragment?
This file contains constants used for implementing Dwarf debug support.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
This file implements the SmallBitVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
APInt bitcastToAPInt() const
Definition APFloat.h:1467
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:768
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:483
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
const DataLayout & getDataLayout() const
Return information about data layout.
This is an important base class in LLVM.
Definition Constant.h:43
Holds a DIExpression and keeps track of how many operands have been consumed so far.
std::optional< DIExpression::ExprOperand > peekNext() const
Return the next operation.
std::optional< DIExpression::FragmentInfo > getFragmentInfo() const
Retrieve the fragment information, if any.
std::optional< DIExpression::ExprOperand > peek() const
Return the current operation.
void consume(unsigned N)
Consume N operations.
std::optional< DIExpression::ExprOperand > take()
Consume one operation.
A lightweight wrapper around an expression operand.
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
bool isFragment() const
Return whether this is a piece of an aggregate variable.
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
bool isBigEndian() const
Definition DataLayout.h:218
void addAnd(unsigned Mask)
Emit a bitwise and dwarf operation.
void setLocation(const MachineLocation &Loc, const DIExpression *DIExpr)
Set the location (Loc) and DIExpression (DIExpr) to describe.
virtual void emitOp(uint8_t Op, const char *Comment=nullptr)=0
Output a dwarf operand and an optional assembler comment.
virtual void disableTemporaryBuffer()=0
Disable emission to the temporary buffer.
bool isUnknownLocation() const
virtual unsigned getTemporaryBufferSize()=0
Return the emitted size, in number of bytes, for the data stored in the temporary buffer.
uint64_t OffsetInBits
Current Fragment Offset in Bits.
virtual bool isFrameRegister(const TargetRegisterInfo &TRI, llvm::Register MachineReg)=0
Return whether the given machine register is the frame register in the current function.
void finalize()
This needs to be called last to commit any pending changes.
void addFragmentOffset(const DIExpression *Expr)
If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to the fragment described by Ex...
void emitLegacySExt(unsigned FromBits)
void cancelEntryValue()
Cancel the emission of an entry value.
bool isRegisterLocation() const
void setMemoryLocationKind()
Lock this down to become a memory location description.
virtual void emitBaseTypeRef(uint64_t Idx)=0
virtual void emitData1(uint8_t Value)=0
bool addMachineReg(const TargetRegisterInfo &TRI, llvm::Register MachineReg, unsigned MaxSize=~1U)
Emit a partial DWARF register operation.
std::optional< uint8_t > TagOffset
bool isImplicitLocation() const
virtual void emitUnsigned(uint64_t Value)=0
Emit a raw unsigned value.
void addBooleanConstant(int64_t Value)
Emit a boolean constant.
void addConstantFP(const APFloat &Value, const AsmPrinter &AP)
Emit an floating point constant.
void maskSubRegister()
Emit shift/mask operations for the pending subregister.
SmallVector< Register, 2 > DwarfRegs
The register location, if any.
bool addMachineRegExpression(const TargetRegisterInfo &TRI, DIExpressionCursor &Expr, llvm::Register MachineReg, unsigned FragmentOffsetInBits=0)
Emit a machine register location.
void addStackValue()
Emit a DW_OP_stack_value, if supported.
void finalizeEntryValue()
Finalize an entry value by emitting its size operand, and committing the DWARF block which has been e...
bool isMemoryLocation() const
void addUnsignedConstant(uint64_t Value)
Emit an unsigned constant.
unsigned SubRegisterSizeInBits
Sometimes we need to add a DW_OP_bit_piece to describe a subregister.
void addFBReg(int64_t Offset)
Emit DW_OP_fbreg <Offset>.
void setSubRegisterPiece(unsigned SizeInBits, unsigned OffsetInBits)
Push a DW_OP_piece / DW_OP_bit_piece for emitting later, if one is needed to represent a subregister.
void addExpression(DIExpressionCursor &&Expr)
Emit all remaining operations in the DIExpressionCursor.
unsigned getOrCreateBaseType(unsigned BitSize, dwarf::TypeKind Encoding)
Return the index of a base type with the given properties and create one if necessary.
void addImplicitValue(const APInt &Value, const AsmPrinter &AP)
Emit an implicit value.
void addSignedConstant(int64_t Value)
Emit a signed constant.
void emitLegacyZExt(unsigned FromBits)
bool IsEmittingEntryValue
Whether we are currently emitting an entry value operation.
virtual void emitSigned(int64_t Value)=0
Emit a raw signed value.
void addReg(int64_t DwarfReg, const char *Comment=nullptr)
Emit a DW_OP_reg operation.
void setEntryValueFlags(const MachineLocation &Loc)
Lock this down to become an entry value location.
virtual void commitTemporaryBuffer()=0
Commit the data stored in the temporary buffer to the main output.
void addShr(unsigned ShiftBy)
Emit a shift-right dwarf operation.
void addWasmLocation(unsigned Index, uint64_t Offset)
Emit location information expressed via WebAssembly location + offset The Index is an identifier for ...
virtual void enableTemporaryBuffer()=0
Start emitting data to the temporary buffer.
void emitConstu(uint64_t Value)
Emit a normalized unsigned constant.
void beginEntryValueExpression(DIExpressionCursor &ExprCursor)
Begin emission of an entry value dwarf operation.
void addOpPiece(unsigned SizeInBits, unsigned OffsetInBits=0)
Emit a DW_OP_piece or DW_OP_bit_piece operation for a variable fragment.
void addBReg(int64_t DwarfReg, int64_t Offset)
Emit a DW_OP_breg operation.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
bool subsetOf(const SmallBitVector &RHS) const
Check if This is a subset of RHS.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM Value Representation.
Definition Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ DW_OP_LLVM_implicit_pointer
Only used in LLVM metadata.
Definition Dwarf.h:148
@ DW_OP_LLVM_extract_bits_zext
Only used in LLVM metadata.
Definition Dwarf.h:151
@ DW_OP_LLVM_tag_offset
Only used in LLVM metadata.
Definition Dwarf.h:146
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
Definition Dwarf.h:144
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
@ DW_OP_LLVM_convert
Only used in LLVM metadata.
Definition Dwarf.h:145
@ DW_OP_LLVM_extract_bits_sext
Only used in LLVM metadata.
Definition Dwarf.h:150
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N
Holds information about all subregisters comprising a register location.
static Register createRegister(int64_t RegNo, const char *Comment)
Create a full register, no extra DW_OP_piece operators necessary.
static Register createSubRegister(int64_t RegNo, unsigned SizeInBits, const char *Comment)
Create a subregister that needs a DW_OP_piece operator with SizeInBits.