Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[IR] Add getDataLayout() helpers to BasicBlock and Instruction #96902

Merged
merged 3 commits into from
Jun 27, 2024

Conversation

nikic
Copy link
Contributor

@nikic nikic commented Jun 27, 2024

This is a helper to avoid writing getModule()->getDataLayout(). I regularly try to use this method only to remember it doesn't exist...

getModule()->getDataLayout() is also a common (the most common?) reason why code has to include the Module.h header.

@llvmbot
Copy link
Collaborator

llvmbot commented Jun 27, 2024

@llvm/pr-subscribers-llvm-transforms
@llvm/pr-subscribers-backend-x86
@llvm/pr-subscribers-backend-arm
@llvm/pr-subscribers-compiler-rt-sanitizer
@llvm/pr-subscribers-backend-aarch64
@llvm/pr-subscribers-coroutines
@llvm/pr-subscribers-llvm-analysis
@llvm/pr-subscribers-llvm-ir
@llvm/pr-subscribers-backend-nvptx
@llvm/pr-subscribers-backend-loongarch

@llvm/pr-subscribers-backend-amdgpu

Author: Nikita Popov (nikic)

Changes

This is a helper to avoid writing getModule()->getDataLayout(). I regularly try to use this method only to remember it doesn't exist...

getModule()->getDataLayout() is also a common (the most common?) reason why code has to include the Module.h header.


Patch is 121.24 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/96902.diff

