BTFDebug.cpp 48 KB

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