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