LLVM  10.0.0svn
BTFDebug.cpp
Go to the documentation of this file.
1 //===- BTFDebug.cpp - BTF Generator ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for writing BTF debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "BTFDebug.h"
14 #include "BPF.h"
15 #include "BPFCORE.h"
17 #include "llvm/BinaryFormat/ELF.h"
20 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCSectionELF.h"
23 #include "llvm/MC/MCStreamer.h"
25 
26 using namespace llvm;
27 
28 static const char *BTFKindStr[] = {
29 #define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
30 #include "BTF.def"
31 };
32 
33 /// Emit a BTF common type.
35  OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
36  ")");
39  OS.EmitIntValue(BTFType.Info, 4);
40  OS.EmitIntValue(BTFType.Size, 4);
41 }
42 
44  bool NeedsFixup)
45  : DTy(DTy), NeedsFixup(NeedsFixup) {
46  switch (Tag) {
47  case dwarf::DW_TAG_pointer_type:
48  Kind = BTF::BTF_KIND_PTR;
49  break;
50  case dwarf::DW_TAG_const_type:
51  Kind = BTF::BTF_KIND_CONST;
52  break;
53  case dwarf::DW_TAG_volatile_type:
54  Kind = BTF::BTF_KIND_VOLATILE;
55  break;
56  case dwarf::DW_TAG_typedef:
57  Kind = BTF::BTF_KIND_TYPEDEF;
58  break;
59  case dwarf::DW_TAG_restrict_type:
60  Kind = BTF::BTF_KIND_RESTRICT;
61  break;
62  default:
63  llvm_unreachable("Unknown DIDerivedType Tag");
64  }
65  BTFType.Info = Kind << 24;
66 }
67 
69  if (IsCompleted)
70  return;
71  IsCompleted = true;
72 
73  BTFType.NameOff = BDebug.addString(DTy->getName());
74 
75  if (NeedsFixup)
76  return;
77 
78  // The base type for PTR/CONST/VOLATILE could be void.
79  const DIType *ResolvedType = DTy->getBaseType();
80  if (!ResolvedType) {
81  assert((Kind == BTF::BTF_KIND_PTR || Kind == BTF::BTF_KIND_CONST ||
82  Kind == BTF::BTF_KIND_VOLATILE) &&
83  "Invalid null basetype");
84  BTFType.Type = 0;
85  } else {
86  BTFType.Type = BDebug.getTypeId(ResolvedType);
87  }
88 }
89 
91 
93  BTFType.Type = PointeeType;
94 }
95 
96 /// Represent a struct/union forward declaration.
97 BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) {
98  Kind = BTF::BTF_KIND_FWD;
99  BTFType.Info = IsUnion << 31 | Kind << 24;
100  BTFType.Type = 0;
101 }
102 
104  if (IsCompleted)
105  return;
106  IsCompleted = true;
107 
108  BTFType.NameOff = BDebug.addString(Name);
109 }
110 
112 
114  uint32_t OffsetInBits, StringRef TypeName)
115  : Name(TypeName) {
116  // Translate IR int encoding to BTF int encoding.
117  uint8_t BTFEncoding;
118  switch (Encoding) {
119  case dwarf::DW_ATE_boolean:
120  BTFEncoding = BTF::INT_BOOL;
121  break;
122  case dwarf::DW_ATE_signed:
123  case dwarf::DW_ATE_signed_char:
124  BTFEncoding = BTF::INT_SIGNED;
125  break;
126  case dwarf::DW_ATE_unsigned:
127  case dwarf::DW_ATE_unsigned_char:
128  BTFEncoding = 0;
129  break;
130  default:
131  llvm_unreachable("Unknown BTFTypeInt Encoding");
132  }
133 
134  Kind = BTF::BTF_KIND_INT;
135  BTFType.Info = Kind << 24;
136  BTFType.Size = roundupToBytes(SizeInBits);
137  IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits;
138 }
139 
141  if (IsCompleted)
142  return;
143  IsCompleted = true;
144 
145  BTFType.NameOff = BDebug.addString(Name);
146 }
147 
150  OS.AddComment("0x" + Twine::utohexstr(IntVal));
151  OS.EmitIntValue(IntVal, 4);
152 }
153 
154 BTFTypeEnum::BTFTypeEnum(const DICompositeType *ETy, uint32_t VLen) : ETy(ETy) {
155  Kind = BTF::BTF_KIND_ENUM;
156  BTFType.Info = Kind << 24 | VLen;
158 }
159 
161  if (IsCompleted)
162  return;
163  IsCompleted = true;
164 
165  BTFType.NameOff = BDebug.addString(ETy->getName());
166 
167  DINodeArray Elements = ETy->getElements();
168  for (const auto Element : Elements) {
169  const auto *Enum = cast<DIEnumerator>(Element);
170 
171  struct BTF::BTFEnum BTFEnum;
172  BTFEnum.NameOff = BDebug.addString(Enum->getName());
173  // BTF enum value is 32bit, enforce it.
174  BTFEnum.Val = static_cast<uint32_t>(Enum->getValue());
175  EnumValues.push_back(BTFEnum);
176  }
177 }
178 
181  for (const auto &Enum : EnumValues) {
182  OS.EmitIntValue(Enum.NameOff, 4);
183  OS.EmitIntValue(Enum.Val, 4);
184  }
185 }
186 
188  Kind = BTF::BTF_KIND_ARRAY;
189  BTFType.NameOff = 0;
190  BTFType.Info = Kind << 24;
191  BTFType.Size = 0;
192 
193  ArrayInfo.ElemType = ElemTypeId;
194  ArrayInfo.Nelems = NumElems;
195 }
196 
197 /// Represent a BTF array.
199  if (IsCompleted)
200  return;
201  IsCompleted = true;
202 
203  // The IR does not really have a type for the index.
204  // A special type for array index should have been
205  // created during initial type traversal. Just
206  // retrieve that type id.
207  ArrayInfo.IndexType = BDebug.getArrayIndexTypeId();
208 }
209 
212  OS.EmitIntValue(ArrayInfo.ElemType, 4);
213  OS.EmitIntValue(ArrayInfo.IndexType, 4);
214  OS.EmitIntValue(ArrayInfo.Nelems, 4);
215 }
216 
217 /// Represent either a struct or a union.
219  bool HasBitField, uint32_t Vlen)
220  : STy(STy), HasBitField(HasBitField) {
221  Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
223  BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
224 }
225 
227  if (IsCompleted)
228  return;
229  IsCompleted = true;
230 
231  BTFType.NameOff = BDebug.addString(STy->getName());
232 
233  // Add struct/union members.
234  const DINodeArray Elements = STy->getElements();
235  for (const auto *Element : Elements) {
236  struct BTF::BTFMember BTFMember;
237  const auto *DDTy = cast<DIDerivedType>(Element);
238 
239  BTFMember.NameOff = BDebug.addString(DDTy->getName());
240  if (HasBitField) {
241  uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0;
242  BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits();
243  } else {
244  BTFMember.Offset = DDTy->getOffsetInBits();
245  }
246  const auto *BaseTy = DDTy->getBaseType();
247  BTFMember.Type = BDebug.getTypeId(BaseTy);
248  Members.push_back(BTFMember);
249  }
250 }
251 
254  for (const auto &Member : Members) {
255  OS.EmitIntValue(Member.NameOff, 4);
256  OS.EmitIntValue(Member.Type, 4);
257  OS.AddComment("0x" + Twine::utohexstr(Member.Offset));
258  OS.EmitIntValue(Member.Offset, 4);
259  }
260 }
261 
262 std::string BTFTypeStruct::getName() { return STy->getName(); }
263 
264 /// The Func kind represents both subprogram and pointee of function
265 /// pointers. If the FuncName is empty, it represents a pointee of function
266 /// pointer. Otherwise, it represents a subprogram. The func arg names
267 /// are empty for pointee of function pointer case, and are valid names
268 /// for subprogram.
270  const DISubroutineType *STy, uint32_t VLen,
271  const std::unordered_map<uint32_t, StringRef> &FuncArgNames)
272  : STy(STy), FuncArgNames(FuncArgNames) {
273  Kind = BTF::BTF_KIND_FUNC_PROTO;
274  BTFType.Info = (Kind << 24) | VLen;
275 }
276 
278  if (IsCompleted)
279  return;
280  IsCompleted = true;
281 
282  DITypeRefArray Elements = STy->getTypeArray();
283  auto RetType = Elements[0];
284  BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
285  BTFType.NameOff = 0;
286 
287  // For null parameter which is typically the last one
288  // to represent the vararg, encode the NameOff/Type to be 0.
289  for (unsigned I = 1, N = Elements.size(); I < N; ++I) {
290  struct BTF::BTFParam Param;
291  auto Element = Elements[I];
292  if (Element) {
293  Param.NameOff = BDebug.addString(FuncArgNames[I]);
294  Param.Type = BDebug.getTypeId(Element);
295  } else {
296  Param.NameOff = 0;
297  Param.Type = 0;
298  }
299  Parameters.push_back(Param);
300  }
301 }
302 
305  for (const auto &Param : Parameters) {
306  OS.EmitIntValue(Param.NameOff, 4);
307  OS.EmitIntValue(Param.Type, 4);
308  }
309 }
310 
312  : Name(FuncName) {
313  Kind = BTF::BTF_KIND_FUNC;
314  BTFType.Info = Kind << 24;
315  BTFType.Type = ProtoTypeId;
316 }
317 
319  if (IsCompleted)
320  return;
321  IsCompleted = true;
322 
323  BTFType.NameOff = BDebug.addString(Name);
324 }
325 
327 
329  : Name(VarName) {
330  Kind = BTF::BTF_KIND_VAR;
331  BTFType.Info = Kind << 24;
332  BTFType.Type = TypeId;
333  Info = VarInfo;
334 }
335 
337  BTFType.NameOff = BDebug.addString(Name);
338 }
339 
342  OS.EmitIntValue(Info, 4);
343 }
344 
345 BTFKindDataSec::BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
346  : Asm(AsmPrt), Name(SecName) {
347  Kind = BTF::BTF_KIND_DATASEC;
348  BTFType.Info = Kind << 24;
349  BTFType.Size = 0;
350 }
351 
353  BTFType.NameOff = BDebug.addString(Name);
354  BTFType.Info |= Vars.size();
355 }
356 
359 
360  for (const auto &V : Vars) {
361  OS.EmitIntValue(std::get<0>(V), 4);
362  Asm->EmitLabelReference(std::get<1>(V), 4);
363  OS.EmitIntValue(std::get<2>(V), 4);
364  }
365 }
366 
368  // Check whether the string already exists.
369  for (auto &OffsetM : OffsetToIdMap) {
370  if (Table[OffsetM.second] == S)
371  return OffsetM.first;
372  }
373  // Not find, add to the string table.
374  uint32_t Offset = Size;
375  OffsetToIdMap[Offset] = Table.size();
376  Table.push_back(S);
377  Size += S.size() + 1;
378  return Offset;
379 }
380 
382  : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
383  LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
384  MapDefNotCollected(true) {
385  addString("\0");
386 }
387 
388 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
389  const DIType *Ty) {
390  TypeEntry->setId(TypeEntries.size() + 1);
391  uint32_t Id = TypeEntry->getId();
392  DIToIdMap[Ty] = Id;
393  TypeEntries.push_back(std::move(TypeEntry));
394  return Id;
395 }
396 
397 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
398  TypeEntry->setId(TypeEntries.size() + 1);
399  uint32_t Id = TypeEntry->getId();
400  TypeEntries.push_back(std::move(TypeEntry));
401  return Id;
402 }
403 
404 void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
405  // Only int types are supported in BTF.
406  uint32_t Encoding = BTy->getEncoding();
407  if (Encoding != dwarf::DW_ATE_boolean && Encoding != dwarf::DW_ATE_signed &&
408  Encoding != dwarf::DW_ATE_signed_char &&
409  Encoding != dwarf::DW_ATE_unsigned &&
410  Encoding != dwarf::DW_ATE_unsigned_char)
411  return;
412 
413  // Create a BTF type instance for this DIBasicType and put it into
414  // DIToIdMap for cross-type reference check.
415  auto TypeEntry = std::make_unique<BTFTypeInt>(
416  Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
417  TypeId = addType(std::move(TypeEntry), BTy);
418 }
419 
420 /// Handle subprogram or subroutine types.
421 void BTFDebug::visitSubroutineType(
422  const DISubroutineType *STy, bool ForSubprog,
423  const std::unordered_map<uint32_t, StringRef> &FuncArgNames,
424  uint32_t &TypeId) {
425  DITypeRefArray Elements = STy->getTypeArray();
426  uint32_t VLen = Elements.size() - 1;
427  if (VLen > BTF::MAX_VLEN)
428  return;
429 
430  // Subprogram has a valid non-zero-length name, and the pointee of
431  // a function pointer has an empty name. The subprogram type will
432  // not be added to DIToIdMap as it should not be referenced by
433  // any other types.
434  auto TypeEntry = std::make_unique<BTFTypeFuncProto>(STy, VLen, FuncArgNames);
435  if (ForSubprog)
436  TypeId = addType(std::move(TypeEntry)); // For subprogram
437  else
438  TypeId = addType(std::move(TypeEntry), STy); // For func ptr
439 
440  // Visit return type and func arg types.
441  for (const auto Element : Elements) {
442  visitTypeEntry(Element);
443  }
444 }
445 
446 /// Handle structure/union types.
447 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
448  uint32_t &TypeId) {
449  const DINodeArray Elements = CTy->getElements();
450  uint32_t VLen = Elements.size();
451  if (VLen > BTF::MAX_VLEN)
452  return;
453 
454  // Check whether we have any bitfield members or not
455  bool HasBitField = false;
456  for (const auto *Element : Elements) {
457  auto E = cast<DIDerivedType>(Element);
458  if (E->isBitField()) {
459  HasBitField = true;
460  break;
461  }
462  }
463 
464  auto TypeEntry =
465  std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
466  StructTypes.push_back(TypeEntry.get());
467  TypeId = addType(std::move(TypeEntry), CTy);
468 
469  // Visit all struct members.
470  for (const auto *Element : Elements)
471  visitTypeEntry(cast<DIDerivedType>(Element));
472 }
473 
474 void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
475  // Visit array element type.
476  uint32_t ElemTypeId;
477  const DIType *ElemType = CTy->getBaseType();
478  visitTypeEntry(ElemType, ElemTypeId, false, false);
479 
480  // Visit array dimensions.
481  DINodeArray Elements = CTy->getElements();
482  for (int I = Elements.size() - 1; I >= 0; --I) {
483  if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
484  if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
485  const DISubrange *SR = cast<DISubrange>(Element);
486  auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
487  int64_t Count = CI->getSExtValue();
488 
489  // For struct s { int b; char c[]; }, the c[] will be represented
490  // as an array with Count = -1.
491  auto TypeEntry =
492  std::make_unique<BTFTypeArray>(ElemTypeId,
493  Count >= 0 ? Count : 0);
494  if (I == 0)
495  ElemTypeId = addType(std::move(TypeEntry), CTy);
496  else
497  ElemTypeId = addType(std::move(TypeEntry));
498  }
499  }
500 
501  // The array TypeId is the type id of the outermost dimension.
502  TypeId = ElemTypeId;
503 
504  // The IR does not have a type for array index while BTF wants one.
505  // So create an array index type if there is none.
506  if (!ArrayIndexTypeId) {
507  auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
508  0, "__ARRAY_SIZE_TYPE__");
509  ArrayIndexTypeId = addType(std::move(TypeEntry));
510  }
511 }
512 
513 void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
514  DINodeArray Elements = CTy->getElements();
515  uint32_t VLen = Elements.size();
516  if (VLen > BTF::MAX_VLEN)
517  return;
518 
519  auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen);
520  TypeId = addType(std::move(TypeEntry), CTy);
521  // No need to visit base type as BTF does not encode it.
522 }
523 
524 /// Handle structure/union forward declarations.
525 void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
526  uint32_t &TypeId) {
527  auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
528  TypeId = addType(std::move(TypeEntry), CTy);
529 }
530 
531 /// Handle structure, union, array and enumeration types.
532 void BTFDebug::visitCompositeType(const DICompositeType *CTy,
533  uint32_t &TypeId) {
534  auto Tag = CTy->getTag();
535  if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
536  // Handle forward declaration differently as it does not have members.
537  if (CTy->isForwardDecl())
538  visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
539  else
540  visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
541  } else if (Tag == dwarf::DW_TAG_array_type)
542  visitArrayType(CTy, TypeId);
543  else if (Tag == dwarf::DW_TAG_enumeration_type)
544  visitEnumType(CTy, TypeId);
545 }
546 
547 /// Handle pointer, typedef, const, volatile, restrict and member types.
548 void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
549  bool CheckPointer, bool SeenPointer) {
550  unsigned Tag = DTy->getTag();
551 
552  /// Try to avoid chasing pointees, esp. structure pointees which may
553  /// unnecessary bring in a lot of types.
554  if (CheckPointer && !SeenPointer) {
555  SeenPointer = Tag == dwarf::DW_TAG_pointer_type;
556  }
557 
558  if (CheckPointer && SeenPointer) {
559  const DIType *Base = DTy->getBaseType();
560  if (Base) {
561  if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
562  auto CTag = CTy->getTag();
563  if ((CTag == dwarf::DW_TAG_structure_type ||
564  CTag == dwarf::DW_TAG_union_type) &&
565  !CTy->isForwardDecl()) {
566  /// Find a candidate, generate a fixup. Later on the struct/union
567  /// pointee type will be replaced with either a real type or
568  /// a forward declaration.
569  auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
570  auto &Fixup = FixupDerivedTypes[CTy->getName()];
571  Fixup.first = CTag == dwarf::DW_TAG_union_type;
572  Fixup.second.push_back(TypeEntry.get());
573  TypeId = addType(std::move(TypeEntry), DTy);
574  return;
575  }
576  }
577  }
578  }
579 
580  if (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_typedef ||
581  Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
582  Tag == dwarf::DW_TAG_restrict_type) {
583  auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
584  TypeId = addType(std::move(TypeEntry), DTy);
585  } else if (Tag != dwarf::DW_TAG_member) {
586  return;
587  }
588 
589  // Visit base type of pointer, typedef, const, volatile, restrict or
590  // struct/union member.
591  uint32_t TempTypeId = 0;
592  if (Tag == dwarf::DW_TAG_member)
593  visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
594  else
595  visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
596 }
597 
598 void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
599  bool CheckPointer, bool SeenPointer) {
600  if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
601  TypeId = DIToIdMap[Ty];
602  return;
603  }
604 
605  if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
606  visitBasicType(BTy, TypeId);
607  else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
608  visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(),
609  TypeId);
610  else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
611  visitCompositeType(CTy, TypeId);
612  else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
613  visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
614  else
615  llvm_unreachable("Unknown DIType");
616 }
617 
618 void BTFDebug::visitTypeEntry(const DIType *Ty) {
619  uint32_t TypeId;
620  visitTypeEntry(Ty, TypeId, false, false);
621 }
622 
623 void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
624  if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
625  TypeId = DIToIdMap[Ty];
626  return;
627  }
628 
629  // MapDef type is a struct type
630  const auto *CTy = dyn_cast<DICompositeType>(Ty);
631  if (!CTy)
632  return;
633 
634  auto Tag = CTy->getTag();
635  if (Tag != dwarf::DW_TAG_structure_type || CTy->isForwardDecl())
636  return;
637 
638  // Record this type
639  const DINodeArray Elements = CTy->getElements();
640  bool HasBitField = false;
641  for (const auto *Element : Elements) {
642  auto E = cast<DIDerivedType>(Element);
643  if (E->isBitField()) {
644  HasBitField = true;
645  break;
646  }
647  }
648 
649  auto TypeEntry =
650  std::make_unique<BTFTypeStruct>(CTy, true, HasBitField, Elements.size());
651  StructTypes.push_back(TypeEntry.get());
652  TypeId = addType(std::move(TypeEntry), CTy);
653 
654  // Visit all struct members
655  for (const auto *Element : Elements) {
656  const auto *MemberType = cast<DIDerivedType>(Element);
657  visitTypeEntry(MemberType->getBaseType());
658  }
659 }
660 
661 /// Read file contents from the actual file or from the source
662 std::string BTFDebug::populateFileContent(const DISubprogram *SP) {
663  auto File = SP->getFile();
664  std::string FileName;
665 
666  if (!File->getFilename().startswith("/") && File->getDirectory().size())
667  FileName = File->getDirectory().str() + "/" + File->getFilename().str();
668  else
669  FileName = File->getFilename();
670 
671  // No need to populate the contends if it has been populated!
672  if (FileContent.find(FileName) != FileContent.end())
673  return FileName;
674 
675  std::vector<std::string> Content;
676  std::string Line;
677  Content.push_back(Line); // Line 0 for empty string
678 
679  std::unique_ptr<MemoryBuffer> Buf;
680  auto Source = File->getSource();
681  if (Source)
683  else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
684  MemoryBuffer::getFile(FileName))
685  Buf = std::move(*BufOrErr);
686  if (Buf)
687  for (line_iterator I(*Buf, false), E; I != E; ++I)
688  Content.push_back(*I);
689 
690  FileContent[FileName] = Content;
691  return FileName;
692 }
693 
694 void BTFDebug::constructLineInfo(const DISubprogram *SP, MCSymbol *Label,
695  uint32_t Line, uint32_t Column) {
696  std::string FileName = populateFileContent(SP);
697  BTFLineInfo LineInfo;
698 
699  LineInfo.Label = Label;
700  LineInfo.FileNameOff = addString(FileName);
701  // If file content is not available, let LineOff = 0.
702  if (Line < FileContent[FileName].size())
703  LineInfo.LineOff = addString(FileContent[FileName][Line]);
704  else
705  LineInfo.LineOff = 0;
706  LineInfo.LineNum = Line;
707  LineInfo.ColumnNum = Column;
708  LineInfoTable[SecNameOff].push_back(LineInfo);
709 }
710 
711 void BTFDebug::emitCommonHeader() {
713  OS.EmitIntValue(BTF::MAGIC, 2);
714  OS.EmitIntValue(BTF::VERSION, 1);
715  OS.EmitIntValue(0, 1);
716 }
717 
718 void BTFDebug::emitBTFSection() {
719  // Do not emit section if no types and only "" string.
720  if (!TypeEntries.size() && StringTable.getSize() == 1)
721  return;
722 
723  MCContext &Ctx = OS.getContext();
724  OS.SwitchSection(Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0));
725 
726  // Emit header.
727  emitCommonHeader();
729 
730  uint32_t TypeLen = 0, StrLen;
731  for (const auto &TypeEntry : TypeEntries)
732  TypeLen += TypeEntry->getSize();
733  StrLen = StringTable.getSize();
734 
735  OS.EmitIntValue(0, 4);
736  OS.EmitIntValue(TypeLen, 4);
737  OS.EmitIntValue(TypeLen, 4);
738  OS.EmitIntValue(StrLen, 4);
739 
740  // Emit type table.
741  for (const auto &TypeEntry : TypeEntries)
742  TypeEntry->emitType(OS);
743 
744  // Emit string table.
745  uint32_t StringOffset = 0;
746  for (const auto &S : StringTable.getTable()) {
747  OS.AddComment("string offset=" + std::to_string(StringOffset));
748  OS.EmitBytes(S);
749  OS.EmitBytes(StringRef("\0", 1));
750  StringOffset += S.size() + 1;
751  }
752 }
753 
754 void BTFDebug::emitBTFExtSection() {
755  // Do not emit section if empty FuncInfoTable and LineInfoTable
756  // and FieldRelocTable.
757  if (!FuncInfoTable.size() && !LineInfoTable.size() &&
758  !FieldRelocTable.size())
759  return;
760 
761  MCContext &Ctx = OS.getContext();
762  OS.SwitchSection(Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0));
763 
764  // Emit header.
765  emitCommonHeader();
767 
768  // Account for FuncInfo/LineInfo record size as well.
769  uint32_t FuncLen = 4, LineLen = 4;
770  // Do not account for optional FieldReloc.
771  uint32_t FieldRelocLen = 0;
772  for (const auto &FuncSec : FuncInfoTable) {
773  FuncLen += BTF::SecFuncInfoSize;
774  FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
775  }
776  for (const auto &LineSec : LineInfoTable) {
777  LineLen += BTF::SecLineInfoSize;
778  LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
779  }
780  for (const auto &FieldRelocSec : FieldRelocTable) {
781  FieldRelocLen += BTF::SecFieldRelocSize;
782  FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
783  }
784 
785  if (FieldRelocLen)
786  FieldRelocLen += 4;
787 
788  OS.EmitIntValue(0, 4);
789  OS.EmitIntValue(FuncLen, 4);
790  OS.EmitIntValue(FuncLen, 4);
791  OS.EmitIntValue(LineLen, 4);
792  OS.EmitIntValue(FuncLen + LineLen, 4);
793  OS.EmitIntValue(FieldRelocLen, 4);
794 
795  // Emit func_info table.
796  OS.AddComment("FuncInfo");
798  for (const auto &FuncSec : FuncInfoTable) {
799  OS.AddComment("FuncInfo section string offset=" +
800  std::to_string(FuncSec.first));
801  OS.EmitIntValue(FuncSec.first, 4);
802  OS.EmitIntValue(FuncSec.second.size(), 4);
803  for (const auto &FuncInfo : FuncSec.second) {
804  Asm->EmitLabelReference(FuncInfo.Label, 4);
805  OS.EmitIntValue(FuncInfo.TypeId, 4);
806  }
807  }
808 
809  // Emit line_info table.
810  OS.AddComment("LineInfo");
812  for (const auto &LineSec : LineInfoTable) {
813  OS.AddComment("LineInfo section string offset=" +
814  std::to_string(LineSec.first));
815  OS.EmitIntValue(LineSec.first, 4);
816  OS.EmitIntValue(LineSec.second.size(), 4);
817  for (const auto &LineInfo : LineSec.second) {
818  Asm->EmitLabelReference(LineInfo.Label, 4);
819  OS.EmitIntValue(LineInfo.FileNameOff, 4);
820  OS.EmitIntValue(LineInfo.LineOff, 4);
821  OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
822  std::to_string(LineInfo.ColumnNum));
823  OS.EmitIntValue(LineInfo.LineNum << 10 | LineInfo.ColumnNum, 4);
824  }
825  }
826 
827  // Emit field reloc table.
828  if (FieldRelocLen) {
829  OS.AddComment("FieldReloc");
831  for (const auto &FieldRelocSec : FieldRelocTable) {
832  OS.AddComment("Field reloc section string offset=" +
833  std::to_string(FieldRelocSec.first));
834  OS.EmitIntValue(FieldRelocSec.first, 4);
835  OS.EmitIntValue(FieldRelocSec.second.size(), 4);
836  for (const auto &FieldRelocInfo : FieldRelocSec.second) {
837  Asm->EmitLabelReference(FieldRelocInfo.Label, 4);
838  OS.EmitIntValue(FieldRelocInfo.TypeID, 4);
839  OS.EmitIntValue(FieldRelocInfo.OffsetNameOff, 4);
840  OS.EmitIntValue(FieldRelocInfo.RelocKind, 4);
841  }
842  }
843  }
844 }
845 
847  auto *SP = MF->getFunction().getSubprogram();
848  auto *Unit = SP->getUnit();
849 
850  if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
851  SkipInstruction = true;
852  return;
853  }
854  SkipInstruction = false;
855 
856  // Collect MapDef types. Map definition needs to collect
857  // pointee types. Do it first. Otherwise, for the following
858  // case:
859  // struct m { ...};
860  // struct t {
861  // struct m *key;
862  // };
863  // foo(struct t *arg);
864  //
865  // struct mapdef {
866  // ...
867  // struct m *key;
868  // ...
869  // } __attribute__((section(".maps"))) hash_map;
870  //
871  // If subroutine foo is traversed first, a type chain
872  // "ptr->struct m(fwd)" will be created and later on
873  // when traversing mapdef, since "ptr->struct m" exists,
874  // the traversal of "struct m" will be omitted.
875  if (MapDefNotCollected) {
876  processGlobals(true);
877  MapDefNotCollected = false;
878  }
879 
880  // Collect all types locally referenced in this function.
881  // Use RetainedNodes so we can collect all argument names
882  // even if the argument is not used.
883  std::unordered_map<uint32_t, StringRef> FuncArgNames;
884  for (const DINode *DN : SP->getRetainedNodes()) {
885  if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
886  // Collect function arguments for subprogram func type.
887  uint32_t Arg = DV->getArg();
888  if (Arg) {
889  visitTypeEntry(DV->getType());
890  FuncArgNames[Arg] = DV->getName();
891  }
892  }
893  }
894 
895  // Construct subprogram func proto type.
896  uint32_t ProtoTypeId;
897  visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
898 
899  // Construct subprogram func type
900  auto FuncTypeEntry =
901  std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId);
902  uint32_t FuncTypeId = addType(std::move(FuncTypeEntry));
903 
904  for (const auto &TypeEntry : TypeEntries)
905  TypeEntry->completeType(*this);
906 
907  // Construct funcinfo and the first lineinfo for the function.
908  MCSymbol *FuncLabel = Asm->getFunctionBegin();
909  BTFFuncInfo FuncInfo;
910  FuncInfo.Label = FuncLabel;
911  FuncInfo.TypeId = FuncTypeId;
912  if (FuncLabel->isInSection()) {
913  MCSection &Section = FuncLabel->getSection();
914  const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section);
915  assert(SectionELF && "Null section for Function Label");
916  SecNameOff = addString(SectionELF->getSectionName());
917  } else {
918  SecNameOff = addString(".text");
919  }
920  FuncInfoTable[SecNameOff].push_back(FuncInfo);
921 }
922 
924  SkipInstruction = false;
925  LineInfoGenerated = false;
926  SecNameOff = 0;
927 }
928 
929 /// On-demand populate struct types as requested from abstract member
930 /// accessing.
931 unsigned BTFDebug::populateStructType(const DIType *Ty) {
932  unsigned Id;
933  visitTypeEntry(Ty, Id, false, false);
934  for (const auto &TypeEntry : TypeEntries)
935  TypeEntry->completeType(*this);
936  return Id;
937 }
938 
939 /// Generate a struct member field relocation.
940 void BTFDebug::generateFieldReloc(const MachineInstr *MI,
941  const MCSymbol *ORSym, DIType *RootTy,
942  StringRef AccessPattern) {
943  unsigned RootId = populateStructType(RootTy);
944  size_t FirstDollar = AccessPattern.find_first_of('$');
945  size_t FirstColon = AccessPattern.find_first_of(':');
946  size_t SecondColon = AccessPattern.find_first_of(':', FirstColon + 1);
947  StringRef IndexPattern = AccessPattern.substr(FirstDollar + 1);
948  StringRef RelocKindStr = AccessPattern.substr(FirstColon + 1,
949  SecondColon - FirstColon);
950  StringRef PatchImmStr = AccessPattern.substr(SecondColon + 1,
951  FirstDollar - SecondColon);
952 
953  BTFFieldReloc FieldReloc;
954  FieldReloc.Label = ORSym;
955  FieldReloc.OffsetNameOff = addString(IndexPattern);
956  FieldReloc.TypeID = RootId;
957  FieldReloc.RelocKind = std::stoull(RelocKindStr);
958  PatchImms[AccessPattern.str()] = std::stoul(PatchImmStr);
959  FieldRelocTable[SecNameOff].push_back(FieldReloc);
960 }
961 
962 void BTFDebug::processLDimm64(const MachineInstr *MI) {
963  // If the insn is an LD_imm64, the following two cases
964  // will generate an .BTF.ext record.
965  //
966  // If the insn is "r2 = LD_imm64 @__BTF_...",
967  // add this insn into the .BTF.ext FieldReloc subsection.
968  // Relocation looks like:
969  // . SecName:
970  // . InstOffset
971  // . TypeID
972  // . OffSetNameOff
973  // Later, the insn is replaced with "r2 = <offset>"
974  // where "<offset>" equals to the offset based on current
975  // type definitions.
976  //
977  // If the insn is "r2 = LD_imm64 @VAR" and VAR is
978  // a patchable external global, add this insn into the .BTF.ext
979  // ExternReloc subsection.
980  // Relocation looks like:
981  // . SecName:
982  // . InstOffset
983  // . ExternNameOff
984  // Later, the insn is replaced with "r2 = <value>" or
985  // "LD_imm64 r2, <value>" where "<value>" = 0.
986 
987  // check whether this is a candidate or not
988  const MachineOperand &MO = MI->getOperand(1);
989  if (MO.isGlobal()) {
990  const GlobalValue *GVal = MO.getGlobal();
991  auto *GVar = dyn_cast<GlobalVariable>(GVal);
992  if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
993  MCSymbol *ORSym = OS.getContext().createTempSymbol();
994  OS.EmitLabel(ORSym);
995 
996  MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
997  DIType *Ty = dyn_cast<DIType>(MDN);
998  generateFieldReloc(MI, ORSym, Ty, GVar->getName());
999  }
1000  }
1001 }
1002 
1005 
1006  if (SkipInstruction || MI->isMetaInstruction() ||
1008  return;
1009 
1010  if (MI->isInlineAsm()) {
1011  // Count the number of register definitions to find the asm string.
1012  unsigned NumDefs = 0;
1013  for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1014  ++NumDefs)
1015  ;
1016 
1017  // Skip this inline asm instruction if the asmstr is empty.
1018  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1019  if (AsmStr[0] == 0)
1020  return;
1021  }
1022 
1023  if (MI->getOpcode() == BPF::LD_imm64)
1024  processLDimm64(MI);
1025 
1026  // Skip this instruction if no DebugLoc or the DebugLoc
1027  // is the same as the previous instruction.
1028  const DebugLoc &DL = MI->getDebugLoc();
1029  if (!DL || PrevInstLoc == DL) {
1030  // This instruction will be skipped, no LineInfo has
1031  // been generated, construct one based on function signature.
1032  if (LineInfoGenerated == false) {
1033  auto *S = MI->getMF()->getFunction().getSubprogram();
1034  MCSymbol *FuncLabel = Asm->getFunctionBegin();
1035  constructLineInfo(S, FuncLabel, S->getLine(), 0);
1036  LineInfoGenerated = true;
1037  }
1038 
1039  return;
1040  }
1041 
1042  // Create a temporary label to remember the insn for lineinfo.
1043  MCSymbol *LineSym = OS.getContext().createTempSymbol();
1044  OS.EmitLabel(LineSym);
1045 
1046  // Construct the lineinfo.
1047  auto SP = DL.get()->getScope()->getSubprogram();
1048  constructLineInfo(SP, LineSym, DL.getLine(), DL.getCol());
1049 
1050  LineInfoGenerated = true;
1051  PrevInstLoc = DL;
1052 }
1053 
1054 void BTFDebug::processGlobals(bool ProcessingMapDef) {
1055  // Collect all types referenced by globals.
1056  const Module *M = MMI->getModule();
1057  for (const GlobalVariable &Global : M->globals()) {
1058  // Ignore external globals for now.
1059  if (!Global.hasInitializer() && Global.hasExternalLinkage())
1060  continue;
1061 
1062  // Decide the section name.
1063  StringRef SecName;
1064  if (Global.hasSection()) {
1065  SecName = Global.getSection();
1066  } else {
1067  // data, bss, or readonly sections
1068  if (Global.isConstant())
1069  SecName = ".rodata";
1070  else
1071  SecName = Global.getInitializer()->isZeroValue() ? ".bss" : ".data";
1072  }
1073 
1074  if (ProcessingMapDef != SecName.startswith(".maps"))
1075  continue;
1076 
1078  Global.getDebugInfo(GVs);
1079  uint32_t GVTypeId = 0;
1080  for (auto *GVE : GVs) {
1081  if (SecName.startswith(".maps"))
1082  visitMapDefType(GVE->getVariable()->getType(), GVTypeId);
1083  else
1084  visitTypeEntry(GVE->getVariable()->getType(), GVTypeId, false, false);
1085  break;
1086  }
1087 
1088  // Only support the following globals:
1089  // . static variables
1090  // . non-static global variables with section attributes
1091  // Essentially means:
1092  // . .bcc/.data/.rodata DataSec entities only contain static data
1093  // . Other DataSec entities contain static or initialized global data.
1094  // Initialized global data are mostly used for finding map key/value type
1095  // id's. Whether DataSec is readonly or not can be found from
1096  // corresponding ELF section flags.
1097  auto Linkage = Global.getLinkage();
1099  (Linkage != GlobalValue::ExternalLinkage || !Global.hasSection()))
1100  continue;
1101 
1104  : BTF::VAR_STATIC;
1105  auto VarEntry =
1106  std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
1107  uint32_t VarId = addType(std::move(VarEntry));
1108 
1109  // Find or create a DataSec
1110  if (DataSecEntries.find(SecName) == DataSecEntries.end()) {
1111  DataSecEntries[SecName] = std::make_unique<BTFKindDataSec>(Asm, SecName);
1112  }
1113 
1114  // Calculate symbol size
1115  const DataLayout &DL = Global.getParent()->getDataLayout();
1116  uint32_t Size = DL.getTypeAllocSize(Global.getType()->getElementType());
1117 
1118  DataSecEntries[SecName]->addVar(VarId, Asm->getSymbol(&Global), Size);
1119  }
1120 }
1121 
1122 /// Emit proper patchable instructions.
1123 bool BTFDebug::InstLower(const MachineInstr *MI, MCInst &OutMI) {
1124  if (MI->getOpcode() == BPF::LD_imm64) {
1125  const MachineOperand &MO = MI->getOperand(1);
1126  if (MO.isGlobal()) {
1127  const GlobalValue *GVal = MO.getGlobal();
1128  auto *GVar = dyn_cast<GlobalVariable>(GVal);
1129  if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1130  // Emit "mov ri, <imm>" for patched immediate.
1131  uint32_t Imm = PatchImms[GVar->getName().str()];
1132  OutMI.setOpcode(BPF::MOV_ri);
1134  OutMI.addOperand(MCOperand::createImm(Imm));
1135  return true;
1136  }
1137  }
1138  }
1139  return false;
1140 }
1141 
1143  // Collect MapDef globals if not collected yet.
1144  if (MapDefNotCollected) {
1145  processGlobals(true);
1146  MapDefNotCollected = false;
1147  }
1148 
1149  // Collect global types/variables except MapDef globals.
1150  processGlobals(false);
1151  for (auto &DataSec : DataSecEntries)
1152  addType(std::move(DataSec.second));
1153 
1154  // Fixups
1155  for (auto &Fixup : FixupDerivedTypes) {
1156  StringRef TypeName = Fixup.first;
1157  bool IsUnion = Fixup.second.first;
1158 
1159  // Search through struct types
1160  uint32_t StructTypeId = 0;
1161  for (const auto &StructType : StructTypes) {
1162  if (StructType->getName() == TypeName) {
1163  StructTypeId = StructType->getId();
1164  break;
1165  }
1166  }
1167 
1168  if (StructTypeId == 0) {
1169  auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
1170  StructTypeId = addType(std::move(FwdTypeEntry));
1171  }
1172 
1173  for (auto &DType : Fixup.second.second) {
1174  DType->setPointeeType(StructTypeId);
1175  }
1176  }
1177 
1178  // Complete BTF type cross refereences.
1179  for (const auto &TypeEntry : TypeEntries)
1180  TypeEntry->completeType(*this);
1181 
1182  // Emit BTF sections.
1183  emitBTFSection();
1184  emitBTFExtSection();
1185 }
uint32_t RelocKind
What to patch the instruction.
Definition: BTFDebug.h:231
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:39
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:112
BTFTypeArray(uint32_t ElemTypeId, uint32_t NumElems)
Definition: BTFDebug.cpp:187
Represents either an error or a value T.
Definition: ErrorOr.h:56
uint32_t Type
Definition: BTF.h:176
uint64_t getOffsetInBits() const
Max # of struct/union/enum members or func args.
Definition: BTF.h:89
void endFunctionImpl(const MachineFunction *MF) override
Post process after all instructions in this function are processed.
Definition: BTFDebug.cpp:923
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
Represent one func and its type id.
Definition: BTFDebug.h:212
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:232
BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
Definition: BTFDebug.cpp:345
BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId)
Definition: BTFDebug.cpp:311
uint32_t ColumnNum
the column number
Definition: BTFDebug.h:223
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
uint32_t NameOff
Definition: BTF.h:175
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
unsigned size() const
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:270
DIFile * getFile() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:385
uint32_t getArrayIndexTypeId()
Get the special array index type id.
Definition: BTFDebug.h:329
virtual void EmitBytes(StringRef Data)
Emit the bytes in Data into the output.
bool isInlineAsm() const
uint32_t getSize()
Definition: BTFDebug.h:204
BTFTypeEnum(const DICompositeType *ETy, uint32_t NumValues)
Definition: BTFDebug.cpp:154
iterator find(StringRef Key)
Definition: StringMap.h:355
Externally visible function.
Definition: GlobalValue.h:48
BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits, uint32_t OffsetInBits, StringRef TypeName)
Definition: BTFDebug.cpp:113
A forward iterator which reads text lines from a buffer.
Definition: LineIterator.h:31
void completeType(BTFDebug &BDebug)
Represent a BTF array.
Definition: BTFDebug.cpp:198
unsigned getLine() const
Definition: DebugLoc.cpp:25
uint32_t Size
Definition: BTF.h:119
A debug info location.
Definition: DebugLoc.h:33
Metadata node.
Definition: Metadata.h:863
block Block Frequency true
bool isMetaInstruction() const
Return true if this instruction doesn&#39;t produce any output in the form of executable instructions...
bool isForwardDecl() const
static const char * BTFKindStr[]
Definition: BTFDebug.cpp:28
uint32_t Offset
BitOffset or BitFieldSize+BitOffset.
Definition: BTF.h:168
std::string getName()
Definition: BTFDebug.cpp:262
StringRef getName() const
Tagged DWARF-like metadata node.
DINodeArray getElements() const
uint32_t Type
Member type.
Definition: BTF.h:167
MCContext & getContext() const
Definition: MCStreamer.h:252
DebugLoc PrevInstLoc
Previous instruction&#39;s location information.
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:326
BTFTypeDerived(const DIDerivedType *Ty, unsigned Tag, bool NeedsFixup)
Definition: BTFDebug.cpp:43
static MCOperand createReg(unsigned Reg)
Definition: MCInst.h:115
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:303
unsigned getTag() const
Class to represent struct types.
Definition: DerivedTypes.h:238
Array subrange.
virtual void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:34
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute)...
Definition: MCSymbol.h:253
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:140
BTF_KIND_ENUM is followed by multiple "struct BTFEnum".
Definition: BTF.h:143
BTFKindVar(StringRef VarName, uint32_t TypeId, uint32_t VarInfo)
Definition: BTFDebug.cpp:328
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:411
uint32_t roundupToBytes(uint32_t NumBits)
Definition: BTFDebug.h:44
uint64_t getSizeInBits() const
const char * getSymbolName() const
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:592
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
Definition: BTFDebug.cpp:846
Context object for machine code objects.
Definition: MCContext.h:65
Subprogram description.
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition: MCStreamer.h:311
DIType * getBaseType() const
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:160
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:212
uint32_t Type
Definition: BTF.h:120
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:144
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:357
virtual void EmitIntValue(uint64_t Value, unsigned Size)
Special case of EmitValue that avoids the client having to pass in a MCExpr for constant integers...
Definition: MCStreamer.cpp:130
Represent one offset relocation.
Definition: BTFDebug.h:227
BTF_KIND_FUNC_PROTO are followed by multiple "struct BTFParam".
Definition: BTF.h:174
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
Analysis containing CSE Info
Definition: CSEInfo.cpp:20
void endModule() override
Complete all the types and emit the BTF sections.
Definition: BTFDebug.cpp:1142
uint8_t Kind
Definition: BTFDebug.h:34
BTFTypeStruct(const DICompositeType *STy, bool IsStruct, bool HasBitField, uint32_t NumMembers)
Represent either a struct or a union.
Definition: BTFDebug.cpp:218
Streaming machine code generation interface.
Definition: MCStreamer.h:190
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:225
Linkage: InternalLinkage.
Definition: BTF.h:181
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:103
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:352
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1504
Instrumentation for Order File
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
virtual void SwitchSection(MCSection *Section, const MCExpr *Subsection=nullptr)
Set the current section where code is being emitted to Section.
CountType getCount() const
struct BTF::CommonType BTFType
Definition: BTFDebug.h:37
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
Definition: BTFDebug.cpp:1003
const GlobalValue * getGlobal() const
AsmPrinter * Asm
Target of debug info emission.
Collect and emit BTF information.
Definition: BTFDebug.h:235
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:78
uint32_t NameOff
Member name offset in the string table.
Definition: BTF.h:166
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:148
bool InstLower(const MachineInstr *MI, MCInst &OutMI)
Emit proper patchable instructions.
Definition: BTFDebug.cpp:1123
StringRef getName() const
Return the name for this struct type if it has an identity.
Definition: Type.cpp:504
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:336
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
void EmitLabelReference(const MCSymbol *Label, unsigned Size, bool IsSectionRelative=false) const
Emit something like ".long Label" where the size in bytes of the directive is specified by Size and L...
Definition: AsmPrinter.h:506
Represent one line info.
Definition: BTFDebug.h:218
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
BTF_KIND_STRUCT and BTF_KIND_UNION are followed by multiple "struct BTFMember".
Definition: BTF.h:165
uint32_t NameOff
Type name offset in the string table.
Definition: BTF.h:101
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:179
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
PowerPC TLS Dynamic Call Fixup
std::vector< std::string > & getTable()
Definition: BTFDebug.h:205
void setOpcode(unsigned Op)
Definition: MCInst.h:170
Base class for types.
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
uint32_t LineNum
the line number
Definition: BTFDebug.h:222
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1146
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
uint32_t Id
Definition: BTFDebug.h:36
StringRef getName() const
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:449
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
int32_t Val
Enum member value.
Definition: BTF.h:145
uint32_t NameOff
Enum name offset in the string table.
Definition: BTF.h:144
void setPointeeType(uint32_t PointeeType)
Definition: BTFDebug.cpp:92
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:226
MCSymbol * Label
MCSymbol identifying insn for the lineinfo.
Definition: BTFDebug.h:219
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:387
uint32_t getTypeId(const DIType *Ty)
Get the type id for a particular DIType.
Definition: BTFDebug.h:338
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:277
const Function & getFunction() const
Return the LLVM function that this machine code represents.
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it...
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:268
This file contains support for writing BTF debug info.
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:210
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:68
BTFDebug(AsmPrinter *AP)
Definition: BTFDebug.cpp:381
Type array for a subprogram.
Representation of each machine instruction.
Definition: MachineInstr.h:64
uint32_t OffsetNameOff
The string to traverse types.
Definition: BTFDebug.h:230
uint32_t addString(StringRef S)
Add a string to the string table and returns its offset in the table.
Definition: BTFDebug.cpp:367
unsigned getEncoding() const
BTFTypeFwd(StringRef Name, bool IsUnion)
Represent a struct/union forward declaration.
Definition: BTFDebug.cpp:97
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:394
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:111
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
Linkage: ExternalLinkage.
Definition: BTF.h:182
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:27
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Base class for debug information backends.
BTFTypeFuncProto(const DISubroutineType *STy, uint32_t NumParams, const std::unordered_map< uint32_t, StringRef > &FuncArgNames)
The Func kind represents both subprogram and pointee of function pointers.
Definition: BTFDebug.cpp:269
uint32_t Size
Definition: Profile.cpp:46
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
static const std::string AmaAttr
The attribute attached to globals representing a field access.
Definition: BPFCORE.h:27
const MCSymbol * Label
Func MCSymbol.
Definition: BTFDebug.h:213
const Module * getModule() const
uint32_t FileNameOff
file name offset in the .BTF string table
Definition: BTFDebug.h:220
size_t addString(StringRef S)
Add string to the string table.
Definition: BTFDebug.h:335
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const std::string to_string(const T &Value)
Definition: ScopedPrinter.h:61
unsigned getCol() const
Definition: DebugLoc.cpp:30
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:318
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:424
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:90
virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:399
DITypeRefArray getTypeArray() const
MachineModuleInfo * MMI
Collected machine module information.
iterator_range< global_iterator > globals()
Definition: Module.h:587
IRTranslator LLVM IR MI
void addOperand(const MCOperand &Op)
Definition: MCInst.h:183
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
uint32_t Info
"Info" bits arrangement: Bits 0-15: vlen (e.g.
Definition: BTF.h:110
Register getReg() const
getReg - Returns the register number.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:156
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:340
const MCSymbol * Label
MCSymbol identifying insn for the reloc.
Definition: BTFDebug.h:228
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:416
uint32_t TypeID
Type ID.
Definition: BTFDebug.h:229
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:122
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:252
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
Definition: MachineInstr.h:297
iterator end()
Definition: StringMap.h:340
uint32_t TypeId
Type id referring to .BTF type section.
Definition: BTFDebug.h:214
StringRef getSectionName() const
Definition: MCSectionELF.h:70
uint32_t LineOff
line offset in the .BTF string table
Definition: BTFDebug.h:221
Basic type, like &#39;int&#39; or &#39;float&#39;.