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"
16#include "llvm/ADT/SmallBitVector.h"
17#include "llvm/BinaryFormat/Dwarf.h"
18#include "llvm/CodeGen/Register.h"
19#include "llvm/CodeGen/TargetRegisterInfo.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/MC/MCAsmInfo.h"
22#include "llvm/Support/ErrorHandling.h"
23#include <algorithm>
24
25using namespace llvm;
26
27#define DEBUG_TYPE "dwarfdebug"
28
29void DwarfExpression::emitConstu(uint64_t Value) {
30 if (Value < 32)
31 emitOp(Op: dwarf::DW_OP_lit0 + Value);
32 else if (Value == std::numeric_limits<uint64_t>::max()) {
33 // Only do this for 64-bit values as the DWARF expression stack uses
34 // target-address-size values.
35 emitOp(Op: dwarf::DW_OP_lit0);
36 emitOp(Op: dwarf::DW_OP_not);
37 } else {
38 emitOp(Op: dwarf::DW_OP_constu);
39 emitUnsigned(Value);
40 }
41}
42
43void DwarfExpression::addReg(int64_t DwarfReg, const char *Comment) {
44 assert(DwarfReg >= 0 && "invalid negative dwarf register number");
45 assert((isUnknownLocation() || isRegisterLocation()) &&
46 "location description already locked down");
47 LocationKind = Register;
48 if (DwarfReg < 32) {
49 emitOp(Op: dwarf::DW_OP_reg0 + DwarfReg, Comment);
50 } else {
51 emitOp(Op: dwarf::DW_OP_regx, Comment);
52 emitUnsigned(Value: DwarfReg);
53 }
54}
55
56void DwarfExpression::addBReg(int64_t DwarfReg, int64_t Offset) {
57 assert(DwarfReg >= 0 && "invalid negative dwarf register number");
58 assert(!isRegisterLocation() && "location description already locked down");
59 if (DwarfReg < 32) {
60 emitOp(Op: dwarf::DW_OP_breg0 + DwarfReg);
61 } else {
62 emitOp(Op: dwarf::DW_OP_bregx);
63 emitUnsigned(Value: DwarfReg);
64 }
65 emitSigned(Value: Offset);
66}
67
68void DwarfExpression::addFBReg(int64_t Offset) {
69 emitOp(Op: dwarf::DW_OP_fbreg);
70 emitSigned(Value: Offset);
71}
72
73void DwarfExpression::addOpPiece(unsigned SizeInBits, unsigned OffsetInBits) {
74 if (!SizeInBits)
75 return;
76
77 const unsigned SizeOfByte = 8;
78 if (OffsetInBits > 0 || SizeInBits % SizeOfByte) {
79 emitOp(Op: dwarf::DW_OP_bit_piece);
80 emitUnsigned(Value: SizeInBits);
81 emitUnsigned(Value: OffsetInBits);
82 } else {
83 emitOp(Op: dwarf::DW_OP_piece);
84 unsigned ByteSize = SizeInBits / SizeOfByte;
85 emitUnsigned(Value: ByteSize);
86 }
87 this->OffsetInBits += SizeInBits;
88}
89
90void DwarfExpression::addShr(unsigned ShiftBy) {
91 emitConstu(Value: ShiftBy);
92 emitOp(Op: dwarf::DW_OP_shr);
93}
94
95void DwarfExpression::addAnd(unsigned Mask) {
96 emitConstu(Value: Mask);
97 emitOp(Op: dwarf::DW_OP_and);
98}
99
100bool DwarfExpression::addMachineReg(const TargetRegisterInfo &TRI,
101 llvm::Register MachineReg,
102 unsigned MaxSize) {
103 if (!MachineReg.isPhysical()) {
104 if (isFrameRegister(TRI, MachineReg)) {
105 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: -1, Comment: nullptr));
106 return true;
107 }
108 // Try getting dwarf register for targets that use virtual registers.
109 int64_t Reg = TRI.getDwarfRegNumForVirtReg(RegNum: MachineReg, isEH: false);
110 if (Reg > 0) {
111 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: Reg, Comment: nullptr));
112 return true;
113 }
114 return false;
115 }
116
117 int64_t Reg = TRI.getDwarfRegNum(Reg: MachineReg, isEH: false);
118
119 // If this is a valid register number, emit it.
120 if (Reg >= 0) {
121 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: Reg, Comment: nullptr));
122 return true;
123 }
124
125 // Walk up the super-register chain until we find a valid number.
126 // For example, EAX on x86_64 is a 32-bit fragment of RAX with offset 0.
127 for (MCPhysReg SR : TRI.superregs(Reg: MachineReg)) {
128 Reg = TRI.getDwarfRegNum(Reg: SR, isEH: false);
129 if (Reg >= 0) {
130 unsigned Idx = TRI.getSubRegIndex(RegNo: SR, SubRegNo: MachineReg);
131 unsigned Size = TRI.getSubRegIdxSize(Idx);
132 unsigned RegOffset = TRI.getSubRegIdxOffset(Idx);
133 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: Reg, Comment: "super-register"));
134 // Use a DW_OP_bit_piece to describe the sub-register.
135 setSubRegisterPiece(SizeInBits: Size, OffsetInBits: RegOffset);
136 return true;
137 }
138 }
139
140 // Otherwise, attempt to find a covering set of sub-register numbers.
141 // For example, Q0 on ARM is a composition of D0+D1.
142 unsigned CurPos = 0;
143 // The size of the register in bits.
144 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(Reg: MachineReg);
145 unsigned RegSize = TRI.getRegSizeInBits(RC: *RC);
146 // Keep track of the bits in the register we already emitted, so we
147 // can avoid emitting redundant aliasing subregs. Because this is
148 // just doing a greedy scan of all subregisters, it is possible that
149 // this doesn't find a combination of subregisters that fully cover
150 // the register (even though one may exist).
151 SmallBitVector Coverage(RegSize, false);
152 for (MCPhysReg SR : TRI.subregs(Reg: MachineReg)) {
153 unsigned Idx = TRI.getSubRegIndex(RegNo: MachineReg, SubRegNo: SR);
154 unsigned Size = TRI.getSubRegIdxSize(Idx);
155 unsigned Offset = TRI.getSubRegIdxOffset(Idx);
156 Reg = TRI.getDwarfRegNum(Reg: SR, isEH: false);
157 if (Reg < 0 || Offset + Size > RegSize)
158 continue;
159
160 // Used to build the intersection between the bits we already
161 // emitted and the bits covered by this subregister.
162 SmallBitVector CurSubReg(RegSize, false);
163 CurSubReg.set(I: Offset, E: Offset + Size);
164
165 // If this sub-register has a DWARF number and we haven't covered
166 // its range, and its range covers the value, emit a DWARF piece for it.
167 if (Offset < MaxSize && !CurSubReg.subsetOf(RHS: Coverage)) {
168 // Emit a piece for any gap in the coverage.
169 if (Offset > CurPos)
170 DwarfRegs.push_back(Elt: Register::createSubRegister(
171 RegNo: -1, SizeInBits: Offset - CurPos, Comment: "no DWARF register encoding"));
172 if (Offset == 0 && Size >= MaxSize)
173 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: Reg, Comment: "sub-register"));
174 else
175 DwarfRegs.push_back(Elt: Register::createSubRegister(
176 RegNo: Reg, SizeInBits: std::min<unsigned>(a: Size, b: MaxSize - Offset), Comment: "sub-register"));
177 }
178 // Mark it as emitted.
179 Coverage.set(I: Offset, E: Offset + Size);
180 CurPos = Offset + Size;
181 }
182 // Failed to find any DWARF encoding.
183 if (CurPos == 0)
184 return false;
185 // Found a partial or complete DWARF encoding.
186 if (CurPos < RegSize)
187 DwarfRegs.push_back(Elt: Register::createSubRegister(
188 RegNo: -1, SizeInBits: RegSize - CurPos, Comment: "no DWARF register encoding"));
189 return true;
190}
191
192void DwarfExpression::addStackValue() {
193 if (DwarfVersion >= 4)
194 emitOp(Op: dwarf::DW_OP_stack_value);
195}
196
197void DwarfExpression::addBooleanConstant(int64_t Value) {
198 assert(isImplicitLocation() || isUnknownLocation());
199 LocationKind = Implicit;
200 if (Value == 0)
201 emitOp(Op: dwarf::DW_OP_lit0);
202 else
203 emitOp(Op: dwarf::DW_OP_lit1);
204}
205
206void DwarfExpression::addSignedConstant(int64_t Value) {
207 assert(isImplicitLocation() || isUnknownLocation());
208 LocationKind = Implicit;
209 emitOp(Op: dwarf::DW_OP_consts);
210 emitSigned(Value);
211}
212
213void DwarfExpression::addUnsignedConstant(uint64_t Value) {
214 assert(isImplicitLocation() || isUnknownLocation());
215 LocationKind = Implicit;
216 emitConstu(Value);
217}
218
219void DwarfExpression::addUnsignedConstant(const APInt &Value) {
220 assert(isImplicitLocation() || isUnknownLocation());
221 LocationKind = Implicit;
222
223 unsigned Size = Value.getBitWidth();
224 const uint64_t *Data = Value.getRawData();
225
226 // Chop it up into 64-bit pieces, because that's the maximum that
227 // addUnsignedConstant takes.
228 unsigned Offset = 0;
229 while (Offset < Size) {
230 addUnsignedConstant(Value: *Data++);
231 if (Offset == 0 && Size <= 64)
232 break;
233 addStackValue();
234 addOpPiece(SizeInBits: std::min(a: Size - Offset, b: 64u), OffsetInBits: Offset);
235 Offset += 64;
236 }
237}
238
239void DwarfExpression::addImplicitValue(const APInt &Value,
240 const AsmPrinter &AP) {
241 assert(isImplicitLocation() || isUnknownLocation());
242 assert(DwarfVersion >= 4);
243
244 APInt API = Value;
245 unsigned NumBytes = API.getBitWidth() / 8;
246 assert(API.getBitWidth() == NumBytes * 8 &&
247 "implicit value must be byte-sized");
248
249 emitOp(Op: dwarf::DW_OP_implicit_value);
250 emitUnsigned(Value: NumBytes);
251
252 // The loop below is emitting the value starting at the least significant
253 // byte, so byte-swap first for big-endian targets.
254 if (AP.getDataLayout().isBigEndian())
255 API = API.byteSwap();
256
257 for (unsigned I = 0; I < NumBytes; ++I)
258 emitData1(Value: API.extractBits(numBits: 8, bitPosition: I * 8).getZExtValue());
259}
260
261void DwarfExpression::addConstantFP(const APFloat &APF, const AsmPrinter &AP) {
262 assert(isImplicitLocation() || isUnknownLocation());
263 APInt API = APF.bitcastToAPInt();
264 int NumBytes = API.getBitWidth() / 8;
265 if (NumBytes == 4 /*float*/ || NumBytes == 8 /*double*/) {
266 // FIXME: Add support for `long double`.
267 emitOp(Op: dwarf::DW_OP_implicit_value);
268 emitUnsigned(Value: NumBytes /*Size of the block in bytes*/);
269
270 // The loop below is emitting the value starting at least significant byte,
271 // so we need to perform a byte-swap to get the byte order correct in case
272 // of a big-endian target.
273 if (AP.getDataLayout().isBigEndian())
274 API = API.byteSwap();
275
276 for (int i = 0; i < NumBytes; ++i) {
277 emitData1(Value: API.getZExtValue() & 0xFF);
278 API = API.lshr(shiftAmt: 8);
279 }
280
281 return;
282 }
283 LLVM_DEBUG(
284 dbgs() << "Skipped DW_OP_implicit_value creation for ConstantFP of size: "
285 << API.getBitWidth() << " bits\n");
286}
287
288bool DwarfExpression::addMachineRegExpression(const TargetRegisterInfo &TRI,
289 DIExpressionCursor &ExprCursor,
290 llvm::Register MachineReg,
291 unsigned FragmentOffsetInBits) {
292 auto Fragment = ExprCursor.getFragmentInfo();
293 if (!addMachineReg(TRI, MachineReg, MaxSize: Fragment ? Fragment->SizeInBits : ~1U)) {
294 LocationKind = Unknown;
295 return false;
296 }
297
298 bool HasComplexExpression = false;
299 auto Op = ExprCursor.peek();
300 if (Op && Op->getOp() != dwarf::DW_OP_LLVM_fragment)
301 HasComplexExpression = true;
302
303 // If the register can only be described by a complex expression (i.e.,
304 // multiple subregisters) it doesn't safely compose with another complex
305 // expression. For example, it is not possible to apply a DW_OP_deref
306 // operation to multiple DW_OP_pieces, since composite location descriptions
307 // do not push anything on the DWARF stack.
308 //
309 // DW_OP_entry_value operations can only hold a DWARF expression or a
310 // register location description, so we can't emit a single entry value
311 // covering a composite location description. In the future we may want to
312 // emit entry value operations for each register location in the composite
313 // location, but until that is supported do not emit anything.
314 if ((HasComplexExpression || IsEmittingEntryValue) && DwarfRegs.size() > 1) {
315 if (IsEmittingEntryValue)
316 cancelEntryValue();
317 DwarfRegs.clear();
318 LocationKind = Unknown;
319 return false;
320 }
321
322 // Handle simple register locations. If we are supposed to emit
323 // a call site parameter expression and if that expression is just a register
324 // location, emit it with addBReg and offset 0, because we should emit a DWARF
325 // expression representing a value, rather than a location.
326 if ((!isParameterValue() && !isMemoryLocation() && !HasComplexExpression) ||
327 isEntryValue()) {
328 unsigned RegSize = 0;
329 for (auto &Reg : DwarfRegs) {
330 RegSize += Reg.SubRegSize;
331 if (Reg.DwarfRegNo >= 0)
332 addReg(DwarfReg: Reg.DwarfRegNo, Comment: Reg.Comment);
333 if (Fragment && RegSize > Fragment->SizeInBits)
334 // If the register is larger than the current fragment stop
335 // once the fragment is covered.
336 break;
337 addOpPiece(SizeInBits: Reg.SubRegSize);
338 }
339
340 if (isEntryValue()) {
341 finalizeEntryValue();
342
343 if (!isIndirect() && !isParameterValue() && !HasComplexExpression &&
344 DwarfVersion >= 4)
345 emitOp(Op: dwarf::DW_OP_stack_value);
346 }
347
348 DwarfRegs.clear();
349 // If we need to mask out a subregister, do it now, unless the next
350 // operation would emit an OpPiece anyway.
351 auto NextOp = ExprCursor.peek();
352 if (SubRegisterSizeInBits && NextOp &&
353 (NextOp->getOp() != dwarf::DW_OP_LLVM_fragment))
354 maskSubRegister();
355 return true;
356 }
357
358 // Don't emit locations that cannot be expressed without DW_OP_stack_value.
359 if (DwarfVersion < 4)
360 if (any_of(Range&: ExprCursor, P: [](DIExpression::ExprOperand Op) -> bool {
361 return Op.getOp() == dwarf::DW_OP_stack_value;
362 })) {
363 DwarfRegs.clear();
364 LocationKind = Unknown;
365 return false;
366 }
367
368 // TODO: We should not give up here but the following code needs to be changed
369 // to deal with multiple (sub)registers first.
370 if (DwarfRegs.size() > 1) {
371 LLVM_DEBUG(dbgs() << "TODO: giving up on debug information due to "
372 "multi-register usage.\n");
373 DwarfRegs.clear();
374 LocationKind = Unknown;
375 return false;
376 }
377
378 auto Reg = DwarfRegs[0];
379 int SignedOffset = 0;
380 assert(!Reg.isSubRegister() && "full register expected");
381
382 // Pattern-match combinations for which more efficient representations exist.
383 // [Reg, DW_OP_plus_uconst, Offset] --> [DW_OP_breg, Offset].
384 if (Op && (Op->getOp() == dwarf::DW_OP_plus_uconst)) {
385 uint64_t Offset = Op->getArg(I: 0);
386 uint64_t IntMax = static_cast<uint64_t>(std::numeric_limits<int>::max());
387 if (Offset <= IntMax) {
388 SignedOffset = Offset;
389 ExprCursor.take();
390 }
391 }
392
393 // [Reg, DW_OP_constu, Offset, DW_OP_plus] --> [DW_OP_breg, Offset]
394 // [Reg, DW_OP_constu, Offset, DW_OP_minus] --> [DW_OP_breg,-Offset]
395 // If Reg is a subregister we need to mask it out before subtracting.
396 if (Op && Op->getOp() == dwarf::DW_OP_constu) {
397 uint64_t Offset = Op->getArg(I: 0);
398 uint64_t IntMax = static_cast<uint64_t>(std::numeric_limits<int>::max());
399 auto N = ExprCursor.peekNext();
400 if (N && N->getOp() == dwarf::DW_OP_plus && Offset <= IntMax) {
401 SignedOffset = Offset;
402 ExprCursor.consume(N: 2);
403 } else if (N && N->getOp() == dwarf::DW_OP_minus &&
404 !SubRegisterSizeInBits && Offset <= IntMax + 1) {
405 SignedOffset = -static_cast<int64_t>(Offset);
406 ExprCursor.consume(N: 2);
407 }
408 }
409
410 if (isFrameRegister(TRI, MachineReg))
411 addFBReg(Offset: SignedOffset);
412 else
413 addBReg(DwarfReg: Reg.DwarfRegNo, Offset: SignedOffset);
414 DwarfRegs.clear();
415
416 // If we need to mask out a subregister, do it now, unless the next
417 // operation would emit an OpPiece anyway.
418 auto NextOp = ExprCursor.peek();
419 if (SubRegisterSizeInBits && NextOp &&
420 (NextOp->getOp() != dwarf::DW_OP_LLVM_fragment))
421 maskSubRegister();
422
423 return true;
424}
425
426void DwarfExpression::setEntryValueFlags(const MachineLocation &Loc) {
427 LocationFlags |= EntryValue;
428 if (Loc.isIndirect())
429 LocationFlags |= Indirect;
430}
431
432void DwarfExpression::setLocation(const MachineLocation &Loc,
433 const DIExpression *DIExpr) {
434 if (Loc.isIndirect())
435 setMemoryLocationKind();
436
437 if (DIExpr->isEntryValue())
438 setEntryValueFlags(Loc);
439}
440
441void DwarfExpression::beginEntryValueExpression(
442 DIExpressionCursor &ExprCursor) {
443 auto Op = ExprCursor.take();
444 (void)Op;
445 assert(Op && Op->getOp() == dwarf::DW_OP_LLVM_entry_value);
446 assert(!IsEmittingEntryValue && "Already emitting entry value?");
447 assert(Op->getArg(0) == 1 &&
448 "Can currently only emit entry values covering a single operation");
449
450 SavedLocationKind = LocationKind;
451 LocationKind = Register;
452 LocationFlags |= EntryValue;
453 IsEmittingEntryValue = true;
454 enableTemporaryBuffer();
455}
456
457void DwarfExpression::finalizeEntryValue() {
458 assert(IsEmittingEntryValue && "Entry value not open?");
459 disableTemporaryBuffer();
460
461 emitOp(Op: CU.getDwarf5OrGNULocationAtom(Loc: dwarf::DW_OP_entry_value));
462
463 // Emit the entry value's size operand.
464 unsigned Size = getTemporaryBufferSize();
465 emitUnsigned(Value: Size);
466
467 // Emit the entry value's DWARF block operand.
468 commitTemporaryBuffer();
469
470 LocationFlags &= ~EntryValue;
471 LocationKind = SavedLocationKind;
472 IsEmittingEntryValue = false;
473}
474
475void DwarfExpression::cancelEntryValue() {
476 assert(IsEmittingEntryValue && "Entry value not open?");
477 disableTemporaryBuffer();
478
479 // The temporary buffer can't be emptied, so for now just assert that nothing
480 // has been emitted to it.
481 assert(getTemporaryBufferSize() == 0 &&
482 "Began emitting entry value block before cancelling entry value");
483
484 LocationKind = SavedLocationKind;
485 IsEmittingEntryValue = false;
486}
487
488unsigned DwarfExpression::getOrCreateBaseType(unsigned BitSize,
489 dwarf::TypeKind Encoding) {
490 // Reuse the base_type if we already have one in this CU otherwise we
491 // create a new one.
492 unsigned I = 0, E = CU.ExprRefedBaseTypes.size();
493 for (; I != E; ++I)
494 if (CU.ExprRefedBaseTypes[I].BitSize == BitSize &&
495 CU.ExprRefedBaseTypes[I].Encoding == Encoding)
496 break;
497
498 if (I == E)
499 CU.ExprRefedBaseTypes.emplace_back(args&: BitSize, args&: Encoding);
500 return I;
501}
502
503/// Assuming a well-formed expression, match "DW_OP_deref*
504/// DW_OP_LLVM_fragment?".
505static bool isMemoryLocation(DIExpressionCursor ExprCursor) {
506 while (ExprCursor) {
507 auto Op = ExprCursor.take();
508 switch (Op->getOp()) {
509 case dwarf::DW_OP_deref:
510 case dwarf::DW_OP_LLVM_fragment:
511 break;
512 default:
513 return false;
514 }
515 }
516 return true;
517}
518
519void DwarfExpression::addExpression(DIExpressionCursor &&ExprCursor) {
520 addExpression(Expr: std::move(ExprCursor),
521 InsertArg: [](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
522 llvm_unreachable("unhandled opcode found in expression");
523 });
524}
525
526bool DwarfExpression::addExpression(
527 DIExpressionCursor &&ExprCursor,
528 llvm::function_ref<bool(unsigned, DIExpressionCursor &)> InsertArg) {
529 // Entry values can currently only cover the initial register location,
530 // and not any other parts of the following DWARF expression.
531 assert(!IsEmittingEntryValue && "Can't emit entry value around expression");
532
533 std::optional<DIExpression::ExprOperand> PrevConvertOp;
534
535 while (ExprCursor) {
536 auto Op = ExprCursor.take();
537 uint64_t OpNum = Op->getOp();
538
539 if (OpNum >= dwarf::DW_OP_reg0 && OpNum <= dwarf::DW_OP_reg31) {
540 emitOp(Op: OpNum);
541 continue;
542 } else if (OpNum >= dwarf::DW_OP_breg0 && OpNum <= dwarf::DW_OP_breg31) {
543 addBReg(DwarfReg: OpNum - dwarf::DW_OP_breg0, Offset: Op->getArg(I: 0));
544 continue;
545 }
546
547 switch (OpNum) {
548 case dwarf::DW_OP_LLVM_arg:
549 if (!InsertArg(Op->getArg(I: 0), ExprCursor)) {
550 LocationKind = Unknown;
551 return false;
552 }
553 break;
554 case dwarf::DW_OP_LLVM_fragment: {
555 unsigned SizeInBits = Op->getArg(I: 1);
556 unsigned FragmentOffset = Op->getArg(I: 0);
557 // The fragment offset must have already been adjusted by emitting an
558 // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
559 // location.
560 assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
561 assert(SizeInBits >= OffsetInBits - FragmentOffset && "size underflow");
562
563 // If addMachineReg already emitted DW_OP_piece operations to represent
564 // a super-register by splicing together sub-registers, subtract the size
565 // of the pieces that was already emitted.
566 SizeInBits -= OffsetInBits - FragmentOffset;
567
568 // If addMachineReg requested a DW_OP_bit_piece to stencil out a
569 // sub-register that is smaller than the current fragment's size, use it.
570 if (SubRegisterSizeInBits)
571 SizeInBits = std::min<unsigned>(a: SizeInBits, b: SubRegisterSizeInBits);
572
573 // Emit a DW_OP_stack_value for implicit location descriptions.
574 if (isImplicitLocation())
575 addStackValue();
576
577 // Emit the DW_OP_piece.
578 addOpPiece(SizeInBits, OffsetInBits: SubRegisterOffsetInBits);
579 setSubRegisterPiece(SizeInBits: 0, OffsetInBits: 0);
580 // Reset the location description kind.
581 LocationKind = Unknown;
582 return true;
583 }
584 case dwarf::DW_OP_LLVM_extract_bits_sext:
585 case dwarf::DW_OP_LLVM_extract_bits_zext: {
586 unsigned SizeInBits = Op->getArg(I: 1);
587 unsigned BitOffset = Op->getArg(I: 0);
588 unsigned DerefSize = 0;
589 // Operations are done in the DWARF "generic type" whose size
590 // is the size of a pointer.
591 unsigned PtrSizeInBytes = CU.getAsmPrinter()->MAI.getCodePointerSize();
592
593 // If we have a memory location then dereference to get the value, though
594 // we have to make sure we don't dereference any bytes past the end of the
595 // object.
596 if (isMemoryLocation()) {
597 DerefSize = alignTo(Value: BitOffset + SizeInBits, Align: 8) / 8;
598 if (DerefSize == PtrSizeInBytes) {
599 emitOp(Op: dwarf::DW_OP_deref);
600 } else {
601 emitOp(Op: dwarf::DW_OP_deref_size);
602 emitUnsigned(Value: DerefSize);
603 }
604 }
605
606 // If a dereference was emitted for an unsigned value, and
607 // there's no bit offset, then a bit of optimization is
608 // possible.
609 if (OpNum == dwarf::DW_OP_LLVM_extract_bits_zext && BitOffset == 0) {
610 if (8 * DerefSize == SizeInBits) {
611 // The correct value is already on the stack.
612 } else {
613 // No need to shift, we can just mask off the desired bits.
614 emitOp(Op: dwarf::DW_OP_constu);
615 emitUnsigned(Value: (1u << SizeInBits) - 1);
616 emitOp(Op: dwarf::DW_OP_and);
617 }
618 } else {
619 // Extract the bits by a shift left (to shift out the bits after what we
620 // want to extract) followed by shift right (to shift the bits to
621 // position 0 and also sign/zero extend).
622 unsigned LeftShift = PtrSizeInBytes * 8 - (SizeInBits + BitOffset);
623 unsigned RightShift = LeftShift + BitOffset;
624 if (LeftShift) {
625 emitOp(Op: dwarf::DW_OP_constu);
626 emitUnsigned(Value: LeftShift);
627 emitOp(Op: dwarf::DW_OP_shl);
628 }
629 if (RightShift) {
630 emitOp(Op: dwarf::DW_OP_constu);
631 emitUnsigned(Value: RightShift);
632 emitOp(Op: OpNum == dwarf::DW_OP_LLVM_extract_bits_sext
633 ? dwarf::DW_OP_shra
634 : dwarf::DW_OP_shr);
635 }
636 }
637
638 // The value is now at the top of the stack, so set the location to
639 // implicit so that we get a stack_value at the end.
640 LocationKind = Implicit;
641 break;
642 }
643 case dwarf::DW_OP_plus_uconst:
644 assert(!isRegisterLocation());
645 emitOp(Op: dwarf::DW_OP_plus_uconst);
646 emitUnsigned(Value: Op->getArg(I: 0));
647 break;
648 case dwarf::DW_OP_plus:
649 case dwarf::DW_OP_minus:
650 case dwarf::DW_OP_mul:
651 case dwarf::DW_OP_div:
652 case dwarf::DW_OP_mod:
653 case dwarf::DW_OP_or:
654 case dwarf::DW_OP_and:
655 case dwarf::DW_OP_xor:
656 case dwarf::DW_OP_shl:
657 case dwarf::DW_OP_shr:
658 case dwarf::DW_OP_shra:
659 case dwarf::DW_OP_lit0:
660 case dwarf::DW_OP_not:
661 case dwarf::DW_OP_dup:
662 case dwarf::DW_OP_push_object_address:
663 case dwarf::DW_OP_over:
664 case dwarf::DW_OP_rot:
665 case dwarf::DW_OP_eq:
666 case dwarf::DW_OP_ne:
667 case dwarf::DW_OP_gt:
668 case dwarf::DW_OP_ge:
669 case dwarf::DW_OP_lt:
670 case dwarf::DW_OP_le:
671 case dwarf::DW_OP_neg:
672 case dwarf::DW_OP_abs:
673 emitOp(Op: OpNum);
674 break;
675 case dwarf::DW_OP_deref:
676 assert(!isRegisterLocation());
677 if (!isMemoryLocation() && ::isMemoryLocation(ExprCursor))
678 // Turning this into a memory location description makes the deref
679 // implicit.
680 LocationKind = Memory;
681 else
682 emitOp(Op: dwarf::DW_OP_deref);
683 break;
684 case dwarf::DW_OP_constu:
685 assert(!isRegisterLocation());
686 emitConstu(Value: Op->getArg(I: 0));
687 break;
688 case dwarf::DW_OP_consts:
689 assert(!isRegisterLocation());
690 emitOp(Op: dwarf::DW_OP_consts);
691 emitSigned(Value: Op->getArg(I: 0));
692 break;
693 case dwarf::DW_OP_LLVM_convert: {
694 unsigned BitSize = Op->getArg(I: 0);
695 dwarf::TypeKind Encoding = static_cast<dwarf::TypeKind>(Op->getArg(I: 1));
696 if (DwarfVersion >= 5 && CU.getDwarfDebug().useOpConvert()) {
697 emitOp(Op: dwarf::DW_OP_convert);
698 // If targeting a location-list; simply emit the index into the raw
699 // byte stream as ULEB128, DwarfDebug::emitDebugLocEntry has been
700 // fitted with means to extract it later.
701 // If targeting a inlined DW_AT_location; insert a DIEBaseTypeRef
702 // (containing the index and a resolve mechanism during emit) into the
703 // DIE value list.
704 emitBaseTypeRef(Idx: getOrCreateBaseType(BitSize, Encoding));
705 } else {
706 if (PrevConvertOp && PrevConvertOp->getArg(I: 0) < BitSize) {
707 if (Encoding == dwarf::DW_ATE_signed)
708 emitLegacySExt(FromBits: PrevConvertOp->getArg(I: 0));
709 else if (Encoding == dwarf::DW_ATE_unsigned)
710 emitLegacyZExt(FromBits: PrevConvertOp->getArg(I: 0));
711 PrevConvertOp = std::nullopt;
712 } else {
713 PrevConvertOp = Op;
714 }
715 }
716 break;
717 }
718 case dwarf::DW_OP_stack_value:
719 LocationKind = Implicit;
720 break;
721 case dwarf::DW_OP_swap:
722 assert(!isRegisterLocation());
723 emitOp(Op: dwarf::DW_OP_swap);
724 break;
725 case dwarf::DW_OP_xderef:
726 assert(!isRegisterLocation());
727 emitOp(Op: dwarf::DW_OP_xderef);
728 break;
729 case dwarf::DW_OP_deref_size:
730 emitOp(Op: dwarf::DW_OP_deref_size);
731 emitData1(Value: Op->getArg(I: 0));
732 break;
733 case dwarf::DW_OP_LLVM_tag_offset:
734 TagOffset = Op->getArg(I: 0);
735 break;
736 case dwarf::DW_OP_regx:
737 emitOp(Op: dwarf::DW_OP_regx);
738 emitUnsigned(Value: Op->getArg(I: 0));
739 break;
740 case dwarf::DW_OP_bregx:
741 emitOp(Op: dwarf::DW_OP_bregx);
742 emitUnsigned(Value: Op->getArg(I: 0));
743 emitSigned(Value: Op->getArg(I: 1));
744 break;
745 case dwarf::DW_OP_LLVM_implicit_pointer:
746 // Handled in DwarfCompileUnit::emitImplicitPointerLocation for
747 // Loc::Single variables. If we reach here, the variable has a
748 // location list or other unsupported path. Drop the
749 // location rather than crashing.
750 return false;
751 default:
752 llvm_unreachable("unhandled opcode found in expression");
753 }
754 }
755
756 if (isImplicitLocation() && !isParameterValue())
757 // Turn this into an implicit location description.
758 addStackValue();
759
760 return true;
761}
762
763/// add masking operations to stencil out a subregister.
764void DwarfExpression::maskSubRegister() {
765 assert(SubRegisterSizeInBits && "no subregister was registered");
766 if (SubRegisterOffsetInBits > 0)
767 addShr(ShiftBy: SubRegisterOffsetInBits);
768 uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
769 addAnd(Mask);
770}
771
772void DwarfExpression::finalize() {
773 assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
774 // Emit any outstanding DW_OP_piece operations to mask out subregisters.
775 if (SubRegisterSizeInBits == 0)
776 return;
777 // Don't emit a DW_OP_piece for a subregister at offset 0.
778 if (SubRegisterOffsetInBits == 0)
779 return;
780 addOpPiece(SizeInBits: SubRegisterSizeInBits, OffsetInBits: SubRegisterOffsetInBits);
781}
782
783void DwarfExpression::addFragmentOffset(const DIExpression *Expr) {
784 if (!Expr || !Expr->isFragment())
785 return;
786
787 uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
788 assert(FragmentOffset >= OffsetInBits &&
789 "overlapping or duplicate fragments");
790 if (FragmentOffset > OffsetInBits)
791 addOpPiece(SizeInBits: FragmentOffset - OffsetInBits);
792 OffsetInBits = FragmentOffset;
793}
794
795void DwarfExpression::emitLegacySExt(unsigned FromBits) {
796 // (((X >> (FromBits - 1)) * (~0)) << FromBits) | X
797 emitOp(Op: dwarf::DW_OP_dup);
798 emitOp(Op: dwarf::DW_OP_constu);
799 emitUnsigned(Value: FromBits - 1);
800 emitOp(Op: dwarf::DW_OP_shr);
801 emitOp(Op: dwarf::DW_OP_lit0);
802 emitOp(Op: dwarf::DW_OP_not);
803 emitOp(Op: dwarf::DW_OP_mul);
804 emitOp(Op: dwarf::DW_OP_constu);
805 emitUnsigned(Value: FromBits);
806 emitOp(Op: dwarf::DW_OP_shl);
807 emitOp(Op: dwarf::DW_OP_or);
808}
809
810void DwarfExpression::emitLegacyZExt(unsigned FromBits) {
811 // Heuristic to decide the most efficient encoding.
812 // A ULEB can encode 7 1-bits per byte.
813 if (FromBits / 7 < 1+1+1+1+1) {
814 // (X & (1 << FromBits - 1))
815 emitOp(Op: dwarf::DW_OP_constu);
816 emitUnsigned(Value: (1ULL << FromBits) - 1);
817 } else {
818 // Note that the DWARF 4 stack consists of pointer-sized elements,
819 // so technically it doesn't make sense to shift left more than 64
820 // bits. We leave that for the consumer to decide though. LLDB for
821 // example uses APInt for the stack elements and can still deal
822 // with this.
823 emitOp(Op: dwarf::DW_OP_lit1);
824 emitOp(Op: dwarf::DW_OP_constu);
825 emitUnsigned(Value: FromBits);
826 emitOp(Op: dwarf::DW_OP_shl);
827 emitOp(Op: dwarf::DW_OP_lit1);
828 emitOp(Op: dwarf::DW_OP_minus);
829 }
830 emitOp(Op: dwarf::DW_OP_and);
831}
832
833void DwarfExpression::addWasmLocation(unsigned Index, uint64_t Offset) {
834 emitOp(Op: dwarf::DW_OP_WASM_location);
835 emitUnsigned(Value: Index == 4/*TI_LOCAL_INDIRECT*/ ? 0/*TI_LOCAL*/ : Index);
836 emitUnsigned(Value: Offset);
837 if (Index == 4 /*TI_LOCAL_INDIRECT*/) {
838 assert(LocationKind == Unknown);
839 LocationKind = Memory;
840 } else {
841 assert(LocationKind == Implicit || LocationKind == Unknown);
842 LocationKind = Implicit;
843 }
844}
845