100 Files Affected:

  • (modified) llvm/include/llvm/Analysis/MemorySSA.h (+1-1)
  • (modified) llvm/include/llvm/IR/BasicBlock.h (+6)
  • (modified) llvm/include/llvm/IR/IRBuilder.h (+7-7)
  • (modified) llvm/include/llvm/IR/Instruction.h (+6)
  • (modified) llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerCommon.h (+1-1)
  • (modified) llvm/lib/Analysis/BranchProbabilityInfo.cpp (+1-1)
  • (modified) llvm/lib/Analysis/CaptureTracking.cpp (+1-1)
  • (modified) llvm/lib/Analysis/DemandedBits.cpp (+3-3)
  • (modified) llvm/lib/Analysis/IVDescriptors.cpp (+1-1)
  • (modified) llvm/lib/Analysis/IVUsers.cpp (+1-1)
  • (modified) llvm/lib/Analysis/InstructionSimplify.cpp (+1-1)
  • (modified) llvm/lib/Analysis/LazyValueInfo.cpp (+3-3)
  • (modified) llvm/lib/Analysis/Lint.cpp (+4-4)
  • (modified) llvm/lib/Analysis/Loads.cpp (+3-3)
  • (modified) llvm/lib/Analysis/LoopAccessAnalysis.cpp (+7-7)
  • (modified) llvm/lib/Analysis/LoopUnrollAnalyzer.cpp (+3-3)
  • (modified) llvm/lib/Analysis/MemoryBuiltins.cpp (+1-1)
  • (modified) llvm/lib/Analysis/MemoryDependenceAnalysis.cpp (+2-2)
  • (modified) llvm/lib/Analysis/MemoryLocation.cpp (+5-5)
  • (modified) llvm/lib/Analysis/MustExecute.cpp (+1-1)
  • (modified) llvm/lib/Analysis/StackSafetyAnalysis.cpp (+1-1)
  • (modified) llvm/lib/Analysis/ValueTracking.cpp (+2-2)
  • (modified) llvm/lib/Analysis/VectorUtils.cpp (+1-1)
  • (modified) llvm/lib/CodeGen/AssignmentTrackingAnalysis.cpp (+1-1)
  • (modified) llvm/lib/CodeGen/AtomicExpandPass.cpp (+5-5)
  • (modified) llvm/lib/CodeGen/CodeGenPrepare.cpp (+2-2)
  • (modified) llvm/lib/IR/BasicBlock.cpp (+4)
  • (modified) llvm/lib/IR/Instruction.cpp (+5)
  • (modified) llvm/lib/IR/Instructions.cpp (+2-2)
  • (modified) llvm/lib/Target/AArch64/AArch64ISelLowering.cpp (+6-6)
  • (modified) llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp (+2-2)
  • (modified) llvm/lib/Target/AMDGPU/AMDGPULowerBufferFatPointers.cpp (+4-4)
  • (modified) llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp (+2-2)
  • (modified) llvm/lib/Target/ARM/ARMISelLowering.cpp (+2-2)
  • (modified) llvm/lib/Target/ARM/MVETailPredication.cpp (+2-2)
  • (modified) llvm/lib/Target/BPF/BPFPreserveStaticOffset.cpp (+1-1)
  • (modified) llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp (+1-1)
  • (modified) llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp (+1-1)
  • (modified) llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp (+3-3)
  • (modified) llvm/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp (+2-2)
  • (modified) llvm/lib/Target/RISCV/RISCVISelLowering.cpp (+6-6)
  • (modified) llvm/lib/Target/WebAssembly/WebAssemblyFixFunctionBitcasts.cpp (+1-1)
  • (modified) llvm/lib/Target/X86/X86InstCombineIntrinsic.cpp (+4-4)
  • (modified) llvm/lib/Target/X86/X86InterleavedAccess.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Coroutines/CoroFrame.cpp (+1-1)
  • (modified) llvm/lib/Transforms/IPO/AttributorAttributes.cpp (+3-3)
  • (modified) llvm/lib/Transforms/IPO/OpenMPOpt.cpp (+1-1)
  • (modified) llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp (+1-1)
  • (modified) llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp (+2-2)
  • (modified) llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp (+1-1)
  • (modified) llvm/lib/Transforms/InstCombine/InstructionCombining.cpp (+2-2)
  • (modified) llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp (+3-3)
  • (modified) llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Scalar/GVN.cpp (+6-6)
  • (modified) llvm/lib/Transforms/Scalar/GuardWidening.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Scalar/IndVarSimplify.cpp (+5-5)
  • (modified) llvm/lib/Transforms/Scalar/JumpThreading.cpp (+8-8)
  • (modified) llvm/lib/Transforms/Scalar/LICM.cpp (+5-5)
  • (modified) llvm/lib/Transforms/Scalar/LoopDataPrefetch.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Scalar/LoopDeletion.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Scalar/LoopLoadElimination.cpp (+4-4)
  • (modified) llvm/lib/Transforms/Scalar/LoopRotation.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp (+6-6)
  • (modified) llvm/lib/Transforms/Scalar/LowerMatrixIntrinsics.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp (+7-7)
  • (modified) llvm/lib/Transforms/Scalar/MergeICmps.cpp (+3-3)
  • (modified) llvm/lib/Transforms/Scalar/MergedLoadStoreMotion.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Scalar/Reassociate.cpp (+4-4)
  • (modified) llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp (+4-4)
  • (modified) llvm/lib/Transforms/Scalar/SROA.cpp (+7-7)
  • (modified) llvm/lib/Transforms/Scalar/Scalarizer.cpp (+2-2)
  • (modified) llvm/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp (+2-2)
  • (modified) llvm/lib/Transforms/Scalar/TailRecursionElimination.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/AssumeBundleBuilder.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/BasicBlockUtils.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/BypassSlowDivision.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/CloneFunction.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/DemoteRegToStack.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/Local.cpp (+3-3)
  • (modified) llvm/lib/Transforms/Utils/LoopConstrainer.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/LoopPeel.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/LoopSimplify.cpp (+2-2)
  • (modified) llvm/lib/Transforms/Utils/LoopUnroll.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp (+2-2)
  • (modified) llvm/lib/Transforms/Utils/LoopUtils.cpp (+2-2)
  • (modified) llvm/lib/Transforms/Utils/LoopVersioning.cpp (+3-3)
  • (modified) llvm/lib/Transforms/Utils/MemoryTaggingSupport.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/SSAUpdater.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Utils/SimplifyCFG.cpp (+2-2)
  • (modified) llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp (+3-3)
  • (modified) llvm/lib/Transforms/Vectorize/LoopIdiomVectorize.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp (+1-1)
  • (modified) llvm/lib/Transforms/Vectorize/LoopVectorize.cpp (+3-3)
  • (modified) llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp (+2-2)
  • (modified) llvm/tools/llvm-reduce/deltas/ReduceOpcodes.cpp (+1-1)
  • (modified) llvm/tools/llvm-stress/llvm-stress.cpp (+1-1)
