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 BTFTypeTag::BTFTypeTag(uint32_t BaseTypeId, int ComponentIdx, StringRef Tag)
390     : Tag(Tag) {
391   Kind = BTF::BTF_KIND_TAG;
392   BTFType.Info = Kind << 24;
393   BTFType.Type = BaseTypeId;
394   Info = ComponentIdx;
395 }
396 
397 void BTFTypeTag::completeType(BTFDebug &BDebug) {
398   if (IsCompleted)
399     return;
400   IsCompleted = true;
401 
402   BTFType.NameOff = BDebug.addString(Tag);
403 }
404 
405 void BTFTypeTag::emitType(MCStreamer &OS) {
406   BTFTypeBase::emitType(OS);
407   OS.emitInt32(Info);
408 }
409 
410 uint32_t BTFStringTable::addString(StringRef S) {
411   // Check whether the string already exists.
412   for (auto &OffsetM : OffsetToIdMap) {
413     if (Table[OffsetM.second] == S)
414       return OffsetM.first;
415   }
416   // Not find, add to the string table.
417   uint32_t Offset = Size;
418   OffsetToIdMap[Offset] = Table.size();
419   Table.push_back(std::string(S));
420   Size += S.size() + 1;
421   return Offset;
422 }
423 
424 BTFDebug::BTFDebug(AsmPrinter *AP)
425     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
426       LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
427       MapDefNotCollected(true) {
428   addString("\0");
429 }
430 
431 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
432                            const DIType *Ty) {
433   TypeEntry->setId(TypeEntries.size() + 1);
434   uint32_t Id = TypeEntry->getId();
435   DIToIdMap[Ty] = Id;
436   TypeEntries.push_back(std::move(TypeEntry));
437   return Id;
438 }
439 
440 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
441   TypeEntry->setId(TypeEntries.size() + 1);
442   uint32_t Id = TypeEntry->getId();
443   TypeEntries.push_back(std::move(TypeEntry));
444   return Id;
445 }
446 
447 void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
448   // Only int and binary floating point types are supported in BTF.
449   uint32_t Encoding = BTy->getEncoding();
450   std::unique_ptr<BTFTypeBase> TypeEntry;
451   switch (Encoding) {
452   case dwarf::DW_ATE_boolean:
453   case dwarf::DW_ATE_signed:
454   case dwarf::DW_ATE_signed_char:
455   case dwarf::DW_ATE_unsigned:
456   case dwarf::DW_ATE_unsigned_char:
457     // Create a BTF type instance for this DIBasicType and put it into
458     // DIToIdMap for cross-type reference check.
459     TypeEntry = std::make_unique<BTFTypeInt>(
460         Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
461     break;
462   case dwarf::DW_ATE_float:
463     TypeEntry =
464         std::make_unique<BTFTypeFloat>(BTy->getSizeInBits(), BTy->getName());
465     break;
466   default:
467     return;
468   }
469 
470   TypeId = addType(std::move(TypeEntry), BTy);
471 }
472 
473 /// Handle subprogram or subroutine types.
474 void BTFDebug::visitSubroutineType(
475     const DISubroutineType *STy, bool ForSubprog,
476     const std::unordered_map<uint32_t, StringRef> &FuncArgNames,
477     uint32_t &TypeId) {
478   DITypeRefArray Elements = STy->getTypeArray();
479   uint32_t VLen = Elements.size() - 1;
480   if (VLen > BTF::MAX_VLEN)
481     return;
482 
483   // Subprogram has a valid non-zero-length name, and the pointee of
484   // a function pointer has an empty name. The subprogram type will
485   // not be added to DIToIdMap as it should not be referenced by
486   // any other types.
487   auto TypeEntry = std::make_unique<BTFTypeFuncProto>(STy, VLen, FuncArgNames);
488   if (ForSubprog)
489     TypeId = addType(std::move(TypeEntry)); // For subprogram
490   else
491     TypeId = addType(std::move(TypeEntry), STy); // For func ptr
492 
493   // Visit return type and func arg types.
494   for (const auto Element : Elements) {
495     visitTypeEntry(Element);
496   }
497 }
498 
499 void BTFDebug::processAnnotations(DINodeArray Annotations, uint32_t BaseTypeId,
500                                   int ComponentIdx) {
501   if (!Annotations)
502      return;
503 
504   for (const Metadata *Annotation : Annotations->operands()) {
505     const MDNode *MD = cast<MDNode>(Annotation);
506     const MDString *Name = cast<MDString>(MD->getOperand(0));
507     if (!Name->getString().equals("btf_tag"))
508       continue;
509 
510     const MDString *Value = cast<MDString>(MD->getOperand(1));
511     auto TypeEntry = std::make_unique<BTFTypeTag>(BaseTypeId, ComponentIdx,
512                                                   Value->getString());
513     addType(std::move(TypeEntry));
514   }
515 }
516 
517 /// Handle structure/union types.
518 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
519                                uint32_t &TypeId) {
520   const DINodeArray Elements = CTy->getElements();
521   uint32_t VLen = Elements.size();
522   if (VLen > BTF::MAX_VLEN)
523     return;
524 
525   // Check whether we have any bitfield members or not
526   bool HasBitField = false;
527   for (const auto *Element : Elements) {
528     auto E = cast<DIDerivedType>(Element);
529     if (E->isBitField()) {
530       HasBitField = true;
531       break;
532     }
533   }
534 
535   auto TypeEntry =
536       std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
537   StructTypes.push_back(TypeEntry.get());
538   TypeId = addType(std::move(TypeEntry), CTy);
539 
540   // Check struct/union annotations
541   processAnnotations(CTy->getAnnotations(), TypeId, -1);
542 
543   // Visit all struct members.
544   int FieldNo = 0;
545   for (const auto *Element : Elements) {
546     const auto Elem = cast<DIDerivedType>(Element);
547     visitTypeEntry(Elem);
548     processAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
549     FieldNo++;
550   }
551 }
552 
553 void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
554   // Visit array element type.
555   uint32_t ElemTypeId;
556   const DIType *ElemType = CTy->getBaseType();
557   visitTypeEntry(ElemType, ElemTypeId, false, false);
558 
559   // Visit array dimensions.
560   DINodeArray Elements = CTy->getElements();
561   for (int I = Elements.size() - 1; I >= 0; --I) {
562     if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
563       if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
564         const DISubrange *SR = cast<DISubrange>(Element);
565         auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
566         int64_t Count = CI->getSExtValue();
567 
568         // For struct s { int b; char c[]; }, the c[] will be represented
569         // as an array with Count = -1.
570         auto TypeEntry =
571             std::make_unique<BTFTypeArray>(ElemTypeId,
572                 Count >= 0 ? Count : 0);
573         if (I == 0)
574           ElemTypeId = addType(std::move(TypeEntry), CTy);
575         else
576           ElemTypeId = addType(std::move(TypeEntry));
577       }
578   }
579 
580   // The array TypeId is the type id of the outermost dimension.
581   TypeId = ElemTypeId;
582 
583   // The IR does not have a type for array index while BTF wants one.
584   // So create an array index type if there is none.
585   if (!ArrayIndexTypeId) {
586     auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
587                                                    0, "__ARRAY_SIZE_TYPE__");
588     ArrayIndexTypeId = addType(std::move(TypeEntry));
589   }
590 }
591 
592 void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
593   DINodeArray Elements = CTy->getElements();
594   uint32_t VLen = Elements.size();
595   if (VLen > BTF::MAX_VLEN)
596     return;
597 
598   auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen);
599   TypeId = addType(std::move(TypeEntry), CTy);
600   // No need to visit base type as BTF does not encode it.
601 }
602 
603 /// Handle structure/union forward declarations.
604 void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
605                                 uint32_t &TypeId) {
606   auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
607   TypeId = addType(std::move(TypeEntry), CTy);
608 }
609 
610 /// Handle structure, union, array and enumeration types.
611 void BTFDebug::visitCompositeType(const DICompositeType *CTy,
612                                   uint32_t &TypeId) {
613   auto Tag = CTy->getTag();
614   if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
615     // Handle forward declaration differently as it does not have members.
616     if (CTy->isForwardDecl())
617       visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
618     else
619       visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
620   } else if (Tag == dwarf::DW_TAG_array_type)
621     visitArrayType(CTy, TypeId);
622   else if (Tag == dwarf::DW_TAG_enumeration_type)
623     visitEnumType(CTy, TypeId);
624 }
625 
626 /// Handle pointer, typedef, const, volatile, restrict and member types.
627 void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
628                                 bool CheckPointer, bool SeenPointer) {
629   unsigned Tag = DTy->getTag();
630 
631   /// Try to avoid chasing pointees, esp. structure pointees which may
632   /// unnecessary bring in a lot of types.
633   if (CheckPointer && !SeenPointer) {
634     SeenPointer = Tag == dwarf::DW_TAG_pointer_type;
635   }
636 
637   if (CheckPointer && SeenPointer) {
638     const DIType *Base = DTy->getBaseType();
639     if (Base) {
640       if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
641         auto CTag = CTy->getTag();
642         if ((CTag == dwarf::DW_TAG_structure_type ||
643              CTag == dwarf::DW_TAG_union_type) &&
644             !CTy->getName().empty() && !CTy->isForwardDecl()) {
645           /// Find a candidate, generate a fixup. Later on the struct/union
646           /// pointee type will be replaced with either a real type or
647           /// a forward declaration.
648           auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
649           auto &Fixup = FixupDerivedTypes[CTy->getName()];
650           Fixup.first = CTag == dwarf::DW_TAG_union_type;
651           Fixup.second.push_back(TypeEntry.get());
652           TypeId = addType(std::move(TypeEntry), DTy);
653           return;
654         }
655       }
656     }
657   }
658 
659   if (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_typedef ||
660       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
661       Tag == dwarf::DW_TAG_restrict_type) {
662     auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
663     TypeId = addType(std::move(TypeEntry), DTy);
664   } else if (Tag != dwarf::DW_TAG_member) {
665     return;
666   }
667 
668   // Visit base type of pointer, typedef, const, volatile, restrict or
669   // struct/union member.
670   uint32_t TempTypeId = 0;
671   if (Tag == dwarf::DW_TAG_member)
672     visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
673   else
674     visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
675 }
676 
677 void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
678                               bool CheckPointer, bool SeenPointer) {
679   if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
680     TypeId = DIToIdMap[Ty];
681 
682     // To handle the case like the following:
683     //    struct t;
684     //    typedef struct t _t;
685     //    struct s1 { _t *c; };
686     //    int test1(struct s1 *arg) { ... }
687     //
688     //    struct t { int a; int b; };
689     //    struct s2 { _t c; }
690     //    int test2(struct s2 *arg) { ... }
691     //
692     // During traversing test1() argument, "_t" is recorded
693     // in DIToIdMap and a forward declaration fixup is created
694     // for "struct t" to avoid pointee type traversal.
695     //
696     // During traversing test2() argument, even if we see "_t" is
697     // already defined, we should keep moving to eventually
698     // bring in types for "struct t". Otherwise, the "struct s2"
699     // definition won't be correct.
700     if (Ty && (!CheckPointer || !SeenPointer)) {
701       if (const auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
702         unsigned Tag = DTy->getTag();
703         if (Tag == dwarf::DW_TAG_typedef || Tag == dwarf::DW_TAG_const_type ||
704             Tag == dwarf::DW_TAG_volatile_type ||
705             Tag == dwarf::DW_TAG_restrict_type) {
706           uint32_t TmpTypeId;
707           visitTypeEntry(DTy->getBaseType(), TmpTypeId, CheckPointer,
708                          SeenPointer);
709         }
710       }
711     }
712 
713     return;
714   }
715 
716   if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
717     visitBasicType(BTy, TypeId);
718   else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
719     visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(),
720                         TypeId);
721   else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
722     visitCompositeType(CTy, TypeId);
723   else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
724     visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
725   else
726     llvm_unreachable("Unknown DIType");
727 }
728 
729 void BTFDebug::visitTypeEntry(const DIType *Ty) {
730   uint32_t TypeId;
731   visitTypeEntry(Ty, TypeId, false, false);
732 }
733 
734 void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
735   if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
736     TypeId = DIToIdMap[Ty];
737     return;
738   }
739 
740   // MapDef type may be a struct type or a non-pointer derived type
741   const DIType *OrigTy = Ty;
742   while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
743     auto Tag = DTy->getTag();
744     if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
745         Tag != dwarf::DW_TAG_volatile_type &&
746         Tag != dwarf::DW_TAG_restrict_type)
747       break;
748     Ty = DTy->getBaseType();
749   }
750 
751   const auto *CTy = dyn_cast<DICompositeType>(Ty);
752   if (!CTy)
753     return;
754 
755   auto Tag = CTy->getTag();
756   if (Tag != dwarf::DW_TAG_structure_type || CTy->isForwardDecl())
757     return;
758 
759   // Visit all struct members to ensure pointee type is visited
760   const DINodeArray Elements = CTy->getElements();
761   for (const auto *Element : Elements) {
762     const auto *MemberType = cast<DIDerivedType>(Element);
763     visitTypeEntry(MemberType->getBaseType());
764   }
765 
766   // Visit this type, struct or a const/typedef/volatile/restrict type
767   visitTypeEntry(OrigTy, TypeId, false, false);
768 }
769 
770 /// Read file contents from the actual file or from the source
771 std::string BTFDebug::populateFileContent(const DISubprogram *SP) {
772   auto File = SP->getFile();
773   std::string FileName;
774 
775   if (!File->getFilename().startswith("/") && File->getDirectory().size())
776     FileName = File->getDirectory().str() + "/" + File->getFilename().str();
777   else
778     FileName = std::string(File->getFilename());
779 
780   // No need to populate the contends if it has been populated!
781   if (FileContent.find(FileName) != FileContent.end())
782     return FileName;
783 
784   std::vector<std::string> Content;
785   std::string Line;
786   Content.push_back(Line); // Line 0 for empty string
787 
788   std::unique_ptr<MemoryBuffer> Buf;
789   auto Source = File->getSource();
790   if (Source)
791     Buf = MemoryBuffer::getMemBufferCopy(*Source);
792   else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
793                MemoryBuffer::getFile(FileName))
794     Buf = std::move(*BufOrErr);
795   if (Buf)
796     for (line_iterator I(*Buf, false), E; I != E; ++I)
797       Content.push_back(std::string(*I));
798 
799   FileContent[FileName] = Content;
800   return FileName;
801 }
802 
803 void BTFDebug::constructLineInfo(const DISubprogram *SP, MCSymbol *Label,
804                                  uint32_t Line, uint32_t Column) {
805   std::string FileName = populateFileContent(SP);
806   BTFLineInfo LineInfo;
807 
808   LineInfo.Label = Label;
809   LineInfo.FileNameOff = addString(FileName);
810   // If file content is not available, let LineOff = 0.
811   if (Line < FileContent[FileName].size())
812     LineInfo.LineOff = addString(FileContent[FileName][Line]);
813   else
814     LineInfo.LineOff = 0;
815   LineInfo.LineNum = Line;
816   LineInfo.ColumnNum = Column;
817   LineInfoTable[SecNameOff].push_back(LineInfo);
818 }
819 
820 void BTFDebug::emitCommonHeader() {
821   OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC));
822   OS.emitIntValue(BTF::MAGIC, 2);
823   OS.emitInt8(BTF::VERSION);
824   OS.emitInt8(0);
825 }
826 
827 void BTFDebug::emitBTFSection() {
828   // Do not emit section if no types and only "" string.
829   if (!TypeEntries.size() && StringTable.getSize() == 1)
830     return;
831 
832   MCContext &Ctx = OS.getContext();
833   OS.SwitchSection(Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0));
834 
835   // Emit header.
836   emitCommonHeader();
837   OS.emitInt32(BTF::HeaderSize);
838 
839   uint32_t TypeLen = 0, StrLen;
840   for (const auto &TypeEntry : TypeEntries)
841     TypeLen += TypeEntry->getSize();
842   StrLen = StringTable.getSize();
843 
844   OS.emitInt32(0);
845   OS.emitInt32(TypeLen);
846   OS.emitInt32(TypeLen);
847   OS.emitInt32(StrLen);
848 
849   // Emit type table.
850   for (const auto &TypeEntry : TypeEntries)
851     TypeEntry->emitType(OS);
852 
853   // Emit string table.
854   uint32_t StringOffset = 0;
855   for (const auto &S : StringTable.getTable()) {
856     OS.AddComment("string offset=" + std::to_string(StringOffset));
857     OS.emitBytes(S);
858     OS.emitBytes(StringRef("\0", 1));
859     StringOffset += S.size() + 1;
860   }
861 }
862 
863 void BTFDebug::emitBTFExtSection() {
864   // Do not emit section if empty FuncInfoTable and LineInfoTable
865   // and FieldRelocTable.
866   if (!FuncInfoTable.size() && !LineInfoTable.size() &&
867       !FieldRelocTable.size())
868     return;
869 
870   MCContext &Ctx = OS.getContext();
871   OS.SwitchSection(Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0));
872 
873   // Emit header.
874   emitCommonHeader();
875   OS.emitInt32(BTF::ExtHeaderSize);
876 
877   // Account for FuncInfo/LineInfo record size as well.
878   uint32_t FuncLen = 4, LineLen = 4;
879   // Do not account for optional FieldReloc.
880   uint32_t FieldRelocLen = 0;
881   for (const auto &FuncSec : FuncInfoTable) {
882     FuncLen += BTF::SecFuncInfoSize;
883     FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
884   }
885   for (const auto &LineSec : LineInfoTable) {
886     LineLen += BTF::SecLineInfoSize;
887     LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
888   }
889   for (const auto &FieldRelocSec : FieldRelocTable) {
890     FieldRelocLen += BTF::SecFieldRelocSize;
891     FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
892   }
893 
894   if (FieldRelocLen)
895     FieldRelocLen += 4;
896 
897   OS.emitInt32(0);
898   OS.emitInt32(FuncLen);
899   OS.emitInt32(FuncLen);
900   OS.emitInt32(LineLen);
901   OS.emitInt32(FuncLen + LineLen);
902   OS.emitInt32(FieldRelocLen);
903 
904   // Emit func_info table.
905   OS.AddComment("FuncInfo");
906   OS.emitInt32(BTF::BPFFuncInfoSize);
907   for (const auto &FuncSec : FuncInfoTable) {
908     OS.AddComment("FuncInfo section string offset=" +
909                   std::to_string(FuncSec.first));
910     OS.emitInt32(FuncSec.first);
911     OS.emitInt32(FuncSec.second.size());
912     for (const auto &FuncInfo : FuncSec.second) {
913       Asm->emitLabelReference(FuncInfo.Label, 4);
914       OS.emitInt32(FuncInfo.TypeId);
915     }
916   }
917 
918   // Emit line_info table.
919   OS.AddComment("LineInfo");
920   OS.emitInt32(BTF::BPFLineInfoSize);
921   for (const auto &LineSec : LineInfoTable) {
922     OS.AddComment("LineInfo section string offset=" +
923                   std::to_string(LineSec.first));
924     OS.emitInt32(LineSec.first);
925     OS.emitInt32(LineSec.second.size());
926     for (const auto &LineInfo : LineSec.second) {
927       Asm->emitLabelReference(LineInfo.Label, 4);
928       OS.emitInt32(LineInfo.FileNameOff);
929       OS.emitInt32(LineInfo.LineOff);
930       OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
931                     std::to_string(LineInfo.ColumnNum));
932       OS.emitInt32(LineInfo.LineNum << 10 | LineInfo.ColumnNum);
933     }
934   }
935 
936   // Emit field reloc table.
937   if (FieldRelocLen) {
938     OS.AddComment("FieldReloc");
939     OS.emitInt32(BTF::BPFFieldRelocSize);
940     for (const auto &FieldRelocSec : FieldRelocTable) {
941       OS.AddComment("Field reloc section string offset=" +
942                     std::to_string(FieldRelocSec.first));
943       OS.emitInt32(FieldRelocSec.first);
944       OS.emitInt32(FieldRelocSec.second.size());
945       for (const auto &FieldRelocInfo : FieldRelocSec.second) {
946         Asm->emitLabelReference(FieldRelocInfo.Label, 4);
947         OS.emitInt32(FieldRelocInfo.TypeID);
948         OS.emitInt32(FieldRelocInfo.OffsetNameOff);
949         OS.emitInt32(FieldRelocInfo.RelocKind);
950       }
951     }
952   }
953 }
954 
955 void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
956   auto *SP = MF->getFunction().getSubprogram();
957   auto *Unit = SP->getUnit();
958 
959   if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
960     SkipInstruction = true;
961     return;
962   }
963   SkipInstruction = false;
964 
965   // Collect MapDef types. Map definition needs to collect
966   // pointee types. Do it first. Otherwise, for the following
967   // case:
968   //    struct m { ...};
969   //    struct t {
970   //      struct m *key;
971   //    };
972   //    foo(struct t *arg);
973   //
974   //    struct mapdef {
975   //      ...
976   //      struct m *key;
977   //      ...
978   //    } __attribute__((section(".maps"))) hash_map;
979   //
980   // If subroutine foo is traversed first, a type chain
981   // "ptr->struct m(fwd)" will be created and later on
982   // when traversing mapdef, since "ptr->struct m" exists,
983   // the traversal of "struct m" will be omitted.
984   if (MapDefNotCollected) {
985     processGlobals(true);
986     MapDefNotCollected = false;
987   }
988 
989   // Collect all types locally referenced in this function.
990   // Use RetainedNodes so we can collect all argument names
991   // even if the argument is not used.
992   std::unordered_map<uint32_t, StringRef> FuncArgNames;
993   for (const DINode *DN : SP->getRetainedNodes()) {
994     if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
995       // Collect function arguments for subprogram func type.
996       uint32_t Arg = DV->getArg();
997       if (Arg) {
998         visitTypeEntry(DV->getType());
999         FuncArgNames[Arg] = DV->getName();
1000       }
1001     }
1002   }
1003 
1004   // Construct subprogram func proto type.
1005   uint32_t ProtoTypeId;
1006   visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
1007 
1008   // Construct subprogram func type
1009   uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
1010   auto FuncTypeEntry =
1011       std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
1012   uint32_t FuncTypeId = addType(std::move(FuncTypeEntry));
1013 
1014   // Process argument annotations.
1015   for (const DINode *DN : SP->getRetainedNodes()) {
1016     if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
1017       uint32_t Arg = DV->getArg();
1018       if (Arg)
1019         processAnnotations(DV->getAnnotations(), FuncTypeId, Arg - 1);
1020     }
1021   }
1022 
1023   processAnnotations(SP->getAnnotations(), FuncTypeId, -1);
1024 
1025   for (const auto &TypeEntry : TypeEntries)
1026     TypeEntry->completeType(*this);
1027 
1028   // Construct funcinfo and the first lineinfo for the function.
1029   MCSymbol *FuncLabel = Asm->getFunctionBegin();
1030   BTFFuncInfo FuncInfo;
1031   FuncInfo.Label = FuncLabel;
1032   FuncInfo.TypeId = FuncTypeId;
1033   if (FuncLabel->isInSection()) {
1034     MCSection &Section = FuncLabel->getSection();
1035     const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section);
1036     assert(SectionELF && "Null section for Function Label");
1037     SecNameOff = addString(SectionELF->getName());
1038   } else {
1039     SecNameOff = addString(".text");
1040   }
1041   FuncInfoTable[SecNameOff].push_back(FuncInfo);
1042 }
1043 
1044 void BTFDebug::endFunctionImpl(const MachineFunction *MF) {
1045   SkipInstruction = false;
1046   LineInfoGenerated = false;
1047   SecNameOff = 0;
1048 }
1049 
1050 /// On-demand populate types as requested from abstract member
1051 /// accessing or preserve debuginfo type.
1052 unsigned BTFDebug::populateType(const DIType *Ty) {
1053   unsigned Id;
1054   visitTypeEntry(Ty, Id, false, false);
1055   for (const auto &TypeEntry : TypeEntries)
1056     TypeEntry->completeType(*this);
1057   return Id;
1058 }
1059 
1060 /// Generate a struct member field relocation.
1061 void BTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
1062                                      const GlobalVariable *GVar, bool IsAma) {
1063   BTFFieldReloc FieldReloc;
1064   FieldReloc.Label = ORSym;
1065   FieldReloc.TypeID = RootId;
1066 
1067   StringRef AccessPattern = GVar->getName();
1068   size_t FirstDollar = AccessPattern.find_first_of('$');
1069   if (IsAma) {
1070     size_t FirstColon = AccessPattern.find_first_of(':');
1071     size_t SecondColon = AccessPattern.find_first_of(':', FirstColon + 1);
1072     StringRef IndexPattern = AccessPattern.substr(FirstDollar + 1);
1073     StringRef RelocKindStr = AccessPattern.substr(FirstColon + 1,
1074         SecondColon - FirstColon);
1075     StringRef PatchImmStr = AccessPattern.substr(SecondColon + 1,
1076         FirstDollar - SecondColon);
1077 
1078     FieldReloc.OffsetNameOff = addString(IndexPattern);
1079     FieldReloc.RelocKind = std::stoull(std::string(RelocKindStr));
1080     PatchImms[GVar] = std::make_pair(std::stoll(std::string(PatchImmStr)),
1081                                      FieldReloc.RelocKind);
1082   } else {
1083     StringRef RelocStr = AccessPattern.substr(FirstDollar + 1);
1084     FieldReloc.OffsetNameOff = addString("0");
1085     FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
1086     PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
1087   }
1088   FieldRelocTable[SecNameOff].push_back(FieldReloc);
1089 }
1090 
1091 void BTFDebug::processGlobalValue(const MachineOperand &MO) {
1092   // check whether this is a candidate or not
1093   if (MO.isGlobal()) {
1094     const GlobalValue *GVal = MO.getGlobal();
1095     auto *GVar = dyn_cast<GlobalVariable>(GVal);
1096     if (!GVar) {
1097       // Not a global variable. Maybe an extern function reference.
1098       processFuncPrototypes(dyn_cast<Function>(GVal));
1099       return;
1100     }
1101 
1102     if (!GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) &&
1103         !GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
1104       return;
1105 
1106     MCSymbol *ORSym = OS.getContext().createTempSymbol();
1107     OS.emitLabel(ORSym);
1108 
1109     MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
1110     uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
1111     generatePatchImmReloc(ORSym, RootId, GVar,
1112                           GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr));
1113   }
1114 }
1115 
1116 void BTFDebug::beginInstruction(const MachineInstr *MI) {
1117   DebugHandlerBase::beginInstruction(MI);
1118 
1119   if (SkipInstruction || MI->isMetaInstruction() ||
1120       MI->getFlag(MachineInstr::FrameSetup))
1121     return;
1122 
1123   if (MI->isInlineAsm()) {
1124     // Count the number of register definitions to find the asm string.
1125     unsigned NumDefs = 0;
1126     for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1127          ++NumDefs)
1128       ;
1129 
1130     // Skip this inline asm instruction if the asmstr is empty.
1131     const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1132     if (AsmStr[0] == 0)
1133       return;
1134   }
1135 
1136   if (MI->getOpcode() == BPF::LD_imm64) {
1137     // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
1138     // add this insn into the .BTF.ext FieldReloc subsection.
1139     // Relocation looks like:
1140     //  . SecName:
1141     //    . InstOffset
1142     //    . TypeID
1143     //    . OffSetNameOff
1144     //    . RelocType
1145     // Later, the insn is replaced with "r2 = <offset>"
1146     // where "<offset>" equals to the offset based on current
1147     // type definitions.
1148     //
1149     // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
1150     // The LD_imm64 result will be replaced with a btf type id.
1151     processGlobalValue(MI->getOperand(1));
1152   } else if (MI->getOpcode() == BPF::CORE_MEM ||
1153              MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1154              MI->getOpcode() == BPF::CORE_SHIFT) {
1155     // relocation insn is a load, store or shift insn.
1156     processGlobalValue(MI->getOperand(3));
1157   } else if (MI->getOpcode() == BPF::JAL) {
1158     // check extern function references
1159     const MachineOperand &MO = MI->getOperand(0);
1160     if (MO.isGlobal()) {
1161       processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
1162     }
1163   }
1164 
1165   if (!CurMI) // no debug info
1166     return;
1167 
1168   // Skip this instruction if no DebugLoc or the DebugLoc
1169   // is the same as the previous instruction.
1170   const DebugLoc &DL = MI->getDebugLoc();
1171   if (!DL || PrevInstLoc == DL) {
1172     // This instruction will be skipped, no LineInfo has
1173     // been generated, construct one based on function signature.
1174     if (LineInfoGenerated == false) {
1175       auto *S = MI->getMF()->getFunction().getSubprogram();
1176       MCSymbol *FuncLabel = Asm->getFunctionBegin();
1177       constructLineInfo(S, FuncLabel, S->getLine(), 0);
1178       LineInfoGenerated = true;
1179     }
1180 
1181     return;
1182   }
1183 
1184   // Create a temporary label to remember the insn for lineinfo.
1185   MCSymbol *LineSym = OS.getContext().createTempSymbol();
1186   OS.emitLabel(LineSym);
1187 
1188   // Construct the lineinfo.
1189   auto SP = DL.get()->getScope()->getSubprogram();
1190   constructLineInfo(SP, LineSym, DL.getLine(), DL.getCol());
1191 
1192   LineInfoGenerated = true;
1193   PrevInstLoc = DL;
1194 }
1195 
1196 void BTFDebug::processGlobals(bool ProcessingMapDef) {
1197   // Collect all types referenced by globals.
1198   const Module *M = MMI->getModule();
1199   for (const GlobalVariable &Global : M->globals()) {
1200     // Decide the section name.
1201     StringRef SecName;
1202     if (Global.hasSection()) {
1203       SecName = Global.getSection();
1204     } else if (Global.hasInitializer()) {
1205       // data, bss, or readonly sections
1206       if (Global.isConstant())
1207         SecName = ".rodata";
1208       else
1209         SecName = Global.getInitializer()->isZeroValue() ? ".bss" : ".data";
1210     }
1211 
1212     if (ProcessingMapDef != SecName.startswith(".maps"))
1213       continue;
1214 
1215     // Create a .rodata datasec if the global variable is an initialized
1216     // constant with private linkage and if it won't be in .rodata.str<#>
1217     // and .rodata.cst<#> sections.
1218     if (SecName == ".rodata" && Global.hasPrivateLinkage() &&
1219         DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1220       SectionKind GVKind =
1221           TargetLoweringObjectFile::getKindForGlobal(&Global, Asm->TM);
1222       // skip .rodata.str<#> and .rodata.cst<#> sections
1223       if (!GVKind.isMergeableCString() && !GVKind.isMergeableConst()) {
1224         DataSecEntries[std::string(SecName)] =
1225             std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1226       }
1227     }
1228 
1229     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1230     Global.getDebugInfo(GVs);
1231 
1232     // No type information, mostly internal, skip it.
1233     if (GVs.size() == 0)
1234       continue;
1235 
1236     uint32_t GVTypeId = 0;
1237     DIGlobalVariable *DIGlobal = nullptr;
1238     for (auto *GVE : GVs) {
1239       DIGlobal = GVE->getVariable();
1240       if (SecName.startswith(".maps"))
1241         visitMapDefType(DIGlobal->getType(), GVTypeId);
1242       else
1243         visitTypeEntry(DIGlobal->getType(), GVTypeId, false, false);
1244       break;
1245     }
1246 
1247     // Only support the following globals:
1248     //  . static variables
1249     //  . non-static weak or non-weak global variables
1250     //  . weak or non-weak extern global variables
1251     // Whether DataSec is readonly or not can be found from corresponding ELF
1252     // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1253     // can be found from the corresponding ELF symbol table.
1254     auto Linkage = Global.getLinkage();
1255     if (Linkage != GlobalValue::InternalLinkage &&
1256         Linkage != GlobalValue::ExternalLinkage &&
1257         Linkage != GlobalValue::WeakAnyLinkage &&
1258         Linkage != GlobalValue::WeakODRLinkage &&
1259         Linkage != GlobalValue::ExternalWeakLinkage)
1260       continue;
1261 
1262     uint32_t GVarInfo;
1263     if (Linkage == GlobalValue::InternalLinkage) {
1264       GVarInfo = BTF::VAR_STATIC;
1265     } else if (Global.hasInitializer()) {
1266       GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
1267     } else {
1268       GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
1269     }
1270 
1271     auto VarEntry =
1272         std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
1273     uint32_t VarId = addType(std::move(VarEntry));
1274 
1275     processAnnotations(DIGlobal->getAnnotations(), VarId, -1);
1276 
1277     // An empty SecName means an extern variable without section attribute.
1278     if (SecName.empty())
1279       continue;
1280 
1281     // Find or create a DataSec
1282     if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1283       DataSecEntries[std::string(SecName)] =
1284           std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1285     }
1286 
1287     // Calculate symbol size
1288     const DataLayout &DL = Global.getParent()->getDataLayout();
1289     uint32_t Size = DL.getTypeAllocSize(Global.getType()->getElementType());
1290 
1291     DataSecEntries[std::string(SecName)]->addDataSecEntry(VarId,
1292         Asm->getSymbol(&Global), Size);
1293   }
1294 }
1295 
1296 /// Emit proper patchable instructions.
1297 bool BTFDebug::InstLower(const MachineInstr *MI, MCInst &OutMI) {
1298   if (MI->getOpcode() == BPF::LD_imm64) {
1299     const MachineOperand &MO = MI->getOperand(1);
1300     if (MO.isGlobal()) {
1301       const GlobalValue *GVal = MO.getGlobal();
1302       auto *GVar = dyn_cast<GlobalVariable>(GVal);
1303       if (GVar) {
1304         // Emit "mov ri, <imm>"
1305         int64_t Imm;
1306         uint32_t Reloc;
1307         if (GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) ||
1308             GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr)) {
1309           Imm = PatchImms[GVar].first;
1310           Reloc = PatchImms[GVar].second;
1311         } else {
1312           return false;
1313         }
1314 
1315         if (Reloc == BPFCoreSharedInfo::ENUM_VALUE_EXISTENCE ||
1316             Reloc == BPFCoreSharedInfo::ENUM_VALUE ||
1317             Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_LOCAL ||
1318             Reloc == BPFCoreSharedInfo::BTF_TYPE_ID_REMOTE)
1319           OutMI.setOpcode(BPF::LD_imm64);
1320         else
1321           OutMI.setOpcode(BPF::MOV_ri);
1322         OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1323         OutMI.addOperand(MCOperand::createImm(Imm));
1324         return true;
1325       }
1326     }
1327   } else if (MI->getOpcode() == BPF::CORE_MEM ||
1328              MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1329              MI->getOpcode() == BPF::CORE_SHIFT) {
1330     const MachineOperand &MO = MI->getOperand(3);
1331     if (MO.isGlobal()) {
1332       const GlobalValue *GVal = MO.getGlobal();
1333       auto *GVar = dyn_cast<GlobalVariable>(GVal);
1334       if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1335         uint32_t Imm = PatchImms[GVar].first;
1336         OutMI.setOpcode(MI->getOperand(1).getImm());
1337         if (MI->getOperand(0).isImm())
1338           OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
1339         else
1340           OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1341         OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
1342         OutMI.addOperand(MCOperand::createImm(Imm));
1343         return true;
1344       }
1345     }
1346   }
1347   return false;
1348 }
1349 
1350 void BTFDebug::processFuncPrototypes(const Function *F) {
1351   if (!F)
1352     return;
1353 
1354   const DISubprogram *SP = F->getSubprogram();
1355   if (!SP || SP->isDefinition())
1356     return;
1357 
1358   // Do not emit again if already emitted.
1359   if (ProtoFunctions.find(F) != ProtoFunctions.end())
1360     return;
1361   ProtoFunctions.insert(F);
1362 
1363   uint32_t ProtoTypeId;
1364   const std::unordered_map<uint32_t, StringRef> FuncArgNames;
1365   visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
1366 
1367   uint8_t Scope = BTF::FUNC_EXTERN;
1368   auto FuncTypeEntry =
1369       std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId, Scope);
1370   uint32_t FuncId = addType(std::move(FuncTypeEntry));
1371 
1372   processAnnotations(SP->getAnnotations(), FuncId, -1);
1373 
1374   if (F->hasSection()) {
1375     StringRef SecName = F->getSection();
1376 
1377     if (DataSecEntries.find(std::string(SecName)) == DataSecEntries.end()) {
1378       DataSecEntries[std::string(SecName)] =
1379           std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
1380     }
1381 
1382     // We really don't know func size, set it to 0.
1383     DataSecEntries[std::string(SecName)]->addDataSecEntry(FuncId,
1384         Asm->getSymbol(F), 0);
1385   }
1386 }
1387 
1388 void BTFDebug::endModule() {
1389   // Collect MapDef globals if not collected yet.
1390   if (MapDefNotCollected) {
1391     processGlobals(true);
1392     MapDefNotCollected = false;
1393   }
1394 
1395   // Collect global types/variables except MapDef globals.
1396   processGlobals(false);
1397 
1398   for (auto &DataSec : DataSecEntries)
1399     addType(std::move(DataSec.second));
1400 
1401   // Fixups
1402   for (auto &Fixup : FixupDerivedTypes) {
1403     StringRef TypeName = Fixup.first;
1404     bool IsUnion = Fixup.second.first;
1405 
1406     // Search through struct types
1407     uint32_t StructTypeId = 0;
1408     for (const auto &StructType : StructTypes) {
1409       if (StructType->getName() == TypeName) {
1410         StructTypeId = StructType->getId();
1411         break;
1412       }
1413     }
1414 
1415     if (StructTypeId == 0) {
1416       auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
1417       StructTypeId = addType(std::move(FwdTypeEntry));
1418     }
1419 
1420     for (auto &DType : Fixup.second.second) {
1421       DType->setPointeeType(StructTypeId);
1422     }
1423   }
1424 
1425   // Complete BTF type cross refereences.
1426   for (const auto &TypeEntry : TypeEntries)
1427     TypeEntry->completeType(*this);
1428 
1429   // Emit BTF sections.
1430   emitBTFSection();
1431   emitBTFExtSection();
1432 }
1433