blob: b213b1579661784dcb61e5c5c57f7c7d67c848fa [file] [log] [blame]
Yonghong Songd3d88d02019-07-09 15:28:41 +00001//===------ BPFAbstractMemberAccess.cpp - Abstracting Member Accesses -----===//
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 pass abstracted struct/union member accesses in order to support
10// compile-once run-everywhere (CO-RE). The CO-RE intends to compile the program
11// which can run on different kernels. In particular, if bpf program tries to
12// access a particular kernel data structure member, the details of the
13// intermediate member access will be remembered so bpf loader can do
14// necessary adjustment right before program loading.
15//
16// For example,
17//
18// struct s {
19// int a;
20// int b;
21// };
22// struct t {
23// struct s c;
24// int d;
25// };
26// struct t e;
27//
28// For the member access e.c.b, the compiler will generate code
29// &e + 4
30//
31// The compile-once run-everywhere instead generates the following code
32// r = 4
33// &e + r
34// The "4" in "r = 4" can be changed based on a particular kernel version.
35// For example, on a particular kernel version, if struct s is changed to
36//
37// struct s {
38// int new_field;
39// int a;
40// int b;
41// }
42//
43// By repeating the member access on the host, the bpf loader can
44// adjust "r = 4" as "r = 8".
45//
46// This feature relies on the following three intrinsic calls:
47// addr = preserve_array_access_index(base, dimension, index)
48// addr = preserve_union_access_index(base, di_index)
49// !llvm.preserve.access.index <union_ditype>
50// addr = preserve_struct_access_index(base, gep_index, di_index)
51// !llvm.preserve.access.index <struct_ditype>
52//
Yonghong Song05e46972019-10-08 18:23:17 +000053// Bitfield member access needs special attention. User cannot take the
54// address of a bitfield acceess. To facilitate kernel verifier
55// for easy bitfield code optimization, a new clang intrinsic is introduced:
56// uint32_t __builtin_preserve_field_info(member_access, info_kind)
57// In IR, a chain with two (or more) intrinsic calls will be generated:
58// ...
59// addr = preserve_struct_access_index(base, 1, 1) !struct s
60// uint32_t result = bpf_preserve_field_info(addr, info_kind)
61//
62// Suppose the info_kind is FIELD_SIGNEDNESS,
63// The above two IR intrinsics will be replaced with
64// a relocatable insn:
65// signness = /* signness of member_access */
66// and signness can be changed by bpf loader based on the
67// types on the host.
68//
69// User can also test whether a field exists or not with
70// uint32_t result = bpf_preserve_field_info(member_access, FIELD_EXISTENCE)
71// The field will be always available (result = 1) during initial
72// compilation, but bpf loader can patch with the correct value
73// on the target host where the member_access may or may not be available
74//
Yonghong Songd3d88d02019-07-09 15:28:41 +000075//===----------------------------------------------------------------------===//
76
77#include "BPF.h"
78#include "BPFCORE.h"
79#include "BPFTargetMachine.h"
80#include "llvm/IR/DebugInfoMetadata.h"
81#include "llvm/IR/GlobalVariable.h"
82#include "llvm/IR/Instruction.h"
83#include "llvm/IR/Instructions.h"
84#include "llvm/IR/Module.h"
85#include "llvm/IR/Type.h"
86#include "llvm/IR/User.h"
87#include "llvm/IR/Value.h"
88#include "llvm/Pass.h"
89#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Yonghong Song37d24a62019-08-02 23:16:44 +000090#include <stack>
Yonghong Songd3d88d02019-07-09 15:28:41 +000091
92#define DEBUG_TYPE "bpf-abstract-member-access"
93
94namespace llvm {
Benjamin Kramerdf9a51d2020-06-17 14:27:36 +020095constexpr StringRef BPFCoreSharedInfo::AmaAttr;
Yonghong Songd3d88d02019-07-09 15:28:41 +000096} // namespace llvm
97
98using namespace llvm;
99
100namespace {
101
102class BPFAbstractMemberAccess final : public ModulePass {
103 StringRef getPassName() const override {
104 return "BPF Abstract Member Access";
105 }
106
107 bool runOnModule(Module &M) override;
108
109public:
110 static char ID;
Yonghong Song05e46972019-10-08 18:23:17 +0000111 TargetMachine *TM;
112 // Add optional BPFTargetMachine parameter so that BPF backend can add the phase
113 // with target machine to find out the endianness. The default constructor (without
114 // parameters) is used by the pass manager for managing purposes.
115 BPFAbstractMemberAccess(BPFTargetMachine *TM = nullptr) : ModulePass(ID), TM(TM) {}
Yonghong Songd3d88d02019-07-09 15:28:41 +0000116
Yonghong Song02ac7502019-10-03 16:30:29 +0000117 struct CallInfo {
118 uint32_t Kind;
119 uint32_t AccessIndex;
Yonghong Song9f344472019-11-04 22:12:52 -0800120 uint32_t RecordAlignment;
Yonghong Song02ac7502019-10-03 16:30:29 +0000121 MDNode *Metadata;
122 Value *Base;
123 };
Yonghong Song05e46972019-10-08 18:23:17 +0000124 typedef std::stack<std::pair<CallInst *, CallInfo>> CallInfoStack;
Yonghong Song02ac7502019-10-03 16:30:29 +0000125
Yonghong Songd3d88d02019-07-09 15:28:41 +0000126private:
127 enum : uint32_t {
128 BPFPreserveArrayAI = 1,
129 BPFPreserveUnionAI = 2,
130 BPFPreserveStructAI = 3,
Yonghong Song05e46972019-10-08 18:23:17 +0000131 BPFPreserveFieldInfoAI = 4,
Yonghong Songd3d88d02019-07-09 15:28:41 +0000132 };
133
Simon Pilgrimf784ad82019-11-14 13:53:35 +0000134 const DataLayout *DL = nullptr;
Yonghong Songfff27212019-10-30 12:44:49 -0400135
Yonghong Songd3d88d02019-07-09 15:28:41 +0000136 std::map<std::string, GlobalVariable *> GEPGlobals;
137 // A map to link preserve_*_access_index instrinsic calls.
Yonghong Song02ac7502019-10-03 16:30:29 +0000138 std::map<CallInst *, std::pair<CallInst *, CallInfo>> AIChain;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000139 // A map to hold all the base preserve_*_access_index instrinsic calls.
Yonghong Song05e46972019-10-08 18:23:17 +0000140 // The base call is not an input of any other preserve_*
Yonghong Songd3d88d02019-07-09 15:28:41 +0000141 // intrinsics.
Yonghong Song02ac7502019-10-03 16:30:29 +0000142 std::map<CallInst *, CallInfo> BaseAICalls;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000143
144 bool doTransformation(Module &M);
145
Yonghong Song02ac7502019-10-03 16:30:29 +0000146 void traceAICall(CallInst *Call, CallInfo &ParentInfo);
147 void traceBitCast(BitCastInst *BitCast, CallInst *Parent,
148 CallInfo &ParentInfo);
149 void traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
150 CallInfo &ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000151 void collectAICallChains(Module &M, Function &F);
152
Yonghong Song02ac7502019-10-03 16:30:29 +0000153 bool IsPreserveDIAccessIndexCall(const CallInst *Call, CallInfo &Cinfo);
Yonghong Song37d24a62019-08-02 23:16:44 +0000154 bool IsValidAIChain(const MDNode *ParentMeta, uint32_t ParentAI,
155 const MDNode *ChildMeta);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000156 bool removePreserveAccessIndexIntrinsic(Module &M);
157 void replaceWithGEP(std::vector<CallInst *> &CallList,
158 uint32_t NumOfZerosIndex, uint32_t DIIndex);
Yonghong Song05e46972019-10-08 18:23:17 +0000159 bool HasPreserveFieldInfoCall(CallInfoStack &CallStack);
Yonghong Songfff27212019-10-30 12:44:49 -0400160 void GetStorageBitRange(DIDerivedType *MemberTy, uint32_t RecordAlignment,
161 uint32_t &StartBitOffset, uint32_t &EndBitOffset);
Yonghong Song05e46972019-10-08 18:23:17 +0000162 uint32_t GetFieldInfo(uint32_t InfoKind, DICompositeType *CTy,
Yonghong Songfff27212019-10-30 12:44:49 -0400163 uint32_t AccessIndex, uint32_t PatchImm,
164 uint32_t RecordAlignment);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000165
Yonghong Song02ac7502019-10-03 16:30:29 +0000166 Value *computeBaseAndAccessKey(CallInst *Call, CallInfo &CInfo,
167 std::string &AccessKey, MDNode *&BaseMeta);
168 uint64_t getConstant(const Value *IndexValue);
169 bool transformGEPChain(Module &M, CallInst *Call, CallInfo &CInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000170};
171} // End anonymous namespace
172
173char BPFAbstractMemberAccess::ID = 0;
174INITIALIZE_PASS(BPFAbstractMemberAccess, DEBUG_TYPE,
175 "abstracting struct/union member accessees", false, false)
176
Yonghong Song05e46972019-10-08 18:23:17 +0000177ModulePass *llvm::createBPFAbstractMemberAccess(BPFTargetMachine *TM) {
178 return new BPFAbstractMemberAccess(TM);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000179}
180
181bool BPFAbstractMemberAccess::runOnModule(Module &M) {
182 LLVM_DEBUG(dbgs() << "********** Abstract Member Accesses **********\n");
183
184 // Bail out if no debug info.
Jordan Rosefdaa7422019-10-07 18:14:24 +0000185 if (M.debug_compile_units().empty())
Yonghong Songd3d88d02019-07-09 15:28:41 +0000186 return false;
187
Yonghong Songfff27212019-10-30 12:44:49 -0400188 DL = &M.getDataLayout();
Yonghong Songd3d88d02019-07-09 15:28:41 +0000189 return doTransformation(M);
190}
191
Yonghong Song6d078022020-02-01 21:00:00 -0800192static bool SkipDIDerivedTag(unsigned Tag, bool skipTypedef) {
Yonghong Song37d24a62019-08-02 23:16:44 +0000193 if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
194 Tag != dwarf::DW_TAG_volatile_type &&
195 Tag != dwarf::DW_TAG_restrict_type &&
196 Tag != dwarf::DW_TAG_member)
Yonghong Song6d078022020-02-01 21:00:00 -0800197 return false;
198 if (Tag == dwarf::DW_TAG_typedef && !skipTypedef)
199 return false;
Yonghong Song37d24a62019-08-02 23:16:44 +0000200 return true;
201}
202
Yonghong Song6d078022020-02-01 21:00:00 -0800203static DIType * stripQualifiers(DIType *Ty, bool skipTypedef = true) {
Yonghong Song37d24a62019-08-02 23:16:44 +0000204 while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
Yonghong Song6d078022020-02-01 21:00:00 -0800205 if (!SkipDIDerivedTag(DTy->getTag(), skipTypedef))
Yonghong Song37d24a62019-08-02 23:16:44 +0000206 break;
207 Ty = DTy->getBaseType();
208 }
209 return Ty;
210}
211
212static const DIType * stripQualifiers(const DIType *Ty) {
213 while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
Yonghong Song6d078022020-02-01 21:00:00 -0800214 if (!SkipDIDerivedTag(DTy->getTag(), true))
Yonghong Song37d24a62019-08-02 23:16:44 +0000215 break;
216 Ty = DTy->getBaseType();
217 }
218 return Ty;
219}
220
221static uint32_t calcArraySize(const DICompositeType *CTy, uint32_t StartDim) {
222 DINodeArray Elements = CTy->getElements();
223 uint32_t DimSize = 1;
224 for (uint32_t I = StartDim; I < Elements.size(); ++I) {
225 if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
226 if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
227 const DISubrange *SR = cast<DISubrange>(Element);
228 auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
229 DimSize *= CI->getSExtValue();
230 }
231 }
232
233 return DimSize;
234}
235
Yonghong Songd3d88d02019-07-09 15:28:41 +0000236/// Check whether a call is a preserve_*_access_index intrinsic call or not.
237bool BPFAbstractMemberAccess::IsPreserveDIAccessIndexCall(const CallInst *Call,
Yonghong Song02ac7502019-10-03 16:30:29 +0000238 CallInfo &CInfo) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000239 if (!Call)
240 return false;
241
Craig Toppera58b62b2020-04-27 20:15:59 -0700242 const auto *GV = dyn_cast<GlobalValue>(Call->getCalledOperand());
Yonghong Songd3d88d02019-07-09 15:28:41 +0000243 if (!GV)
244 return false;
245 if (GV->getName().startswith("llvm.preserve.array.access.index")) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000246 CInfo.Kind = BPFPreserveArrayAI;
247 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
248 if (!CInfo.Metadata)
Yonghong Song37d24a62019-08-02 23:16:44 +0000249 report_fatal_error("Missing metadata for llvm.preserve.array.access.index intrinsic");
Yonghong Song02ac7502019-10-03 16:30:29 +0000250 CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
251 CInfo.Base = Call->getArgOperand(0);
Yonghong Song9f344472019-11-04 22:12:52 -0800252 CInfo.RecordAlignment =
253 DL->getABITypeAlignment(CInfo.Base->getType()->getPointerElementType());
Yonghong Songd3d88d02019-07-09 15:28:41 +0000254 return true;
255 }
256 if (GV->getName().startswith("llvm.preserve.union.access.index")) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000257 CInfo.Kind = BPFPreserveUnionAI;
258 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
259 if (!CInfo.Metadata)
Yonghong Song37d24a62019-08-02 23:16:44 +0000260 report_fatal_error("Missing metadata for llvm.preserve.union.access.index intrinsic");
Yonghong Song02ac7502019-10-03 16:30:29 +0000261 CInfo.AccessIndex = getConstant(Call->getArgOperand(1));
262 CInfo.Base = Call->getArgOperand(0);
Yonghong Song9f344472019-11-04 22:12:52 -0800263 CInfo.RecordAlignment =
264 DL->getABITypeAlignment(CInfo.Base->getType()->getPointerElementType());
Yonghong Songd3d88d02019-07-09 15:28:41 +0000265 return true;
266 }
267 if (GV->getName().startswith("llvm.preserve.struct.access.index")) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000268 CInfo.Kind = BPFPreserveStructAI;
269 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
270 if (!CInfo.Metadata)
Yonghong Song37d24a62019-08-02 23:16:44 +0000271 report_fatal_error("Missing metadata for llvm.preserve.struct.access.index intrinsic");
Yonghong Song02ac7502019-10-03 16:30:29 +0000272 CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
273 CInfo.Base = Call->getArgOperand(0);
Yonghong Song9f344472019-11-04 22:12:52 -0800274 CInfo.RecordAlignment =
275 DL->getABITypeAlignment(CInfo.Base->getType()->getPointerElementType());
Yonghong Songd3d88d02019-07-09 15:28:41 +0000276 return true;
277 }
Yonghong Song05e46972019-10-08 18:23:17 +0000278 if (GV->getName().startswith("llvm.bpf.preserve.field.info")) {
279 CInfo.Kind = BPFPreserveFieldInfoAI;
280 CInfo.Metadata = nullptr;
281 // Check validity of info_kind as clang did not check this.
282 uint64_t InfoKind = getConstant(Call->getArgOperand(1));
283 if (InfoKind >= BPFCoreSharedInfo::MAX_FIELD_RELOC_KIND)
284 report_fatal_error("Incorrect info_kind for llvm.bpf.preserve.field.info intrinsic");
285 CInfo.AccessIndex = InfoKind;
286 return true;
287 }
Yonghong Songd3d88d02019-07-09 15:28:41 +0000288
289 return false;
290}
291
292void BPFAbstractMemberAccess::replaceWithGEP(std::vector<CallInst *> &CallList,
293 uint32_t DimensionIndex,
294 uint32_t GEPIndex) {
295 for (auto Call : CallList) {
296 uint32_t Dimension = 1;
297 if (DimensionIndex > 0)
Yonghong Song02ac7502019-10-03 16:30:29 +0000298 Dimension = getConstant(Call->getArgOperand(DimensionIndex));
Yonghong Songd3d88d02019-07-09 15:28:41 +0000299
300 Constant *Zero =
301 ConstantInt::get(Type::getInt32Ty(Call->getParent()->getContext()), 0);
302 SmallVector<Value *, 4> IdxList;
303 for (unsigned I = 0; I < Dimension; ++I)
304 IdxList.push_back(Zero);
305 IdxList.push_back(Call->getArgOperand(GEPIndex));
306
307 auto *GEP = GetElementPtrInst::CreateInBounds(Call->getArgOperand(0),
308 IdxList, "", Call);
309 Call->replaceAllUsesWith(GEP);
310 Call->eraseFromParent();
311 }
312}
313
314bool BPFAbstractMemberAccess::removePreserveAccessIndexIntrinsic(Module &M) {
315 std::vector<CallInst *> PreserveArrayIndexCalls;
316 std::vector<CallInst *> PreserveUnionIndexCalls;
317 std::vector<CallInst *> PreserveStructIndexCalls;
318 bool Found = false;
319
320 for (Function &F : M)
321 for (auto &BB : F)
322 for (auto &I : BB) {
323 auto *Call = dyn_cast<CallInst>(&I);
Yonghong Song02ac7502019-10-03 16:30:29 +0000324 CallInfo CInfo;
325 if (!IsPreserveDIAccessIndexCall(Call, CInfo))
Yonghong Songd3d88d02019-07-09 15:28:41 +0000326 continue;
327
328 Found = true;
Yonghong Song02ac7502019-10-03 16:30:29 +0000329 if (CInfo.Kind == BPFPreserveArrayAI)
Yonghong Songd3d88d02019-07-09 15:28:41 +0000330 PreserveArrayIndexCalls.push_back(Call);
Yonghong Song02ac7502019-10-03 16:30:29 +0000331 else if (CInfo.Kind == BPFPreserveUnionAI)
Yonghong Songd3d88d02019-07-09 15:28:41 +0000332 PreserveUnionIndexCalls.push_back(Call);
333 else
334 PreserveStructIndexCalls.push_back(Call);
335 }
336
337 // do the following transformation:
338 // . addr = preserve_array_access_index(base, dimension, index)
339 // is transformed to
340 // addr = GEP(base, dimenion's zero's, index)
341 // . addr = preserve_union_access_index(base, di_index)
342 // is transformed to
343 // addr = base, i.e., all usages of "addr" are replaced by "base".
344 // . addr = preserve_struct_access_index(base, gep_index, di_index)
345 // is transformed to
346 // addr = GEP(base, 0, gep_index)
347 replaceWithGEP(PreserveArrayIndexCalls, 1, 2);
348 replaceWithGEP(PreserveStructIndexCalls, 0, 1);
349 for (auto Call : PreserveUnionIndexCalls) {
350 Call->replaceAllUsesWith(Call->getArgOperand(0));
351 Call->eraseFromParent();
352 }
353
354 return Found;
355}
356
Yonghong Song37d24a62019-08-02 23:16:44 +0000357/// Check whether the access index chain is valid. We check
358/// here because there may be type casts between two
359/// access indexes. We want to ensure memory access still valid.
360bool BPFAbstractMemberAccess::IsValidAIChain(const MDNode *ParentType,
361 uint32_t ParentAI,
362 const MDNode *ChildType) {
Yonghong Song05e46972019-10-08 18:23:17 +0000363 if (!ChildType)
364 return true; // preserve_field_info, no type comparison needed.
365
Yonghong Song37d24a62019-08-02 23:16:44 +0000366 const DIType *PType = stripQualifiers(cast<DIType>(ParentType));
367 const DIType *CType = stripQualifiers(cast<DIType>(ChildType));
368
369 // Child is a derived/pointer type, which is due to type casting.
370 // Pointer type cannot be in the middle of chain.
Bill Wendlingebc2cf92019-08-06 07:27:26 +0000371 if (isa<DIDerivedType>(CType))
Yonghong Song37d24a62019-08-02 23:16:44 +0000372 return false;
373
374 // Parent is a pointer type.
375 if (const auto *PtrTy = dyn_cast<DIDerivedType>(PType)) {
376 if (PtrTy->getTag() != dwarf::DW_TAG_pointer_type)
377 return false;
378 return stripQualifiers(PtrTy->getBaseType()) == CType;
379 }
380
381 // Otherwise, struct/union/array types
382 const auto *PTy = dyn_cast<DICompositeType>(PType);
383 const auto *CTy = dyn_cast<DICompositeType>(CType);
384 assert(PTy && CTy && "ParentType or ChildType is null or not composite");
385
386 uint32_t PTyTag = PTy->getTag();
387 assert(PTyTag == dwarf::DW_TAG_array_type ||
388 PTyTag == dwarf::DW_TAG_structure_type ||
389 PTyTag == dwarf::DW_TAG_union_type);
390
391 uint32_t CTyTag = CTy->getTag();
392 assert(CTyTag == dwarf::DW_TAG_array_type ||
393 CTyTag == dwarf::DW_TAG_structure_type ||
394 CTyTag == dwarf::DW_TAG_union_type);
395
396 // Multi dimensional arrays, base element should be the same
397 if (PTyTag == dwarf::DW_TAG_array_type && PTyTag == CTyTag)
398 return PTy->getBaseType() == CTy->getBaseType();
399
400 DIType *Ty;
401 if (PTyTag == dwarf::DW_TAG_array_type)
402 Ty = PTy->getBaseType();
403 else
404 Ty = dyn_cast<DIType>(PTy->getElements()[ParentAI]);
405
406 return dyn_cast<DICompositeType>(stripQualifiers(Ty)) == CTy;
407}
408
Yonghong Song02ac7502019-10-03 16:30:29 +0000409void BPFAbstractMemberAccess::traceAICall(CallInst *Call,
410 CallInfo &ParentInfo) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000411 for (User *U : Call->users()) {
412 Instruction *Inst = dyn_cast<Instruction>(U);
413 if (!Inst)
414 continue;
415
416 if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000417 traceBitCast(BI, Call, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000418 } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000419 CallInfo ChildInfo;
420
421 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
422 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
423 ChildInfo.Metadata)) {
424 AIChain[CI] = std::make_pair(Call, ParentInfo);
425 traceAICall(CI, ChildInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000426 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000427 BaseAICalls[Call] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000428 }
429 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
430 if (GI->hasAllZeroIndices())
Yonghong Song02ac7502019-10-03 16:30:29 +0000431 traceGEP(GI, Call, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000432 else
Yonghong Song02ac7502019-10-03 16:30:29 +0000433 BaseAICalls[Call] = ParentInfo;
Yonghong Songc68ee0c2019-09-18 03:49:07 +0000434 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000435 BaseAICalls[Call] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000436 }
437 }
438}
439
440void BPFAbstractMemberAccess::traceBitCast(BitCastInst *BitCast,
Yonghong Song02ac7502019-10-03 16:30:29 +0000441 CallInst *Parent,
442 CallInfo &ParentInfo) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000443 for (User *U : BitCast->users()) {
444 Instruction *Inst = dyn_cast<Instruction>(U);
445 if (!Inst)
446 continue;
447
448 if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000449 traceBitCast(BI, Parent, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000450 } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000451 CallInfo ChildInfo;
452 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
453 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
454 ChildInfo.Metadata)) {
455 AIChain[CI] = std::make_pair(Parent, ParentInfo);
456 traceAICall(CI, ChildInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000457 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000458 BaseAICalls[Parent] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000459 }
460 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
461 if (GI->hasAllZeroIndices())
Yonghong Song02ac7502019-10-03 16:30:29 +0000462 traceGEP(GI, Parent, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000463 else
Yonghong Song02ac7502019-10-03 16:30:29 +0000464 BaseAICalls[Parent] = ParentInfo;
Yonghong Songc68ee0c2019-09-18 03:49:07 +0000465 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000466 BaseAICalls[Parent] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000467 }
468 }
469}
470
471void BPFAbstractMemberAccess::traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
Yonghong Song02ac7502019-10-03 16:30:29 +0000472 CallInfo &ParentInfo) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000473 for (User *U : GEP->users()) {
474 Instruction *Inst = dyn_cast<Instruction>(U);
475 if (!Inst)
476 continue;
477
478 if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000479 traceBitCast(BI, Parent, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000480 } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000481 CallInfo ChildInfo;
482 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
483 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
484 ChildInfo.Metadata)) {
485 AIChain[CI] = std::make_pair(Parent, ParentInfo);
486 traceAICall(CI, ChildInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000487 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000488 BaseAICalls[Parent] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000489 }
490 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
491 if (GI->hasAllZeroIndices())
Yonghong Song02ac7502019-10-03 16:30:29 +0000492 traceGEP(GI, Parent, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000493 else
Yonghong Song02ac7502019-10-03 16:30:29 +0000494 BaseAICalls[Parent] = ParentInfo;
Yonghong Songc68ee0c2019-09-18 03:49:07 +0000495 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000496 BaseAICalls[Parent] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000497 }
498 }
499}
500
501void BPFAbstractMemberAccess::collectAICallChains(Module &M, Function &F) {
502 AIChain.clear();
503 BaseAICalls.clear();
504
505 for (auto &BB : F)
506 for (auto &I : BB) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000507 CallInfo CInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000508 auto *Call = dyn_cast<CallInst>(&I);
Yonghong Song02ac7502019-10-03 16:30:29 +0000509 if (!IsPreserveDIAccessIndexCall(Call, CInfo) ||
Yonghong Songd3d88d02019-07-09 15:28:41 +0000510 AIChain.find(Call) != AIChain.end())
511 continue;
512
Yonghong Song02ac7502019-10-03 16:30:29 +0000513 traceAICall(Call, CInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000514 }
515}
516
Yonghong Song02ac7502019-10-03 16:30:29 +0000517uint64_t BPFAbstractMemberAccess::getConstant(const Value *IndexValue) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000518 const ConstantInt *CV = dyn_cast<ConstantInt>(IndexValue);
Yonghong Song02ac7502019-10-03 16:30:29 +0000519 assert(CV);
520 return CV->getValue().getZExtValue();
Yonghong Songd3d88d02019-07-09 15:28:41 +0000521}
522
Yonghong Song05e46972019-10-08 18:23:17 +0000523/// Get the start and the end of storage offset for \p MemberTy.
Yonghong Songfff27212019-10-30 12:44:49 -0400524void BPFAbstractMemberAccess::GetStorageBitRange(DIDerivedType *MemberTy,
525 uint32_t RecordAlignment,
Yonghong Song05e46972019-10-08 18:23:17 +0000526 uint32_t &StartBitOffset,
527 uint32_t &EndBitOffset) {
Yonghong Songfff27212019-10-30 12:44:49 -0400528 uint32_t MemberBitSize = MemberTy->getSizeInBits();
529 uint32_t MemberBitOffset = MemberTy->getOffsetInBits();
530 uint32_t AlignBits = RecordAlignment * 8;
531 if (RecordAlignment > 8 || MemberBitSize > AlignBits)
532 report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
533 "requiring too big alignment");
Yonghong Song05e46972019-10-08 18:23:17 +0000534
Yonghong Songfff27212019-10-30 12:44:49 -0400535 StartBitOffset = MemberBitOffset & ~(AlignBits - 1);
536 if ((StartBitOffset + AlignBits) < (MemberBitOffset + MemberBitSize))
537 report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
538 "cross alignment boundary");
539 EndBitOffset = StartBitOffset + AlignBits;
Yonghong Song05e46972019-10-08 18:23:17 +0000540}
541
542uint32_t BPFAbstractMemberAccess::GetFieldInfo(uint32_t InfoKind,
543 DICompositeType *CTy,
544 uint32_t AccessIndex,
Yonghong Songfff27212019-10-30 12:44:49 -0400545 uint32_t PatchImm,
546 uint32_t RecordAlignment) {
Yonghong Song05e46972019-10-08 18:23:17 +0000547 if (InfoKind == BPFCoreSharedInfo::FIELD_EXISTENCE)
548 return 1;
549
550 uint32_t Tag = CTy->getTag();
551 if (InfoKind == BPFCoreSharedInfo::FIELD_BYTE_OFFSET) {
552 if (Tag == dwarf::DW_TAG_array_type) {
553 auto *EltTy = stripQualifiers(CTy->getBaseType());
554 PatchImm += AccessIndex * calcArraySize(CTy, 1) *
555 (EltTy->getSizeInBits() >> 3);
556 } else if (Tag == dwarf::DW_TAG_structure_type) {
557 auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
558 if (!MemberTy->isBitField()) {
559 PatchImm += MemberTy->getOffsetInBits() >> 3;
560 } else {
Yonghong Songfff27212019-10-30 12:44:49 -0400561 unsigned SBitOffset, NextSBitOffset;
562 GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset,
563 NextSBitOffset);
564 PatchImm += SBitOffset >> 3;
Yonghong Song05e46972019-10-08 18:23:17 +0000565 }
566 }
567 return PatchImm;
568 }
569
570 if (InfoKind == BPFCoreSharedInfo::FIELD_BYTE_SIZE) {
571 if (Tag == dwarf::DW_TAG_array_type) {
572 auto *EltTy = stripQualifiers(CTy->getBaseType());
573 return calcArraySize(CTy, 1) * (EltTy->getSizeInBits() >> 3);
574 } else {
575 auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
576 uint32_t SizeInBits = MemberTy->getSizeInBits();
577 if (!MemberTy->isBitField())
578 return SizeInBits >> 3;
579
580 unsigned SBitOffset, NextSBitOffset;
Yonghong Songfff27212019-10-30 12:44:49 -0400581 GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
Yonghong Song05e46972019-10-08 18:23:17 +0000582 SizeInBits = NextSBitOffset - SBitOffset;
583 if (SizeInBits & (SizeInBits - 1))
584 report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info");
585 return SizeInBits >> 3;
586 }
587 }
588
589 if (InfoKind == BPFCoreSharedInfo::FIELD_SIGNEDNESS) {
590 const DIType *BaseTy;
591 if (Tag == dwarf::DW_TAG_array_type) {
592 // Signedness only checked when final array elements are accessed.
593 if (CTy->getElements().size() != 1)
594 report_fatal_error("Invalid array expression for llvm.bpf.preserve.field.info");
595 BaseTy = stripQualifiers(CTy->getBaseType());
596 } else {
597 auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
598 BaseTy = stripQualifiers(MemberTy->getBaseType());
599 }
600
601 // Only basic types and enum types have signedness.
602 const auto *BTy = dyn_cast<DIBasicType>(BaseTy);
603 while (!BTy) {
604 const auto *CompTy = dyn_cast<DICompositeType>(BaseTy);
605 // Report an error if the field expression does not have signedness.
606 if (!CompTy || CompTy->getTag() != dwarf::DW_TAG_enumeration_type)
607 report_fatal_error("Invalid field expression for llvm.bpf.preserve.field.info");
608 BaseTy = stripQualifiers(CompTy->getBaseType());
609 BTy = dyn_cast<DIBasicType>(BaseTy);
610 }
611 uint32_t Encoding = BTy->getEncoding();
612 return (Encoding == dwarf::DW_ATE_signed || Encoding == dwarf::DW_ATE_signed_char);
613 }
614
615 if (InfoKind == BPFCoreSharedInfo::FIELD_LSHIFT_U64) {
616 // The value is loaded into a value with FIELD_BYTE_SIZE size,
617 // and then zero or sign extended to U64.
618 // FIELD_LSHIFT_U64 and FIELD_RSHIFT_U64 are operations
619 // to extract the original value.
620 const Triple &Triple = TM->getTargetTriple();
621 DIDerivedType *MemberTy = nullptr;
622 bool IsBitField = false;
623 uint32_t SizeInBits;
624
625 if (Tag == dwarf::DW_TAG_array_type) {
626 auto *EltTy = stripQualifiers(CTy->getBaseType());
627 SizeInBits = calcArraySize(CTy, 1) * EltTy->getSizeInBits();
628 } else {
629 MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
630 SizeInBits = MemberTy->getSizeInBits();
631 IsBitField = MemberTy->isBitField();
632 }
633
634 if (!IsBitField) {
635 if (SizeInBits > 64)
636 report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
637 return 64 - SizeInBits;
638 }
639
640 unsigned SBitOffset, NextSBitOffset;
Yonghong Songfff27212019-10-30 12:44:49 -0400641 GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
Yonghong Song05e46972019-10-08 18:23:17 +0000642 if (NextSBitOffset - SBitOffset > 64)
643 report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
644
645 unsigned OffsetInBits = MemberTy->getOffsetInBits();
646 if (Triple.getArch() == Triple::bpfel)
647 return SBitOffset + 64 - OffsetInBits - SizeInBits;
648 else
649 return OffsetInBits + 64 - NextSBitOffset;
650 }
651
652 if (InfoKind == BPFCoreSharedInfo::FIELD_RSHIFT_U64) {
653 DIDerivedType *MemberTy = nullptr;
654 bool IsBitField = false;
655 uint32_t SizeInBits;
656 if (Tag == dwarf::DW_TAG_array_type) {
657 auto *EltTy = stripQualifiers(CTy->getBaseType());
658 SizeInBits = calcArraySize(CTy, 1) * EltTy->getSizeInBits();
659 } else {
660 MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
661 SizeInBits = MemberTy->getSizeInBits();
662 IsBitField = MemberTy->isBitField();
663 }
664
665 if (!IsBitField) {
666 if (SizeInBits > 64)
667 report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
668 return 64 - SizeInBits;
669 }
670
671 unsigned SBitOffset, NextSBitOffset;
Yonghong Songfff27212019-10-30 12:44:49 -0400672 GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
Yonghong Song05e46972019-10-08 18:23:17 +0000673 if (NextSBitOffset - SBitOffset > 64)
674 report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
675
676 return 64 - SizeInBits;
677 }
678
679 llvm_unreachable("Unknown llvm.bpf.preserve.field.info info kind");
680}
681
682bool BPFAbstractMemberAccess::HasPreserveFieldInfoCall(CallInfoStack &CallStack) {
683 // This is called in error return path, no need to maintain CallStack.
684 while (CallStack.size()) {
685 auto StackElem = CallStack.top();
686 if (StackElem.second.Kind == BPFPreserveFieldInfoAI)
687 return true;
688 CallStack.pop();
689 }
690 return false;
691}
692
693/// Compute the base of the whole preserve_* intrinsics chains, i.e., the base
Yonghong Songd3d88d02019-07-09 15:28:41 +0000694/// pointer of the first preserve_*_access_index call, and construct the access
695/// string, which will be the name of a global variable.
Yonghong Songd8efec92019-07-25 16:01:26 +0000696Value *BPFAbstractMemberAccess::computeBaseAndAccessKey(CallInst *Call,
Yonghong Song02ac7502019-10-03 16:30:29 +0000697 CallInfo &CInfo,
Yonghong Songd3d88d02019-07-09 15:28:41 +0000698 std::string &AccessKey,
Yonghong Songd3d88d02019-07-09 15:28:41 +0000699 MDNode *&TypeMeta) {
700 Value *Base = nullptr;
Yonghong Song37d24a62019-08-02 23:16:44 +0000701 std::string TypeName;
Yonghong Song05e46972019-10-08 18:23:17 +0000702 CallInfoStack CallStack;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000703
Yonghong Song37d24a62019-08-02 23:16:44 +0000704 // Put the access chain into a stack with the top as the head of the chain.
Yonghong Songd3d88d02019-07-09 15:28:41 +0000705 while (Call) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000706 CallStack.push(std::make_pair(Call, CInfo));
707 CInfo = AIChain[Call].second;
Yonghong Song37d24a62019-08-02 23:16:44 +0000708 Call = AIChain[Call].first;
709 }
Yonghong Songd3d88d02019-07-09 15:28:41 +0000710
Yonghong Song37d24a62019-08-02 23:16:44 +0000711 // The access offset from the base of the head of chain is also
712 // calculated here as all debuginfo types are available.
713
714 // Get type name and calculate the first index.
Yonghong Song6d078022020-02-01 21:00:00 -0800715 // We only want to get type name from typedef, structure or union.
Yonghong Song37d24a62019-08-02 23:16:44 +0000716 // If user wants a relocation like
717 // int *p; ... __builtin_preserve_access_index(&p[4]) ...
718 // or
719 // int a[10][20]; ... __builtin_preserve_access_index(&a[2][3]) ...
720 // we will skip them.
721 uint32_t FirstIndex = 0;
Yonghong Song05e46972019-10-08 18:23:17 +0000722 uint32_t PatchImm = 0; // AccessOffset or the requested field info
723 uint32_t InfoKind = BPFCoreSharedInfo::FIELD_BYTE_OFFSET;
Yonghong Song37d24a62019-08-02 23:16:44 +0000724 while (CallStack.size()) {
725 auto StackElem = CallStack.top();
726 Call = StackElem.first;
Yonghong Song02ac7502019-10-03 16:30:29 +0000727 CInfo = StackElem.second;
Yonghong Song37d24a62019-08-02 23:16:44 +0000728
729 if (!Base)
Yonghong Song02ac7502019-10-03 16:30:29 +0000730 Base = CInfo.Base;
Yonghong Song37d24a62019-08-02 23:16:44 +0000731
Yonghong Song6d078022020-02-01 21:00:00 -0800732 DIType *PossibleTypeDef = stripQualifiers(cast<DIType>(CInfo.Metadata),
733 false);
734 DIType *Ty = stripQualifiers(PossibleTypeDef);
Yonghong Song02ac7502019-10-03 16:30:29 +0000735 if (CInfo.Kind == BPFPreserveUnionAI ||
736 CInfo.Kind == BPFPreserveStructAI) {
Yonghong Song6d078022020-02-01 21:00:00 -0800737 // struct or union type. If the typedef is in the metadata, always
738 // use the typedef.
739 TypeName = std::string(PossibleTypeDef->getName());
740 TypeMeta = PossibleTypeDef;
Yonghong Song05e46972019-10-08 18:23:17 +0000741 PatchImm += FirstIndex * (Ty->getSizeInBits() >> 3);
Yonghong Song37d24a62019-08-02 23:16:44 +0000742 break;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000743 }
744
Yonghong Song05e46972019-10-08 18:23:17 +0000745 assert(CInfo.Kind == BPFPreserveArrayAI);
746
Yonghong Song37d24a62019-08-02 23:16:44 +0000747 // Array entries will always be consumed for accumulative initial index.
748 CallStack.pop();
749
750 // BPFPreserveArrayAI
Yonghong Song02ac7502019-10-03 16:30:29 +0000751 uint64_t AccessIndex = CInfo.AccessIndex;
Yonghong Song37d24a62019-08-02 23:16:44 +0000752
753 DIType *BaseTy = nullptr;
754 bool CheckElemType = false;
755 if (const auto *CTy = dyn_cast<DICompositeType>(Ty)) {
756 // array type
757 assert(CTy->getTag() == dwarf::DW_TAG_array_type);
758
759
760 FirstIndex += AccessIndex * calcArraySize(CTy, 1);
761 BaseTy = stripQualifiers(CTy->getBaseType());
762 CheckElemType = CTy->getElements().size() == 1;
763 } else {
764 // pointer type
765 auto *DTy = cast<DIDerivedType>(Ty);
766 assert(DTy->getTag() == dwarf::DW_TAG_pointer_type);
767
768 BaseTy = stripQualifiers(DTy->getBaseType());
769 CTy = dyn_cast<DICompositeType>(BaseTy);
770 if (!CTy) {
771 CheckElemType = true;
772 } else if (CTy->getTag() != dwarf::DW_TAG_array_type) {
773 FirstIndex += AccessIndex;
774 CheckElemType = true;
775 } else {
776 FirstIndex += AccessIndex * calcArraySize(CTy, 0);
777 }
778 }
779
780 if (CheckElemType) {
781 auto *CTy = dyn_cast<DICompositeType>(BaseTy);
Yonghong Song05e46972019-10-08 18:23:17 +0000782 if (!CTy) {
783 if (HasPreserveFieldInfoCall(CallStack))
784 report_fatal_error("Invalid field access for llvm.preserve.field.info intrinsic");
Yonghong Song37d24a62019-08-02 23:16:44 +0000785 return nullptr;
Yonghong Song05e46972019-10-08 18:23:17 +0000786 }
Yonghong Song37d24a62019-08-02 23:16:44 +0000787
788 unsigned CTag = CTy->getTag();
Yonghong Song05e46972019-10-08 18:23:17 +0000789 if (CTag == dwarf::DW_TAG_structure_type || CTag == dwarf::DW_TAG_union_type) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100790 TypeName = std::string(CTy->getName());
Yonghong Song05e46972019-10-08 18:23:17 +0000791 } else {
792 if (HasPreserveFieldInfoCall(CallStack))
793 report_fatal_error("Invalid field access for llvm.preserve.field.info intrinsic");
794 return nullptr;
795 }
Yonghong Song37d24a62019-08-02 23:16:44 +0000796 TypeMeta = CTy;
Yonghong Song05e46972019-10-08 18:23:17 +0000797 PatchImm += FirstIndex * (CTy->getSizeInBits() >> 3);
Yonghong Song37d24a62019-08-02 23:16:44 +0000798 break;
799 }
800 }
801 assert(TypeName.size());
802 AccessKey += std::to_string(FirstIndex);
803
804 // Traverse the rest of access chain to complete offset calculation
805 // and access key construction.
806 while (CallStack.size()) {
807 auto StackElem = CallStack.top();
Yonghong Song02ac7502019-10-03 16:30:29 +0000808 CInfo = StackElem.second;
Yonghong Song37d24a62019-08-02 23:16:44 +0000809 CallStack.pop();
810
Yonghong Song05e46972019-10-08 18:23:17 +0000811 if (CInfo.Kind == BPFPreserveFieldInfoAI)
812 break;
813
814 // If the next Call (the top of the stack) is a BPFPreserveFieldInfoAI,
815 // the action will be extracting field info.
816 if (CallStack.size()) {
817 auto StackElem2 = CallStack.top();
818 CallInfo CInfo2 = StackElem2.second;
819 if (CInfo2.Kind == BPFPreserveFieldInfoAI) {
820 InfoKind = CInfo2.AccessIndex;
821 assert(CallStack.size() == 1);
822 }
823 }
824
Yonghong Songd3d88d02019-07-09 15:28:41 +0000825 // Access Index
Yonghong Song02ac7502019-10-03 16:30:29 +0000826 uint64_t AccessIndex = CInfo.AccessIndex;
Yonghong Song37d24a62019-08-02 23:16:44 +0000827 AccessKey += ":" + std::to_string(AccessIndex);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000828
Yonghong Song02ac7502019-10-03 16:30:29 +0000829 MDNode *MDN = CInfo.Metadata;
Yonghong Song9f344472019-11-04 22:12:52 -0800830 uint32_t RecordAlignment = CInfo.RecordAlignment;
Yonghong Song37d24a62019-08-02 23:16:44 +0000831 // At this stage, it cannot be pointer type.
832 auto *CTy = cast<DICompositeType>(stripQualifiers(cast<DIType>(MDN)));
Yonghong Songfff27212019-10-30 12:44:49 -0400833 PatchImm = GetFieldInfo(InfoKind, CTy, AccessIndex, PatchImm,
834 RecordAlignment);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000835 }
836
Yonghong Song6db023b2019-11-25 16:31:33 -0800837 // Access key is the
838 // "llvm." + type name + ":" + reloc type + ":" + patched imm + "$" +
839 // access string,
Yonghong Song05e46972019-10-08 18:23:17 +0000840 // uniquely identifying one relocation.
Yonghong Song6db023b2019-11-25 16:31:33 -0800841 // The prefix "llvm." indicates this is a temporary global, which should
842 // not be emitted to ELF file.
843 AccessKey = "llvm." + TypeName + ":" + std::to_string(InfoKind) + ":" +
Yonghong Song05e46972019-10-08 18:23:17 +0000844 std::to_string(PatchImm) + "$" + AccessKey;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000845
846 return Base;
847}
848
849/// Call/Kind is the base preserve_*_access_index() call. Attempts to do
850/// transformation to a chain of relocable GEPs.
851bool BPFAbstractMemberAccess::transformGEPChain(Module &M, CallInst *Call,
Yonghong Song02ac7502019-10-03 16:30:29 +0000852 CallInfo &CInfo) {
Yonghong Songd8efec92019-07-25 16:01:26 +0000853 std::string AccessKey;
Yonghong Song37d24a62019-08-02 23:16:44 +0000854 MDNode *TypeMeta;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000855 Value *Base =
Yonghong Song02ac7502019-10-03 16:30:29 +0000856 computeBaseAndAccessKey(Call, CInfo, AccessKey, TypeMeta);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000857 if (!Base)
858 return false;
859
Yonghong Song05e46972019-10-08 18:23:17 +0000860 BasicBlock *BB = Call->getParent();
861 GlobalVariable *GV;
862
863 if (GEPGlobals.find(AccessKey) == GEPGlobals.end()) {
864 IntegerType *VarType;
865 if (CInfo.Kind == BPFPreserveFieldInfoAI)
866 VarType = Type::getInt32Ty(BB->getContext()); // 32bit return value
867 else
868 VarType = Type::getInt64Ty(BB->getContext()); // 64bit ptr arith
869
870 GV = new GlobalVariable(M, VarType, false, GlobalVariable::ExternalLinkage,
871 NULL, AccessKey);
872 GV->addAttribute(BPFCoreSharedInfo::AmaAttr);
873 GV->setMetadata(LLVMContext::MD_preserve_access_index, TypeMeta);
874 GEPGlobals[AccessKey] = GV;
875 } else {
876 GV = GEPGlobals[AccessKey];
877 }
878
879 if (CInfo.Kind == BPFPreserveFieldInfoAI) {
880 // Load the global variable which represents the returned field info.
Eli Friedman565b56a2020-04-07 16:25:52 -0700881 auto *LDInst = new LoadInst(Type::getInt32Ty(BB->getContext()), GV, "",
882 Call);
Yonghong Song05e46972019-10-08 18:23:17 +0000883 Call->replaceAllUsesWith(LDInst);
884 Call->eraseFromParent();
885 return true;
886 }
887
Yonghong Songd3d88d02019-07-09 15:28:41 +0000888 // For any original GEP Call and Base %2 like
889 // %4 = bitcast %struct.net_device** %dev1 to i64*
890 // it is transformed to:
Yonghong Song37d24a62019-08-02 23:16:44 +0000891 // %6 = load sk_buff:50:$0:0:0:2:0
Yonghong Songd3d88d02019-07-09 15:28:41 +0000892 // %7 = bitcast %struct.sk_buff* %2 to i8*
893 // %8 = getelementptr i8, i8* %7, %6
894 // %9 = bitcast i8* %8 to i64*
895 // using %9 instead of %4
896 // The original Call inst is removed.
Yonghong Songd3d88d02019-07-09 15:28:41 +0000897
898 // Load the global variable.
Eli Friedman565b56a2020-04-07 16:25:52 -0700899 auto *LDInst = new LoadInst(Type::getInt64Ty(BB->getContext()), GV, "", Call);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000900
901 // Generate a BitCast
902 auto *BCInst = new BitCastInst(Base, Type::getInt8PtrTy(BB->getContext()));
903 BB->getInstList().insert(Call->getIterator(), BCInst);
904
905 // Generate a GetElementPtr
906 auto *GEP = GetElementPtrInst::Create(Type::getInt8Ty(BB->getContext()),
907 BCInst, LDInst);
908 BB->getInstList().insert(Call->getIterator(), GEP);
909
910 // Generate a BitCast
911 auto *BCInst2 = new BitCastInst(GEP, Call->getType());
912 BB->getInstList().insert(Call->getIterator(), BCInst2);
913
914 Call->replaceAllUsesWith(BCInst2);
915 Call->eraseFromParent();
916
917 return true;
918}
919
920bool BPFAbstractMemberAccess::doTransformation(Module &M) {
921 bool Transformed = false;
922
923 for (Function &F : M) {
924 // Collect PreserveDIAccessIndex Intrinsic call chains.
925 // The call chains will be used to generate the access
926 // patterns similar to GEP.
927 collectAICallChains(M, F);
928
929 for (auto &C : BaseAICalls)
930 Transformed = transformGEPChain(M, C.first, C.second) || Transformed;
931 }
932
933 return removePreserveAccessIndexIntrinsic(M) || Transformed;
934}