1 //===------ 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 // 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 //
75 //===----------------------------------------------------------------------===//
76 
77 #include "BPF.h"
78 #include "BPFCORE.h"
79 #include "BPFTargetMachine.h"
80 #include "llvm/BinaryFormat/Dwarf.h"
81 #include "llvm/IR/DebugInfoMetadata.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicsBPF.h"
86 #include "llvm/IR/Module.h"
87 #include "llvm/IR/PassManager.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/Pass.h"
92 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
93 #include <stack>
94 
95 #define DEBUG_TYPE "bpf-abstract-member-access"
96 
97 namespace llvm {
98 constexpr StringRef BPFCoreSharedInfo::AmaAttr;
99 uint32_t BPFCoreSharedInfo::SeqNum;
100 
101 Instruction *BPFCoreSharedInfo::insertPassThrough(Module *M, BasicBlock *BB,
102                                                   Instruction *Input,
103                                                   Instruction *Before) {
104   Function *Fn = Intrinsic::getDeclaration(
105       M, Intrinsic::bpf_passthrough, {Input->getType(), Input->getType()});
106   Constant *SeqNumVal = ConstantInt::get(Type::getInt32Ty(BB->getContext()),
107                                          BPFCoreSharedInfo::SeqNum++);
108 
109   auto *NewInst = CallInst::Create(Fn, {SeqNumVal, Input});
110   BB->getInstList().insert(Before->getIterator(), NewInst);
111   return NewInst;
112 }
113 } // namespace llvm
114 
115 using namespace llvm;
116 
117 namespace {
118 class BPFAbstractMemberAccess final {
119 public:
120   BPFAbstractMemberAccess(BPFTargetMachine *TM) : TM(TM) {}
121 
122   bool run(Function &F);
123 
124   struct CallInfo {
125     uint32_t Kind;
126     uint32_t AccessIndex;
127     Align RecordAlignment;
128     MDNode *Metadata;
129     Value *Base;
130   };
131   typedef std::stack<std::pair<CallInst *, CallInfo>> CallInfoStack;
132 
133 private:
134   enum : uint32_t {
135     BPFPreserveArrayAI = 1,
136     BPFPreserveUnionAI = 2,
137     BPFPreserveStructAI = 3,
138     BPFPreserveFieldInfoAI = 4,
139   };
140 
141   TargetMachine *TM;
142   const DataLayout *DL = nullptr;
143   Module *M = nullptr;
144 
145   static std::map<std::string, GlobalVariable *> GEPGlobals;
146   // A map to link preserve_*_access_index instrinsic calls.
147   std::map<CallInst *, std::pair<CallInst *, CallInfo>> AIChain;
148   // A map to hold all the base preserve_*_access_index instrinsic calls.
149   // The base call is not an input of any other preserve_*
150   // intrinsics.
151   std::map<CallInst *, CallInfo> BaseAICalls;
152 
153   bool doTransformation(Function &F);
154 
155   void traceAICall(CallInst *Call, CallInfo &ParentInfo);
156   void traceBitCast(BitCastInst *BitCast, CallInst *Parent,
157                     CallInfo &ParentInfo);
158   void traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
159                 CallInfo &ParentInfo);
160   void collectAICallChains(Function &F);
161 
162   bool IsPreserveDIAccessIndexCall(const CallInst *Call, CallInfo &Cinfo);
163   bool IsValidAIChain(const MDNode *ParentMeta, uint32_t ParentAI,
164                       const MDNode *ChildMeta);
165   bool removePreserveAccessIndexIntrinsic(Function &F);
166   void replaceWithGEP(std::vector<CallInst *> &CallList,
167                       uint32_t NumOfZerosIndex, uint32_t DIIndex);
168   bool HasPreserveFieldInfoCall(CallInfoStack &CallStack);
169   void GetStorageBitRange(DIDerivedType *MemberTy, Align RecordAlignment,
170                           uint32_t &StartBitOffset, uint32_t &EndBitOffset);
171   uint32_t GetFieldInfo(uint32_t InfoKind, DICompositeType *CTy,
172                         uint32_t AccessIndex, uint32_t PatchImm,
173                         Align RecordAlignment);
174 
175   Value *computeBaseAndAccessKey(CallInst *Call, CallInfo &CInfo,
176                                  std::string &AccessKey, MDNode *&BaseMeta);
177   MDNode *computeAccessKey(CallInst *Call, CallInfo &CInfo,
178                            std::string &AccessKey, bool &IsInt32Ret);
179   uint64_t getConstant(const Value *IndexValue);
180   bool transformGEPChain(CallInst *Call, CallInfo &CInfo);
181 };
182 
183 std::map<std::string, GlobalVariable *> BPFAbstractMemberAccess::GEPGlobals;
184 
185 class BPFAbstractMemberAccessLegacyPass final : public FunctionPass {
186   BPFTargetMachine *TM;
187 
188   bool runOnFunction(Function &F) override {
189     return BPFAbstractMemberAccess(TM).run(F);
190   }
191 
192 public:
193   static char ID;
194 
195   // Add optional BPFTargetMachine parameter so that BPF backend can add the
196   // phase with target machine to find out the endianness. The default
197   // constructor (without parameters) is used by the pass manager for managing
198   // purposes.
199   BPFAbstractMemberAccessLegacyPass(BPFTargetMachine *TM = nullptr)
200       : FunctionPass(ID), TM(TM) {}
201 };
202 
203 } // End anonymous namespace
204 
205 char BPFAbstractMemberAccessLegacyPass::ID = 0;
206 INITIALIZE_PASS(BPFAbstractMemberAccessLegacyPass, DEBUG_TYPE,
207                 "BPF Abstract Member Access", false, false)
208 
209 FunctionPass *llvm::createBPFAbstractMemberAccess(BPFTargetMachine *TM) {
210   return new BPFAbstractMemberAccessLegacyPass(TM);
211 }
212 
213 bool BPFAbstractMemberAccess::run(Function &F) {
214   LLVM_DEBUG(dbgs() << "********** Abstract Member Accesses **********\n");
215 
216   M = F.getParent();
217   if (!M)
218     return false;
219 
220   // Bail out if no debug info.
221   if (M->debug_compile_units().empty())
222     return false;
223 
224   DL = &M->getDataLayout();
225   return doTransformation(F);
226 }
227 
228 static bool SkipDIDerivedTag(unsigned Tag, bool skipTypedef) {
229   if (Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type &&
230       Tag != dwarf::DW_TAG_volatile_type &&
231       Tag != dwarf::DW_TAG_restrict_type &&
232       Tag != dwarf::DW_TAG_member)
233     return false;
234   if (Tag == dwarf::DW_TAG_typedef && !skipTypedef)
235     return false;
236   return true;
237 }
238 
239 static DIType * stripQualifiers(DIType *Ty, bool skipTypedef = true) {
240   while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
241     if (!SkipDIDerivedTag(DTy->getTag(), skipTypedef))
242       break;
243     Ty = DTy->getBaseType();
244   }
245   return Ty;
246 }
247 
248 static const DIType * stripQualifiers(const DIType *Ty) {
249   while (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
250     if (!SkipDIDerivedTag(DTy->getTag(), true))
251       break;
252     Ty = DTy->getBaseType();
253   }
254   return Ty;
255 }
256 
257 static uint32_t calcArraySize(const DICompositeType *CTy, uint32_t StartDim) {
258   DINodeArray Elements = CTy->getElements();
259   uint32_t DimSize = 1;
260   for (uint32_t I = StartDim; I < Elements.size(); ++I) {
261     if (auto *Element = dyn_cast_or_null<DINode>(Elements[I]))
262       if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
263         const DISubrange *SR = cast<DISubrange>(Element);
264         auto *CI = SR->getCount().dyn_cast<ConstantInt *>();
265         DimSize *= CI->getSExtValue();
266       }
267   }
268 
269   return DimSize;
270 }
271 
272 static Type *getBaseElementType(const CallInst *Call) {
273   // Element type is stored in an elementtype() attribute on the first param.
274   return Call->getParamElementType(0);
275 }
276 
277 /// Check whether a call is a preserve_*_access_index intrinsic call or not.
278 bool BPFAbstractMemberAccess::IsPreserveDIAccessIndexCall(const CallInst *Call,
279                                                           CallInfo &CInfo) {
280   if (!Call)
281     return false;
282 
283   const auto *GV = dyn_cast<GlobalValue>(Call->getCalledOperand());
284   if (!GV)
285     return false;
286   if (GV->getName().startswith("llvm.preserve.array.access.index")) {
287     CInfo.Kind = BPFPreserveArrayAI;
288     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
289     if (!CInfo.Metadata)
290       report_fatal_error("Missing metadata for llvm.preserve.array.access.index intrinsic");
291     CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
292     CInfo.Base = Call->getArgOperand(0);
293     CInfo.RecordAlignment = DL->getABITypeAlign(getBaseElementType(Call));
294     return true;
295   }
296   if (GV->getName().startswith("llvm.preserve.union.access.index")) {
297     CInfo.Kind = BPFPreserveUnionAI;
298     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
299     if (!CInfo.Metadata)
300       report_fatal_error("Missing metadata for llvm.preserve.union.access.index intrinsic");
301     CInfo.AccessIndex = getConstant(Call->getArgOperand(1));
302     CInfo.Base = Call->getArgOperand(0);
303     CInfo.RecordAlignment =
304         DL->getABITypeAlign(CInfo.Base->getType()->getPointerElementType());
305     return true;
306   }
307   if (GV->getName().startswith("llvm.preserve.struct.access.index")) {
308     CInfo.Kind = BPFPreserveStructAI;
309     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
310     if (!CInfo.Metadata)
311       report_fatal_error("Missing metadata for llvm.preserve.struct.access.index intrinsic");
312     CInfo.AccessIndex = getConstant(Call->getArgOperand(2));
313     CInfo.Base = Call->getArgOperand(0);
314     CInfo.RecordAlignment = DL->getABITypeAlign(getBaseElementType(Call));
315     return true;
316   }
317   if (GV->getName().startswith("llvm.bpf.preserve.field.info")) {
318     CInfo.Kind = BPFPreserveFieldInfoAI;
319     CInfo.Metadata = nullptr;
320     // Check validity of info_kind as clang did not check this.
321     uint64_t InfoKind = getConstant(Call->getArgOperand(1));
322     if (InfoKind >= BPFCoreSharedInfo::MAX_FIELD_RELOC_KIND)
323       report_fatal_error("Incorrect info_kind for llvm.bpf.preserve.field.info intrinsic");
324     CInfo.AccessIndex = InfoKind;
325     return true;
326   }
327   if (GV->getName().startswith("llvm.bpf.preserve.type.info")) {
328     CInfo.Kind = BPFPreserveFieldInfoAI;
329     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
330     if (!CInfo.Metadata)
331       report_fatal_error("Missing metadata for llvm.preserve.type.info intrinsic");
332     uint64_t Flag = getConstant(Call->getArgOperand(1));
333     if (Flag >= BPFCoreSharedInfo::MAX_PRESERVE_TYPE_INFO_FLAG)
334       report_fatal_error("Incorrect flag for llvm.bpf.preserve.type.info intrinsic");
335     if (Flag == BPFCoreSharedInfo::PRESERVE_TYPE_INFO_EXISTENCE)
336       CInfo.AccessIndex = BPFCoreSharedInfo::TYPE_EXISTENCE;
337     else
338       CInfo.AccessIndex = BPFCoreSharedInfo::TYPE_SIZE;
339     return true;
340   }
341   if (GV->getName().startswith("llvm.bpf.preserve.enum.value")) {
342     CInfo.Kind = BPFPreserveFieldInfoAI;
343     CInfo.Metadata = Call->getMetadata(LLVMContext::MD_preserve_access_index);
344     if (!CInfo.Metadata)
345       report_fatal_error("Missing metadata for llvm.preserve.enum.value intrinsic");
346     uint64_t Flag = getConstant(Call->getArgOperand(2));
347     if (Flag >= BPFCoreSharedInfo::MAX_PRESERVE_ENUM_VALUE_FLAG)
348       report_fatal_error("Incorrect flag for llvm.bpf.preserve.enum.value intrinsic");
349     if (Flag == BPFCoreSharedInfo::PRESERVE_ENUM_VALUE_EXISTENCE)
350       CInfo.AccessIndex = BPFCoreSharedInfo::ENUM_VALUE_EXISTENCE;
351     else
352       CInfo.AccessIndex = BPFCoreSharedInfo::ENUM_VALUE;
353     return true;
354   }
355 
356   return false;
357 }
358 
359 void BPFAbstractMemberAccess::replaceWithGEP(std::vector<CallInst *> &CallList,
360                                              uint32_t DimensionIndex,
361                                              uint32_t GEPIndex) {
362   for (auto Call : CallList) {
363     uint32_t Dimension = 1;
364     if (DimensionIndex > 0)
365       Dimension = getConstant(Call->getArgOperand(DimensionIndex));
366 
367     Constant *Zero =
368         ConstantInt::get(Type::getInt32Ty(Call->getParent()->getContext()), 0);
369     SmallVector<Value *, 4> IdxList;
370     for (unsigned I = 0; I < Dimension; ++I)
371       IdxList.push_back(Zero);
372     IdxList.push_back(Call->getArgOperand(GEPIndex));
373 
374     auto *GEP = GetElementPtrInst::CreateInBounds(
375         getBaseElementType(Call), Call->getArgOperand(0), IdxList, "", Call);
376     Call->replaceAllUsesWith(GEP);
377     Call->eraseFromParent();
378   }
379 }
380 
381 bool BPFAbstractMemberAccess::removePreserveAccessIndexIntrinsic(Function &F) {
382   std::vector<CallInst *> PreserveArrayIndexCalls;
383   std::vector<CallInst *> PreserveUnionIndexCalls;
384   std::vector<CallInst *> PreserveStructIndexCalls;
385   bool Found = false;
386 
387   for (auto &BB : F)
388     for (auto &I : BB) {
389       auto *Call = dyn_cast<CallInst>(&I);
390       CallInfo CInfo;
391       if (!IsPreserveDIAccessIndexCall(Call, CInfo))
392         continue;
393 
394       Found = true;
395       if (CInfo.Kind == BPFPreserveArrayAI)
396         PreserveArrayIndexCalls.push_back(Call);
397       else if (CInfo.Kind == BPFPreserveUnionAI)
398         PreserveUnionIndexCalls.push_back(Call);
399       else
400         PreserveStructIndexCalls.push_back(Call);
401     }
402 
403   // do the following transformation:
404   // . addr = preserve_array_access_index(base, dimension, index)
405   //   is transformed to
406   //     addr = GEP(base, dimenion's zero's, index)
407   // . addr = preserve_union_access_index(base, di_index)
408   //   is transformed to
409   //     addr = base, i.e., all usages of "addr" are replaced by "base".
410   // . addr = preserve_struct_access_index(base, gep_index, di_index)
411   //   is transformed to
412   //     addr = GEP(base, 0, gep_index)
413   replaceWithGEP(PreserveArrayIndexCalls, 1, 2);
414   replaceWithGEP(PreserveStructIndexCalls, 0, 1);
415   for (auto Call : PreserveUnionIndexCalls) {
416     Call->replaceAllUsesWith(Call->getArgOperand(0));
417     Call->eraseFromParent();
418   }
419 
420   return Found;
421 }
422 
423 /// Check whether the access index chain is valid. We check
424 /// here because there may be type casts between two
425 /// access indexes. We want to ensure memory access still valid.
426 bool BPFAbstractMemberAccess::IsValidAIChain(const MDNode *ParentType,
427                                              uint32_t ParentAI,
428                                              const MDNode *ChildType) {
429   if (!ChildType)
430     return true; // preserve_field_info, no type comparison needed.
431 
432   const DIType *PType = stripQualifiers(cast<DIType>(ParentType));
433   const DIType *CType = stripQualifiers(cast<DIType>(ChildType));
434 
435   // Child is a derived/pointer type, which is due to type casting.
436   // Pointer type cannot be in the middle of chain.
437   if (isa<DIDerivedType>(CType))
438     return false;
439 
440   // Parent is a pointer type.
441   if (const auto *PtrTy = dyn_cast<DIDerivedType>(PType)) {
442     if (PtrTy->getTag() != dwarf::DW_TAG_pointer_type)
443       return false;
444     return stripQualifiers(PtrTy->getBaseType()) == CType;
445   }
446 
447   // Otherwise, struct/union/array types
448   const auto *PTy = dyn_cast<DICompositeType>(PType);
449   const auto *CTy = dyn_cast<DICompositeType>(CType);
450   assert(PTy && CTy && "ParentType or ChildType is null or not composite");
451 
452   uint32_t PTyTag = PTy->getTag();
453   assert(PTyTag == dwarf::DW_TAG_array_type ||
454          PTyTag == dwarf::DW_TAG_structure_type ||
455          PTyTag == dwarf::DW_TAG_union_type);
456 
457   uint32_t CTyTag = CTy->getTag();
458   assert(CTyTag == dwarf::DW_TAG_array_type ||
459          CTyTag == dwarf::DW_TAG_structure_type ||
460          CTyTag == dwarf::DW_TAG_union_type);
461 
462   // Multi dimensional arrays, base element should be the same
463   if (PTyTag == dwarf::DW_TAG_array_type && PTyTag == CTyTag)
464     return PTy->getBaseType() == CTy->getBaseType();
465 
466   DIType *Ty;
467   if (PTyTag == dwarf::DW_TAG_array_type)
468     Ty = PTy->getBaseType();
469   else
470     Ty = dyn_cast<DIType>(PTy->getElements()[ParentAI]);
471 
472   return dyn_cast<DICompositeType>(stripQualifiers(Ty)) == CTy;
473 }
474 
475 void BPFAbstractMemberAccess::traceAICall(CallInst *Call,
476                                           CallInfo &ParentInfo) {
477   for (User *U : Call->users()) {
478     Instruction *Inst = dyn_cast<Instruction>(U);
479     if (!Inst)
480       continue;
481 
482     if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
483       traceBitCast(BI, Call, ParentInfo);
484     } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
485       CallInfo ChildInfo;
486 
487       if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
488           IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
489                          ChildInfo.Metadata)) {
490         AIChain[CI] = std::make_pair(Call, ParentInfo);
491         traceAICall(CI, ChildInfo);
492       } else {
493         BaseAICalls[Call] = ParentInfo;
494       }
495     } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
496       if (GI->hasAllZeroIndices())
497         traceGEP(GI, Call, ParentInfo);
498       else
499         BaseAICalls[Call] = ParentInfo;
500     } else {
501       BaseAICalls[Call] = ParentInfo;
502     }
503   }
504 }
505 
506 void BPFAbstractMemberAccess::traceBitCast(BitCastInst *BitCast,
507                                            CallInst *Parent,
508                                            CallInfo &ParentInfo) {
509   for (User *U : BitCast->users()) {
510     Instruction *Inst = dyn_cast<Instruction>(U);
511     if (!Inst)
512       continue;
513 
514     if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
515       traceBitCast(BI, Parent, ParentInfo);
516     } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
517       CallInfo ChildInfo;
518       if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
519           IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
520                          ChildInfo.Metadata)) {
521         AIChain[CI] = std::make_pair(Parent, ParentInfo);
522         traceAICall(CI, ChildInfo);
523       } else {
524         BaseAICalls[Parent] = ParentInfo;
525       }
526     } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
527       if (GI->hasAllZeroIndices())
528         traceGEP(GI, Parent, ParentInfo);
529       else
530         BaseAICalls[Parent] = ParentInfo;
531     } else {
532       BaseAICalls[Parent] = ParentInfo;
533     }
534   }
535 }
536 
537 void BPFAbstractMemberAccess::traceGEP(GetElementPtrInst *GEP, CallInst *Parent,
538                                        CallInfo &ParentInfo) {
539   for (User *U : GEP->users()) {
540     Instruction *Inst = dyn_cast<Instruction>(U);
541     if (!Inst)
542       continue;
543 
544     if (auto *BI = dyn_cast<BitCastInst>(Inst)) {
545       traceBitCast(BI, Parent, ParentInfo);
546     } else if (auto *CI = dyn_cast<CallInst>(Inst)) {
547       CallInfo ChildInfo;
548       if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
549           IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
550                          ChildInfo.Metadata)) {
551         AIChain[CI] = std::make_pair(Parent, ParentInfo);
552         traceAICall(CI, ChildInfo);
553       } else {
554         BaseAICalls[Parent] = ParentInfo;
555       }
556     } else if (auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
557       if (GI->hasAllZeroIndices())
558         traceGEP(GI, Parent, ParentInfo);
559       else
560         BaseAICalls[Parent] = ParentInfo;
561     } else {
562       BaseAICalls[Parent] = ParentInfo;
563     }
564   }
565 }
566 
567 void BPFAbstractMemberAccess::collectAICallChains(Function &F) {
568   AIChain.clear();
569   BaseAICalls.clear();
570 
571   for (auto &BB : F)
572     for (auto &I : BB) {
573       CallInfo CInfo;
574       auto *Call = dyn_cast<CallInst>(&I);
575       if (!IsPreserveDIAccessIndexCall(Call, CInfo) ||
576           AIChain.find(Call) != AIChain.end())
577         continue;
578 
579       traceAICall(Call, CInfo);
580     }
581 }
582 
583 uint64_t BPFAbstractMemberAccess::getConstant(const Value *IndexValue) {
584   const ConstantInt *CV = dyn_cast<ConstantInt>(IndexValue);
585   assert(CV);
586   return CV->getValue().getZExtValue();
587 }
588 
589 /// Get the start and the end of storage offset for \p MemberTy.
590 void BPFAbstractMemberAccess::GetStorageBitRange(DIDerivedType *MemberTy,
591                                                  Align RecordAlignment,
592                                                  uint32_t &StartBitOffset,
593                                                  uint32_t &EndBitOffset) {
594   uint32_t MemberBitSize = MemberTy->getSizeInBits();
595   uint32_t MemberBitOffset = MemberTy->getOffsetInBits();
596 
597   if (RecordAlignment > 8) {
598     // If the Bits are within an aligned 8-byte, set the RecordAlignment
599     // to 8, other report the fatal error.
600     if (MemberBitOffset / 64 != (MemberBitOffset + MemberBitSize) / 64)
601       report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
602                          "requiring too big alignment");
603     RecordAlignment = Align(8);
604   }
605 
606   uint32_t AlignBits = RecordAlignment.value() * 8;
607   if (MemberBitSize > AlignBits)
608     report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
609                        "bitfield size greater than record alignment");
610 
611   StartBitOffset = MemberBitOffset & ~(AlignBits - 1);
612   if ((StartBitOffset + AlignBits) < (MemberBitOffset + MemberBitSize))
613     report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info, "
614                        "cross alignment boundary");
615   EndBitOffset = StartBitOffset + AlignBits;
616 }
617 
618 uint32_t BPFAbstractMemberAccess::GetFieldInfo(uint32_t InfoKind,
619                                                DICompositeType *CTy,
620                                                uint32_t AccessIndex,
621                                                uint32_t PatchImm,
622                                                Align RecordAlignment) {
623   if (InfoKind == BPFCoreSharedInfo::FIELD_EXISTENCE)
624       return 1;
625 
626   uint32_t Tag = CTy->getTag();
627   if (InfoKind == BPFCoreSharedInfo::FIELD_BYTE_OFFSET) {
628     if (Tag == dwarf::DW_TAG_array_type) {
629       auto *EltTy = stripQualifiers(CTy->getBaseType());
630       PatchImm += AccessIndex * calcArraySize(CTy, 1) *
631                   (EltTy->getSizeInBits() >> 3);
632     } else if (Tag == dwarf::DW_TAG_structure_type) {
633       auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
634       if (!MemberTy->isBitField()) {
635         PatchImm += MemberTy->getOffsetInBits() >> 3;
636       } else {
637         unsigned SBitOffset, NextSBitOffset;
638         GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset,
639                            NextSBitOffset);
640         PatchImm += SBitOffset >> 3;
641       }
642     }
643     return PatchImm;
644   }
645 
646   if (InfoKind == BPFCoreSharedInfo::FIELD_BYTE_SIZE) {
647     if (Tag == dwarf::DW_TAG_array_type) {
648       auto *EltTy = stripQualifiers(CTy->getBaseType());
649       return calcArraySize(CTy, 1) * (EltTy->getSizeInBits() >> 3);
650     } else {
651       auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
652       uint32_t SizeInBits = MemberTy->getSizeInBits();
653       if (!MemberTy->isBitField())
654         return SizeInBits >> 3;
655 
656       unsigned SBitOffset, NextSBitOffset;
657       GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
658       SizeInBits = NextSBitOffset - SBitOffset;
659       if (SizeInBits & (SizeInBits - 1))
660         report_fatal_error("Unsupported field expression for llvm.bpf.preserve.field.info");
661       return SizeInBits >> 3;
662     }
663   }
664 
665   if (InfoKind == BPFCoreSharedInfo::FIELD_SIGNEDNESS) {
666     const DIType *BaseTy;
667     if (Tag == dwarf::DW_TAG_array_type) {
668       // Signedness only checked when final array elements are accessed.
669       if (CTy->getElements().size() != 1)
670         report_fatal_error("Invalid array expression for llvm.bpf.preserve.field.info");
671       BaseTy = stripQualifiers(CTy->getBaseType());
672     } else {
673       auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
674       BaseTy = stripQualifiers(MemberTy->getBaseType());
675     }
676 
677     // Only basic types and enum types have signedness.
678     const auto *BTy = dyn_cast<DIBasicType>(BaseTy);
679     while (!BTy) {
680       const auto *CompTy = dyn_cast<DICompositeType>(BaseTy);
681       // Report an error if the field expression does not have signedness.
682       if (!CompTy || CompTy->getTag() != dwarf::DW_TAG_enumeration_type)
683         report_fatal_error("Invalid field expression for llvm.bpf.preserve.field.info");
684       BaseTy = stripQualifiers(CompTy->getBaseType());
685       BTy = dyn_cast<DIBasicType>(BaseTy);
686     }
687     uint32_t Encoding = BTy->getEncoding();
688     return (Encoding == dwarf::DW_ATE_signed || Encoding == dwarf::DW_ATE_signed_char);
689   }
690 
691   if (InfoKind == BPFCoreSharedInfo::FIELD_LSHIFT_U64) {
692     // The value is loaded into a value with FIELD_BYTE_SIZE size,
693     // and then zero or sign extended to U64.
694     // FIELD_LSHIFT_U64 and FIELD_RSHIFT_U64 are operations
695     // to extract the original value.
696     const Triple &Triple = TM->getTargetTriple();
697     DIDerivedType *MemberTy = nullptr;
698     bool IsBitField = false;
699     uint32_t SizeInBits;
700 
701     if (Tag == dwarf::DW_TAG_array_type) {
702       auto *EltTy = stripQualifiers(CTy->getBaseType());
703       SizeInBits = calcArraySize(CTy, 1) * EltTy->getSizeInBits();
704     } else {
705       MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
706       SizeInBits = MemberTy->getSizeInBits();
707       IsBitField = MemberTy->isBitField();
708     }
709 
710     if (!IsBitField) {
711       if (SizeInBits > 64)
712         report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
713       return 64 - SizeInBits;
714     }
715 
716     unsigned SBitOffset, NextSBitOffset;
717     GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
718     if (NextSBitOffset - SBitOffset > 64)
719       report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
720 
721     unsigned OffsetInBits = MemberTy->getOffsetInBits();
722     if (Triple.getArch() == Triple::bpfel)
723       return SBitOffset + 64 - OffsetInBits - SizeInBits;
724     else
725       return OffsetInBits + 64 - NextSBitOffset;
726   }
727 
728   if (InfoKind == BPFCoreSharedInfo::FIELD_RSHIFT_U64) {
729     DIDerivedType *MemberTy = nullptr;
730     bool IsBitField = false;
731     uint32_t SizeInBits;
732     if (Tag == dwarf::DW_TAG_array_type) {
733       auto *EltTy = stripQualifiers(CTy->getBaseType());
734       SizeInBits = calcArraySize(CTy, 1) * EltTy->getSizeInBits();
735     } else {
736       MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
737       SizeInBits = MemberTy->getSizeInBits();
738       IsBitField = MemberTy->isBitField();
739     }
740 
741     if (!IsBitField) {
742       if (SizeInBits > 64)
743         report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
744       return 64 - SizeInBits;
745     }
746 
747     unsigned SBitOffset, NextSBitOffset;
748     GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
749     if (NextSBitOffset - SBitOffset > 64)
750       report_fatal_error("too big field size for llvm.bpf.preserve.field.info");
751 
752     return 64 - SizeInBits;
753   }
754 
755   llvm_unreachable("Unknown llvm.bpf.preserve.field.info info kind");
756 }
757 
758 bool BPFAbstractMemberAccess::HasPreserveFieldInfoCall(CallInfoStack &CallStack) {
759   // This is called in error return path, no need to maintain CallStack.
760   while (CallStack.size()) {
761     auto StackElem = CallStack.top();
762     if (StackElem.second.Kind == BPFPreserveFieldInfoAI)
763       return true;
764     CallStack.pop();
765   }
766   return false;
767 }
768 
769 /// Compute the base of the whole preserve_* intrinsics chains, i.e., the base
770 /// pointer of the first preserve_*_access_index call, and construct the access
771 /// string, which will be the name of a global variable.
772 Value *BPFAbstractMemberAccess::computeBaseAndAccessKey(CallInst *Call,
773                                                         CallInfo &CInfo,
774                                                         std::string &AccessKey,
775                                                         MDNode *&TypeMeta) {
776   Value *Base = nullptr;
777   std::string TypeName;
778   CallInfoStack CallStack;
779 
780   // Put the access chain into a stack with the top as the head of the chain.
781   while (Call) {
782     CallStack.push(std::make_pair(Call, CInfo));
783     CInfo = AIChain[Call].second;
784     Call = AIChain[Call].first;
785   }
786 
787   // The access offset from the base of the head of chain is also
788   // calculated here as all debuginfo types are available.
789 
790   // Get type name and calculate the first index.
791   // We only want to get type name from typedef, structure or union.
792   // If user wants a relocation like
793   //    int *p; ... __builtin_preserve_access_index(&p[4]) ...
794   // or
795   //    int a[10][20]; ... __builtin_preserve_access_index(&a[2][3]) ...
796   // we will skip them.
797   uint32_t FirstIndex = 0;
798   uint32_t PatchImm = 0; // AccessOffset or the requested field info
799   uint32_t InfoKind = BPFCoreSharedInfo::FIELD_BYTE_OFFSET;
800   while (CallStack.size()) {
801     auto StackElem = CallStack.top();
802     Call = StackElem.first;
803     CInfo = StackElem.second;
804 
805     if (!Base)
806       Base = CInfo.Base;
807 
808     DIType *PossibleTypeDef = stripQualifiers(cast<DIType>(CInfo.Metadata),
809                                               false);
810     DIType *Ty = stripQualifiers(PossibleTypeDef);
811     if (CInfo.Kind == BPFPreserveUnionAI ||
812         CInfo.Kind == BPFPreserveStructAI) {
813       // struct or union type. If the typedef is in the metadata, always
814       // use the typedef.
815       TypeName = std::string(PossibleTypeDef->getName());
816       TypeMeta = PossibleTypeDef;
817       PatchImm += FirstIndex * (Ty->getSizeInBits() >> 3);
818       break;
819     }
820 
821     assert(CInfo.Kind == BPFPreserveArrayAI);
822 
823     // Array entries will always be consumed for accumulative initial index.
824     CallStack.pop();
825 
826     // BPFPreserveArrayAI
827     uint64_t AccessIndex = CInfo.AccessIndex;
828 
829     DIType *BaseTy = nullptr;
830     bool CheckElemType = false;
831     if (const auto *CTy = dyn_cast<DICompositeType>(Ty)) {
832       // array type
833       assert(CTy->getTag() == dwarf::DW_TAG_array_type);
834 
835 
836       FirstIndex += AccessIndex * calcArraySize(CTy, 1);
837       BaseTy = stripQualifiers(CTy->getBaseType());
838       CheckElemType = CTy->getElements().size() == 1;
839     } else {
840       // pointer type
841       auto *DTy = cast<DIDerivedType>(Ty);
842       assert(DTy->getTag() == dwarf::DW_TAG_pointer_type);
843 
844       BaseTy = stripQualifiers(DTy->getBaseType());
845       CTy = dyn_cast<DICompositeType>(BaseTy);
846       if (!CTy) {
847         CheckElemType = true;
848       } else if (CTy->getTag() != dwarf::DW_TAG_array_type) {
849         FirstIndex += AccessIndex;
850         CheckElemType = true;
851       } else {
852         FirstIndex += AccessIndex * calcArraySize(CTy, 0);
853       }
854     }
855 
856     if (CheckElemType) {
857       auto *CTy = dyn_cast<DICompositeType>(BaseTy);
858       if (!CTy) {
859         if (HasPreserveFieldInfoCall(CallStack))
860           report_fatal_error("Invalid field access for llvm.preserve.field.info intrinsic");
861         return nullptr;
862       }
863 
864       unsigned CTag = CTy->getTag();
865       if (CTag == dwarf::DW_TAG_structure_type || CTag == dwarf::DW_TAG_union_type) {
866         TypeName = std::string(CTy->getName());
867       } else {
868         if (HasPreserveFieldInfoCall(CallStack))
869           report_fatal_error("Invalid field access for llvm.preserve.field.info intrinsic");
870         return nullptr;
871       }
872       TypeMeta = CTy;
873       PatchImm += FirstIndex * (CTy->getSizeInBits() >> 3);
874       break;
875     }
876   }
877   assert(TypeName.size());
878   AccessKey += std::to_string(FirstIndex);
879 
880   // Traverse the rest of access chain to complete offset calculation
881   // and access key construction.
882   while (CallStack.size()) {
883     auto StackElem = CallStack.top();
884     CInfo = StackElem.second;
885     CallStack.pop();
886 
887     if (CInfo.Kind == BPFPreserveFieldInfoAI) {
888       InfoKind = CInfo.AccessIndex;
889       if (InfoKind == BPFCoreSharedInfo::FIELD_EXISTENCE)
890         PatchImm = 1;
891       break;
892     }
893 
894     // If the next Call (the top of the stack) is a BPFPreserveFieldInfoAI,
895     // the action will be extracting field info.
896     if (CallStack.size()) {
897       auto StackElem2 = CallStack.top();
898       CallInfo CInfo2 = StackElem2.second;
899       if (CInfo2.Kind == BPFPreserveFieldInfoAI) {
900         InfoKind = CInfo2.AccessIndex;
901         assert(CallStack.size() == 1);
902       }
903     }
904 
905     // Access Index
906     uint64_t AccessIndex = CInfo.AccessIndex;
907     AccessKey += ":" + std::to_string(AccessIndex);
908 
909     MDNode *MDN = CInfo.Metadata;
910     // At this stage, it cannot be pointer type.
911     auto *CTy = cast<DICompositeType>(stripQualifiers(cast<DIType>(MDN)));
912     PatchImm = GetFieldInfo(InfoKind, CTy, AccessIndex, PatchImm,
913                             CInfo.RecordAlignment);
914   }
915 
916   // Access key is the
917   //   "llvm." + type name + ":" + reloc type + ":" + patched imm + "$" +
918   //   access string,
919   // uniquely identifying one relocation.
920   // The prefix "llvm." indicates this is a temporary global, which should
921   // not be emitted to ELF file.
922   AccessKey = "llvm." + TypeName + ":" + std::to_string(InfoKind) + ":" +
923               std::to_string(PatchImm) + "$" + AccessKey;
924 
925   return Base;
926 }
927 
928 MDNode *BPFAbstractMemberAccess::computeAccessKey(CallInst *Call,
929                                                   CallInfo &CInfo,
930                                                   std::string &AccessKey,
931                                                   bool &IsInt32Ret) {
932   DIType *Ty = stripQualifiers(cast<DIType>(CInfo.Metadata), false);
933   assert(!Ty->getName().empty());
934 
935   int64_t PatchImm;
936   std::string AccessStr("0");
937   if (CInfo.AccessIndex == BPFCoreSharedInfo::TYPE_EXISTENCE) {
938     PatchImm = 1;
939   } else if (CInfo.AccessIndex == BPFCoreSharedInfo::TYPE_SIZE) {
940     // typedef debuginfo type has size 0, get the eventual base type.
941     DIType *BaseTy = stripQualifiers(Ty, true);
942     PatchImm = BaseTy->getSizeInBits() / 8;
943   } else {
944     // ENUM_VALUE_EXISTENCE and ENUM_VALUE
945     IsInt32Ret = false;
946 
947     const auto *CE = cast<ConstantExpr>(Call->getArgOperand(1));
948     const GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
949     assert(GV->hasInitializer());
950     const ConstantDataArray *DA = cast<ConstantDataArray>(GV->getInitializer());
951     assert(DA->isString());
952     StringRef ValueStr = DA->getAsString();
953 
954     // ValueStr format: <EnumeratorStr>:<Value>
955     size_t Separator = ValueStr.find_first_of(':');
956     StringRef EnumeratorStr = ValueStr.substr(0, Separator);
957 
958     // Find enumerator index in the debuginfo
959     DIType *BaseTy = stripQualifiers(Ty, true);
960     const auto *CTy = cast<DICompositeType>(BaseTy);
961     assert(CTy->getTag() == dwarf::DW_TAG_enumeration_type);
962     int EnumIndex = 0;
963     for (const auto Element : CTy->getElements()) {
964       const auto *Enum = cast<DIEnumerator>(Element);
965       if (Enum->getName() == EnumeratorStr) {
966         AccessStr = std::to_string(EnumIndex);
967         break;
968       }
969       EnumIndex++;
970     }
971 
972     if (CInfo.AccessIndex == BPFCoreSharedInfo::ENUM_VALUE) {
973       StringRef EValueStr = ValueStr.substr(Separator + 1);
974       PatchImm = std::stoll(std::string(EValueStr));
975     } else {
976       PatchImm = 1;
977     }
978   }
979 
980   AccessKey = "llvm." + Ty->getName().str() + ":" +
981               std::to_string(CInfo.AccessIndex) + std::string(":") +
982               std::to_string(PatchImm) + std::string("$") + AccessStr;
983 
984   return Ty;
985 }
986 
987 /// Call/Kind is the base preserve_*_access_index() call. Attempts to do
988 /// transformation to a chain of relocable GEPs.
989 bool BPFAbstractMemberAccess::transformGEPChain(CallInst *Call,
990                                                 CallInfo &CInfo) {
991   std::string AccessKey;
992   MDNode *TypeMeta;
993   Value *Base = nullptr;
994   bool IsInt32Ret;
995 
996   IsInt32Ret = CInfo.Kind == BPFPreserveFieldInfoAI;
997   if (CInfo.Kind == BPFPreserveFieldInfoAI && CInfo.Metadata) {
998     TypeMeta = computeAccessKey(Call, CInfo, AccessKey, IsInt32Ret);
999   } else {
1000     Base = computeBaseAndAccessKey(Call, CInfo, AccessKey, TypeMeta);
1001     if (!Base)
1002       return false;
1003   }
1004 
1005   BasicBlock *BB = Call->getParent();
1006   GlobalVariable *GV;
1007 
1008   if (GEPGlobals.find(AccessKey) == GEPGlobals.end()) {
1009     IntegerType *VarType;
1010     if (IsInt32Ret)
1011       VarType = Type::getInt32Ty(BB->getContext()); // 32bit return value
1012     else
1013       VarType = Type::getInt64Ty(BB->getContext()); // 64bit ptr or enum value
1014 
1015     GV = new GlobalVariable(*M, VarType, false, GlobalVariable::ExternalLinkage,
1016                             nullptr, AccessKey);
1017     GV->addAttribute(BPFCoreSharedInfo::AmaAttr);
1018     GV->setMetadata(LLVMContext::MD_preserve_access_index, TypeMeta);
1019     GEPGlobals[AccessKey] = GV;
1020   } else {
1021     GV = GEPGlobals[AccessKey];
1022   }
1023 
1024   if (CInfo.Kind == BPFPreserveFieldInfoAI) {
1025     // Load the global variable which represents the returned field info.
1026     LoadInst *LDInst;
1027     if (IsInt32Ret)
1028       LDInst = new LoadInst(Type::getInt32Ty(BB->getContext()), GV, "", Call);
1029     else
1030       LDInst = new LoadInst(Type::getInt64Ty(BB->getContext()), GV, "", Call);
1031 
1032     Instruction *PassThroughInst =
1033         BPFCoreSharedInfo::insertPassThrough(M, BB, LDInst, Call);
1034     Call->replaceAllUsesWith(PassThroughInst);
1035     Call->eraseFromParent();
1036     return true;
1037   }
1038 
1039   // For any original GEP Call and Base %2 like
1040   //   %4 = bitcast %struct.net_device** %dev1 to i64*
1041   // it is transformed to:
1042   //   %6 = load llvm.sk_buff:0:50$0:0:0:2:0
1043   //   %7 = bitcast %struct.sk_buff* %2 to i8*
1044   //   %8 = getelementptr i8, i8* %7, %6
1045   //   %9 = bitcast i8* %8 to i64*
1046   //   using %9 instead of %4
1047   // The original Call inst is removed.
1048 
1049   // Load the global variable.
1050   auto *LDInst = new LoadInst(Type::getInt64Ty(BB->getContext()), GV, "", Call);
1051 
1052   // Generate a BitCast
1053   auto *BCInst = new BitCastInst(Base, Type::getInt8PtrTy(BB->getContext()));
1054   BB->getInstList().insert(Call->getIterator(), BCInst);
1055 
1056   // Generate a GetElementPtr
1057   auto *GEP = GetElementPtrInst::Create(Type::getInt8Ty(BB->getContext()),
1058                                         BCInst, LDInst);
1059   BB->getInstList().insert(Call->getIterator(), GEP);
1060 
1061   // Generate a BitCast
1062   auto *BCInst2 = new BitCastInst(GEP, Call->getType());
1063   BB->getInstList().insert(Call->getIterator(), BCInst2);
1064 
1065   // For the following code,
1066   //    Block0:
1067   //      ...
1068   //      if (...) goto Block1 else ...
1069   //    Block1:
1070   //      %6 = load llvm.sk_buff:0:50$0:0:0:2:0
1071   //      %7 = bitcast %struct.sk_buff* %2 to i8*
1072   //      %8 = getelementptr i8, i8* %7, %6
1073   //      ...
1074   //      goto CommonExit
1075   //    Block2:
1076   //      ...
1077   //      if (...) goto Block3 else ...
1078   //    Block3:
1079   //      %6 = load llvm.bpf_map:0:40$0:0:0:2:0
1080   //      %7 = bitcast %struct.sk_buff* %2 to i8*
1081   //      %8 = getelementptr i8, i8* %7, %6
1082   //      ...
1083   //      goto CommonExit
1084   //    CommonExit
1085   // SimplifyCFG may generate:
1086   //    Block0:
1087   //      ...
1088   //      if (...) goto Block_Common else ...
1089   //     Block2:
1090   //       ...
1091   //      if (...) goto Block_Common else ...
1092   //    Block_Common:
1093   //      PHI = [llvm.sk_buff:0:50$0:0:0:2:0, llvm.bpf_map:0:40$0:0:0:2:0]
1094   //      %6 = load PHI
1095   //      %7 = bitcast %struct.sk_buff* %2 to i8*
1096   //      %8 = getelementptr i8, i8* %7, %6
1097   //      ...
1098   //      goto CommonExit
1099   //  For the above code, we cannot perform proper relocation since
1100   //  "load PHI" has two possible relocations.
1101   //
1102   // To prevent above tail merging, we use __builtin_bpf_passthrough()
1103   // where one of its parameters is a seq_num. Since two
1104   // __builtin_bpf_passthrough() funcs will always have different seq_num,
1105   // tail merging cannot happen. The __builtin_bpf_passthrough() will be
1106   // removed in the beginning of Target IR passes.
1107   //
1108   // This approach is also used in other places when global var
1109   // representing a relocation is used.
1110   Instruction *PassThroughInst =
1111       BPFCoreSharedInfo::insertPassThrough(M, BB, BCInst2, Call);
1112   Call->replaceAllUsesWith(PassThroughInst);
1113   Call->eraseFromParent();
1114 
1115   return true;
1116 }
1117 
1118 bool BPFAbstractMemberAccess::doTransformation(Function &F) {
1119   bool Transformed = false;
1120 
1121   // Collect PreserveDIAccessIndex Intrinsic call chains.
1122   // The call chains will be used to generate the access
1123   // patterns similar to GEP.
1124   collectAICallChains(F);
1125 
1126   for (auto &C : BaseAICalls)
1127     Transformed = transformGEPChain(C.first, C.second) || Transformed;
1128 
1129   return removePreserveAccessIndexIntrinsic(F) || Transformed;
1130 }
1131 
1132 PreservedAnalyses
1133 BPFAbstractMemberAccessPass::run(Function &F, FunctionAnalysisManager &AM) {
1134   return BPFAbstractMemberAccess(TM).run(F) ? PreservedAnalyses::none()
1135                                             : PreservedAnalyses::all();
1136 }
1137