LLVM 24.0.0git
BTFDebug.cpp
Go to the documentation of this file.
1//===- BTFDebug.cpp - BTF Generator ---------------------------------------===//
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 BTF debug info.
10//
11//===----------------------------------------------------------------------===//
12
13#include "BTFDebug.h"
14#include "BPF.h"
15#include "BPFCORE.h"
17#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Twine.h"
29#include "llvm/IR/Module.h"
30#include "llvm/MC/MCContext.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/Support/Debug.h"
41#include <optional>
42
43using namespace llvm;
44
45#define DEBUG_TYPE "btf-debug"
46
47#define GET_CC_REGISTER_LISTS
48#include "BPFGenCallingConv.inc"
49
50static const char *BTFKindStr[] = {
51#define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
52#include "llvm/DebugInfo/BTF/BTF.def"
53};
54
55static const DIType *tryRemoveAtomicType(const DIType *Ty) {
56 if (!Ty)
57 return Ty;
58 auto DerivedTy = dyn_cast<DIDerivedType>(Ty);
59 if (DerivedTy && DerivedTy->getTag() == dwarf::DW_TAG_atomic_type)
60 return DerivedTy->getBaseType();
61 return Ty;
62}
63
64static const DIType *stripDITypeAttributes(const DIType *Ty) {
65 while (const auto *DTy = dyn_cast_or_null<DIDerivedType>(Ty)) {
66 switch (DTy->getTag()) {
67 case dwarf::DW_TAG_atomic_type:
68 case dwarf::DW_TAG_const_type:
69 case dwarf::DW_TAG_restrict_type:
70 case dwarf::DW_TAG_typedef:
71 case dwarf::DW_TAG_volatile_type:
72 Ty = DTy->getBaseType();
73 break;
74 default:
75 return Ty;
76 }
77 }
78 return Ty;
79}
80
81static bool sourceArgMatchesIRType(const DIType *SourceTy, Type *IRTy) {
82 SourceTy = stripDITypeAttributes(SourceTy);
83
84 // All pointers are opaque in LLVM IR, so any source-level pointer matches any
85 // IR pointer regardless of pointee type.
86 if (const auto *DTy = dyn_cast<DIDerivedType>(SourceTy))
87 return DTy->getTag() == dwarf::DW_TAG_pointer_type && IRTy->isPointerTy();
88
89 if (const auto *BTy = dyn_cast<DIBasicType>(SourceTy)) {
90 uint64_t SizeInBits = BTy->getSizeInBits();
91 if (BTy->getEncoding() == dwarf::DW_ATE_float)
92 return IRTy->isFloatingPointTy() &&
93 IRTy->getPrimitiveSizeInBits() == SizeInBits;
94 // _Bool is 8 bits in DWARF/source but lowered to i1 in LLVM IR.
95 if (BTy->getEncoding() == dwarf::DW_ATE_boolean && IRTy->isIntegerTy(1))
96 return true;
97 return IRTy->isIntegerTy(SizeInBits);
98 }
99
100 const auto *CTy = dyn_cast<DICompositeType>(SourceTy);
101 if (!CTy)
102 return false;
103
104 switch (CTy->getTag()) {
105 case dwarf::DW_TAG_enumeration_type:
106 return IRTy->isIntegerTy(CTy->getSizeInBits());
107 default:
108 return false;
109 }
110}
111
112/// Collect the physical register each source argument lives in by scanning
113/// DBG_VALUE instructions in the entry block. A DBG_VALUE is only recorded
114/// when its register either (a) has not been redefined by any preceding
115/// non-debug instruction (i.e. it still holds the caller-passed value), or
116/// (b) was most recently loaded from the stack via $r11 (a stack-passed
117/// argument beyond the first five register args). For each argument only the
118/// first eligible DBG_VALUE is recorded, since that is its entry location.
119///
120/// There is another case where DBG_VALUE is not emitted due to
121/// AssignmentTrackingAnalysis which determines that a variable is
122/// always stack-homed, and describes the variable via MachineFunction's
123/// VariableDbgInfo (setVariableDbgInfo with a frame index). To recover the
124/// register for those arguments, we also track stores of un-redefined physical
125/// registers to stack frame objects during the entry-block walk (using
126/// MachineMemOperands to identify the target frame index), then match them
127/// against VariableDbgInfo entries after the scan.
131 const DISubprogram *SP = MF.getFunction().getSubprogram();
132 SmallDenseSet<Register> DefinedRegs, StackLoadRegs;
133
134 // Build a reverse map from IR alloca to frame index so we can
135 // identify which frame object a store targets via its MachineMemOperand.
136 const MachineFrameInfo &MFI = MF.getFrameInfo();
138 for (int I = 0, N = MFI.getObjectIndexEnd(); I < N; ++I)
139 if (const AllocaInst *AI = MFI.getObjectAllocation(I))
140 AllocaToFI[AI] = I;
141
142 // Maps frame index → first physical register stored there before
143 // that register is redefined.
144 SmallDenseMap<int, Register> FrameIndexToReg;
145
146 for (const MachineInstr &MI : MF.front()) {
147 if (MI.isDebugValue()) {
148 // Skip indirect DBG_VALUEs — the register is a base address for a
149 // memory location, not the argument value itself.
150 if (MI.isIndirectDebugValue())
151 continue;
152
153 const DILocalVariable *DV = MI.getDebugVariable();
154 if (!DV || !DV->getArg() || DV->getScope()->getSubprogram() != SP)
155 continue;
156
157 uint32_t Arg = DV->getArg();
158 const MachineOperand &MO = MI.getDebugOperand(0);
159 if (!MO.isReg() || !MO.getReg().isPhysical())
160 continue;
161
162 if (!DefinedRegs.contains(MO.getReg()) ||
163 StackLoadRegs.contains(MO.getReg()))
164 EntryRegMap.try_emplace(Arg, MO.getReg());
165 continue;
166 }
167
168 // Track stores of unredefined physical registers to stack frame
169 // objects. Use MachineMemOperands to identify the target frame
170 // index rather than assuming a particular addressing mode.
171 if (MI.mayStore() && !MI.isCall() && MI.getOperand(0).isReg()) {
172 Register SrcReg = MI.getOperand(0).getReg();
173 if (SrcReg.isPhysical() && !DefinedRegs.contains(SrcReg)) {
174 for (const MachineMemOperand *MMO : MI.memoperands()) {
175 const Value *V = MMO->getValue();
176 if (!V)
177 continue;
178 auto It = AllocaToFI.find(V);
179 if (It != AllocaToFI.end())
180 FrameIndexToReg.try_emplace(It->second, SrcReg);
181 }
182 }
183 }
184
185 for (const MachineOperand &MO : MI.operands())
186 if (MO.isReg() && MO.isDef() && MO.getReg().isPhysical()) {
187 DefinedRegs.insert(MO.getReg());
188 StackLoadRegs.erase(MO.getReg());
189 }
190
191 // Detect stack argument loads: $rX = LDD $r11, offset.
192 if (MI.getOpcode() == BPF::LDD && MI.getOperand(1).getReg() == BPF::R11)
193 StackLoadRegs.insert(MI.getOperand(0).getReg());
194 }
195
196 // Check VariableDbgInfo for args that AssignmentTrackingAnalysis described
197 // via setVariableDbgInfo (single-loc stack-homed variables) rather than
198 // DBG_VALUE instructions.
199 for (const auto &VI : MF.getVariableDbgInfo()) {
200 if (!VI.Var || !VI.Var->getArg() || !VI.inStackSlot())
201 continue;
202 if (VI.Var->getScope()->getSubprogram() != SP)
203 continue;
204 uint32_t Arg = VI.Var->getArg();
205 if (EntryRegMap.count(Arg))
206 continue;
207 auto It = FrameIndexToReg.find(VI.getStackSlot());
208 if (It != FrameIndexToReg.end())
209 EntryRegMap[Arg] = It->second;
210 }
211
212 SmallVector<std::pair<uint32_t, Register>, 8> AliveArgs(EntryRegMap.begin(),
213 EntryRegMap.end());
214 llvm::sort(AliveArgs, llvm::less_first());
215 return AliveArgs;
216}
217
218/// Check whether the optimized IR signature matches the surviving source
219/// arguments precisely enough to emit a filtered BTF prototype.
220/// Requires exact IR/source arg count match, matching types, and correct
221/// BPF register order (R1..R5) for register args.
223 const MachineFunction &MF, DITypeArray Elements,
224 ArrayRef<std::pair<uint32_t, Register>> AliveArgs,
225 const TargetRegisterInfo &TRI) {
226 if (MF.getFunction().arg_size() != AliveArgs.size()) {
227 LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName() << ": IR arg count ("
228 << MF.getFunction().arg_size() << ") != alive arg count ("
229 << AliveArgs.size() << ")\n");
230 return false;
231 }
232
233 auto ArgIt = MF.getFunction().arg_begin();
234 for (unsigned I = 0, N = AliveArgs.size(); I < N; ++I, ++ArgIt) {
235 auto [ArgNo, Reg] = AliveArgs[I];
236 if (!sourceArgMatchesIRType(Elements[ArgNo], ArgIt->getType())) {
237 LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName()
238 << ": type mismatch for source arg " << ArgNo
239 << " at IR position " << I << "\n");
240 return false;
241 }
242
243 if (I >= std::size(CC_BPF64_ArgRegs))
244 continue;
245
246 int DwarfReg = TRI.getDwarfRegNum(Reg, false);
247 if (DwarfReg != static_cast<int>(I + 1)) {
248 LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName() << ": arg " << ArgNo
249 << " in DWARF reg " << DwarfReg << ", expected "
250 << (I + 1) << "\n");
251 return false;
252 }
253 }
254
255 return true;
256}
257
258/// Emit a BTF common type.
260 OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
261 ")");
262 OS.emitInt32(BTFType.NameOff);
263 OS.AddComment("0x" + Twine::utohexstr(BTFType.Info));
264 OS.emitInt32(BTFType.Info);
265 OS.emitInt32(BTFType.Size);
266}
267
269 bool NeedsFixup)
270 : DTy(DTy), NeedsFixup(NeedsFixup), Name(DTy->getName()) {
271 switch (Tag) {
272 case dwarf::DW_TAG_pointer_type:
273 Kind = BTF::BTF_KIND_PTR;
274 break;
275 case dwarf::DW_TAG_const_type:
276 Kind = BTF::BTF_KIND_CONST;
277 break;
278 case dwarf::DW_TAG_volatile_type:
279 Kind = BTF::BTF_KIND_VOLATILE;
280 break;
281 case dwarf::DW_TAG_typedef:
282 Kind = BTF::BTF_KIND_TYPEDEF;
283 break;
284 case dwarf::DW_TAG_restrict_type:
285 Kind = BTF::BTF_KIND_RESTRICT;
286 break;
287 default:
288 llvm_unreachable("Unknown DIDerivedType Tag");
289 }
290 BTFType.Info = Kind << 24;
291}
292
293/// Used by DW_TAG_pointer_type and DW_TAG_typedef only.
294BTFTypeDerived::BTFTypeDerived(unsigned NextTypeId, unsigned Tag,
295 StringRef Name)
296 : DTy(nullptr), NeedsFixup(false), Name(Name) {
297 switch (Tag) {
298 case dwarf::DW_TAG_pointer_type:
299 Kind = BTF::BTF_KIND_PTR;
300 break;
301 case dwarf::DW_TAG_typedef:
302 Kind = BTF::BTF_KIND_TYPEDEF;
303 break;
304 default:
305 llvm_unreachable("Tag must be pointer or typedef");
306 }
307
308 BTFType.Info = Kind << 24;
309 BTFType.Type = NextTypeId;
310}
311
313 if (IsCompleted)
314 return;
315 IsCompleted = true;
316
317 switch (Kind) {
318 case BTF::BTF_KIND_PTR:
319 case BTF::BTF_KIND_CONST:
320 case BTF::BTF_KIND_VOLATILE:
321 case BTF::BTF_KIND_RESTRICT:
322 // Debug info might contain names for these types, but given that we want
323 // to keep BTF minimal and naming reference types doesn't bring any value
324 // (what matters is the completeness of the base type), we don't emit them.
325 //
326 // Furthermore, the Linux kernel refuses to load BPF programs that contain
327 // BTF with these types named:
328 // https://elixir.bootlin.com/linux/v6.17.1/source/kernel/bpf/btf.c#L2586
329 BTFType.NameOff = 0;
330 break;
331 default:
332 BTFType.NameOff = BDebug.addString(Name);
333 break;
334 }
335
336 if (NeedsFixup || !DTy)
337 return;
338
339 // A pointer, qualifier, or typedef can refer to void.
340 const DIType *Base = tryRemoveAtomicType(DTy->getBaseType());
341 BTFType.Type = Base ? BDebug.getTypeId(Base) : 0;
342}
343
345
347 BTFType.Type = PointeeType;
348}
349
350/// Represent a struct/union forward declaration.
351BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) {
352 Kind = BTF::BTF_KIND_FWD;
353 BTFType.Info = IsUnion << 31 | Kind << 24;
354 BTFType.Type = 0;
355}
356
358 if (IsCompleted)
359 return;
360 IsCompleted = true;
361
362 BTFType.NameOff = BDebug.addString(Name);
363}
364
366
368 uint32_t OffsetInBits, StringRef TypeName)
369 : Name(TypeName) {
370 // Translate IR int encoding to BTF int encoding.
371 uint8_t BTFEncoding;
372 switch (Encoding) {
373 case dwarf::DW_ATE_boolean:
374 BTFEncoding = BTF::INT_BOOL;
375 break;
376 case dwarf::DW_ATE_signed:
377 case dwarf::DW_ATE_signed_char:
378 BTFEncoding = BTF::INT_SIGNED;
379 break;
380 case dwarf::DW_ATE_unsigned:
381 case dwarf::DW_ATE_unsigned_char:
382 case dwarf::DW_ATE_UTF:
383 BTFEncoding = 0;
384 break;
385 default:
386 llvm_unreachable("Unknown BTFTypeInt Encoding");
387 }
388
389 Kind = BTF::BTF_KIND_INT;
390 BTFType.Info = Kind << 24;
391 BTFType.Size = roundupToBytes(SizeInBits);
392 IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits;
393}
394
396 if (IsCompleted)
397 return;
398 IsCompleted = true;
399
400 BTFType.NameOff = BDebug.addString(Name);
401}
402
405 OS.AddComment("0x" + Twine::utohexstr(IntVal));
406 OS.emitInt32(IntVal);
407}
408
410 bool IsSigned) : ETy(ETy) {
411 Kind = BTF::BTF_KIND_ENUM;
412 BTFType.Info = IsSigned << 31 | Kind << 24 | VLen;
413 BTFType.Size = roundupToBytes(ETy->getSizeInBits());
414}
415
417 if (IsCompleted)
418 return;
419 IsCompleted = true;
420
421 BTFType.NameOff = BDebug.addString(ETy->getName());
422
423 DINodeArray Elements = ETy->getElements();
424 for (const auto Element : Elements) {
425 const auto *Enum = cast<DIEnumerator>(Element);
426
427 struct BTF::BTFEnum BTFEnum;
428 BTFEnum.NameOff = BDebug.addString(Enum->getName());
429 // BTF enum value is 32bit, enforce it.
431 if (Enum->isUnsigned())
432 Value = static_cast<uint32_t>(Enum->getValue().getZExtValue());
433 else
434 Value = static_cast<uint32_t>(Enum->getValue().getSExtValue());
435 BTFEnum.Val = Value;
436 EnumValues.push_back(BTFEnum);
437 }
438}
439
442 for (const auto &Enum : EnumValues) {
443 OS.emitInt32(Enum.NameOff);
444 OS.emitInt32(Enum.Val);
445 }
446}
447
449 bool IsSigned) : ETy(ETy) {
450 Kind = BTF::BTF_KIND_ENUM64;
451 BTFType.Info = IsSigned << 31 | Kind << 24 | VLen;
452 BTFType.Size = roundupToBytes(ETy->getSizeInBits());
453}
454
456 if (IsCompleted)
457 return;
458 IsCompleted = true;
459
460 BTFType.NameOff = BDebug.addString(ETy->getName());
461
462 DINodeArray Elements = ETy->getElements();
463 for (const auto Element : Elements) {
464 const auto *Enum = cast<DIEnumerator>(Element);
465
466 struct BTF::BTFEnum64 BTFEnum;
467 BTFEnum.NameOff = BDebug.addString(Enum->getName());
468 uint64_t Value;
469 if (Enum->isUnsigned())
470 Value = Enum->getValue().getZExtValue();
471 else
472 Value = static_cast<uint64_t>(Enum->getValue().getSExtValue());
473 BTFEnum.Val_Lo32 = Value;
474 BTFEnum.Val_Hi32 = Value >> 32;
475 EnumValues.push_back(BTFEnum);
476 }
477}
478
481 for (const auto &Enum : EnumValues) {
482 OS.emitInt32(Enum.NameOff);
483 OS.AddComment("0x" + Twine::utohexstr(Enum.Val_Lo32));
484 OS.emitInt32(Enum.Val_Lo32);
485 OS.AddComment("0x" + Twine::utohexstr(Enum.Val_Hi32));
486 OS.emitInt32(Enum.Val_Hi32);
487 }
488}
489
491 Kind = BTF::BTF_KIND_ARRAY;
492 BTFType.NameOff = 0;
493 BTFType.Info = Kind << 24;
494 BTFType.Size = 0;
495
496 ArrayInfo.ElemType = ElemTypeId;
497 ArrayInfo.Nelems = NumElems;
498}
499
500/// Represent a BTF array.
502 if (IsCompleted)
503 return;
504 IsCompleted = true;
505
506 // The IR does not really have a type for the index.
507 // A special type for array index should have been
508 // created during initial type traversal. Just
509 // retrieve that type id.
510 ArrayInfo.IndexType = BDebug.getArrayIndexTypeId();
511}
512
515 OS.emitInt32(ArrayInfo.ElemType);
516 OS.emitInt32(ArrayInfo.IndexType);
517 OS.emitInt32(ArrayInfo.Nelems);
518}
519
520/// Represent either a struct or a union.
522 ArrayRef<const DINode *> Elements, bool IsStruct,
523 bool HasBitField, uint32_t Vlen)
524 : STy(STy), Elements(Elements.begin(), Elements.end()),
525 HasBitField(HasBitField) {
526 Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
527 BTFType.Size = roundupToBytes(STy->getSizeInBits());
528 BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
529}
530
532 if (IsCompleted)
533 return;
534 IsCompleted = true;
535
536 BTFType.NameOff = BDebug.addString(STy->getName());
537
538 if (STy->getTag() == dwarf::DW_TAG_variant_part) {
539 // Variant parts might have a discriminator, which has its own memory
540 // location, and variants, which share the memory location afterwards. LLVM
541 // DI doesn't consider discriminator as an element and instead keeps
542 // it as a separate reference.
543 // To keep BTF simple, let's represent the structure as an union with
544 // discriminator as the first element.
545 // The offsets inside variant types are already handled correctly in the
546 // DI.
547 const auto *DTy = STy->getDiscriminator();
548 if (DTy) {
549 struct BTF::BTFMember Discriminator;
550
551 Discriminator.NameOff = BDebug.addString(DTy->getName());
552 Discriminator.Offset = DTy->getOffsetInBits();
553 const auto *BaseTy = DTy->getBaseType();
554 Discriminator.Type = BDebug.getTypeId(BaseTy);
555
556 Members.push_back(Discriminator);
557 }
558 }
559
560 // Add struct/union members.
561 for (const auto *Element : Elements) {
562 struct BTF::BTFMember BTFMember;
563
564 switch (Element->getTag()) {
565 case dwarf::DW_TAG_member: {
566 const auto *DDTy = cast<DIDerivedType>(Element);
567
568 BTFMember.NameOff = BDebug.addString(DDTy->getName());
569 if (HasBitField) {
570 uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0;
571 BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits();
572 } else {
573 BTFMember.Offset = DDTy->getOffsetInBits();
574 }
575 const auto *BaseTy = tryRemoveAtomicType(DDTy->getBaseType());
576 BTFMember.Type = BDebug.getTypeId(BaseTy);
577 break;
578 }
579 case dwarf::DW_TAG_variant_part: {
580 const auto *DCTy = dyn_cast<DICompositeType>(Element);
581
582 BTFMember.NameOff = BDebug.addString(DCTy->getName());
583 BTFMember.Offset = DCTy->getOffsetInBits();
584 BTFMember.Type = BDebug.getTypeId(DCTy);
585 break;
586 }
587 default:
588 llvm_unreachable("Unexpected DI tag of a struct/union element");
589 }
590 Members.push_back(BTFMember);
591 }
592}
593
596 for (const auto &Member : Members) {
597 OS.emitInt32(Member.NameOff);
598 OS.emitInt32(Member.Type);
599 OS.AddComment("0x" + Twine::utohexstr(Member.Offset));
600 OS.emitInt32(Member.Offset);
601 }
602}
603
604std::string BTFTypeStruct::getName() { return std::string(STy->getName()); }
605
606/// The Func kind represents both subprogram and pointee of function
607/// pointers. If the FuncName is empty, it represents a pointee of function
608/// pointer. Otherwise, it represents a subprogram. The func arg names
609/// are empty for pointee of function pointer case, and are valid names
610/// for subprogram.
612 const DISubroutineType *STy, uint32_t VLen,
613 const SmallDenseMap<uint32_t, StringRef> &FuncArgNames,
614 bool UseFilteredParams, ArrayRef<uint32_t> AliveParamIndices,
615 bool VoidReturn)
616 : STy(STy), FuncArgNames(FuncArgNames),
617 AliveParamIndices(AliveParamIndices),
618 UseFilteredParams(UseFilteredParams), VoidReturn(VoidReturn) {
619 Kind = BTF::BTF_KIND_FUNC_PROTO;
620 BTFType.Info = (Kind << 24) | VLen;
621}
622
624 if (IsCompleted)
625 return;
626 IsCompleted = true;
627
628 DITypeArray Elements = STy->getTypeArray();
629 if (VoidReturn) {
630 BTFType.Type = 0;
631 } else {
632 auto RetType = tryRemoveAtomicType(Elements[0]);
633 BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
634 }
635 BTFType.NameOff = 0;
636
637 auto EmitParam = [&](uint32_t I) {
638 struct BTF::BTFParam Param;
639 auto Element = tryRemoveAtomicType(Elements[I]);
640 if (Element) {
641 auto It = FuncArgNames.find(I);
642 Param.NameOff =
643 It != FuncArgNames.end() ? BDebug.addString(It->second) : 0;
644 Param.Type = BDebug.getTypeId(Element);
645 } else {
646 Param.NameOff = 0;
647 Param.Type = 0;
648 }
649 Parameters.push_back(Param);
650 };
651
652 if (UseFilteredParams) {
653 for (uint32_t I : AliveParamIndices)
654 EmitParam(I);
655 return;
656 }
657
658 for (unsigned I = 1, N = Elements.size(); I < N; ++I)
659 EmitParam(I);
660}
661
664 for (const auto &Param : Parameters) {
665 OS.emitInt32(Param.NameOff);
666 OS.emitInt32(Param.Type);
667 }
668}
669
671 uint32_t Scope)
672 : Name(FuncName) {
673 Kind = BTF::BTF_KIND_FUNC;
674 BTFType.Info = (Kind << 24) | Scope;
675 BTFType.Type = ProtoTypeId;
676}
677
679 if (IsCompleted)
680 return;
681 IsCompleted = true;
682
683 BTFType.NameOff = BDebug.addString(Name);
684}
685
687
689 : Name(VarName) {
690 Kind = BTF::BTF_KIND_VAR;
691 BTFType.Info = Kind << 24;
692 BTFType.Type = TypeId;
693 Info = VarInfo;
694}
695
697 BTFType.NameOff = BDebug.addString(Name);
698}
699
702 OS.emitInt32(Info);
703}
704
705BTFKindDataSec::BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
706 : Asm(AsmPrt), Name(SecName) {
707 Kind = BTF::BTF_KIND_DATASEC;
708 BTFType.Info = Kind << 24;
709 BTFType.Size = 0;
710}
711
713 BTFType.NameOff = BDebug.addString(Name);
714 BTFType.Info |= Vars.size();
715}
716
719
720 for (const auto &V : Vars) {
721 OS.emitInt32(std::get<0>(V));
722 Asm->emitLabelReference(std::get<1>(V), 4);
723 OS.emitInt32(std::get<2>(V));
724 }
725}
726
728 : Name(TypeName) {
729 Kind = BTF::BTF_KIND_FLOAT;
730 BTFType.Info = Kind << 24;
731 BTFType.Size = roundupToBytes(SizeInBits);
732}
733
735 if (IsCompleted)
736 return;
737 IsCompleted = true;
738
739 BTFType.NameOff = BDebug.addString(Name);
740}
741
742BTFTypeDeclTag::BTFTypeDeclTag(uint32_t BaseTypeId, int ComponentIdx,
743 StringRef Tag)
744 : Tag(Tag) {
745 Kind = BTF::BTF_KIND_DECL_TAG;
746 BTFType.Info = Kind << 24;
747 BTFType.Type = BaseTypeId;
748 Info = ComponentIdx;
749}
750
752 if (IsCompleted)
753 return;
754 IsCompleted = true;
755
756 BTFType.NameOff = BDebug.addString(Tag);
757}
758
763
765 : DTy(nullptr), Tag(Tag) {
766 Kind = BTF::BTF_KIND_TYPE_TAG;
767 BTFType.Info = Kind << 24;
768 BTFType.Type = NextTypeId;
769}
770
772 : DTy(DTy), Tag(Tag) {
773 Kind = BTF::BTF_KIND_TYPE_TAG;
774 BTFType.Info = Kind << 24;
775}
776
778 if (IsCompleted)
779 return;
780 IsCompleted = true;
781 BTFType.NameOff = BDebug.addString(Tag);
782 if (DTy) {
783 const DIType *ResolvedType = tryRemoveAtomicType(DTy->getBaseType());
784 if (!ResolvedType)
785 BTFType.Type = 0;
786 else
787 BTFType.Type = BDebug.getTypeId(ResolvedType);
788 }
789}
790
792 // Check whether the string already exists.
793 for (auto &OffsetM : OffsetToIdMap) {
794 if (Table[OffsetM.second] == S)
795 return OffsetM.first;
796 }
797 // Not find, add to the string table.
798 uint32_t Offset = Size;
799 OffsetToIdMap[Offset] = Table.size();
800 Table.push_back(std::string(S));
801 Size += S.size() + 1;
802 return Offset;
803}
804
806 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
807 LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
808 MapDefNotCollected(true) {
809 addString("\0");
810}
811
812uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
813 const DIType *Ty) {
814 TypeEntry->setId(TypeEntries.size() + 1);
815 uint32_t Id = TypeEntry->getId();
816 DIToIdMap[Ty] = Id;
817 TypeEntries.push_back(std::move(TypeEntry));
818 return Id;
819}
820
821uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
822 TypeEntry->setId(TypeEntries.size() + 1);
823 uint32_t Id = TypeEntry->getId();
824 TypeEntries.push_back(std::move(TypeEntry));
825 return Id;
826}
827
828void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
829 // Only int and binary floating point types are supported in BTF.
830 uint32_t Encoding = BTy->getEncoding();
831 std::unique_ptr<BTFTypeBase> TypeEntry;
832 switch (Encoding) {
833 case dwarf::DW_ATE_boolean:
834 case dwarf::DW_ATE_signed:
835 case dwarf::DW_ATE_signed_char:
836 case dwarf::DW_ATE_unsigned:
837 case dwarf::DW_ATE_unsigned_char:
838 case dwarf::DW_ATE_UTF:
839 // Create a BTF type instance for this DIBasicType and put it into
840 // DIToIdMap for cross-type reference check.
841 TypeEntry = std::make_unique<BTFTypeInt>(
842 Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
843 break;
844 case dwarf::DW_ATE_float:
845 TypeEntry =
846 std::make_unique<BTFTypeFloat>(BTy->getSizeInBits(), BTy->getName());
847 break;
848 default:
849 return;
850 }
851
852 TypeId = addType(std::move(TypeEntry), BTy);
853}
854
855/// Handle subprogram or subroutine types.
856void BTFDebug::visitSubroutineType(
857 const DISubroutineType *STy, bool ForSubprog,
858 const SmallDenseMap<uint32_t, StringRef> &FuncArgNames, uint32_t &TypeId,
859 bool VoidReturn) {
860 DITypeArray Elements = STy->getTypeArray();
861 uint32_t VLen = Elements.size() - 1;
862 if (VLen > BTF::MAX_VLEN)
863 return;
864
865 // Subprogram has a valid non-zero-length name, and the pointee of
866 // a function pointer has an empty name. The subprogram type will
867 // not be added to DIToIdMap as it should not be referenced by
868 // any other types.
869 auto TypeEntry = std::make_unique<BTFTypeFuncProto>(
870 STy, VLen, FuncArgNames, false, ArrayRef<uint32_t>(), VoidReturn);
871 if (ForSubprog)
872 TypeId = addType(std::move(TypeEntry)); // For subprogram
873 else
874 TypeId = addType(std::move(TypeEntry), STy); // For func ptr
875
876 // Visit return type and func arg types.
877 if (!VoidReturn) {
878 for (const auto Element : Elements)
879 visitTypeEntry(Element);
880 } else {
881 for (unsigned I = 1, N = Elements.size(); I < N; ++I)
882 visitTypeEntry(Elements[I]);
883 }
884}
885
886void BTFDebug::processDeclAnnotations(DINodeArray Annotations,
887 uint32_t BaseTypeId,
888 int ComponentIdx) {
889 if (!Annotations)
890 return;
891
892 for (const Metadata *Annotation : Annotations->operands()) {
893 const MDNode *MD = cast<MDNode>(Annotation);
894 const MDString *Name = cast<MDString>(MD->getOperand(0));
895 if (Name->getString() != "btf_decl_tag")
896 continue;
897
898 const MDString *Value = cast<MDString>(MD->getOperand(1));
899 auto TypeEntry = std::make_unique<BTFTypeDeclTag>(BaseTypeId, ComponentIdx,
900 Value->getString());
901 addType(std::move(TypeEntry));
902 }
903}
904
905uint32_t BTFDebug::processDISubprogram(
906 const DISubprogram *SP, uint32_t ProtoTypeId, uint8_t Scope,
907 const SmallDenseMap<uint32_t, uint32_t> *ArgIndexMap) {
908 auto FuncTypeEntry =
909 std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
910 uint32_t FuncId = addType(std::move(FuncTypeEntry));
911
912 // Process argument annotations.
913 for (const MDNode *DN : SP->getRetainedNodes()) {
914 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
915 uint32_t Arg = DV->getArg();
916 if (Arg) {
917 if (ArgIndexMap) {
918 auto It = ArgIndexMap->find(Arg);
919 if (It != ArgIndexMap->end())
920 processDeclAnnotations(DV->getAnnotations(), FuncId, It->second);
921 } else {
922 processDeclAnnotations(DV->getAnnotations(), FuncId, Arg - 1);
923 }
924 }
925 }
926 }
927 processDeclAnnotations(SP->getAnnotations(), FuncId, -1);
928
929 return FuncId;
930}
931
932/// Generate btf_type_tag chains.
933int BTFDebug::genBTFTypeTags(const DIDerivedType *DTy, int BaseTypeId) {
935 DINodeArray Annots = DTy->getAnnotations();
936 if (Annots) {
937 // For type with "int __tag1 __tag2 *p", the MDStrs will have
938 // content: [__tag1, __tag2].
939 for (const Metadata *Annotations : Annots->operands()) {
940 const MDNode *MD = cast<MDNode>(Annotations);
941 const MDString *Name = cast<MDString>(MD->getOperand(0));
942 if (Name->getString() != "btf_type_tag")
943 continue;
944 MDStrs.push_back(cast<MDString>(MD->getOperand(1)));
945 }
946 }
947
948 if (MDStrs.size() == 0)
949 return -1;
950
951 // With MDStrs [__tag1, __tag2], the output type chain looks like
952 // PTR -> __tag2 -> __tag1 -> BaseType
953 // In the below, we construct BTF types with the order of __tag1, __tag2
954 // and PTR.
955 unsigned TmpTypeId;
956 std::unique_ptr<BTFTypeTypeTag> TypeEntry;
957 if (BaseTypeId >= 0)
958 TypeEntry =
959 std::make_unique<BTFTypeTypeTag>(BaseTypeId, MDStrs[0]->getString());
960 else
961 TypeEntry = std::make_unique<BTFTypeTypeTag>(DTy, MDStrs[0]->getString());
962 TmpTypeId = addType(std::move(TypeEntry));
963
964 for (unsigned I = 1; I < MDStrs.size(); I++) {
965 const MDString *Value = MDStrs[I];
966 TypeEntry = std::make_unique<BTFTypeTypeTag>(TmpTypeId, Value->getString());
967 TmpTypeId = addType(std::move(TypeEntry));
968 }
969 return TmpTypeId;
970}
971
972/// Handle structure/union types.
973void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
974 uint32_t &TypeId) {
975 DINodeArray DIElements = CTy->getElements();
976 SmallVector<const DINode *, 8> Elements(DIElements.begin(), DIElements.end());
977 // Structure elements must have nondecreasing offsets in BTF. Preserve DI
978 // order for union and variant-part records.
979 if (CTy->getTag() == dwarf::DW_TAG_structure_type)
980 llvm::stable_sort(Elements, [](const DINode *LHS, const DINode *RHS) {
982 });
983 uint32_t VLen = Elements.size();
984 // Variant parts might have a discriminator. LLVM DI doesn't consider it as
985 // an element and instead keeps it as a separate reference. But we represent
986 // it as an element in BTF.
987 if (CTy->getTag() == dwarf::DW_TAG_variant_part) {
988 const auto *DTy = CTy->getDiscriminator();
989 if (DTy) {
990 visitTypeEntry(DTy);
991 VLen++;
992 }
993 }
994 if (VLen > BTF::MAX_VLEN)
995 return;
996
997 // Check whether we have any bitfield members or not
998 bool HasBitField = false;
999 for (const auto *Element : Elements) {
1000 if (Element->getTag() == dwarf::DW_TAG_member) {
1001 auto E = cast<DIDerivedType>(Element);
1002 if (E->isBitField()) {
1003 HasBitField = true;
1004 break;
1005 }
1006 }
1007 }
1008
1009 auto TypeEntry = std::make_unique<BTFTypeStruct>(CTy, Elements, IsStruct,
1010 HasBitField, VLen);
1011 StructTypes.push_back(TypeEntry.get());
1012 TypeId = addType(std::move(TypeEntry), CTy);
1013
1014 // Check struct/union annotations
1015 processDeclAnnotations(CTy->getAnnotations(), TypeId, -1);
1016
1017 // Visit all struct members.
1018 int FieldNo = 0;
1019 for (const auto *Element : Elements) {
1020 switch (Element->getTag()) {
1021 case dwarf::DW_TAG_member: {
1022 const auto Elem = cast<DIDerivedType>(Element);
1023 visitTypeEntry(Elem);
1024 processDeclAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
1025 break;
1026 }
1027 case dwarf::DW_TAG_variant_part: {
1028 const auto Elem = cast<DICompositeType>(Element);
1029 visitTypeEntry(Elem);
1030 processDeclAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
1031 break;
1032 }
1033 default:
1034 llvm_unreachable("Unexpected DI tag of a struct/union element");
1035 }
1036 FieldNo++;
1037 }
1038}
1039
1040// After a diagnostic, use a placeholder length so enclosing types can still
1041// refer to the array during error recovery.
1042static uint32_t getBTFArrayLength(const DINode *Dimension, MCContext &Ctx) {
1043 const auto *Range = dyn_cast<DISubrange>(Dimension);
1044 const auto *Count =
1045 Range ? dyn_cast_if_present<ConstantInt *>(Range->getCount()) : nullptr;
1046 if (!Count) {
1047 Ctx.reportError({},
1048 "BTF array dimension requires a constant element count");
1049 return 0;
1050 }
1051 // A flexible array has count -1 in debug info and zero elements in BTF.
1052 if (Count->isMinusOne())
1053 return 0;
1054 if (!Count->getValue().isIntN(32)) {
1055 Ctx.reportError({}, "BTF array length exceeds the 32-bit limit");
1056 return 0;
1057 }
1058 return Count->getZExtValue();
1059}
1060
1061void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
1062 // Visit array element type.
1063 uint32_t ElemTypeId = 0;
1064 const DIType *ElemType = tryRemoveAtomicType(CTy->getBaseType());
1065 visitTypeEntry(ElemType, ElemTypeId, false, false);
1066 if (!ElemTypeId) {
1067 SmallString<128> Message;
1068 raw_svector_ostream Err(Message);
1069 Err << "unsupported BTF array element type";
1070 if (ElemType && !ElemType->getName().empty())
1071 Err << " '" << ElemType->getName() << '\'';
1072 OS.getContext().reportError({}, Message);
1073 // Still register the array so enclosing types can resolve their references.
1074 }
1075
1076 // Visit array dimensions.
1077 DINodeArray Elements = CTy->getElements();
1078 // Build the inner arrays first. Only the outermost is registered for CTy.
1079 for (unsigned I = Elements.size(); I > 1; --I) {
1080 const uint32_t Count = getBTFArrayLength(Elements[I - 1], OS.getContext());
1081 ElemTypeId = addType(std::make_unique<BTFTypeArray>(ElemTypeId, Count));
1082 }
1083 // Rust and other languages may omit the dimensions of a zero-length array.
1084 const uint32_t OuterCount =
1085 Elements.empty() ? 0 : getBTFArrayLength(Elements[0], OS.getContext());
1086 TypeId = addType(std::make_unique<BTFTypeArray>(ElemTypeId, OuterCount), CTy);
1087
1088 // The IR does not have a type for array index while BTF wants one.
1089 // So create an array index type if there is none.
1090 if (!ArrayIndexTypeId) {
1091 auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
1092 0, "__ARRAY_SIZE_TYPE__");
1093 ArrayIndexTypeId = addType(std::move(TypeEntry));
1094 }
1095}
1096
1097void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
1098 DINodeArray Elements = CTy->getElements();
1099 uint32_t VLen = Elements.size();
1100 if (VLen > BTF::MAX_VLEN)
1101 return;
1102
1103 bool IsSigned = false;
1104 unsigned NumBits = 32;
1105 // No BaseType implies forward declaration in which case a
1106 // BTFTypeEnum with Vlen = 0 is emitted.
1107 if (CTy->getBaseType() != nullptr) {
1108 const auto *BTy = cast<DIBasicType>(CTy->getBaseType());
1109 IsSigned = BTy->getEncoding() == dwarf::DW_ATE_signed ||
1110 BTy->getEncoding() == dwarf::DW_ATE_signed_char;
1111 NumBits = BTy->getSizeInBits();
1112 }
1113
1114 if (NumBits <= 32) {
1115 auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen, IsSigned);
1116 TypeId = addType(std::move(TypeEntry), CTy);
1117 } else {
1118 assert(NumBits == 64);
1119 auto TypeEntry = std::make_unique<BTFTypeEnum64>(CTy, VLen, IsSigned);
1120 TypeId = addType(std::move(TypeEntry), CTy);
1121 }
1122 // No need to visit base type as BTF does not encode it.
1123}
1124
1125/// Handle structure/union forward declarations.
1126void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
1127 uint32_t &TypeId) {
1128 auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
1129 TypeId = addType(std::move(TypeEntry), CTy);
1130}
1131
1132/// Handle structure, union, array and enumeration types.
1133void BTFDebug::visitCompositeType(const DICompositeType *CTy,
1134 uint32_t &TypeId) {
1135 auto Tag = CTy->getTag();
1136 switch (Tag) {
1137 case dwarf::DW_TAG_structure_type:
1138 case dwarf::DW_TAG_union_type:
1139 case dwarf::DW_TAG_variant_part:
1140 // Handle forward declaration differently as it does not have members.
1141 if (CTy->isForwardDecl())
1142 visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
1143 else
1144 visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
1145 break;
1146 case dwarf::DW_TAG_array_type:
1147 visitArrayType(CTy, TypeId);
1148 break;
1149 case dwarf::DW_TAG_enumeration_type:
1150 visitEnumType(CTy, TypeId);
1151 break;
1152 default:
1153 llvm_unreachable("Unexpected DI tag of a composite type");
1154 }
1155}
1156
1157bool BTFDebug::IsForwardDeclCandidate(const DIType *Base) {
1158 if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
1159 auto CTag = CTy->getTag();
1160 if ((CTag == dwarf::DW_TAG_structure_type ||
1161 CTag == dwarf::DW_TAG_union_type) &&
1162 !CTy->getName().empty() && !CTy->isForwardDecl())
1163 return true;
1164 }
1165 return false;
1166}
1167
1168/// Handle pointer, typedef, const, volatile, restrict and member types.
1169void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
1170 bool CheckPointer, bool SeenPointer) {
1171 unsigned Tag = DTy->getTag();
1172
1173 if (Tag == dwarf::DW_TAG_atomic_type)
1174 return visitTypeEntry(DTy->getBaseType(), TypeId, CheckPointer,
1175 SeenPointer);
1176
1177 /// Try to avoid chasing pointees, esp. structure pointees which may
1178 /// unnecessary bring in a lot of types.
1179 if (CheckPointer && !SeenPointer) {
1180 SeenPointer = Tag == dwarf::DW_TAG_pointer_type && !DTy->getAnnotations();
1181 }
1182
1183 if (CheckPointer && SeenPointer) {
1184 const DIType *Base = DTy->getBaseType();
1185 if (Base) {
1186 if (IsForwardDeclCandidate(Base)) {
1187 /// Find a candidate, generate a fixup. Later on the struct/union
1188 /// pointee type will be replaced with either a real type or
1189 /// a forward declaration.
1190 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
1191 auto &Fixup = FixupDerivedTypes[cast<DICompositeType>(Base)];
1192 Fixup.push_back(std::make_pair(DTy, TypeEntry.get()));
1193 TypeId = addType(std::move(TypeEntry), DTy);
1194 return;
1195 }
1196 }
1197 }
1198
1199 if (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_typedef) {
1200 int TmpTypeId = genBTFTypeTags(DTy, -1);
1201 if (TmpTypeId >= 0) {
1202 auto TypeDEntry =
1203 std::make_unique<BTFTypeDerived>(TmpTypeId, Tag, DTy->getName());
1204 TypeId = addType(std::move(TypeDEntry), DTy);
1205 } else {
1206 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
1207 TypeId = addType(std::move(TypeEntry), DTy);
1208 }
1209 if (Tag == dwarf::DW_TAG_typedef)
1210 processDeclAnnotations(DTy->getAnnotations(), TypeId, -1);
1211 } else if (Tag == dwarf::DW_TAG_const_type ||
1212 Tag == dwarf::DW_TAG_volatile_type ||
1213 Tag == dwarf::DW_TAG_restrict_type) {
1214 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
1215 TypeId = addType(std::move(TypeEntry), DTy);
1216 } else if (Tag != dwarf::DW_TAG_member) {
1217 return;
1218 }
1219
1220 // Visit base type of pointer, typedef, const, volatile, restrict or
1221 // struct/union member.
1222 uint32_t TempTypeId = 0;
1223 if (Tag == dwarf::DW_TAG_member)
1224 visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
1225 else
1226 visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
1227}
1228
1229/// Visit a type entry. CheckPointer is true if the type has
1230/// one of its predecessors as one struct/union member. SeenPointer
1231/// is true if CheckPointer is true and one of its predecessors
1232/// is a pointer. The goal of CheckPointer and SeenPointer is to
1233/// do pruning for struct/union types so some of these types
1234/// will not be emitted in BTF and rather forward declarations
1235/// will be generated.
1236void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
1237 bool CheckPointer, bool SeenPointer) {
1238 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
1239 TypeId = DIToIdMap[Ty];
1240
1241 // To handle the case like the following:
1242 // struct t;
1243 // typedef struct t _t;
1244 // struct s1 { _t *c; };
1245 // int test1(struct s1 *arg) { ... }
1246 //
1247 // struct t { int a; int b; };
1248 // struct s2 { _t c; }
1249 // int test2(struct s2 *arg) { ... }
1250 //
1251 // During traversing test1() argument, "_t" is recorded
1252 // in DIToIdMap and a forward declaration fixup is created
1253 // for "struct t" to avoid pointee type traversal.
1254 //
1255 // During traversing test2() argument, even if we see "_t" is
1256 // already defined, we should keep moving to eventually
1257 // bring in types for "struct t". Otherwise, the "struct s2"
1258 // definition won't be correct.
1259 //
1260 // In the above, we have following debuginfo:
1261 // {ptr, struct_member} -> typedef -> struct
1262 // and BTF type for 'typedef' is generated while 'struct' may
1263 // be in FixUp. But let us generalize the above to handle
1264 // {different types} -> [various derived types]+ -> another type.
1265 // For example,
1266 // {func_param, struct_member} -> const -> ptr -> volatile -> struct
1267 // We will traverse const/ptr/volatile which already have corresponding
1268 // BTF types and generate type for 'struct' which might be in Fixup
1269 // state.
1270 if (Ty && (!CheckPointer || !SeenPointer)) {
1271 if (const auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
1272 while (DTy) {
1273 const DIType *BaseTy = DTy->getBaseType();
1274 if (!BaseTy)
1275 break;
1276
1277 if (DIToIdMap.find(BaseTy) != DIToIdMap.end()) {
1278 DTy = dyn_cast<DIDerivedType>(BaseTy);
1279 } else {
1280 if (CheckPointer && DTy->getTag() == dwarf::DW_TAG_pointer_type &&
1281 !DTy->getAnnotations()) {
1282 SeenPointer = true;
1283 if (IsForwardDeclCandidate(BaseTy))
1284 break;
1285 }
1286 uint32_t TmpTypeId;
1287 visitTypeEntry(BaseTy, TmpTypeId, CheckPointer, SeenPointer);
1288 break;
1289 }
1290 }
1291 }
1292 }
1293
1294 return;
1295 }
1296
1297 if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
1298 visitBasicType(BTy, TypeId);
1299 else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
1300 visitSubroutineType(STy, false, SmallDenseMap<uint32_t, StringRef>(),
1301 TypeId);
1302 else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
1303 visitCompositeType(CTy, TypeId);
1304 else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
1305 visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
1306 else
1307 llvm_unreachable("Unknown DIType");
1308}
1309
1310void BTFDebug::visitTypeEntry(const DIType *Ty) {
1311 uint32_t TypeId;
1312 visitTypeEntry(Ty, TypeId, false, false);
1313}
1314
1315void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
1316 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
1317 TypeId = DIToIdMap[Ty];
1318 return;
1319 }
1320
1321 uint32_t TmpId;
1322 switch (Ty->getTag()) {
1323 case dwarf::DW_TAG_typedef:
1324 case dwarf::DW_TAG_const_type:
1325 case dwarf::DW_TAG_volatile_type:
1326 case dwarf::DW_TAG_restrict_type:
1327 case dwarf::DW_TAG_pointer_type:
1328 visitMapDefType(dyn_cast<DIDerivedType>(Ty)->getBaseType(), TmpId);
1329 break;
1330 case dwarf::DW_TAG_array_type:
1331 // Visit nested map array and jump to the element type
1332 visitMapDefType(dyn_cast<DICompositeType>(Ty)->getBaseType(), TmpId);
1333 break;
1334 case dwarf::DW_TAG_structure_type: {
1335 // Visit all struct members to ensure their types are visited.
1336 const auto *CTy = cast<DICompositeType>(Ty);
1337 const DINodeArray Elements = CTy->getElements();
1338 for (const auto *Element : Elements) {
1339 const auto *MemberType = cast<DIDerivedType>(Element);
1340 const DIType *MemberBaseType = MemberType->getBaseType();
1341 // If the member is a composite type, that may indicate the currently
1342 // visited composite type is a wrapper, and the member represents the
1343 // actual map definition.
1344 // In that case, visit the member with `visitMapDefType` instead of
1345 // `visitTypeEntry`, treating it specifically as a map definition rather
1346 // than as a regular composite type.
1347 const auto *MemberCTy = dyn_cast<DICompositeType>(MemberBaseType);
1348 if (MemberCTy) {
1349 visitMapDefType(MemberBaseType, TmpId);
1350 } else {
1351 visitTypeEntry(MemberBaseType);
1352 }
1353 }
1354 break;
1355 }
1356 default:
1357 break;
1358 }
1359
1360 // Visit this type, struct or a const/typedef/volatile/restrict type
1361 visitTypeEntry(Ty, TypeId, false, false);
1362}
1363
1364/// Read file contents from the actual file or from the source
1365std::string BTFDebug::populateFileContent(const DIFile *File) {
1366 std::string FileName;
1367
1368 if (!File->getFilename().starts_with("/") && File->getDirectory().size())
1369 FileName = File->getDirectory().str() + "/" + File->getFilename().str();
1370 else
1371 FileName = std::string(File->getFilename());
1372
1373 // No need to populate the contends if it has been populated!
1374 if (FileContent.contains(FileName))
1375 return FileName;
1376
1377 std::vector<std::string> Content;
1378 std::string Line;
1379 Content.push_back(Line); // Line 0 for empty string
1380
1381 auto LoadFile = [&File](StringRef FileName) {
1382 return File->getContext().getVirtualFileSystem().getBufferForFile(FileName);
1383 };
1384
1385 std::unique_ptr<MemoryBuffer> Buf;
1386 auto Source = File->getSource();
1387 if (Source)
1388 Buf = MemoryBuffer::getMemBufferCopy(*Source);
1389 else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = LoadFile(FileName))
1390 Buf = std::move(*BufOrErr);
1391 if (Buf)
1392 for (line_iterator I(*Buf, false), E; I != E; ++I)
1393 Content.push_back(std::string(*I));
1394
1395 FileContent[FileName] = std::move(Content);
1396 return FileName;
1397}
1398
1399void BTFDebug::constructLineInfo(MCSymbol *Label, const DIFile *File,
1400 uint32_t Line, uint32_t Column) {
1401 std::string FileName = populateFileContent(File);
1402 BTFLineInfo LineInfo;
1403
1404 LineInfo.Label = Label;
1405 LineInfo.FileNameOff = addString(FileName);
1406 // If file content is not available, let LineOff = 0.
1407 const auto &Content = FileContent[FileName];
1408 if (Line < Content.size())
1409 LineInfo.LineOff = addString(Content[Line]);
1410 else
1411 LineInfo.LineOff = 0;
1412 LineInfo.LineNum = Line;
1413 LineInfo.ColumnNum = Column;
1414 LineInfoTable[SecNameOff].push_back(LineInfo);
1415}
1416
1417void BTFDebug::emitCommonHeader() {
1418 OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC));
1419 OS.emitIntValue(BTF::MAGIC, 2);
1420 OS.emitInt8(BTF::VERSION);
1421 OS.emitInt8(0);
1422}
1423
1424void BTFDebug::emitBTFSection() {
1425 // Do not emit section if no types and only "" string.
1426 if (!TypeEntries.size() && StringTable.getSize() == 1)
1427 return;
1428
1429 MCContext &Ctx = OS.getContext();
1430 MCSectionELF *Sec = Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0);
1431 Sec->setAlignment(Align(4));
1432 OS.switchSection(Sec);
1433
1434 // Emit header.
1435 emitCommonHeader();
1436 OS.emitInt32(BTF::HeaderSize);
1437
1438 uint32_t TypeLen = 0, StrLen;
1439 for (const auto &TypeEntry : TypeEntries)
1440 TypeLen += TypeEntry->getSize();
1441 StrLen = StringTable.getSize();
1442
1443 OS.emitInt32(0);
1444 OS.emitInt32(TypeLen);
1445 OS.emitInt32(TypeLen);
1446 OS.emitInt32(StrLen);
1447
1448 // Emit type table.
1449 for (const auto &TypeEntry : TypeEntries)
1450 TypeEntry->emitType(OS);
1451
1452 // Emit string table.
1453 uint32_t StringOffset = 0;
1454 for (const auto &S : StringTable.getTable()) {
1455 OS.AddComment("string offset=" + std::to_string(StringOffset));
1456 OS.emitBytes(S);
1457 OS.emitBytes(StringRef("\0", 1));
1458 StringOffset += S.size() + 1;
1459 }
1460}
1461
1462void BTFDebug::emitBTFExtSection() {
1463 // Do not emit section if empty FuncInfoTable and LineInfoTable
1464 // and FieldRelocTable.
1465 if (!FuncInfoTable.size() && !LineInfoTable.size() &&
1466 !FieldRelocTable.size())
1467 return;
1468
1469 MCContext &Ctx = OS.getContext();
1470 MCSectionELF *Sec = Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0);
1471 Sec->setAlignment(Align(4));
1472 OS.switchSection(Sec);
1473
1474 // Emit header.
1475 emitCommonHeader();
1476 OS.emitInt32(BTF::ExtHeaderSize);
1477
1478 // Account for FuncInfo/LineInfo record size as well.
1479 uint32_t FuncLen = 4, LineLen = 4;
1480 // Do not account for optional FieldReloc.
1481 uint32_t FieldRelocLen = 0;
1482 for (const auto &FuncSec : FuncInfoTable) {
1483 FuncLen += BTF::SecFuncInfoSize;
1484 FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
1485 }
1486 for (const auto &LineSec : LineInfoTable) {
1487 LineLen += BTF::SecLineInfoSize;
1488 LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
1489 }
1490 for (const auto &FieldRelocSec : FieldRelocTable) {
1491 FieldRelocLen += BTF::SecFieldRelocSize;
1492 FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
1493 }
1494
1495 if (FieldRelocLen)
1496 FieldRelocLen += 4;
1497
1498 OS.emitInt32(0);
1499 OS.emitInt32(FuncLen);
1500 OS.emitInt32(FuncLen);
1501 OS.emitInt32(LineLen);
1502 OS.emitInt32(FuncLen + LineLen);
1503 OS.emitInt32(FieldRelocLen);
1504
1505 // Emit func_info table.
1506 OS.AddComment("FuncInfo");
1507 OS.emitInt32(BTF::BPFFuncInfoSize);
1508 for (const auto &FuncSec : FuncInfoTable) {
1509 OS.AddComment("FuncInfo section string offset=" +
1510 std::to_string(FuncSec.first));
1511 OS.emitInt32(FuncSec.first);
1512 OS.emitInt32(FuncSec.second.size());
1513 for (const auto &FuncInfo : FuncSec.second) {
1514 Asm->emitLabelReference(FuncInfo.Label, 4);
1515 OS.emitInt32(FuncInfo.TypeId);
1516 }
1517 }
1518
1519 // Emit line_info table.
1520 OS.AddComment("LineInfo");
1521 OS.emitInt32(BTF::BPFLineInfoSize);
1522 for (const auto &LineSec : LineInfoTable) {
1523 OS.AddComment("LineInfo section string offset=" +
1524 std::to_string(LineSec.first));
1525 OS.emitInt32(LineSec.first);
1526 OS.emitInt32(LineSec.second.size());
1527 for (const auto &LineInfo : LineSec.second) {
1528 Asm->emitLabelReference(LineInfo.Label, 4);
1529 OS.emitInt32(LineInfo.FileNameOff);
1530 OS.emitInt32(LineInfo.LineOff);
1531 OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
1532 std::to_string(LineInfo.ColumnNum));
1533 OS.emitInt32(LineInfo.LineNum << 10 | LineInfo.ColumnNum);
1534 }
1535 }
1536
1537 // Emit field reloc table.
1538 if (FieldRelocLen) {
1539 OS.AddComment("FieldReloc");
1540 OS.emitInt32(BTF::BPFFieldRelocSize);
1541 for (const auto &FieldRelocSec : FieldRelocTable) {
1542 OS.AddComment("Field reloc section string offset=" +
1543 std::to_string(FieldRelocSec.first));
1544 OS.emitInt32(FieldRelocSec.first);
1545 OS.emitInt32(FieldRelocSec.second.size());
1546 for (const auto &FieldRelocInfo : FieldRelocSec.second) {
1547 Asm->emitLabelReference(FieldRelocInfo.Label, 4);
1548 OS.emitInt32(FieldRelocInfo.TypeID);
1549 OS.emitInt32(FieldRelocInfo.OffsetNameOff);
1550 OS.emitInt32(FieldRelocInfo.RelocKind);
1551 }
1552 }
1553 }
1554}
1555
1557 auto *SP = MF->getFunction().getSubprogram();
1558 auto *Unit = SP->getUnit();
1559
1560 if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
1561 SkipInstruction = true;
1562 return;
1563 }
1564 SkipInstruction = false;
1565
1566 // Collect MapDef types. Map definition needs to collect
1567 // pointee types. Do it first. Otherwise, for the following
1568 // case:
1569 // struct m { ...};
1570 // struct t {
1571 // struct m *key;
1572 // };
1573 // foo(struct t *arg);
1574 //
1575 // struct mapdef {
1576 // ...
1577 // struct m *key;
1578 // ...
1579 // } __attribute__((section(".maps"))) hash_map;
1580 //
1581 // If subroutine foo is traversed first, a type chain
1582 // "ptr->struct m(fwd)" will be created and later on
1583 // when traversing mapdef, since "ptr->struct m" exists,
1584 // the traversal of "struct m" will be omitted.
1585 if (MapDefNotCollected) {
1586 processGlobals(true);
1587 MapDefNotCollected = false;
1588 }
1589
1590 // Collect all types locally referenced in this function.
1591 // Use RetainedNodes so we can collect all argument names
1592 // even if the argument is not used.
1594 for (const MDNode *DN : SP->getRetainedNodes()) {
1595 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1596 // Collect function arguments for subprogram func type.
1597 uint32_t Arg = DV->getArg();
1598 if (Arg) {
1599 visitTypeEntry(DV->getType());
1600 FuncArgNames[Arg] = DV->getName();
1601 }
1602 }
1603 }
1604
1605 // Construct subprogram func proto type.
1606 uint32_t ProtoTypeId, FuncTypeId;
1607 uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
1608 bool IsNocall = SP->getType()->getCC() == dwarf::DW_CC_nocall;
1609 bool UseFilteredParams = false;
1610 bool VoidReturn = MF->getFunction().getReturnType()->isVoidTy();
1611
1612 if (IsNocall) {
1613 // For DW_CC_nocall functions, try to build a FUNC_PROTO reflecting
1614 // the true ABI: only parameters that survived optimization and whose
1615 // first 5 arguments map to the correct BPF registers (R1-R5).
1617 DITypeArray Elements = SP->getType()->getTypeArray();
1618
1621
1622 UseFilteredParams =
1623 canUseNocallOptimizedSignature(*MF, Elements, AliveArgs, *TRI);
1624
1625 if (UseFilteredParams) {
1626 SmallVector<uint32_t, 8> AliveParamIndices;
1628 for (auto [I, ArgReg] : llvm::enumerate(AliveArgs)) {
1629 AliveParamIndices.push_back(ArgReg.first);
1630 ArgIndexMap[ArgReg.first] = I;
1631 }
1632
1633 if (!VoidReturn)
1634 visitTypeEntry(Elements[0]);
1635 for (uint32_t ArgNo : AliveParamIndices)
1636 visitTypeEntry(Elements[ArgNo]);
1637
1638 auto TypeEntry = std::make_unique<BTFTypeFuncProto>(
1639 SP->getType(), AliveParamIndices.size(), FuncArgNames, true,
1640 AliveParamIndices, VoidReturn);
1641 ProtoTypeId = addType(std::move(TypeEntry));
1642 FuncTypeId = processDISubprogram(SP, ProtoTypeId, Scope, &ArgIndexMap);
1643 }
1644 }
1645
1646 if (!UseFilteredParams) {
1647 // Fall back to the full source prototype, still voiding the return
1648 // type if compiler removed it.
1649 visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId,
1650 VoidReturn);
1651 FuncTypeId = processDISubprogram(SP, ProtoTypeId, Scope);
1652 }
1653
1654 for (const auto &TypeEntry : TypeEntries)
1655 TypeEntry->completeType(*this);
1656
1657 // Construct funcinfo and the first lineinfo for the function.
1658 MCSymbol *FuncLabel = Asm->getFunctionBegin();
1659 BTFFuncInfo FuncInfo;
1660 FuncInfo.Label = FuncLabel;
1661 FuncInfo.TypeId = FuncTypeId;
1662 if (FuncLabel->isInSection()) {
1663 auto &Sec = static_cast<const MCSectionELF &>(FuncLabel->getSection());
1664 SecNameOff = addString(Sec.getName());
1665 } else {
1666 SecNameOff = addString(".text");
1667 }
1668 FuncInfoTable[SecNameOff].push_back(FuncInfo);
1669}
1670
1672 SkipInstruction = false;
1673 LineInfoGenerated = false;
1674 SecNameOff = 0;
1675}
1676
1677/// On-demand populate types as requested from abstract member
1678/// accessing or preserve debuginfo type.
1679unsigned BTFDebug::populateType(const DIType *Ty) {
1680 unsigned Id;
1681 visitTypeEntry(Ty, Id, false, false);
1682 for (const auto &TypeEntry : TypeEntries)
1683 TypeEntry->completeType(*this);
1684 return Id;
1685}
1686
1687/// Generate a struct member field relocation.
1688void BTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
1689 const GlobalVariable *GVar, bool IsAma) {
1690 BTFFieldReloc FieldReloc;
1691 FieldReloc.Label = ORSym;
1692 FieldReloc.TypeID = RootId;
1693
1694 if (IsAma) {
1696 FieldReloc.OffsetNameOff = addString(Reloc.AccessString);
1697 FieldReloc.RelocKind = Reloc.Kind;
1698 PatchImms[GVar] = {Reloc.PatchImm, Reloc.Kind};
1699 } else {
1700 StringRef RelocStr = GVar->getName().split('$').second;
1701 FieldReloc.OffsetNameOff = addString("0");
1702 FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
1703 PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
1704 }
1705 FieldRelocTable[SecNameOff].push_back(FieldReloc);
1706}
1707
1708void BTFDebug::processGlobalValue(const MachineOperand &MO) {
1709 // check whether this is a candidate or not
1710 if (MO.isGlobal()) {
1711 const GlobalValue *GVal = MO.getGlobal();
1712 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1713 if (!GVar) {
1714 // Not a global variable. Maybe an extern function reference.
1715 processFuncPrototypes(dyn_cast<Function>(GVal));
1716 return;
1717 }
1718
1721 return;
1722
1723 MCSymbol *ORSym = OS.getContext().createTempSymbol();
1724 OS.emitLabel(ORSym);
1725
1726 MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
1727 uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
1728 generatePatchImmReloc(ORSym, RootId, GVar,
1730 }
1731}
1732
1735
1736 if (SkipInstruction || MI->isMetaInstruction() ||
1737 MI->getFlag(MachineInstr::FrameSetup))
1738 return;
1739
1740 if (MI->isInlineAsm()) {
1741 // Count the number of register definitions to find the asm string.
1742 unsigned NumDefs = 0;
1743 while (true) {
1744 const MachineOperand &MO = MI->getOperand(NumDefs);
1745 if (MO.isReg() && MO.isDef()) {
1746 ++NumDefs;
1747 continue;
1748 }
1749 // Skip this inline asm instruction if the asmstr is empty.
1750 const char *AsmStr = MO.getSymbolName();
1751 if (AsmStr[0] == 0)
1752 return;
1753 break;
1754 }
1755 }
1756
1757 if (MI->getOpcode() == BPF::LD_imm64) {
1758 // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
1759 // add this insn into the .BTF.ext FieldReloc subsection.
1760 // Relocation looks like:
1761 // . SecName:
1762 // . InstOffset
1763 // . TypeID
1764 // . OffSetNameOff
1765 // . RelocType
1766 // Later, the insn is replaced with "r2 = <offset>"
1767 // where "<offset>" equals to the offset based on current
1768 // type definitions.
1769 //
1770 // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
1771 // The LD_imm64 result will be replaced with a btf type id.
1772 processGlobalValue(MI->getOperand(1));
1773 } else if (MI->getOpcode() == BPF::CORE_LD64 ||
1774 MI->getOpcode() == BPF::CORE_LD32 ||
1775 MI->getOpcode() == BPF::CORE_ST ||
1776 MI->getOpcode() == BPF::CORE_SHIFT) {
1777 // relocation insn is a load, store or shift insn.
1778 processGlobalValue(MI->getOperand(3));
1779 } else if (MI->getOpcode() == BPF::JAL) {
1780 // check extern function references
1781 const MachineOperand &MO = MI->getOperand(0);
1782 if (MO.isGlobal()) {
1783 processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
1784 }
1785 }
1786
1787 if (!CurMI) // no debug info
1788 return;
1789
1790 // Skip this instruction if no DebugLoc, the DebugLoc
1791 // is the same as the previous instruction or Line is 0.
1792 const DebugLoc &DL = MI->getDebugLoc();
1793 if (!DL || PrevInstLoc == DL || DL.getLine() == 0) {
1794 // This instruction will be skipped, no LineInfo has
1795 // been generated, construct one based on function signature.
1796 if (LineInfoGenerated == false) {
1797 auto *S = MI->getMF()->getFunction().getSubprogram();
1798 if (!S)
1799 return;
1800 MCSymbol *FuncLabel = Asm->getFunctionBegin();
1801 constructLineInfo(FuncLabel, S->getFile(), S->getLine(), 0);
1802 LineInfoGenerated = true;
1803 }
1804
1805 return;
1806 }
1807
1808 // Create a temporary label to remember the insn for lineinfo.
1809 MCSymbol *LineSym = OS.getContext().createTempSymbol();
1810 OS.emitLabel(LineSym);
1811
1812 // Construct the lineinfo.
1813 constructLineInfo(LineSym, DL->getFile(), DL.getLine(), DL.getCol());
1814
1815 LineInfoGenerated = true;
1816 PrevInstLoc = DL;
1817}
1818
1819void BTFDebug::processGlobals(bool ProcessingMapDef) {
1820 // Collect all types referenced by globals.
1821 const Module *M = MMI->getModule();
1822 for (const GlobalVariable &Global : M->globals()) {
1823 // Decide the section name.
1824 StringRef SecName;
1825 std::optional<SectionKind> GVKind;
1826
1827 if (!Global.isDeclarationForLinker())
1829
1830 if (Global.isDeclarationForLinker())
1831 SecName = Global.hasSection() ? Global.getSection() : "";
1832 else if (GVKind->isCommon())
1833 SecName = ".bss";
1834 else {
1836 MCSection *Sec = TLOF->SectionForGlobal(&Global, Asm->TM);
1837 SecName = Sec->getName();
1838 }
1839
1840 if (ProcessingMapDef != SecName.starts_with(".maps"))
1841 continue;
1842
1843 // Create a .rodata datasec if the global variable is an initialized
1844 // constant with private linkage and if it won't be in .rodata.str<#>
1845 // and .rodata.cst<#> sections.
1846 if (SecName == ".rodata" && Global.hasPrivateLinkage() &&
1847 DataSecEntries.find(SecName) == DataSecEntries.end()) {
1848 // skip .rodata.str<#> and .rodata.cst<#> sections
1849 if (!GVKind->isMergeableCString() && !GVKind->isMergeableConst()) {
1850 DataSecEntries[std::string(SecName)] =
1851 std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1852 }
1853 }
1854
1856 Global.getDebugInfo(GVs);
1857
1858 // No type information, mostly internal, skip it.
1859 if (GVs.size() == 0)
1860 continue;
1861
1862 uint32_t GVTypeId = 0;
1863 DIGlobalVariable *DIGlobal = nullptr;
1864 for (auto *GVE : GVs) {
1865 DIGlobal = GVE->getVariable();
1866 if (SecName.starts_with(".maps"))
1867 visitMapDefType(DIGlobal->getType(), GVTypeId);
1868 else {
1869 const DIType *Ty = tryRemoveAtomicType(DIGlobal->getType());
1870 visitTypeEntry(Ty, GVTypeId, false, false);
1871 }
1872 break;
1873 }
1874
1875 // Only support the following globals:
1876 // . static variables
1877 // . non-static weak or non-weak global variables
1878 // . weak or non-weak extern global variables
1879 // Whether DataSec is readonly or not can be found from corresponding ELF
1880 // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1881 // can be found from the corresponding ELF symbol table.
1882 auto Linkage = Global.getLinkage();
1888 continue;
1889
1890 uint32_t GVarInfo;
1892 GVarInfo = BTF::VAR_STATIC;
1893 } else if (Global.hasInitializer()) {
1894 GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
1895 } else {
1896 GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
1897 }
1898
1899 auto VarEntry =
1900 std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
1901 uint32_t VarId = addType(std::move(VarEntry));
1902
1903 processDeclAnnotations(DIGlobal->getAnnotations(), VarId, -1);
1904
1905 // An empty SecName means an extern variable without section attribute.
1906 if (SecName.empty())
1907 continue;
1908
1909 // Find or create a DataSec
1910 auto [It, Inserted] = DataSecEntries.try_emplace(std::string(SecName));
1911 if (Inserted)
1912 It->second = std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1913
1914 // Calculate symbol size
1915 const DataLayout &DL = Global.getDataLayout();
1916 uint32_t Size = Global.getGlobalSize(DL);
1917
1918 It->second->addDataSecEntry(VarId, Asm->getSymbol(&Global), Size);
1919
1920 if (Global.hasInitializer())
1921 processGlobalInitializer(Global.getInitializer());
1922 }
1923}
1924
1925/// Process global variable initializer in pursuit for function
1926/// pointers. Add discovered (extern) functions to BTF. Some (extern)
1927/// functions might have been missed otherwise. Every symbol needs BTF
1928/// info when linking with bpftool. Primary use case: "static"
1929/// initialization of BPF maps.
1930///
1931/// struct {
1932/// __uint(type, BPF_MAP_TYPE_PROG_ARRAY);
1933/// ...
1934/// } prog_map SEC(".maps") = { .values = { extern_func } };
1935///
1936void BTFDebug::processGlobalInitializer(const Constant *C) {
1937 if (auto *Fn = dyn_cast<Function>(C))
1938 processFuncPrototypes(Fn);
1939 if (auto *CA = dyn_cast<ConstantAggregate>(C)) {
1940 for (unsigned I = 0, N = CA->getNumOperands(); I < N; ++I)
1941 processGlobalInitializer(CA->getOperand(I));
1942 }
1943}
1944
1945/// Emit proper patchable instructions.
1947 if (MI->getOpcode() == BPF::LD_imm64) {
1948 const MachineOperand &MO = MI->getOperand(1);
1949 if (MO.isGlobal()) {
1950 const GlobalValue *GVal = MO.getGlobal();
1951 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1952 if (GVar) {
1955 return false;
1956
1957 // Emit "mov ri, <imm>"
1958 auto [Imm, Reloc] = PatchImms[GVar];
1961 OutMI.setOpcode(BPF::LD_imm64);
1962 else
1963 OutMI.setOpcode(BPF::MOV_ri);
1964 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1966 return true;
1967 }
1968 }
1969 } else if (MI->getOpcode() == BPF::CORE_LD64 ||
1970 MI->getOpcode() == BPF::CORE_LD32 ||
1971 MI->getOpcode() == BPF::CORE_ST ||
1972 MI->getOpcode() == BPF::CORE_SHIFT) {
1973 const MachineOperand &MO = MI->getOperand(3);
1974 if (MO.isGlobal()) {
1975 const GlobalValue *GVal = MO.getGlobal();
1976 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1977 if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1978 uint32_t Imm = PatchImms[GVar].first;
1979 OutMI.setOpcode(MI->getOperand(1).getImm());
1980 if (MI->getOperand(0).isImm())
1981 OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
1982 else
1983 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1984 OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
1986 return true;
1987 }
1988 }
1989 }
1990 return false;
1991}
1992
1993void BTFDebug::processFuncPrototypes(const Function *F) {
1994 if (!F)
1995 return;
1996
1997 const DISubprogram *SP = F->getSubprogram();
1998 if (!SP || SP->isDefinition())
1999 return;
2000
2001 // Do not emit again if already emitted.
2002 if (!ProtoFunctions.insert(F).second)
2003 return;
2004
2005 uint32_t ProtoTypeId;
2006 const SmallDenseMap<uint32_t, StringRef> FuncArgNames;
2007 visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
2008 uint32_t FuncId = processDISubprogram(SP, ProtoTypeId, BTF::FUNC_EXTERN);
2009
2010 if (F->hasSection()) {
2011 StringRef SecName = F->getSection();
2012
2013 auto [It, Inserted] = DataSecEntries.try_emplace(std::string(SecName));
2014 if (Inserted)
2015 It->second = std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
2016
2017 // We really don't know func size, set it to 0.
2018 It->second->addDataSecEntry(FuncId, Asm->getSymbol(F), 0);
2019 }
2020}
2021
2023 // Collect MapDef globals if not collected yet.
2024 if (MapDefNotCollected) {
2025 processGlobals(true);
2026 MapDefNotCollected = false;
2027 }
2028
2029 // Collect global types/variables except MapDef globals.
2030 processGlobals(false);
2031
2032 // In case that BPF_TRAP usage is removed during machine-level optimization,
2033 // generate btf for BPF_TRAP function here.
2034 for (const Function &F : *MMI->getModule()) {
2035 if (F.getName() == BPF_TRAP)
2036 processFuncPrototypes(&F);
2037 }
2038
2039 for (auto &DataSec : DataSecEntries)
2040 addType(std::move(DataSec.second));
2041
2042 // Fixups
2043 for (auto &Fixup : FixupDerivedTypes) {
2044 const DICompositeType *CTy = Fixup.first;
2045 StringRef TypeName = CTy->getName();
2046 bool IsUnion = CTy->getTag() == dwarf::DW_TAG_union_type;
2047
2048 // Search through struct types
2049 uint32_t StructTypeId = 0;
2050 for (const auto &StructType : StructTypes) {
2051 if (StructType->getName() == TypeName) {
2052 StructTypeId = StructType->getId();
2053 break;
2054 }
2055 }
2056
2057 if (StructTypeId == 0) {
2058 auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
2059 StructTypeId = addType(std::move(FwdTypeEntry));
2060 }
2061
2062 for (auto &TypeInfo : Fixup.second) {
2063 const DIDerivedType *DTy = TypeInfo.first;
2064 BTFTypeDerived *BDType = TypeInfo.second;
2065
2066 int TmpTypeId = genBTFTypeTags(DTy, StructTypeId);
2067 if (TmpTypeId >= 0)
2068 BDType->setPointeeType(TmpTypeId);
2069 else
2070 BDType->setPointeeType(StructTypeId);
2071 }
2072 }
2073
2074 // Complete BTF type cross refereences.
2075 for (const auto &TypeEntry : TypeEntries)
2076 TypeEntry->completeType(*this);
2077
2078 // Emit BTF sections.
2079 emitBTFSection();
2080 emitBTFExtSection();
2081}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define BPF_TRAP
Definition BPF.h:29
static uint32_t getBTFArrayLength(const DINode *Dimension, MCContext &Ctx)
static SmallVector< std::pair< uint32_t, Register >, 8 > collectNocallEntryArgRegs(const MachineFunction &MF)
Collect the physical register each source argument lives in by scanning DBG_VALUE instructions in the...
Definition BTFDebug.cpp:129
static bool sourceArgMatchesIRType(const DIType *SourceTy, Type *IRTy)
Definition BTFDebug.cpp:81
static const char * BTFKindStr[]
Definition BTFDebug.cpp:50
static const DIType * stripDITypeAttributes(const DIType *Ty)
Definition BTFDebug.cpp:64
static bool canUseNocallOptimizedSignature(const MachineFunction &MF, DITypeArray Elements, ArrayRef< std::pair< uint32_t, Register > > AliveArgs, const TargetRegisterInfo &TRI)
Check whether the optimized IR signature matches the surviving source arguments precisely enough to e...
Definition BTFDebug.cpp:222
static const DIType * tryRemoveAtomicType(const DIType *Ty)
Definition BTFDebug.cpp:55
This file contains support for writing BTF debug info.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file contains constants used for implementing Dwarf debug support.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static StringRef getName(Value *V)
This file contains some templates that are useful if you are working with the STL at all.
static enum BaseType getBaseType(const Value *Val)
Return the baseType for Val which states whether Val is exclusively derived from constant/null,...
This file defines the SmallString class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
an instruction to allocate memory on the stack
Annotations lets you mark points and ranges inside source code, for tests:
Definition Annotations.h:67
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:95
MCSymbol * getSymbol(const GlobalValue *GV) const
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:98
static constexpr StringRef TypeIdAttr
The attribute attached to globals representing a type id.
Definition BPFCORE.h:64
static constexpr StringRef AmaAttr
The attribute attached to globals representing a field access.
Definition BPFCORE.h:62
Collect and emit BTF information.
Definition BTFDebug.h:297
void endFunctionImpl(const MachineFunction *MF) override
Post process after all instructions in this function are processed.
BTFDebug(AsmPrinter *AP)
Definition BTFDebug.cpp:805
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
bool InstLower(const MachineInstr *MI, MCInst &OutMI)
Emit proper patchable instructions.
size_t addString(StringRef S)
Add string to the string table.
Definition BTFDebug.h:427
uint32_t getArrayIndexTypeId()
Get the special array index type id.
Definition BTFDebug.h:421
uint32_t getTypeId(const DIType *Ty)
Get the type id for a particular DIType.
Definition BTFDebug.h:430
void endModule() override
Complete all the types and emit the BTF sections.
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:717
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:712
BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
Definition BTFDebug.cpp:705
BTFKindVar(StringRef VarName, uint32_t TypeId, uint32_t VarInfo)
Definition BTFDebug.cpp:688
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:700
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:696
uint32_t addString(StringRef S)
Add a string to the string table and returns its offset in the table.
Definition BTFDebug.cpp:791
BTFTypeArray(uint32_t ElemTypeId, uint32_t NumElems)
Definition BTFDebug.cpp:490
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:513
void completeType(BTFDebug &BDebug) override
Represent a BTF array.
Definition BTFDebug.cpp:501
struct BTF::CommonType BTFType
Definition BTFDebug.h:45
virtual void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition BTFDebug.cpp:259
uint32_t roundupToBytes(uint32_t NumBits)
Definition BTFDebug.h:52
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:751
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:759
BTFTypeDeclTag(uint32_t BaseTypeId, int ComponentId, StringRef Tag)
Definition BTFDebug.cpp:742
Handle several derived types include pointer, const, volatile, typedef and restrict.
Definition BTFDebug.h:65
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:312
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:344
void setPointeeType(uint32_t PointeeType)
Definition BTFDebug.cpp:346
BTFTypeDerived(const DIDerivedType *Ty, unsigned Tag, bool NeedsFixup)
Definition BTFDebug.cpp:268
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:455
BTFTypeEnum64(const DICompositeType *ETy, uint32_t NumValues, bool IsSigned)
Definition BTFDebug.cpp:448
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:479
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:416
BTFTypeEnum(const DICompositeType *ETy, uint32_t NumValues, bool IsSigned)
Definition BTFDebug.cpp:409
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:440
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:734
BTFTypeFloat(uint32_t SizeInBits, StringRef TypeName)
Definition BTFDebug.cpp:727
BTFTypeFuncProto(const DISubroutineType *STy, uint32_t NumParams, const SmallDenseMap< uint32_t, StringRef > &FuncArgNames, bool UseFilteredParams=false, ArrayRef< uint32_t > AliveParamIndices={}, bool VoidReturn=false)
The Func kind represents both subprogram and pointee of function pointers.
Definition BTFDebug.cpp:611
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:623
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:662
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:686
BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId, uint32_t Scope)
Definition BTFDebug.cpp:670
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:678
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:365
BTFTypeFwd(StringRef Name, bool IsUnion)
Represent a struct/union forward declaration.
Definition BTFDebug.cpp:351
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:357
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:403
BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits, uint32_t OffsetInBits, StringRef TypeName)
Definition BTFDebug.cpp:367
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:395
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition BTFDebug.cpp:594
BTFTypeStruct(const DICompositeType *STy, ArrayRef< const DINode * > Elements, bool IsStruct, bool HasBitField, uint32_t NumMembers)
Represent either a struct or a union.
Definition BTFDebug.cpp:521
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:531
std::string getName()
Definition BTFDebug.cpp:604
void completeType(BTFDebug &BDebug) override
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition BTFDebug.cpp:777
BTFTypeTypeTag(uint32_t NextTypeId, StringRef Tag)
Definition BTFDebug.cpp:764
This is an important base class in LLVM.
Definition Constant.h:44
Basic type, like 'int' or 'float'.
unsigned getEncoding() const
DIDerivedType * getDiscriminator() const
DINodeArray getElements() const
DINodeArray getAnnotations() const
DIType * getBaseType() const
DINodeArray getAnnotations() const
Get annotations associated with this derived type.
DINodeArray getAnnotations() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
Subprogram description. Uses SubclassData1.
Type array for a subprogram.
DITypeArray getTypeArray() const
Base class for types.
uint64_t getOffsetInBits() const
StringRef getName() const
bool isForwardDecl() const
uint64_t getSizeInBits() const
DIType * getType() const
const MachineInstr * CurMI
If nonnull, stores the current machine instruction we're processing.
AsmPrinter * Asm
Target of debug info emission.
MachineModuleInfo * MMI
Collected machine module information.
DebugLoc PrevInstLoc
Previous instruction's location information.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
A debug info location.
Definition DebugLoc.h:126
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
iterator begin()
Definition DenseMap.h:682
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
DISubprogram * getSubprogram() const
Get the attached subprogram.
arg_iterator arg_begin()
Definition Function.h:853
size_t arg_size() const
Definition Function.h:886
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists.
Context object for machine code objects.
Definition MCContext.h:83
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition MCContext.h:552
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
void addOperand(const MCOperand Op)
Definition MCInst.h:215
void setOpcode(unsigned Op)
Definition MCInst.h:201
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:138
static MCOperand createImm(int64_t Val)
Definition MCInst.h:145
This represents a section on linux, lots of unix variants and some bare metal systems.
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:580
void setAlignment(Align Value)
Definition MCSection.h:665
StringRef getName() const
Definition MCSection.h:650
Streaming machine code generation interface.
Definition MCStreamer.h:222
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition MCStreamer.h:404
void emitInt32(uint64_t Value)
Definition MCStreamer.h:769
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition MCSymbol.h:237
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition MCSymbol.h:251
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
VariableDbgInfoMapTy & getVariableDbgInfo()
const MachineBasicBlock & front() const
Representation of each machine instruction.
A description of a memory reference used in the backend.
const Module * getModule() const
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Class to represent struct types.
LLVM_ABI StringRef getName() const
Return the name for this struct type if it has an identity.
Definition Type.cpp:736
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
virtual TargetLoweringObjectFile * getObjFileLowering() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
bool erase(const ValueT &V)
Definition DenseSet.h:98
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ INT_SIGNED
Definition BTF.h:145
@ INT_BOOL
Definition BTF.h:147
@ VAR_GLOBAL_ALLOCATED
Linkage: ExternalLinkage.
Definition BTF.h:208
@ VAR_STATIC
Linkage: InternalLinkage.
Definition BTF.h:207
@ VAR_GLOBAL_EXTERNAL
Linkage: ExternalLinkage.
Definition BTF.h:209
@ VERSION
Definition BTF.h:57
@ MAGIC
Definition BTF.h:57
@ BPFFuncInfoSize
Definition BTF.h:73
@ HeaderSize
Definition BTF.h:61
@ ExtHeaderSize
Definition BTF.h:62
@ SecLineInfoSize
Definition BTF.h:71
@ SecFieldRelocSize
Definition BTF.h:72
@ BPFLineInfoSize
Definition BTF.h:74
@ SecFuncInfoSize
Definition BTF.h:70
@ BPFFieldRelocSize
Definition BTF.h:75
@ MAX_VLEN
Max # of struct/union/enum members or func args.
Definition BTF.h:93
@ ENUM_VALUE
Definition BTF.h:292
@ ENUM_VALUE_EXISTENCE
Definition BTF.h:291
@ BTF_TYPE_ID_REMOTE
Definition BTF.h:288
@ BTF_TYPE_ID_LOCAL
Definition BTF.h:287
@ FUNC_STATIC
Definition BTF.h:200
@ FUNC_EXTERN
Definition BTF.h:202
@ FUNC_GLOBAL
Definition BTF.h:201
@ SHT_PROGBITS
Definition ELF.h:965
constexpr MCPhysReg SP
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
Definition TypePool.h:31
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
uint64_t getBTFRecordElementOffset(const DINode *Element)
Return the bit offset used to order an element of a BTF structure record.
Definition BPFCORE.h:26
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Global
Append to llvm.global_dtors.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
#define N
static AmaRelocation decode(StringRef Name)
Represent one field relocation.
Definition BTFDebug.h:289
uint32_t RelocKind
What to patch the instruction.
Definition BTFDebug.h:293
const MCSymbol * Label
MCSymbol identifying insn for the reloc.
Definition BTFDebug.h:290
uint32_t TypeID
Type ID.
Definition BTFDebug.h:291
uint32_t OffsetNameOff
The string to traverse types.
Definition BTFDebug.h:292
Represent one func and its type id.
Definition BTFDebug.h:274
uint32_t TypeId
Type id referring to .BTF type section.
Definition BTFDebug.h:276
const MCSymbol * Label
Func MCSymbol.
Definition BTFDebug.h:275
uint32_t LineOff
line offset in the .BTF string table
Definition BTFDebug.h:283
MCSymbol * Label
MCSymbol identifying insn for the lineinfo.
Definition BTFDebug.h:281
uint32_t ColumnNum
the column number
Definition BTFDebug.h:285
uint32_t FileNameOff
file name offset in the .BTF string table
Definition BTFDebug.h:282
uint32_t LineNum
the line number
Definition BTFDebug.h:284
BTF_KIND_ENUM64 is followed by multiple "struct BTFEnum64".
Definition BTF.h:161
uint32_t NameOff
Enum name offset in the string table.
Definition BTF.h:162
uint32_t Val_Hi32
Enum member hi32 value.
Definition BTF.h:164
uint32_t Val_Lo32
Enum member lo32 value.
Definition BTF.h:163
BTF_KIND_ENUM is followed by multiple "struct BTFEnum".
Definition BTF.h:153
int32_t Val
Enum member value.
Definition BTF.h:155
uint32_t NameOff
Enum name offset in the string table.
Definition BTF.h:154
BTF_KIND_STRUCT and BTF_KIND_UNION are followed by multiple "struct BTFMember".
Definition BTF.h:184
uint32_t NameOff
Member name offset in the string table.
Definition BTF.h:185
uint32_t Offset
BitOffset or BitFieldSize+BitOffset.
Definition BTF.h:187
uint32_t Type
Member type.
Definition BTF.h:186
BTF_KIND_FUNC_PROTO are followed by multiple "struct BTFParam".
Definition BTF.h:193
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1455