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"
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/MC/MCContext.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCSectionELF.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/Support/LineIterator.h"
25 #include "llvm/Target/TargetLoweringObjectFile.h"
26 
27 using namespace llvm;
28 
29 static const char *BTFKindStr[] = {
30 #define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
31 #include "BTF.def"
32 };
33 
34 /// Emit a BTF common type.
35 void BTFTypeBase::emitType(MCStreamer &OS) {
36   OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
37                 ")");
38   OS.emitInt32(BTFType.NameOff);
39   OS.AddComment("0x" + Twine::utohexstr(BTFType.Info));
40   OS.emitInt32(BTFType.Info);
41   OS.emitInt32(BTFType.Size);
42 }
43 
44 BTFTypeDerived::BTFTypeDerived(const DIDerivedType *DTy, unsigned Tag,
45                                bool NeedsFixup)
46     : DTy(DTy), NeedsFixup(NeedsFixup) {
47   switch (Tag) {
48   case dwarf::DW_TAG_pointer_type:
49     Kind = BTF::BTF_KIND_PTR;
50     break;
51   case dwarf::DW_TAG_const_type:
52     Kind = BTF::BTF_KIND_CONST;
53     break;
54   case dwarf::DW_TAG_volatile_type:
55     Kind = BTF::BTF_KIND_VOLATILE;
56     break;
57   case dwarf::DW_TAG_typedef:
58     Kind = BTF::BTF_KIND_TYPEDEF;
59     break;
60   case dwarf::DW_TAG_restrict_type:
61     Kind = BTF::BTF_KIND_RESTRICT;
62     break;
63   default:
64     llvm_unreachable("Unknown DIDerivedType Tag");
65   }
66   BTFType.Info = Kind << 24;
67 }
68 
69 void BTFTypeDerived::completeType(BTFDebug &BDebug) {
70   if (IsCompleted)
71     return;
72   IsCompleted = true;
73 
74   BTFType.NameOff = BDebug.addString(DTy->getName());
75 
76   if (NeedsFixup)
77     return;
78 
79   // The base type for PTR/CONST/VOLATILE could be void.
80   const DIType *ResolvedType = DTy->getBaseType();
81   if (!ResolvedType) {
82     assert((Kind == BTF::BTF_KIND_PTR || Kind == BTF::BTF_KIND_CONST ||
83             Kind == BTF::BTF_KIND_VOLATILE) &&
84            "Invalid null basetype");
85     BTFType.Type = 0;
86   } else {
87     BTFType.Type = BDebug.getTypeId(ResolvedType);
88   }
89 }
90 
91 void BTFTypeDerived::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
92 
93 void BTFTypeDerived::setPointeeType(uint32_t PointeeType) {
94   BTFType.Type = PointeeType;
95 }
96 
97 /// Represent a struct/union forward declaration.
98 BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) {
99   Kind = BTF::BTF_KIND_FWD;
100   BTFType.Info = IsUnion << 31 | Kind << 24;
101   BTFType.Type = 0;
102 }
103 
104 void BTFTypeFwd::completeType(BTFDebug &BDebug) {
105   if (IsCompleted)
106     return;
107   IsCompleted = true;
108 
109   BTFType.NameOff = BDebug.addString(Name);
110 }
111 
112 void BTFTypeFwd::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
113 
114 BTFTypeInt::BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits,
115                        uint32_t OffsetInBits, StringRef TypeName)
116     : Name(TypeName) {
117   // Translate IR int encoding to BTF int encoding.
118   uint8_t BTFEncoding;
119   switch (Encoding) {
120   case dwarf::DW_ATE_boolean:
121     BTFEncoding = BTF::INT_BOOL;
122     break;
123   case dwarf::DW_ATE_signed:
124   case dwarf::DW_ATE_signed_char:
125     BTFEncoding = BTF::INT_SIGNED;
126     break;
127   case dwarf::DW_ATE_unsigned:
128   case dwarf::DW_ATE_unsigned_char:
129     BTFEncoding = 0;
130     break;
131   default:
132     llvm_unreachable("Unknown BTFTypeInt Encoding");
133   }
134 
135   Kind = BTF::BTF_KIND_INT;
136   BTFType.Info = Kind << 24;
137   BTFType.Size = roundupToBytes(SizeInBits);
138   IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits;
139 }
140 
141 void BTFTypeInt::completeType(BTFDebug &BDebug) {
142   if (IsCompleted)
143     return;
144   IsCompleted = true;
145 
146   BTFType.NameOff = BDebug.addString(Name);
147 }
148 
149 void BTFTypeInt::emitType(MCStreamer &OS) {
150   BTFTypeBase::emitType(OS);
151   OS.AddComment("0x" + Twine::utohexstr(IntVal));
152   OS.emitInt32(IntVal);
153 }
154 
155 BTFTypeEnum::BTFTypeEnum(const DICompositeType *ETy, uint32_t VLen) : ETy(ETy) {
156   Kind = BTF::BTF_KIND_ENUM;
157   BTFType.Info = Kind << 24 | VLen;
158   BTFType.Size = roundupToBytes(ETy->getSizeInBits());
159 }
160 
161 void BTFTypeEnum::completeType(BTFDebug &BDebug) {
162   if (IsCompleted)
163     return;
164   IsCompleted = true;
165 
166   BTFType.NameOff = BDebug.addString(ETy->getName());
167 
168   DINodeArray Elements = ETy->getElements();
169   for (const auto Element : Elements) {
170     const auto *Enum = cast<DIEnumerator>(Element);
171 
172     struct BTF::BTFEnum BTFEnum;
173     BTFEnum.NameOff = BDebug.addString(Enum->getName());
174     // BTF enum value is 32bit, enforce it.
175     uint32_t Value;
176     if (Enum->isUnsigned())
177       Value = static_cast<uint32_t>(Enum->getValue().getZExtValue());
178     else
179       Value = static_cast<uint32_t>(Enum->getValue().getSExtValue());
180     BTFEnum.Val = Value;
181     EnumValues.push_back(BTFEnum);
182   }
183 }
184 
185 void BTFTypeEnum::emitType(MCStreamer &OS) {
186   BTFTypeBase::emitType(OS);
187   for (const auto &Enum : EnumValues) {
188     OS.emitInt32(Enum.NameOff);
189     OS.emitInt32(Enum.Val);
190   }
191 }
192 
193 BTFTypeArray::BTFTypeArray(uint32_t ElemTypeId, uint32_t NumElems) {
194   Kind = BTF::BTF_KIND_ARRAY;
195   BTFType.NameOff = 0;
196   BTFType.Info = Kind << 24;
197   BTFType.Size = 0;
198 
199   ArrayInfo.ElemType = ElemTypeId;
200   ArrayInfo.Nelems = NumElems;
201 }
202 
203 /// Represent a BTF array.
204 void BTFTypeArray::completeType(BTFDebug &BDebug) {
205   if (IsCompleted)
206     return;
207   IsCompleted = true;
208 
209   // The IR does not really have a type for the index.
210   // A special type for array index should have been
211   // created during initial type traversal. Just
212   // retrieve that type id.
213   ArrayInfo.IndexType = BDebug.getArrayIndexTypeId();
214 }
215 
216 void BTFTypeArray::emitType(MCStreamer &OS) {
217   BTFTypeBase::emitType(OS);
218   OS.emitInt32(ArrayInfo.ElemType);
219   OS.emitInt32(ArrayInfo.IndexType);
220   OS.emitInt32(ArrayInfo.Nelems);
221 }
222 
223 /// Represent either a struct or a union.
224 BTFTypeStruct::BTFTypeStruct(const DICompositeType *STy, bool IsStruct,
225                              bool HasBitField, uint32_t Vlen)
226     : STy(STy), HasBitField(HasBitField) {
227   Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
228   BTFType.Size = roundupToBytes(STy->getSizeInBits());
229   BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
230 }
231 
232 void BTFTypeStruct::completeType(BTFDebug &BDebug) {
233   if (IsCompleted)
234     return;
235   IsCompleted = true;
236 
237   BTFType.NameOff = BDebug.addString(STy->getName());
238 
239   // Add struct/union members.
240   const DINodeArray Elements = STy->getElements();
241   for (const auto *Element : Elements) {
242     struct BTF::BTFMember BTFMember;
243     const auto *DDTy = cast<DIDerivedType>(Element);
244 
245     BTFMember.NameOff = BDebug.addString(DDTy->getName());
246     if (HasBitField) {
247       uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0;
248       BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits();
249     } else {
250       BTFMember.Offset = DDTy->getOffsetInBits();
251     }
252     const auto *BaseTy = DDTy->getBaseType();
253     BTFMember.Type = BDebug.getTypeId(BaseTy);
254     Members.push_back(BTFMember);
255   }
256 }
257 
258 void BTFTypeStruct::emitType(MCStreamer &OS) {
259   BTFTypeBase::emitType(OS);
260   for (const auto &Member : Members) {
261     OS.emitInt32(Member.NameOff);
262     OS.emitInt32(Member.Type);
263     OS.AddComment("0x" + Twine::utohexstr(Member.Offset));
264     OS.emitInt32(Member.Offset);
265   }
266 }
267 
268 std::string BTFTypeStruct::getName() { return std::string(STy->getName()); }
269 
270 /// The Func kind represents both subprogram and pointee of function
271 /// pointers. If the FuncName is empty, it represents a pointee of function
272 /// pointer. Otherwise, it represents a subprogram. The func arg names
273 /// are empty for pointee of function pointer case, and are valid names
274 /// for subprogram.
275 BTFTypeFuncProto::BTFTypeFuncProto(
276     const DISubroutineType *STy, uint32_t VLen,
277     const std::unordered_map<uint32_t, StringRef> &FuncArgNames)
278     : STy(STy), FuncArgNames(FuncArgNames) {
279   Kind = BTF::BTF_KIND_FUNC_PROTO;
280   BTFType.Info = (Kind << 24) | VLen;
281 }
282 
283 void BTFTypeFuncProto::completeType(BTFDebug &BDebug) {
284   if (IsCompleted)
285     return;
286   IsCompleted = true;
287 
288   DITypeRefArray Elements = STy->getTypeArray();
289   auto RetType = Elements[0];
290   BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
291   BTFType.NameOff = 0;
292 
293   // For null parameter which is typically the last one
294   // to represent the vararg, encode the NameOff/Type to be 0.
295   for (unsigned I = 1, N = Elements.size(); I < N; ++I) {
296     struct BTF::BTFParam Param;
297     auto Element = Elements[I];
298     if (Element) {
299       Param.NameOff = BDebug.addString(FuncArgNames[I]);
300       Param.Type = BDebug.getTypeId(Element);
301     } else {
302       Param.NameOff = 0;
303       Param.Type = 0;
304     }
305     Parameters.push_back(Param);
306   }
307 }
308 
309 void BTFTypeFuncProto::emitType(MCStreamer &OS) {
310   BTFTypeBase::emitType(OS);
311   for (const auto &Param : Parameters) {
312     OS.emitInt32(Param.NameOff);
313     OS.emitInt32(Param.Type);
314   }
315 }
316 
317 BTFTypeFunc::BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId,
318     uint32_t Scope)
319     : Name(FuncName) {
320   Kind = BTF::BTF_KIND_FUNC;
321   BTFType.Info = (Kind << 24) | Scope;
322   BTFType.Type = ProtoTypeId;
323 }
324 
325 void BTFTypeFunc::completeType(BTFDebug &BDebug) {
326   if (IsCompleted)
327     return;
328   IsCompleted = true;
329 
330   BTFType.NameOff = BDebug.addString(Name);
331 }
332 
333 void BTFTypeFunc::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
334 
335 BTFKindVar::BTFKindVar(StringRef VarName, uint32_t TypeId, uint32_t VarInfo)
336     : Name(VarName) {
337   Kind = BTF::BTF_KIND_VAR;
338   BTFType.Info = Kind << 24;
339   BTFType.Type = TypeId;
340   Info = VarInfo;
341 }
342 
343 void BTFKindVar::completeType(BTFDebug &BDebug) {
344   BTFType.NameOff = BDebug.addString(Name);
345 }
346 
347 void BTFKindVar::emitType(MCStreamer &OS) {
348   BTFTypeBase::emitType(OS);
349   OS.emitInt32(Info);
350 }
351 
352 BTFKindDataSec::BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
353     : Asm(AsmPrt), Name(SecName) {
354   Kind = BTF::BTF_KIND_DATASEC;
355   BTFType.Info = Kind << 24;
356   BTFType.Size = 0;
357 }
358 
359 void BTFKindDataSec::completeType(BTFDebug &BDebug) {
360   BTFType.NameOff = BDebug.addString(Name);
361   BTFType.Info |= Vars.size();
362 }
363 
364 void BTFKindDataSec::emitType(MCStreamer &OS) {
365   BTFTypeBase::emitType(OS);
366 
367   for (const auto &V : Vars) {
368     OS.emitInt32(std::get<0>(V));
369     Asm->emitLabelReference(std::get<1>(V), 4);
370     OS.emitInt32(std::get<2>(V));
371   }
372 }
373 
374 BTFTypeFloat::BTFTypeFloat(uint32_t SizeInBits, StringRef TypeName)
375     : Name(TypeName) {
376   Kind = BTF::BTF_KIND_FLOAT;
377   BTFType.Info = Kind << 24;
378   BTFType.Size = roundupToBytes(SizeInBits);
379 }
380 
381 void BTFTypeFloat::completeType(BTFDebug &BDebug) {
382   if (IsCompleted)
383     return;
384   IsCompleted = true;
385 
386   BTFType.NameOff = BDebug.addString(Name);
387 }
388 
389 BTFTypeDeclTag::BTFTypeDeclTag(uint32_t BaseTypeId, int ComponentIdx,
390                                StringRef Tag)
391     : Tag(Tag) {
392   Kind = BTF::BTF_KIND_DECL_TAG;
393   BTFType.Info = Kind << 24;
394   BTFType.Type = BaseTypeId;
395   Info = ComponentIdx;
396 }
397 
398 void BTFTypeDeclTag::completeType(BTFDebug &BDebug) {
399   if (IsCompleted)
400     return;
401   IsCompleted = true;
402 
403   BTFType.NameOff = BDebug.addString(Tag);
404 }
405 
406 void BTFTypeDeclTag::emitType(MCStreamer &OS) {
407   BTFTypeBase::emitType(OS);
408   OS.emitInt32(Info);
409 }
410 
411 uint32_t BTFStringTable::addString(StringRef S) {
412   // Check whether the string already exists.
413   for (auto &OffsetM : OffsetToIdMap) {
414     if (Table[OffsetM.second] == S)
415       return OffsetM.first;
416   }
417   // Not find, add to the string table.
418   uint32_t Offset = Size;
419   OffsetToIdMap[Offset] = Table.size();
420   Table.push_back(std::string(S));
421   Size += S.size() + 1;
422   return Offset;
423 }
424 
425 BTFDebug::BTFDebug(AsmPrinter *AP)
426     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
427       LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
428       MapDefNotCollected(true) {
429   addString("\0");
430 }
431 
432 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
433                            const DIType *Ty) {
434   TypeEntry->setId(TypeEntries.size() + 1);
435   uint32_t Id = TypeEntry->getId();
436   DIToIdMap[Ty] = Id;
437   TypeEntries.push_back(std::move(TypeEntry));
438   return Id;
439 }
440 
441 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
442   TypeEntry->setId(TypeEntries.size() + 1);
443   uint32_t Id = TypeEntry->getId();
444   TypeEntries.push_back(std::move(TypeEntry));
445   return Id;
446 }
447 
448 void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
449   // Only int and binary floating point types are supported in BTF.
450   uint32_t Encoding = BTy->getEncoding();
451   std::unique_ptr<BTFTypeBase> TypeEntry;
452   switch (Encoding) {
453   case dwarf::DW_ATE_boolean:
454   case dwarf::DW_ATE_signed:
455   case dwarf::DW_ATE_signed_char:
456   case dwarf::DW_ATE_unsigned:
457   case dwarf::DW_ATE_unsigned_char:
458     // Create a BTF type instance for this DIBasicType and put it into
459     // DIToIdMap for cross-type reference check.
460     TypeEntry = std::make_unique<BTFTypeInt>(
461         Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
462     break;
463   case dwarf::DW_ATE_float:
464     TypeEntry =
465         std::make_unique<BTFTypeFloat>(BTy->getSizeInBits(), BTy->getName());
466     break;
467   default:
468     return;
469   }
470 
471   TypeId = addType(std::move(TypeEntry), BTy);
472 }
473 
474 /// Handle subprogram or subroutine types.
475 void BTFDebug::visitSubroutineType(
476     const DISubroutineType *STy, bool ForSubprog,
477     const std::unordered_map<uint32_t, StringRef> &FuncArgNames,
478     uint32_t &TypeId) {
479   DITypeRefArray Elements = STy->getTypeArray();
480   uint32_t VLen = Elements.size() - 1;
481   if (VLen > BTF::MAX_VLEN)
482     return;
483 
484   // Subprogram has a valid non-zero-length name, and the pointee of
485   // a function pointer has an empty name. The subprogram type will
486   // not be added to DIToIdMap as it should not be referenced by
487   // any other types.
488   auto TypeEntry = std::make_unique<BTFTypeFuncProto>(STy, VLen, FuncArgNames);
489   if (ForSubprog)
490     TypeId = addType(std::move(TypeEntry)); // For subprogram
491   else
492     TypeId = addType(std::move(TypeEntry), STy); // For func ptr
493 
494   // Visit return type and func arg types.
495   for (const auto Element : Elements) {
496     visitTypeEntry(Element);
497   }
498 }
499 
500 void BTFDebug::processDeclAnnotations(DINodeArray Annotations,
501                                       uint32_t BaseTypeId,
502                                       int ComponentIdx) {
503   if (!Annotations)
504      return;
505 
506   for (const Metadata *Annotation : Annotations->operands()) {
507     const MDNode *MD = cast<MDNode>(Annotation);
508     const MDString *Name = cast<MDString>(MD->getOperand(0));
509     if (!Name->getString().equals("btf_decl_tag"))
510       continue;
511 
512     const MDString *Value = cast<MDString>(MD->getOperand(1));
513     auto TypeEntry = std::make_unique<BTFTypeDeclTag>(BaseTypeId, ComponentIdx,
514                                                       Value->getString());
515     addType(std::move(TypeEntry));
516   }
517 }
518 
519 /// Handle structure/union types.
520 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
521                                uint32_t &TypeId) {
522   const DINodeArray Elements = CTy->getElements();
523   uint32_t VLen = Elements.size();
524   if (VLen > BTF::MAX_VLEN)
525     return;
526 
527   // Check whether we have any bitfield members or not
528   bool HasBitField = false;
529   for (const auto *Element : Elements) {
530     auto E = cast<DIDerivedType>(Element);
531     if (E->isBitField()) {
532       HasBitField = true;
533       break;
534     }
535   }
536 
537   auto TypeEntry =
538       std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
539   StructTypes.push_back(TypeEntry.get());
540   TypeId = addType(std::move(TypeEntry), CTy);
541 
542   // Check struct/union annotations
543   processDeclAnnotations(CTy->getAnnotations(), TypeId, -1);
544 
545   // Visit all struct members.
546   int FieldNo = 0;
547   for (const auto *Element : Elements) {
548     const auto Elem = cast<DIDerivedType>(Element);
549     visitTypeEntry(Elem);
550     processDeclAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
551     FieldNo++;
552   }
553 }
554 
555 void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
556   // Visit array element type.
557   uint32_t ElemTypeId;
558   const DIType *ElemType = CTy->getBaseType();
559   visitTypeEntry(ElemType, ElemTypeId, false, false);
560 
561   // Visit array dimensions.
562   DINodeArray Elements = CTy->getElements();
563   for (int I = Elements.size() - 1; I >= 0; --I) {
564     if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
565       if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
566         const DISubrange *SR = cast<DISubrange>(Element);
567         auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
568         int64_t Count = CI->getSExtValue();
569 
570         // For struct s { int b; char c[]; }, the c[] will be represented
571         // as an array with Count = -1.
572         auto TypeEntry =
573             std::make_unique<BTFTypeArray>(ElemTypeId,
574                 Count >= 0 ? Count : 0);
575         if (I == 0)
576           ElemTypeId = addType(std::move(TypeEntry), CTy);
577         else
578           ElemTypeId = addType(std::move(TypeEntry));
579       }
580   }
581 
582   // The array TypeId is the type id of the outermost dimension.
583   TypeId = ElemTypeId;
584 
585   // The IR does not have a type for array index while BTF wants one.
586   // So create an array index type if there is none.
587   if (!ArrayIndexTypeId) {
588     auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
589                                                    0, "__ARRAY_SIZE_TYPE__");
590     ArrayIndexTypeId = addType(std::move(TypeEntry));
591   }
592 }
593 
594 void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
595   DINodeArray Elements = CTy->getElements();
596   uint32_t VLen = Elements.size();
597   if (VLen > BTF::MAX_VLEN)
598     return;
599 
600   auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen);
601   TypeId = addType(std::move(TypeEntry), CTy);
602   // No need to visit base type as BTF does not encode it.
603 }
604 
605 /// Handle structure/union forward declarations.
606 void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
607                                 uint32_t &TypeId) {
608   auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
609   TypeId = addType(std::move(TypeEntry), CTy);
610 }
611 
612 /// Handle structure, union, array and enumeration types.
613 void BTFDebug::visitCompositeType(const DICompositeType *CTy,
614                                   uint32_t &TypeId) {
615   auto Tag = CTy->getTag();
616   if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
617     // Handle forward declaration differently as it does not have members.
618     if (CTy->isForwardDecl())
619       visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
620     else
621       visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
622   } else if (Tag == dwarf::DW_TAG_array_type)
623     visitArrayType(CTy, TypeId);
624   else if (Tag == dwarf::DW_TAG_enumeration_type)
625     visitEnumType(CTy, TypeId);
626 }
627 
628 /// Handle pointer, typedef, const, volatile, restrict and member types.
629 void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
630                                 bool CheckPointer, bool SeenPointer) {
631   unsigned Tag = DTy->getTag();
632 
633   /// Try to avoid chasing pointees, esp. structure pointees which may
634   /// unnecessary bring in a lot of types.
635   if (CheckPointer && !SeenPointer) {
636     SeenPointer = Tag == dwarf::DW_TAG_pointer_type;
637   }
638 
639   if (CheckPointer && SeenPointer) {
640     const DIType *Base = DTy->getBaseType();
641     if (Base) {
642       if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
643         auto CTag = CTy->getTag();
644         if ((CTag == dwarf::DW_TAG_structure_type ||
645              CTag == dwarf::DW_TAG_union_type) &&
646             !CTy->getName().empty() && !CTy->isForwardDecl()) {
647           /// Find a candidate, generate a fixup. Later on the struct/union
648           /// pointee type will be replaced with either a real type or
649           /// a forward declaration.
650           auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
651           auto &Fixup = FixupDerivedTypes[CTy->getName()];
652           Fixup.first = CTag == dwarf::DW_TAG_union_type;
653           Fixup.second.push_back(TypeEntry.get());
654           TypeId = addType(std::move(TypeEntry), DTy);
655           return;
656         }
657       }
658     }
659   }
660 
661   if (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_typedef ||
662       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
663       Tag == dwarf::DW_TAG_restrict_type) {
664     auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
665     TypeId = addType(std::move(TypeEntry), DTy);
666     if (Tag == dwarf::DW_TAG_typedef)
667       processDeclAnnotations(DTy->getAnnotations(), TypeId, -1);
668   } else if (Tag != dwarf::DW_TAG_member) {
669     return;
670   }
671 
672   // Visit base type of pointer, typedef, const, volatile, restrict or
673   // struct/union member.
674   uint32_t TempTypeId = 0;
675   if (Tag == dwarf::DW_TAG_member)
676     visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
677   else
678     visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
679 }
680 
681 void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
682                               bool CheckPointer, bool SeenPointer) {
683   if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
684     TypeId = DIToIdMap[Ty];
685 
686     // To handle the case like the following:
687     //    struct t;
688     //    typedef struct t _t;
689     //    struct s1 { _t *c; };
690     //    int test1(struct s1 *arg) { ... }
691     //
692     //    struct t { int a; int b; };
693     //    struct s2 { _t c; }
694     //    int test2(struct s2 *arg) { ... }
695     //
696     // During traversing test1() argument, "_t" is recorded
697     // in DIToIdMap and a forward declaration fixup is created
698     // for "struct t" to avoid pointee type traversal.
699     //
700     // During traversing test2() argument, even if we see "_t" is
701     // already defined, we should keep moving to eventually
702     // bring in types for "struct t". Otherwise, the "struct s2"
703     // definition won't be correct.
704     if (Ty && (!CheckPointer || !SeenPointer)) {
705       if (const auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
706         unsigned Tag = DTy->getTag();
707         if (Tag == dwarf::DW_TAG_typedef || Tag == dwarf::DW_TAG_const_type ||
708             Tag == dwarf::DW_TAG_volatile_type ||
709             Tag == dwarf::DW_TAG_restrict_type) {
710           uint32_t TmpTypeId;
711           visitTypeEntry(DTy->getBaseType(), TmpTypeId, CheckPointer,
712                          SeenPointer);
713         }
714       }
715     }
716 
717     return;
718   }
719 
720   if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
721     visitBasicType(BTy, TypeId);
722   else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
723     visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(),
724                         TypeId);
725   else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
726     visitCompositeType(CTy, TypeId);
727   else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
728     visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
729   else
730     llvm_unreachable("Unknown DIType");
731 }
732 
733 void BTFDebug::visitTypeEntry(const DIType *Ty) {
734   uint32_t TypeId;
735   visitTypeEntry(Ty, TypeId, false, false);
736 }
737 
738 void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
739   if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
740     TypeId = DIToIdMap[Ty];
741     return;
742   }
743 
744   // MapDef type may be a struct type or a non-pointer derived type
745   const DIType *OrigTy = Ty;
746   while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
747     auto Tag = DTy->getTag();
748     if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
749         Tag != dwarf::DW_TAG_volatile_type &&
750         Tag != dwarf::DW_TAG_restrict_type)
751       break;
752     Ty = DTy->getBaseType();
753   }
754 
755   const auto *CTy = dyn_cast<DICompositeType>(Ty);
756   if (!CTy)
757     return;
758 
759   auto Tag = CTy->getTag();
760   if (Tag != dwarf::DW_TAG_structure_type || CTy->isForwardDecl())
761     return;
762 
763   // Visit all struct members to ensure pointee type is visited
764   const DINodeArray Elements = CTy->getElements();
765   for (const auto *Element : Elements) {
766     const auto *MemberType = cast<DIDerivedType>(Element);
767     visitTypeEntry(MemberType->getBaseType());
768   }
769 
770   // Visit this type, struct or a const/typedef/volatile/restrict type
771   visitTypeEntry(OrigTy, TypeId, false, false);
772 }
773 
774 /// Read file contents from the actual file or from the source
775 std::string BTFDebug::populateFileContent(const DISubprogram *SP) {
776   auto File = SP->getFile();
777   std::string FileName;
778 
779   if (!File->getFilename().startswith("/") && File->getDirectory().size())
780     FileName = File->getDirectory().str() + "/" + File->getFilename().str();
781   else
782     FileName = std::string(File->getFilename());
783 
784   // No need to populate the contends if it has been populated!
785   if (FileContent.find(FileName) != FileContent.end())
786     return FileName;
787 
788   std::vector<std::string> Content;
789   std::string Line;
790   Content.push_back(Line); // Line 0 for empty string
791 
792   std::unique_ptr<MemoryBuffer> Buf;
793   auto Source = File->getSource();
794   if (Source)
795     Buf = MemoryBuffer::getMemBufferCopy(*Source);
796   else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
797                MemoryBuffer::getFile(FileName))
798     Buf = std::move(*BufOrErr);
799   if (Buf)
800     for (line_iterator I(*Buf, false), E; I != E; ++I)
801       Content.push_back(std::string(*I));
802 
803   FileContent[FileName] = Content;
804   return FileName;
805 }
806 
807 void BTFDebug::constructLineInfo(const DISubprogram *SP, MCSymbol *Label,
808                                  uint32_t Line, uint32_t Column) {
809   std::string FileName = populateFileContent(SP);
810   BTFLineInfo LineInfo;
811 
812   LineInfo.Label = Label;
813   LineInfo.FileNameOff = addString(FileName);
814   // If file content is not available, let LineOff = 0.
815   if (Line < FileContent[FileName].size())
816     LineInfo.LineOff = addString(FileContent[FileName][Line]);
817   else
818     LineInfo.LineOff = 0;
819   LineInfo.LineNum = Line;
820   LineInfo.ColumnNum = Column;
821   LineInfoTable[SecNameOff].push_back(LineInfo);
822 }
823 
824 void BTFDebug::emitCommonHeader() {
825   OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC));
826   OS.emitIntValue(BTF::MAGIC, 2);
827   OS.emitInt8(BTF::VERSION);
828   OS.emitInt8(0);
829 }
830 
831 void BTFDebug::emitBTFSection() {
832   // Do not emit section if no types and only "" string.
833   if (!TypeEntries.size() && StringTable.getSize() == 1)
834     return;
835 
836   MCContext &Ctx = OS.getContext();
837   MCSectionELF *Sec = Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0);
838   Sec->setAlignment(Align(4));
839   OS.SwitchSection(Sec);
840 
841   // Emit header.
842   emitCommonHeader();
843   OS.emitInt32(BTF::HeaderSize);
844 
845   uint32_t TypeLen = 0, StrLen;
846   for (const auto &TypeEntry : TypeEntries)
847     TypeLen += TypeEntry->getSize();
848   StrLen = StringTable.getSize();
849 
850   OS.emitInt32(0);
851   OS.emitInt32(TypeLen);
852   OS.emitInt32(TypeLen);
853   OS.emitInt32(StrLen);
854 
855   // Emit type table.
856   for (const auto &TypeEntry : TypeEntries)
857     TypeEntry->emitType(OS);
858 
859   // Emit string table.
860   uint32_t StringOffset = 0;
861   for (const auto &S : StringTable.getTable()) {
862     OS.AddComment("string offset=" + std::to_string(StringOffset));
863     OS.emitBytes(S);
864     OS.emitBytes(StringRef("\0", 1));
865     StringOffset += S.size() + 1;
866   }
867 }
868 
869 void BTFDebug::emitBTFExtSection() {
870   // Do not emit section if empty FuncInfoTable and LineInfoTable
871   // and FieldRelocTable.
872   if (!FuncInfoTable.size() && !LineInfoTable.size() &&
873       !FieldRelocTable.size())
874     return;
875 
876   MCContext &Ctx = OS.getContext();
877   MCSectionELF *Sec = Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0);
878   Sec->setAlignment(Align(4));
879   OS.SwitchSection(Sec);
880 
881   // Emit header.
882   emitCommonHeader();
883   OS.emitInt32(BTF::ExtHeaderSize);
884 
885   // Account for FuncInfo/LineInfo record size as well.
886   uint32_t FuncLen = 4, LineLen = 4;
887   // Do not account for optional FieldReloc.
888   uint32_t FieldRelocLen = 0;
889   for (const auto &FuncSec : FuncInfoTable) {
890     FuncLen += BTF::SecFuncInfoSize;
891     FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
892   }
893   for (const auto &LineSec : LineInfoTable) {
894     LineLen += BTF::SecLineInfoSize;
895     LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
896   }
897   for (const auto &FieldRelocSec : FieldRelocTable) {
898     FieldRelocLen += BTF::SecFieldRelocSize;
899     FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
900   }
901 
902   if (FieldRelocLen)
903     FieldRelocLen += 4;
904 
905   OS.emitInt32(0);
906   OS.emitInt32(FuncLen);
907   OS.emitInt32(FuncLen);
908   OS.emitInt32(LineLen);
909   OS.emitInt32(FuncLen + LineLen);
910   OS.emitInt32(FieldRelocLen);
911 
912   // Emit func_info table.
913   OS.AddComment("FuncInfo");
914   OS.emitInt32(BTF::BPFFuncInfoSize);
915   for (const auto &FuncSec : FuncInfoTable) {
916     OS.AddComment("FuncInfo section string offset=" +
917                   std::to_string(FuncSec.first));
918     OS.emitInt32(FuncSec.first);
919     OS.emitInt32(FuncSec.second.size());
920     for (const auto &FuncInfo : FuncSec.second) {
921       Asm->emitLabelReference(FuncInfo.Label, 4);
922       OS.emitInt32(FuncInfo.TypeId);
923     }
924   }
925 
926   // Emit line_info table.
927   OS.AddComment("LineInfo");
928   OS.emitInt32(BTF::BPFLineInfoSize);
929   for (const auto &LineSec : LineInfoTable) {
930     OS.AddComment("LineInfo section string offset=" +
931                   std::to_string(LineSec.first));
932     OS.emitInt32(LineSec.first);
933     OS.emitInt32(LineSec.second.size());
934     for (const auto &LineInfo : LineSec.second) {
935       Asm->emitLabelReference(LineInfo.Label, 4);
936       OS.emitInt32(LineInfo.FileNameOff);
937       OS.emitInt32(LineInfo.LineOff);
938       OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
939                     std::to_string(LineInfo.ColumnNum));
940       OS.emitInt32(LineInfo.LineNum << 10 | LineInfo.ColumnNum);
941     }
942   }
943 
944   // Emit field reloc table.
945   if (FieldRelocLen) {
946     OS.AddComment("FieldReloc");
947     OS.emitInt32(BTF::BPFFieldRelocSize);
948     for (const auto &FieldRelocSec : FieldRelocTable) {
949       OS.AddComment("Field reloc section string offset=" +
950                     std::to_string(FieldRelocSec.first));
951       OS.emitInt32(FieldRelocSec.first);
952       OS.emitInt32(FieldRelocSec.second.size());
953       for (const auto &FieldRelocInfo : FieldRelocSec.second) {
954         Asm->emitLabelReference(FieldRelocInfo.Label, 4);
955         OS.emitInt32(FieldRelocInfo.TypeID);
956         OS.emitInt32(FieldRelocInfo.OffsetNameOff);
957         OS.emitInt32(FieldRelocInfo.RelocKind);
958       }
959     }
960   }
961 }
962 
963 void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
964   auto *SP = MF->getFunction().getSubprogram();
965   auto *Unit = SP->getUnit();
966 
967   if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
968     SkipInstruction = true;
969     return;
970   }
971   SkipInstruction = false;
972 
973   // Collect MapDef types. Map definition needs to collect
974   // pointee types. Do it first. Otherwise, for the following
975   // case:
976   //    struct m { ...};
977   //    struct t {
978   //      struct m *key;
979   //    };
980   //    foo(struct t *arg);
981   //
982   //    struct mapdef {
983   //      ...
984   //      struct m *key;
985   //      ...
986   //    } __attribute__((section(".maps"))) hash_map;
987   //
988   // If subroutine foo is traversed first, a type chain
989   // "ptr->struct m(fwd)" will be created and later on
990   // when traversing mapdef, since "ptr->struct m" exists,
991   // the traversal of "struct m" will be omitted.
992   if (MapDefNotCollected) {
993     processGlobals(true);
994     MapDefNotCollected = false;
995   }
996 
997   // Collect all types locally referenced in this function.
998   // Use RetainedNodes so we can collect all argument names
999   // even if the argument is not used.
1000   std::unordered_map<uint32_t, StringRef> FuncArgNames;
1001   for (const DINode *DN : SP->getRetainedNodes()) {
1002     if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1003       // Collect function arguments for subprogram func type.
1004       uint32_t Arg = DV->getArg();
1005       if (Arg) {
1006         visitTypeEntry(DV->getType());
1007         FuncArgNames[Arg] = DV->getName();
1008       }
1009     }
1010   }
1011 
1012   // Construct subprogram func proto type.
1013   uint32_t ProtoTypeId;
1014   visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
1015 
1016   // Construct subprogram func type
1017   uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
1018   auto FuncTypeEntry =
1019       std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
1020   uint32_t FuncTypeId = addType(std::move(FuncTypeEntry));
1021 
1022   // Process argument annotations.
1023   for (const DINode *DN : SP->getRetainedNodes()) {
1024     if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1025       uint32_t Arg = DV->getArg();
1026       if (Arg)
1027         processDeclAnnotations(DV->getAnnotations(), FuncTypeId, Arg - 1);
1028     }
1029   }
1030 
1031   processDeclAnnotations(SP->getAnnotations(), FuncTypeId, -1);
1032 
1033   for (const auto &TypeEntry : TypeEntries)
1034     TypeEntry->completeType(*this);
1035 
1036   // Construct funcinfo and the first lineinfo for the function.
1037   MCSymbol *FuncLabel = Asm->getFunctionBegin();
1038   BTFFuncInfo FuncInfo;
1039   FuncInfo.Label = FuncLabel;
1040   FuncInfo.TypeId = FuncTypeId;
1041   if (FuncLabel->isInSection()) {
1042     MCSection &Section = FuncLabel->getSection();
1043     const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section);
1044     assert(SectionELF && "Null section for Function Label");
1045     SecNameOff = addString(SectionELF->getName());
1046   } else {
1047     SecNameOff = addString(".text");
1048   }
1049   FuncInfoTable[SecNameOff].push_back(FuncInfo);
1050 }
1051 
1052 void BTFDebug::endFunctionImpl(const MachineFunction *MF) {
1053   SkipInstruction = false;
1054   LineInfoGenerated = false;
1055   SecNameOff = 0;
1056 }
1057 
1058 /// On-demand populate types as requested from abstract member
1059 /// accessing or preserve debuginfo type.
1060 unsigned BTFDebug::populateType(const DIType *Ty) {
1061   unsigned Id;
1062   visitTypeEntry(Ty, Id, false, false);
1063   for (const auto &TypeEntry : TypeEntries)
1064     TypeEntry->completeType(*this);
1065   return Id;
1066 }
1067 
1068 /// Generate a struct member field relocation.
1069 void BTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
1070                                      const GlobalVariable *GVar, bool IsAma) {
1071   BTFFieldReloc FieldReloc;
1072   FieldReloc.Label = ORSym;
1073   FieldReloc.TypeID = RootId;
1074 
1075   StringRef AccessPattern = GVar->getName();
1076   size_t FirstDollar = AccessPattern.find_first_of('$');
1077   if (IsAma) {
1078     size_t FirstColon = AccessPattern.find_first_of(':');
1079     size_t SecondColon = AccessPattern.find_first_of(':', FirstColon + 1);
1080     StringRef IndexPattern = AccessPattern.substr(FirstDollar + 1);
1081     StringRef RelocKindStr = AccessPattern.substr(FirstColon + 1,
1082         SecondColon - FirstColon);
1083     StringRef PatchImmStr = AccessPattern.substr(SecondColon + 1,
1084         FirstDollar - SecondColon);
1085 
1086     FieldReloc.OffsetNameOff = addString(IndexPattern);
1087     FieldReloc.RelocKind = std::stoull(std::string(RelocKindStr));
1088     PatchImms[GVar] = std::make_pair(std::stoll(std::string(PatchImmStr)),
1089                                      FieldReloc.RelocKind);
1090   } else {
1091     StringRef RelocStr = AccessPattern.substr(FirstDollar + 1);
1092     FieldReloc.OffsetNameOff = addString("0");
1093     FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
1094     PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
1095   }
1096   FieldRelocTable[SecNameOff].push_back(FieldReloc);
1097 }
1098 
1099 void BTFDebug::processGlobalValue(const MachineOperand &MO) {
1100   // check whether this is a candidate or not
1101   if (MO.isGlobal()) {
1102     const GlobalValue *GVal = MO.getGlobal();
1103     auto *GVar = dyn_cast<GlobalVariable>(GVal);
1104     if (!GVar) {
1105       // Not a global variable. Maybe an extern function reference.
1106       processFuncPrototypes(dyn_cast<Function>(GVal));
1107       return;
1108     }
1109 
1110     if (!GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) &&
1111         !GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
1112       return;
1113 
1114     MCSymbol *ORSym = OS.getContext().createTempSymbol();
1115     OS.emitLabel(ORSym);
1116 
1117     MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
1118     uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
1119     generatePatchImmReloc(ORSym, RootId, GVar,
1120                           GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr));
1121   }
1122 }
1123 
1124 void BTFDebug::beginInstruction(const MachineInstr *MI) {
1125   DebugHandlerBase::beginInstruction(MI);
1126 
1127   if (SkipInstruction || MI->isMetaInstruction() ||
1128       MI->getFlag(MachineInstr::FrameSetup))
1129     return;
1130 
1131   if (MI->isInlineAsm()) {
1132     // Count the number of register definitions to find the asm string.
1133     unsigned NumDefs = 0;
1134     for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1135          ++NumDefs)
1136       ;
1137 
1138     // Skip this inline asm instruction if the asmstr is empty.
1139     const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1140     if (AsmStr[0] == 0)
1141       return;
1142   }
1143 
1144   if (MI->getOpcode() == BPF::LD_imm64) {
1145     // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
1146     // add this insn into the .BTF.ext FieldReloc subsection.
1147     // Relocation looks like:
1148     //  . SecName:
1149     //    . InstOffset
1150     //    . TypeID
1151     //    . OffSetNameOff
1152     //    . RelocType
1153     // Later, the insn is replaced with "r2 = <offset>"
1154     // where "<offset>" equals to the offset based on current
1155     // type definitions.
1156     //
1157     // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
1158     // The LD_imm64 result will be replaced with a btf type id.
1159     processGlobalValue(MI->getOperand(1));
1160   } else if (MI->getOpcode() == BPF::CORE_MEM ||
1161              MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1162              MI->getOpcode() == BPF::CORE_SHIFT) {
1163     // relocation insn is a load, store or shift insn.
1164     processGlobalValue(MI->getOperand(3));
1165   } else if (MI->getOpcode() == BPF::JAL) {
1166     // check extern function references
1167     const MachineOperand &MO = MI->getOperand(0);
1168     if (MO.isGlobal()) {
1169       processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
1170     }
1171   }
1172 
1173   if (!CurMI) // no debug info
1174     return;
1175 
1176   // Skip this instruction if no DebugLoc or the DebugLoc
1177   // is the same as the previous instruction.
1178   const DebugLoc &DL = MI->getDebugLoc();
1179   if (!DL || PrevInstLoc == DL) {
1180     // This instruction will be skipped, no LineInfo has
1181     // been generated, construct one based on function signature.
1182     if (LineInfoGenerated == false) {
1183       auto *S = MI->getMF()->getFunction().getSubprogram();
1184       MCSymbol *FuncLabel = Asm->getFunctionBegin();
1185       constructLineInfo(S, FuncLabel, S->getLine(), 0);
1186       LineInfoGenerated = true;
1187     }
1188 
1189     return;
1190   }
1191 
1192   // Create a temporary label to remember the insn for lineinfo.
1193   MCSymbol *LineSym = OS.getContext().createTempSymbol();
1194   OS.emitLabel(LineSym);
1195 
1196   // Construct the lineinfo.
1197   auto SP = DL.get()->getScope()->getSubprogram();
1198   constructLineInfo(SP, LineSym, DL.getLine(), DL.getCol());
1199 
1200   LineInfoGenerated = true;
1201   PrevInstLoc = DL;
1202 }
1203 
1204 void BTFDebug::processGlobals(bool ProcessingMapDef) {
1205   // Collect all types referenced by globals.
1206   const Module *M = MMI->getModule();
1207   for (const GlobalVariable &Global : M->globals()) {
1208     // Decide the section name.
1209     StringRef SecName;
1210     if (Global.hasSection()) {
1211       SecName = Global.getSection();
1212     } else if (Global.hasInitializer()) {
1213       // data, bss, or readonly sections
1214       if (Global.isConstant())
1215         SecName = ".rodata";
1216       else
1217         SecName = Global.getInitializer()->isZeroValue() ? ".bss" : ".data";
1218     }
1219 
1220     if (ProcessingMapDef != SecName.startswith(".maps"))
1221       continue;
1222 
1223     // Create a .rodata datasec if the global variable is an initialized
1224     // constant with private linkage and if it won't be in .rodata.str<#>
1225     // and .rodata.cst<#> sections.
1226     if (SecName == ".rodata" && Global.hasPrivateLinkage() &&
1227         DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1228       SectionKind GVKind =
1229           TargetLoweringObjectFile::getKindForGlobal(&Global, Asm->TM);
1230       // skip .rodata.str<#> and .rodata.cst<#> sections
1231       if (!GVKind.isMergeableCString() && !GVKind.isMergeableConst()) {
1232         DataSecEntries[std::string(SecName)] =
1233             std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1234       }
1235     }
1236 
1237     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1238     Global.getDebugInfo(GVs);
1239 
1240     // No type information, mostly internal, skip it.
1241     if (GVs.size() == 0)
1242       continue;
1243 
1244     uint32_t GVTypeId = 0;
1245     DIGlobalVariable *DIGlobal = nullptr;
1246     for (auto *GVE : GVs) {
1247       DIGlobal = GVE->getVariable();
1248       if (SecName.startswith(".maps"))
1249         visitMapDefType(DIGlobal->getType(), GVTypeId);
1250       else
1251         visitTypeEntry(DIGlobal->getType(), GVTypeId, false, false);
1252       break;
1253     }
1254 
1255     // Only support the following globals:
1256     //  . static variables
1257     //  . non-static weak or non-weak global variables
1258     //  . weak or non-weak extern global variables
1259     // Whether DataSec is readonly or not can be found from corresponding ELF
1260     // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1261     // can be found from the corresponding ELF symbol table.
1262     auto Linkage = Global.getLinkage();
1263     if (Linkage != GlobalValue::InternalLinkage &&
1264         Linkage != GlobalValue::ExternalLinkage &&
1265         Linkage != GlobalValue::WeakAnyLinkage &&
1266         Linkage != GlobalValue::WeakODRLinkage &&
1267         Linkage != GlobalValue::ExternalWeakLinkage)
1268       continue;
1269 
1270     uint32_t GVarInfo;
1271     if (Linkage == GlobalValue::InternalLinkage) {
1272       GVarInfo = BTF::VAR_STATIC;
1273     } else if (Global.hasInitializer()) {
1274       GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
1275     } else {
1276       GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
1277     }
1278 
1279     auto VarEntry =
1280         std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
1281     uint32_t VarId = addType(std::move(VarEntry));
1282 
1283     processDeclAnnotations(DIGlobal->getAnnotations(), VarId, -1);
1284 
1285     // An empty SecName means an extern variable without section attribute.
1286     if (SecName.empty())
1287       continue;
1288 
1289     // Find or create a DataSec
1290     if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1291       DataSecEntries[std::string(SecName)] =
1292           std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1293     }
1294 
1295     // Calculate symbol size
1296     const DataLayout &DL = Global.getParent()->getDataLayout();
1297     uint32_t Size = DL.getTypeAllocSize(Global.getType()->getElementType());
1298 
1299     DataSecEntries[std::string(SecName)]->addDataSecEntry(VarId,
1300         Asm->getSymbol(&Global), Size);
1301   }
1302 }
1303 
1304 /// Emit proper patchable instructions.
1305 bool BTFDebug::InstLower(const MachineInstr *MI, MCInst &OutMI) {
1306   if (MI->getOpcode() == BPF::LD_imm64) {
1307     const MachineOperand &MO = MI->getOperand(1);
1308     if (MO.isGlobal()) {
1309       const GlobalValue *GVal = MO.getGlobal();
1310       auto *GVar = dyn_cast<GlobalVariable>(GVal);
1311       if (GVar) {
1312         // Emit "mov ri, <imm>"
1313         int64_t Imm;
1314         uint32_t Reloc;
1315         if (GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) ||
1316             GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr)) {
1317           Imm = PatchImms[GVar].first;
1318           Reloc = PatchImms[GVar].second;
1319         } else {
1320           return false;
1321         }
1322 
1323         if (Reloc == BPFCoreSharedInfo::ENUM_VALUE_EXISTENCE ||
1324             Reloc == BPFCoreSharedInfo::ENUM_VALUE ||
1325             Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_LOCAL ||
1326             Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_REMOTE)
1327           OutMI.setOpcode(BPF::LD_imm64);
1328         else
1329           OutMI.setOpcode(BPF::MOV_ri);
1330         OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1331         OutMI.addOperand(MCOperand::createImm(Imm));
1332         return true;
1333       }
1334     }
1335   } else if (MI->getOpcode() == BPF::CORE_MEM ||
1336              MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1337              MI->getOpcode() == BPF::CORE_SHIFT) {
1338     const MachineOperand &MO = MI->getOperand(3);
1339     if (MO.isGlobal()) {
1340       const GlobalValue *GVal = MO.getGlobal();
1341       auto *GVar = dyn_cast<GlobalVariable>(GVal);
1342       if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1343         uint32_t Imm = PatchImms[GVar].first;
1344         OutMI.setOpcode(MI->getOperand(1).getImm());
1345         if (MI->getOperand(0).isImm())
1346           OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
1347         else
1348           OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1349         OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
1350         OutMI.addOperand(MCOperand::createImm(Imm));
1351         return true;
1352       }
1353     }
1354   }
1355   return false;
1356 }
1357 
1358 void BTFDebug::processFuncPrototypes(const Function *F) {
1359   if (!F)
1360     return;
1361 
1362   const DISubprogram *SP = F->getSubprogram();
1363   if (!SP || SP->isDefinition())
1364     return;
1365 
1366   // Do not emit again if already emitted.
1367   if (ProtoFunctions.find(F) != ProtoFunctions.end())
1368     return;
1369   ProtoFunctions.insert(F);
1370 
1371   uint32_t ProtoTypeId;
1372   const std::unordered_map<uint32_t, StringRef> FuncArgNames;
1373   visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
1374 
1375   uint8_t Scope = BTF::FUNC_EXTERN;
1376   auto FuncTypeEntry =
1377       std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
1378   uint32_t FuncId = addType(std::move(FuncTypeEntry));
1379 
1380   processDeclAnnotations(SP->getAnnotations(), FuncId, -1);
1381 
1382   if (F->hasSection()) {
1383     StringRef SecName = F->getSection();
1384 
1385     if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1386       DataSecEntries[std::string(SecName)] =
1387           std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1388     }
1389 
1390     // We really don't know func size, set it to 0.
1391     DataSecEntries[std::string(SecName)]->addDataSecEntry(FuncId,
1392         Asm->getSymbol(F), 0);
1393   }
1394 }
1395 
1396 void BTFDebug::endModule() {
1397   // Collect MapDef globals if not collected yet.
1398   if (MapDefNotCollected) {
1399     processGlobals(true);
1400     MapDefNotCollected = false;
1401   }
1402 
1403   // Collect global types/variables except MapDef globals.
1404   processGlobals(false);
1405 
1406   for (auto &DataSec : DataSecEntries)
1407     addType(std::move(DataSec.second));
1408 
1409   // Fixups
1410   for (auto &Fixup : FixupDerivedTypes) {
1411     StringRef TypeName = Fixup.first;
1412     bool IsUnion = Fixup.second.first;
1413 
1414     // Search through struct types
1415     uint32_t StructTypeId = 0;
1416     for (const auto &StructType : StructTypes) {
1417       if (StructType->getName() == TypeName) {
1418         StructTypeId = StructType->getId();
1419         break;
1420       }
1421     }
1422 
1423     if (StructTypeId == 0) {
1424       auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
1425       StructTypeId = addType(std::move(FwdTypeEntry));
1426     }
1427 
1428     for (auto &DType : Fixup.second.second) {
1429       DType->setPointeeType(StructTypeId);
1430     }
1431   }
1432 
1433   // Complete BTF type cross refereences.
1434   for (const auto &TypeEntry : TypeEntries)
1435     TypeEntry->completeType(*this);
1436 
1437   // Emit BTF sections.
1438   emitBTFSection();
1439   emitBTFExtSection();
1440 }
1441