blob: 86e625b547e4721554ef4862151583b06893a513 [file] [log] [blame]
Yonghong Song7b410ac2018-12-19 16:40:25 +00001//===- BTFDebug.cpp - BTF Generator ---------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Yonghong Song7b410ac2018-12-19 16:40:25 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for writing BTF debug info.
10//
11//===----------------------------------------------------------------------===//
12
13#include "BTFDebug.h"
Yonghong Songd3d88d02019-07-09 15:28:41 +000014#include "BPF.h"
15#include "BPFCORE.h"
16#include "MCTargetDesc/BPFMCTargetDesc.h"
Yonghong Song7b410ac2018-12-19 16:40:25 +000017#include "llvm/BinaryFormat/ELF.h"
18#include "llvm/CodeGen/AsmPrinter.h"
19#include "llvm/CodeGen/MachineModuleInfo.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCObjectFileInfo.h"
22#include "llvm/MC/MCSectionELF.h"
23#include "llvm/MC/MCStreamer.h"
Fangrui Song83db8872019-04-02 16:15:46 +000024#include "llvm/Support/LineIterator.h"
Yonghong Song7b410ac2018-12-19 16:40:25 +000025
26using namespace llvm;
27
28static const char *BTFKindStr[] = {
29#define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
30#include "BTF.def"
31};
32
33/// Emit a BTF common type.
34void BTFTypeBase::emitType(MCStreamer &OS) {
35 OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
36 ")");
37 OS.EmitIntValue(BTFType.NameOff, 4);
38 OS.AddComment("0x" + Twine::utohexstr(BTFType.Info));
39 OS.EmitIntValue(BTFType.Info, 4);
40 OS.EmitIntValue(BTFType.Size, 4);
41}
42
Yonghong Songd3d88d02019-07-09 15:28:41 +000043BTFTypeDerived::BTFTypeDerived(const DIDerivedType *DTy, unsigned Tag,
44 bool NeedsFixup)
45 : DTy(DTy), NeedsFixup(NeedsFixup) {
Yonghong Song7b410ac2018-12-19 16:40:25 +000046 switch (Tag) {
47 case dwarf::DW_TAG_pointer_type:
48 Kind = BTF::BTF_KIND_PTR;
49 break;
50 case dwarf::DW_TAG_const_type:
51 Kind = BTF::BTF_KIND_CONST;
52 break;
53 case dwarf::DW_TAG_volatile_type:
54 Kind = BTF::BTF_KIND_VOLATILE;
55 break;
56 case dwarf::DW_TAG_typedef:
57 Kind = BTF::BTF_KIND_TYPEDEF;
58 break;
59 case dwarf::DW_TAG_restrict_type:
60 Kind = BTF::BTF_KIND_RESTRICT;
61 break;
62 default:
63 llvm_unreachable("Unknown DIDerivedType Tag");
64 }
65 BTFType.Info = Kind << 24;
66}
67
68void BTFTypeDerived::completeType(BTFDebug &BDebug) {
Yonghong Songd3d88d02019-07-09 15:28:41 +000069 if (IsCompleted)
70 return;
71 IsCompleted = true;
72
Yonghong Song7b410ac2018-12-19 16:40:25 +000073 BTFType.NameOff = BDebug.addString(DTy->getName());
74
Yonghong Songd3d88d02019-07-09 15:28:41 +000075 if (NeedsFixup)
76 return;
77
Yonghong Song7b410ac2018-12-19 16:40:25 +000078 // The base type for PTR/CONST/VOLATILE could be void.
Fangrui Songda82ce92019-05-07 02:06:37 +000079 const DIType *ResolvedType = DTy->getBaseType();
Yonghong Song7b410ac2018-12-19 16:40:25 +000080 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
90void BTFTypeDerived::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
91
Yonghong Songd3d88d02019-07-09 15:28:41 +000092void BTFTypeDerived::setPointeeType(uint32_t PointeeType) {
93 BTFType.Type = PointeeType;
94}
95
Yonghong Song7b410ac2018-12-19 16:40:25 +000096/// Represent a struct/union forward declaration.
97BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) {
98 Kind = BTF::BTF_KIND_FWD;
99 BTFType.Info = IsUnion << 31 | Kind << 24;
100 BTFType.Type = 0;
101}
102
103void BTFTypeFwd::completeType(BTFDebug &BDebug) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000104 if (IsCompleted)
105 return;
106 IsCompleted = true;
107
Yonghong Song7b410ac2018-12-19 16:40:25 +0000108 BTFType.NameOff = BDebug.addString(Name);
109}
110
111void BTFTypeFwd::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
112
113BTFTypeInt::BTFTypeInt(uint32_t Encoding, uint32_t SizeInBits,
114 uint32_t OffsetInBits, StringRef TypeName)
115 : Name(TypeName) {
116 // Translate IR int encoding to BTF int encoding.
117 uint8_t BTFEncoding;
118 switch (Encoding) {
119 case dwarf::DW_ATE_boolean:
120 BTFEncoding = BTF::INT_BOOL;
121 break;
122 case dwarf::DW_ATE_signed:
123 case dwarf::DW_ATE_signed_char:
124 BTFEncoding = BTF::INT_SIGNED;
125 break;
126 case dwarf::DW_ATE_unsigned:
127 case dwarf::DW_ATE_unsigned_char:
128 BTFEncoding = 0;
129 break;
130 default:
131 llvm_unreachable("Unknown BTFTypeInt Encoding");
132 }
133
134 Kind = BTF::BTF_KIND_INT;
135 BTFType.Info = Kind << 24;
136 BTFType.Size = roundupToBytes(SizeInBits);
137 IntVal = (BTFEncoding << 24) | OffsetInBits << 16 | SizeInBits;
138}
139
140void BTFTypeInt::completeType(BTFDebug &BDebug) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000141 if (IsCompleted)
142 return;
143 IsCompleted = true;
144
Yonghong Song7b410ac2018-12-19 16:40:25 +0000145 BTFType.NameOff = BDebug.addString(Name);
146}
147
148void BTFTypeInt::emitType(MCStreamer &OS) {
149 BTFTypeBase::emitType(OS);
150 OS.AddComment("0x" + Twine::utohexstr(IntVal));
151 OS.EmitIntValue(IntVal, 4);
152}
153
154BTFTypeEnum::BTFTypeEnum(const DICompositeType *ETy, uint32_t VLen) : ETy(ETy) {
155 Kind = BTF::BTF_KIND_ENUM;
156 BTFType.Info = Kind << 24 | VLen;
157 BTFType.Size = roundupToBytes(ETy->getSizeInBits());
158}
159
160void BTFTypeEnum::completeType(BTFDebug &BDebug) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000161 if (IsCompleted)
162 return;
163 IsCompleted = true;
164
Yonghong Song7b410ac2018-12-19 16:40:25 +0000165 BTFType.NameOff = BDebug.addString(ETy->getName());
166
167 DINodeArray Elements = ETy->getElements();
168 for (const auto Element : Elements) {
169 const auto *Enum = cast<DIEnumerator>(Element);
170
171 struct BTF::BTFEnum BTFEnum;
172 BTFEnum.NameOff = BDebug.addString(Enum->getName());
173 // BTF enum value is 32bit, enforce it.
174 BTFEnum.Val = static_cast<uint32_t>(Enum->getValue());
175 EnumValues.push_back(BTFEnum);
176 }
177}
178
179void BTFTypeEnum::emitType(MCStreamer &OS) {
180 BTFTypeBase::emitType(OS);
181 for (const auto &Enum : EnumValues) {
182 OS.EmitIntValue(Enum.NameOff, 4);
183 OS.EmitIntValue(Enum.Val, 4);
184 }
185}
186
Yonghong Song37d24a62019-08-02 23:16:44 +0000187BTFTypeArray::BTFTypeArray(uint32_t ElemTypeId, uint32_t NumElems) {
Yonghong Song7b410ac2018-12-19 16:40:25 +0000188 Kind = BTF::BTF_KIND_ARRAY;
Yonghong Song360a4e2c2019-03-28 21:59:49 +0000189 BTFType.NameOff = 0;
Yonghong Song7b410ac2018-12-19 16:40:25 +0000190 BTFType.Info = Kind << 24;
Yonghong Song7b410ac2018-12-19 16:40:25 +0000191 BTFType.Size = 0;
192
Yonghong Song360a4e2c2019-03-28 21:59:49 +0000193 ArrayInfo.ElemType = ElemTypeId;
194 ArrayInfo.Nelems = NumElems;
195}
196
197/// Represent a BTF array.
198void BTFTypeArray::completeType(BTFDebug &BDebug) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000199 if (IsCompleted)
200 return;
201 IsCompleted = true;
Yonghong Song7b410ac2018-12-19 16:40:25 +0000202
203 // The IR does not really have a type for the index.
204 // A special type for array index should have been
205 // created during initial type traversal. Just
206 // retrieve that type id.
207 ArrayInfo.IndexType = BDebug.getArrayIndexTypeId();
Yonghong Song7b410ac2018-12-19 16:40:25 +0000208}
209
210void BTFTypeArray::emitType(MCStreamer &OS) {
211 BTFTypeBase::emitType(OS);
212 OS.EmitIntValue(ArrayInfo.ElemType, 4);
213 OS.EmitIntValue(ArrayInfo.IndexType, 4);
214 OS.EmitIntValue(ArrayInfo.Nelems, 4);
215}
216
217/// Represent either a struct or a union.
218BTFTypeStruct::BTFTypeStruct(const DICompositeType *STy, bool IsStruct,
219 bool HasBitField, uint32_t Vlen)
220 : STy(STy), HasBitField(HasBitField) {
221 Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
222 BTFType.Size = roundupToBytes(STy->getSizeInBits());
223 BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
224}
225
226void BTFTypeStruct::completeType(BTFDebug &BDebug) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000227 if (IsCompleted)
228 return;
229 IsCompleted = true;
230
Yonghong Song7b410ac2018-12-19 16:40:25 +0000231 BTFType.NameOff = BDebug.addString(STy->getName());
232
233 // Add struct/union members.
234 const DINodeArray Elements = STy->getElements();
235 for (const auto *Element : Elements) {
236 struct BTF::BTFMember BTFMember;
237 const auto *DDTy = cast<DIDerivedType>(Element);
238
239 BTFMember.NameOff = BDebug.addString(DDTy->getName());
240 if (HasBitField) {
241 uint8_t BitFieldSize = DDTy->isBitField() ? DDTy->getSizeInBits() : 0;
242 BTFMember.Offset = BitFieldSize << 24 | DDTy->getOffsetInBits();
243 } else {
244 BTFMember.Offset = DDTy->getOffsetInBits();
245 }
Yonghong Song329abf22019-07-25 21:47:27 +0000246 const auto *BaseTy = DDTy->getBaseType();
247 BTFMember.Type = BDebug.getTypeId(BaseTy);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000248 Members.push_back(BTFMember);
249 }
250}
251
252void BTFTypeStruct::emitType(MCStreamer &OS) {
253 BTFTypeBase::emitType(OS);
254 for (const auto &Member : Members) {
255 OS.EmitIntValue(Member.NameOff, 4);
256 OS.EmitIntValue(Member.Type, 4);
257 OS.AddComment("0x" + Twine::utohexstr(Member.Offset));
258 OS.EmitIntValue(Member.Offset, 4);
259 }
260}
261
Yonghong Songd3d88d02019-07-09 15:28:41 +0000262std::string BTFTypeStruct::getName() { return STy->getName(); }
263
Yonghong Song7b410ac2018-12-19 16:40:25 +0000264/// The Func kind represents both subprogram and pointee of function
265/// pointers. If the FuncName is empty, it represents a pointee of function
266/// pointer. Otherwise, it represents a subprogram. The func arg names
267/// are empty for pointee of function pointer case, and are valid names
268/// for subprogram.
269BTFTypeFuncProto::BTFTypeFuncProto(
270 const DISubroutineType *STy, uint32_t VLen,
271 const std::unordered_map<uint32_t, StringRef> &FuncArgNames)
272 : STy(STy), FuncArgNames(FuncArgNames) {
273 Kind = BTF::BTF_KIND_FUNC_PROTO;
274 BTFType.Info = (Kind << 24) | VLen;
275}
276
277void BTFTypeFuncProto::completeType(BTFDebug &BDebug) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000278 if (IsCompleted)
279 return;
280 IsCompleted = true;
281
Yonghong Song7b410ac2018-12-19 16:40:25 +0000282 DITypeRefArray Elements = STy->getTypeArray();
Fangrui Songda82ce92019-05-07 02:06:37 +0000283 auto RetType = Elements[0];
Yonghong Song7b410ac2018-12-19 16:40:25 +0000284 BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
285 BTFType.NameOff = 0;
286
287 // For null parameter which is typically the last one
288 // to represent the vararg, encode the NameOff/Type to be 0.
289 for (unsigned I = 1, N = Elements.size(); I < N; ++I) {
290 struct BTF::BTFParam Param;
Fangrui Songda82ce92019-05-07 02:06:37 +0000291 auto Element = Elements[I];
Yonghong Song7b410ac2018-12-19 16:40:25 +0000292 if (Element) {
293 Param.NameOff = BDebug.addString(FuncArgNames[I]);
294 Param.Type = BDebug.getTypeId(Element);
295 } else {
296 Param.NameOff = 0;
297 Param.Type = 0;
298 }
299 Parameters.push_back(Param);
300 }
301}
302
303void BTFTypeFuncProto::emitType(MCStreamer &OS) {
304 BTFTypeBase::emitType(OS);
305 for (const auto &Param : Parameters) {
306 OS.EmitIntValue(Param.NameOff, 4);
307 OS.EmitIntValue(Param.Type, 4);
308 }
309}
310
311BTFTypeFunc::BTFTypeFunc(StringRef FuncName, uint32_t ProtoTypeId)
312 : Name(FuncName) {
313 Kind = BTF::BTF_KIND_FUNC;
314 BTFType.Info = Kind << 24;
315 BTFType.Type = ProtoTypeId;
316}
317
318void BTFTypeFunc::completeType(BTFDebug &BDebug) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000319 if (IsCompleted)
320 return;
321 IsCompleted = true;
322
Yonghong Song7b410ac2018-12-19 16:40:25 +0000323 BTFType.NameOff = BDebug.addString(Name);
324}
325
326void BTFTypeFunc::emitType(MCStreamer &OS) { BTFTypeBase::emitType(OS); }
327
Yonghong Song6db6b562019-03-16 15:36:31 +0000328BTFKindVar::BTFKindVar(StringRef VarName, uint32_t TypeId, uint32_t VarInfo)
329 : Name(VarName) {
330 Kind = BTF::BTF_KIND_VAR;
331 BTFType.Info = Kind << 24;
332 BTFType.Type = TypeId;
333 Info = VarInfo;
334}
335
336void BTFKindVar::completeType(BTFDebug &BDebug) {
337 BTFType.NameOff = BDebug.addString(Name);
338}
339
340void BTFKindVar::emitType(MCStreamer &OS) {
341 BTFTypeBase::emitType(OS);
342 OS.EmitIntValue(Info, 4);
343}
344
345BTFKindDataSec::BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
346 : Asm(AsmPrt), Name(SecName) {
347 Kind = BTF::BTF_KIND_DATASEC;
348 BTFType.Info = Kind << 24;
349 BTFType.Size = 0;
350}
351
352void BTFKindDataSec::completeType(BTFDebug &BDebug) {
353 BTFType.NameOff = BDebug.addString(Name);
354 BTFType.Info |= Vars.size();
355}
356
357void BTFKindDataSec::emitType(MCStreamer &OS) {
358 BTFTypeBase::emitType(OS);
359
360 for (const auto &V : Vars) {
361 OS.EmitIntValue(std::get<0>(V), 4);
362 Asm->EmitLabelReference(std::get<1>(V), 4);
363 OS.EmitIntValue(std::get<2>(V), 4);
364 }
365}
366
Yonghong Song7b410ac2018-12-19 16:40:25 +0000367uint32_t BTFStringTable::addString(StringRef S) {
368 // Check whether the string already exists.
369 for (auto &OffsetM : OffsetToIdMap) {
370 if (Table[OffsetM.second] == S)
371 return OffsetM.first;
372 }
373 // Not find, add to the string table.
374 uint32_t Offset = Size;
375 OffsetToIdMap[Offset] = Table.size();
376 Table.push_back(S);
377 Size += S.size() + 1;
378 return Offset;
379}
380
381BTFDebug::BTFDebug(AsmPrinter *AP)
382 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
Yonghong Songd3d88d02019-07-09 15:28:41 +0000383 LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
384 MapDefNotCollected(true) {
Yonghong Song7b410ac2018-12-19 16:40:25 +0000385 addString("\0");
386}
387
Yonghong Song6db6b562019-03-16 15:36:31 +0000388uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry,
389 const DIType *Ty) {
Yonghong Song7b410ac2018-12-19 16:40:25 +0000390 TypeEntry->setId(TypeEntries.size() + 1);
Yonghong Song6db6b562019-03-16 15:36:31 +0000391 uint32_t Id = TypeEntry->getId();
392 DIToIdMap[Ty] = Id;
Yonghong Song7b410ac2018-12-19 16:40:25 +0000393 TypeEntries.push_back(std::move(TypeEntry));
Yonghong Song6db6b562019-03-16 15:36:31 +0000394 return Id;
Yonghong Song7b410ac2018-12-19 16:40:25 +0000395}
396
397uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
398 TypeEntry->setId(TypeEntries.size() + 1);
399 uint32_t Id = TypeEntry->getId();
400 TypeEntries.push_back(std::move(TypeEntry));
401 return Id;
402}
403
Yonghong Song6db6b562019-03-16 15:36:31 +0000404void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
Yonghong Song7b410ac2018-12-19 16:40:25 +0000405 // Only int types are supported in BTF.
406 uint32_t Encoding = BTy->getEncoding();
407 if (Encoding != dwarf::DW_ATE_boolean && Encoding != dwarf::DW_ATE_signed &&
408 Encoding != dwarf::DW_ATE_signed_char &&
409 Encoding != dwarf::DW_ATE_unsigned &&
410 Encoding != dwarf::DW_ATE_unsigned_char)
411 return;
412
413 // Create a BTF type instance for this DIBasicType and put it into
414 // DIToIdMap for cross-type reference check.
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000415 auto TypeEntry = std::make_unique<BTFTypeInt>(
Yonghong Song7b410ac2018-12-19 16:40:25 +0000416 Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
Yonghong Song6db6b562019-03-16 15:36:31 +0000417 TypeId = addType(std::move(TypeEntry), BTy);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000418}
419
420/// Handle subprogram or subroutine types.
421void BTFDebug::visitSubroutineType(
422 const DISubroutineType *STy, bool ForSubprog,
423 const std::unordered_map<uint32_t, StringRef> &FuncArgNames,
424 uint32_t &TypeId) {
425 DITypeRefArray Elements = STy->getTypeArray();
426 uint32_t VLen = Elements.size() - 1;
427 if (VLen > BTF::MAX_VLEN)
428 return;
429
430 // Subprogram has a valid non-zero-length name, and the pointee of
431 // a function pointer has an empty name. The subprogram type will
432 // not be added to DIToIdMap as it should not be referenced by
433 // any other types.
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000434 auto TypeEntry = std::make_unique<BTFTypeFuncProto>(STy, VLen, FuncArgNames);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000435 if (ForSubprog)
436 TypeId = addType(std::move(TypeEntry)); // For subprogram
437 else
Yonghong Song6db6b562019-03-16 15:36:31 +0000438 TypeId = addType(std::move(TypeEntry), STy); // For func ptr
Yonghong Song7b410ac2018-12-19 16:40:25 +0000439
440 // Visit return type and func arg types.
441 for (const auto Element : Elements) {
Fangrui Songda82ce92019-05-07 02:06:37 +0000442 visitTypeEntry(Element);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000443 }
444}
445
446/// Handle structure/union types.
Yonghong Song6db6b562019-03-16 15:36:31 +0000447void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
448 uint32_t &TypeId) {
Yonghong Song7b410ac2018-12-19 16:40:25 +0000449 const DINodeArray Elements = CTy->getElements();
450 uint32_t VLen = Elements.size();
451 if (VLen > BTF::MAX_VLEN)
452 return;
453
454 // Check whether we have any bitfield members or not
455 bool HasBitField = false;
456 for (const auto *Element : Elements) {
457 auto E = cast<DIDerivedType>(Element);
458 if (E->isBitField()) {
459 HasBitField = true;
460 break;
461 }
462 }
463
464 auto TypeEntry =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000465 std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000466 StructTypes.push_back(TypeEntry.get());
Yonghong Song6db6b562019-03-16 15:36:31 +0000467 TypeId = addType(std::move(TypeEntry), CTy);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000468
469 // Visit all struct members.
470 for (const auto *Element : Elements)
471 visitTypeEntry(cast<DIDerivedType>(Element));
472}
473
Yonghong Song6db6b562019-03-16 15:36:31 +0000474void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
Yonghong Song360a4e2c2019-03-28 21:59:49 +0000475 // Visit array element type.
Yonghong Song1487bf62019-09-24 22:38:43 +0000476 uint32_t ElemTypeId;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000477 const DIType *ElemType = CTy->getBaseType();
478 visitTypeEntry(ElemType, ElemTypeId, false, false);
Yonghong Song329abf22019-07-25 21:47:27 +0000479
Yonghong Song1487bf62019-09-24 22:38:43 +0000480 // Visit array dimensions.
481 DINodeArray Elements = CTy->getElements();
482 for (int I = Elements.size() - 1; I >= 0; --I) {
483 if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
484 if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
485 const DISubrange *SR = cast<DISubrange>(Element);
486 auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
487 int64_t Count = CI->getSExtValue();
Yonghong Song360a4e2c2019-03-28 21:59:49 +0000488
Yonghong Song1487bf62019-09-24 22:38:43 +0000489 // For struct s { int b; char c[]; }, the c[] will be represented
490 // as an array with Count = -1.
491 auto TypeEntry =
492 std::make_unique<BTFTypeArray>(ElemTypeId,
493 Count >= 0 ? Count : 0);
494 if (I == 0)
495 ElemTypeId = addType(std::move(TypeEntry), CTy);
496 else
497 ElemTypeId = addType(std::move(TypeEntry));
498 }
Yonghong Song360a4e2c2019-03-28 21:59:49 +0000499 }
500
501 // The array TypeId is the type id of the outermost dimension.
502 TypeId = ElemTypeId;
Yonghong Song7b410ac2018-12-19 16:40:25 +0000503
504 // The IR does not have a type for array index while BTF wants one.
505 // So create an array index type if there is none.
506 if (!ArrayIndexTypeId) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000507 auto TypeEntry = std::make_unique<BTFTypeInt>(dwarf::DW_ATE_unsigned, 32,
Yonghong Song7b410ac2018-12-19 16:40:25 +0000508 0, "__ARRAY_SIZE_TYPE__");
509 ArrayIndexTypeId = addType(std::move(TypeEntry));
510 }
Yonghong Song7b410ac2018-12-19 16:40:25 +0000511}
512
Yonghong Song6db6b562019-03-16 15:36:31 +0000513void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
Yonghong Song7b410ac2018-12-19 16:40:25 +0000514 DINodeArray Elements = CTy->getElements();
515 uint32_t VLen = Elements.size();
516 if (VLen > BTF::MAX_VLEN)
517 return;
518
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000519 auto TypeEntry = std::make_unique<BTFTypeEnum>(CTy, VLen);
Yonghong Song6db6b562019-03-16 15:36:31 +0000520 TypeId = addType(std::move(TypeEntry), CTy);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000521 // No need to visit base type as BTF does not encode it.
522}
523
524/// Handle structure/union forward declarations.
Yonghong Song6db6b562019-03-16 15:36:31 +0000525void BTFDebug::visitFwdDeclType(const DICompositeType *CTy, bool IsUnion,
526 uint32_t &TypeId) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000527 auto TypeEntry = std::make_unique<BTFTypeFwd>(CTy->getName(), IsUnion);
Yonghong Song6db6b562019-03-16 15:36:31 +0000528 TypeId = addType(std::move(TypeEntry), CTy);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000529}
530
531/// Handle structure, union, array and enumeration types.
Yonghong Song6db6b562019-03-16 15:36:31 +0000532void BTFDebug::visitCompositeType(const DICompositeType *CTy,
533 uint32_t &TypeId) {
Yonghong Song7b410ac2018-12-19 16:40:25 +0000534 auto Tag = CTy->getTag();
535 if (Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
536 // Handle forward declaration differently as it does not have members.
537 if (CTy->isForwardDecl())
Yonghong Song6db6b562019-03-16 15:36:31 +0000538 visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000539 else
Yonghong Song6db6b562019-03-16 15:36:31 +0000540 visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000541 } else if (Tag == dwarf::DW_TAG_array_type)
Yonghong Song6db6b562019-03-16 15:36:31 +0000542 visitArrayType(CTy, TypeId);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000543 else if (Tag == dwarf::DW_TAG_enumeration_type)
Yonghong Song6db6b562019-03-16 15:36:31 +0000544 visitEnumType(CTy, TypeId);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000545}
546
547/// Handle pointer, typedef, const, volatile, restrict and member types.
Yonghong Songd3d88d02019-07-09 15:28:41 +0000548void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
549 bool CheckPointer, bool SeenPointer) {
Yonghong Song7b410ac2018-12-19 16:40:25 +0000550 unsigned Tag = DTy->getTag();
551
Yonghong Songd3d88d02019-07-09 15:28:41 +0000552 /// Try to avoid chasing pointees, esp. structure pointees which may
553 /// unnecessary bring in a lot of types.
554 if (CheckPointer && !SeenPointer) {
555 SeenPointer = Tag == dwarf::DW_TAG_pointer_type;
556 }
557
558 if (CheckPointer && SeenPointer) {
559 const DIType *Base = DTy->getBaseType();
560 if (Base) {
561 if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
562 auto CTag = CTy->getTag();
563 if ((CTag == dwarf::DW_TAG_structure_type ||
564 CTag == dwarf::DW_TAG_union_type) &&
565 !CTy->isForwardDecl()) {
566 /// Find a candidate, generate a fixup. Later on the struct/union
567 /// pointee type will be replaced with either a real type or
568 /// a forward declaration.
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000569 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, true);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000570 auto &Fixup = FixupDerivedTypes[CTy->getName()];
571 Fixup.first = CTag == dwarf::DW_TAG_union_type;
572 Fixup.second.push_back(TypeEntry.get());
573 TypeId = addType(std::move(TypeEntry), DTy);
574 return;
575 }
576 }
577 }
578 }
579
Yonghong Song7b410ac2018-12-19 16:40:25 +0000580 if (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_typedef ||
581 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
582 Tag == dwarf::DW_TAG_restrict_type) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000583 auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
Yonghong Song6db6b562019-03-16 15:36:31 +0000584 TypeId = addType(std::move(TypeEntry), DTy);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000585 } else if (Tag != dwarf::DW_TAG_member) {
586 return;
587 }
588
589 // Visit base type of pointer, typedef, const, volatile, restrict or
590 // struct/union member.
Yonghong Songded9a442019-03-22 01:30:50 +0000591 uint32_t TempTypeId = 0;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000592 if (Tag == dwarf::DW_TAG_member)
593 visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
594 else
595 visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000596}
597
Yonghong Songd3d88d02019-07-09 15:28:41 +0000598void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
599 bool CheckPointer, bool SeenPointer) {
Yonghong Song6db6b562019-03-16 15:36:31 +0000600 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
601 TypeId = DIToIdMap[Ty];
Yonghong Song7b410ac2018-12-19 16:40:25 +0000602 return;
Yonghong Song6db6b562019-03-16 15:36:31 +0000603 }
Yonghong Song7b410ac2018-12-19 16:40:25 +0000604
Yonghong Song7b410ac2018-12-19 16:40:25 +0000605 if (const auto *BTy = dyn_cast<DIBasicType>(Ty))
Yonghong Song6db6b562019-03-16 15:36:31 +0000606 visitBasicType(BTy, TypeId);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000607 else if (const auto *STy = dyn_cast<DISubroutineType>(Ty))
608 visitSubroutineType(STy, false, std::unordered_map<uint32_t, StringRef>(),
609 TypeId);
610 else if (const auto *CTy = dyn_cast<DICompositeType>(Ty))
Yonghong Song6db6b562019-03-16 15:36:31 +0000611 visitCompositeType(CTy, TypeId);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000612 else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
Yonghong Songd3d88d02019-07-09 15:28:41 +0000613 visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000614 else
615 llvm_unreachable("Unknown DIType");
616}
617
Yonghong Song6db6b562019-03-16 15:36:31 +0000618void BTFDebug::visitTypeEntry(const DIType *Ty) {
619 uint32_t TypeId;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000620 visitTypeEntry(Ty, TypeId, false, false);
621}
622
623void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
624 if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
625 TypeId = DIToIdMap[Ty];
626 return;
627 }
628
629 // MapDef type is a struct type
630 const auto *CTy = dyn_cast<DICompositeType>(Ty);
631 if (!CTy)
632 return;
633
634 auto Tag = CTy->getTag();
635 if (Tag != dwarf::DW_TAG_structure_type || CTy->isForwardDecl())
636 return;
637
638 // Record this type
639 const DINodeArray Elements = CTy->getElements();
640 bool HasBitField = false;
641 for (const auto *Element : Elements) {
642 auto E = cast<DIDerivedType>(Element);
643 if (E->isBitField()) {
644 HasBitField = true;
645 break;
646 }
647 }
648
649 auto TypeEntry =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000650 std::make_unique<BTFTypeStruct>(CTy, true, HasBitField, Elements.size());
Yonghong Songd3d88d02019-07-09 15:28:41 +0000651 StructTypes.push_back(TypeEntry.get());
652 TypeId = addType(std::move(TypeEntry), CTy);
653
654 // Visit all struct members
655 for (const auto *Element : Elements) {
656 const auto *MemberType = cast<DIDerivedType>(Element);
657 visitTypeEntry(MemberType->getBaseType());
658 }
Yonghong Song6db6b562019-03-16 15:36:31 +0000659}
660
Yonghong Song7b410ac2018-12-19 16:40:25 +0000661/// Read file contents from the actual file or from the source
662std::string BTFDebug::populateFileContent(const DISubprogram *SP) {
663 auto File = SP->getFile();
664 std::string FileName;
665
Yonghong Songfa365402019-02-02 05:54:59 +0000666 if (!File->getFilename().startswith("/") && File->getDirectory().size())
Yonghong Song7b410ac2018-12-19 16:40:25 +0000667 FileName = File->getDirectory().str() + "/" + File->getFilename().str();
668 else
669 FileName = File->getFilename();
670
671 // No need to populate the contends if it has been populated!
672 if (FileContent.find(FileName) != FileContent.end())
673 return FileName;
674
675 std::vector<std::string> Content;
676 std::string Line;
677 Content.push_back(Line); // Line 0 for empty string
678
Fangrui Song83db8872019-04-02 16:15:46 +0000679 std::unique_ptr<MemoryBuffer> Buf;
Yonghong Song7b410ac2018-12-19 16:40:25 +0000680 auto Source = File->getSource();
Fangrui Song83db8872019-04-02 16:15:46 +0000681 if (Source)
682 Buf = MemoryBuffer::getMemBufferCopy(*Source);
683 else if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
684 MemoryBuffer::getFile(FileName))
685 Buf = std::move(*BufOrErr);
686 if (Buf)
687 for (line_iterator I(*Buf, false), E; I != E; ++I)
688 Content.push_back(*I);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000689
690 FileContent[FileName] = Content;
691 return FileName;
692}
693
694void BTFDebug::constructLineInfo(const DISubprogram *SP, MCSymbol *Label,
695 uint32_t Line, uint32_t Column) {
696 std::string FileName = populateFileContent(SP);
697 BTFLineInfo LineInfo;
698
699 LineInfo.Label = Label;
700 LineInfo.FileNameOff = addString(FileName);
701 // If file content is not available, let LineOff = 0.
702 if (Line < FileContent[FileName].size())
703 LineInfo.LineOff = addString(FileContent[FileName][Line]);
704 else
705 LineInfo.LineOff = 0;
706 LineInfo.LineNum = Line;
707 LineInfo.ColumnNum = Column;
708 LineInfoTable[SecNameOff].push_back(LineInfo);
709}
710
711void BTFDebug::emitCommonHeader() {
712 OS.AddComment("0x" + Twine::utohexstr(BTF::MAGIC));
713 OS.EmitIntValue(BTF::MAGIC, 2);
714 OS.EmitIntValue(BTF::VERSION, 1);
715 OS.EmitIntValue(0, 1);
716}
717
718void BTFDebug::emitBTFSection() {
Yonghong Songd82247c2019-03-05 01:01:21 +0000719 // Do not emit section if no types and only "" string.
720 if (!TypeEntries.size() && StringTable.getSize() == 1)
721 return;
722
Yonghong Song7b410ac2018-12-19 16:40:25 +0000723 MCContext &Ctx = OS.getContext();
724 OS.SwitchSection(Ctx.getELFSection(".BTF", ELF::SHT_PROGBITS, 0));
725
726 // Emit header.
727 emitCommonHeader();
728 OS.EmitIntValue(BTF::HeaderSize, 4);
729
730 uint32_t TypeLen = 0, StrLen;
731 for (const auto &TypeEntry : TypeEntries)
732 TypeLen += TypeEntry->getSize();
733 StrLen = StringTable.getSize();
734
735 OS.EmitIntValue(0, 4);
736 OS.EmitIntValue(TypeLen, 4);
737 OS.EmitIntValue(TypeLen, 4);
738 OS.EmitIntValue(StrLen, 4);
739
740 // Emit type table.
741 for (const auto &TypeEntry : TypeEntries)
742 TypeEntry->emitType(OS);
743
744 // Emit string table.
745 uint32_t StringOffset = 0;
746 for (const auto &S : StringTable.getTable()) {
747 OS.AddComment("string offset=" + std::to_string(StringOffset));
748 OS.EmitBytes(S);
749 OS.EmitBytes(StringRef("\0", 1));
750 StringOffset += S.size() + 1;
751 }
752}
753
754void BTFDebug::emitBTFExtSection() {
Yonghong Songd46a6a92019-10-10 15:33:09 +0000755 // Do not emit section if empty FuncInfoTable and LineInfoTable
756 // and FieldRelocTable.
Yonghong Songd3d88d02019-07-09 15:28:41 +0000757 if (!FuncInfoTable.size() && !LineInfoTable.size() &&
Yonghong Songd46a6a92019-10-10 15:33:09 +0000758 !FieldRelocTable.size())
Yonghong Songd82247c2019-03-05 01:01:21 +0000759 return;
760
Yonghong Song7b410ac2018-12-19 16:40:25 +0000761 MCContext &Ctx = OS.getContext();
762 OS.SwitchSection(Ctx.getELFSection(".BTF.ext", ELF::SHT_PROGBITS, 0));
763
764 // Emit header.
765 emitCommonHeader();
766 OS.EmitIntValue(BTF::ExtHeaderSize, 4);
767
768 // Account for FuncInfo/LineInfo record size as well.
769 uint32_t FuncLen = 4, LineLen = 4;
Yonghong Songd46a6a92019-10-10 15:33:09 +0000770 // Do not account for optional FieldReloc.
771 uint32_t FieldRelocLen = 0;
Yonghong Song7b410ac2018-12-19 16:40:25 +0000772 for (const auto &FuncSec : FuncInfoTable) {
773 FuncLen += BTF::SecFuncInfoSize;
774 FuncLen += FuncSec.second.size() * BTF::BPFFuncInfoSize;
775 }
776 for (const auto &LineSec : LineInfoTable) {
777 LineLen += BTF::SecLineInfoSize;
778 LineLen += LineSec.second.size() * BTF::BPFLineInfoSize;
779 }
Yonghong Song05e46972019-10-08 18:23:17 +0000780 for (const auto &FieldRelocSec : FieldRelocTable) {
781 FieldRelocLen += BTF::SecFieldRelocSize;
782 FieldRelocLen += FieldRelocSec.second.size() * BTF::BPFFieldRelocSize;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000783 }
Yonghong Songd3d88d02019-07-09 15:28:41 +0000784
Yonghong Song05e46972019-10-08 18:23:17 +0000785 if (FieldRelocLen)
786 FieldRelocLen += 4;
Yonghong Song7b410ac2018-12-19 16:40:25 +0000787
788 OS.EmitIntValue(0, 4);
789 OS.EmitIntValue(FuncLen, 4);
790 OS.EmitIntValue(FuncLen, 4);
791 OS.EmitIntValue(LineLen, 4);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000792 OS.EmitIntValue(FuncLen + LineLen, 4);
Yonghong Song05e46972019-10-08 18:23:17 +0000793 OS.EmitIntValue(FieldRelocLen, 4);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000794
795 // Emit func_info table.
796 OS.AddComment("FuncInfo");
797 OS.EmitIntValue(BTF::BPFFuncInfoSize, 4);
798 for (const auto &FuncSec : FuncInfoTable) {
799 OS.AddComment("FuncInfo section string offset=" +
800 std::to_string(FuncSec.first));
801 OS.EmitIntValue(FuncSec.first, 4);
802 OS.EmitIntValue(FuncSec.second.size(), 4);
803 for (const auto &FuncInfo : FuncSec.second) {
804 Asm->EmitLabelReference(FuncInfo.Label, 4);
805 OS.EmitIntValue(FuncInfo.TypeId, 4);
806 }
807 }
808
809 // Emit line_info table.
810 OS.AddComment("LineInfo");
811 OS.EmitIntValue(BTF::BPFLineInfoSize, 4);
812 for (const auto &LineSec : LineInfoTable) {
813 OS.AddComment("LineInfo section string offset=" +
814 std::to_string(LineSec.first));
815 OS.EmitIntValue(LineSec.first, 4);
816 OS.EmitIntValue(LineSec.second.size(), 4);
817 for (const auto &LineInfo : LineSec.second) {
818 Asm->EmitLabelReference(LineInfo.Label, 4);
819 OS.EmitIntValue(LineInfo.FileNameOff, 4);
820 OS.EmitIntValue(LineInfo.LineOff, 4);
821 OS.AddComment("Line " + std::to_string(LineInfo.LineNum) + " Col " +
822 std::to_string(LineInfo.ColumnNum));
823 OS.EmitIntValue(LineInfo.LineNum << 10 | LineInfo.ColumnNum, 4);
824 }
825 }
Yonghong Songd3d88d02019-07-09 15:28:41 +0000826
Yonghong Song05e46972019-10-08 18:23:17 +0000827 // Emit field reloc table.
828 if (FieldRelocLen) {
829 OS.AddComment("FieldReloc");
830 OS.EmitIntValue(BTF::BPFFieldRelocSize, 4);
831 for (const auto &FieldRelocSec : FieldRelocTable) {
832 OS.AddComment("Field reloc section string offset=" +
833 std::to_string(FieldRelocSec.first));
834 OS.EmitIntValue(FieldRelocSec.first, 4);
835 OS.EmitIntValue(FieldRelocSec.second.size(), 4);
836 for (const auto &FieldRelocInfo : FieldRelocSec.second) {
837 Asm->EmitLabelReference(FieldRelocInfo.Label, 4);
838 OS.EmitIntValue(FieldRelocInfo.TypeID, 4);
839 OS.EmitIntValue(FieldRelocInfo.OffsetNameOff, 4);
840 OS.EmitIntValue(FieldRelocInfo.RelocKind, 4);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000841 }
842 }
843 }
Yonghong Song7b410ac2018-12-19 16:40:25 +0000844}
845
846void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
847 auto *SP = MF->getFunction().getSubprogram();
848 auto *Unit = SP->getUnit();
849
850 if (Unit->getEmissionKind() == DICompileUnit::NoDebug) {
851 SkipInstruction = true;
852 return;
853 }
854 SkipInstruction = false;
855
Yonghong Songd3d88d02019-07-09 15:28:41 +0000856 // Collect MapDef types. Map definition needs to collect
857 // pointee types. Do it first. Otherwise, for the following
858 // case:
859 // struct m { ...};
860 // struct t {
861 // struct m *key;
862 // };
863 // foo(struct t *arg);
864 //
865 // struct mapdef {
866 // ...
867 // struct m *key;
868 // ...
869 // } __attribute__((section(".maps"))) hash_map;
870 //
871 // If subroutine foo is traversed first, a type chain
872 // "ptr->struct m(fwd)" will be created and later on
873 // when traversing mapdef, since "ptr->struct m" exists,
874 // the traversal of "struct m" will be omitted.
875 if (MapDefNotCollected) {
876 processGlobals(true);
877 MapDefNotCollected = false;
878 }
879
Yonghong Song7b410ac2018-12-19 16:40:25 +0000880 // Collect all types locally referenced in this function.
881 // Use RetainedNodes so we can collect all argument names
882 // even if the argument is not used.
883 std::unordered_map<uint32_t, StringRef> FuncArgNames;
884 for (const DINode *DN : SP->getRetainedNodes()) {
885 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
Yonghong Song7b410ac2018-12-19 16:40:25 +0000886 // Collect function arguments for subprogram func type.
887 uint32_t Arg = DV->getArg();
Yonghong Songcacac052019-03-15 05:51:25 +0000888 if (Arg) {
Fangrui Songda82ce92019-05-07 02:06:37 +0000889 visitTypeEntry(DV->getType());
Yonghong Song7b410ac2018-12-19 16:40:25 +0000890 FuncArgNames[Arg] = DV->getName();
Yonghong Songcacac052019-03-15 05:51:25 +0000891 }
Yonghong Song7b410ac2018-12-19 16:40:25 +0000892 }
893 }
894
895 // Construct subprogram func proto type.
896 uint32_t ProtoTypeId;
897 visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
898
899 // Construct subprogram func type
900 auto FuncTypeEntry =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000901 std::make_unique<BTFTypeFunc>(SP->getName(), ProtoTypeId);
Yonghong Song7b410ac2018-12-19 16:40:25 +0000902 uint32_t FuncTypeId = addType(std::move(FuncTypeEntry));
903
Yonghong Songd3d88d02019-07-09 15:28:41 +0000904 for (const auto &TypeEntry : TypeEntries)
905 TypeEntry->completeType(*this);
906
Yonghong Song7b410ac2018-12-19 16:40:25 +0000907 // Construct funcinfo and the first lineinfo for the function.
908 MCSymbol *FuncLabel = Asm->getFunctionBegin();
909 BTFFuncInfo FuncInfo;
910 FuncInfo.Label = FuncLabel;
911 FuncInfo.TypeId = FuncTypeId;
912 if (FuncLabel->isInSection()) {
913 MCSection &Section = FuncLabel->getSection();
914 const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section);
915 assert(SectionELF && "Null section for Function Label");
916 SecNameOff = addString(SectionELF->getSectionName());
917 } else {
918 SecNameOff = addString(".text");
919 }
920 FuncInfoTable[SecNameOff].push_back(FuncInfo);
921}
922
923void BTFDebug::endFunctionImpl(const MachineFunction *MF) {
924 SkipInstruction = false;
925 LineInfoGenerated = false;
926 SecNameOff = 0;
927}
928
Yonghong Songd3d88d02019-07-09 15:28:41 +0000929/// On-demand populate struct types as requested from abstract member
930/// accessing.
931unsigned BTFDebug::populateStructType(const DIType *Ty) {
932 unsigned Id;
933 visitTypeEntry(Ty, Id, false, false);
934 for (const auto &TypeEntry : TypeEntries)
935 TypeEntry->completeType(*this);
936 return Id;
937}
938
Yonghong Song05e46972019-10-08 18:23:17 +0000939/// Generate a struct member field relocation.
Yonghong Songffd57402019-12-19 15:21:53 -0800940void BTFDebug::generateFieldReloc(const MCSymbol *ORSym, DIType *RootTy,
941 StringRef AccessPattern) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000942 unsigned RootId = populateStructType(RootTy);
Yonghong Song37d24a62019-08-02 23:16:44 +0000943 size_t FirstDollar = AccessPattern.find_first_of('$');
944 size_t FirstColon = AccessPattern.find_first_of(':');
Yonghong Song05e46972019-10-08 18:23:17 +0000945 size_t SecondColon = AccessPattern.find_first_of(':', FirstColon + 1);
Yonghong Song37d24a62019-08-02 23:16:44 +0000946 StringRef IndexPattern = AccessPattern.substr(FirstDollar + 1);
Yonghong Song05e46972019-10-08 18:23:17 +0000947 StringRef RelocKindStr = AccessPattern.substr(FirstColon + 1,
948 SecondColon - FirstColon);
949 StringRef PatchImmStr = AccessPattern.substr(SecondColon + 1,
950 FirstDollar - SecondColon);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000951
Yonghong Song05e46972019-10-08 18:23:17 +0000952 BTFFieldReloc FieldReloc;
953 FieldReloc.Label = ORSym;
954 FieldReloc.OffsetNameOff = addString(IndexPattern);
955 FieldReloc.TypeID = RootId;
956 FieldReloc.RelocKind = std::stoull(RelocKindStr);
957 PatchImms[AccessPattern.str()] = std::stoul(PatchImmStr);
958 FieldRelocTable[SecNameOff].push_back(FieldReloc);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000959}
960
Yonghong Songffd57402019-12-19 15:21:53 -0800961void BTFDebug::processReloc(const MachineOperand &MO) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000962 // check whether this is a candidate or not
Yonghong Songd3d88d02019-07-09 15:28:41 +0000963 if (MO.isGlobal()) {
964 const GlobalValue *GVal = MO.getGlobal();
965 auto *GVar = dyn_cast<GlobalVariable>(GVal);
966 if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
967 MCSymbol *ORSym = OS.getContext().createTempSymbol();
968 OS.EmitLabel(ORSym);
969
970 MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
971 DIType *Ty = dyn_cast<DIType>(MDN);
Yonghong Songffd57402019-12-19 15:21:53 -0800972 generateFieldReloc(ORSym, Ty, GVar->getName());
Yonghong Songd3d88d02019-07-09 15:28:41 +0000973 }
974 }
975}
976
Yonghong Song7b410ac2018-12-19 16:40:25 +0000977void BTFDebug::beginInstruction(const MachineInstr *MI) {
978 DebugHandlerBase::beginInstruction(MI);
979
980 if (SkipInstruction || MI->isMetaInstruction() ||
981 MI->getFlag(MachineInstr::FrameSetup))
982 return;
983
984 if (MI->isInlineAsm()) {
985 // Count the number of register definitions to find the asm string.
986 unsigned NumDefs = 0;
987 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
988 ++NumDefs)
989 ;
990
991 // Skip this inline asm instruction if the asmstr is empty.
992 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
993 if (AsmStr[0] == 0)
994 return;
995 }
996
Yonghong Songffd57402019-12-19 15:21:53 -0800997 if (MI->getOpcode() == BPF::LD_imm64) {
998 // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
999 // add this insn into the .BTF.ext FieldReloc subsection.
1000 // Relocation looks like:
1001 // . SecName:
1002 // . InstOffset
1003 // . TypeID
1004 // . OffSetNameOff
1005 // . RelocType
1006 // Later, the insn is replaced with "r2 = <offset>"
1007 // where "<offset>" equals to the offset based on current
1008 // type definitions.
1009 processReloc(MI->getOperand(1));
1010 } else if (MI->getOpcode() == BPF::CORE_MEM ||
1011 MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1012 MI->getOpcode() == BPF::CORE_SHIFT) {
1013 // relocation insn is a load, store or shift insn.
1014 processReloc(MI->getOperand(3));
1015 }
Yonghong Songd3d88d02019-07-09 15:28:41 +00001016
Yonghong Song7b410ac2018-12-19 16:40:25 +00001017 // Skip this instruction if no DebugLoc or the DebugLoc
1018 // is the same as the previous instruction.
1019 const DebugLoc &DL = MI->getDebugLoc();
1020 if (!DL || PrevInstLoc == DL) {
1021 // This instruction will be skipped, no LineInfo has
1022 // been generated, construct one based on function signature.
1023 if (LineInfoGenerated == false) {
1024 auto *S = MI->getMF()->getFunction().getSubprogram();
1025 MCSymbol *FuncLabel = Asm->getFunctionBegin();
1026 constructLineInfo(S, FuncLabel, S->getLine(), 0);
1027 LineInfoGenerated = true;
1028 }
1029
1030 return;
1031 }
1032
1033 // Create a temporary label to remember the insn for lineinfo.
1034 MCSymbol *LineSym = OS.getContext().createTempSymbol();
1035 OS.EmitLabel(LineSym);
1036
1037 // Construct the lineinfo.
1038 auto SP = DL.get()->getScope()->getSubprogram();
1039 constructLineInfo(SP, LineSym, DL.getLine(), DL.getCol());
1040
1041 LineInfoGenerated = true;
1042 PrevInstLoc = DL;
1043}
1044
Yonghong Songd3d88d02019-07-09 15:28:41 +00001045void BTFDebug::processGlobals(bool ProcessingMapDef) {
Yonghong Song7b410ac2018-12-19 16:40:25 +00001046 // Collect all types referenced by globals.
1047 const Module *M = MMI->getModule();
Yonghong Songcacac052019-03-15 05:51:25 +00001048 for (const GlobalVariable &Global : M->globals()) {
Yonghong Songd3d88d02019-07-09 15:28:41 +00001049 // Decide the section name.
1050 StringRef SecName;
1051 if (Global.hasSection()) {
1052 SecName = Global.getSection();
Yonghong Song44481252019-11-22 08:45:37 -08001053 } else if (Global.hasInitializer()) {
Yonghong Songd3d88d02019-07-09 15:28:41 +00001054 // data, bss, or readonly sections
1055 if (Global.isConstant())
1056 SecName = ".rodata";
1057 else
1058 SecName = Global.getInitializer()->isZeroValue() ? ".bss" : ".data";
Yonghong Song7d0e8932019-12-10 11:05:22 -08001059 } else {
1060 // extern variables without explicit section,
1061 // put them into ".extern" section.
1062 SecName = ".extern";
Yonghong Songd3d88d02019-07-09 15:28:41 +00001063 }
1064
1065 if (ProcessingMapDef != SecName.startswith(".maps"))
1066 continue;
1067
Yonghong Songcacac052019-03-15 05:51:25 +00001068 SmallVector<DIGlobalVariableExpression *, 1> GVs;
1069 Global.getDebugInfo(GVs);
Yonghong Song166cdc02019-11-12 11:31:52 -08001070
1071 // No type information, mostly internal, skip it.
1072 if (GVs.size() == 0)
1073 continue;
1074
Yonghong Song6db6b562019-03-16 15:36:31 +00001075 uint32_t GVTypeId = 0;
Yonghong Songcacac052019-03-15 05:51:25 +00001076 for (auto *GVE : GVs) {
Yonghong Songd3d88d02019-07-09 15:28:41 +00001077 if (SecName.startswith(".maps"))
1078 visitMapDefType(GVE->getVariable()->getType(), GVTypeId);
1079 else
1080 visitTypeEntry(GVE->getVariable()->getType(), GVTypeId, false, false);
Yonghong Song6db6b562019-03-16 15:36:31 +00001081 break;
Yonghong Song7b410ac2018-12-19 16:40:25 +00001082 }
Yonghong Song6db6b562019-03-16 15:36:31 +00001083
1084 // Only support the following globals:
1085 // . static variables
Yonghong Song5ea611d2019-12-06 23:00:41 -08001086 // . non-static weak or non-weak global variables
Yonghong Song44481252019-11-22 08:45:37 -08001087 // . weak or non-weak extern global variables
1088 // Whether DataSec is readonly or not can be found from corresponding ELF
1089 // section flags. Whether a BTF_KIND_VAR is a weak symbol or not
1090 // can be found from the corresponding ELF symbol table.
Yonghong Song6db6b562019-03-16 15:36:31 +00001091 auto Linkage = Global.getLinkage();
1092 if (Linkage != GlobalValue::InternalLinkage &&
Yonghong Song5ea611d2019-12-06 23:00:41 -08001093 Linkage != GlobalValue::ExternalLinkage &&
Yonghong Song44481252019-11-22 08:45:37 -08001094 Linkage != GlobalValue::WeakAnyLinkage &&
1095 Linkage != GlobalValue::ExternalWeakLinkage)
Yonghong Song6db6b562019-03-16 15:36:31 +00001096 continue;
1097
Yonghong Song44481252019-11-22 08:45:37 -08001098 uint32_t GVarInfo;
1099 if (Linkage == GlobalValue::InternalLinkage) {
1100 GVarInfo = BTF::VAR_STATIC;
1101 } else if (Global.hasInitializer()) {
1102 GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
1103 } else {
1104 GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
1105 }
1106
Yonghong Song6db6b562019-03-16 15:36:31 +00001107 auto VarEntry =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001108 std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
Yonghong Song6db6b562019-03-16 15:36:31 +00001109 uint32_t VarId = addType(std::move(VarEntry));
1110
Yonghong Song7d0e8932019-12-10 11:05:22 -08001111 assert(!SecName.empty());
Yonghong Song44481252019-11-22 08:45:37 -08001112
Yonghong Song6db6b562019-03-16 15:36:31 +00001113 // Find or create a DataSec
1114 if (DataSecEntries.find(SecName) == DataSecEntries.end()) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001115 DataSecEntries[SecName] = std::make_unique<BTFKindDataSec>(Asm, SecName);
Yonghong Song6db6b562019-03-16 15:36:31 +00001116 }
1117
1118 // Calculate symbol size
1119 const DataLayout &DL = Global.getParent()->getDataLayout();
1120 uint32_t Size = DL.getTypeAllocSize(Global.getType()->getElementType());
1121
1122 DataSecEntries[SecName]->addVar(VarId, Asm->getSymbol(&Global), Size);
Yonghong Song7b410ac2018-12-19 16:40:25 +00001123 }
Yonghong Songd3d88d02019-07-09 15:28:41 +00001124}
Yonghong Song7b410ac2018-12-19 16:40:25 +00001125
Yonghong Songd3d88d02019-07-09 15:28:41 +00001126/// Emit proper patchable instructions.
1127bool BTFDebug::InstLower(const MachineInstr *MI, MCInst &OutMI) {
1128 if (MI->getOpcode() == BPF::LD_imm64) {
1129 const MachineOperand &MO = MI->getOperand(1);
1130 if (MO.isGlobal()) {
1131 const GlobalValue *GVal = MO.getGlobal();
1132 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1133 if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
Yonghong Song05e46972019-10-08 18:23:17 +00001134 // Emit "mov ri, <imm>" for patched immediate.
1135 uint32_t Imm = PatchImms[GVar->getName().str()];
Yonghong Songd3d88d02019-07-09 15:28:41 +00001136 OutMI.setOpcode(BPF::MOV_ri);
1137 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1138 OutMI.addOperand(MCOperand::createImm(Imm));
1139 return true;
Yonghong Songd3d88d02019-07-09 15:28:41 +00001140 }
1141 }
Yonghong Songffd57402019-12-19 15:21:53 -08001142 } else if (MI->getOpcode() == BPF::CORE_MEM ||
1143 MI->getOpcode() == BPF::CORE_ALU32_MEM ||
1144 MI->getOpcode() == BPF::CORE_SHIFT) {
1145 const MachineOperand &MO = MI->getOperand(3);
1146 if (MO.isGlobal()) {
1147 const GlobalValue *GVal = MO.getGlobal();
1148 auto *GVar = dyn_cast<GlobalVariable>(GVal);
1149 if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
1150 uint32_t Imm = PatchImms[GVar->getName().str()];
1151 OutMI.setOpcode(MI->getOperand(1).getImm());
1152 if (MI->getOperand(0).isImm())
1153 OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
1154 else
1155 OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1156 OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
1157 OutMI.addOperand(MCOperand::createImm(Imm));
1158 return true;
1159 }
1160 }
Yonghong Songd3d88d02019-07-09 15:28:41 +00001161 }
1162 return false;
Yonghong Song6db6b562019-03-16 15:36:31 +00001163}
1164
Yonghong Song44481252019-11-22 08:45:37 -08001165void BTFDebug::processFuncPrototypes() {
1166 const Module *M = MMI->getModule();
1167 for (const Function &F : M->functions()) {
1168 const DISubprogram *SP = F.getSubprogram();
1169 if (!SP || SP->isDefinition())
1170 continue;
1171
1172 uint32_t ProtoTypeId;
1173 const std::unordered_map<uint32_t, StringRef> FuncArgNames;
1174 visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
1175
1176 auto VarEntry =
1177 std::make_unique<BTFKindVar>(SP->getName(), ProtoTypeId,
1178 BTF::VAR_GLOBAL_EXTERNAL);
1179 uint32_t VarId = addType(std::move(VarEntry));
1180
1181 StringRef SecName = F.getSection();
1182 if (SecName.empty())
Yonghong Song7d0e8932019-12-10 11:05:22 -08001183 SecName = ".extern";
Yonghong Song44481252019-11-22 08:45:37 -08001184
1185 if (DataSecEntries.find(SecName) == DataSecEntries.end()) {
1186 DataSecEntries[SecName] = std::make_unique<BTFKindDataSec>(Asm, SecName);
1187 }
1188
1189 DataSecEntries[SecName]->addVar(VarId, Asm->getSymbol(&F), 8);
1190 }
1191}
1192
Yonghong Song6db6b562019-03-16 15:36:31 +00001193void BTFDebug::endModule() {
Yonghong Songd3d88d02019-07-09 15:28:41 +00001194 // Collect MapDef globals if not collected yet.
1195 if (MapDefNotCollected) {
1196 processGlobals(true);
1197 MapDefNotCollected = false;
1198 }
1199
1200 // Collect global types/variables except MapDef globals.
1201 processGlobals(false);
Yonghong Song44481252019-11-22 08:45:37 -08001202
1203 processFuncPrototypes();
1204
Yonghong Songd3d88d02019-07-09 15:28:41 +00001205 for (auto &DataSec : DataSecEntries)
1206 addType(std::move(DataSec.second));
1207
1208 // Fixups
1209 for (auto &Fixup : FixupDerivedTypes) {
1210 StringRef TypeName = Fixup.first;
1211 bool IsUnion = Fixup.second.first;
1212
1213 // Search through struct types
1214 uint32_t StructTypeId = 0;
1215 for (const auto &StructType : StructTypes) {
1216 if (StructType->getName() == TypeName) {
1217 StructTypeId = StructType->getId();
1218 break;
1219 }
1220 }
1221
1222 if (StructTypeId == 0) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001223 auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
Yonghong Songd3d88d02019-07-09 15:28:41 +00001224 StructTypeId = addType(std::move(FwdTypeEntry));
1225 }
1226
1227 for (auto &DType : Fixup.second.second) {
1228 DType->setPointeeType(StructTypeId);
1229 }
1230 }
Yonghong Song6db6b562019-03-16 15:36:31 +00001231
Yonghong Song7b410ac2018-12-19 16:40:25 +00001232 // Complete BTF type cross refereences.
1233 for (const auto &TypeEntry : TypeEntries)
1234 TypeEntry->completeType(*this);
1235
1236 // Emit BTF sections.
1237 emitBTFSection();
1238 emitBTFExtSection();
1239}