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