LLVM  9.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 "llvm/BinaryFormat/ELF.h"
17 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCSectionELF.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include <fstream>
22 #include <sstream>
23 
24 using namespace llvm;
25 
26 static const char *BTFKindStr[] = {
27 #define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
28 #include "BTF.def"
29 };
30 
31 /// Emit a BTF common type.
33  OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
34  ")");
37  OS.EmitIntValue(BTFType.Info, 4);
38  OS.EmitIntValue(BTFType.Size, 4);
39 }
40 
42  : DTy(DTy) {
43  switch (Tag) {
44  case dwarf::DW_TAG_pointer_type:
45  Kind = BTF::BTF_KIND_PTR;
46  break;
47  case dwarf::DW_TAG_const_type:
48  Kind = BTF::BTF_KIND_CONST;
49  break;
50  case dwarf::DW_TAG_volatile_type:
51  Kind = BTF::BTF_KIND_VOLATILE;
52  break;
53  case dwarf::DW_TAG_typedef:
54  Kind = BTF::BTF_KIND_TYPEDEF;
55  break;
56  case dwarf::DW_TAG_restrict_type:
57  Kind = BTF::BTF_KIND_RESTRICT;
58  break;
59  default:
60  llvm_unreachable("Unknown DIDerivedType Tag");
61  }
62  BTFType.Info = Kind << 24;
63 }
64 
66  BTFType.NameOff = BDebug.addString(DTy->getName());
67 
68  // The base type for PTR/CONST/VOLATILE could be void.
69  const DIType *ResolvedType = DTy->getBaseType().resolve();
70  if (!ResolvedType) {
71  assert((Kind == BTF::BTF_KIND_PTR || Kind == BTF::BTF_KIND_CONST ||
72  Kind == BTF::BTF_KIND_VOLATILE) &&
73  "Invalid null basetype");
74  BTFType.Type = 0;
75  } else {
76  BTFType.Type = BDebug.getTypeId(ResolvedType);
77  }
78 }
79 
81 
82 /// Represent a struct/union forward declaration.
83 BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) {
84  Kind = BTF::BTF_KIND_FWD;
85  BTFType.Info = IsUnion << 31 | Kind << 24;
86  BTFType.Type = 0;
87 }
88 
90  BTFType.NameOff = BDebug.addString(Name);
91 }
92 
94 
96  uint32_t OffsetInBits, StringRef TypeName)
97  : Name(TypeName) {
98  // Translate IR int encoding to BTF int encoding.
99  uint8_t BTFEncoding;
100  switch (Encoding) {
101  case dwarf::DW_ATE_boolean:
102  BTFEncoding = BTF::INT_BOOL;
103  break;
104  case dwarf::DW_ATE_signed:
105  case dwarf::DW_ATE_signed_char:
106  BTFEncoding = BTF::INT_SIGNED;
107  break;
108  case dwarf::DW_ATE_unsigned:
109  case dwarf::DW_ATE_unsigned_char:
110  BTFEncoding = 0;
111  break;
112  default:
113  llvm_unreachable("Unknown BTFTypeInt Encoding");
114  }
115 
116  Kind = BTF::BTF_KIND_INT;
117  BTFType.Info = Kind << 24;
118  BTFType.Size = roundupToBytes(SizeInBits);
119  IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits;
120 }
121 
123  BTFType.NameOff = BDebug.addString(Name);
124 }
125 
128  OS.AddComment("0x" + Twine::utohexstr(IntVal));
129  OS.EmitIntValue(IntVal, 4);
130 }
131 
132 BTFTypeEnum::BTFTypeEnum(const DICompositeType *ETy, uint32_t VLen) : ETy(ETy) {
133  Kind = BTF::BTF_KIND_ENUM;
134  BTFType.Info = Kind << 24 | VLen;
136 }
137 
139  BTFType.NameOff = BDebug.addString(ETy->getName());
140 
141  DINodeArray Elements = ETy->getElements();
142  for (const auto Element : Elements) {
143  const auto *Enum = cast<DIEnumerator>(Element);
144 
145  struct BTF::BTFEnum BTFEnum;
146  BTFEnum.NameOff = BDebug.addString(Enum->getName());
147  // BTF enum value is 32bit, enforce it.
148  BTFEnum.Val = static_cast<uint32_t>(Enum->getValue());
149  EnumValues.push_back(BTFEnum);
150  }
151 }
152 
155  for (const auto &Enum : EnumValues) {
156  OS.EmitIntValue(Enum.NameOff, 4);
157  OS.EmitIntValue(Enum.Val, 4);
158  }
159 }
160 
162  Kind = BTF::BTF_KIND_ARRAY;
163  BTFType.Info = Kind << 24;
164 }
165 
166 /// Represent a BTF array. BTF does not record array dimensions,
167 /// so conceptually a BTF array is a one-dimensional array.
169  BTFType.NameOff = BDebug.addString(ATy->getName());
170  BTFType.Size = 0;
171 
172  auto *BaseType = ATy->getBaseType().resolve();
173  ArrayInfo.ElemType = BDebug.getTypeId(BaseType);
174 
175  // The IR does not really have a type for the index.
176  // A special type for array index should have been
177  // created during initial type traversal. Just
178  // retrieve that type id.
179  ArrayInfo.IndexType = BDebug.getArrayIndexTypeId();
180 
181  // Get the number of array elements.
182  // If the array size is 0, set the number of elements as 0.
183  // Otherwise, recursively traverse the base types to
184  // find the element size. The number of elements is
185  // the totoal array size in bits divided by
186  // element size in bits.
187  uint64_t ArraySizeInBits = ATy->getSizeInBits();
188  if (!ArraySizeInBits) {
189  ArrayInfo.Nelems = 0;
190  } else {
191  uint32_t BaseTypeSize = BaseType->getSizeInBits();
192  while (!BaseTypeSize) {
193  const auto *DDTy = cast<DIDerivedType>(BaseType);
194  BaseType = DDTy->getBaseType().resolve();
195  assert(BaseType);
196  BaseTypeSize = BaseType->getSizeInBits();
197  }
198  ArrayInfo.Nelems = ATy->getSizeInBits() / BaseTypeSize;
199  }
200 }
201 
204  OS.EmitIntValue(ArrayInfo.ElemType, 4);
205  OS.EmitIntValue(ArrayInfo.IndexType, 4);
206  OS.EmitIntValue(ArrayInfo.Nelems, 4);
207 }
208 
209 /// Represent either a struct or a union.
211  bool HasBitField, uint32_t Vlen)
212  : STy(STy), HasBitField(HasBitField) {
213  Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
215  BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
216 }
217 
219  BTFType.NameOff = BDebug.addString(STy->getName());
220 
221  // Add struct/union members.
222  const DINodeArray Elements = STy->getElements();
223  for (const auto *Element : Elements) {
224  struct BTF::BTFMember BTFMember;
225  const auto *DDTy = cast<DIDerivedType>(Element);
226 
227  BTFMember.NameOff = BDebug.addString(DDTy->getName());
228  if (HasBitField) {
229  uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0;
230  BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits();
231  } else {
232  BTFMember.Offset = DDTy->getOffsetInBits();
233  }
234  BTFMember.Type = BDebug.getTypeId(DDTy->getBaseType().resolve());
235  Members.push_back(BTFMember);
236  }
237 }
238 
241  for (const auto &Member : Members) {
242  OS.EmitIntValue(Member.NameOff, 4);
243  OS.EmitIntValue(Member.Type, 4);
244  OS.AddComment("0x" + Twine::utohexstr(Member.Offset));
245  OS.EmitIntValue(Member.Offset, 4);
246  }
247 }
248 
249 /// The Func kind represents both subprogram and pointee of function
250 /// pointers. If the FuncName is empty, it represents a pointee of function
251 /// pointer. Otherwise, it represents a subprogram. The func arg names
252 /// are empty for pointee of function pointer case, and are valid names
253 /// for subprogram.
255  const DISubroutineType *STy, uint32_t VLen,
256  const std::unordered_map<uint32_t, StringRef> &FuncArgNames)
257  : STy(STy), FuncArgNames(FuncArgNames) {
258  Kind = BTF::BTF_KIND_FUNC_PROTO;
259  BTFType.Info = (Kind << 24) | VLen;
260 }
261 
263  DITypeRefArray Elements = STy->getTypeArray();
264  auto RetType = Elements[0].resolve();
265  BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
266  BTFType.NameOff = 0;
267 
268  // For null parameter which is typically the last one
269  // to represent the vararg, encode the NameOff/Type to be 0.
270  for (unsigned I = 1, N = Elements.size(); I < N; ++I) {
271  struct BTF::BTFParam Param;
272  auto Element = Elements[I].resolve();
273  if (Element) {
274  Param.NameOff = BDebug.addString(FuncArgNames[I]);
275  Param.Type = BDebug.getTypeId(Element);
276  } else {
277  Param.NameOff = 0;
278  Param.Type = 0;
279  }
280  Parameters.push_back(Param);
281  }
282 }
283 
286  for (const auto &Param : Parameters) {
287  OS.EmitIntValue(Param.NameOff, 4);
288  OS.EmitIntValue(Param.Type, 4);
289  }
290 }
291 
293  : Name(FuncName) {
294  Kind = BTF::BTF_KIND_FUNC;
295  BTFType.Info = Kind << 24;
296  BTFType.Type = ProtoTypeId;
297 }
298 
300  BTFType.NameOff = BDebug.addString(Name);
301 }
302 
304 
306  // Check whether the string already exists.
307  for (auto &OffsetM : OffsetToIdMap) {
308  if (Table[OffsetM.second] == S)
309  return OffsetM.first;
310  }
311  // Not find, add to the string table.
312  uint32_t Offset = Size;
313  OffsetToIdMap[Offset] = Table.size();
314  Table.push_back(S);
315  Size += S.size() + 1;
316  return Offset;
317 }
318 
320  : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
321  LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0) {
322  addString("\0");
323 }
324 
325 void BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
326  const DIType *Ty) {
327  TypeEntry->setId(TypeEntries.size() + 1);
328  DIToIdMap[Ty] = TypeEntry->getId();
329  TypeEntries.push_back(std::move(TypeEntry));
330 }
331 
332 uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
333  TypeEntry->setId(TypeEntries.size() + 1);
334  uint32_t Id = TypeEntry->getId();
335  TypeEntries.push_back(std::move(TypeEntry));
336  return Id;
337 }
338 
339 void BTFDebug::visitBasicType(const DIBasicType *BTy) {
340  // Only int types are supported in BTF.
341  uint32_t Encoding = BTy->getEncoding();
342  if (Encoding != dwarf::DW_ATE_boolean && Encoding != dwarf::DW_ATE_signed &&
343  Encoding != dwarf::DW_ATE_signed_char &&
344  Encoding != dwarf::DW_ATE_unsigned &&
345  Encoding != dwarf::DW_ATE_unsigned_char)
346  return;
347 
348  // Create a BTF type instance for this DIBasicType and put it into
349  // DIToIdMap for cross-type reference check.
350  auto TypeEntry = llvm::make_unique<BTFTypeInt>(
351  Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
352  addType(std::move(TypeEntry), BTy);
353 }
354 
355 /// Handle subprogram or subroutine types.
356 void BTFDebug::visitSubroutineType(
357  const DISubroutineType *STy, bool ForSubprog,
358  const std::unordered_map<uint32_t, StringRef> &FuncArgNames,
359  uint32_t &TypeId) {
360  DITypeRefArray Elements = STy->getTypeArray();
361  uint32_t VLen = Elements.size() - 1;
362  if (VLen > BTF::MAX_VLEN)
363  return;
364 
365  // Subprogram has a valid non-zero-length name, and the pointee of
366  // a function pointer has an empty name. The subprogram type will
367  // not be added to DIToIdMap as it should not be referenced by
368  // any other types.
369  auto TypeEntry = llvm::make_unique<BTFTypeFuncProto>(STy, VLen, FuncArgNames);
370  if (ForSubprog)
371  TypeId = addType(std::move(TypeEntry)); // For subprogram
372  else
373  addType(std::move(TypeEntry), STy); // For func ptr
374 
375  // Visit return type and func arg types.
376  for (const auto Element : Elements) {
377  visitTypeEntry(Element.resolve());
378  }
379 }
380 
381 /// Handle structure/union types.
382 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct) {
383  const DINodeArray Elements = CTy->getElements();
384  uint32_t VLen = Elements.size();
385  if (VLen > BTF::MAX_VLEN)
386  return;
387 
388  // Check whether we have any bitfield members or not
389  bool HasBitField = false;
390  for (const auto *Element : Elements) {
391  auto E = cast<DIDerivedType>(Element);
392  if (E->isBitField()) {
393  HasBitField = true;
394  break;
395  }
396  }
397 
398  auto TypeEntry =
399  llvm::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
400  addType(std::move(TypeEntry), CTy);
401 
402  // Visit all struct members.
403  for (const auto *Element : Elements)
404  visitTypeEntry(cast<DIDerivedType>(Element));
405 }
406 
407 void BTFDebug::visitArrayType(const DICompositeType *CTy) {
408  auto TypeEntry = llvm::make_unique<BTFTypeArray>(CTy);
409  addType(std::move(TypeEntry), CTy);
410 
411  // The IR does not have a type for array index while BTF wants one.
412  // So create an array index type if there is none.
413  if (!ArrayIndexTypeId) {
414  auto TypeEntry = llvm::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
415  0, "__ARRAY_SIZE_TYPE__");
416  ArrayIndexTypeId = addType(std::move(TypeEntry));
417  }
418 
419  // Visit array element type.
420  visitTypeEntry(CTy->getBaseType().resolve());
421 }
422 
423 void BTFDebug::visitEnumType(const DICompositeType *CTy) {
424  DINodeArray Elements = CTy->getElements();
425  uint32_t VLen = Elements.size();
426  if (VLen > BTF::MAX_VLEN)
427  return;
428 
429  auto TypeEntry = llvm::make_unique<BTFTypeEnum>(CTy, VLen);
430  addType(std::move(TypeEntry), CTy);
431  // No need to visit base type as BTF does not encode it.
432 }
433 
434 /// Handle structure/union forward declarations.
435 void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion) {
436  auto TypeEntry = llvm::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
437  addType(std::move(TypeEntry), CTy);
438 }
439 
440 /// Handle structure, union, array and enumeration types.
441 void BTFDebug::visitCompositeType(const DICompositeType *CTy) {
442  auto Tag = CTy->getTag();
443  if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
444  // Handle forward declaration differently as it does not have members.
445  if (CTy->isForwardDecl())
446  visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type);
447  else
448  visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type);
449  } else if (Tag == dwarf::DW_TAG_array_type)
450  visitArrayType(CTy);
451  else if (Tag == dwarf::DW_TAG_enumeration_type)
452  visitEnumType(CTy);
453 }
454 
455 /// Handle pointer, typedef, const, volatile, restrict and member types.
456 void BTFDebug::visitDerivedType(const DIDerivedType *DTy) {
457  unsigned Tag = DTy->getTag();
458 
459  if (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_typedef ||
460  Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
461  Tag == dwarf::DW_TAG_restrict_type) {
462  auto TypeEntry = llvm::make_unique<BTFTypeDerived>(DTy, Tag);
463  addType(std::move(TypeEntry), DTy);
464  } else if (Tag != dwarf::DW_TAG_member) {
465  return;
466  }
467 
468  // Visit base type of pointer, typedef, const, volatile, restrict or
469  // struct/union member.
470  visitTypeEntry(DTy->getBaseType().resolve());
471 }
472 
473 void BTFDebug::visitTypeEntry(const DIType *Ty) {
474  if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end())
475  return;
476 
477  uint32_t TypeId;
478  if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
479  visitBasicType(BTy);
480  else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
481  visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(),
482  TypeId);
483  else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
484  visitCompositeType(CTy);
485  else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
486  visitDerivedType(DTy);
487  else
488  llvm_unreachable("Unknown DIType");
489 }
490 
491 /// Read file contents from the actual file or from the source
492 std::string BTFDebug::populateFileContent(const DISubprogram *SP) {
493  auto File = SP->getFile();
494  std::string FileName;
495 
496  if (!File->getFilename().startswith("/") && File->getDirectory().size())
497  FileName = File->getDirectory().str() + "/" + File->getFilename().str();
498  else
499  FileName = File->getFilename();
500 
501  // No need to populate the contends if it has been populated!
502  if (FileContent.find(FileName) != FileContent.end())
503  return FileName;
504 
505  std::vector<std::string> Content;
506  std::string Line;
507  Content.push_back(Line); // Line 0 for empty string
508 
509  auto Source = File->getSource();
510  if (Source) {
511  std::istringstream InputString(Source.getValue());
512  while (std::getline(InputString, Line))
513  Content.push_back(Line);
514  } else {
515  std::ifstream InputFile(FileName);
516  while (std::getline(InputFile, Line))
517  Content.push_back(Line);
518  }
519 
520  FileContent[FileName] = Content;
521  return FileName;
522 }
523 
524 void BTFDebug::constructLineInfo(const DISubprogram *SP, MCSymbol *Label,
525  uint32_t Line, uint32_t Column) {
526  std::string FileName = populateFileContent(SP);
527  BTFLineInfo LineInfo;
528 
529  LineInfo.Label = Label;
530  LineInfo.FileNameOff = addString(FileName);
531  // If file content is not available, let LineOff = 0.
532  if (Line < FileContent[FileName].size())
533  LineInfo.LineOff = addString(FileContent[FileName][Line]);
534  else
535  LineInfo.LineOff = 0;
536  LineInfo.LineNum = Line;
537  LineInfo.ColumnNum = Column;
538  LineInfoTable[SecNameOff].push_back(LineInfo);
539 }
540 
541 void BTFDebug::emitCommonHeader() {
543  OS.EmitIntValue(BTF::MAGIC, 2);
544  OS.EmitIntValue(BTF::VERSION, 1);
545  OS.EmitIntValue(0, 1);
546 }
547 
548 void BTFDebug::emitBTFSection() {
549  MCContext &Ctx = OS.getContext();
550  OS.SwitchSection(Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0));
551 
552  // Emit header.
553  emitCommonHeader();
555 
556  uint32_t TypeLen = 0, StrLen;
557  for (const auto &TypeEntry : TypeEntries)
558  TypeLen += TypeEntry->getSize();
559  StrLen = StringTable.getSize();
560 
561  OS.EmitIntValue(0, 4);
562  OS.EmitIntValue(TypeLen, 4);
563  OS.EmitIntValue(TypeLen, 4);
564  OS.EmitIntValue(StrLen, 4);
565 
566  // Emit type table.
567  for (const auto &TypeEntry : TypeEntries)
568  TypeEntry->emitType(OS);
569 
570  // Emit string table.
571  uint32_t StringOffset = 0;
572  for (const auto &S : StringTable.getTable()) {
573  OS.AddComment("string offset=" + std::to_string(StringOffset));
574  OS.EmitBytes(S);
575  OS.EmitBytes(StringRef("\0", 1));
576  StringOffset += S.size() + 1;
577  }
578 }
579 
580 void BTFDebug::emitBTFExtSection() {
581  MCContext &Ctx = OS.getContext();
582  OS.SwitchSection(Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0));
583 
584  // Emit header.
585  emitCommonHeader();
587 
588  // Account for FuncInfo/LineInfo record size as well.
589  uint32_t FuncLen = 4, LineLen = 4;
590  for (const auto &FuncSec : FuncInfoTable) {
591  FuncLen += BTF::SecFuncInfoSize;
592  FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
593  }
594  for (const auto &LineSec : LineInfoTable) {
595  LineLen += BTF::SecLineInfoSize;
596  LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
597  }
598 
599  OS.EmitIntValue(0, 4);
600  OS.EmitIntValue(FuncLen, 4);
601  OS.EmitIntValue(FuncLen, 4);
602  OS.EmitIntValue(LineLen, 4);
603 
604  // Emit func_info table.
605  OS.AddComment("FuncInfo");
607  for (const auto &FuncSec : FuncInfoTable) {
608  OS.AddComment("FuncInfo section string offset=" +
609  std::to_string(FuncSec.first));
610  OS.EmitIntValue(FuncSec.first, 4);
611  OS.EmitIntValue(FuncSec.second.size(), 4);
612  for (const auto &FuncInfo : FuncSec.second) {
613  Asm->EmitLabelReference(FuncInfo.Label, 4);
614  OS.EmitIntValue(FuncInfo.TypeId, 4);
615  }
616  }
617 
618  // Emit line_info table.
619  OS.AddComment("LineInfo");
621  for (const auto &LineSec : LineInfoTable) {
622  OS.AddComment("LineInfo section string offset=" +
623  std::to_string(LineSec.first));
624  OS.EmitIntValue(LineSec.first, 4);
625  OS.EmitIntValue(LineSec.second.size(), 4);
626  for (const auto &LineInfo : LineSec.second) {
627  Asm->EmitLabelReference(LineInfo.Label, 4);
628  OS.EmitIntValue(LineInfo.FileNameOff, 4);
629  OS.EmitIntValue(LineInfo.LineOff, 4);
630  OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
631  std::to_string(LineInfo.ColumnNum));
632  OS.EmitIntValue(LineInfo.LineNum << 10 | LineInfo.ColumnNum, 4);
633  }
634  }
635 }
636 
638  auto *SP = MF->getFunction().getSubprogram();
639  auto *Unit = SP->getUnit();
640 
641  if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
642  SkipInstruction = true;
643  return;
644  }
645  SkipInstruction = false;
646 
647  // Collect all types locally referenced in this function.
648  // Use RetainedNodes so we can collect all argument names
649  // even if the argument is not used.
650  std::unordered_map<uint32_t, StringRef> FuncArgNames;
651  for (const DINode *DN : SP->getRetainedNodes()) {
652  if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
653  visitTypeEntry(DV->getType().resolve());
654 
655  // Collect function arguments for subprogram func type.
656  uint32_t Arg = DV->getArg();
657  if (Arg)
658  FuncArgNames[Arg] = DV->getName();
659  }
660  }
661 
662  // Construct subprogram func proto type.
663  uint32_t ProtoTypeId;
664  visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
665 
666  // Construct subprogram func type
667  auto FuncTypeEntry =
668  llvm::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId);
669  uint32_t FuncTypeId = addType(std::move(FuncTypeEntry));
670 
671  // Construct funcinfo and the first lineinfo for the function.
672  MCSymbol *FuncLabel = Asm->getFunctionBegin();
673  BTFFuncInfo FuncInfo;
674  FuncInfo.Label = FuncLabel;
675  FuncInfo.TypeId = FuncTypeId;
676  if (FuncLabel->isInSection()) {
677  MCSection &Section = FuncLabel->getSection();
678  const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section);
679  assert(SectionELF && "Null section for Function Label");
680  SecNameOff = addString(SectionELF->getSectionName());
681  } else {
682  SecNameOff = addString(".text");
683  }
684  FuncInfoTable[SecNameOff].push_back(FuncInfo);
685 }
686 
688  SkipInstruction = false;
689  LineInfoGenerated = false;
690  SecNameOff = 0;
691 }
692 
695 
696  if (SkipInstruction || MI->isMetaInstruction() ||
698  return;
699 
700  if (MI->isInlineAsm()) {
701  // Count the number of register definitions to find the asm string.
702  unsigned NumDefs = 0;
703  for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
704  ++NumDefs)
705  ;
706 
707  // Skip this inline asm instruction if the asmstr is empty.
708  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
709  if (AsmStr[0] == 0)
710  return;
711  }
712 
713  // Skip this instruction if no DebugLoc or the DebugLoc
714  // is the same as the previous instruction.
715  const DebugLoc &DL = MI->getDebugLoc();
716  if (!DL || PrevInstLoc == DL) {
717  // This instruction will be skipped, no LineInfo has
718  // been generated, construct one based on function signature.
719  if (LineInfoGenerated == false) {
720  auto *S = MI->getMF()->getFunction().getSubprogram();
721  MCSymbol *FuncLabel = Asm->getFunctionBegin();
722  constructLineInfo(S, FuncLabel, S->getLine(), 0);
723  LineInfoGenerated = true;
724  }
725 
726  return;
727  }
728 
729  // Create a temporary label to remember the insn for lineinfo.
730  MCSymbol *LineSym = OS.getContext().createTempSymbol();
731  OS.EmitLabel(LineSym);
732 
733  // Construct the lineinfo.
734  auto SP = DL.get()->getScope()->getSubprogram();
735  constructLineInfo(SP, LineSym, DL.getLine(), DL.getCol());
736 
737  LineInfoGenerated = true;
738  PrevInstLoc = DL;
739 }
740 
742  // Collect all types referenced by globals.
743  const Module *M = MMI->getModule();
744  for (const DICompileUnit *CUNode : M->debug_compile_units()) {
745  for (const auto *GVE : CUNode->getGlobalVariables()) {
746  DIGlobalVariable *GV = GVE->getVariable();
747  visitTypeEntry(GV->getType().resolve());
748  }
749  }
750 
751  // Complete BTF type cross refereences.
752  for (const auto &TypeEntry : TypeEntries)
753  TypeEntry->completeType(*this);
754 
755  // Emit BTF sections.
756  emitBTFSection();
757  emitBTFExtSection();
758 }
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:38
uint32_t Type
Definition: BTF.h:162
uint64_t getOffsetInBits() const
void endFunctionImpl(const MachineFunction *MF) override
Post process after all instructions in this function are processed.
Definition: BTFDebug.cpp:687
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
Represent one func and its type id.
Definition: BTFDebug.h:177
BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId)
Definition: BTFDebug.cpp:292
uint32_t ColumnNum
the column number
Definition: BTFDebug.h:188
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:161
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:64
unsigned size() const
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
DIFile * getFile() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:382
DITypeRef getBaseType() const
uint32_t getArrayIndexTypeId()
Get the special array index type id.
Definition: BTFDebug.h:257
virtual void EmitBytes(StringRef Data)
Emit the bytes in Data into the output.
bool isInlineAsm() const
uint32_t getSize()
Definition: BTFDebug.h:169
BTFTypeEnum(const DICompositeType *ETy, uint32_t NumValues)
Definition: BTFDebug.cpp:132
iterator find(StringRef Key)
Definition: StringMap.h:332
BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits, uint32_t OffsetInBits, StringRef TypeName)
Definition: BTFDebug.cpp:95
BTFTypeDerived(const DIDerivedType *Ty, unsigned Tag)
Definition: BTFDebug.cpp:41
void completeType(BTFDebug &BDebug)
Represent a BTF array.
Definition: BTFDebug.cpp:168
unsigned getLine() const
Definition: DebugLoc.cpp:25
uint32_t Size
Definition: BTF.h:109
A debug info location.
Definition: DebugLoc.h:33
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:26
uint32_t Offset
BitOffset or BitFieldSize+BitOffset.
Definition: BTF.h:154
StringRef getName() const
Tagged DWARF-like metadata node.
DINodeArray getElements() const
uint32_t Type
Member type.
Definition: BTF.h:153
MCContext & getContext() const
Definition: MCStreamer.h:250
DebugLoc PrevInstLoc
Previous instruction&#39;s location information.
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:303
uint32_t ElemType
Element type.
Definition: BTF.h:136
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:284
unsigned getTag() const
virtual void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:32
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute)...
Definition: MCSymbol.h:251
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:122
BTF_KIND_ENUM is followed by multiple "struct BTFEnum".
Definition: BTF.h:129
uint32_t roundupToBytes(uint32_t NumBits)
Definition: BTFDebug.h:42
BTFTypeArray(const DICompositeType *ATy)
Definition: BTFDebug.cpp:161
uint64_t getSizeInBits() const
const char * getSymbolName() const
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
Definition: BTFDebug.cpp:637
Context object for machine code objects.
Definition: MCContext.h:62
Subprogram description.
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition: MCStreamer.h:311
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:138
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:208
uint32_t Type
Definition: BTF.h:110
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
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:123
BTF_KIND_FUNC_PROTO are followed by multiple "struct BTFParam".
Definition: BTF.h:160
void endModule() override
Complete all the types and emit the BTF sections.
Definition: BTFDebug.cpp:741
void resolve()
Resolve a unique, unresolved node.
Definition: Metadata.cpp:575
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:210
Streaming machine code generation interface.
Definition: MCStreamer.h:188
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:216
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:89
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1507
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.
Max # of struct/union/enum members or func args.
Definition: BTF.h:79
struct BTF::CommonType BTFType
Definition: BTFDebug.h:36
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
Definition: BTFDebug.cpp:693
AsmPrinter * Asm
Target of debug info emission.
Collect and emit BTF information.
Definition: BTFDebug.h:192
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:152
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:126
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
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:497
Represent one line info.
Definition: BTFDebug.h:183
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:151
uint32_t NameOff
Type name offset in the string table.
Definition: BTF.h:91
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:153
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
std::vector< std::string > & getTable()
Definition: BTFDebug.h:170
Base class for types.
uint32_t LineNum
the line number
Definition: BTFDebug.h:187
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:1166
uint32_t Id
Definition: BTFDebug.h:35
StringRef getName() const
int32_t Val
Enum member value.
Definition: BTF.h:131
uint32_t NameOff
Enum name offset in the string table.
Definition: BTF.h:130
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:218
MCSymbol * Label
MCSymbol identifying insn for the lineinfo.
Definition: BTFDebug.h:184
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:266
uint32_t IndexType
Index type.
Definition: BTF.h:137
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:262
const Function & getFunction() const
Return the LLVM function that this machine code represents.
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:266
This file contains support for writing BTF debug info.
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:202
void completeType(BTFDebug &BDebug)
Complete BTF type generation after all related DebugInfo types have been visited so their BTF type id...
Definition: BTFDebug.cpp:65
uint32_t Nelems
Number of elements for this array.
Definition: BTF.h:138
BTFDebug(AsmPrinter *AP)
Definition: BTFDebug.cpp:319
Type array for a subprogram.
Representation of each machine instruction.
Definition: MachineInstr.h:63
uint32_t addString(StringRef S)
Add a string to the string table and returns its offset in the table.
Definition: BTFDebug.cpp:305
unsigned getEncoding() const
BTFTypeFwd(StringRef Name, bool IsUnion)
Represent a struct/union forward declaration.
Definition: BTFDebug.cpp:83
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:93
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
iterator_range< debug_compile_units_iterator > debug_compile_units() const
Return an iterator for all DICompileUnits listed in this Module&#39;s llvm.dbg.cu named metadata node and...
Definition: Module.h:780
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:322
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:254
uint32_t Size
Definition: Profile.cpp:46
const MCSymbol * Label
Func MCSymbol.
Definition: BTFDebug.h:178
const Module * getModule() const
uint32_t FileNameOff
file name offset in the .BTF string table
Definition: BTFDebug.h:185
size_t addString(StringRef S)
Add string to the string table.
Definition: BTFDebug.h:263
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
DITypeRef getType() 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:299
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:388
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:80
virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:346
DITypeRefArray getTypeArray() const
MachineModuleInfo * MMI
Collected machine module information.
IRTranslator LLVM IR MI
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:100
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
void emitType(MCStreamer &OS)
Emit types for this BTF type entry.
Definition: BTFDebug.cpp:239
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
Definition: MachineInstr.h:294
iterator end()
Definition: StringMap.h:317
uint32_t TypeId
Type id referring to .BTF type section.
Definition: BTFDebug.h:179
StringRef getSectionName() const
Definition: MCSectionELF.h:70
uint32_t LineOff
line offset in the .BTF string table
Definition: BTFDebug.h:186
Basic type, like &#39;int&#39; or &#39;float&#39;.