diff --git a/llvm/include/llvm/Analysis/MemorySSA.h b/llvm/include/llvm/Analysis/MemorySSA.h
index 2ca5c281166ca..5a2425257b03f 100644
--- a/llvm/include/llvm/Analysis/MemorySSA.h
+++ b/llvm/include/llvm/Analysis/MemorySSA.h
@@ -1269,7 +1269,7 @@ class upward_defs_iterator
     if (WalkingPhi && Location.Ptr) {
       PHITransAddr Translator(
           const_cast<Value *>(Location.Ptr),
-          OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
+          OriginalAccess->getBlock()->getDataLayout(), nullptr);
 
       if (Value *Addr =
               Translator.translateValue(OriginalAccess->getBlock(),
diff --git a/llvm/include/llvm/IR/BasicBlock.h b/llvm/include/llvm/IR/BasicBlock.h
index 80067f2652a2b..0d346a94920c8 100644
--- a/llvm/include/llvm/IR/BasicBlock.h
+++ b/llvm/include/llvm/IR/BasicBlock.h
@@ -32,6 +32,7 @@ namespace llvm {
 
 class AssemblyAnnotationWriter;
 class CallInst;
+class DataLayout;
 class Function;
 class LandingPadInst;
 class LLVMContext;
@@ -218,6 +219,11 @@ class BasicBlock final : public Value, // Basic blocks are data objects also
                             static_cast<const BasicBlock *>(this)->getModule());
   }
 
+  /// Get the data layout of the module this instruction belongs to.
+  ///
+  /// Requires the basic block to have a parent module.
+  const DataLayout &getDataLayout() const;
+
   /// Returns the terminator instruction if the block is well formed or null
   /// if the block is not well formed.
   const Instruction *getTerminator() const LLVM_READONLY {
diff --git a/llvm/include/llvm/IR/IRBuilder.h b/llvm/include/llvm/IR/IRBuilder.h
index c10ea33a4ee13..5b6bae629ae31 100644
--- a/llvm/include/llvm/IR/IRBuilder.h
+++ b/llvm/include/llvm/IR/IRBuilder.h
@@ -1049,7 +1049,7 @@ class IRBuilderBase {
 
   /// Create a call to llvm.stacksave
   CallInst *CreateStackSave(const Twine &Name = "") {
-    const DataLayout &DL = BB->getModule()->getDataLayout();
+    const DataLayout &DL = BB->getDataLayout();
     return CreateIntrinsic(Intrinsic::stacksave, {DL.getAllocaPtrType(Context)},
                            {}, nullptr, Name);
   }
@@ -1770,14 +1770,14 @@ class IRBuilderBase {
 
   AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace,
                            Value *ArraySize = nullptr, const Twine &Name = "") {
-    const DataLayout &DL = BB->getModule()->getDataLayout();
+    const DataLayout &DL = BB->getDataLayout();
     Align AllocaAlign = DL.getPrefTypeAlign(Ty);
     return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
   }
 
   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
                            const Twine &Name = "") {
-    const DataLayout &DL = BB->getModule()->getDataLayout();
+    const DataLayout &DL = BB->getDataLayout();
     Align AllocaAlign = DL.getPrefTypeAlign(Ty);
     unsigned AddrSpace = DL.getAllocaAddrSpace();
     return Insert(new AllocaInst(Ty, AddrSpace, ArraySize, AllocaAlign), Name);
@@ -1815,7 +1815,7 @@ class IRBuilderBase {
   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
                               bool isVolatile, const Twine &Name = "") {
     if (!Align) {
-      const DataLayout &DL = BB->getModule()->getDataLayout();
+      const DataLayout &DL = BB->getDataLayout();
       Align = DL.getABITypeAlign(Ty);
     }
     return Insert(new LoadInst(Ty, Ptr, Twine(), isVolatile, *Align), Name);
@@ -1824,7 +1824,7 @@ class IRBuilderBase {
   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align,
                                 bool isVolatile = false) {
     if (!Align) {
-      const DataLayout &DL = BB->getModule()->getDataLayout();
+      const DataLayout &DL = BB->getDataLayout();
       Align = DL.getABITypeAlign(Val->getType());
     }
     return Insert(new StoreInst(Val, Ptr, isVolatile, *Align));
@@ -1841,7 +1841,7 @@ class IRBuilderBase {
                       AtomicOrdering FailureOrdering,
                       SyncScope::ID SSID = SyncScope::System) {
     if (!Align) {
-      const DataLayout &DL = BB->getModule()->getDataLayout();
+      const DataLayout &DL = BB->getDataLayout();
       Align = llvm::Align(DL.getTypeStoreSize(New->getType()));
     }
 
@@ -1854,7 +1854,7 @@ class IRBuilderBase {
                                  AtomicOrdering Ordering,
                                  SyncScope::ID SSID = SyncScope::System) {
     if (!Align) {
-      const DataLayout &DL = BB->getModule()->getDataLayout();
+      const DataLayout &DL = BB->getDataLayout();
       Align = llvm::Align(DL.getTypeStoreSize(Val->getType()));
     }
 
diff --git a/llvm/include/llvm/IR/Instruction.h b/llvm/include/llvm/IR/Instruction.h
index 2e72f6742a659..7a9b95f23465c 100644
--- a/llvm/include/llvm/IR/Instruction.h
+++ b/llvm/include/llvm/IR/Instruction.h
@@ -29,6 +29,7 @@
 namespace llvm {
 
 class BasicBlock;
+class DataLayout;
 class DbgMarker;
 class FastMathFlags;
 class MDNode;
@@ -189,6 +190,11 @@ class Instruction : public User,
                          static_cast<const Instruction *>(this)->getFunction());
   }
 
+  /// Get the data layout of the module this instruction belongs to.
+  ///
+  /// Requires the instruction to have a parent module.
+  const DataLayout &getDataLayout() const;
+
   /// This method unlinks 'this' from the containing basic block, but does not
   /// delete it.
   void removeFromParent();
diff --git a/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerCommon.h b/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerCommon.h
index 6322df90b18e1..9fe2716220e83 100644
--- a/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerCommon.h
+++ b/llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerCommon.h
@@ -43,7 +43,7 @@ class InterestingMemoryOperand {
                            Value *MaybeStride = nullptr)
       : IsWrite(IsWrite), OpType(OpType), Alignment(Alignment),
         MaybeMask(MaybeMask), MaybeEVL(MaybeEVL), MaybeStride(MaybeStride) {
-    const DataLayout &DL = I->getModule()->getDataLayout();
+    const DataLayout &DL = I->getDataLayout();
     TypeStoreSize = DL.getTypeStoreSizeInBits(OpType);
     PtrUse = &I->getOperandUse(OperandNo);
   }
diff --git a/llvm/lib/Analysis/BranchProbabilityInfo.cpp b/llvm/lib/Analysis/BranchProbabilityInfo.cpp
index 3e9c60918f3c0..85092f70112cd 100644
--- a/llvm/lib/Analysis/BranchProbabilityInfo.cpp
+++ b/llvm/lib/Analysis/BranchProbabilityInfo.cpp
@@ -620,7 +620,7 @@ computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
       if (!CmpLHSConst || !llvm::is_contained(successors(BB), B))
         continue;
       // First collapse InstChain
-      const DataLayout &DL = BB->getModule()->getDataLayout();
+      const DataLayout &DL = BB->getDataLayout();
       for (Instruction *I : llvm::reverse(InstChain)) {
         CmpLHSConst = ConstantFoldBinaryOpOperands(
             I->getOpcode(), CmpLHSConst, cast<Constant>(I->getOperand(1)), DL);
diff --git a/llvm/lib/Analysis/CaptureTracking.cpp b/llvm/lib/Analysis/CaptureTracking.cpp
index d8ca4a60cfbd4..a353842eb809c 100644
--- a/llvm/lib/Analysis/CaptureTracking.cpp
+++ b/llvm/lib/Analysis/CaptureTracking.cpp
@@ -388,7 +388,7 @@ UseCaptureKind llvm::DetermineUseCaptureKind(
         // Comparing a dereferenceable_or_null pointer against null cannot
         // lead to pointer escapes, because if it is not null it must be a
         // valid (in-bounds) pointer.
-        const DataLayout &DL = I->getModule()->getDataLayout();
+        const DataLayout &DL = I->getDataLayout();
         if (IsDereferenceableOrNull && IsDereferenceableOrNull(O, DL))
           return UseCaptureKind::NO_CAPTURE;
       }
diff --git a/llvm/lib/Analysis/DemandedBits.cpp b/llvm/lib/Analysis/DemandedBits.cpp
index c5017bf52498e..cda3ebfd77c5c 100644
--- a/llvm/lib/Analysis/DemandedBits.cpp
+++ b/llvm/lib/Analysis/DemandedBits.cpp
@@ -69,7 +69,7 @@ void DemandedBits::determineLiveOperandBits(
           return;
         KnownBitsComputed = true;
 
-        const DataLayout &DL = UserI->getModule()->getDataLayout();
+        const DataLayout &DL = UserI->getDataLayout();
         Known = KnownBits(BitWidth);
         computeKnownBits(V1, Known, DL, 0, &AC, UserI, &DT);
 
@@ -404,14 +404,14 @@ APInt DemandedBits::getDemandedBits(Instruction *I) {
   if (Found != AliveBits.end())
     return Found->second;
 
-  const DataLayout &DL = I->getModule()->getDataLayout();
+  const DataLayout &DL = I->getDataLayout();
   return APInt::getAllOnes(DL.getTypeSizeInBits(I->getType()->getScalarType()));
 }
 
 APInt DemandedBits::getDemandedBits(Use *U) {
   Type *T = (*U)->getType();
   auto *UserI = cast<Instruction>(U->getUser());
-  const DataLayout &DL = UserI->getModule()->getDataLayout();
+  const DataLayout &DL = UserI->getDataLayout();
   unsigned BitWidth = DL.getTypeSizeInBits(T->getScalarType());
 
   // We only track integer uses, everything else produces a mask with all bits
diff --git a/llvm/lib/Analysis/IVDescriptors.cpp b/llvm/lib/Analysis/IVDescriptors.cpp
index 055f121e74341..699ddf271e9e8 100644
--- a/llvm/lib/Analysis/IVDescriptors.cpp
+++ b/llvm/lib/Analysis/IVDescriptors.cpp
@@ -95,7 +95,7 @@ static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
                                                      AssumptionCache *AC,
                                                      DominatorTree *DT) {
   bool IsSigned = false;
-  const DataLayout &DL = Exit->getModule()->getDataLayout();
+  const DataLayout &DL = Exit->getDataLayout();
   uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
 
   if (DB) {
diff --git a/llvm/lib/Analysis/IVUsers.cpp b/llvm/lib/Analysis/IVUsers.cpp
index 5c7883fb3b37c..fc9f4343178b8 100644
--- a/llvm/lib/Analysis/IVUsers.cpp
+++ b/llvm/lib/Analysis/IVUsers.cpp
@@ -134,7 +134,7 @@ static bool IVUseShouldUsePostIncValue(Instruction *User, Value *Operand,
 /// add its users to the IVUsesByStride set and return true.  Otherwise, return
 /// false.
 bool IVUsers::AddUsersIfInteresting(Instruction *I) {
-  const DataLayout &DL = I->getModule()->getDataLayout();
+  const DataLayout &DL = I->getDataLayout();
 
   // Add this IV user to the Processed set before returning false to ensure that
   // all IV users are members of the set. See IVUsers::isIVUserOrOperand.
diff --git a/llvm/lib/Analysis/InstructionSimplify.cpp b/llvm/lib/Analysis/InstructionSimplify.cpp
index a452add93a7e7..2081f8b70ddb7 100644
--- a/llvm/lib/Analysis/InstructionSimplify.cpp
+++ b/llvm/lib/Analysis/InstructionSimplify.cpp
@@ -7183,7 +7183,7 @@ static bool replaceAndRecursivelySimplifyImpl(
     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
   bool Simplified = false;
   SmallSetVector<Instruction *, 8> Worklist;
-  const DataLayout &DL = I->getModule()->getDataLayout();
+  const DataLayout &DL = I->getDataLayout();
 
   // If we have an explicit value to collapse to, do that round of the
   // simplification loop by hand initially.
diff --git a/llvm/lib/Analysis/LazyValueInfo.cpp b/llvm/lib/Analysis/LazyValueInfo.cpp
index f10b2bc06746a..3597f8f08e770 100644
--- a/llvm/lib/Analysis/LazyValueInfo.cpp
+++ b/llvm/lib/Analysis/LazyValueInfo.cpp
@@ -1059,7 +1059,7 @@ LazyValueInfoImpl::solveBlockValueExtractValue(ExtractValueInst *EVI,
   // based on replaced with.overflow intrinsics.
   if (Value *V = simplifyExtractValueInst(
           EVI->getAggregateOperand(), EVI->getIndices(),
-          EVI->getModule()->getDataLayout()))
+          EVI->getDataLayout()))
     return getBlockValue(V, BB, EVI);
 
   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
@@ -1387,7 +1387,7 @@ LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
         // over the operands unnecessarily which can be expensive for
         // instructions with many operands.
         if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
-          const DataLayout &DL = BBTo->getModule()->getDataLayout();
+          const DataLayout &DL = BBTo->getDataLayout();
           if (usesOperand(Usr, Condition)) {
             // If Val has Condition as an operand and Val can be folded into a
             // constant with either Condition == true or Condition == false,
@@ -1451,7 +1451,7 @@ LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
       ConstantRange EdgeVal(CaseValue);
       if (ValUsesConditionAndMayBeFoldable) {
         User *Usr = cast<User>(Val);
-        const DataLayout &DL = BBTo->getModule()->getDataLayout();
+        const DataLayout &DL = BBTo->getDataLayout();
         ValueLatticeElement EdgeLatticeVal =
             constantFoldUser(Usr, Condition, CaseValue, DL);
         if (EdgeLatticeVal.isOverdefined())
diff --git a/llvm/lib/Analysis/Lint.cpp b/llvm/lib/Analysis/Lint.cpp
index e9ed0c22c8e37..df1b22d48ca7a 100644
--- a/llvm/lib/Analysis/Lint.cpp
+++ b/llvm/lib/Analysis/Lint.cpp
@@ -563,22 +563,22 @@ static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
 }
 
 void Lint::visitSDiv(BinaryOperator &I) {
-  Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
+  Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
         "Undefined behavior: Division by zero", &I);
 }
 
 void Lint::visitUDiv(BinaryOperator &I) {
-  Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
+  Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
         "Undefined behavior: Division by zero", &I);
 }
 
 void Lint::visitSRem(BinaryOperator &I) {
-  Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
+  Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
         "Undefined behavior: Division by zero", &I);
 }
 
 void Lint::visitURem(BinaryOperator &I) {
-  Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
+  Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
         "Undefined behavior: Division by zero", &I);
 }
 
diff --git a/llvm/lib/Analysis/Loads.cpp b/llvm/lib/Analysis/Loads.cpp
index 2b8197066e8e9..b2eb5a96d7d93 100644
--- a/llvm/lib/Analysis/Loads.cpp
+++ b/llvm/lib/Analysis/Loads.cpp
@@ -263,7 +263,7 @@ bool llvm::isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L,
                                              ScalarEvolution &SE,
                                              DominatorTree &DT,
                                              AssumptionCache *AC) {
-  auto &DL = LI->getModule()->getDataLayout();
+  auto &DL = LI->getDataLayout();
   Value *Ptr = LI->getPointerOperand();
 
   APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
@@ -588,7 +588,7 @@ Value *llvm::findAvailablePtrLoadStore(
   if (MaxInstsToScan == 0)
     MaxInstsToScan = ~0U;
 
-  const DataLayout &DL = ScanBB->getModule()->getDataLayout();
+  const DataLayout &DL = ScanBB->getDataLayout();
   const Value *StrippedPtr = Loc.Ptr->stripPointerCasts();
 
   while (ScanFrom != ScanBB->begin()) {
@@ -668,7 +668,7 @@ Value *llvm::findAvailablePtrLoadStore(
 Value *llvm::FindAvailableLoadedValue(LoadInst *Load, BatchAAResults &AA,
                                       bool *IsLoadCSE,
                                       unsigned MaxInstsToScan) {
-  const DataLayout &DL = Load->getModule()->getDataLayout();
+  const DataLayout &DL = Load->getDataLayout();
   Value *StrippedPtr = Load->getPointerOperand()->stripPointerCasts();
   BasicBlock *ScanBB = Load->getParent();
   Type *AccessTy = Load->getType();
diff --git a/llvm/lib/Analysis/LoopAccessAnalysis.cpp b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
index 1f2bdf83651d6..38bf6d8160aa9 100644
--- a/llvm/lib/Analysis/LoopAccessAnalysis.cpp
+++ b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
@@ -239,7 +239,7 @@ getStartAndEndForAccess(const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy,
   assert(SE->isLoopInvariant(ScEnd, Lp)&& "ScEnd needs to be invariant");
 
   // Add the size of the pointed element to ScEnd.
-  auto &DL = Lp->getHeader()->getModule()->getDataLayout();
+  auto &DL = Lp->getHeader()->getDataLayout();
   Type *IdxTy = DL.getIndexType(PtrExpr->getType());
   const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy);
   ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
@@ -309,7 +309,7 @@ bool RuntimePointerChecking::tryToCreateDiffCheck(
     return false;
 
   const DataLayout &DL =
-      SinkAR->getLoop()->getHeader()->getModule()->getDataLayout();
+      SinkAR->getLoop()->getHeader()->getDataLayout();
   unsigned AllocSize =
       std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy));
 
@@ -1494,7 +1494,7 @@ std::optional<int64_t> llvm::getPtrStride(PredicatedScalarEvolution &PSE,
     return std::nullopt;
   }
 
-  auto &DL = Lp->getHeader()->getModule()->getDataLayout();
+  auto &DL = Lp->getHeader()->getDataLayout();
   TypeSize AllocSize = DL.getTypeAllocSize(AccessTy);
   int64_t Size = AllocSize.getFixedValue();
   const APInt &APStepVal = C->getAPInt();
@@ -1907,7 +1907,7 @@ MemoryDepChecker::getDependenceDistanceStrideAndSize(
     const AccessAnalysis::MemAccessInfo &B, Instruction *BInst,
     const DenseMap<Value *, SmallVector<const Value *, 16>>
         &UnderlyingObjects) {
-  auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
+  auto &DL = InnermostLoop->getHeader()->getDataLayout();
   auto &SE = *PSE.getSE();
   auto [APtr, AIsWrite] = A;
   auto [BPtr, BIsWrite] = B;
@@ -2027,7 +2027,7 @@ MemoryDepChecker::Dependence::DepType MemoryDepChecker::isDependent(
   }
 
   ScalarEvolution &SE = *PSE.getSE();
-  auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
+  auto &DL = InnermostLoop->getHeader()->getDataLayout();
   uint64_t MaxStride = std::max(StrideA, StrideB);
 
   // If the distance between the acecsses is larger than their maximum absolute
@@ -2805,7 +2805,7 @@ bool LoopAccessInfo::isInvariant(Value *V) const {
 /// stores. This ignores trailing indices that have no effect on the final
 /// pointer.
 static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) {
-  const DataLayout &DL = Gep->getModule()->getDataLayout();
+  const DataLayout &DL = Gep->getDataLayout();
   unsigned LastOperand = Gep->getNumOperands() - 1;
   TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
 
@@ -2961,7 +2961,7 @@ void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
   // Match the types so we can compare the stride and the MaxBTC.
   // The Stride can be positive/negative, so we sign extend Stride;
   // The backedgeTakenCount is non-negative, so we zero extend MaxBTC.
-  const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
+  const DataLayout &DL = TheLoop->getHeader()->getDataLayout();
   uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType());
   uint64_t BETypeSizeBits = DL.getTypeSizeInBits(MaxBTC->getType());
   const SCEV *CastedStride = StrideExpr;
diff --git a/llvm/lib/Analysis/LoopUnrollAnalyzer.cpp b/llvm/lib/Analysis/LoopUnrollAnalyzer.cpp
index 84f1eff9a7320..7b6ca4d711fcd 100644
--- a/llvm/lib/Analysis/LoopUnrollAnalyzer.cpp
+++ b/llvm/lib/Analysis/LoopUnrollAnalyzer.cpp
@@ -84,7 +84,7 @@ bool UnrolledInstAnalyzer::visitBinaryOperator(BinaryOperator &I) {
       RHS = SimpleRHS;
 
   Value *SimpleV = nullptr;
-  const DataLayout &DL = I.getModule()->getDataLayout();
+  const DataLayout &DL = I.getDataLayout();
   if (auto FI = dyn_cast<FPMathOperator>(&I))
     SimpleV =
         simplifyBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
@@ -157,7 +157,7 @@ bool UnrolledInstAnalyzer::visitCastInst(CastInst &I) {
   // analysis, which operates on integers (and, e.g., might convert i8* null to
   // i32 0).
   if (CastInst::castIsValid(I.getOpcode(), Op, I.getType())) {
-    const DataLayout &DL = I.getModule()->getDataLayout();
+    const DataLayout &DL = I.getDataLayout();
     if (Value *V = simplifyCastInst(I.getOpcode(), Op, I.getType(), DL)) {
       SimplifiedValues[&I] = V;
       return true;
@@ -194,7 +194,7 @@ bool UnrolledInstAnalyzer::visitCmpInst(CmpInst &I) {
     }
   }
 
-  const DataLayout &DL = I.getModule()->getDataLayout();
+  const DataLayout &DL = I.getDataLayout();
   if (Value *V = simplifyCmpInst(I.getPredicate(), LHS, RHS, DL)) {
     SimplifiedValues[&I] = V;
     return true;
diff --git a/llvm/lib/Analysis/MemoryBuiltins.cpp b/llvm/lib/Analysis/MemoryBuiltins.cpp
index 8ca15434833d9..1edc51e9ce5da 100644
--- a/llvm/lib/Analysis/MemoryBuiltin...
[truncated]

@nikic nikic changed the title [IR] Add getDataLayout() helpers to BasicBlock and Function [IR] Add getDataLayout() helpers to BasicBlock and Instruction Jun 27, 2024
Copy link
Member

@dtcxzyw dtcxzyw left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thank you!

llvm/include/llvm/IR/BasicBlock.h Outdated Show resolved Hide resolved
llvm/lib/Transforms/Scalar/LoopLoadElimination.cpp Outdated Show resolved Hide resolved
llvm/lib/Transforms/Scalar/LoopLoadElimination.cpp Outdated Show resolved Hide resolved
llvm/lib/Transforms/Scalar/LoopLoadElimination.cpp Outdated Show resolved Hide resolved
@@ -172,7 +172,7 @@ static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
/// us how to partition the loops.
static PHINode *findPHIToPartitionLoops(Loop *L, DominatorTree *DT,
AssumptionCache *AC) {
const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
const DataLayout &DL = L->getHeader()->getDataLayout();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need an Loop::getDataLayout?

Co-authored-by: Yingwei Zheng <dtcxzyw@qq.com>
Copy link
Contributor

@fhahn fhahn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, this is a nice convenience helper!

@nikic nikic merged commit 2d209d9 into llvm:main Jun 27, 2024
5 of 6 checks passed
@nikic nikic deleted the data-layout-helpers branch June 27, 2024 14:38
nikic added a commit that referenced this pull request Jun 28, 2024
Similar to #96902, this adds
`getDataLayout()` helpers to Function and GlobalValue, replacing the
current `getParent()->getDataLayout()` pattern.
lravenclaw pushed a commit to lravenclaw/llvm-project that referenced this pull request Jul 3, 2024
…96902)

This is a helper to avoid writing `getModule()->getDataLayout()`. I
regularly try to use this method only to remember it doesn't exist...

`getModule()->getDataLayout()` is also a common (the most common?)
reason why code has to include the Module.h header.
lravenclaw pushed a commit to lravenclaw/llvm-project that referenced this pull request Jul 3, 2024
)

Similar to llvm#96902, this adds
`getDataLayout()` helpers to Function and GlobalValue, replacing the
current `getParent()->getDataLayout()` pattern.
AlexisPerry pushed a commit to llvm-project-tlp/llvm-project that referenced this pull request Jul 9, 2024
…96902)

This is a helper to avoid writing `getModule()->getDataLayout()`. I
regularly try to use this method only to remember it doesn't exist...

`getModule()->getDataLayout()` is also a common (the most common?)
reason why code has to include the Module.h header.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants