LLVM 22.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"
21#include "llvm/IR/Module.h"
22#include "llvm/MC/MCContext.h"
25#include "llvm/MC/MCStreamer.h"
29#include <optional>
30
31using namespace llvm;
32
33static const char *BTFKindStr[] = {
34#define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
35#include "llvm/DebugInfo/BTF/BTF.def"
36};
37
38static const DIType *tryRemoveAtomicType(const DIType *Ty) {
39 if (!Ty)
40 return Ty;
41 auto DerivedTy = dyn_cast<DIDerivedType>(Ty);
42 if (DerivedTy && DerivedTy->getTag() == dwarf::DW_TAG_atomic_type)
43 return DerivedTy->getBaseType();
44 return Ty;
45}
46
47/// Emit a BTF common type.
49 OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
50 ")");
51 OS.emitInt32(BTFType.NameOff);
52 OS.AddComment("0x" + Twine::utohexstr(BTFType.Info));
53 OS.emitInt32(BTFType.Info);
54 OS.emitInt32(BTFType.Size);
55}
56
58 bool NeedsFixup)
59 : DTy(DTy), NeedsFixup(NeedsFixup), Name(DTy->getName()) {
60 switch (Tag) {
61 case dwarf::DW_TAG_pointer_type:
62 Kind = BTF::BTF_KIND_PTR;
63 break;
64 case dwarf::DW_TAG_const_type:
65 Kind = BTF::BTF_KIND_CONST;
66 break;
67 case dwarf::DW_TAG_volatile_type:
68 Kind = BTF::BTF_KIND_VOLATILE;
69 break;
70 case dwarf::DW_TAG_typedef:
71 Kind = BTF::BTF_KIND_TYPEDEF;
72 break;
73 case dwarf::DW_TAG_restrict_type:
74 Kind = BTF::BTF_KIND_RESTRICT;
75 break;
76 default:
77 llvm_unreachable("Unknown DIDerivedType Tag");
78 }
79 BTFType.Info = Kind << 24;
80}
81
82/// Used by DW_TAG_pointer_type only.
83BTFTypeDerived::BTFTypeDerived(unsigned NextTypeId, unsigned Tag,
85 : DTy(nullptr), NeedsFixup(false), Name(Name) {
86 Kind = BTF::BTF_KIND_PTR;
87 BTFType.Info = Kind << 24;
88 BTFType.Type = NextTypeId;
89}
90
92 if (IsCompleted)
93 return;
94 IsCompleted = true;
95
96 BTFType.NameOff = BDebug.addString(Name);
97
98 if (NeedsFixup || !DTy)
99 return;
100
101 // The base type for PTR/CONST/VOLATILE could be void.
102 const DIType *ResolvedType = tryRemoveAtomicType(DTy->getBaseType());
103 if (!ResolvedType) {
104 assert((Kind == BTF::BTF_KIND_PTR || Kind == BTF::BTF_KIND_CONST ||
105 Kind == BTF::BTF_KIND_VOLATILE) &&
106 "Invalid null basetype");
107 BTFType.Type = 0;
108 } else {
109 BTFType.Type = BDebug.getTypeId(ResolvedType);
110 }
111}
112
114
116 BTFType.Type = PointeeType;
117}
118
119/// Represent a struct/union forward declaration.
121 Kind = BTF::BTF_KIND_FWD;
122 BTFType.Info = IsUnion << 31 | Kind << 24;
123 BTFType.Type = 0;
124}
125
127 if (IsCompleted)
128 return;
129 IsCompleted = true;
130
131 BTFType.NameOff = BDebug.addString(Name);
132}
133
135
137 uint32_t OffsetInBits, StringRef TypeName)
138 : Name(TypeName) {
139 // Translate IR int encoding to BTF int encoding.
140 uint8_t BTFEncoding;
141 switch (Encoding) {
142 case dwarf::DW_ATE_boolean:
143 BTFEncoding = BTF::INT_BOOL;
144 break;
145 case dwarf::DW_ATE_signed:
146 case dwarf::DW_ATE_signed_char:
147 BTFEncoding = BTF::INT_SIGNED;
148 break;
149 case dwarf::DW_ATE_unsigned:
150 case dwarf::DW_ATE_unsigned_char:
151 BTFEncoding = 0;
152 break;
153 default:
154 llvm_unreachable("Unknown BTFTypeInt Encoding");
155 }
156
157 Kind = BTF::BTF_KIND_INT;
158 BTFType.Info = Kind << 24;
159 BTFType.Size = roundupToBytes(SizeInBits);
160 IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits;
161}
162
164 if (IsCompleted)
165 return;
166 IsCompleted = true;
167
168 BTFType.NameOff = BDebug.addString(Name);
169}
170
173 OS.AddComment("0x" + Twine::utohexstr(IntVal));
174 OS.emitInt32(IntVal);
175}
176
178 bool IsSigned) : ETy(ETy) {
179 Kind = BTF::BTF_KIND_ENUM;
180 BTFType.Info = IsSigned << 31 | Kind << 24 | VLen;
182}
183
185 if (IsCompleted)
186 return;
187 IsCompleted = true;
188
189 BTFType.NameOff = BDebug.addString(ETy->getName());
190
191 DINodeArray Elements = ETy->getElements();
192 for (const auto Element : Elements) {
193 const auto *Enum = cast<DIEnumerator>(Element);
194
195 struct BTF::BTFEnum BTFEnum;
196 BTFEnum.NameOff = BDebug.addString(Enum->getName());
197 // BTF enum value is 32bit, enforce it.
199 if (Enum->isUnsigned())
200 Value = static_cast<uint32_t>(Enum->getValue().getZExtValue());
201 else
202 Value = static_cast<uint32_t>(Enum->getValue().getSExtValue());
203 BTFEnum.Val = Value;
204 EnumValues.push_back(BTFEnum);
205 }
206}
207
210 for (const auto &Enum : EnumValues) {
211 OS.emitInt32(Enum.NameOff);
212 OS.emitInt32(Enum.Val);
213 }
214}
215
217 bool IsSigned) : ETy(ETy) {
218 Kind = BTF::BTF_KIND_ENUM64;
219 BTFType.Info = IsSigned << 31 | Kind << 24 | VLen;
221}
222
224 if (IsCompleted)
225 return;
226 IsCompleted = true;
227
228 BTFType.NameOff = BDebug.addString(ETy->getName());
229
230 DINodeArray Elements = ETy->getElements();
231 for (const auto Element : Elements) {
232 const auto *Enum = cast<DIEnumerator>(Element);
233
234 struct BTF::BTFEnum64 BTFEnum;
235 BTFEnum.NameOff = BDebug.addString(Enum->getName());
237 if (Enum->isUnsigned())
238 Value = static_cast<uint64_t>(Enum->getValue().getZExtValue());
239 else
240 Value = static_cast<uint64_t>(Enum->getValue().getSExtValue());
241 BTFEnum.Val_Lo32 = Value;
242 BTFEnum.Val_Hi32 = Value >> 32;
243 EnumValues.push_back(BTFEnum);
244 }
245}
246
249 for (const auto &Enum : EnumValues) {
250 OS.emitInt32(Enum.NameOff);
251 OS.AddComment("0x" + Twine::utohexstr(Enum.Val_Lo32));
252 OS.emitInt32(Enum.Val_Lo32);
253 OS.AddComment("0x" + Twine::utohexstr(Enum.Val_Hi32));
254 OS.emitInt32(Enum.Val_Hi32);
255 }
256}
257
259 Kind = BTF::BTF_KIND_ARRAY;
260 BTFType.NameOff = 0;
261 BTFType.Info = Kind << 24;
262 BTFType.Size = 0;
263
264 ArrayInfo.ElemType = ElemTypeId;
265 ArrayInfo.Nelems = NumElems;
266}
267
268/// Represent a BTF array.
270 if (IsCompleted)
271 return;
272 IsCompleted = true;
273
274 // The IR does not really have a type for the index.
275 // A special type for array index should have been
276 // created during initial type traversal. Just
277 // retrieve that type id.
278 ArrayInfo.IndexType = BDebug.getArrayIndexTypeId();
279}
280
283 OS.emitInt32(ArrayInfo.ElemType);
284 OS.emitInt32(ArrayInfo.IndexType);
285 OS.emitInt32(ArrayInfo.Nelems);
286}
287
288/// Represent either a struct or a union.
290 bool HasBitField, uint32_t Vlen)
291 : STy(STy), HasBitField(HasBitField) {
292 Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
294 BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
295}
296
298 if (IsCompleted)
299 return;
300 IsCompleted = true;
301
302 BTFType.NameOff = BDebug.addString(STy->getName());
303
304 // Add struct/union members.
305 const DINodeArray Elements = STy->getElements();
306 for (const auto *Element : Elements) {
307 struct BTF::BTFMember BTFMember;
308 const auto *DDTy = cast<DIDerivedType>(Element);
309
310 BTFMember.NameOff = BDebug.addString(DDTy->getName());
311 if (HasBitField) {
312 uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0;
313 BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits();
314 } else {
315 BTFMember.Offset = DDTy->getOffsetInBits();
316 }
317 const auto *BaseTy = tryRemoveAtomicType(DDTy->getBaseType());
318 BTFMember.Type = BDebug.getTypeId(BaseTy);
319 Members.push_back(BTFMember);
320 }
321}
322
325 for (const auto &Member : Members) {
326 OS.emitInt32(Member.NameOff);
327 OS.emitInt32(Member.Type);
328 OS.AddComment("0x" + Twine::utohexstr(Member.Offset));
329 OS.emitInt32(Member.Offset);
330 }
331}
332
333std::string BTFTypeStruct::getName() { return std::string(STy->getName()); }
334
335/// The Func kind represents both subprogram and pointee of function
336/// pointers. If the FuncName is empty, it represents a pointee of function
337/// pointer. Otherwise, it represents a subprogram. The func arg names
338/// are empty for pointee of function pointer case, and are valid names
339/// for subprogram.
341 const DISubroutineType *STy, uint32_t VLen,
342 const std::unordered_map<uint32_t, StringRef> &FuncArgNames)
343 : STy(STy), FuncArgNames(FuncArgNames) {
344 Kind = BTF::BTF_KIND_FUNC_PROTO;
345 BTFType.Info = (Kind << 24) | VLen;
346}
347
349 if (IsCompleted)
350 return;
351 IsCompleted = true;
352
353 DITypeRefArray Elements = STy->getTypeArray();
354 auto RetType = tryRemoveAtomicType(Elements[0]);
355 BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
356 BTFType.NameOff = 0;
357
358 // For null parameter which is typically the last one
359 // to represent the vararg, encode the NameOff/Type to be 0.
360 for (unsigned I = 1, N = Elements.size(); I < N; ++I) {
361 struct BTF::BTFParam Param;
362 auto Element = tryRemoveAtomicType(Elements[I]);
363 if (Element) {
364 Param.NameOff = BDebug.addString(FuncArgNames[I]);
365 Param.Type = BDebug.getTypeId(Element);
366 } else {
367 Param.NameOff = 0;
368 Param.Type = 0;
369 }
370 Parameters.push_back(Param);
371 }
372}
373
376 for (const auto &Param : Parameters) {
377 OS.emitInt32(Param.NameOff);
378 OS.emitInt32(Param.Type);
379 }
380}
381
383 uint32_t Scope)
384 : Name(FuncName) {
385 Kind = BTF::BTF_KIND_FUNC;
386 BTFType.Info = (Kind << 24) | Scope;
387 BTFType.Type = ProtoTypeId;
388}
389
391 if (IsCompleted)
392 return;
393 IsCompleted = true;
394
395 BTFType.NameOff = BDebug.addString(Name);
396}
397
399
401 : Name(VarName) {
402 Kind = BTF::BTF_KIND_VAR;
403 BTFType.Info = Kind << 24;
404 BTFType.Type = TypeId;
405 Info = VarInfo;
406}
407
409 BTFType.NameOff = BDebug.addString(Name);
410}
411
414 OS.emitInt32(Info);
415}
416
417BTFKindDataSec::BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
418 : Asm(AsmPrt), Name(SecName) {
419 Kind = BTF::BTF_KIND_DATASEC;
420 BTFType.Info = Kind << 24;
421 BTFType.Size = 0;
422}
423
425 BTFType.NameOff = BDebug.addString(Name);
426 BTFType.Info |= Vars.size();
427}
428
431
432 for (const auto &V : Vars) {
433 OS.emitInt32(std::get<0>(V));
434 Asm->emitLabelReference(std::get<1>(V), 4);
435 OS.emitInt32(std::get<2>(V));
436 }
437}
438
440 : Name(TypeName) {
441 Kind = BTF::BTF_KIND_FLOAT;
442 BTFType.Info = Kind << 24;
443 BTFType.Size = roundupToBytes(SizeInBits);
444}
445
447 if (IsCompleted)
448 return;
449 IsCompleted = true;
450
451 BTFType.NameOff = BDebug.addString(Name);
452}
453
454BTFTypeDeclTag::BTFTypeDeclTag(uint32_t BaseTypeId, int ComponentIdx,
456 : Tag(Tag) {
457 Kind = BTF::BTF_KIND_DECL_TAG;
458 BTFType.Info = Kind << 24;
459 BTFType.Type = BaseTypeId;
460 Info = ComponentIdx;
461}
462
464 if (IsCompleted)
465 return;
466 IsCompleted = true;
467
468 BTFType.NameOff = BDebug.addString(Tag);
469}
470
473 OS.emitInt32(Info);
474}
475
477 : DTy(nullptr), Tag(Tag) {
478 Kind = BTF::BTF_KIND_TYPE_TAG;
479 BTFType.Info = Kind << 24;
480 BTFType.Type = NextTypeId;
481}
482
484 : DTy(DTy), Tag(Tag) {
485 Kind = BTF::BTF_KIND_TYPE_TAG;
486 BTFType.Info = Kind << 24;
487}
488
490 if (IsCompleted)
491 return;
492 IsCompleted = true;
493 BTFType.NameOff = BDebug.addString(Tag);
494 if (DTy) {
495 const DIType *ResolvedType = tryRemoveAtomicType(DTy->getBaseType());
496 if (!ResolvedType)
497 BTFType.Type = 0;
498 else
499 BTFType.Type = BDebug.getTypeId(ResolvedType);
500 }
501}
502
504 // Check whether the string already exists.
505 for (auto &OffsetM : OffsetToIdMap) {
506 if (Table[OffsetM.second] == S)
507 return OffsetM.first;
508 }
509 // Not find, add to the string table.
511 OffsetToIdMap[Offset] = Table.size();
512 Table.push_back(std::string(S));
513 Size += S.size() + 1;
514 return Offset;
515}
516
518 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
519 LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
520 MapDefNotCollected(true) {
521 addString("\0");
522}
523
524uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
525 const DIType *Ty) {
526 TypeEntry->setId(TypeEntries.size() + 1);
527 uint32_t Id = TypeEntry->getId();
528 DIToIdMap[Ty] = Id;
529 TypeEntries.push_back(std::move(TypeEntry));
530 return Id;
531}
532
533uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
534 TypeEntry->setId(TypeEntries.size() + 1);
535 uint32_t Id = TypeEntry->getId();
536 TypeEntries.push_back(std::move(TypeEntry));
537 return Id;
538}
539
540void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
541 // Only int and binary floating point types are supported in BTF.
542 uint32_t Encoding = BTy->getEncoding();
543 std::unique_ptr<BTFTypeBase> TypeEntry;
544 switch (Encoding) {
545 case dwarf::DW_ATE_boolean:
546 case dwarf::DW_ATE_signed:
547 case dwarf::DW_ATE_signed_char:
548 case dwarf::DW_ATE_unsigned:
549 case dwarf::DW_ATE_unsigned_char:
550 // Create a BTF type instance for this DIBasicType and put it into
551 // DIToIdMap for cross-type reference check.
552 TypeEntry = std::make_unique<BTFTypeInt>(
553 Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
554 break;
555 case dwarf::DW_ATE_float:
556 TypeEntry =
557 std::make_unique<BTFTypeFloat>(BTy->getSizeInBits(), BTy->getName());
558 break;
559 default:
560 return;
561 }
562
563 TypeId = addType(std::move(TypeEntry), BTy);
564}
565
566/// Handle subprogram or subroutine types.
567void BTFDebug::visitSubroutineType(
568 const DISubroutineType *STy, bool ForSubprog,
569 const std::unordered_map<uint32_t, StringRef> &FuncArgNames,
570 uint32_t &TypeId) {
572 uint32_t VLen = Elements.size() - 1;
573 if (VLen > BTF::MAX_VLEN)
574 return;
575
576 // Subprogram has a valid non-zero-length name, and the pointee of
577 // a function pointer has an empty name. The subprogram type will
578 // not be added to DIToIdMap as it should not be referenced by
579 // any other types.
580 auto TypeEntry = std::make_unique<BTFTypeFuncProto>(STy, VLen, FuncArgNames);
581 if (ForSubprog)
582 TypeId = addType(std::move(TypeEntry)); // For subprogram
583 else
584 TypeId = addType(std::move(TypeEntry), STy); // For func ptr
585
586 // Visit return type and func arg types.
587 for (const auto Element : Elements) {
588 visitTypeEntry(Element);
589 }
590}
591
592void BTFDebug::processDeclAnnotations(DINodeArray Annotations,
593 uint32_t BaseTypeId,
594 int ComponentIdx) {
595 if (!Annotations)
596 return;
597
598 for (const Metadata *Annotation : Annotations->operands()) {
599 const MDNode *MD = cast<MDNode>(Annotation);
600 const MDString *Name = cast<MDString>(MD->getOperand(0));
601 if (Name->getString() != "btf_decl_tag")
602 continue;
603
604 const MDString *Value = cast<MDString>(MD->getOperand(1));
605 auto TypeEntry = std::make_unique<BTFTypeDeclTag>(BaseTypeId, ComponentIdx,
606 Value->getString());
607 addType(std::move(TypeEntry));
608 }
609}
610
611uint32_t BTFDebug::processDISubprogram(const DISubprogram *SP,
612 uint32_t ProtoTypeId, uint8_t Scope) {
613 auto FuncTypeEntry =
614 std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
615 uint32_t FuncId = addType(std::move(FuncTypeEntry));
616
617 // Process argument annotations.
618 for (const DINode *DN : SP->getRetainedNodes()) {
619 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
620 uint32_t Arg = DV->getArg();
621 if (Arg)
622 processDeclAnnotations(DV->getAnnotations(), FuncId, Arg - 1);
623 }
624 }
625 processDeclAnnotations(SP->getAnnotations(), FuncId, -1);
626
627 return FuncId;
628}
629
630/// Generate btf_type_tag chains.
631int BTFDebug::genBTFTypeTags(const DIDerivedType *DTy, int BaseTypeId) {
633 DINodeArray Annots = DTy->getAnnotations();
634 if (Annots) {
635 // For type with "int __tag1 __tag2 *p", the MDStrs will have
636 // content: [__tag1, __tag2].
637 for (const Metadata *Annotations : Annots->operands()) {
638 const MDNode *MD = cast<MDNode>(Annotations);
639 const MDString *Name = cast<MDString>(MD->getOperand(0));
640 if (Name->getString() != "btf_type_tag")
641 continue;
642 MDStrs.push_back(cast<MDString>(MD->getOperand(1)));
643 }
644 }
645
646 if (MDStrs.size() == 0)
647 return -1;
648
649 // With MDStrs [__tag1, __tag2], the output type chain looks like
650 // PTR -> __tag2 -> __tag1 -> BaseType
651 // In the below, we construct BTF types with the order of __tag1, __tag2
652 // and PTR.
653 unsigned TmpTypeId;
654 std::unique_ptr<BTFTypeTypeTag> TypeEntry;
655 if (BaseTypeId >= 0)
656 TypeEntry =
657 std::make_unique<BTFTypeTypeTag>(BaseTypeId, MDStrs[0]->getString());
658 else
659 TypeEntry = std::make_unique<BTFTypeTypeTag>(DTy, MDStrs[0]->getString());
660 TmpTypeId = addType(std::move(TypeEntry));
661
662 for (unsigned I = 1; I < MDStrs.size(); I++) {
663 const MDString *Value = MDStrs[I];
664 TypeEntry = std::make_unique<BTFTypeTypeTag>(TmpTypeId, Value->getString());
665 TmpTypeId = addType(std::move(TypeEntry));
666 }
667 return TmpTypeId;
668}
669
670/// Handle structure/union types.
671void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
672 uint32_t &TypeId) {
673 const DINodeArray Elements = CTy->getElements();
674 uint32_t VLen = Elements.size();
675 if (VLen > BTF::MAX_VLEN)
676 return;
677
678 // Check whether we have any bitfield members or not
679 bool HasBitField = false;
680 for (const auto *Element : Elements) {
681 auto E = cast<DIDerivedType>(Element);
682 if (E->isBitField()) {
683 HasBitField = true;
684 break;
685 }
686 }
687
688 auto TypeEntry =
689 std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
690 StructTypes.push_back(TypeEntry.get());
691 TypeId = addType(std::move(TypeEntry), CTy);
692
693 // Check struct/union annotations
694 processDeclAnnotations(CTy->getAnnotations(), TypeId, -1);
695
696 // Visit all struct members.
697 int FieldNo = 0;
698 for (const auto *Element : Elements) {
699 const auto Elem = cast<DIDerivedType>(Element);
700 visitTypeEntry(Elem);
701 processDeclAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
702 FieldNo++;
703 }
704}
705
706void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
707 // Visit array element type.
708 uint32_t ElemTypeId;
709 const DIType *ElemType = CTy->getBaseType();
710 visitTypeEntry(ElemType, ElemTypeId, false, false);
711
712 // Visit array dimensions.
713 DINodeArray Elements = CTy->getElements();
714 for (int I = Elements.size() - 1; I >= 0; --I) {
715 if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
716 if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
717 const DISubrange *SR = cast<DISubrange>(Element);
718 auto *CI = dyn_cast<ConstantInt *>(SR->getCount());
719 int64_t Count = CI->getSExtValue();
720
721 // For struct s { int b; char c[]; }, the c[] will be represented
722 // as an array with Count = -1.
723 auto TypeEntry =
724 std::make_unique<BTFTypeArray>(ElemTypeId,
725 Count >= 0 ? Count : 0);
726 if (I == 0)
727 ElemTypeId = addType(std::move(TypeEntry), CTy);
728 else
729 ElemTypeId = addType(std::move(TypeEntry));
730 }
731 }
732
733 // The array TypeId is the type id of the outermost dimension.
734 TypeId = ElemTypeId;
735
736 // The IR does not have a type for array index while BTF wants one.
737 // So create an array index type if there is none.
738 if (!ArrayIndexTypeId) {
739 auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
740 0, "__ARRAY_SIZE_TYPE__");
741 ArrayIndexTypeId = addType(std::move(TypeEntry));
742 }
743}
744
745void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
746 DINodeArray Elements = CTy->getElements();
747 uint32_t VLen = Elements.size();
748 if (VLen > BTF::MAX_VLEN)
749 return;
750
751 bool IsSigned = false;
752 unsigned NumBits = 32;
753 // No BaseType implies forward declaration in which case a
754 // BTFTypeEnum with Vlen = 0 is emitted.
755 if (CTy->getBaseType() != nullptr) {
756 const auto *BTy = cast<DIBasicType>(CTy->getBaseType());
757 IsSigned = BTy->getEncoding() == dwarf::DW_ATE_signed ||
758 BTy->getEncoding() == dwarf::DW_ATE_signed_char;
759 NumBits = BTy->getSizeInBits();
760 }
761
762 if (NumBits <= 32) {
763 auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen, IsSigned);
764 TypeId = addType(std::move(TypeEntry), CTy);
765 } else {
766 assert(NumBits == 64);
767 auto TypeEntry = std::make_unique<BTFTypeEnum64>(CTy, VLen, IsSigned);
768 TypeId = addType(std::move(TypeEntry), CTy);
769 }
770 // No need to visit base type as BTF does not encode it.
771}
772
773/// Handle structure/union forward declarations.
774void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
775 uint32_t &TypeId) {
776 auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
777 TypeId = addType(std::move(TypeEntry), CTy);
778}
779
780/// Handle structure, union, array and enumeration types.
781void BTFDebug::visitCompositeType(const DICompositeType *CTy,
782 uint32_t &TypeId) {
783 auto Tag = CTy->getTag();
784 if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
785 // Handle forward declaration differently as it does not have members.
786 if (CTy->isForwardDecl())
787 visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
788 else
789 visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
790 } else if (Tag == dwarf::DW_TAG_array_type)
791 visitArrayType(CTy, TypeId);
792 else if (Tag == dwarf::DW_TAG_enumeration_type)
793 visitEnumType(CTy, TypeId);
794}
795
796bool BTFDebug::IsForwardDeclCandidate(const DIType *Base) {
797 if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
798 auto CTag = CTy->getTag();
799 if ((CTag == dwarf::DW_TAG_structure_type ||
800 CTag == dwarf::DW_TAG_union_type) &&
801 !CTy->getName().empty() && !CTy->isForwardDecl())
802 return true;
803 }
804 return false;
805}
806
807/// Handle pointer, typedef, const, volatile, restrict and member types.
808void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
809 bool CheckPointer, bool SeenPointer) {
810 unsigned Tag = DTy->getTag();
811
812 if (Tag == dwarf::DW_TAG_atomic_type)
813 return visitTypeEntry(DTy->getBaseType(), TypeId, CheckPointer,
814 SeenPointer);
815
816 /// Try to avoid chasing pointees, esp. structure pointees which may
817 /// unnecessary bring in a lot of types.
818 if (CheckPointer && !SeenPointer) {
819 SeenPointer = Tag == dwarf::DW_TAG_pointer_type && !DTy->getAnnotations();
820 }
821
822 if (CheckPointer && SeenPointer) {
823 const DIType *Base = DTy->getBaseType();
824 if (Base) {
825 if (IsForwardDeclCandidate(Base)) {
826 /// Find a candidate, generate a fixup. Later on the struct/union
827 /// pointee type will be replaced with either a real type or
828 /// a forward declaration.
829 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
830 auto &Fixup = FixupDerivedTypes[cast<DICompositeType>(Base)];
831 Fixup.push_back(std::make_pair(DTy, TypeEntry.get()));
832 TypeId = addType(std::move(TypeEntry), DTy);
833 return;
834 }
835 }
836 }
837
838 if (Tag == dwarf::DW_TAG_pointer_type) {
839 int TmpTypeId = genBTFTypeTags(DTy, -1);
840 if (TmpTypeId >= 0) {
841 auto TypeDEntry =
842 std::make_unique<BTFTypeDerived>(TmpTypeId, Tag, DTy->getName());
843 TypeId = addType(std::move(TypeDEntry), DTy);
844 } else {
845 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
846 TypeId = addType(std::move(TypeEntry), DTy);
847 }
848 } else if (Tag == dwarf::DW_TAG_typedef || Tag == dwarf::DW_TAG_const_type ||
849 Tag == dwarf::DW_TAG_volatile_type ||
850 Tag == dwarf::DW_TAG_restrict_type) {
851 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
852 TypeId = addType(std::move(TypeEntry), DTy);
853 if (Tag == dwarf::DW_TAG_typedef)
854 processDeclAnnotations(DTy->getAnnotations(), TypeId, -1);
855 } else if (Tag != dwarf::DW_TAG_member) {
856 return;
857 }
858
859 // Visit base type of pointer, typedef, const, volatile, restrict or
860 // struct/union member.
861 uint32_t TempTypeId = 0;
862 if (Tag == dwarf::DW_TAG_member)
863 visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
864 else
865 visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
866}
867
868/// Visit a type entry. CheckPointer is true if the type has
869/// one of its predecessors as one struct/union member. SeenPointer
870/// is true if CheckPointer is true and one of its predecessors
871/// is a pointer. The goal of CheckPointer and SeenPointer is to
872/// do pruning for struct/union types so some of these types
873/// will not be emitted in BTF and rather forward declarations
874/// will be generated.
875void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
876 bool CheckPointer, bool SeenPointer) {
877 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
878 TypeId = DIToIdMap[Ty];
879
880 // To handle the case like the following:
881 // struct t;
882 // typedef struct t _t;
883 // struct s1 { _t *c; };
884 // int test1(struct s1 *arg) { ... }
885 //
886 // struct t { int a; int b; };
887 // struct s2 { _t c; }
888 // int test2(struct s2 *arg) { ... }
889 //
890 // During traversing test1() argument, "_t" is recorded
891 // in DIToIdMap and a forward declaration fixup is created
892 // for "struct t" to avoid pointee type traversal.
893 //
894 // During traversing test2() argument, even if we see "_t" is
895 // already defined, we should keep moving to eventually
896 // bring in types for "struct t". Otherwise, the "struct s2"
897 // definition won't be correct.
898 //
899 // In the above, we have following debuginfo:
900 // {ptr, struct_member} -> typedef -> struct
901 // and BTF type for 'typedef' is generated while 'struct' may
902 // be in FixUp. But let us generalize the above to handle
903 // {different types} -> [various derived types]+ -> another type.
904 // For example,
905 // {func_param, struct_member} -> const -> ptr -> volatile -> struct
906 // We will traverse const/ptr/volatile which already have corresponding
907 // BTF types and generate type for 'struct' which might be in Fixup
908 // state.
909 if (Ty && (!CheckPointer || !SeenPointer)) {
910 if (const auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
911 while (DTy) {
912 const DIType *BaseTy = DTy->getBaseType();
913 if (!BaseTy)
914 break;
915
916 if (DIToIdMap.find(BaseTy) != DIToIdMap.end()) {
917 DTy = dyn_cast<DIDerivedType>(BaseTy);
918 } else {
919 if (CheckPointer && DTy->getTag() == dwarf::DW_TAG_pointer_type &&
920 !DTy->getAnnotations()) {
921 SeenPointer = true;
922 if (IsForwardDeclCandidate(BaseTy))
923 break;
924 }
925 uint32_t TmpTypeId;
926 visitTypeEntry(BaseTy, TmpTypeId, CheckPointer, SeenPointer);
927 break;
928 }
929 }
930 }
931 }
932
933 return;
934 }
935
936 if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
937 visitBasicType(BTy, TypeId);
938 else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
939 visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(),
940 TypeId);
941 else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
942 visitCompositeType(CTy, TypeId);
943 else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
944 visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
945 else
946 llvm_unreachable("Unknown DIType");
947}
948
949void BTFDebug::visitTypeEntry(const DIType *Ty) {
950 uint32_t TypeId;
951 visitTypeEntry(Ty, TypeId, false, false);
952}
953
954void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
955 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
956 TypeId = DIToIdMap[Ty];
957 return;
958 }
959
960 uint32_t TmpId;
961 switch (Ty->getTag()) {
962 case dwarf::DW_TAG_typedef:
963 case dwarf::DW_TAG_const_type:
964 case dwarf::DW_TAG_volatile_type:
965 case dwarf::DW_TAG_restrict_type:
966 case dwarf::DW_TAG_pointer_type:
967 visitMapDefType(dyn_cast<DIDerivedType>(Ty)->getBaseType(), TmpId);
968 break;
969 case dwarf::DW_TAG_array_type:
970 // Visit nested map array and jump to the element type
971 visitMapDefType(dyn_cast<DICompositeType>(Ty)->getBaseType(), TmpId);
972 break;
973 case dwarf::DW_TAG_structure_type: {
974 // Visit all struct members to ensure their types are visited.
975 const auto *CTy = cast<DICompositeType>(Ty);
976 const DINodeArray Elements = CTy->getElements();
977 for (const auto *Element : Elements) {
978 const auto *MemberType = cast<DIDerivedType>(Element);
979 const DIType *MemberBaseType = MemberType->getBaseType();
980 // If the member is a composite type, that may indicate the currently
981 // visited composite type is a wrapper, and the member represents the
982 // actual map definition.
983 // In that case, visit the member with `visitMapDefType` instead of
984 // `visitTypeEntry`, treating it specifically as a map definition rather
985 // than as a regular composite type.
986 const auto *MemberCTy = dyn_cast<DICompositeType>(MemberBaseType);
987 if (MemberCTy) {
988 visitMapDefType(MemberBaseType, TmpId);
989 } else {
990 visitTypeEntry(MemberBaseType);
991 }
992 }
993 break;
994 }
995 default:
996 break;
997 }
998
999 // Visit this type, struct or a const/typedef/volatile/restrict type
1000 visitTypeEntry(Ty, TypeId, false, false);
1001}
1002
1003/// Read file contents from the actual file or from the source
1004std::string BTFDebug::populateFileContent(const DIFile *File) {
1005 std::string FileName;
1006
1007 if (!File->getFilename().starts_with("/") && File->getDirectory().size())
1008 FileName = File->getDirectory().str() + "/" + File->getFilename().str();
1009 else
1010 FileName = std::string(File->getFilename());
1011
1012 // No need to populate the contends if it has been populated!
1013 if (FileContent.contains(FileName))
1014 return FileName;
1015
1016 std::vector<std::string> Content;
1017 std::string Line;
1018 Content.push_back(Line); // Line 0 for empty string
1019
1020 std::unique_ptr<MemoryBuffer> Buf;
1021 auto Source = File->getSource();
1022 if (Source)
1023 Buf = MemoryBuffer::getMemBufferCopy(*Source);
1024 else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
1025 MemoryBuffer::getFile(FileName))
1026 Buf = std::move(*BufOrErr);
1027 if (Buf)
1028 for (line_iterator I(*Buf, false), E; I != E; ++I)
1029 Content.push_back(std::string(*I));
1030
1031 FileContent[FileName] = Content;
1032 return FileName;
1033}
1034
1035void BTFDebug::constructLineInfo(MCSymbol *Label, const DIFile *File,
1036 uint32_t Line, uint32_t Column) {
1037 std::string FileName = populateFileContent(File);
1038 BTFLineInfo LineInfo;
1039
1040 LineInfo.Label = Label;
1041 LineInfo.FileNameOff = addString(FileName);
1042 // If file content is not available, let LineOff = 0.
1043 const auto &Content = FileContent[FileName];
1044 if (Line < Content.size())
1045 LineInfo.LineOff = addString(Content[Line]);
1046 else
1047 LineInfo.LineOff = 0;
1048 LineInfo.LineNum = Line;
1049 LineInfo.ColumnNum = Column;
1050 LineInfoTable[SecNameOff].push_back(LineInfo);
1051}
1052
1053void BTFDebug::emitCommonHeader() {
1054 OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC));
1055 OS.emitIntValue(BTF::MAGIC, 2);
1056 OS.emitInt8(BTF::VERSION);
1057 OS.emitInt8(0);
1058}
1059
1060void BTFDebug::emitBTFSection() {
1061 // Do not emit section if no types and only "" string.
1062 if (!TypeEntries.size() && StringTable.getSize() == 1)
1063 return;
1064
1065 MCContext &Ctx = OS.getContext();
1066 MCSectionELF *Sec = Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0);
1067 Sec->setAlignment(Align(4));
1068 OS.switchSection(Sec);
1069
1070 // Emit header.
1071 emitCommonHeader();
1072 OS.emitInt32(BTF::HeaderSize);
1073
1074 uint32_t TypeLen = 0, StrLen;
1075 for (const auto &TypeEntry : TypeEntries)
1076 TypeLen += TypeEntry->getSize();
1077 StrLen = StringTable.getSize();
1078
1079 OS.emitInt32(0);
1080 OS.emitInt32(TypeLen);
1081 OS.emitInt32(TypeLen);
1082 OS.emitInt32(StrLen);
1083
1084 // Emit type table.
1085 for (const auto &TypeEntry : TypeEntries)
1086 TypeEntry->emitType(OS);
1087
1088 // Emit string table.
1089 uint32_t StringOffset = 0;
1090 for (const auto &S : StringTable.getTable()) {
1091 OS.AddComment("string offset=" + std::to_string(StringOffset));
1092 OS.emitBytes(S);
1093 OS.emitBytes(StringRef("\0", 1));
1094 StringOffset += S.size() + 1;
1095 }
1096}
1097
1098void BTFDebug::emitBTFExtSection() {
1099 // Do not emit section if empty FuncInfoTable and LineInfoTable
1100 // and FieldRelocTable.
1101 if (!FuncInfoTable.size() && !LineInfoTable.size() &&
1102 !FieldRelocTable.size())
1103 return;
1104
1105 MCContext &Ctx = OS.getContext();
1106 MCSectionELF *Sec = Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0);
1107 Sec->setAlignment(Align(4));
1108 OS.switchSection(Sec);
1109
1110 // Emit header.
1111 emitCommonHeader();
1112 OS.emitInt32(BTF::ExtHeaderSize);
1113
1114 // Account for FuncInfo/LineInfo record size as well.
1115 uint32_t FuncLen = 4, LineLen = 4;
1116 // Do not account for optional FieldReloc.
1117 uint32_t FieldRelocLen = 0;
1118 for (const auto &FuncSec : FuncInfoTable) {
1119 FuncLen += BTF::SecFuncInfoSize;
1120 FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
1121 }
1122 for (const auto &LineSec : LineInfoTable) {
1123 LineLen += BTF::SecLineInfoSize;
1124 LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
1125 }
1126 for (const auto &FieldRelocSec : FieldRelocTable) {
1127 FieldRelocLen += BTF::SecFieldRelocSize;
1128 FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
1129 }
1130
1131 if (FieldRelocLen)
1132 FieldRelocLen += 4;
1133
1134 OS.emitInt32(0);
1135 OS.emitInt32(FuncLen);
1136 OS.emitInt32(FuncLen);
1137 OS.emitInt32(LineLen);
1138 OS.emitInt32(FuncLen + LineLen);
1139 OS.emitInt32(FieldRelocLen);
1140
1141 // Emit func_info table.
1142 OS.AddComment("FuncInfo");
1143 OS.emitInt32(BTF::BPFFuncInfoSize);
1144 for (const auto &FuncSec : FuncInfoTable) {
1145 OS.AddComment("FuncInfo section string offset=" +
1146 std::to_string(FuncSec.first));
1147 OS.emitInt32(FuncSec.first);
1148 OS.emitInt32(FuncSec.second.size());
1149 for (const auto &FuncInfo : FuncSec.second) {
1150 Asm->emitLabelReference(FuncInfo.Label, 4);
1151 OS.emitInt32(FuncInfo.TypeId);
1152 }
1153 }
1154
1155 // Emit line_info table.
1156 OS.AddComment("LineInfo");
1157 OS.emitInt32(BTF::BPFLineInfoSize);
1158 for (const auto &LineSec : LineInfoTable) {
1159 OS.AddComment("LineInfo section string offset=" +
1160 std::to_string(LineSec.first));
1161 OS.emitInt32(LineSec.first);
1162 OS.emitInt32(LineSec.second.size());
1163 for (const auto &LineInfo : LineSec.second) {
1164 Asm->emitLabelReference(LineInfo.Label, 4);
1165 OS.emitInt32(LineInfo.FileNameOff);
1166 OS.emitInt32(LineInfo.LineOff);
1167 OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
1168 std::to_string(LineInfo.ColumnNum));
1169 OS.emitInt32(LineInfo.LineNum << 10 | LineInfo.ColumnNum);
1170 }
1171 }
1172
1173 // Emit field reloc table.
1174 if (FieldRelocLen) {
1175 OS.AddComment("FieldReloc");
1176 OS.emitInt32(BTF::BPFFieldRelocSize);
1177 for (const auto &FieldRelocSec : FieldRelocTable) {
1178 OS.AddComment("Field reloc section string offset=" +
1179 std::to_string(FieldRelocSec.first));
1180 OS.emitInt32(FieldRelocSec.first);
1181 OS.emitInt32(FieldRelocSec.second.size());
1182 for (const auto &FieldRelocInfo : FieldRelocSec.second) {
1183 Asm->emitLabelReference(FieldRelocInfo.Label, 4);
1184 OS.emitInt32(FieldRelocInfo.TypeID);
1185 OS.emitInt32(FieldRelocInfo.OffsetNameOff);
1186 OS.emitInt32(FieldRelocInfo.RelocKind);
1187 }
1188 }
1189 }
1190}
1191
1193 auto *SP = MF->getFunction().getSubprogram();
1194 auto *Unit = SP->getUnit();
1195
1196 if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
1197 SkipInstruction = true;
1198 return;
1199 }
1200 SkipInstruction = false;
1201
1202 // Collect MapDef types. Map definition needs to collect
1203 // pointee types. Do it first. Otherwise, for the following
1204 // case:
1205 // struct m { ...};
1206 // struct t {
1207 // struct m *key;
1208 // };
1209 // foo(struct t *arg);
1210 //
1211 // struct mapdef {
1212 // ...
1213 // struct m *key;
1214 // ...
1215 // } __attribute__((section(".maps"))) hash_map;
1216 //
1217 // If subroutine foo is traversed first, a type chain
1218 // "ptr->struct m(fwd)" will be created and later on
1219 // when traversing mapdef, since "ptr->struct m" exists,
1220 // the traversal of "struct m" will be omitted.
1221 if (MapDefNotCollected) {
1222 processGlobals(true);
1223 MapDefNotCollected = false;
1224 }
1225
1226 // Collect all types locally referenced in this function.
1227 // Use RetainedNodes so we can collect all argument names
1228 // even if the argument is not used.
1229 std::unordered_map<uint32_t, StringRef> FuncArgNames;
1230 for (const DINode *DN : SP->getRetainedNodes()) {
1231 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1232 // Collect function arguments for subprogram func type.
1233 uint32_t Arg = DV->getArg();
1234 if (Arg) {
1235 visitTypeEntry(DV->getType());
1236 FuncArgNames[Arg] = DV->getName();
1237 }
1238 }
1239 }
1240
1241 // Construct subprogram func proto type.
1242 uint32_t ProtoTypeId;
1243 visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
1244
1245 // Construct subprogram func type
1246 uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
1247 uint32_t FuncTypeId = processDISubprogram(SP, ProtoTypeId, Scope);
1248
1249 for (const auto &TypeEntry : TypeEntries)
1250 TypeEntry->completeType(*this);
1251
1252 // Construct funcinfo and the first lineinfo for the function.
1253 MCSymbol *FuncLabel = Asm->getFunctionBegin();
1254 BTFFuncInfo FuncInfo;
1255 FuncInfo.Label = FuncLabel;
1256 FuncInfo.TypeId = FuncTypeId;
1257 if (FuncLabel->isInSection()) {
1258 auto &Sec = static_cast<const MCSectionELF &>(FuncLabel->getSection());
1259 SecNameOff = addString(Sec.getName());
1260 } else {
1261 SecNameOff = addString(".text");
1262 }
1263 FuncInfoTable[SecNameOff].push_back(FuncInfo);
1264}
1265
1267 SkipInstruction = false;
1268 LineInfoGenerated = false;
1269 SecNameOff = 0;
1270}
1271
1272/// On-demand populate types as requested from abstract member
1273/// accessing or preserve debuginfo type.
1274unsigned BTFDebug::populateType(const DIType *Ty) {
1275 unsigned Id;
1276 visitTypeEntry(Ty, Id, false, false);
1277 for (const auto &TypeEntry : TypeEntries)
1278 TypeEntry->completeType(*this);
1279 return Id;
1280}
1281
1282/// Generate a struct member field relocation.
1283void BTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
1284 const GlobalVariable *GVar, bool IsAma) {
1285 BTFFieldReloc FieldReloc;
1286 FieldReloc.Label = ORSym;
1287 FieldReloc.TypeID = RootId;
1288
1289 StringRef AccessPattern = GVar->getName();
1290 size_t FirstDollar = AccessPattern.find_first_of('$');
1291 if (IsAma) {
1292 size_t FirstColon = AccessPattern.find_first_of(':');
1293 size_t SecondColon = AccessPattern.find_first_of(':', FirstColon + 1);
1294 StringRef IndexPattern = AccessPattern.substr(FirstDollar + 1);
1295 StringRef RelocKindStr = AccessPattern.substr(FirstColon + 1,
1296 SecondColon - FirstColon);
1297 StringRef PatchImmStr = AccessPattern.substr(SecondColon + 1,
1298 FirstDollar - SecondColon);
1299
1300 FieldReloc.OffsetNameOff = addString(IndexPattern);
1301 FieldReloc.RelocKind = std::stoull(std::string(RelocKindStr));
1302 PatchImms[GVar] = std::make_pair(std::stoll(std::string(PatchImmStr)),
1303 FieldReloc.RelocKind);
1304 } else {
1305 StringRef RelocStr = AccessPattern.substr(FirstDollar + 1);
1306 FieldReloc.OffsetNameOff = addString("0");
1307 FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
1308 PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
1309 }
1310 FieldRelocTable[SecNameOff].push_back(FieldReloc);
1311}
1312
1313void BTFDebug::processGlobalValue(const MachineOperand &MO) {
1314 // check whether this is a candidate or not
1315 if (MO.isGlobal()) {
1316 const GlobalValue *GVal = MO.getGlobal();
1317 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1318 if (!GVar) {
1319 // Not a global variable. Maybe an extern function reference.
1320 processFuncPrototypes(dyn_cast<Function>(GVal));
1321 return;
1322 }
1323
1326 return;
1327
1328 MCSymbol *ORSym = OS.getContext().createTempSymbol();
1329 OS.emitLabel(ORSym);
1330
1331 MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
1332 uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
1333 generatePatchImmReloc(ORSym, RootId, GVar,
1335 }
1336}
1337
1340
1341 if (SkipInstruction || MI->isMetaInstruction() ||
1342 MI->getFlag(MachineInstr::FrameSetup))
1343 return;
1344
1345 if (MI->isInlineAsm()) {
1346 // Count the number of register definitions to find the asm string.
1347 unsigned NumDefs = 0;
1348 while (true) {
1349 const MachineOperand &MO = MI->getOperand(NumDefs);
1350 if (MO.isReg() && MO.isDef()) {
1351 ++NumDefs;
1352 continue;
1353 }
1354 // Skip this inline asm instruction if the asmstr is empty.
1355 const char *AsmStr = MO.getSymbolName();
1356 if (AsmStr[0] == 0)
1357 return;
1358 break;
1359 }
1360 }
1361
1362 if (MI->getOpcode() == BPF::LD_imm64) {
1363 // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
1364 // add this insn into the .BTF.ext FieldReloc subsection.
1365 // Relocation looks like:
1366 // . SecName:
1367 // . InstOffset
1368 // . TypeID
1369 // . OffSetNameOff
1370 // . RelocType
1371 // Later, the insn is replaced with "r2 = <offset>"
1372 // where "<offset>" equals to the offset based on current
1373 // type definitions.
1374 //
1375 // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
1376 // The LD_imm64 result will be replaced with a btf type id.
1377 processGlobalValue(MI->getOperand(1));
1378 } else if (MI->getOpcode() == BPF::CORE_LD64 ||
1379 MI->getOpcode() == BPF::CORE_LD32 ||
1380 MI->getOpcode() == BPF::CORE_ST ||
1381 MI->getOpcode() == BPF::CORE_SHIFT) {
1382 // relocation insn is a load, store or shift insn.
1383 processGlobalValue(MI->getOperand(3));
1384 } else if (MI->getOpcode() == BPF::JAL) {
1385 // check extern function references
1386 const MachineOperand &MO = MI->getOperand(0);
1387 if (MO.isGlobal()) {
1388 processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
1389 }
1390 }
1391
1392 if (!CurMI) // no debug info
1393 return;
1394
1395 // Skip this instruction if no DebugLoc, the DebugLoc
1396 // is the same as the previous instruction or Line is 0.
1397 const DebugLoc &DL = MI->getDebugLoc();
1398 if (!DL || PrevInstLoc == DL || DL.getLine() == 0) {
1399 // This instruction will be skipped, no LineInfo has
1400 // been generated, construct one based on function signature.
1401 if (LineInfoGenerated == false) {
1402 auto *S = MI->getMF()->getFunction().getSubprogram();
1403 if (!S)
1404 return;
1405 MCSymbol *FuncLabel = Asm->getFunctionBegin();
1406 constructLineInfo(FuncLabel, S->getFile(), S->getLine(), 0);
1407 LineInfoGenerated = true;
1408 }
1409
1410 return;
1411 }
1412
1413 // Create a temporary label to remember the insn for lineinfo.
1414 MCSymbol *LineSym = OS.getContext().createTempSymbol();
1415 OS.emitLabel(LineSym);
1416
1417 // Construct the lineinfo.
1418 constructLineInfo(LineSym, DL->getFile(), DL.getLine(), DL.getCol());
1419
1420 LineInfoGenerated = true;
1421 PrevInstLoc = DL;
1422}
1423
1424void BTFDebug::processGlobals(bool ProcessingMapDef) {
1425 // Collect all types referenced by globals.
1426 const Module *M = MMI->getModule();
1427 for (const GlobalVariable &Global : M->globals()) {
1428 // Decide the section name.
1429 StringRef SecName;
1430 std::optional<SectionKind> GVKind;
1431
1432 if (!Global.isDeclarationForLinker())
1434
1435 if (Global.isDeclarationForLinker())
1436 SecName = Global.hasSection() ? Global.getSection() : "";
1437 else if (GVKind->isCommon())
1438 SecName = ".bss";
1439 else {
1441 MCSection *Sec = TLOF->SectionForGlobal(&Global, Asm->TM);
1442 SecName = Sec->getName();
1443 }
1444
1445 if (ProcessingMapDef != SecName.starts_with(".maps"))
1446 continue;
1447
1448 // Create a .rodata datasec if the global variable is an initialized
1449 // constant with private linkage and if it won't be in .rodata.str<#>
1450 // and .rodata.cst<#> sections.
1451 if (SecName == ".rodata" && Global.hasPrivateLinkage() &&
1452 DataSecEntries.find(SecName) == DataSecEntries.end()) {
1453 // skip .rodata.str<#> and .rodata.cst<#> sections
1454 if (!GVKind->isMergeableCString() && !GVKind->isMergeableConst()) {
1455 DataSecEntries[std::string(SecName)] =
1456 std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1457 }
1458 }
1459
1461 Global.getDebugInfo(GVs);
1462
1463 // No type information, mostly internal, skip it.
1464 if (GVs.size() == 0)
1465 continue;
1466
1467 uint32_t GVTypeId = 0;
1468 DIGlobalVariable *DIGlobal = nullptr;
1469 for (auto *GVE : GVs) {
1470 DIGlobal = GVE->getVariable();
1471 if (SecName.starts_with(".maps"))
1472 visitMapDefType(DIGlobal->getType(), GVTypeId);
1473 else {
1474 const DIType *Ty = tryRemoveAtomicType(DIGlobal->getType());
1475 visitTypeEntry(Ty, GVTypeId, false, false);
1476 }
1477 break;
1478 }
1479
1480 // Only support the following globals:
1481 // . static variables
1482 // . non-static weak or non-weak global variables
1483 // . weak or non-weak extern global variables
1484 // Whether DataSec is readonly or not can be found from corresponding ELF
1485 // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1486 // can be found from the corresponding ELF symbol table.
1487 auto Linkage = Global.getLinkage();
1493 continue;
1494
1495 uint32_t GVarInfo;
1497 GVarInfo = BTF::VAR_STATIC;
1498 } else if (Global.hasInitializer()) {
1499 GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
1500 } else {
1501 GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
1502 }
1503
1504 auto VarEntry =
1505 std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
1506 uint32_t VarId = addType(std::move(VarEntry));
1507
1508 processDeclAnnotations(DIGlobal->getAnnotations(), VarId, -1);
1509
1510 // An empty SecName means an extern variable without section attribute.
1511 if (SecName.empty())
1512 continue;
1513
1514 // Find or create a DataSec
1515 auto [It, Inserted] = DataSecEntries.try_emplace(std::string(SecName));
1516 if (Inserted)
1517 It->second = std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1518
1519 // Calculate symbol size
1520 const DataLayout &DL = Global.getDataLayout();
1521 uint32_t Size = DL.getTypeAllocSize(Global.getValueType());
1522
1523 It->second->addDataSecEntry(VarId, Asm->getSymbol(&Global), Size);
1524
1525 if (Global.hasInitializer())
1526 processGlobalInitializer(Global.getInitializer());
1527 }
1528}
1529
1530/// Process global variable initializer in pursuit for function
1531/// pointers. Add discovered (extern) functions to BTF. Some (extern)
1532/// functions might have been missed otherwise. Every symbol needs BTF
1533/// info when linking with bpftool. Primary use case: "static"
1534/// initialization of BPF maps.
1535///
1536/// struct {
1537/// __uint(type, BPF_MAP_TYPE_PROG_ARRAY);
1538/// ...
1539/// } prog_map SEC(".maps") = { .values = { extern_func } };
1540///
1541void BTFDebug::processGlobalInitializer(const Constant *C) {
1542 if (auto *Fn = dyn_cast<Function>(C))
1543 processFuncPrototypes(Fn);
1544 if (auto *CA = dyn_cast<ConstantAggregate>(C)) {
1545 for (unsigned I = 0, N = CA->getNumOperands(); I < N; ++I)
1546 processGlobalInitializer(CA->getOperand(I));
1547 }
1548}
1549
1550/// Emit proper patchable instructions.
1552 if (MI->getOpcode() == BPF::LD_imm64) {
1553 const MachineOperand &MO = MI->getOperand(1);
1554 if (MO.isGlobal()) {
1555 const GlobalValue *GVal = MO.getGlobal();
1556 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1557 if (GVar) {
1560 return false;
1561
1562 // Emit "mov ri, <imm>"
1563 auto [Imm, Reloc] = PatchImms[GVar];
1564 if (Reloc == BTF::ENUM_VALUE_EXISTENCE || Reloc == BTF::ENUM_VALUE ||
1566 OutMI.setOpcode(BPF::LD_imm64);
1567 else
1568 OutMI.setOpcode(BPF::MOV_ri);
1569 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1570 OutMI.addOperand(MCOperand::createImm(Imm));
1571 return true;
1572 }
1573 }
1574 } else if (MI->getOpcode() == BPF::CORE_LD64 ||
1575 MI->getOpcode() == BPF::CORE_LD32 ||
1576 MI->getOpcode() == BPF::CORE_ST ||
1577 MI->getOpcode() == BPF::CORE_SHIFT) {
1578 const MachineOperand &MO = MI->getOperand(3);
1579 if (MO.isGlobal()) {
1580 const GlobalValue *GVal = MO.getGlobal();
1581 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1582 if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1583 uint32_t Imm = PatchImms[GVar].first;
1584 OutMI.setOpcode(MI->getOperand(1).getImm());
1585 if (MI->getOperand(0).isImm())
1586 OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
1587 else
1588 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1589 OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
1590 OutMI.addOperand(MCOperand::createImm(Imm));
1591 return true;
1592 }
1593 }
1594 }
1595 return false;
1596}
1597
1598void BTFDebug::processFuncPrototypes(const Function *F) {
1599 if (!F)
1600 return;
1601
1602 const DISubprogram *SP = F->getSubprogram();
1603 if (!SP || SP->isDefinition())
1604 return;
1605
1606 // Do not emit again if already emitted.
1607 if (!ProtoFunctions.insert(F).second)
1608 return;
1609
1610 uint32_t ProtoTypeId;
1611 const std::unordered_map<uint32_t, StringRef> FuncArgNames;
1612 visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
1613 uint32_t FuncId = processDISubprogram(SP, ProtoTypeId, BTF::FUNC_EXTERN);
1614
1615 if (F->hasSection()) {
1616 StringRef SecName = F->getSection();
1617
1618 auto [It, Inserted] = DataSecEntries.try_emplace(std::string(SecName));
1619 if (Inserted)
1620 It->second = std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1621
1622 // We really don't know func size, set it to 0.
1623 It->second->addDataSecEntry(FuncId, Asm->getSymbol(F), 0);
1624 }
1625}
1626
1628 // Collect MapDef globals if not collected yet.
1629 if (MapDefNotCollected) {
1630 processGlobals(true);
1631 MapDefNotCollected = false;
1632 }
1633
1634 // Collect global types/variables except MapDef globals.
1635 processGlobals(false);
1636
1637 // In case that BPF_TRAP usage is removed during machine-level optimization,
1638 // generate btf for BPF_TRAP function here.
1639 for (const Function &F : *MMI->getModule()) {
1640 if (F.getName() == BPF_TRAP)
1641 processFuncPrototypes(&F);
1642 }
1643
1644 for (auto &DataSec : DataSecEntries)
1645 addType(std::move(DataSec.second));
1646
1647 // Fixups
1648 for (auto &Fixup : FixupDerivedTypes) {
1649 const DICompositeType *CTy = Fixup.first;
1650 StringRef TypeName = CTy->getName();
1651 bool IsUnion = CTy->getTag() == dwarf::DW_TAG_union_type;
1652
1653 // Search through struct types
1654 uint32_t StructTypeId = 0;
1655 for (const auto &StructType : StructTypes) {
1656 if (StructType->getName() == TypeName) {
1657 StructTypeId = StructType->getId();
1658 break;
1659 }
1660 }
1661
1662 if (StructTypeId == 0) {
1663 auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
1664 StructTypeId = addType(std::move(FwdTypeEntry));
1665 }
1666
1667 for (auto &TypeInfo : Fixup.second) {
1668 const DIDerivedType *DTy = TypeInfo.first;
1669 BTFTypeDerived *BDType = TypeInfo.second;
1670
1671 int TmpTypeId = genBTFTypeTags(DTy, StructTypeId);
1672 if (TmpTypeId >= 0)
1673 BDType->setPointeeType(TmpTypeId);
1674 else
1675 BDType->setPointeeType(StructTypeId);
1676 }
1677 }
1678
1679 // Complete BTF type cross refereences.
1680 for (const auto &TypeEntry : TypeEntries)
1681 TypeEntry->completeType(*this);
1682
1683 // Emit BTF sections.
1684 emitBTFSection();
1685 emitBTFExtSection();
1686}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define BPF_TRAP
Definition: BPF.h:25
static const char * BTFKindStr[]
Definition: BTFDebug.cpp:33
static const DIType * tryRemoveAtomicType(const DIType *Ty)
Definition: BTFDebug.cpp:38
This file contains support for writing BTF debug info.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
DXIL Finalize Linkage
T Content
std::string Name
uint64_t Size
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
PowerPC TLS Dynamic Call Fixup
Profile::FuncID FuncId
Definition: Profile.cpp:320
static StringRef getName(Value *V)
static enum BaseType getBaseType(const Value *Val)
Return the baseType for Val which states whether Val is exclusively derived from constant/null,...
raw_pwrite_stream & OS
Annotations lets you mark points and ranges inside source code, for tests:
Definition: Annotations.h:53
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:90
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:706
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:93
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:316
void emitLabelReference(const MCSymbol *Label, unsigned Size, bool IsSectionRelative=false) const
Emit something like ".long Label" where the size in bytes of the directive is specified by Size and L...
Definition: AsmPrinter.h:760
static constexpr StringRef TypeIdAttr
The attribute attached to globals representing a type id.
Definition: BPFCORE.h:48
static constexpr StringRef AmaAttr
The attribute attached to globals representing a field access.
Definition: BPFCORE.h:46
Collect and emit BTF information.
Definition: BTFDebug.h:289
void endFunctionImpl(const MachineFunction *MF) override
Post process after all instructions in this function are processed.
Definition: BTFDebug.cpp:1266
BTFDebug(AsmPrinter *AP)
Definition: BTFDebug.cpp:517
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
Definition: BTFDebug.cpp:1338
bool InstLower(const MachineInstr *MI, MCInst &OutMI)
Emit proper patchable instructions.
Definition: BTFDebug.cpp:1551
size_t addString(StringRef S)
Add string to the string table.
Definition: BTFDebug.h:418
uint32_t getArrayIndexTypeId()
Get the special array index type id.
Definition: BTFDebug.h:412
uint32_t getTypeId(const DIType *Ty)
Get the type id for a particular DIType.
Definition: BTFDebug.h:421
void endModule() override
Complete all the types and emit the BTF sections.
Definition: BTFDebug.cpp:1627
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
Definition: BTFDebug.cpp:1192
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:429
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:424
BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
Definition: BTFDebug.cpp:417
BTFKindVar(StringRef VarName, uint32_t TypeId, uint32_t VarInfo)
Definition: BTFDebug.cpp:400
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:412
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:408
uint32_t addString(StringRef S)
Add a string to the string table and returns its offset in the table.
Definition: BTFDebug.cpp:503
BTFTypeArray(uint32_t ElemTypeId, uint32_t NumElems)
Definition: BTFDebug.cpp:258
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:281
void completeType(BTFDebug &BDebug) override
Represent a BTF array.
Definition: BTFDebug.cpp:269
uint8_t Kind
Definition: BTFDebug.h:41
struct BTF::CommonType BTFType
Definition: BTFDebug.h:44
uint32_t Id
Definition: BTFDebug.h:43
virtual void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:48
uint32_t roundupToBytes(uint32_t NumBits)
Definition: BTFDebug.h:51
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:463
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:471
BTFTypeDeclTag(uint32_t BaseTypeId, int ComponentId, StringRef Tag)
Definition: BTFDebug.cpp:454
Handle several derived types include pointer, const, volatile, typedef and restrict.
Definition: BTFDebug.h:64
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:91
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:113
void setPointeeType(uint32_t PointeeType)
Definition: BTFDebug.cpp:115
BTFTypeDerived(const DIDerivedType *Ty, unsigned Tag, bool NeedsFixup)
Definition: BTFDebug.cpp:57
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:223
BTFTypeEnum64(const DICompositeType *ETy, uint32_t NumValues, bool IsSigned)
Definition: BTFDebug.cpp:216
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:247
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:184
BTFTypeEnum(const DICompositeType *ETy, uint32_t NumValues, bool IsSigned)
Definition: BTFDebug.cpp:177
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:208
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:446
BTFTypeFloat(uint32_t SizeInBits, StringRef TypeName)
Definition: BTFDebug.cpp:439
BTFTypeFuncProto(const DISubroutineType *STy, uint32_t NumParams, const std::unordered_map< uint32_t, StringRef > &FuncArgNames)
The Func kind represents both subprogram and pointee of function pointers.
Definition: BTFDebug.cpp:340
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:348
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:374
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:398
BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId, uint32_t Scope)
Definition: BTFDebug.cpp:382
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:390
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:134
BTFTypeFwd(StringRef Name, bool IsUnion)
Represent a struct/union forward declaration.
Definition: BTFDebug.cpp:120
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:126
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:171
BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits, uint32_t OffsetInBits, StringRef TypeName)
Definition: BTFDebug.cpp:136
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:163
void emitType(MCStreamer &OS) override
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:323
BTFTypeStruct(const DICompositeType *STy, bool IsStruct, bool HasBitField, uint32_t NumMembers)
Represent either a struct or a union.
Definition: BTFDebug.cpp:289
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:297
std::string getName()
Definition: BTFDebug.cpp:333
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:489
BTFTypeTypeTag(uint32_t NextTypeId, StringRef Tag)
Definition: BTFDebug.cpp:476
This is an important base class in LLVM.
Definition: Constant.h:43
Basic type, like 'int' or 'float'.
unsigned getEncoding() const
DINodeArray getElements() const
DINodeArray getAnnotations() const
DIType * getBaseType() const
DINodeArray getAnnotations() const
Get annotations associated with this derived type.
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
Subprogram description. Uses SubclassData1.
Array subrange.
LLVM_ABI BoundType getCount() const
Type array for a subprogram.
DITypeRefArray getTypeArray() const
Base class for types.
uint64_t getOffsetInBits() const
StringRef getName() const
bool isForwardDecl() const
uint64_t getSizeInBits() const
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Base class for debug information backends.
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:124
Represents either an error or a value T.
Definition: ErrorOr.h:56
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1915
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Value.h:576
@ 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:549
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.
Definition: MCSectionELF.h:27
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:496
void setAlignment(Align Value)
Definition: MCSection.h:580
StringRef getName() const
Definition: MCSection.h:565
Streaming machine code generation interface.
Definition: MCStreamer.h:220
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:1077
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1445
A single uniqued string.
Definition: Metadata.h:720
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
Definition: MachineInstr.h:72
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
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.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Root of the metadata hierarchy.
Definition: Metadata.h:63
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
size_t size() const
Definition: SmallVector.h:79
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
bool contains(StringRef Key) const
contains - Return true if the element is in the map, false otherwise.
Definition: StringMap.h:277
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:581
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:269
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:384
A table of densely packed, null-terminated strings indexed by offset.
Definition: StringTable.h:33
Class to represent struct types.
Definition: DerivedTypes.h:218
LLVM_ABI StringRef getName() const
Return the name for this struct type if it has an identity.
Definition: Type.cpp:697
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
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:418
LLVM Value Representation.
Definition: Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:322
A forward iterator which reads text lines from a buffer.
Definition: LineIterator.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ 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
@ VAR_GLOBAL_ALLOCATED
Linkage: ExternalLinkage.
Definition: BTF.h:209
@ VAR_STATIC
Linkage: InternalLinkage.
Definition: BTF.h:208
@ VAR_GLOBAL_EXTERNAL
Linkage: ExternalLinkage.
Definition: BTF.h:210
@ FUNC_STATIC
Definition: BTF.h:201
@ FUNC_EXTERN
Definition: BTF.h:203
@ FUNC_GLOBAL
Definition: BTF.h:202
@ INT_SIGNED
Definition: BTF.h:146
@ INT_BOOL
Definition: BTF.h:148
@ MAX_VLEN
Max # of struct/union/enum members or func args.
Definition: BTF.h:93
@ VERSION
Definition: BTF.h:57
@ MAGIC
Definition: BTF.h:57
@ ENUM_VALUE
Definition: BTF.h:293
@ ENUM_VALUE_EXISTENCE
Definition: BTF.h:292
@ BTF_TYPE_ID_REMOTE
Definition: BTF.h:289
@ BTF_TYPE_ID_LOCAL
Definition: BTF.h:288
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ SHT_PROGBITS
Definition: ELF.h:1140
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
Definition: TypePool.h:27
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
@ Global
Append to llvm.global_dtors.
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Represent one field relocation.
Definition: BTFDebug.h:281
uint32_t RelocKind
What to patch the instruction.
Definition: BTFDebug.h:285
const MCSymbol * Label
MCSymbol identifying insn for the reloc.
Definition: BTFDebug.h:282
uint32_t TypeID
Type ID.
Definition: BTFDebug.h:283
uint32_t OffsetNameOff
The string to traverse types.
Definition: BTFDebug.h:284
Represent one func and its type id.
Definition: BTFDebug.h:266
uint32_t TypeId
Type id referring to .BTF type section.
Definition: BTFDebug.h:268
const MCSymbol * Label
Func MCSymbol.
Definition: BTFDebug.h:267
Represent one line info.
Definition: BTFDebug.h:272
uint32_t LineOff
line offset in the .BTF string table
Definition: BTFDebug.h:275
MCSymbol * Label
MCSymbol identifying insn for the lineinfo.
Definition: BTFDebug.h:273
uint32_t ColumnNum
the column number
Definition: BTFDebug.h:277
uint32_t FileNameOff
file name offset in the .BTF string table
Definition: BTFDebug.h:274
uint32_t LineNum
the line number
Definition: BTFDebug.h:276
uint32_t Nelems
Number of elements for this array.
Definition: BTF.h:172
uint32_t IndexType
Index type.
Definition: BTF.h:171
uint32_t ElemType
Element type.
Definition: BTF.h:170
BTF_KIND_ENUM64 is followed by multiple "struct BTFEnum64".
Definition: BTF.h:162
uint32_t NameOff
Enum name offset in the string table.
Definition: BTF.h:163
uint32_t Val_Hi32
Enum member hi32 value.
Definition: BTF.h:165
uint32_t Val_Lo32
Enum member lo32 value.
Definition: BTF.h:164
BTF_KIND_ENUM is followed by multiple "struct BTFEnum".
Definition: BTF.h:154
int32_t Val
Enum member value.
Definition: BTF.h:156
uint32_t NameOff
Enum name offset in the string table.
Definition: BTF.h:155
BTF_KIND_STRUCT and BTF_KIND_UNION are followed by multiple "struct BTFMember".
Definition: BTF.h:185
uint32_t NameOff
Member name offset in the string table.
Definition: BTF.h:186
uint32_t Offset
BitOffset or BitFieldSize+BitOffset.
Definition: BTF.h:188
uint32_t Type
Member type.
Definition: BTF.h:187
BTF_KIND_FUNC_PROTO are followed by multiple "struct BTFParam".
Definition: BTF.h:194
uint32_t Type
Definition: BTF.h:128
uint32_t Size
Definition: BTF.h:127
uint32_t NameOff
Type name offset in the string table.
Definition: BTF.h:109
uint32_t Info
"Info" bits arrangement: Bits 0-15: vlen (e.g.
Definition: BTF.h:118
Container for description of a global variable.
Definition: DIContext.h:120