blob: 5a9a34e4af3c28612d3ffc1cd63fb5b348104637 [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//
53//===----------------------------------------------------------------------===//
54
55#include "BPF.h"
56#include "BPFCORE.h"
57#include "BPFTargetMachine.h"
58#include "llvm/IR/DebugInfoMetadata.h"
59#include "llvm/IR/GlobalVariable.h"
60#include "llvm/IR/Instruction.h"
61#include "llvm/IR/Instructions.h"
62#include "llvm/IR/Module.h"
63#include "llvm/IR/Type.h"
64#include "llvm/IR/User.h"
65#include "llvm/IR/Value.h"
66#include "llvm/Pass.h"
67#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Yonghong Song37d24a62019-08-02 23:16:44 +000068#include <stack>
Yonghong Songd3d88d02019-07-09 15:28:41 +000069
70#define DEBUG_TYPE "bpf-abstract-member-access"
71
72namespace llvm {
73const std::string BPFCoreSharedInfo::AmaAttr = "btf_ama";
74const std::string BPFCoreSharedInfo::PatchableExtSecName =
75 ".BPF.patchable_externs";
76} // namespace llvm
77
78using namespace llvm;
79
80namespace {
81
82class BPFAbstractMemberAccess final : public ModulePass {
83 StringRef getPassName() const override {
84 return "BPF Abstract Member Access";
85 }
86
87 bool runOnModule(Module &M) override;
88
89public:
90 static char ID;
91 BPFAbstractMemberAccess() : ModulePass(ID) {}
92
Yonghong Song02ac7502019-10-03 16:30:29 +000093 struct CallInfo {
94 uint32_t Kind;
95 uint32_t AccessIndex;
96 MDNode *Metadata;
97 Value *Base;
98 };
99
Yonghong Songd3d88d02019-07-09 15:28:41 +0000100private:
101 enum : uint32_t {
102 BPFPreserveArrayAI = 1,
103 BPFPreserveUnionAI = 2,
104 BPFPreserveStructAI = 3,
105 };
106
107 std::map<std::string, GlobalVariable *> GEPGlobals;
108 // A map to link preserve_*_access_index instrinsic calls.
Yonghong Song02ac7502019-10-03 16:30:29 +0000109 std::map<CallInst *, std::pair<CallInst *, CallInfo>> AIChain;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000110 // A map to hold all the base preserve_*_access_index instrinsic calls.
111 // The base call is not an input of any other preserve_*_access_index
112 // intrinsics.
Yonghong Song02ac7502019-10-03 16:30:29 +0000113 std::map<CallInst *, CallInfo> BaseAICalls;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000114
115 bool doTransformation(Module &M);
116
Yonghong Song02ac7502019-10-03 16:30:29 +0000117 void traceAICall(CallInst *Call, CallInfo &ParentInfo);
118 void traceBitCast(BitCastInst *BitCast, CallInst *Parent,
119 CallInfo &ParentInfo);
120 void traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
121 CallInfo &ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000122 void collectAICallChains(Module &M, Function &F);
123
Yonghong Song02ac7502019-10-03 16:30:29 +0000124 bool IsPreserveDIAccessIndexCall(const CallInst *Call, CallInfo &Cinfo);
Yonghong Song37d24a62019-08-02 23:16:44 +0000125 bool IsValidAIChain(const MDNode *ParentMeta, uint32_t ParentAI,
126 const MDNode *ChildMeta);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000127 bool removePreserveAccessIndexIntrinsic(Module &M);
128 void replaceWithGEP(std::vector<CallInst *> &CallList,
129 uint32_t NumOfZerosIndex, uint32_t DIIndex);
130
Yonghong Song02ac7502019-10-03 16:30:29 +0000131 Value *computeBaseAndAccessKey(CallInst *Call, CallInfo &CInfo,
132 std::string &AccessKey, MDNode *&BaseMeta);
133 uint64_t getConstant(const Value *IndexValue);
134 bool transformGEPChain(Module &M, CallInst *Call, CallInfo &CInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000135};
136} // End anonymous namespace
137
138char BPFAbstractMemberAccess::ID = 0;
139INITIALIZE_PASS(BPFAbstractMemberAccess, DEBUG_TYPE,
140 "abstracting struct/union member accessees", false, false)
141
142ModulePass *llvm::createBPFAbstractMemberAccess() {
143 return new BPFAbstractMemberAccess();
144}
145
146bool BPFAbstractMemberAccess::runOnModule(Module &M) {
147 LLVM_DEBUG(dbgs() << "********** Abstract Member Accesses **********\n");
148
149 // Bail out if no debug info.
Jordan Rosefdaa7422019-10-07 18:14:24 +0000150 if (M.debug_compile_units().empty())
Yonghong Songd3d88d02019-07-09 15:28:41 +0000151 return false;
152
153 return doTransformation(M);
154}
155
Yonghong Song37d24a62019-08-02 23:16:44 +0000156static bool SkipDIDerivedTag(unsigned Tag) {
157 if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
158 Tag != dwarf::DW_TAG_volatile_type &&
159 Tag != dwarf::DW_TAG_restrict_type &&
160 Tag != dwarf::DW_TAG_member)
161 return false;
162 return true;
163}
164
165static DIType * stripQualifiers(DIType *Ty) {
166 while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
167 if (!SkipDIDerivedTag(DTy->getTag()))
168 break;
169 Ty = DTy->getBaseType();
170 }
171 return Ty;
172}
173
174static const DIType * stripQualifiers(const DIType *Ty) {
175 while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
176 if (!SkipDIDerivedTag(DTy->getTag()))
177 break;
178 Ty = DTy->getBaseType();
179 }
180 return Ty;
181}
182
183static uint32_t calcArraySize(const DICompositeType *CTy, uint32_t StartDim) {
184 DINodeArray Elements = CTy->getElements();
185 uint32_t DimSize = 1;
186 for (uint32_t I = StartDim; I < Elements.size(); ++I) {
187 if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
188 if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
189 const DISubrange *SR = cast<DISubrange>(Element);
190 auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
191 DimSize *= CI->getSExtValue();
192 }
193 }
194
195 return DimSize;
196}
197
Yonghong Songd3d88d02019-07-09 15:28:41 +0000198/// Check whether a call is a preserve_*_access_index intrinsic call or not.
199bool BPFAbstractMemberAccess::IsPreserveDIAccessIndexCall(const CallInst *Call,
Yonghong Song02ac7502019-10-03 16:30:29 +0000200 CallInfo &CInfo) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000201 if (!Call)
202 return false;
203
204 const auto *GV = dyn_cast<GlobalValue>(Call->getCalledValue());
205 if (!GV)
206 return false;
207 if (GV->getName().startswith("llvm.preserve.array.access.index")) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000208 CInfo.Kind = BPFPreserveArrayAI;
209 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
210 if (!CInfo.Metadata)
Yonghong Song37d24a62019-08-02 23:16:44 +0000211 report_fatal_error("Missing metadata for llvm.preserve.array.access.index intrinsic");
Yonghong Song02ac7502019-10-03 16:30:29 +0000212 CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
213 CInfo.Base = Call->getArgOperand(0);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000214 return true;
215 }
216 if (GV->getName().startswith("llvm.preserve.union.access.index")) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000217 CInfo.Kind = BPFPreserveUnionAI;
218 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
219 if (!CInfo.Metadata)
Yonghong Song37d24a62019-08-02 23:16:44 +0000220 report_fatal_error("Missing metadata for llvm.preserve.union.access.index intrinsic");
Yonghong Song02ac7502019-10-03 16:30:29 +0000221 CInfo.AccessIndex = getConstant(Call->getArgOperand(1));
222 CInfo.Base = Call->getArgOperand(0);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000223 return true;
224 }
225 if (GV->getName().startswith("llvm.preserve.struct.access.index")) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000226 CInfo.Kind = BPFPreserveStructAI;
227 CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
228 if (!CInfo.Metadata)
Yonghong Song37d24a62019-08-02 23:16:44 +0000229 report_fatal_error("Missing metadata for llvm.preserve.struct.access.index intrinsic");
Yonghong Song02ac7502019-10-03 16:30:29 +0000230 CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
231 CInfo.Base = Call->getArgOperand(0);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000232 return true;
233 }
234
235 return false;
236}
237
238void BPFAbstractMemberAccess::replaceWithGEP(std::vector<CallInst *> &CallList,
239 uint32_t DimensionIndex,
240 uint32_t GEPIndex) {
241 for (auto Call : CallList) {
242 uint32_t Dimension = 1;
243 if (DimensionIndex > 0)
Yonghong Song02ac7502019-10-03 16:30:29 +0000244 Dimension = getConstant(Call->getArgOperand(DimensionIndex));
Yonghong Songd3d88d02019-07-09 15:28:41 +0000245
246 Constant *Zero =
247 ConstantInt::get(Type::getInt32Ty(Call->getParent()->getContext()), 0);
248 SmallVector<Value *, 4> IdxList;
249 for (unsigned I = 0; I < Dimension; ++I)
250 IdxList.push_back(Zero);
251 IdxList.push_back(Call->getArgOperand(GEPIndex));
252
253 auto *GEP = GetElementPtrInst::CreateInBounds(Call->getArgOperand(0),
254 IdxList, "", Call);
255 Call->replaceAllUsesWith(GEP);
256 Call->eraseFromParent();
257 }
258}
259
260bool BPFAbstractMemberAccess::removePreserveAccessIndexIntrinsic(Module &M) {
261 std::vector<CallInst *> PreserveArrayIndexCalls;
262 std::vector<CallInst *> PreserveUnionIndexCalls;
263 std::vector<CallInst *> PreserveStructIndexCalls;
264 bool Found = false;
265
266 for (Function &F : M)
267 for (auto &BB : F)
268 for (auto &I : BB) {
269 auto *Call = dyn_cast<CallInst>(&I);
Yonghong Song02ac7502019-10-03 16:30:29 +0000270 CallInfo CInfo;
271 if (!IsPreserveDIAccessIndexCall(Call, CInfo))
Yonghong Songd3d88d02019-07-09 15:28:41 +0000272 continue;
273
274 Found = true;
Yonghong Song02ac7502019-10-03 16:30:29 +0000275 if (CInfo.Kind == BPFPreserveArrayAI)
Yonghong Songd3d88d02019-07-09 15:28:41 +0000276 PreserveArrayIndexCalls.push_back(Call);
Yonghong Song02ac7502019-10-03 16:30:29 +0000277 else if (CInfo.Kind == BPFPreserveUnionAI)
Yonghong Songd3d88d02019-07-09 15:28:41 +0000278 PreserveUnionIndexCalls.push_back(Call);
279 else
280 PreserveStructIndexCalls.push_back(Call);
281 }
282
283 // do the following transformation:
284 // . addr = preserve_array_access_index(base, dimension, index)
285 // is transformed to
286 // addr = GEP(base, dimenion's zero's, index)
287 // . addr = preserve_union_access_index(base, di_index)
288 // is transformed to
289 // addr = base, i.e., all usages of "addr" are replaced by "base".
290 // . addr = preserve_struct_access_index(base, gep_index, di_index)
291 // is transformed to
292 // addr = GEP(base, 0, gep_index)
293 replaceWithGEP(PreserveArrayIndexCalls, 1, 2);
294 replaceWithGEP(PreserveStructIndexCalls, 0, 1);
295 for (auto Call : PreserveUnionIndexCalls) {
296 Call->replaceAllUsesWith(Call->getArgOperand(0));
297 Call->eraseFromParent();
298 }
299
300 return Found;
301}
302
Yonghong Song37d24a62019-08-02 23:16:44 +0000303/// Check whether the access index chain is valid. We check
304/// here because there may be type casts between two
305/// access indexes. We want to ensure memory access still valid.
306bool BPFAbstractMemberAccess::IsValidAIChain(const MDNode *ParentType,
307 uint32_t ParentAI,
308 const MDNode *ChildType) {
309 const DIType *PType = stripQualifiers(cast<DIType>(ParentType));
310 const DIType *CType = stripQualifiers(cast<DIType>(ChildType));
311
312 // Child is a derived/pointer type, which is due to type casting.
313 // Pointer type cannot be in the middle of chain.
Bill Wendlingebc2cf92019-08-06 07:27:26 +0000314 if (isa<DIDerivedType>(CType))
Yonghong Song37d24a62019-08-02 23:16:44 +0000315 return false;
316
317 // Parent is a pointer type.
318 if (const auto *PtrTy = dyn_cast<DIDerivedType>(PType)) {
319 if (PtrTy->getTag() != dwarf::DW_TAG_pointer_type)
320 return false;
321 return stripQualifiers(PtrTy->getBaseType()) == CType;
322 }
323
324 // Otherwise, struct/union/array types
325 const auto *PTy = dyn_cast<DICompositeType>(PType);
326 const auto *CTy = dyn_cast<DICompositeType>(CType);
327 assert(PTy && CTy && "ParentType or ChildType is null or not composite");
328
329 uint32_t PTyTag = PTy->getTag();
330 assert(PTyTag == dwarf::DW_TAG_array_type ||
331 PTyTag == dwarf::DW_TAG_structure_type ||
332 PTyTag == dwarf::DW_TAG_union_type);
333
334 uint32_t CTyTag = CTy->getTag();
335 assert(CTyTag == dwarf::DW_TAG_array_type ||
336 CTyTag == dwarf::DW_TAG_structure_type ||
337 CTyTag == dwarf::DW_TAG_union_type);
338
339 // Multi dimensional arrays, base element should be the same
340 if (PTyTag == dwarf::DW_TAG_array_type && PTyTag == CTyTag)
341 return PTy->getBaseType() == CTy->getBaseType();
342
343 DIType *Ty;
344 if (PTyTag == dwarf::DW_TAG_array_type)
345 Ty = PTy->getBaseType();
346 else
347 Ty = dyn_cast<DIType>(PTy->getElements()[ParentAI]);
348
349 return dyn_cast<DICompositeType>(stripQualifiers(Ty)) == CTy;
350}
351
Yonghong Song02ac7502019-10-03 16:30:29 +0000352void BPFAbstractMemberAccess::traceAICall(CallInst *Call,
353 CallInfo &ParentInfo) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000354 for (User *U : Call->users()) {
355 Instruction *Inst = dyn_cast<Instruction>(U);
356 if (!Inst)
357 continue;
358
359 if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000360 traceBitCast(BI, Call, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000361 } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000362 CallInfo ChildInfo;
363
364 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
365 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
366 ChildInfo.Metadata)) {
367 AIChain[CI] = std::make_pair(Call, ParentInfo);
368 traceAICall(CI, ChildInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000369 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000370 BaseAICalls[Call] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000371 }
372 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
373 if (GI->hasAllZeroIndices())
Yonghong Song02ac7502019-10-03 16:30:29 +0000374 traceGEP(GI, Call, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000375 else
Yonghong Song02ac7502019-10-03 16:30:29 +0000376 BaseAICalls[Call] = ParentInfo;
Yonghong Songc68ee0c2019-09-18 03:49:07 +0000377 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000378 BaseAICalls[Call] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000379 }
380 }
381}
382
383void BPFAbstractMemberAccess::traceBitCast(BitCastInst *BitCast,
Yonghong Song02ac7502019-10-03 16:30:29 +0000384 CallInst *Parent,
385 CallInfo &ParentInfo) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000386 for (User *U : BitCast->users()) {
387 Instruction *Inst = dyn_cast<Instruction>(U);
388 if (!Inst)
389 continue;
390
391 if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000392 traceBitCast(BI, Parent, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000393 } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000394 CallInfo ChildInfo;
395 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
396 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
397 ChildInfo.Metadata)) {
398 AIChain[CI] = std::make_pair(Parent, ParentInfo);
399 traceAICall(CI, ChildInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000400 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000401 BaseAICalls[Parent] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000402 }
403 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
404 if (GI->hasAllZeroIndices())
Yonghong Song02ac7502019-10-03 16:30:29 +0000405 traceGEP(GI, Parent, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000406 else
Yonghong Song02ac7502019-10-03 16:30:29 +0000407 BaseAICalls[Parent] = ParentInfo;
Yonghong Songc68ee0c2019-09-18 03:49:07 +0000408 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000409 BaseAICalls[Parent] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000410 }
411 }
412}
413
414void BPFAbstractMemberAccess::traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
Yonghong Song02ac7502019-10-03 16:30:29 +0000415 CallInfo &ParentInfo) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000416 for (User *U : GEP->users()) {
417 Instruction *Inst = dyn_cast<Instruction>(U);
418 if (!Inst)
419 continue;
420
421 if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000422 traceBitCast(BI, Parent, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000423 } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000424 CallInfo ChildInfo;
425 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
426 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
427 ChildInfo.Metadata)) {
428 AIChain[CI] = std::make_pair(Parent, ParentInfo);
429 traceAICall(CI, ChildInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000430 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000431 BaseAICalls[Parent] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000432 }
433 } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
434 if (GI->hasAllZeroIndices())
Yonghong Song02ac7502019-10-03 16:30:29 +0000435 traceGEP(GI, Parent, ParentInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000436 else
Yonghong Song02ac7502019-10-03 16:30:29 +0000437 BaseAICalls[Parent] = ParentInfo;
Yonghong Songc68ee0c2019-09-18 03:49:07 +0000438 } else {
Yonghong Song02ac7502019-10-03 16:30:29 +0000439 BaseAICalls[Parent] = ParentInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000440 }
441 }
442}
443
444void BPFAbstractMemberAccess::collectAICallChains(Module &M, Function &F) {
445 AIChain.clear();
446 BaseAICalls.clear();
447
448 for (auto &BB : F)
449 for (auto &I : BB) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000450 CallInfo CInfo;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000451 auto *Call = dyn_cast<CallInst>(&I);
Yonghong Song02ac7502019-10-03 16:30:29 +0000452 if (!IsPreserveDIAccessIndexCall(Call, CInfo) ||
Yonghong Songd3d88d02019-07-09 15:28:41 +0000453 AIChain.find(Call) != AIChain.end())
454 continue;
455
Yonghong Song02ac7502019-10-03 16:30:29 +0000456 traceAICall(Call, CInfo);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000457 }
458}
459
Yonghong Song02ac7502019-10-03 16:30:29 +0000460uint64_t BPFAbstractMemberAccess::getConstant(const Value *IndexValue) {
Yonghong Songd3d88d02019-07-09 15:28:41 +0000461 const ConstantInt *CV = dyn_cast<ConstantInt>(IndexValue);
Yonghong Song02ac7502019-10-03 16:30:29 +0000462 assert(CV);
463 return CV->getValue().getZExtValue();
Yonghong Songd3d88d02019-07-09 15:28:41 +0000464}
465
466/// Compute the base of the whole preserve_*_access_index chains, i.e., the base
467/// pointer of the first preserve_*_access_index call, and construct the access
468/// string, which will be the name of a global variable.
Yonghong Songd8efec92019-07-25 16:01:26 +0000469Value *BPFAbstractMemberAccess::computeBaseAndAccessKey(CallInst *Call,
Yonghong Song02ac7502019-10-03 16:30:29 +0000470 CallInfo &CInfo,
Yonghong Songd3d88d02019-07-09 15:28:41 +0000471 std::string &AccessKey,
Yonghong Songd3d88d02019-07-09 15:28:41 +0000472 MDNode *&TypeMeta) {
473 Value *Base = nullptr;
Yonghong Song37d24a62019-08-02 23:16:44 +0000474 std::string TypeName;
Yonghong Song02ac7502019-10-03 16:30:29 +0000475 std::stack<std::pair<CallInst *, CallInfo>> CallStack;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000476
Yonghong Song37d24a62019-08-02 23:16:44 +0000477 // Put the access chain into a stack with the top as the head of the chain.
Yonghong Songd3d88d02019-07-09 15:28:41 +0000478 while (Call) {
Yonghong Song02ac7502019-10-03 16:30:29 +0000479 CallStack.push(std::make_pair(Call, CInfo));
480 CInfo = AIChain[Call].second;
Yonghong Song37d24a62019-08-02 23:16:44 +0000481 Call = AIChain[Call].first;
482 }
Yonghong Songd3d88d02019-07-09 15:28:41 +0000483
Yonghong Song37d24a62019-08-02 23:16:44 +0000484 // The access offset from the base of the head of chain is also
485 // calculated here as all debuginfo types are available.
486
487 // Get type name and calculate the first index.
488 // We only want to get type name from structure or union.
489 // If user wants a relocation like
490 // int *p; ... __builtin_preserve_access_index(&p[4]) ...
491 // or
492 // int a[10][20]; ... __builtin_preserve_access_index(&a[2][3]) ...
493 // we will skip them.
494 uint32_t FirstIndex = 0;
495 uint32_t AccessOffset = 0;
496 while (CallStack.size()) {
497 auto StackElem = CallStack.top();
498 Call = StackElem.first;
Yonghong Song02ac7502019-10-03 16:30:29 +0000499 CInfo = StackElem.second;
Yonghong Song37d24a62019-08-02 23:16:44 +0000500
501 if (!Base)
Yonghong Song02ac7502019-10-03 16:30:29 +0000502 Base = CInfo.Base;
Yonghong Song37d24a62019-08-02 23:16:44 +0000503
Yonghong Song02ac7502019-10-03 16:30:29 +0000504 DIType *Ty = stripQualifiers(cast<DIType>(CInfo.Metadata));
505 if (CInfo.Kind == BPFPreserveUnionAI ||
506 CInfo.Kind == BPFPreserveStructAI) {
Yonghong Song37d24a62019-08-02 23:16:44 +0000507 // struct or union type
Yonghong Songd3d88d02019-07-09 15:28:41 +0000508 TypeName = Ty->getName();
Yonghong Song37d24a62019-08-02 23:16:44 +0000509 TypeMeta = Ty;
510 AccessOffset += FirstIndex * Ty->getSizeInBits() >> 3;
511 break;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000512 }
513
Yonghong Song37d24a62019-08-02 23:16:44 +0000514 // Array entries will always be consumed for accumulative initial index.
515 CallStack.pop();
516
517 // BPFPreserveArrayAI
Yonghong Song02ac7502019-10-03 16:30:29 +0000518 uint64_t AccessIndex = CInfo.AccessIndex;
Yonghong Song37d24a62019-08-02 23:16:44 +0000519
520 DIType *BaseTy = nullptr;
521 bool CheckElemType = false;
522 if (const auto *CTy = dyn_cast<DICompositeType>(Ty)) {
523 // array type
524 assert(CTy->getTag() == dwarf::DW_TAG_array_type);
525
526
527 FirstIndex += AccessIndex * calcArraySize(CTy, 1);
528 BaseTy = stripQualifiers(CTy->getBaseType());
529 CheckElemType = CTy->getElements().size() == 1;
530 } else {
531 // pointer type
532 auto *DTy = cast<DIDerivedType>(Ty);
533 assert(DTy->getTag() == dwarf::DW_TAG_pointer_type);
534
535 BaseTy = stripQualifiers(DTy->getBaseType());
536 CTy = dyn_cast<DICompositeType>(BaseTy);
537 if (!CTy) {
538 CheckElemType = true;
539 } else if (CTy->getTag() != dwarf::DW_TAG_array_type) {
540 FirstIndex += AccessIndex;
541 CheckElemType = true;
542 } else {
543 FirstIndex += AccessIndex * calcArraySize(CTy, 0);
544 }
545 }
546
547 if (CheckElemType) {
548 auto *CTy = dyn_cast<DICompositeType>(BaseTy);
549 if (!CTy)
550 return nullptr;
551
552 unsigned CTag = CTy->getTag();
553 if (CTag != dwarf::DW_TAG_structure_type && CTag != dwarf::DW_TAG_union_type)
554 return nullptr;
555 else
556 TypeName = CTy->getName();
557 TypeMeta = CTy;
558 AccessOffset += FirstIndex * CTy->getSizeInBits() >> 3;
559 break;
560 }
561 }
562 assert(TypeName.size());
563 AccessKey += std::to_string(FirstIndex);
564
565 // Traverse the rest of access chain to complete offset calculation
566 // and access key construction.
567 while (CallStack.size()) {
568 auto StackElem = CallStack.top();
Yonghong Song02ac7502019-10-03 16:30:29 +0000569 CInfo = StackElem.second;
Yonghong Song37d24a62019-08-02 23:16:44 +0000570 CallStack.pop();
571
Yonghong Songd3d88d02019-07-09 15:28:41 +0000572 // Access Index
Yonghong Song02ac7502019-10-03 16:30:29 +0000573 uint64_t AccessIndex = CInfo.AccessIndex;
Yonghong Song37d24a62019-08-02 23:16:44 +0000574 AccessKey += ":" + std::to_string(AccessIndex);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000575
Yonghong Song02ac7502019-10-03 16:30:29 +0000576 MDNode *MDN = CInfo.Metadata;
Yonghong Song37d24a62019-08-02 23:16:44 +0000577 // At this stage, it cannot be pointer type.
578 auto *CTy = cast<DICompositeType>(stripQualifiers(cast<DIType>(MDN)));
579 uint32_t Tag = CTy->getTag();
580 if (Tag == dwarf::DW_TAG_structure_type) {
581 auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
582 AccessOffset += MemberTy->getOffsetInBits() >> 3;
583 } else if (Tag == dwarf::DW_TAG_array_type) {
584 auto *EltTy = stripQualifiers(CTy->getBaseType());
585 AccessOffset += AccessIndex * calcArraySize(CTy, 1) *
586 EltTy->getSizeInBits() >> 3;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000587 }
Yonghong Songd3d88d02019-07-09 15:28:41 +0000588 }
589
Yonghong Songd3d88d02019-07-09 15:28:41 +0000590 // Access key is the type name + access string, uniquely identifying
591 // one kernel memory access.
Yonghong Song37d24a62019-08-02 23:16:44 +0000592 AccessKey = TypeName + ":" + std::to_string(AccessOffset) + "$" + AccessKey;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000593
594 return Base;
595}
596
597/// Call/Kind is the base preserve_*_access_index() call. Attempts to do
598/// transformation to a chain of relocable GEPs.
599bool BPFAbstractMemberAccess::transformGEPChain(Module &M, CallInst *Call,
Yonghong Song02ac7502019-10-03 16:30:29 +0000600 CallInfo &CInfo) {
Yonghong Songd8efec92019-07-25 16:01:26 +0000601 std::string AccessKey;
Yonghong Song37d24a62019-08-02 23:16:44 +0000602 MDNode *TypeMeta;
Yonghong Songd3d88d02019-07-09 15:28:41 +0000603 Value *Base =
Yonghong Song02ac7502019-10-03 16:30:29 +0000604 computeBaseAndAccessKey(Call, CInfo, AccessKey, TypeMeta);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000605 if (!Base)
606 return false;
607
608 // Do the transformation
609 // For any original GEP Call and Base %2 like
610 // %4 = bitcast %struct.net_device** %dev1 to i64*
611 // it is transformed to:
Yonghong Song37d24a62019-08-02 23:16:44 +0000612 // %6 = load sk_buff:50:$0:0:0:2:0
Yonghong Songd3d88d02019-07-09 15:28:41 +0000613 // %7 = bitcast %struct.sk_buff* %2 to i8*
614 // %8 = getelementptr i8, i8* %7, %6
615 // %9 = bitcast i8* %8 to i64*
616 // using %9 instead of %4
617 // The original Call inst is removed.
618 BasicBlock *BB = Call->getParent();
619 GlobalVariable *GV;
620
621 if (GEPGlobals.find(AccessKey) == GEPGlobals.end()) {
622 GV = new GlobalVariable(M, Type::getInt64Ty(BB->getContext()), false,
Yonghong Songd8efec92019-07-25 16:01:26 +0000623 GlobalVariable::ExternalLinkage, NULL, AccessKey);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000624 GV->addAttribute(BPFCoreSharedInfo::AmaAttr);
Yonghong Song37d24a62019-08-02 23:16:44 +0000625 GV->setMetadata(LLVMContext::MD_preserve_access_index, TypeMeta);
Yonghong Songd3d88d02019-07-09 15:28:41 +0000626 GEPGlobals[AccessKey] = GV;
627 } else {
628 GV = GEPGlobals[AccessKey];
629 }
630
631 // Load the global variable.
632 auto *LDInst = new LoadInst(Type::getInt64Ty(BB->getContext()), GV);
633 BB->getInstList().insert(Call->getIterator(), LDInst);
634
635 // Generate a BitCast
636 auto *BCInst = new BitCastInst(Base, Type::getInt8PtrTy(BB->getContext()));
637 BB->getInstList().insert(Call->getIterator(), BCInst);
638
639 // Generate a GetElementPtr
640 auto *GEP = GetElementPtrInst::Create(Type::getInt8Ty(BB->getContext()),
641 BCInst, LDInst);
642 BB->getInstList().insert(Call->getIterator(), GEP);
643
644 // Generate a BitCast
645 auto *BCInst2 = new BitCastInst(GEP, Call->getType());
646 BB->getInstList().insert(Call->getIterator(), BCInst2);
647
648 Call->replaceAllUsesWith(BCInst2);
649 Call->eraseFromParent();
650
651 return true;
652}
653
654bool BPFAbstractMemberAccess::doTransformation(Module &M) {
655 bool Transformed = false;
656
657 for (Function &F : M) {
658 // Collect PreserveDIAccessIndex Intrinsic call chains.
659 // The call chains will be used to generate the access
660 // patterns similar to GEP.
661 collectAICallChains(M, F);
662
663 for (auto &C : BaseAICalls)
664 Transformed = transformGEPChain(M, C.first, C.second) || Transformed;
665 }
666
667 return removePreserveAccessIndexIntrinsic(M) || Transformed;
668}