1 //===- BTFDebug.cpp - BTF Generator ---------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains support for writing BTF debug info.
11 //===----------------------------------------------------------------------===//
16 #include "MCTargetDesc/BPFMCTargetDesc.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/MachineOperand.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCSectionELF.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/Support/LineIterator.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Target/TargetLoweringObjectFile.h"
32 static const char *BTFKindStr
[] = {
33 #define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
34 #include "llvm/DebugInfo/BTF/BTF.def"
37 /// Emit a BTF common type.
38 void BTFTypeBase::emitType(MCStreamer
&OS
) {
39 OS
.AddComment(std::string(BTFKindStr
[Kind
]) + "(id = " + std::to_string(Id
) +
41 OS
.emitInt32(BTFType
.NameOff
);
42 OS
.AddComment("0x" + Twine::utohexstr(BTFType
.Info
));
43 OS
.emitInt32(BTFType
.Info
);
44 OS
.emitInt32(BTFType
.Size
);
47 BTFTypeDerived::BTFTypeDerived(const DIDerivedType
*DTy
, unsigned Tag
,
49 : DTy(DTy
), NeedsFixup(NeedsFixup
), Name(DTy
->getName()) {
51 case dwarf::DW_TAG_pointer_type
:
52 Kind
= BTF::BTF_KIND_PTR
;
54 case dwarf::DW_TAG_const_type
:
55 Kind
= BTF::BTF_KIND_CONST
;
57 case dwarf::DW_TAG_volatile_type
:
58 Kind
= BTF::BTF_KIND_VOLATILE
;
60 case dwarf::DW_TAG_typedef
:
61 Kind
= BTF::BTF_KIND_TYPEDEF
;
63 case dwarf::DW_TAG_restrict_type
:
64 Kind
= BTF::BTF_KIND_RESTRICT
;
67 llvm_unreachable("Unknown DIDerivedType Tag");
69 BTFType
.Info
= Kind
<< 24;
72 /// Used by DW_TAG_pointer_type only.
73 BTFTypeDerived::BTFTypeDerived(unsigned NextTypeId
, unsigned Tag
,
75 : DTy(nullptr), NeedsFixup(false), Name(Name
) {
76 Kind
= BTF::BTF_KIND_PTR
;
77 BTFType
.Info
= Kind
<< 24;
78 BTFType
.Type
= NextTypeId
;
81 void BTFTypeDerived::completeType(BTFDebug
&BDebug
) {
86 BTFType
.NameOff
= BDebug
.addString(Name
);
88 if (NeedsFixup
|| !DTy
)
91 // The base type for PTR/CONST/VOLATILE could be void.
92 const DIType
*ResolvedType
= DTy
->getBaseType();
94 assert((Kind
== BTF::BTF_KIND_PTR
|| Kind
== BTF::BTF_KIND_CONST
||
95 Kind
== BTF::BTF_KIND_VOLATILE
) &&
96 "Invalid null basetype");
99 BTFType
.Type
= BDebug
.getTypeId(ResolvedType
);
103 void BTFTypeDerived::emitType(MCStreamer
&OS
) { BTFTypeBase::emitType(OS
); }
105 void BTFTypeDerived::setPointeeType(uint32_t PointeeType
) {
106 BTFType
.Type
= PointeeType
;
109 /// Represent a struct/union forward declaration.
110 BTFTypeFwd::BTFTypeFwd(StringRef Name
, bool IsUnion
) : Name(Name
) {
111 Kind
= BTF::BTF_KIND_FWD
;
112 BTFType
.Info
= IsUnion
<< 31 | Kind
<< 24;
116 void BTFTypeFwd::completeType(BTFDebug
&BDebug
) {
121 BTFType
.NameOff
= BDebug
.addString(Name
);
124 void BTFTypeFwd::emitType(MCStreamer
&OS
) { BTFTypeBase::emitType(OS
); }
126 BTFTypeInt::BTFTypeInt(uint32_t Encoding
, uint32_t SizeInBits
,
127 uint32_t OffsetInBits
, StringRef TypeName
)
129 // Translate IR int encoding to BTF int encoding.
132 case dwarf::DW_ATE_boolean
:
133 BTFEncoding
= BTF::INT_BOOL
;
135 case dwarf::DW_ATE_signed
:
136 case dwarf::DW_ATE_signed_char
:
137 BTFEncoding
= BTF::INT_SIGNED
;
139 case dwarf::DW_ATE_unsigned
:
140 case dwarf::DW_ATE_unsigned_char
:
144 llvm_unreachable("Unknown BTFTypeInt Encoding");
147 Kind
= BTF::BTF_KIND_INT
;
148 BTFType
.Info
= Kind
<< 24;
149 BTFType
.Size
= roundupToBytes(SizeInBits
);
150 IntVal
= (BTFEncoding
<< 24) | OffsetInBits
<< 16 | SizeInBits
;
153 void BTFTypeInt::completeType(BTFDebug
&BDebug
) {
158 BTFType
.NameOff
= BDebug
.addString(Name
);
161 void BTFTypeInt::emitType(MCStreamer
&OS
) {
162 BTFTypeBase::emitType(OS
);
163 OS
.AddComment("0x" + Twine::utohexstr(IntVal
));
164 OS
.emitInt32(IntVal
);
167 BTFTypeEnum::BTFTypeEnum(const DICompositeType
*ETy
, uint32_t VLen
,
168 bool IsSigned
) : ETy(ETy
) {
169 Kind
= BTF::BTF_KIND_ENUM
;
170 BTFType
.Info
= IsSigned
<< 31 | Kind
<< 24 | VLen
;
171 BTFType
.Size
= roundupToBytes(ETy
->getSizeInBits());
174 void BTFTypeEnum::completeType(BTFDebug
&BDebug
) {
179 BTFType
.NameOff
= BDebug
.addString(ETy
->getName());
181 DINodeArray Elements
= ETy
->getElements();
182 for (const auto Element
: Elements
) {
183 const auto *Enum
= cast
<DIEnumerator
>(Element
);
185 struct BTF::BTFEnum BTFEnum
;
186 BTFEnum
.NameOff
= BDebug
.addString(Enum
->getName());
187 // BTF enum value is 32bit, enforce it.
189 if (Enum
->isUnsigned())
190 Value
= static_cast<uint32_t>(Enum
->getValue().getZExtValue());
192 Value
= static_cast<uint32_t>(Enum
->getValue().getSExtValue());
194 EnumValues
.push_back(BTFEnum
);
198 void BTFTypeEnum::emitType(MCStreamer
&OS
) {
199 BTFTypeBase::emitType(OS
);
200 for (const auto &Enum
: EnumValues
) {
201 OS
.emitInt32(Enum
.NameOff
);
202 OS
.emitInt32(Enum
.Val
);
206 BTFTypeEnum64::BTFTypeEnum64(const DICompositeType
*ETy
, uint32_t VLen
,
207 bool IsSigned
) : ETy(ETy
) {
208 Kind
= BTF::BTF_KIND_ENUM64
;
209 BTFType
.Info
= IsSigned
<< 31 | Kind
<< 24 | VLen
;
210 BTFType
.Size
= roundupToBytes(ETy
->getSizeInBits());
213 void BTFTypeEnum64::completeType(BTFDebug
&BDebug
) {
218 BTFType
.NameOff
= BDebug
.addString(ETy
->getName());
220 DINodeArray Elements
= ETy
->getElements();
221 for (const auto Element
: Elements
) {
222 const auto *Enum
= cast
<DIEnumerator
>(Element
);
224 struct BTF::BTFEnum64 BTFEnum
;
225 BTFEnum
.NameOff
= BDebug
.addString(Enum
->getName());
227 if (Enum
->isUnsigned())
228 Value
= static_cast<uint64_t>(Enum
->getValue().getZExtValue());
230 Value
= static_cast<uint64_t>(Enum
->getValue().getSExtValue());
231 BTFEnum
.Val_Lo32
= Value
;
232 BTFEnum
.Val_Hi32
= Value
>> 32;
233 EnumValues
.push_back(BTFEnum
);
237 void BTFTypeEnum64::emitType(MCStreamer
&OS
) {
238 BTFTypeBase::emitType(OS
);
239 for (const auto &Enum
: EnumValues
) {
240 OS
.emitInt32(Enum
.NameOff
);
241 OS
.AddComment("0x" + Twine::utohexstr(Enum
.Val_Lo32
));
242 OS
.emitInt32(Enum
.Val_Lo32
);
243 OS
.AddComment("0x" + Twine::utohexstr(Enum
.Val_Hi32
));
244 OS
.emitInt32(Enum
.Val_Hi32
);
248 BTFTypeArray::BTFTypeArray(uint32_t ElemTypeId
, uint32_t NumElems
) {
249 Kind
= BTF::BTF_KIND_ARRAY
;
251 BTFType
.Info
= Kind
<< 24;
254 ArrayInfo
.ElemType
= ElemTypeId
;
255 ArrayInfo
.Nelems
= NumElems
;
258 /// Represent a BTF array.
259 void BTFTypeArray::completeType(BTFDebug
&BDebug
) {
264 // The IR does not really have a type for the index.
265 // A special type for array index should have been
266 // created during initial type traversal. Just
267 // retrieve that type id.
268 ArrayInfo
.IndexType
= BDebug
.getArrayIndexTypeId();
271 void BTFTypeArray::emitType(MCStreamer
&OS
) {
272 BTFTypeBase::emitType(OS
);
273 OS
.emitInt32(ArrayInfo
.ElemType
);
274 OS
.emitInt32(ArrayInfo
.IndexType
);
275 OS
.emitInt32(ArrayInfo
.Nelems
);
278 /// Represent either a struct or a union.
279 BTFTypeStruct::BTFTypeStruct(const DICompositeType
*STy
, bool IsStruct
,
280 bool HasBitField
, uint32_t Vlen
)
281 : STy(STy
), HasBitField(HasBitField
) {
282 Kind
= IsStruct
? BTF::BTF_KIND_STRUCT
: BTF::BTF_KIND_UNION
;
283 BTFType
.Size
= roundupToBytes(STy
->getSizeInBits());
284 BTFType
.Info
= (HasBitField
<< 31) | (Kind
<< 24) | Vlen
;
287 void BTFTypeStruct::completeType(BTFDebug
&BDebug
) {
292 BTFType
.NameOff
= BDebug
.addString(STy
->getName());
294 // Add struct/union members.
295 const DINodeArray Elements
= STy
->getElements();
296 for (const auto *Element
: Elements
) {
297 struct BTF::BTFMember BTFMember
;
298 const auto *DDTy
= cast
<DIDerivedType
>(Element
);
300 BTFMember
.NameOff
= BDebug
.addString(DDTy
->getName());
302 uint8_t BitFieldSize
= DDTy
->isBitField() ? DDTy
->getSizeInBits() : 0;
303 BTFMember
.Offset
= BitFieldSize
<< 24 | DDTy
->getOffsetInBits();
305 BTFMember
.Offset
= DDTy
->getOffsetInBits();
307 const auto *BaseTy
= DDTy
->getBaseType();
308 BTFMember
.Type
= BDebug
.getTypeId(BaseTy
);
309 Members
.push_back(BTFMember
);
313 void BTFTypeStruct::emitType(MCStreamer
&OS
) {
314 BTFTypeBase::emitType(OS
);
315 for (const auto &Member
: Members
) {
316 OS
.emitInt32(Member
.NameOff
);
317 OS
.emitInt32(Member
.Type
);
318 OS
.AddComment("0x" + Twine::utohexstr(Member
.Offset
));
319 OS
.emitInt32(Member
.Offset
);
323 std::string
BTFTypeStruct::getName() { return std::string(STy
->getName()); }
325 /// The Func kind represents both subprogram and pointee of function
326 /// pointers. If the FuncName is empty, it represents a pointee of function
327 /// pointer. Otherwise, it represents a subprogram. The func arg names
328 /// are empty for pointee of function pointer case, and are valid names
330 BTFTypeFuncProto::BTFTypeFuncProto(
331 const DISubroutineType
*STy
, uint32_t VLen
,
332 const std::unordered_map
<uint32_t, StringRef
> &FuncArgNames
)
333 : STy(STy
), FuncArgNames(FuncArgNames
) {
334 Kind
= BTF::BTF_KIND_FUNC_PROTO
;
335 BTFType
.Info
= (Kind
<< 24) | VLen
;
338 void BTFTypeFuncProto::completeType(BTFDebug
&BDebug
) {
343 DITypeRefArray Elements
= STy
->getTypeArray();
344 auto RetType
= Elements
[0];
345 BTFType
.Type
= RetType
? BDebug
.getTypeId(RetType
) : 0;
348 // For null parameter which is typically the last one
349 // to represent the vararg, encode the NameOff/Type to be 0.
350 for (unsigned I
= 1, N
= Elements
.size(); I
< N
; ++I
) {
351 struct BTF::BTFParam Param
;
352 auto Element
= Elements
[I
];
354 Param
.NameOff
= BDebug
.addString(FuncArgNames
[I
]);
355 Param
.Type
= BDebug
.getTypeId(Element
);
360 Parameters
.push_back(Param
);
364 void BTFTypeFuncProto::emitType(MCStreamer
&OS
) {
365 BTFTypeBase::emitType(OS
);
366 for (const auto &Param
: Parameters
) {
367 OS
.emitInt32(Param
.NameOff
);
368 OS
.emitInt32(Param
.Type
);
372 BTFTypeFunc::BTFTypeFunc(StringRef FuncName
, uint32_t ProtoTypeId
,
375 Kind
= BTF::BTF_KIND_FUNC
;
376 BTFType
.Info
= (Kind
<< 24) | Scope
;
377 BTFType
.Type
= ProtoTypeId
;
380 void BTFTypeFunc::completeType(BTFDebug
&BDebug
) {
385 BTFType
.NameOff
= BDebug
.addString(Name
);
388 void BTFTypeFunc::emitType(MCStreamer
&OS
) { BTFTypeBase::emitType(OS
); }
390 BTFKindVar::BTFKindVar(StringRef VarName
, uint32_t TypeId
, uint32_t VarInfo
)
392 Kind
= BTF::BTF_KIND_VAR
;
393 BTFType
.Info
= Kind
<< 24;
394 BTFType
.Type
= TypeId
;
398 void BTFKindVar::completeType(BTFDebug
&BDebug
) {
399 BTFType
.NameOff
= BDebug
.addString(Name
);
402 void BTFKindVar::emitType(MCStreamer
&OS
) {
403 BTFTypeBase::emitType(OS
);
407 BTFKindDataSec::BTFKindDataSec(AsmPrinter
*AsmPrt
, std::string SecName
)
408 : Asm(AsmPrt
), Name(SecName
) {
409 Kind
= BTF::BTF_KIND_DATASEC
;
410 BTFType
.Info
= Kind
<< 24;
414 void BTFKindDataSec::completeType(BTFDebug
&BDebug
) {
415 BTFType
.NameOff
= BDebug
.addString(Name
);
416 BTFType
.Info
|= Vars
.size();
419 void BTFKindDataSec::emitType(MCStreamer
&OS
) {
420 BTFTypeBase::emitType(OS
);
422 for (const auto &V
: Vars
) {
423 OS
.emitInt32(std::get
<0>(V
));
424 Asm
->emitLabelReference(std::get
<1>(V
), 4);
425 OS
.emitInt32(std::get
<2>(V
));
429 BTFTypeFloat::BTFTypeFloat(uint32_t SizeInBits
, StringRef TypeName
)
431 Kind
= BTF::BTF_KIND_FLOAT
;
432 BTFType
.Info
= Kind
<< 24;
433 BTFType
.Size
= roundupToBytes(SizeInBits
);
436 void BTFTypeFloat::completeType(BTFDebug
&BDebug
) {
441 BTFType
.NameOff
= BDebug
.addString(Name
);
444 BTFTypeDeclTag::BTFTypeDeclTag(uint32_t BaseTypeId
, int ComponentIdx
,
447 Kind
= BTF::BTF_KIND_DECL_TAG
;
448 BTFType
.Info
= Kind
<< 24;
449 BTFType
.Type
= BaseTypeId
;
453 void BTFTypeDeclTag::completeType(BTFDebug
&BDebug
) {
458 BTFType
.NameOff
= BDebug
.addString(Tag
);
461 void BTFTypeDeclTag::emitType(MCStreamer
&OS
) {
462 BTFTypeBase::emitType(OS
);
466 BTFTypeTypeTag::BTFTypeTypeTag(uint32_t NextTypeId
, StringRef Tag
)
467 : DTy(nullptr), Tag(Tag
) {
468 Kind
= BTF::BTF_KIND_TYPE_TAG
;
469 BTFType
.Info
= Kind
<< 24;
470 BTFType
.Type
= NextTypeId
;
473 BTFTypeTypeTag::BTFTypeTypeTag(const DIDerivedType
*DTy
, StringRef Tag
)
474 : DTy(DTy
), Tag(Tag
) {
475 Kind
= BTF::BTF_KIND_TYPE_TAG
;
476 BTFType
.Info
= Kind
<< 24;
479 void BTFTypeTypeTag::completeType(BTFDebug
&BDebug
) {
483 BTFType
.NameOff
= BDebug
.addString(Tag
);
485 const DIType
*ResolvedType
= DTy
->getBaseType();
489 BTFType
.Type
= BDebug
.getTypeId(ResolvedType
);
493 uint32_t BTFStringTable::addString(StringRef S
) {
494 // Check whether the string already exists.
495 for (auto &OffsetM
: OffsetToIdMap
) {
496 if (Table
[OffsetM
.second
] == S
)
497 return OffsetM
.first
;
499 // Not find, add to the string table.
500 uint32_t Offset
= Size
;
501 OffsetToIdMap
[Offset
] = Table
.size();
502 Table
.push_back(std::string(S
));
503 Size
+= S
.size() + 1;
507 BTFDebug::BTFDebug(AsmPrinter
*AP
)
508 : DebugHandlerBase(AP
), OS(*Asm
->OutStreamer
), SkipInstruction(false),
509 LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
510 MapDefNotCollected(true) {
514 uint32_t BTFDebug::addType(std::unique_ptr
<BTFTypeBase
> TypeEntry
,
516 TypeEntry
->setId(TypeEntries
.size() + 1);
517 uint32_t Id
= TypeEntry
->getId();
519 TypeEntries
.push_back(std::move(TypeEntry
));
523 uint32_t BTFDebug::addType(std::unique_ptr
<BTFTypeBase
> TypeEntry
) {
524 TypeEntry
->setId(TypeEntries
.size() + 1);
525 uint32_t Id
= TypeEntry
->getId();
526 TypeEntries
.push_back(std::move(TypeEntry
));
530 void BTFDebug::visitBasicType(const DIBasicType
*BTy
, uint32_t &TypeId
) {
531 // Only int and binary floating point types are supported in BTF.
532 uint32_t Encoding
= BTy
->getEncoding();
533 std::unique_ptr
<BTFTypeBase
> TypeEntry
;
535 case dwarf::DW_ATE_boolean
:
536 case dwarf::DW_ATE_signed
:
537 case dwarf::DW_ATE_signed_char
:
538 case dwarf::DW_ATE_unsigned
:
539 case dwarf::DW_ATE_unsigned_char
:
540 // Create a BTF type instance for this DIBasicType and put it into
541 // DIToIdMap for cross-type reference check.
542 TypeEntry
= std::make_unique
<BTFTypeInt
>(
543 Encoding
, BTy
->getSizeInBits(), BTy
->getOffsetInBits(), BTy
->getName());
545 case dwarf::DW_ATE_float
:
547 std::make_unique
<BTFTypeFloat
>(BTy
->getSizeInBits(), BTy
->getName());
553 TypeId
= addType(std::move(TypeEntry
), BTy
);
556 /// Handle subprogram or subroutine types.
557 void BTFDebug::visitSubroutineType(
558 const DISubroutineType
*STy
, bool ForSubprog
,
559 const std::unordered_map
<uint32_t, StringRef
> &FuncArgNames
,
561 DITypeRefArray Elements
= STy
->getTypeArray();
562 uint32_t VLen
= Elements
.size() - 1;
563 if (VLen
> BTF::MAX_VLEN
)
566 // Subprogram has a valid non-zero-length name, and the pointee of
567 // a function pointer has an empty name. The subprogram type will
568 // not be added to DIToIdMap as it should not be referenced by
570 auto TypeEntry
= std::make_unique
<BTFTypeFuncProto
>(STy
, VLen
, FuncArgNames
);
572 TypeId
= addType(std::move(TypeEntry
)); // For subprogram
574 TypeId
= addType(std::move(TypeEntry
), STy
); // For func ptr
576 // Visit return type and func arg types.
577 for (const auto Element
: Elements
) {
578 visitTypeEntry(Element
);
582 void BTFDebug::processDeclAnnotations(DINodeArray Annotations
,
588 for (const Metadata
*Annotation
: Annotations
->operands()) {
589 const MDNode
*MD
= cast
<MDNode
>(Annotation
);
590 const MDString
*Name
= cast
<MDString
>(MD
->getOperand(0));
591 if (!Name
->getString().equals("btf_decl_tag"))
594 const MDString
*Value
= cast
<MDString
>(MD
->getOperand(1));
595 auto TypeEntry
= std::make_unique
<BTFTypeDeclTag
>(BaseTypeId
, ComponentIdx
,
597 addType(std::move(TypeEntry
));
601 uint32_t BTFDebug::processDISubprogram(const DISubprogram
*SP
,
602 uint32_t ProtoTypeId
, uint8_t Scope
) {
604 std::make_unique
<BTFTypeFunc
>(SP
->getName(), ProtoTypeId
, Scope
);
605 uint32_t FuncId
= addType(std::move(FuncTypeEntry
));
607 // Process argument annotations.
608 for (const DINode
*DN
: SP
->getRetainedNodes()) {
609 if (const auto *DV
= dyn_cast
<DILocalVariable
>(DN
)) {
610 uint32_t Arg
= DV
->getArg();
612 processDeclAnnotations(DV
->getAnnotations(), FuncId
, Arg
- 1);
615 processDeclAnnotations(SP
->getAnnotations(), FuncId
, -1);
620 /// Generate btf_type_tag chains.
621 int BTFDebug::genBTFTypeTags(const DIDerivedType
*DTy
, int BaseTypeId
) {
622 SmallVector
<const MDString
*, 4> MDStrs
;
623 DINodeArray Annots
= DTy
->getAnnotations();
625 // For type with "int __tag1 __tag2 *p", the MDStrs will have
626 // content: [__tag1, __tag2].
627 for (const Metadata
*Annotations
: Annots
->operands()) {
628 const MDNode
*MD
= cast
<MDNode
>(Annotations
);
629 const MDString
*Name
= cast
<MDString
>(MD
->getOperand(0));
630 if (!Name
->getString().equals("btf_type_tag"))
632 MDStrs
.push_back(cast
<MDString
>(MD
->getOperand(1)));
636 if (MDStrs
.size() == 0)
639 // With MDStrs [__tag1, __tag2], the output type chain looks like
640 // PTR -> __tag2 -> __tag1 -> BaseType
641 // In the below, we construct BTF types with the order of __tag1, __tag2
644 std::unique_ptr
<BTFTypeTypeTag
> TypeEntry
;
647 std::make_unique
<BTFTypeTypeTag
>(BaseTypeId
, MDStrs
[0]->getString());
649 TypeEntry
= std::make_unique
<BTFTypeTypeTag
>(DTy
, MDStrs
[0]->getString());
650 TmpTypeId
= addType(std::move(TypeEntry
));
652 for (unsigned I
= 1; I
< MDStrs
.size(); I
++) {
653 const MDString
*Value
= MDStrs
[I
];
654 TypeEntry
= std::make_unique
<BTFTypeTypeTag
>(TmpTypeId
, Value
->getString());
655 TmpTypeId
= addType(std::move(TypeEntry
));
660 /// Handle structure/union types.
661 void BTFDebug::visitStructType(const DICompositeType
*CTy
, bool IsStruct
,
663 const DINodeArray Elements
= CTy
->getElements();
664 uint32_t VLen
= Elements
.size();
665 if (VLen
> BTF::MAX_VLEN
)
668 // Check whether we have any bitfield members or not
669 bool HasBitField
= false;
670 for (const auto *Element
: Elements
) {
671 auto E
= cast
<DIDerivedType
>(Element
);
672 if (E
->isBitField()) {
679 std::make_unique
<BTFTypeStruct
>(CTy
, IsStruct
, HasBitField
, VLen
);
680 StructTypes
.push_back(TypeEntry
.get());
681 TypeId
= addType(std::move(TypeEntry
), CTy
);
683 // Check struct/union annotations
684 processDeclAnnotations(CTy
->getAnnotations(), TypeId
, -1);
686 // Visit all struct members.
688 for (const auto *Element
: Elements
) {
689 const auto Elem
= cast
<DIDerivedType
>(Element
);
690 visitTypeEntry(Elem
);
691 processDeclAnnotations(Elem
->getAnnotations(), TypeId
, FieldNo
);
696 void BTFDebug::visitArrayType(const DICompositeType
*CTy
, uint32_t &TypeId
) {
697 // Visit array element type.
699 const DIType
*ElemType
= CTy
->getBaseType();
700 visitTypeEntry(ElemType
, ElemTypeId
, false, false);
702 // Visit array dimensions.
703 DINodeArray Elements
= CTy
->getElements();
704 for (int I
= Elements
.size() - 1; I
>= 0; --I
) {
705 if (auto *Element
= dyn_cast_or_null
<DINode
>(Elements
[I
]))
706 if (Element
->getTag() == dwarf::DW_TAG_subrange_type
) {
707 const DISubrange
*SR
= cast
<DISubrange
>(Element
);
708 auto *CI
= SR
->getCount().dyn_cast
<ConstantInt
*>();
709 int64_t Count
= CI
->getSExtValue();
711 // For struct s { int b; char c[]; }, the c[] will be represented
712 // as an array with Count = -1.
714 std::make_unique
<BTFTypeArray
>(ElemTypeId
,
715 Count
>= 0 ? Count
: 0);
717 ElemTypeId
= addType(std::move(TypeEntry
), CTy
);
719 ElemTypeId
= addType(std::move(TypeEntry
));
723 // The array TypeId is the type id of the outermost dimension.
726 // The IR does not have a type for array index while BTF wants one.
727 // So create an array index type if there is none.
728 if (!ArrayIndexTypeId
) {
729 auto TypeEntry
= std::make_unique
<BTFTypeInt
>(dwarf::DW_ATE_unsigned
, 32,
730 0, "__ARRAY_SIZE_TYPE__");
731 ArrayIndexTypeId
= addType(std::move(TypeEntry
));
735 void BTFDebug::visitEnumType(const DICompositeType
*CTy
, uint32_t &TypeId
) {
736 DINodeArray Elements
= CTy
->getElements();
737 uint32_t VLen
= Elements
.size();
738 if (VLen
> BTF::MAX_VLEN
)
741 bool IsSigned
= false;
742 unsigned NumBits
= 32;
743 // No BaseType implies forward declaration in which case a
744 // BTFTypeEnum with Vlen = 0 is emitted.
745 if (CTy
->getBaseType() != nullptr) {
746 const auto *BTy
= cast
<DIBasicType
>(CTy
->getBaseType());
747 IsSigned
= BTy
->getEncoding() == dwarf::DW_ATE_signed
||
748 BTy
->getEncoding() == dwarf::DW_ATE_signed_char
;
749 NumBits
= BTy
->getSizeInBits();
753 auto TypeEntry
= std::make_unique
<BTFTypeEnum
>(CTy
, VLen
, IsSigned
);
754 TypeId
= addType(std::move(TypeEntry
), CTy
);
756 assert(NumBits
== 64);
757 auto TypeEntry
= std::make_unique
<BTFTypeEnum64
>(CTy
, VLen
, IsSigned
);
758 TypeId
= addType(std::move(TypeEntry
), CTy
);
760 // No need to visit base type as BTF does not encode it.
763 /// Handle structure/union forward declarations.
764 void BTFDebug::visitFwdDeclType(const DICompositeType
*CTy
, bool IsUnion
,
766 auto TypeEntry
= std::make_unique
<BTFTypeFwd
>(CTy
->getName(), IsUnion
);
767 TypeId
= addType(std::move(TypeEntry
), CTy
);
770 /// Handle structure, union, array and enumeration types.
771 void BTFDebug::visitCompositeType(const DICompositeType
*CTy
,
773 auto Tag
= CTy
->getTag();
774 if (Tag
== dwarf::DW_TAG_structure_type
|| Tag
== dwarf::DW_TAG_union_type
) {
775 // Handle forward declaration differently as it does not have members.
776 if (CTy
->isForwardDecl())
777 visitFwdDeclType(CTy
, Tag
== dwarf::DW_TAG_union_type
, TypeId
);
779 visitStructType(CTy
, Tag
== dwarf::DW_TAG_structure_type
, TypeId
);
780 } else if (Tag
== dwarf::DW_TAG_array_type
)
781 visitArrayType(CTy
, TypeId
);
782 else if (Tag
== dwarf::DW_TAG_enumeration_type
)
783 visitEnumType(CTy
, TypeId
);
786 bool BTFDebug::IsForwardDeclCandidate(const DIType
*Base
) {
787 if (const auto *CTy
= dyn_cast
<DICompositeType
>(Base
)) {
788 auto CTag
= CTy
->getTag();
789 if ((CTag
== dwarf::DW_TAG_structure_type
||
790 CTag
== dwarf::DW_TAG_union_type
) &&
791 !CTy
->getName().empty() && !CTy
->isForwardDecl())
797 /// Handle pointer, typedef, const, volatile, restrict and member types.
798 void BTFDebug::visitDerivedType(const DIDerivedType
*DTy
, uint32_t &TypeId
,
799 bool CheckPointer
, bool SeenPointer
) {
800 unsigned Tag
= DTy
->getTag();
802 /// Try to avoid chasing pointees, esp. structure pointees which may
803 /// unnecessary bring in a lot of types.
804 if (CheckPointer
&& !SeenPointer
) {
805 SeenPointer
= Tag
== dwarf::DW_TAG_pointer_type
;
808 if (CheckPointer
&& SeenPointer
) {
809 const DIType
*Base
= DTy
->getBaseType();
811 if (IsForwardDeclCandidate(Base
)) {
812 /// Find a candidate, generate a fixup. Later on the struct/union
813 /// pointee type will be replaced with either a real type or
814 /// a forward declaration.
815 auto TypeEntry
= std::make_unique
<BTFTypeDerived
>(DTy
, Tag
, true);
816 auto &Fixup
= FixupDerivedTypes
[cast
<DICompositeType
>(Base
)];
817 Fixup
.push_back(std::make_pair(DTy
, TypeEntry
.get()));
818 TypeId
= addType(std::move(TypeEntry
), DTy
);
824 if (Tag
== dwarf::DW_TAG_pointer_type
) {
825 int TmpTypeId
= genBTFTypeTags(DTy
, -1);
826 if (TmpTypeId
>= 0) {
828 std::make_unique
<BTFTypeDerived
>(TmpTypeId
, Tag
, DTy
->getName());
829 TypeId
= addType(std::move(TypeDEntry
), DTy
);
831 auto TypeEntry
= std::make_unique
<BTFTypeDerived
>(DTy
, Tag
, false);
832 TypeId
= addType(std::move(TypeEntry
), DTy
);
834 } else if (Tag
== dwarf::DW_TAG_typedef
|| Tag
== dwarf::DW_TAG_const_type
||
835 Tag
== dwarf::DW_TAG_volatile_type
||
836 Tag
== dwarf::DW_TAG_restrict_type
) {
837 auto TypeEntry
= std::make_unique
<BTFTypeDerived
>(DTy
, Tag
, false);
838 TypeId
= addType(std::move(TypeEntry
), DTy
);
839 if (Tag
== dwarf::DW_TAG_typedef
)
840 processDeclAnnotations(DTy
->getAnnotations(), TypeId
, -1);
841 } else if (Tag
!= dwarf::DW_TAG_member
) {
845 // Visit base type of pointer, typedef, const, volatile, restrict or
846 // struct/union member.
847 uint32_t TempTypeId
= 0;
848 if (Tag
== dwarf::DW_TAG_member
)
849 visitTypeEntry(DTy
->getBaseType(), TempTypeId
, true, false);
851 visitTypeEntry(DTy
->getBaseType(), TempTypeId
, CheckPointer
, SeenPointer
);
854 /// Visit a type entry. CheckPointer is true if the type has
855 /// one of its predecessors as one struct/union member. SeenPointer
856 /// is true if CheckPointer is true and one of its predecessors
857 /// is a pointer. The goal of CheckPointer and SeenPointer is to
858 /// do pruning for struct/union types so some of these types
859 /// will not be emitted in BTF and rather forward declarations
860 /// will be generated.
861 void BTFDebug::visitTypeEntry(const DIType
*Ty
, uint32_t &TypeId
,
862 bool CheckPointer
, bool SeenPointer
) {
863 if (!Ty
|| DIToIdMap
.find(Ty
) != DIToIdMap
.end()) {
864 TypeId
= DIToIdMap
[Ty
];
866 // To handle the case like the following:
868 // typedef struct t _t;
869 // struct s1 { _t *c; };
870 // int test1(struct s1 *arg) { ... }
872 // struct t { int a; int b; };
873 // struct s2 { _t c; }
874 // int test2(struct s2 *arg) { ... }
876 // During traversing test1() argument, "_t" is recorded
877 // in DIToIdMap and a forward declaration fixup is created
878 // for "struct t" to avoid pointee type traversal.
880 // During traversing test2() argument, even if we see "_t" is
881 // already defined, we should keep moving to eventually
882 // bring in types for "struct t". Otherwise, the "struct s2"
883 // definition won't be correct.
885 // In the above, we have following debuginfo:
886 // {ptr, struct_member} -> typedef -> struct
887 // and BTF type for 'typedef' is generated while 'struct' may
888 // be in FixUp. But let us generalize the above to handle
889 // {different types} -> [various derived types]+ -> another type.
891 // {func_param, struct_member} -> const -> ptr -> volatile -> struct
892 // We will traverse const/ptr/volatile which already have corresponding
893 // BTF types and generate type for 'struct' which might be in Fixup
895 if (Ty
&& (!CheckPointer
|| !SeenPointer
)) {
896 if (const auto *DTy
= dyn_cast
<DIDerivedType
>(Ty
)) {
898 const DIType
*BaseTy
= DTy
->getBaseType();
902 if (DIToIdMap
.find(BaseTy
) != DIToIdMap
.end()) {
903 DTy
= dyn_cast
<DIDerivedType
>(BaseTy
);
905 if (CheckPointer
&& DTy
->getTag() == dwarf::DW_TAG_pointer_type
) {
907 if (IsForwardDeclCandidate(BaseTy
))
911 visitTypeEntry(BaseTy
, TmpTypeId
, CheckPointer
, SeenPointer
);
921 if (const auto *BTy
= dyn_cast
<DIBasicType
>(Ty
))
922 visitBasicType(BTy
, TypeId
);
923 else if (const auto *STy
= dyn_cast
<DISubroutineType
>(Ty
))
924 visitSubroutineType(STy
, false, std::unordered_map
<uint32_t, StringRef
>(),
926 else if (const auto *CTy
= dyn_cast
<DICompositeType
>(Ty
))
927 visitCompositeType(CTy
, TypeId
);
928 else if (const auto *DTy
= dyn_cast
<DIDerivedType
>(Ty
))
929 visitDerivedType(DTy
, TypeId
, CheckPointer
, SeenPointer
);
931 llvm_unreachable("Unknown DIType");
934 void BTFDebug::visitTypeEntry(const DIType
*Ty
) {
936 visitTypeEntry(Ty
, TypeId
, false, false);
939 void BTFDebug::visitMapDefType(const DIType
*Ty
, uint32_t &TypeId
) {
940 if (!Ty
|| DIToIdMap
.find(Ty
) != DIToIdMap
.end()) {
941 TypeId
= DIToIdMap
[Ty
];
945 // MapDef type may be a struct type or a non-pointer derived type
946 const DIType
*OrigTy
= Ty
;
947 while (auto *DTy
= dyn_cast
<DIDerivedType
>(Ty
)) {
948 auto Tag
= DTy
->getTag();
949 if (Tag
!= dwarf::DW_TAG_typedef
&& Tag
!= dwarf::DW_TAG_const_type
&&
950 Tag
!= dwarf::DW_TAG_volatile_type
&&
951 Tag
!= dwarf::DW_TAG_restrict_type
)
953 Ty
= DTy
->getBaseType();
956 const auto *CTy
= dyn_cast
<DICompositeType
>(Ty
);
960 auto Tag
= CTy
->getTag();
961 if (Tag
!= dwarf::DW_TAG_structure_type
|| CTy
->isForwardDecl())
964 // Visit all struct members to ensure pointee type is visited
965 const DINodeArray Elements
= CTy
->getElements();
966 for (const auto *Element
: Elements
) {
967 const auto *MemberType
= cast
<DIDerivedType
>(Element
);
968 visitTypeEntry(MemberType
->getBaseType());
971 // Visit this type, struct or a const/typedef/volatile/restrict type
972 visitTypeEntry(OrigTy
, TypeId
, false, false);
975 /// Read file contents from the actual file or from the source
976 std::string
BTFDebug::populateFileContent(const DISubprogram
*SP
) {
977 auto File
= SP
->getFile();
978 std::string FileName
;
980 if (!File
->getFilename().starts_with("/") && File
->getDirectory().size())
981 FileName
= File
->getDirectory().str() + "/" + File
->getFilename().str();
983 FileName
= std::string(File
->getFilename());
985 // No need to populate the contends if it has been populated!
986 if (FileContent
.contains(FileName
))
989 std::vector
<std::string
> Content
;
991 Content
.push_back(Line
); // Line 0 for empty string
993 std::unique_ptr
<MemoryBuffer
> Buf
;
994 auto Source
= File
->getSource();
996 Buf
= MemoryBuffer::getMemBufferCopy(*Source
);
997 else if (ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
998 MemoryBuffer::getFile(FileName
))
999 Buf
= std::move(*BufOrErr
);
1001 for (line_iterator
I(*Buf
, false), E
; I
!= E
; ++I
)
1002 Content
.push_back(std::string(*I
));
1004 FileContent
[FileName
] = Content
;
1008 void BTFDebug::constructLineInfo(const DISubprogram
*SP
, MCSymbol
*Label
,
1009 uint32_t Line
, uint32_t Column
) {
1010 std::string FileName
= populateFileContent(SP
);
1011 BTFLineInfo LineInfo
;
1013 LineInfo
.Label
= Label
;
1014 LineInfo
.FileNameOff
= addString(FileName
);
1015 // If file content is not available, let LineOff = 0.
1016 if (Line
< FileContent
[FileName
].size())
1017 LineInfo
.LineOff
= addString(FileContent
[FileName
][Line
]);
1019 LineInfo
.LineOff
= 0;
1020 LineInfo
.LineNum
= Line
;
1021 LineInfo
.ColumnNum
= Column
;
1022 LineInfoTable
[SecNameOff
].push_back(LineInfo
);
1025 void BTFDebug::emitCommonHeader() {
1026 OS
.AddComment("0x" + Twine::utohexstr(BTF::MAGIC
));
1027 OS
.emitIntValue(BTF::MAGIC
, 2);
1028 OS
.emitInt8(BTF::VERSION
);
1032 void BTFDebug::emitBTFSection() {
1033 // Do not emit section if no types and only "" string.
1034 if (!TypeEntries
.size() && StringTable
.getSize() == 1)
1037 MCContext
&Ctx
= OS
.getContext();
1038 MCSectionELF
*Sec
= Ctx
.getELFSection(".BTF", ELF::SHT_PROGBITS
, 0);
1039 Sec
->setAlignment(Align(4));
1040 OS
.switchSection(Sec
);
1044 OS
.emitInt32(BTF::HeaderSize
);
1046 uint32_t TypeLen
= 0, StrLen
;
1047 for (const auto &TypeEntry
: TypeEntries
)
1048 TypeLen
+= TypeEntry
->getSize();
1049 StrLen
= StringTable
.getSize();
1052 OS
.emitInt32(TypeLen
);
1053 OS
.emitInt32(TypeLen
);
1054 OS
.emitInt32(StrLen
);
1057 for (const auto &TypeEntry
: TypeEntries
)
1058 TypeEntry
->emitType(OS
);
1060 // Emit string table.
1061 uint32_t StringOffset
= 0;
1062 for (const auto &S
: StringTable
.getTable()) {
1063 OS
.AddComment("string offset=" + std::to_string(StringOffset
));
1065 OS
.emitBytes(StringRef("\0", 1));
1066 StringOffset
+= S
.size() + 1;
1070 void BTFDebug::emitBTFExtSection() {
1071 // Do not emit section if empty FuncInfoTable and LineInfoTable
1072 // and FieldRelocTable.
1073 if (!FuncInfoTable
.size() && !LineInfoTable
.size() &&
1074 !FieldRelocTable
.size())
1077 MCContext
&Ctx
= OS
.getContext();
1078 MCSectionELF
*Sec
= Ctx
.getELFSection(".BTF.ext", ELF::SHT_PROGBITS
, 0);
1079 Sec
->setAlignment(Align(4));
1080 OS
.switchSection(Sec
);
1084 OS
.emitInt32(BTF::ExtHeaderSize
);
1086 // Account for FuncInfo/LineInfo record size as well.
1087 uint32_t FuncLen
= 4, LineLen
= 4;
1088 // Do not account for optional FieldReloc.
1089 uint32_t FieldRelocLen
= 0;
1090 for (const auto &FuncSec
: FuncInfoTable
) {
1091 FuncLen
+= BTF::SecFuncInfoSize
;
1092 FuncLen
+= FuncSec
.second
.size() * BTF::BPFFuncInfoSize
;
1094 for (const auto &LineSec
: LineInfoTable
) {
1095 LineLen
+= BTF::SecLineInfoSize
;
1096 LineLen
+= LineSec
.second
.size() * BTF::BPFLineInfoSize
;
1098 for (const auto &FieldRelocSec
: FieldRelocTable
) {
1099 FieldRelocLen
+= BTF::SecFieldRelocSize
;
1100 FieldRelocLen
+= FieldRelocSec
.second
.size() * BTF::BPFFieldRelocSize
;
1107 OS
.emitInt32(FuncLen
);
1108 OS
.emitInt32(FuncLen
);
1109 OS
.emitInt32(LineLen
);
1110 OS
.emitInt32(FuncLen
+ LineLen
);
1111 OS
.emitInt32(FieldRelocLen
);
1113 // Emit func_info table.
1114 OS
.AddComment("FuncInfo");
1115 OS
.emitInt32(BTF::BPFFuncInfoSize
);
1116 for (const auto &FuncSec
: FuncInfoTable
) {
1117 OS
.AddComment("FuncInfo section string offset=" +
1118 std::to_string(FuncSec
.first
));
1119 OS
.emitInt32(FuncSec
.first
);
1120 OS
.emitInt32(FuncSec
.second
.size());
1121 for (const auto &FuncInfo
: FuncSec
.second
) {
1122 Asm
->emitLabelReference(FuncInfo
.Label
, 4);
1123 OS
.emitInt32(FuncInfo
.TypeId
);
1127 // Emit line_info table.
1128 OS
.AddComment("LineInfo");
1129 OS
.emitInt32(BTF::BPFLineInfoSize
);
1130 for (const auto &LineSec
: LineInfoTable
) {
1131 OS
.AddComment("LineInfo section string offset=" +
1132 std::to_string(LineSec
.first
));
1133 OS
.emitInt32(LineSec
.first
);
1134 OS
.emitInt32(LineSec
.second
.size());
1135 for (const auto &LineInfo
: LineSec
.second
) {
1136 Asm
->emitLabelReference(LineInfo
.Label
, 4);
1137 OS
.emitInt32(LineInfo
.FileNameOff
);
1138 OS
.emitInt32(LineInfo
.LineOff
);
1139 OS
.AddComment("Line " + std::to_string(LineInfo
.LineNum
) + " Col " +
1140 std::to_string(LineInfo
.ColumnNum
));
1141 OS
.emitInt32(LineInfo
.LineNum
<< 10 | LineInfo
.ColumnNum
);
1145 // Emit field reloc table.
1146 if (FieldRelocLen
) {
1147 OS
.AddComment("FieldReloc");
1148 OS
.emitInt32(BTF::BPFFieldRelocSize
);
1149 for (const auto &FieldRelocSec
: FieldRelocTable
) {
1150 OS
.AddComment("Field reloc section string offset=" +
1151 std::to_string(FieldRelocSec
.first
));
1152 OS
.emitInt32(FieldRelocSec
.first
);
1153 OS
.emitInt32(FieldRelocSec
.second
.size());
1154 for (const auto &FieldRelocInfo
: FieldRelocSec
.second
) {
1155 Asm
->emitLabelReference(FieldRelocInfo
.Label
, 4);
1156 OS
.emitInt32(FieldRelocInfo
.TypeID
);
1157 OS
.emitInt32(FieldRelocInfo
.OffsetNameOff
);
1158 OS
.emitInt32(FieldRelocInfo
.RelocKind
);
1164 void BTFDebug::beginFunctionImpl(const MachineFunction
*MF
) {
1165 auto *SP
= MF
->getFunction().getSubprogram();
1166 auto *Unit
= SP
->getUnit();
1168 if (Unit
->getEmissionKind() == DICompileUnit::NoDebug
) {
1169 SkipInstruction
= true;
1172 SkipInstruction
= false;
1174 // Collect MapDef types. Map definition needs to collect
1175 // pointee types. Do it first. Otherwise, for the following
1181 // foo(struct t *arg);
1187 // } __attribute__((section(".maps"))) hash_map;
1189 // If subroutine foo is traversed first, a type chain
1190 // "ptr->struct m(fwd)" will be created and later on
1191 // when traversing mapdef, since "ptr->struct m" exists,
1192 // the traversal of "struct m" will be omitted.
1193 if (MapDefNotCollected
) {
1194 processGlobals(true);
1195 MapDefNotCollected
= false;
1198 // Collect all types locally referenced in this function.
1199 // Use RetainedNodes so we can collect all argument names
1200 // even if the argument is not used.
1201 std::unordered_map
<uint32_t, StringRef
> FuncArgNames
;
1202 for (const DINode
*DN
: SP
->getRetainedNodes()) {
1203 if (const auto *DV
= dyn_cast
<DILocalVariable
>(DN
)) {
1204 // Collect function arguments for subprogram func type.
1205 uint32_t Arg
= DV
->getArg();
1207 visitTypeEntry(DV
->getType());
1208 FuncArgNames
[Arg
] = DV
->getName();
1213 // Construct subprogram func proto type.
1214 uint32_t ProtoTypeId
;
1215 visitSubroutineType(SP
->getType(), true, FuncArgNames
, ProtoTypeId
);
1217 // Construct subprogram func type
1218 uint8_t Scope
= SP
->isLocalToUnit() ? BTF::FUNC_STATIC
: BTF::FUNC_GLOBAL
;
1219 uint32_t FuncTypeId
= processDISubprogram(SP
, ProtoTypeId
, Scope
);
1221 for (const auto &TypeEntry
: TypeEntries
)
1222 TypeEntry
->completeType(*this);
1224 // Construct funcinfo and the first lineinfo for the function.
1225 MCSymbol
*FuncLabel
= Asm
->getFunctionBegin();
1226 BTFFuncInfo FuncInfo
;
1227 FuncInfo
.Label
= FuncLabel
;
1228 FuncInfo
.TypeId
= FuncTypeId
;
1229 if (FuncLabel
->isInSection()) {
1230 MCSection
&Section
= FuncLabel
->getSection();
1231 const MCSectionELF
*SectionELF
= dyn_cast
<MCSectionELF
>(&Section
);
1232 assert(SectionELF
&& "Null section for Function Label");
1233 SecNameOff
= addString(SectionELF
->getName());
1235 SecNameOff
= addString(".text");
1237 FuncInfoTable
[SecNameOff
].push_back(FuncInfo
);
1240 void BTFDebug::endFunctionImpl(const MachineFunction
*MF
) {
1241 SkipInstruction
= false;
1242 LineInfoGenerated
= false;
1246 /// On-demand populate types as requested from abstract member
1247 /// accessing or preserve debuginfo type.
1248 unsigned BTFDebug::populateType(const DIType
*Ty
) {
1250 visitTypeEntry(Ty
, Id
, false, false);
1251 for (const auto &TypeEntry
: TypeEntries
)
1252 TypeEntry
->completeType(*this);
1256 /// Generate a struct member field relocation.
1257 void BTFDebug::generatePatchImmReloc(const MCSymbol
*ORSym
, uint32_t RootId
,
1258 const GlobalVariable
*GVar
, bool IsAma
) {
1259 BTFFieldReloc FieldReloc
;
1260 FieldReloc
.Label
= ORSym
;
1261 FieldReloc
.TypeID
= RootId
;
1263 StringRef AccessPattern
= GVar
->getName();
1264 size_t FirstDollar
= AccessPattern
.find_first_of('$');
1266 size_t FirstColon
= AccessPattern
.find_first_of(':');
1267 size_t SecondColon
= AccessPattern
.find_first_of(':', FirstColon
+ 1);
1268 StringRef IndexPattern
= AccessPattern
.substr(FirstDollar
+ 1);
1269 StringRef RelocKindStr
= AccessPattern
.substr(FirstColon
+ 1,
1270 SecondColon
- FirstColon
);
1271 StringRef PatchImmStr
= AccessPattern
.substr(SecondColon
+ 1,
1272 FirstDollar
- SecondColon
);
1274 FieldReloc
.OffsetNameOff
= addString(IndexPattern
);
1275 FieldReloc
.RelocKind
= std::stoull(std::string(RelocKindStr
));
1276 PatchImms
[GVar
] = std::make_pair(std::stoll(std::string(PatchImmStr
)),
1277 FieldReloc
.RelocKind
);
1279 StringRef RelocStr
= AccessPattern
.substr(FirstDollar
+ 1);
1280 FieldReloc
.OffsetNameOff
= addString("0");
1281 FieldReloc
.RelocKind
= std::stoull(std::string(RelocStr
));
1282 PatchImms
[GVar
] = std::make_pair(RootId
, FieldReloc
.RelocKind
);
1284 FieldRelocTable
[SecNameOff
].push_back(FieldReloc
);
1287 void BTFDebug::processGlobalValue(const MachineOperand
&MO
) {
1288 // check whether this is a candidate or not
1289 if (MO
.isGlobal()) {
1290 const GlobalValue
*GVal
= MO
.getGlobal();
1291 auto *GVar
= dyn_cast
<GlobalVariable
>(GVal
);
1293 // Not a global variable. Maybe an extern function reference.
1294 processFuncPrototypes(dyn_cast
<Function
>(GVal
));
1298 if (!GVar
->hasAttribute(BPFCoreSharedInfo::AmaAttr
) &&
1299 !GVar
->hasAttribute(BPFCoreSharedInfo::TypeIdAttr
))
1302 MCSymbol
*ORSym
= OS
.getContext().createTempSymbol();
1303 OS
.emitLabel(ORSym
);
1305 MDNode
*MDN
= GVar
->getMetadata(LLVMContext::MD_preserve_access_index
);
1306 uint32_t RootId
= populateType(dyn_cast
<DIType
>(MDN
));
1307 generatePatchImmReloc(ORSym
, RootId
, GVar
,
1308 GVar
->hasAttribute(BPFCoreSharedInfo::AmaAttr
));
1312 void BTFDebug::beginInstruction(const MachineInstr
*MI
) {
1313 DebugHandlerBase::beginInstruction(MI
);
1315 if (SkipInstruction
|| MI
->isMetaInstruction() ||
1316 MI
->getFlag(MachineInstr::FrameSetup
))
1319 if (MI
->isInlineAsm()) {
1320 // Count the number of register definitions to find the asm string.
1321 unsigned NumDefs
= 0;
1323 const MachineOperand
&MO
= MI
->getOperand(NumDefs
);
1324 if (MO
.isReg() && MO
.isDef()) {
1328 // Skip this inline asm instruction if the asmstr is empty.
1329 const char *AsmStr
= MO
.getSymbolName();
1336 if (MI
->getOpcode() == BPF::LD_imm64
) {
1337 // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
1338 // add this insn into the .BTF.ext FieldReloc subsection.
1339 // Relocation looks like:
1345 // Later, the insn is replaced with "r2 = <offset>"
1346 // where "<offset>" equals to the offset based on current
1347 // type definitions.
1349 // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
1350 // The LD_imm64 result will be replaced with a btf type id.
1351 processGlobalValue(MI
->getOperand(1));
1352 } else if (MI
->getOpcode() == BPF::CORE_LD64
||
1353 MI
->getOpcode() == BPF::CORE_LD32
||
1354 MI
->getOpcode() == BPF::CORE_ST
||
1355 MI
->getOpcode() == BPF::CORE_SHIFT
) {
1356 // relocation insn is a load, store or shift insn.
1357 processGlobalValue(MI
->getOperand(3));
1358 } else if (MI
->getOpcode() == BPF::JAL
) {
1359 // check extern function references
1360 const MachineOperand
&MO
= MI
->getOperand(0);
1361 if (MO
.isGlobal()) {
1362 processFuncPrototypes(dyn_cast
<Function
>(MO
.getGlobal()));
1366 if (!CurMI
) // no debug info
1369 // Skip this instruction if no DebugLoc or the DebugLoc
1370 // is the same as the previous instruction.
1371 const DebugLoc
&DL
= MI
->getDebugLoc();
1372 if (!DL
|| PrevInstLoc
== DL
) {
1373 // This instruction will be skipped, no LineInfo has
1374 // been generated, construct one based on function signature.
1375 if (LineInfoGenerated
== false) {
1376 auto *S
= MI
->getMF()->getFunction().getSubprogram();
1379 MCSymbol
*FuncLabel
= Asm
->getFunctionBegin();
1380 constructLineInfo(S
, FuncLabel
, S
->getLine(), 0);
1381 LineInfoGenerated
= true;
1387 // Create a temporary label to remember the insn for lineinfo.
1388 MCSymbol
*LineSym
= OS
.getContext().createTempSymbol();
1389 OS
.emitLabel(LineSym
);
1391 // Construct the lineinfo.
1392 auto SP
= DL
->getScope()->getSubprogram();
1393 constructLineInfo(SP
, LineSym
, DL
.getLine(), DL
.getCol());
1395 LineInfoGenerated
= true;
1399 void BTFDebug::processGlobals(bool ProcessingMapDef
) {
1400 // Collect all types referenced by globals.
1401 const Module
*M
= MMI
->getModule();
1402 for (const GlobalVariable
&Global
: M
->globals()) {
1403 // Decide the section name.
1405 std::optional
<SectionKind
> GVKind
;
1407 if (!Global
.isDeclarationForLinker())
1408 GVKind
= TargetLoweringObjectFile::getKindForGlobal(&Global
, Asm
->TM
);
1410 if (Global
.isDeclarationForLinker())
1411 SecName
= Global
.hasSection() ? Global
.getSection() : "";
1412 else if (GVKind
->isCommon())
1415 TargetLoweringObjectFile
*TLOF
= Asm
->TM
.getObjFileLowering();
1416 MCSection
*Sec
= TLOF
->SectionForGlobal(&Global
, Asm
->TM
);
1417 SecName
= Sec
->getName();
1420 if (ProcessingMapDef
!= SecName
.starts_with(".maps"))
1423 // Create a .rodata datasec if the global variable is an initialized
1424 // constant with private linkage and if it won't be in .rodata.str<#>
1425 // and .rodata.cst<#> sections.
1426 if (SecName
== ".rodata" && Global
.hasPrivateLinkage() &&
1427 DataSecEntries
.find(std::string(SecName
)) == DataSecEntries
.end()) {
1428 // skip .rodata.str<#> and .rodata.cst<#> sections
1429 if (!GVKind
->isMergeableCString() && !GVKind
->isMergeableConst()) {
1430 DataSecEntries
[std::string(SecName
)] =
1431 std::make_unique
<BTFKindDataSec
>(Asm
, std::string(SecName
));
1435 SmallVector
<DIGlobalVariableExpression
*, 1> GVs
;
1436 Global
.getDebugInfo(GVs
);
1438 // No type information, mostly internal, skip it.
1439 if (GVs
.size() == 0)
1442 uint32_t GVTypeId
= 0;
1443 DIGlobalVariable
*DIGlobal
= nullptr;
1444 for (auto *GVE
: GVs
) {
1445 DIGlobal
= GVE
->getVariable();
1446 if (SecName
.starts_with(".maps"))
1447 visitMapDefType(DIGlobal
->getType(), GVTypeId
);
1449 visitTypeEntry(DIGlobal
->getType(), GVTypeId
, false, false);
1453 // Only support the following globals:
1454 // . static variables
1455 // . non-static weak or non-weak global variables
1456 // . weak or non-weak extern global variables
1457 // Whether DataSec is readonly or not can be found from corresponding ELF
1458 // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1459 // can be found from the corresponding ELF symbol table.
1460 auto Linkage
= Global
.getLinkage();
1461 if (Linkage
!= GlobalValue::InternalLinkage
&&
1462 Linkage
!= GlobalValue::ExternalLinkage
&&
1463 Linkage
!= GlobalValue::WeakAnyLinkage
&&
1464 Linkage
!= GlobalValue::WeakODRLinkage
&&
1465 Linkage
!= GlobalValue::ExternalWeakLinkage
)
1469 if (Linkage
== GlobalValue::InternalLinkage
) {
1470 GVarInfo
= BTF::VAR_STATIC
;
1471 } else if (Global
.hasInitializer()) {
1472 GVarInfo
= BTF::VAR_GLOBAL_ALLOCATED
;
1474 GVarInfo
= BTF::VAR_GLOBAL_EXTERNAL
;
1478 std::make_unique
<BTFKindVar
>(Global
.getName(), GVTypeId
, GVarInfo
);
1479 uint32_t VarId
= addType(std::move(VarEntry
));
1481 processDeclAnnotations(DIGlobal
->getAnnotations(), VarId
, -1);
1483 // An empty SecName means an extern variable without section attribute.
1484 if (SecName
.empty())
1487 // Find or create a DataSec
1488 if (DataSecEntries
.find(std::string(SecName
)) == DataSecEntries
.end()) {
1489 DataSecEntries
[std::string(SecName
)] =
1490 std::make_unique
<BTFKindDataSec
>(Asm
, std::string(SecName
));
1493 // Calculate symbol size
1494 const DataLayout
&DL
= Global
.getParent()->getDataLayout();
1495 uint32_t Size
= DL
.getTypeAllocSize(Global
.getValueType());
1497 DataSecEntries
[std::string(SecName
)]->addDataSecEntry(VarId
,
1498 Asm
->getSymbol(&Global
), Size
);
1502 /// Emit proper patchable instructions.
1503 bool BTFDebug::InstLower(const MachineInstr
*MI
, MCInst
&OutMI
) {
1504 if (MI
->getOpcode() == BPF::LD_imm64
) {
1505 const MachineOperand
&MO
= MI
->getOperand(1);
1506 if (MO
.isGlobal()) {
1507 const GlobalValue
*GVal
= MO
.getGlobal();
1508 auto *GVar
= dyn_cast
<GlobalVariable
>(GVal
);
1510 // Emit "mov ri, <imm>"
1513 if (GVar
->hasAttribute(BPFCoreSharedInfo::AmaAttr
) ||
1514 GVar
->hasAttribute(BPFCoreSharedInfo::TypeIdAttr
)) {
1515 Imm
= PatchImms
[GVar
].first
;
1516 Reloc
= PatchImms
[GVar
].second
;
1521 if (Reloc
== BTF::ENUM_VALUE_EXISTENCE
|| Reloc
== BTF::ENUM_VALUE
||
1522 Reloc
== BTF::BTF_TYPE_ID_LOCAL
|| Reloc
== BTF::BTF_TYPE_ID_REMOTE
)
1523 OutMI
.setOpcode(BPF::LD_imm64
);
1525 OutMI
.setOpcode(BPF::MOV_ri
);
1526 OutMI
.addOperand(MCOperand::createReg(MI
->getOperand(0).getReg()));
1527 OutMI
.addOperand(MCOperand::createImm(Imm
));
1531 } else if (MI
->getOpcode() == BPF::CORE_LD64
||
1532 MI
->getOpcode() == BPF::CORE_LD32
||
1533 MI
->getOpcode() == BPF::CORE_ST
||
1534 MI
->getOpcode() == BPF::CORE_SHIFT
) {
1535 const MachineOperand
&MO
= MI
->getOperand(3);
1536 if (MO
.isGlobal()) {
1537 const GlobalValue
*GVal
= MO
.getGlobal();
1538 auto *GVar
= dyn_cast
<GlobalVariable
>(GVal
);
1539 if (GVar
&& GVar
->hasAttribute(BPFCoreSharedInfo::AmaAttr
)) {
1540 uint32_t Imm
= PatchImms
[GVar
].first
;
1541 OutMI
.setOpcode(MI
->getOperand(1).getImm());
1542 if (MI
->getOperand(0).isImm())
1543 OutMI
.addOperand(MCOperand::createImm(MI
->getOperand(0).getImm()));
1545 OutMI
.addOperand(MCOperand::createReg(MI
->getOperand(0).getReg()));
1546 OutMI
.addOperand(MCOperand::createReg(MI
->getOperand(2).getReg()));
1547 OutMI
.addOperand(MCOperand::createImm(Imm
));
1555 void BTFDebug::processFuncPrototypes(const Function
*F
) {
1559 const DISubprogram
*SP
= F
->getSubprogram();
1560 if (!SP
|| SP
->isDefinition())
1563 // Do not emit again if already emitted.
1564 if (!ProtoFunctions
.insert(F
).second
)
1567 uint32_t ProtoTypeId
;
1568 const std::unordered_map
<uint32_t, StringRef
> FuncArgNames
;
1569 visitSubroutineType(SP
->getType(), false, FuncArgNames
, ProtoTypeId
);
1570 uint32_t FuncId
= processDISubprogram(SP
, ProtoTypeId
, BTF::FUNC_EXTERN
);
1572 if (F
->hasSection()) {
1573 StringRef SecName
= F
->getSection();
1575 if (DataSecEntries
.find(std::string(SecName
)) == DataSecEntries
.end()) {
1576 DataSecEntries
[std::string(SecName
)] =
1577 std::make_unique
<BTFKindDataSec
>(Asm
, std::string(SecName
));
1580 // We really don't know func size, set it to 0.
1581 DataSecEntries
[std::string(SecName
)]->addDataSecEntry(FuncId
,
1582 Asm
->getSymbol(F
), 0);
1586 void BTFDebug::endModule() {
1587 // Collect MapDef globals if not collected yet.
1588 if (MapDefNotCollected
) {
1589 processGlobals(true);
1590 MapDefNotCollected
= false;
1593 // Collect global types/variables except MapDef globals.
1594 processGlobals(false);
1596 for (auto &DataSec
: DataSecEntries
)
1597 addType(std::move(DataSec
.second
));
1600 for (auto &Fixup
: FixupDerivedTypes
) {
1601 const DICompositeType
*CTy
= Fixup
.first
;
1602 StringRef TypeName
= CTy
->getName();
1603 bool IsUnion
= CTy
->getTag() == dwarf::DW_TAG_union_type
;
1605 // Search through struct types
1606 uint32_t StructTypeId
= 0;
1607 for (const auto &StructType
: StructTypes
) {
1608 if (StructType
->getName() == TypeName
) {
1609 StructTypeId
= StructType
->getId();
1614 if (StructTypeId
== 0) {
1615 auto FwdTypeEntry
= std::make_unique
<BTFTypeFwd
>(TypeName
, IsUnion
);
1616 StructTypeId
= addType(std::move(FwdTypeEntry
));
1619 for (auto &TypeInfo
: Fixup
.second
) {
1620 const DIDerivedType
*DTy
= TypeInfo
.first
;
1621 BTFTypeDerived
*BDType
= TypeInfo
.second
;
1623 int TmpTypeId
= genBTFTypeTags(DTy
, StructTypeId
);
1625 BDType
->setPointeeType(TmpTypeId
);
1627 BDType
->setPointeeType(StructTypeId
);
1631 // Complete BTF type cross refereences.
1632 for (const auto &TypeEntry
: TypeEntries
)
1633 TypeEntry
->completeType(*this);
1635 // Emit BTF sections.
1637 emitBTFExtSection();