92 #define DEBUG_TYPE "bpf-abstract-member-access" 102 class BPFAbstractMemberAccess final :
public ModulePass {
104 return "BPF Abstract Member Access";
107 bool runOnModule(
Module &M)
override;
124 typedef std::stack<std::pair<CallInst *, CallInfo>> CallInfoStack;
128 BPFPreserveArrayAI = 1,
129 BPFPreserveUnionAI = 2,
130 BPFPreserveStructAI = 3,
131 BPFPreserveFieldInfoAI = 4,
136 std::map<std::string, GlobalVariable *> GEPGlobals;
138 std::map<CallInst *, std::pair<CallInst *, CallInfo>> AIChain;
142 std::map<CallInst *, CallInfo> BaseAICalls;
144 bool doTransformation(
Module &M);
156 bool removePreserveAccessIndexIntrinsic(
Module &M);
157 void replaceWithGEP(std::vector<CallInst *> &CallList,
159 bool HasPreserveFieldInfoCall(CallInfoStack &CallStack);
167 std::string &AccessKey,
MDNode *&BaseMeta);
168 uint64_t getConstant(
const Value *IndexValue);
175 "abstracting struct/union member accessees",
false,
false)
178 return new BPFAbstractMemberAccess(TM);
181 bool BPFAbstractMemberAccess::runOnModule(
Module &M) {
182 LLVM_DEBUG(
dbgs() <<
"********** Abstract Member Accesses **********\n");
189 return doTransformation(M);
193 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)
202 while (
auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
205 Ty = DTy->getBaseType();
211 while (
auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
214 Ty = DTy->getBaseType();
222 for (
uint32_t I = StartDim;
I < Elements.size(); ++
I) {
223 if (
auto *Element = dyn_cast_or_null<DINode>(Elements[
I]))
224 if (Element->getTag() == dwarf::DW_TAG_subrange_type) {
225 const DISubrange *SR = cast<DISubrange>(Element);
227 DimSize *= CI->getSExtValue();
235 bool BPFAbstractMemberAccess::IsPreserveDIAccessIndexCall(
const CallInst *Call,
243 if (GV->getName().startswith(
"llvm.preserve.array.access.index")) {
244 CInfo.Kind = BPFPreserveArrayAI;
245 CInfo.Metadata = Call->
getMetadata(LLVMContext::MD_preserve_access_index);
247 report_fatal_error(
"Missing metadata for llvm.preserve.array.access.index intrinsic");
250 CInfo.RecordAlignment =
251 DL->getABITypeAlignment(CInfo.Base->getType()->getPointerElementType());
254 if (GV->getName().startswith(
"llvm.preserve.union.access.index")) {
255 CInfo.Kind = BPFPreserveUnionAI;
256 CInfo.Metadata = Call->
getMetadata(LLVMContext::MD_preserve_access_index);
258 report_fatal_error(
"Missing metadata for llvm.preserve.union.access.index intrinsic");
261 CInfo.RecordAlignment =
262 DL->getABITypeAlignment(CInfo.Base->getType()->getPointerElementType());
265 if (GV->getName().startswith(
"llvm.preserve.struct.access.index")) {
266 CInfo.Kind = BPFPreserveStructAI;
267 CInfo.Metadata = Call->
getMetadata(LLVMContext::MD_preserve_access_index);
269 report_fatal_error(
"Missing metadata for llvm.preserve.struct.access.index intrinsic");
272 CInfo.RecordAlignment =
273 DL->getABITypeAlignment(CInfo.Base->getType()->getPointerElementType());
276 if (GV->getName().startswith(
"llvm.bpf.preserve.field.info")) {
277 CInfo.Kind = BPFPreserveFieldInfoAI;
278 CInfo.Metadata =
nullptr;
283 CInfo.AccessIndex = InfoKind;
290 void BPFAbstractMemberAccess::replaceWithGEP(std::vector<CallInst *> &CallList,
293 for (
auto Call : CallList) {
295 if (DimensionIndex > 0)
296 Dimension = getConstant(Call->
getArgOperand(DimensionIndex));
301 for (
unsigned I = 0;
I < Dimension; ++
I)
312 bool BPFAbstractMemberAccess::removePreserveAccessIndexIntrinsic(
Module &M) {
313 std::vector<CallInst *> PreserveArrayIndexCalls;
314 std::vector<CallInst *> PreserveUnionIndexCalls;
315 std::vector<CallInst *> PreserveStructIndexCalls;
323 if (!IsPreserveDIAccessIndexCall(Call, CInfo))
327 if (CInfo.Kind == BPFPreserveArrayAI)
328 PreserveArrayIndexCalls.push_back(Call);
329 else if (CInfo.Kind == BPFPreserveUnionAI)
330 PreserveUnionIndexCalls.push_back(Call);
332 PreserveStructIndexCalls.push_back(Call);
345 replaceWithGEP(PreserveArrayIndexCalls, 1, 2);
346 replaceWithGEP(PreserveStructIndexCalls, 0, 1);
347 for (
auto Call : PreserveUnionIndexCalls) {
358 bool BPFAbstractMemberAccess::IsValidAIChain(
const MDNode *ParentType,
360 const MDNode *ChildType) {
369 if (isa<DIDerivedType>(CType))
373 if (
const auto *PtrTy = dyn_cast<DIDerivedType>(PType)) {
374 if (PtrTy->getTag() != dwarf::DW_TAG_pointer_type)
382 assert(PTy && CTy &&
"ParentType or ChildType is null or not composite");
385 assert(PTyTag == dwarf::DW_TAG_array_type ||
386 PTyTag == dwarf::DW_TAG_structure_type ||
387 PTyTag == dwarf::DW_TAG_union_type);
390 assert(CTyTag == dwarf::DW_TAG_array_type ||
391 CTyTag == dwarf::DW_TAG_structure_type ||
392 CTyTag == dwarf::DW_TAG_union_type);
395 if (PTyTag == dwarf::DW_TAG_array_type && PTyTag == CTyTag)
396 return PTy->getBaseType() == CTy->getBaseType();
399 if (PTyTag == dwarf::DW_TAG_array_type)
400 Ty = PTy->getBaseType();
407 void BPFAbstractMemberAccess::traceAICall(
CallInst *Call,
414 if (
auto *BI = dyn_cast<BitCastInst>(Inst)) {
415 traceBitCast(BI, Call, ParentInfo);
416 }
else if (
auto *CI = dyn_cast<CallInst>(Inst)) {
419 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
420 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
421 ChildInfo.Metadata)) {
422 AIChain[CI] = std::make_pair(Call, ParentInfo);
423 traceAICall(CI, ChildInfo);
425 BaseAICalls[Call] = ParentInfo;
427 }
else if (
auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
428 if (GI->hasAllZeroIndices())
429 traceGEP(GI, Call, ParentInfo);
431 BaseAICalls[Call] = ParentInfo;
433 BaseAICalls[Call] = ParentInfo;
438 void BPFAbstractMemberAccess::traceBitCast(
BitCastInst *BitCast,
446 if (
auto *BI = dyn_cast<BitCastInst>(Inst)) {
447 traceBitCast(BI, Parent, ParentInfo);
448 }
else if (
auto *CI = dyn_cast<CallInst>(Inst)) {
450 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
451 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
452 ChildInfo.Metadata)) {
453 AIChain[CI] = std::make_pair(Parent, ParentInfo);
454 traceAICall(CI, ChildInfo);
456 BaseAICalls[Parent] = ParentInfo;
458 }
else if (
auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
459 if (GI->hasAllZeroIndices())
460 traceGEP(GI, Parent, ParentInfo);
462 BaseAICalls[Parent] = ParentInfo;
464 BaseAICalls[Parent] = ParentInfo;
476 if (
auto *BI = dyn_cast<BitCastInst>(Inst)) {
477 traceBitCast(BI, Parent, ParentInfo);
478 }
else if (
auto *CI = dyn_cast<CallInst>(Inst)) {
480 if (IsPreserveDIAccessIndexCall(CI, ChildInfo) &&
481 IsValidAIChain(ParentInfo.Metadata, ParentInfo.AccessIndex,
482 ChildInfo.Metadata)) {
483 AIChain[CI] = std::make_pair(Parent, ParentInfo);
484 traceAICall(CI, ChildInfo);
486 BaseAICalls[Parent] = ParentInfo;
488 }
else if (
auto *GI = dyn_cast<GetElementPtrInst>(Inst)) {
489 if (GI->hasAllZeroIndices())
490 traceGEP(GI, Parent, ParentInfo);
492 BaseAICalls[Parent] = ParentInfo;
494 BaseAICalls[Parent] = ParentInfo;
499 void BPFAbstractMemberAccess::collectAICallChains(
Module &M,
Function &
F) {
507 if (!IsPreserveDIAccessIndexCall(Call, CInfo) ||
508 AIChain.find(Call) != AIChain.end())
511 traceAICall(Call, CInfo);
515 uint64_t BPFAbstractMemberAccess::getConstant(
const Value *IndexValue) {
522 void BPFAbstractMemberAccess::GetStorageBitRange(
DIDerivedType *MemberTy,
528 uint32_t AlignBits = RecordAlignment * 8;
529 if (RecordAlignment > 8 || MemberBitSize > AlignBits)
531 "requiring too big alignment");
533 StartBitOffset = MemberBitOffset & ~(AlignBits - 1);
534 if ((StartBitOffset + AlignBits) < (MemberBitOffset + MemberBitSize))
536 "cross alignment boundary");
537 EndBitOffset = StartBitOffset + AlignBits;
550 if (Tag == dwarf::DW_TAG_array_type) {
553 (EltTy->getSizeInBits() >> 3);
554 }
else if (Tag == dwarf::DW_TAG_structure_type) {
555 auto *MemberTy = cast<DIDerivedType>(CTy->
getElements()[AccessIndex]);
559 unsigned SBitOffset, NextSBitOffset;
560 GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset,
562 PatchImm += SBitOffset >> 3;
569 if (Tag == dwarf::DW_TAG_array_type) {
571 return calcArraySize(CTy, 1) * (EltTy->getSizeInBits() >> 3);
573 auto *MemberTy = cast<DIDerivedType>(CTy->
getElements()[AccessIndex]);
576 return SizeInBits >> 3;
578 unsigned SBitOffset, NextSBitOffset;
579 GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
580 SizeInBits = NextSBitOffset - SBitOffset;
581 if (SizeInBits & (SizeInBits - 1))
583 return SizeInBits >> 3;
589 if (Tag == dwarf::DW_TAG_array_type) {
595 auto *MemberTy = cast<DIDerivedType>(CTy->
getElements()[AccessIndex]);
604 if (!CompTy || CompTy->getTag() != dwarf::DW_TAG_enumeration_type)
609 uint32_t Encoding = BTy->getEncoding();
610 return (Encoding == dwarf::DW_ATE_signed || Encoding == dwarf::DW_ATE_signed_char);
620 bool IsBitField =
false;
623 if (Tag == dwarf::DW_TAG_array_type) {
627 MemberTy = cast<DIDerivedType>(CTy->
getElements()[AccessIndex]);
635 return 64 - SizeInBits;
638 unsigned SBitOffset, NextSBitOffset;
639 GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
640 if (NextSBitOffset - SBitOffset > 64)
645 return SBitOffset + 64 - OffsetInBits - SizeInBits;
647 return OffsetInBits + 64 - NextSBitOffset;
652 bool IsBitField =
false;
654 if (Tag == dwarf::DW_TAG_array_type) {
658 MemberTy = cast<DIDerivedType>(CTy->
getElements()[AccessIndex]);
666 return 64 - SizeInBits;
669 unsigned SBitOffset, NextSBitOffset;
670 GetStorageBitRange(MemberTy, RecordAlignment, SBitOffset, NextSBitOffset);
671 if (NextSBitOffset - SBitOffset > 64)
674 return 64 - SizeInBits;
680 bool BPFAbstractMemberAccess::HasPreserveFieldInfoCall(CallInfoStack &CallStack) {
682 while (CallStack.size()) {
683 auto StackElem = CallStack.top();
684 if (StackElem.second.Kind == BPFPreserveFieldInfoAI)
694 Value *BPFAbstractMemberAccess::computeBaseAndAccessKey(
CallInst *Call,
696 std::string &AccessKey,
700 CallInfoStack CallStack;
704 CallStack.push(std::make_pair(Call, CInfo));
705 CInfo = AIChain[Call].second;
706 Call = AIChain[Call].first;
722 while (CallStack.size()) {
723 auto StackElem = CallStack.top();
724 Call = StackElem.first;
725 CInfo = StackElem.second;
731 if (CInfo.Kind == BPFPreserveUnionAI ||
732 CInfo.Kind == BPFPreserveStructAI) {
740 assert(CInfo.Kind == BPFPreserveArrayAI);
746 uint64_t AccessIndex = CInfo.AccessIndex;
749 bool CheckElemType =
false;
750 if (
const auto *CTy = dyn_cast<DICompositeType>(Ty)) {
760 auto *DTy = cast<DIDerivedType>(Ty);
761 assert(DTy->getTag() == dwarf::DW_TAG_pointer_type);
766 CheckElemType =
true;
767 }
else if (CTy->getTag() != dwarf::DW_TAG_array_type) {
768 FirstIndex += AccessIndex;
769 CheckElemType =
true;
778 if (HasPreserveFieldInfoCall(CallStack))
783 unsigned CTag = CTy->
getTag();
784 if (CTag == dwarf::DW_TAG_structure_type || CTag == dwarf::DW_TAG_union_type) {
787 if (HasPreserveFieldInfoCall(CallStack))
801 while (CallStack.size()) {
802 auto StackElem = CallStack.top();
803 CInfo = StackElem.second;
806 if (CInfo.Kind == BPFPreserveFieldInfoAI)
811 if (CallStack.size()) {
812 auto StackElem2 = CallStack.top();
813 CallInfo CInfo2 = StackElem2.second;
814 if (CInfo2.Kind == BPFPreserveFieldInfoAI) {
815 InfoKind = CInfo2.AccessIndex;
816 assert(CallStack.size() == 1);
821 uint64_t AccessIndex = CInfo.AccessIndex;
824 MDNode *MDN = CInfo.Metadata;
825 uint32_t RecordAlignment = CInfo.RecordAlignment;
828 PatchImm = GetFieldInfo(InfoKind, CTy, AccessIndex, PatchImm,
838 AccessKey =
"llvm." + TypeName +
":" +
std::to_string(InfoKind) +
":" +
846 bool BPFAbstractMemberAccess::transformGEPChain(
Module &M,
CallInst *Call,
848 std::string AccessKey;
851 computeBaseAndAccessKey(Call, CInfo, AccessKey, TypeMeta);
858 if (GEPGlobals.find(AccessKey) == GEPGlobals.end()) {
860 if (CInfo.Kind == BPFPreserveFieldInfoAI)
868 GV->setMetadata(LLVMContext::MD_preserve_access_index, TypeMeta);
869 GEPGlobals[AccessKey] = GV;
871 GV = GEPGlobals[AccessKey];
874 if (CInfo.Kind == BPFPreserveFieldInfoAI) {
916 bool BPFAbstractMemberAccess::doTransformation(
Module &M) {
917 bool Transformed =
false;
923 collectAICallChains(M, F);
925 for (
auto &
C : BaseAICalls)
926 Transformed = transformGEPChain(M,
C.first,
C.second) || Transformed;
929 return removePreserveAccessIndexIntrinsic(M) || Transformed;
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
uint64_t getOffsetInBits() const
uint64_t getZExtValue() const
Get zero extended value.
INITIALIZE_PASS(BPFAbstractMemberAccess, DEBUG_TYPE, "abstracting struct/union member accessees", false, false) ModulePass *llvm
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
void push_back(const T &Elt)
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
This class represents a function call, abstracting a target machine's calling convention.
static bool SkipDIDerivedTag(unsigned Tag)
Externally visible function.
An instruction for reading from memory.
static IntegerType * getInt64Ty(LLVMContext &C)
LLVMContext & getContext() const
Get the context in which this basic block lives.
StringRef getName() const
DINodeArray getElements() const
Value * getArgOperand(unsigned i) const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
uint64_t getSizeInBits() const
static DIType * stripQualifiers(DIType *Ty)
DIType * getBaseType() const
Type * getType() const
All values are typed, get the type of this value.
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
static uint32_t calcArraySize(const DICompositeType *CTy, uint32_t StartDim)
This class represents a no-op cast from one type to another.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
const APInt & getValue() const
Return the constant as an APInt value reference.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
ModulePass * createBPFAbstractMemberAccess(BPFTargetMachine *TM)
Value * getCalledValue() const
LLVM Basic Block Representation.
This is an important base class in LLVM.
CountType getCount() const
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
self_iterator getIterator()
Class to represent integer types.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
const InstListType & getInstList() const
Return the underlying instruction list container.
This is the shared class of boolean and integer constants.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
iterator_range< user_iterator > users()
iterator insert(iterator where, pointer New)
static IntegerType * getInt32Ty(LLVMContext &C)
iterator_range< debug_compile_units_iterator > debug_compile_units() const
Return an iterator for all DICompileUnits listed in this Module's llvm.dbg.cu named metadata node and...
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static const std::string AmaAttr
The attribute attached to globals representing a field access.
const std::string to_string(const T &Value)
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Primary interface to the complete machine description for the target machine.
StringRef - Represent a constant reference to a string, i.e.
static IntegerType * getInt8Ty(LLVMContext &C)
const BasicBlock * getParent() const
Basic type, like 'int' or 'float'.