[Mlir-commits] [mlir] ecc201f - [IRBuilder] Accept Module instead of LLVMContext in ctor (#229430)

llvmlistbot at llvm.org llvmlistbot at llvm.org
Wed Oct 7 01:20:44 PDT 2026


Author: Nikita Popov
Date: 2026-10-07T08:20:33Z
New Revision: ecc201f1d0d5372d0a3a77a516c0530e880170fb

URL: https://github.com/llvm/llvm-project/commit/ecc201f1d0d5372d0a3a77a516c0530e880170fb
DIFF: https://github.com/llvm/llvm-project/commit/ecc201f1d0d5372d0a3a77a516c0530e880170fb.diff

LOG: [IRBuilder] Accept Module instead of LLVMContext in ctor (#229430)

This adds new constructor overloads, which accept `Module &` instead of
`LLVMContext &` in the ctor, and replaces nearly all usages of the old
constructors. A few more complicated cases (C API, SandboxIR context and
one unit test) are left alone for now.

The intent is to remove the old LLVMContext constructors and make
availability of the Module required at time of construction (either
directly passed to the ctor or implied by the insertion point).

The motivation for this is to ensure that IRBuilder always has an
available DataLayout. IRBuilder used to be DL-agnostic, but at this
point we've accumulated a number of key places which require a data
layout, and get it from the insertion point instead. This is not great,
because the insertion point is not actually required to be set when
producing instructions (they just won't be inserted).

Additionally, not having a required DataLayout also introduces the
ConstantFolder (default) vs TargetFolder dichotomy, and is also a big
part of the reason why we still have separate ConstantFold and
ConstantFolding APIs that differ in DL-awareness.

Rather than accepting LLVMContext + DataLayout, this PR proposes to
accept Module instead. This is both a matter of convenience, but also
some future-proofing: For example, if we decide that constant
expressions should be owned by the Module instead of LLVMContext (which
they should be...) it will be easier to make such a change in the
future. Additionally, we have API's like
`IRBuilder::CreateGlobalString()`, which currently accept an explicit
Module, because IRBuilder itself is not module-aware.

Added: 
    

Modified: 
    clang/lib/CodeGen/CGBuilder.h
    clang/lib/CodeGen/CGHLSLRuntime.cpp
    llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/toy.cpp
    llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/toy.cpp
    llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/toy.cpp
    llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/toy.cpp
    llvm/examples/Kaleidoscope/Chapter3/toy.cpp
    llvm/examples/Kaleidoscope/Chapter4/toy.cpp
    llvm/examples/Kaleidoscope/Chapter5/toy.cpp
    llvm/examples/Kaleidoscope/Chapter6/toy.cpp
    llvm/examples/Kaleidoscope/Chapter7/toy.cpp
    llvm/examples/Kaleidoscope/Chapter8/toy.cpp
    llvm/examples/Kaleidoscope/Chapter9/toy.cpp
    llvm/include/llvm/Analysis/MemoryBuiltins.h
    llvm/include/llvm/Analysis/ScalarEvolution.h
    llvm/include/llvm/Frontend/HLSL/RootSignatureMetadata.h
    llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
    llvm/include/llvm/IR/IRBuilder.h
    llvm/include/llvm/Transforms/IPO/InstrumentorUtils.h
    llvm/include/llvm/Transforms/InstCombine/InstCombiner.h
    llvm/include/llvm/Transforms/Utils/EscapeEnumerator.h
    llvm/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h
    llvm/lib/Analysis/MemoryBuiltins.cpp
    llvm/lib/CodeGen/InlineAsmPrepare.cpp
    llvm/lib/CodeGen/InterleavedAccessPass.cpp
    llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp
    llvm/lib/CodeGen/TypePromotion.cpp
    llvm/lib/CodeGen/WasmEHPrepare.cpp
    llvm/lib/ExecutionEngine/Orc/ReOptimizeLayer.cpp
    llvm/lib/ExecutionEngine/Orc/Speculation.cpp
    llvm/lib/Frontend/HLSL/RootSignatureMetadata.cpp
    llvm/lib/IR/AutoUpgrade.cpp
    llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp
    llvm/lib/Target/AMDGPU/AMDGPULowerBufferFatPointers.cpp
    llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp
    llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp
    llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp
    llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp
    llvm/lib/Target/BPF/BPFCheckAndAdjustIR.cpp
    llvm/lib/Target/DirectX/DXILDataScalarization.cpp
    llvm/lib/Target/DirectX/DXILOpBuilder.cpp
    llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
    llvm/lib/Target/Hexagon/HexagonISelLowering.cpp
    llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
    llvm/lib/Target/PowerPC/PPCBoolRetToInt.cpp
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
    llvm/lib/Target/SPIRV/SPIRVLegalizePointerCast.cpp
    llvm/lib/Target/SPIRV/SPIRVPrepareFunctions.cpp
    llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
    llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
    llvm/lib/Transforms/Coroutines/CoroCleanup.cpp
    llvm/lib/Transforms/Coroutines/CoroCloner.h
    llvm/lib/Transforms/Coroutines/CoroEarly.cpp
    llvm/lib/Transforms/Coroutines/CoroFrame.cpp
    llvm/lib/Transforms/Coroutines/CoroSplit.cpp
    llvm/lib/Transforms/IPO/AttributorAttributes.cpp
    llvm/lib/Transforms/IPO/ExpandVariadics.cpp
    llvm/lib/Transforms/IPO/GlobalOpt.cpp
    llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
    llvm/lib/Transforms/InstCombine/InstCombineInternal.h
    llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp
    llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
    llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
    llvm/lib/Transforms/Instrumentation/CopyProf.cpp
    llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
    llvm/lib/Transforms/Instrumentation/MemProfInstrumentation.cpp
    llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
    llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
    llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
    llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
    llvm/lib/Transforms/Instrumentation/TypeSanitizer.cpp
    llvm/lib/Transforms/Scalar/SROA.cpp
    llvm/lib/Transforms/Utils/InlineFunction.cpp
    llvm/lib/Transforms/Utils/LoopVersioning.cpp
    llvm/lib/Transforms/Utils/ModuleUtils.cpp
    llvm/lib/Transforms/Utils/SimplifyCFG.cpp
    llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp
    llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
    llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
    llvm/lib/Transforms/Vectorize/VectorCombine.cpp
    llvm/tools/lli/lli.cpp
    llvm/unittests/Analysis/BasicAliasAnalysisTest.cpp
    llvm/unittests/Analysis/MemorySSATest.cpp
    llvm/unittests/Analysis/SparsePropagation.cpp
    llvm/unittests/Analysis/ValueTrackingTest.cpp
    llvm/unittests/ExecutionEngine/Orc/ReOptimizeLayerTest.cpp
    llvm/unittests/IR/IRBuilderTest.cpp
    llvm/unittests/IR/InstructionsTest.cpp
    llvm/unittests/Transforms/Utils/CloningTest.cpp
    llvm/unittests/Transforms/Utils/FunctionComparatorTest.cpp
    llvm/unittests/Transforms/Utils/IntegerDivisionTest.cpp
    llvm/unittests/Transforms/Utils/LocalTest.cpp
    llvm/unittests/Transforms/Utils/SSAUpdaterBulkTest.cpp
    mlir/lib/ExecutionEngine/ExecutionEngine.cpp
    mlir/lib/Target/LLVMIR/Dialect/GPU/SelectObjectAttr.cpp
    mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
    polly/lib/CodeGen/PerfMonitor.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/CodeGen/CGBuilder.h b/clang/lib/CodeGen/CGBuilder.h
index 18e738f10ba3b7..2dc70a9071e967 100644
--- a/clang/lib/CodeGen/CGBuilder.h
+++ b/clang/lib/CodeGen/CGBuilder.h
@@ -92,11 +92,13 @@ class CGBuilderTy : public CGBuilderBaseTy {
 
 public:
   CGBuilderTy(const CodeGenModule &CGM, llvm::LLVMContext &C)
-      : CGBuilderBaseTy(C, llvm::TargetFolder(CGM.getDataLayout())),
+      : CGBuilderBaseTy(CGM.getModule(),
+                        llvm::TargetFolder(CGM.getDataLayout())),
         TypeCache(CGM) {}
   CGBuilderTy(const CodeGenModule &CGM, llvm::LLVMContext &C,
               const CGBuilderInserterTy &Inserter)
-      : CGBuilderBaseTy(C, llvm::TargetFolder(CGM.getDataLayout()), Inserter),
+      : CGBuilderBaseTy(CGM.getModule(),
+                        llvm::TargetFolder(CGM.getDataLayout()), Inserter),
         TypeCache(CGM) {}
   CGBuilderTy(const CodeGenModule &CGM, llvm::Instruction *I)
       : CGBuilderBaseTy(I->getIterator(),

diff  --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index 52fde18dc3ebdb..b69fbc907293aa 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -78,7 +78,7 @@ void addDxilValVersion(StringRef ValVersionStr, llvm::Module &M) {
   uint64_t Minor = *Version.getMinor();
 
   auto &Ctx = M.getContext();
-  IRBuilder<> B(M.getContext());
+  IRBuilder<> B(M);
   MDNode *Val = MDNode::get(Ctx, {ConstantAsMetadata::get(B.getInt32(Major)),
                                   ConstantAsMetadata::get(B.getInt32(Minor))});
   StringRef DXILValKey = "dx.valver";
@@ -91,7 +91,7 @@ void addRootSignatureMD(llvm::dxbc::RootSignatureVersion RootSigVer,
                         llvm::Function *Fn, llvm::Module &M) {
   auto &Ctx = M.getContext();
 
-  llvm::hlsl::rootsig::MetadataBuilder RSBuilder(Ctx, Elements);
+  llvm::hlsl::rootsig::MetadataBuilder RSBuilder(M, Elements);
   MDNode *RootSignature = RSBuilder.BuildRootSignature();
 
   ConstantAsMetadata *Version = ConstantAsMetadata::get(ConstantInt::get(
@@ -1075,7 +1075,7 @@ static Value *buildVectorInput(IRBuilder<> &B, Function *F, llvm::Type *Ty) {
 static void addSPIRVBuiltinDecoration(llvm::GlobalVariable *GV,
                                       unsigned BuiltIn) {
   LLVMContext &Ctx = GV->getContext();
-  IRBuilder<> B(GV->getContext());
+  IRBuilder<> B(*GV->getParent());
   MDNode *Operands = MDNode::get(
       Ctx,
       {ConstantAsMetadata::get(B.getInt32(/* Spirv::Decoration::BuiltIn */ 11)),
@@ -1086,7 +1086,7 @@ static void addSPIRVBuiltinDecoration(llvm::GlobalVariable *GV,
 
 static void addLocationDecoration(llvm::GlobalVariable *GV, unsigned Location) {
   LLVMContext &Ctx = GV->getContext();
-  IRBuilder<> B(GV->getContext());
+  IRBuilder<> B(*GV->getParent());
   MDNode *Operands =
       MDNode::get(Ctx, {ConstantAsMetadata::get(B.getInt32(/* Location */ 30)),
                         ConstantAsMetadata::get(B.getInt32(Location))});

diff  --git a/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/toy.cpp b/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/toy.cpp
index ed0770bb3d5a59..92e64b34c2150b 100644
--- a/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/toy.cpp
+++ b/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter1/toy.cpp
@@ -1108,7 +1108,7 @@ static void InitializeModule() {
   TheModule->setDataLayout(TheJIT->getDataLayout());
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 }
 
 static void HandleDefinition() {

diff  --git a/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/toy.cpp b/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/toy.cpp
index ed0770bb3d5a59..92e64b34c2150b 100644
--- a/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/toy.cpp
+++ b/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter2/toy.cpp
@@ -1108,7 +1108,7 @@ static void InitializeModule() {
   TheModule->setDataLayout(TheJIT->getDataLayout());
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 }
 
 static void HandleDefinition() {

diff  --git a/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/toy.cpp b/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/toy.cpp
index ed0770bb3d5a59..92e64b34c2150b 100644
--- a/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/toy.cpp
+++ b/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter3/toy.cpp
@@ -1108,7 +1108,7 @@ static void InitializeModule() {
   TheModule->setDataLayout(TheJIT->getDataLayout());
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 }
 
 static void HandleDefinition() {

diff  --git a/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/toy.cpp b/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/toy.cpp
index 1a7f1475330a80..a4cfc4b9d5b7b5 100644
--- a/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/toy.cpp
+++ b/llvm/examples/Kaleidoscope/BuildingAJIT/Chapter4/toy.cpp
@@ -1099,7 +1099,7 @@ static void InitializeModule() {
   TheModule->setDataLayout(TheJIT->getDataLayout());
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 }
 
 ThreadSafeModule irgenAndTakeOwnership(FunctionAST &FnAST,

diff  --git a/llvm/examples/Kaleidoscope/Chapter3/toy.cpp b/llvm/examples/Kaleidoscope/Chapter3/toy.cpp
index 66973ee3ebcfae..c23f21e3bc0c0c 100644
--- a/llvm/examples/Kaleidoscope/Chapter3/toy.cpp
+++ b/llvm/examples/Kaleidoscope/Chapter3/toy.cpp
@@ -527,7 +527,7 @@ static void InitializeModule() {
   TheModule = std::make_unique<Module>("my cool jit", *TheContext);
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 }
 
 static void HandleDefinition() {

diff  --git a/llvm/examples/Kaleidoscope/Chapter4/toy.cpp b/llvm/examples/Kaleidoscope/Chapter4/toy.cpp
index 0f58391c506679..b73dea67511a30 100644
--- a/llvm/examples/Kaleidoscope/Chapter4/toy.cpp
+++ b/llvm/examples/Kaleidoscope/Chapter4/toy.cpp
@@ -566,7 +566,7 @@ static void InitializeModuleAndManagers() {
   TheModule->setDataLayout(TheJIT->getDataLayout());
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 
   // Create new pass and analysis managers.
   TheFPM = std::make_unique<FunctionPassManager>();

diff  --git a/llvm/examples/Kaleidoscope/Chapter5/toy.cpp b/llvm/examples/Kaleidoscope/Chapter5/toy.cpp
index 7117eaf4982b03..c33e4da68d8756 100644
--- a/llvm/examples/Kaleidoscope/Chapter5/toy.cpp
+++ b/llvm/examples/Kaleidoscope/Chapter5/toy.cpp
@@ -840,7 +840,7 @@ static void InitializeModuleAndManagers() {
   TheModule->setDataLayout(TheJIT->getDataLayout());
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 
   // Create new pass and analysis managers.
   TheFPM = std::make_unique<FunctionPassManager>();

diff  --git a/llvm/examples/Kaleidoscope/Chapter6/toy.cpp b/llvm/examples/Kaleidoscope/Chapter6/toy.cpp
index cb7b6cc8651c13..18cba9447cf04c 100644
--- a/llvm/examples/Kaleidoscope/Chapter6/toy.cpp
+++ b/llvm/examples/Kaleidoscope/Chapter6/toy.cpp
@@ -959,7 +959,7 @@ static void InitializeModuleAndManagers() {
   TheModule->setDataLayout(TheJIT->getDataLayout());
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 
   // Create new pass and analysis managers.
   TheFPM = std::make_unique<FunctionPassManager>();

diff  --git a/llvm/examples/Kaleidoscope/Chapter7/toy.cpp b/llvm/examples/Kaleidoscope/Chapter7/toy.cpp
index 21c504a7357b80..6a8c4840bf4f5c 100644
--- a/llvm/examples/Kaleidoscope/Chapter7/toy.cpp
+++ b/llvm/examples/Kaleidoscope/Chapter7/toy.cpp
@@ -1127,7 +1127,7 @@ static void InitializeModuleAndManagers() {
   TheModule->setDataLayout(TheJIT->getDataLayout());
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 
   // Create new pass and analysis managers.
   TheFPM = std::make_unique<FunctionPassManager>();

diff  --git a/llvm/examples/Kaleidoscope/Chapter8/toy.cpp b/llvm/examples/Kaleidoscope/Chapter8/toy.cpp
index 2634c1891c8fc1..d8fb8e8cd1d599 100644
--- a/llvm/examples/Kaleidoscope/Chapter8/toy.cpp
+++ b/llvm/examples/Kaleidoscope/Chapter8/toy.cpp
@@ -1111,7 +1111,7 @@ static void InitializeModuleAndPassManager() {
   TheModule = std::make_unique<Module>("my cool jit", *TheContext);
 
   // Create a new builder for the module.
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 }
 
 static void HandleDefinition() {

diff  --git a/llvm/examples/Kaleidoscope/Chapter9/toy.cpp b/llvm/examples/Kaleidoscope/Chapter9/toy.cpp
index d25c776401b995..1bd7f8bc0ae493 100644
--- a/llvm/examples/Kaleidoscope/Chapter9/toy.cpp
+++ b/llvm/examples/Kaleidoscope/Chapter9/toy.cpp
@@ -1325,7 +1325,7 @@ static void InitializeModule() {
   TheModule = std::make_unique<Module>("my cool jit", *TheContext);
   TheModule->setDataLayout(TheJIT->getDataLayout());
 
-  Builder = std::make_unique<IRBuilder<>>(*TheContext);
+  Builder = std::make_unique<IRBuilder<>>(*TheModule);
 }
 
 static void HandleDefinition() {

diff  --git a/llvm/include/llvm/Analysis/MemoryBuiltins.h b/llvm/include/llvm/Analysis/MemoryBuiltins.h
index ebe644cee53e12..065dc00da2439e 100644
--- a/llvm/include/llvm/Analysis/MemoryBuiltins.h
+++ b/llvm/include/llvm/Analysis/MemoryBuiltins.h
@@ -354,9 +354,7 @@ class ObjectSizeOffsetEvaluator
   SizeOffsetValue compute_(Value *V);
 
 public:
-  LLVM_ABI ObjectSizeOffsetEvaluator(const DataLayout &DL,
-                                     const TargetLibraryInfo *TLI,
-                                     LLVMContext &Context,
+  LLVM_ABI ObjectSizeOffsetEvaluator(Module &M, const TargetLibraryInfo *TLI,
                                      ObjectSizeOpts EvalOpts = {});
 
   static SizeOffsetValue unknown() { return SizeOffsetValue(); }

diff  --git a/llvm/include/llvm/Analysis/ScalarEvolution.h b/llvm/include/llvm/Analysis/ScalarEvolution.h
index 79944d6870158a..9ef4d0b0542f33 100644
--- a/llvm/include/llvm/Analysis/ScalarEvolution.h
+++ b/llvm/include/llvm/Analysis/ScalarEvolution.h
@@ -665,6 +665,8 @@ class ScalarEvolution {
 
   LLVMContext &getContext() const { return F.getContext(); }
 
+  Module &getModule() const { return *F.getParent(); }
+
   /// Test if values of the given type are analyzable within the SCEV
   /// framework. This primarily includes integer types, and it can optionally
   /// include pointer types if the ScalarEvolution class has access to

diff  --git a/llvm/include/llvm/Frontend/HLSL/RootSignatureMetadata.h b/llvm/include/llvm/Frontend/HLSL/RootSignatureMetadata.h
index 509c0b816f79ee..b3b5fd5a3a0d17 100644
--- a/llvm/include/llvm/Frontend/HLSL/RootSignatureMetadata.h
+++ b/llvm/include/llvm/Frontend/HLSL/RootSignatureMetadata.h
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Frontend/HLSL/HLSLRootSignature.h"
 #include "llvm/IR/Constants.h"
+#include "llvm/IR/Module.h"
 #include "llvm/MC/DXContainerRootSignature.h"
 #include "llvm/Support/Compiler.h"
 
@@ -44,8 +45,8 @@ class RootSignatureValidationError
 
 class MetadataBuilder {
 public:
-  MetadataBuilder(llvm::LLVMContext &Ctx, ArrayRef<RootElement> Elements)
-      : Ctx(Ctx), Elements(Elements) {}
+  MetadataBuilder(llvm::Module &M, ArrayRef<RootElement> Elements)
+      : M(M), Ctx(M.getContext()), Elements(Elements) {}
 
   /// Iterates through elements and dispatches onto the correct Build* method
   ///
@@ -62,6 +63,7 @@ class MetadataBuilder {
   MDNode *BuildDescriptorTableClause(const DescriptorTableClause &Clause);
   MDNode *BuildStaticSampler(const StaticSampler &Sampler);
 
+  llvm::Module &M;
   llvm::LLVMContext &Ctx;
   ArrayRef<RootElement> Elements;
   SmallVector<Metadata *> GeneratedMetadata;

diff  --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index 5acbb692483093..4cd5b88c645403 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -513,8 +513,8 @@ class OpenMPIRBuilder {
   /// Create a new OpenMPIRBuilder operating on the given module \p M. This will
   /// not have an effect on \p M (see initialize)
   OpenMPIRBuilder(Module &M)
-      : M(M), Builder(M.getContext()), OffloadInfoManager(this),
-        T(M.getTargetTriple()), IsFinalized(false) {}
+      : M(M), Builder(M), OffloadInfoManager(this), T(M.getTargetTriple()),
+        IsFinalized(false) {}
   LLVM_ABI ~OpenMPIRBuilder();
 
   class AtomicInfo : public llvm::AtomicInfo {

diff  --git a/llvm/include/llvm/IR/IRBuilder.h b/llvm/include/llvm/IR/IRBuilder.h
index bbeefa8ef90c02..c370433331d5ae 100644
--- a/llvm/include/llvm/IR/IRBuilder.h
+++ b/llvm/include/llvm/IR/IRBuilder.h
@@ -34,6 +34,7 @@
 #include "llvm/IR/Instructions.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
 #include "llvm/IR/Operator.h"
 #include "llvm/IR/Type.h"
 #include "llvm/IR/Value.h"
@@ -2910,6 +2911,7 @@ class IRBuilder : public IRBuilderBase {
   InserterTy Inserter;
 
 public:
+  // TODO: Deprecate ctors accepting LLVMContext.
   IRBuilder(LLVMContext &C, FolderTy Folder, InserterTy Inserter)
       : IRBuilderBase(C, this->Folder, this->Inserter), Folder(Folder),
         Inserter(Inserter) {}
@@ -2920,6 +2922,17 @@ class IRBuilder : public IRBuilderBase {
   explicit IRBuilder(LLVMContext &C)
       : IRBuilderBase(C, this->Folder, this->Inserter) {}
 
+  IRBuilder(Module &M, FolderTy Folder, InserterTy Inserter)
+      : IRBuilderBase(M.getContext(), this->Folder, this->Inserter),
+        Folder(Folder), Inserter(Inserter) {}
+
+  IRBuilder(Module &M, FolderTy Folder)
+      : IRBuilderBase(M.getContext(), this->Folder, this->Inserter),
+        Folder(Folder) {}
+
+  explicit IRBuilder(Module &M)
+      : IRBuilderBase(M.getContext(), this->Folder, this->Inserter) {}
+
   explicit IRBuilder(BasicBlock *TheBB, FolderTy Folder)
       : IRBuilderBase(TheBB->getContext(), this->Folder, this->Inserter),
         Folder(Folder) {
@@ -2981,6 +2994,11 @@ template <typename FolderTy, typename InserterTy>
 IRBuilder(LLVMContext &, FolderTy, InserterTy)
     -> IRBuilder<FolderTy, InserterTy>;
 IRBuilder(LLVMContext &) -> IRBuilder<>;
+template <typename FolderTy, typename InserterTy>
+IRBuilder(Module &, FolderTy, InserterTy) -> IRBuilder<FolderTy, InserterTy>;
+template <typename FolderTy>
+IRBuilder(Module &, FolderTy) -> IRBuilder<FolderTy>;
+IRBuilder(Module &) -> IRBuilder<>;
 template <typename FolderTy>
 IRBuilder(BasicBlock *, FolderTy) -> IRBuilder<FolderTy>;
 IRBuilder(BasicBlock *) -> IRBuilder<>;

diff  --git a/llvm/include/llvm/Transforms/IPO/InstrumentorUtils.h b/llvm/include/llvm/Transforms/IPO/InstrumentorUtils.h
index 44c6c870578503..c8b66e7719fb5c 100644
--- a/llvm/include/llvm/Transforms/IPO/InstrumentorUtils.h
+++ b/llvm/include/llvm/Transforms/IPO/InstrumentorUtils.h
@@ -38,7 +38,7 @@ struct InstrumentorIRBuilderTy {
   /// Construct an IR builder for the module \p M.
   InstrumentorIRBuilderTy(Module &M)
       : M(M), Ctx(M.getContext()),
-        IRB(Ctx, ConstantFolder(),
+        IRB(M, ConstantFolder(),
             // Save the inserted instructions in a structure.
             IRBuilderCallbackInserter(
                 [&](Instruction *I) { NewInsts[I] = Epoch; })) {}

diff  --git a/llvm/include/llvm/Transforms/InstCombine/InstCombiner.h b/llvm/include/llvm/Transforms/InstCombine/InstCombiner.h
index ce9d42c58e3f25..42924a0648efc7 100644
--- a/llvm/include/llvm/Transforms/InstCombine/InstCombiner.h
+++ b/llvm/include/llvm/Transforms/InstCombine/InstCombiner.h
@@ -123,7 +123,7 @@ class LLVM_LIBRARY_VISIBILITY InstCombiner {
                const DataLayout &DL,
                ReversePostOrderTraversal<BasicBlock *> &RPOT)
       : TTIForTargetIntrinsicsOnly(TTI),
-        Builder(F.getContext(), TargetFolder(DL),
+        Builder(*F.getParent(), TargetFolder(DL),
                 IRBuilderInstCombineInserter(*this)),
         Worklist(Worklist), F(F), MinimizeSize(F.hasMinSize()), AA(AA), AC(AC),
         TLI(TLI), DT(DT), DL(DL),
@@ -362,6 +362,7 @@ class LLVM_LIBRARY_VISIBILITY InstCombiner {
 
   void addToWorklist(Instruction *I) { Worklist.push(I); }
 
+  Module &getModule() const { return *F.getParent(); }
   AssumptionCache &getAssumptionCache() const { return AC; }
   TargetLibraryInfo &getTargetLibraryInfo() const { return TLI; }
   DominatorTree &getDominatorTree() const { return DT; }

diff  --git a/llvm/include/llvm/Transforms/Utils/EscapeEnumerator.h b/llvm/include/llvm/Transforms/Utils/EscapeEnumerator.h
index f3f7e9743fa7b1..660dbd47f9ad8c 100644
--- a/llvm/include/llvm/Transforms/Utils/EscapeEnumerator.h
+++ b/llvm/include/llvm/Transforms/Utils/EscapeEnumerator.h
@@ -41,7 +41,7 @@ class EscapeEnumerator {
   EscapeEnumerator(Function &F, const char *N = "cleanup",
                    bool HandleExceptions = true, DomTreeUpdater *DTU = nullptr)
       : F(F), CleanupBBName(N), StateBB(F.begin()), StateE(F.end()),
-        Builder(F.getContext()), HandleExceptions(HandleExceptions), DTU(DTU) {}
+        Builder(*F.getParent()), HandleExceptions(HandleExceptions), DTU(DTU) {}
 
   LLVM_ABI IRBuilder<> *Next();
 };

diff  --git a/llvm/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h b/llvm/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h
index e72235fbf6d42c..181f9dfe4247f0 100644
--- a/llvm/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h
+++ b/llvm/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h
@@ -196,7 +196,7 @@ class SCEVExpander : public SCEVUseVisitor<SCEVExpander, Value *> {
       : SE(SE), DL(SE.getDataLayout()), IVName(Name),
         PreserveLCSSA(PreserveLCSSA), IVIncInsertLoop(nullptr),
         IVIncInsertPos(nullptr), CanonicalMode(true), LSRMode(false),
-        Builder(SE.getContext(), InstSimplifyFolder(DL),
+        Builder(SE.getModule(), InstSimplifyFolder(DL),
                 IRBuilderCallbackInserter(
                     [this](Instruction *I) { rememberInstruction(I); })) {
 #if LLVM_ENABLE_ABI_BREAKING_CHECKS

diff  --git a/llvm/lib/Analysis/MemoryBuiltins.cpp b/llvm/lib/Analysis/MemoryBuiltins.cpp
index 2a8b4e7d81910c..c9eaa82802fe62 100644
--- a/llvm/lib/Analysis/MemoryBuiltins.cpp
+++ b/llvm/lib/Analysis/MemoryBuiltins.cpp
@@ -673,8 +673,7 @@ Value *llvm::lowerObjectSizeCall(
         isUIntN(ResultType->getBitWidth(), Size))
       return ConstantInt::get(ResultType, Size);
   } else {
-    LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
-    ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
+    ObjectSizeOffsetEvaluator Eval(*ObjectSize->getModule(), TLI, EvalOptions);
     SizeOffsetValue SizeOffsetPair = Eval.compute(ObjectSize->getArgOperand(0));
 
     if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
@@ -1231,10 +1230,9 @@ SizeOffsetValue::SizeOffsetValue(const SizeOffsetWeakTrackingVH &SOT)
     : SizeOffsetType(SOT.Size, SOT.Offset) {}
 
 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
-    const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
-    ObjectSizeOpts EvalOpts)
-    : DL(DL), TLI(TLI), Context(Context),
-      Builder(Context, TargetFolder(DL),
+    Module &M, const TargetLibraryInfo *TLI, ObjectSizeOpts EvalOpts)
+    : DL(M.getDataLayout()), TLI(TLI), Context(M.getContext()),
+      Builder(M, TargetFolder(DL),
               IRBuilderCallbackInserter(
                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
       EvalOpts(EvalOpts) {

diff  --git a/llvm/lib/CodeGen/InlineAsmPrepare.cpp b/llvm/lib/CodeGen/InlineAsmPrepare.cpp
index 9587bf34649c1b..ca58eb0e8d794f 100644
--- a/llvm/lib/CodeGen/InlineAsmPrepare.cpp
+++ b/llvm/lib/CodeGen/InlineAsmPrepare.cpp
@@ -173,7 +173,7 @@ static bool splitCriticalEdges(CallBrInst *CBR, DominatorTree *DT) {
 static bool insertIntrinsicCalls(CallBrInst *CBR, DominatorTree &DT) {
   bool Changed = false;
   SmallPtrSet<const BasicBlock *, 4> Visited;
-  IRBuilder<> Builder(CBR->getContext());
+  IRBuilder<> Builder(*CBR->getModule());
 
   if (!CBR->getNumIndirectDests())
     return false;

diff  --git a/llvm/lib/CodeGen/InterleavedAccessPass.cpp b/llvm/lib/CodeGen/InterleavedAccessPass.cpp
index 5498ce1d816475..4ece88a0014bc5 100644
--- a/llvm/lib/CodeGen/InterleavedAccessPass.cpp
+++ b/llvm/lib/CodeGen/InterleavedAccessPass.cpp
@@ -490,7 +490,7 @@ bool InterleavedAccessImpl::tryReplaceExtracts(
   }
 
   // Finally, perform the replacements.
-  IRBuilder<> Builder(Extracts[0]->getContext());
+  IRBuilder<> Builder(*Extracts[0]->getModule());
   for (auto &Replacement : ReplacementMap) {
     auto *Extract = Replacement.first;
     auto *Vector = Replacement.second.first;

diff  --git a/llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp b/llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp
index af445af9403ef3..da9b469249977e 100644
--- a/llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp
+++ b/llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp
@@ -93,7 +93,7 @@ bool MachineSanitizerBinaryMetadata::run(MachineFunction &MF) {
     return false;
   // Non-zero size, update metadata.
   auto &F = MF.getFunction();
-  IRBuilder<> IRB(F.getContext());
+  IRBuilder<> IRB(*F.getParent());
   MDBuilder MDB(F.getContext());
   // Keep the features and append size of stack args to the metadata.
   APInt NewFeatures = Features->getUniqueInteger();

diff  --git a/llvm/lib/CodeGen/TypePromotion.cpp b/llvm/lib/CodeGen/TypePromotion.cpp
index 2736ff3f8a299d..77ba91e55ba628 100644
--- a/llvm/lib/CodeGen/TypePromotion.cpp
+++ b/llvm/lib/CodeGen/TypePromotion.cpp
@@ -102,6 +102,7 @@ static cl::opt<bool> DisablePromotion("disable-type-promotion", cl::Hidden,
 
 namespace {
 class IRPromoter {
+  Module &M;
   LLVMContext &Ctx;
   unsigned PromotedWidth = 0;
   SetVector<Value *> &Visited;
@@ -122,12 +123,13 @@ class IRPromoter {
   void Cleanup();
 
 public:
-  IRPromoter(LLVMContext &C, unsigned Width, SetVector<Value *> &visited,
+  IRPromoter(Module &M, unsigned Width, SetVector<Value *> &visited,
              SetVector<Value *> &sources, SetVector<Instruction *> &sinks,
              SmallPtrSetImpl<Instruction *> &wrap,
              SmallPtrSetImpl<Instruction *> &instsToRemove)
-      : Ctx(C), PromotedWidth(Width), Visited(visited), Sources(sources),
-        Sinks(sinks), SafeWrap(wrap), InstsToRemove(instsToRemove) {
+      : M(M), Ctx(M.getContext()), PromotedWidth(Width), Visited(visited),
+        Sources(sources), Sinks(sinks), SafeWrap(wrap),
+        InstsToRemove(instsToRemove) {
     ExtTy = IntegerType::get(Ctx, PromotedWidth);
   }
 
@@ -137,6 +139,7 @@ class IRPromoter {
 class TypePromotionImpl {
   unsigned TypeSize = 0;
   const TargetLowering *TLI = nullptr;
+  Module *M = nullptr;
   LLVMContext *Ctx = nullptr;
   unsigned RegisterBitWidth = 0;
   SmallPtrSet<Value *, 16> AllVisited;
@@ -444,7 +447,7 @@ void IRPromoter::ReplaceAllUsersOfWith(Value *From, Value *To) {
 }
 
 void IRPromoter::ExtendSources() {
-  IRBuilder<> Builder{Ctx};
+  IRBuilder<> Builder(M);
 
   auto InsertZExt = [&](Value *V, BasicBlock::iterator InsertPt) {
     assert(V->getType() != ExtTy && "zext already extends to i32");
@@ -555,7 +558,7 @@ void IRPromoter::PromoteTree() {
 void IRPromoter::TruncateSinks() {
   LLVM_DEBUG(dbgs() << "IR Promotion: Fixing up the sinks:\n");
 
-  IRBuilder<> Builder{Ctx};
+  IRBuilder<> Builder(M);
 
   auto InsertTrunc = [&](Value *V, Type *TruncTy) -> Instruction * {
     if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
@@ -660,7 +663,7 @@ void IRPromoter::Cleanup() {
 
 void IRPromoter::ConvertTruncs() {
   LLVM_DEBUG(dbgs() << "IR Promotion: Converting truncs..\n");
-  IRBuilder<> Builder{Ctx};
+  IRBuilder<> Builder(M);
 
   for (auto *V : Visited) {
     if (!isa<TruncInst>(V) || isTruncToI1(V) || Sources.count(V))
@@ -941,7 +944,7 @@ bool TypePromotionImpl::TryToPromote(Value *V, unsigned PromotedWidth,
       (ToPromote < 2 || (Blocks.size() == 1 && NonFreeArgs > SafeWrap.size())))
     return false;
 
-  IRPromoter Promoter(*Ctx, PromotedWidth, CurrentVisited, Sources, Sinks,
+  IRPromoter Promoter(*M, PromotedWidth, CurrentVisited, Sources, Sinks,
                       SafeWrap, InstsToRemove);
   Promoter.Mutate();
   return true;
@@ -964,6 +967,7 @@ bool TypePromotionImpl::run(Function &F, const TargetMachine *TM,
   TLI = SubtargetInfo->getTargetLowering();
   RegisterBitWidth =
       TTI.getRegisterBitWidth(TargetTransformInfo::RGK_Scalar).getFixedValue();
+  M = F.getParent();
   Ctx = &F.getContext();
 
   // Return the preferred integer width of the instruction, or zero if we

diff  --git a/llvm/lib/CodeGen/WasmEHPrepare.cpp b/llvm/lib/CodeGen/WasmEHPrepare.cpp
index 76cdac4609e382..9356287b339837 100644
--- a/llvm/lib/CodeGen/WasmEHPrepare.cpp
+++ b/llvm/lib/CodeGen/WasmEHPrepare.cpp
@@ -145,7 +145,7 @@ INITIALIZE_PASS_END(WasmEHPrepare, DEBUG_TYPE, "Prepare WebAssembly exceptions",
 FunctionPass *llvm::createWasmEHPass() { return new WasmEHPrepare(); }
 
 bool WasmEHPrepare::doInitialization(Module &M) {
-  IRBuilder<> IRB(M.getContext());
+  IRBuilder<> IRB(M);
   P.LPadContextTy = StructType::get(IRB.getInt32Ty(), // lpad_index
                                     IRB.getPtrTy(),   // lsda
                                     IRB.getInt32Ty()  // selector
@@ -176,7 +176,7 @@ bool WasmEHPrepareImpl::runOnFunction(Function &F) {
 
 bool WasmEHPrepareImpl::prepareThrows(Function &F) {
   Module &M = *F.getParent();
-  IRBuilder<> IRB(F.getContext());
+  IRBuilder<> IRB(M);
   bool Changed = false;
 
   // wasm.throw() intinsic, which will be lowered to wasm 'throw' instruction.

diff  --git a/llvm/lib/ExecutionEngine/Orc/ReOptimizeLayer.cpp b/llvm/lib/ExecutionEngine/Orc/ReOptimizeLayer.cpp
index cb73ee1a61e330..92e87f58c1a1c9 100644
--- a/llvm/lib/ExecutionEngine/Orc/ReOptimizeLayer.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/ReOptimizeLayer.cpp
@@ -59,7 +59,7 @@ Error ReOptimizeLayer::addOrcRTLiteSupport(JITDylib &PlatformJD,
   auto Mod = std::make_unique<Module>("orc-rt-lite-reoptimize.ll", *Ctx);
   Mod->setDataLayout(DL);
 
-  IRBuilder<> Builder(*Ctx);
+  IRBuilder<> Builder(*Mod);
 
   // Create basic types portably
   Type *VoidTy = Type::getVoidTy(*Ctx);

diff  --git a/llvm/lib/ExecutionEngine/Orc/Speculation.cpp b/llvm/lib/ExecutionEngine/Orc/Speculation.cpp
index fee94b96a9e8ac..b22998afef8106 100644
--- a/llvm/lib/ExecutionEngine/Orc/Speculation.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/Speculation.cpp
@@ -75,7 +75,7 @@ void IRSpeculationLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
         M, SpeculatorVTy, false, GlobalValue::LinkageTypes::ExternalLinkage,
         nullptr, "__orc_speculator");
 
-    IRBuilder<> Mutator(MContext);
+    IRBuilder<> Mutator(M);
 
     // QueryAnalysis allowed to transform the IR source, one such example is
     // Simplify CFG helps the static branch prediction heuristics!

diff  --git a/llvm/lib/Frontend/HLSL/RootSignatureMetadata.cpp b/llvm/lib/Frontend/HLSL/RootSignatureMetadata.cpp
index 014601c08447bf..108b57c34af167 100644
--- a/llvm/lib/Frontend/HLSL/RootSignatureMetadata.cpp
+++ b/llvm/lib/Frontend/HLSL/RootSignatureMetadata.cpp
@@ -138,7 +138,7 @@ MDNode *MetadataBuilder::BuildRootSignature() {
 }
 
 MDNode *MetadataBuilder::BuildRootFlags(const dxbc::RootFlags &Flags) {
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(M);
   Metadata *Operands[] = {
       MDString::get(Ctx, "RootFlags"),
       ConstantAsMetadata::get(Builder.getInt32(to_underlying(Flags))),
@@ -147,7 +147,7 @@ MDNode *MetadataBuilder::BuildRootFlags(const dxbc::RootFlags &Flags) {
 }
 
 MDNode *MetadataBuilder::BuildRootConstants(const RootConstants &Constants) {
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(M);
   Metadata *Operands[] = {
       MDString::get(Ctx, "RootConstants"),
       ConstantAsMetadata::get(
@@ -160,7 +160,7 @@ MDNode *MetadataBuilder::BuildRootConstants(const RootConstants &Constants) {
 }
 
 MDNode *MetadataBuilder::BuildRootDescriptor(const RootDescriptor &Descriptor) {
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(M);
   StringRef ResName = dxil::getResourceClassName(Descriptor.Type);
   assert(!ResName.empty() && "Provided an invalid Resource Class");
   SmallString<7> Name({"Root", ResName});
@@ -177,7 +177,7 @@ MDNode *MetadataBuilder::BuildRootDescriptor(const RootDescriptor &Descriptor) {
 }
 
 MDNode *MetadataBuilder::BuildDescriptorTable(const DescriptorTable &Table) {
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(M);
   SmallVector<Metadata *> TableOperands;
   // Set the mandatory arguments
   TableOperands.push_back(MDString::get(Ctx, "DescriptorTable"));
@@ -200,7 +200,7 @@ MDNode *MetadataBuilder::BuildDescriptorTable(const DescriptorTable &Table) {
 
 MDNode *MetadataBuilder::BuildDescriptorTableClause(
     const DescriptorTableClause &Clause) {
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(M);
   StringRef ResName = dxil::getResourceClassName(Clause.Type);
   assert(!ResName.empty() && "Provided an invalid Resource Class");
   Metadata *Operands[] = {
@@ -215,7 +215,7 @@ MDNode *MetadataBuilder::BuildDescriptorTableClause(
 }
 
 MDNode *MetadataBuilder::BuildStaticSampler(const StaticSampler &Sampler) {
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(M);
   Metadata *Operands[] = {
       MDString::get(Ctx, "StaticSampler"),
       ConstantAsMetadata::get(Builder.getInt32(to_underlying(Sampler.Filter))),

diff  --git a/llvm/lib/IR/AutoUpgrade.cpp b/llvm/lib/IR/AutoUpgrade.cpp
index 2765934ee02d99..0e0c6cf10eeac3 100644
--- a/llvm/lib/IR/AutoUpgrade.cpp
+++ b/llvm/lib/IR/AutoUpgrade.cpp
@@ -2499,8 +2499,7 @@ GlobalVariable *llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
   if (!STy || STy->getNumElements() != 2)
     return nullptr;
 
-  LLVMContext &C = GV->getContext();
-  IRBuilder<> IRB(C);
+  IRBuilder<> IRB(*GV->getParent());
   auto EltTy = StructType::get(STy->getElementType(0), STy->getElementType(1),
                                IRB.getPtrTy());
   Constant *Init = GV->getInitializer();

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp b/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp
index 6b5976bab177aa..cbbe7bcde0be57 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp
@@ -340,7 +340,7 @@ simplifyAMDGCNImageIntrinsic(const GCNSubtarget *ST,
         II.mutateType(HalfVecTy);
         II.setCalledFunction(HalfDecl);
 
-        IRBuilder<> Builder(II.getContext());
+        IRBuilder<> Builder(*M);
         for (auto &[Ext, Tr] : ExtractTruncPairs) {
           Value *Idx = Ext->getIndexOperand();
 

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPULowerBufferFatPointers.cpp b/llvm/lib/Target/AMDGPU/AMDGPULowerBufferFatPointers.cpp
index a00f3372c1f60e..aa0f896b8c1078 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPULowerBufferFatPointers.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPULowerBufferFatPointers.cpp
@@ -453,9 +453,9 @@ class StoreFatPtrsAsIntsAndExpandMemcpyVisitor
 
 public:
   StoreFatPtrsAsIntsAndExpandMemcpyVisitor(BufferFatPtrToIntTypeMap *TypeMap,
-                                           const DataLayout &DL,
-                                           LLVMContext &Ctx)
-      : TypeMap(TypeMap), IRB(Ctx, InstSimplifyFolder(DL)), DL(DL) {}
+                                           Module &M)
+      : TypeMap(TypeMap), IRB(M, InstSimplifyFolder(M.getDataLayout())),
+        DL(M.getDataLayout()) {}
   bool processFunction(Function &F, const TargetTransformInfo *TTI,
                        ScalarEvolution *SE);
 
@@ -832,9 +832,9 @@ class LegalizeBufferContentTypesVisitor
   bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASCI);
 
 public:
-  LegalizeBufferContentTypesVisitor(const DataLayout &DL, LLVMContext &Ctx,
-                                    const TargetMachine *TM)
-      : IRB(Ctx, InstSimplifyFolder(DL)), DL(DL), TM(TM) {}
+  LegalizeBufferContentTypesVisitor(Module &M, const TargetMachine *TM)
+      : IRB(M, InstSimplifyFolder(M.getDataLayout())), DL(M.getDataLayout()),
+        TM(TM) {}
   bool processFunction(Function &F, ScalarEvolution *SE);
 };
 } // namespace
@@ -1603,9 +1603,8 @@ class SplitPtrStructs : public InstVisitor<SplitPtrStructs, PtrParts> {
                           bool IsVolatile, SyncScope::ID SSID);
 
 public:
-  SplitPtrStructs(const DataLayout &DL, LLVMContext &Ctx,
-                  const TargetMachine *TM)
-      : TM(TM), IRB(Ctx, InstSimplifyFolder(DL)) {}
+  SplitPtrStructs(Module &M, const TargetMachine *TM)
+      : TM(TM), IRB(M, InstSimplifyFolder(M.getDataLayout())) {}
 
   void processFunction(Function &F);
 
@@ -2789,10 +2788,8 @@ bool AMDGPULowerBufferFatPointers::run(Module &M, const TargetMachine &TM,
         /*RemoveDeadConstants=*/false, /*IncludeSelf=*/true);
   }
 
-  StoreFatPtrsAsIntsAndExpandMemcpyVisitor MemOpsRewrite(&IntTM, DL,
-                                                         M.getContext());
-  LegalizeBufferContentTypesVisitor BufferContentsTypeRewrite(
-      DL, M.getContext(), &TM);
+  StoreFatPtrsAsIntsAndExpandMemcpyVisitor MemOpsRewrite(&IntTM, M);
+  LegalizeBufferContentTypesVisitor BufferContentsTypeRewrite(M, &TM);
   for (Function &F : M.functions()) {
     bool InterfaceChange = hasFatPointerInterface(F, &StructTM);
     bool BodyChanges = containsBufferFatPointers(F, &StructTM);
@@ -2837,7 +2834,7 @@ bool AMDGPULowerBufferFatPointers::run(Module &M, const TargetMachine &TM,
   IntTM.clear();
   CloneMap.clear();
 
-  SplitPtrStructs Splitter(DL, M.getContext(), &TM);
+  SplitPtrStructs Splitter(M, &TM);
   for (Function *F : NeedsPostProcess)
     Splitter.processFunction(*F);
   for (Function *F : Intrinsics) {

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp b/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp
index fc6f2ac69c000c..2313a955d52b90 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp
@@ -402,7 +402,7 @@ class AMDGPULowerModuleLDS {
       GlobalVariable *LookupTable) {
 
     LLVMContext &Ctx = M.getContext();
-    IRBuilder<> Builder(Ctx);
+    IRBuilder<> Builder(M);
     Type *I32 = Type::getInt32Ty(Ctx);
 
     for (size_t Index = 0; Index < ModuleScopeVariables.size(); Index++) {
@@ -556,7 +556,7 @@ class AMDGPULowerModuleLDS {
 
       // Annotate the kernels with their order in this vector
       LLVMContext &Ctx = M->getContext();
-      IRBuilder<> Builder(Ctx);
+      IRBuilder<> Builder(*M);
 
       if (OrderedKernels.size() > UINT32_MAX) {
         // 32 bit keeps it in one SGPR. > 2**32 kernels won't fit on the GPU
@@ -855,7 +855,7 @@ class AMDGPULowerModuleLDS {
     DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS;
     if (!KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
       LLVMContext &Ctx = M.getContext();
-      IRBuilder<> Builder(Ctx);
+      IRBuilder<> Builder(M);
       Type *LocalPtrTy = PointerType::get(Ctx, AMDGPUAS::LOCAL_ADDRESS);
 
       std::vector<Constant *> newDynamicLDS;
@@ -1138,8 +1138,7 @@ class AMDGPULowerModuleLDS {
                                       KernelsThatIndirectlyAllocateDynamicLDS);
 
     if (!KernelsThatAllocateTableLDS.empty()) {
-      LLVMContext &Ctx = M.getContext();
-      IRBuilder<> Builder(Ctx);
+      IRBuilder<> Builder(M);
 
       // The order must be consistent between lookup table and accesses to
       // lookup table

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp b/llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp
index 98928e26f8de01..1c7f6761d4f302 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUPrintfRuntimeBinding.cpp
@@ -137,7 +137,7 @@ static void diagnoseInvalidFormatString(const CallBase *CI) {
 
 bool AMDGPUPrintfRuntimeBindingImpl::lowerPrintfForGpu(Module &M) {
   LLVMContext &Ctx = M.getContext();
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(M);
   Type *I32Ty = Type::getInt32Ty(Ctx);
 
   // Instead of creating global variables, the printf format strings are

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp b/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp
index 5498f3a20d8a7d..0cac1374b2db98 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp
@@ -469,7 +469,7 @@ static bool isSupportedMemset(MemSetInst *I, AllocaInst *AI,
 }
 
 static Value *calculateVectorIndex(Value *Ptr, AllocaAnalysis &AA) {
-  IRBuilder<> B(Ptr->getContext());
+  IRBuilder<> B(*AA.Alloca->getModule());
 
   Ptr = Ptr->stripPointerCasts();
   if (Ptr == AA.Alloca)

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp b/llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp
index a32a4ea7e721a1..9e2e7ffa23ebe4 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp
@@ -168,7 +168,7 @@ struct FunctionsAndLDSAccess {
 class AMDGPUSwLowerLDS {
 public:
   AMDGPUSwLowerLDS(Module &Mod, DomTreeCallback Callback)
-      : M(Mod), IRB(M.getContext()), DTCallback(Callback) {}
+      : M(Mod), IRB(M), DTCallback(Callback) {}
   bool run();
   void getUsesOfLDSByNonKernels();
   void getNonKernelsWithLDSArguments(const CallGraph &CG);

diff  --git a/llvm/lib/Target/BPF/BPFCheckAndAdjustIR.cpp b/llvm/lib/Target/BPF/BPFCheckAndAdjustIR.cpp
index 888828dd57c804..21a88c3341563e 100644
--- a/llvm/lib/Target/BPF/BPFCheckAndAdjustIR.cpp
+++ b/llvm/lib/Target/BPF/BPFCheckAndAdjustIR.cpp
@@ -443,7 +443,7 @@ static Value *aspaceWrapValue(DenseMap<Value *, Value *> &Cache, Function *F,
     return NewGEP;
   }
 
-  IRBuilder IB(F->getContext());
+  IRBuilder IB(*F->getParent());
   if (Instruction *InsnPtr = dyn_cast<Instruction>(ToWrap))
     IB.SetInsertPoint(*InsnPtr->getInsertionPointAfterDef());
   else

diff  --git a/llvm/lib/Target/DirectX/DXILDataScalarization.cpp b/llvm/lib/Target/DirectX/DXILDataScalarization.cpp
index deaef574a828a6..666d04cec7f387 100644
--- a/llvm/lib/Target/DirectX/DXILDataScalarization.cpp
+++ b/llvm/lib/Target/DirectX/DXILDataScalarization.cpp
@@ -431,7 +431,7 @@ static Constant *transformInitializer(Constant *Init, Type *OrigType,
 static bool findAndReplaceVectors(Module &M) {
   bool MadeChange = false;
   LLVMContext &Ctx = M.getContext();
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(M);
   DataScalarizerVisitor Impl;
   for (GlobalVariable &G : M.globals()) {
     Type *OrigType = G.getValueType();

diff  --git a/llvm/lib/Target/DirectX/DXILOpBuilder.cpp b/llvm/lib/Target/DirectX/DXILOpBuilder.cpp
index 9bb2521d7a9fde..93527c576495c1 100644
--- a/llvm/lib/Target/DirectX/DXILOpBuilder.cpp
+++ b/llvm/lib/Target/DirectX/DXILOpBuilder.cpp
@@ -504,7 +504,7 @@ namespace dxil {
 // Triple is well-formed or that the target is supported since these checks
 // would have been done at the time the module M is constructed in the earlier
 // stages of compilation.
-DXILOpBuilder::DXILOpBuilder(Module &M) : M(M), IRB(M.getContext()) {
+DXILOpBuilder::DXILOpBuilder(Module &M) : M(M), IRB(M) {
   const Triple &TT = M.getTargetTriple();
   DXILVersion = TT.getDXILVersion();
   ShaderStage = TT.getEnvironment();

diff  --git a/llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp b/llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
index bde0729e38e0ce..1bdfb7d7cc0ec5 100644
--- a/llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
+++ b/llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
@@ -297,7 +297,7 @@ static void emitValidatorVersionMD(Module &M, const ModuleMetadataInfo &MMDI) {
     return;
 
   LLVMContext &Ctx = M.getContext();
-  IRBuilder<> IRB(Ctx);
+  IRBuilder<> IRB(M);
   Metadata *MDVals[2];
   MDVals[0] =
       ConstantAsMetadata::get(IRB.getInt32(MMDI.ValidatorVersion.getMajor()));
@@ -312,7 +312,7 @@ static void emitValidatorVersionMD(Module &M, const ModuleMetadataInfo &MMDI) {
 static void emitShaderModelVersionMD(Module &M,
                                      const ModuleMetadataInfo &MMDI) {
   LLVMContext &Ctx = M.getContext();
-  IRBuilder<> IRB(Ctx);
+  IRBuilder<> IRB(M);
   Metadata *SMVals[3];
   VersionTuple SM = MMDI.ShaderModelVersion;
   SMVals[0] = MDString::get(Ctx, getShortShaderStage(MMDI.ShaderProfile));
@@ -324,7 +324,7 @@ static void emitShaderModelVersionMD(Module &M,
 
 static void emitDXILVersionTupleMD(Module &M, const ModuleMetadataInfo &MMDI) {
   LLVMContext &Ctx = M.getContext();
-  IRBuilder<> IRB(Ctx);
+  IRBuilder<> IRB(M);
   VersionTuple DXILVer = MMDI.DXILVersion;
   Metadata *DXILVals[2];
   DXILVals[0] = ConstantAsMetadata::get(IRB.getInt32(DXILVer.getMajor()));
@@ -535,8 +535,7 @@ static void translateGlobalMetadata(Module &M, DXILResourceMap &DRM,
                                     DXILResourceTypeMap &DRTM,
                                     const ModuleShaderFlags &ShaderFlags,
                                     const ModuleMetadataInfo &MMDI) {
-  LLVMContext &Ctx = M.getContext();
-  IRBuilder<> IRB(Ctx);
+  IRBuilder<> IRB(M);
   SmallVector<MDNode *> EntryFnMDNodes;
 
   emitValidatorVersionMD(M, MMDI);

diff  --git a/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp b/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp
index 26f44bb8f4cc67..41a6afa2f59ca7 100644
--- a/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp
+++ b/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp
@@ -1190,13 +1190,13 @@ HexagonTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
   bool isVTi1Type = false;
   if (auto *CV = dyn_cast<ConstantVector>(CPN->getConstVal())) {
     if (cast<VectorType>(CV->getType())->getElementType()->isIntegerTy(1)) {
-      IRBuilder<> IRB(CV->getContext());
       SmallVector<Constant*, 128> NewConst;
       unsigned VecLen = CV->getNumOperands();
       assert(isPowerOf2_32(VecLen) &&
              "conversion only supported for pow2 VectorSize");
       for (unsigned i = 0; i < VecLen; ++i)
-        NewConst.push_back(IRB.getInt8(CV->getOperand(i)->isNullValue()));
+        NewConst.push_back(ConstantInt::get(Type::getInt8Ty(CV->getContext()),
+                                            CV->getOperand(i)->isNullValue()));
 
       CVal = ConstantVector::get(NewConst);
       isVTi1Type = true;

diff  --git a/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp b/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
index db99ec5a32fb32..f2175483f24d6d 100644
--- a/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
+++ b/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
@@ -166,7 +166,7 @@ class HexagonLoopIdiomRecognizeLegacyPass : public LoopPass {
 
 struct Simplifier {
   struct Rule {
-    using FuncType = std::function<Value *(Instruction *, LLVMContext &)>;
+    using FuncType = std::function<Value *(Instruction *, Module &)>;
     Rule(StringRef N, FuncType F) : Name(N), Fn(F) {}
     StringRef Name; // For debugging.
     FuncType Fn;
@@ -211,12 +211,9 @@ struct Simplifier {
     Value *Root;
     ValueSetType Used;   // The set of all cloned values used by Root.
     ValueSetType Clones; // The set of all cloned values.
-    LLVMContext &Ctx;
+    Module &M;
 
-    Context(Instruction *Exp)
-        : Ctx(Exp->getParent()->getParent()->getContext()) {
-      initialize(Exp);
-    }
+    Context(Instruction *Exp) : M(*Exp->getModule()) { initialize(Exp); }
 
     ~Context() { cleanup(); }
 
@@ -537,7 +534,7 @@ Value *Simplifier::simplify(Context &C) {
       continue;
     bool Changed = false;
     for (Rule &R : Rules) {
-      Value *W = R.Fn(U, C.Ctx);
+      Value *W = R.Fn(U, C.M);
       if (!W)
         continue;
       Changed = true;
@@ -1580,154 +1577,160 @@ static bool hasZeroSignBit(const Value *V) {
 
 void PolynomialMultiplyRecognize::setupPreSimplifier(Simplifier &S) {
   S.addRule("sink-zext",
-    // Sink zext past bitwise operations.
-    [](Instruction *I, LLVMContext &Ctx) -> Value* {
-      if (I->getOpcode() != Instruction::ZExt)
-        return nullptr;
-      Instruction *T = dyn_cast<Instruction>(I->getOperand(0));
-      if (!T)
-        return nullptr;
-      switch (T->getOpcode()) {
-        case Instruction::And:
-        case Instruction::Or:
-        case Instruction::Xor:
-          break;
-        default:
-          return nullptr;
-      }
-      IRBuilder<> B(Ctx);
-      return B.CreateBinOp(cast<BinaryOperator>(T)->getOpcode(),
-                           B.CreateZExt(T->getOperand(0), I->getType()),
-                           B.CreateZExt(T->getOperand(1), I->getType()));
-    });
+            // Sink zext past bitwise operations.
+            [](Instruction *I, Module &M) -> Value * {
+              if (I->getOpcode() != Instruction::ZExt)
+                return nullptr;
+              Instruction *T = dyn_cast<Instruction>(I->getOperand(0));
+              if (!T)
+                return nullptr;
+              switch (T->getOpcode()) {
+              case Instruction::And:
+              case Instruction::Or:
+              case Instruction::Xor:
+                break;
+              default:
+                return nullptr;
+              }
+              IRBuilder<> B(M);
+              return B.CreateBinOp(
+                  cast<BinaryOperator>(T)->getOpcode(),
+                  B.CreateZExt(T->getOperand(0), I->getType()),
+                  B.CreateZExt(T->getOperand(1), I->getType()));
+            });
   S.addRule("xor/and -> and/xor",
-    // (xor (and x a) (and y a)) -> (and (xor x y) a)
-    [](Instruction *I, LLVMContext &Ctx) -> Value* {
-      if (I->getOpcode() != Instruction::Xor)
-        return nullptr;
-      Instruction *And0 = dyn_cast<Instruction>(I->getOperand(0));
-      Instruction *And1 = dyn_cast<Instruction>(I->getOperand(1));
-      if (!And0 || !And1)
-        return nullptr;
-      if (And0->getOpcode() != Instruction::And ||
-          And1->getOpcode() != Instruction::And)
-        return nullptr;
-      if (And0->getOperand(1) != And1->getOperand(1))
-        return nullptr;
-      IRBuilder<> B(Ctx);
-      return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1->getOperand(0)),
-                         And0->getOperand(1));
-    });
-  S.addRule("sink binop into select",
-    // (Op (select c x y) z) -> (select c (Op x z) (Op y z))
-    // (Op x (select c y z)) -> (select c (Op x y) (Op x z))
-    [](Instruction *I, LLVMContext &Ctx) -> Value* {
-      BinaryOperator *BO = dyn_cast<BinaryOperator>(I);
-      if (!BO)
+            // (xor (and x a) (and y a)) -> (and (xor x y) a)
+            [](Instruction *I, Module &M) -> Value * {
+              if (I->getOpcode() != Instruction::Xor)
+                return nullptr;
+              Instruction *And0 = dyn_cast<Instruction>(I->getOperand(0));
+              Instruction *And1 = dyn_cast<Instruction>(I->getOperand(1));
+              if (!And0 || !And1)
+                return nullptr;
+              if (And0->getOpcode() != Instruction::And ||
+                  And1->getOpcode() != Instruction::And)
+                return nullptr;
+              if (And0->getOperand(1) != And1->getOperand(1))
+                return nullptr;
+              IRBuilder<> B(M);
+              return B.CreateAnd(
+                  B.CreateXor(And0->getOperand(0), And1->getOperand(0)),
+                  And0->getOperand(1));
+            });
+  S.addRule(
+      "sink binop into select",
+      // (Op (select c x y) z) -> (select c (Op x z) (Op y z))
+      // (Op x (select c y z)) -> (select c (Op x y) (Op x z))
+      [](Instruction *I, Module &M) -> Value * {
+        BinaryOperator *BO = dyn_cast<BinaryOperator>(I);
+        if (!BO)
+          return nullptr;
+        Instruction::BinaryOps Op = BO->getOpcode();
+        if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(0))) {
+          IRBuilder<> B(M);
+          Value *X = Sel->getTrueValue(), *Y = Sel->getFalseValue();
+          Value *Z = BO->getOperand(1);
+          return B.CreateSelect(Sel->getCondition(), B.CreateBinOp(Op, X, Z),
+                                B.CreateBinOp(Op, Y, Z));
+        }
+        if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(1))) {
+          IRBuilder<> B(M);
+          Value *X = BO->getOperand(0);
+          Value *Y = Sel->getTrueValue(), *Z = Sel->getFalseValue();
+          return B.CreateSelect(Sel->getCondition(), B.CreateBinOp(Op, X, Y),
+                                B.CreateBinOp(Op, X, Z));
+        }
         return nullptr;
-      Instruction::BinaryOps Op = BO->getOpcode();
-      if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(0))) {
-        IRBuilder<> B(Ctx);
-        Value *X = Sel->getTrueValue(), *Y = Sel->getFalseValue();
-        Value *Z = BO->getOperand(1);
-        return B.CreateSelect(Sel->getCondition(),
-                              B.CreateBinOp(Op, X, Z),
-                              B.CreateBinOp(Op, Y, Z));
-      }
-      if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(1))) {
-        IRBuilder<> B(Ctx);
-        Value *X = BO->getOperand(0);
-        Value *Y = Sel->getTrueValue(), *Z = Sel->getFalseValue();
-        return B.CreateSelect(Sel->getCondition(),
-                              B.CreateBinOp(Op, X, Y),
-                              B.CreateBinOp(Op, X, Z));
-      }
-      return nullptr;
-    });
-  S.addRule("fold select-select",
-    // (select c (select c x y) z) -> (select c x z)
-    // (select c x (select c y z)) -> (select c x z)
-    [](Instruction *I, LLVMContext &Ctx) -> Value* {
-      SelectInst *Sel = dyn_cast<SelectInst>(I);
-      if (!Sel)
+      });
+  S.addRule(
+      "fold select-select",
+      // (select c (select c x y) z) -> (select c x z)
+      // (select c x (select c y z)) -> (select c x z)
+      [](Instruction *I, Module &M) -> Value * {
+        SelectInst *Sel = dyn_cast<SelectInst>(I);
+        if (!Sel)
+          return nullptr;
+        IRBuilder<> B(M);
+        Value *C = Sel->getCondition();
+        if (SelectInst *Sel0 = dyn_cast<SelectInst>(Sel->getTrueValue())) {
+          if (Sel0->getCondition() == C)
+            return B.CreateSelect(C, Sel0->getTrueValue(),
+                                  Sel->getFalseValue());
+        }
+        if (SelectInst *Sel1 = dyn_cast<SelectInst>(Sel->getFalseValue())) {
+          if (Sel1->getCondition() == C)
+            return B.CreateSelect(C, Sel->getTrueValue(),
+                                  Sel1->getFalseValue());
+        }
         return nullptr;
-      IRBuilder<> B(Ctx);
-      Value *C = Sel->getCondition();
-      if (SelectInst *Sel0 = dyn_cast<SelectInst>(Sel->getTrueValue())) {
-        if (Sel0->getCondition() == C)
-          return B.CreateSelect(C, Sel0->getTrueValue(), Sel->getFalseValue());
-      }
-      if (SelectInst *Sel1 = dyn_cast<SelectInst>(Sel->getFalseValue())) {
-        if (Sel1->getCondition() == C)
-          return B.CreateSelect(C, Sel->getTrueValue(), Sel1->getFalseValue());
-      }
-      return nullptr;
-    });
+      });
   S.addRule("or-signbit -> xor-signbit",
-    // (or (lshr x 1) 0x800.0) -> (xor (lshr x 1) 0x800.0)
-    [](Instruction *I, LLVMContext &Ctx) -> Value* {
-      if (I->getOpcode() != Instruction::Or)
-        return nullptr;
-      ConstantInt *Msb = dyn_cast<ConstantInt>(I->getOperand(1));
-      if (!Msb || !Msb->getValue().isSignMask())
-        return nullptr;
-      if (!hasZeroSignBit(I->getOperand(0)))
-        return nullptr;
-      return IRBuilder<>(Ctx).CreateXor(I->getOperand(0), Msb);
-    });
+            // (or (lshr x 1) 0x800.0) -> (xor (lshr x 1) 0x800.0)
+            [](Instruction *I, Module &M) -> Value * {
+              if (I->getOpcode() != Instruction::Or)
+                return nullptr;
+              ConstantInt *Msb = dyn_cast<ConstantInt>(I->getOperand(1));
+              if (!Msb || !Msb->getValue().isSignMask())
+                return nullptr;
+              if (!hasZeroSignBit(I->getOperand(0)))
+                return nullptr;
+              return IRBuilder<>(M).CreateXor(I->getOperand(0), Msb);
+            });
   S.addRule("sink lshr into binop",
-    // (lshr (BitOp x y) c) -> (BitOp (lshr x c) (lshr y c))
-    [](Instruction *I, LLVMContext &Ctx) -> Value* {
-      if (I->getOpcode() != Instruction::LShr)
-        return nullptr;
-      BinaryOperator *BitOp = dyn_cast<BinaryOperator>(I->getOperand(0));
-      if (!BitOp)
-        return nullptr;
-      switch (BitOp->getOpcode()) {
-        case Instruction::And:
-        case Instruction::Or:
-        case Instruction::Xor:
-          break;
-        default:
-          return nullptr;
-      }
-      IRBuilder<> B(Ctx);
-      Value *S = I->getOperand(1);
-      return B.CreateBinOp(BitOp->getOpcode(),
-                B.CreateLShr(BitOp->getOperand(0), S),
-                B.CreateLShr(BitOp->getOperand(1), S));
-    });
+            // (lshr (BitOp x y) c) -> (BitOp (lshr x c) (lshr y c))
+            [](Instruction *I, Module &M) -> Value * {
+              if (I->getOpcode() != Instruction::LShr)
+                return nullptr;
+              BinaryOperator *BitOp =
+                  dyn_cast<BinaryOperator>(I->getOperand(0));
+              if (!BitOp)
+                return nullptr;
+              switch (BitOp->getOpcode()) {
+              case Instruction::And:
+              case Instruction::Or:
+              case Instruction::Xor:
+                break;
+              default:
+                return nullptr;
+              }
+              IRBuilder<> B(M);
+              Value *S = I->getOperand(1);
+              return B.CreateBinOp(BitOp->getOpcode(),
+                                   B.CreateLShr(BitOp->getOperand(0), S),
+                                   B.CreateLShr(BitOp->getOperand(1), S));
+            });
   S.addRule("expose bitop-const",
-    // (BitOp1 (BitOp2 x a) b) -> (BitOp2 x (BitOp1 a b))
-    [](Instruction *I, LLVMContext &Ctx) -> Value* {
-      auto IsBitOp = [](unsigned Op) -> bool {
-        switch (Op) {
-          case Instruction::And:
-          case Instruction::Or:
-          case Instruction::Xor:
-            return true;
-        }
-        return false;
-      };
-      BinaryOperator *BitOp1 = dyn_cast<BinaryOperator>(I);
-      if (!BitOp1 || !IsBitOp(BitOp1->getOpcode()))
-        return nullptr;
-      BinaryOperator *BitOp2 = dyn_cast<BinaryOperator>(BitOp1->getOperand(0));
-      if (!BitOp2 || !IsBitOp(BitOp2->getOpcode()))
-        return nullptr;
-      ConstantInt *CA = dyn_cast<ConstantInt>(BitOp2->getOperand(1));
-      ConstantInt *CB = dyn_cast<ConstantInt>(BitOp1->getOperand(1));
-      if (!CA || !CB)
-        return nullptr;
-      IRBuilder<> B(Ctx);
-      Value *X = BitOp2->getOperand(0);
-      return B.CreateBinOp(BitOp2->getOpcode(), X,
-                B.CreateBinOp(BitOp1->getOpcode(), CA, CB));
-    });
+            // (BitOp1 (BitOp2 x a) b) -> (BitOp2 x (BitOp1 a b))
+            [](Instruction *I, Module &M) -> Value * {
+              auto IsBitOp = [](unsigned Op) -> bool {
+                switch (Op) {
+                case Instruction::And:
+                case Instruction::Or:
+                case Instruction::Xor:
+                  return true;
+                }
+                return false;
+              };
+              BinaryOperator *BitOp1 = dyn_cast<BinaryOperator>(I);
+              if (!BitOp1 || !IsBitOp(BitOp1->getOpcode()))
+                return nullptr;
+              BinaryOperator *BitOp2 =
+                  dyn_cast<BinaryOperator>(BitOp1->getOperand(0));
+              if (!BitOp2 || !IsBitOp(BitOp2->getOpcode()))
+                return nullptr;
+              ConstantInt *CA = dyn_cast<ConstantInt>(BitOp2->getOperand(1));
+              ConstantInt *CB = dyn_cast<ConstantInt>(BitOp1->getOperand(1));
+              if (!CA || !CB)
+                return nullptr;
+              IRBuilder<> B(M);
+              Value *X = BitOp2->getOperand(0);
+              return B.CreateBinOp(BitOp2->getOpcode(), X,
+                                   B.CreateBinOp(BitOp1->getOpcode(), CA, CB));
+            });
   S.addRule("select with trunc cond to select with icmp cond",
             // select (trunc x to i1) -> select (icmp ne (and x, 1), 0)
             // select (xor (trunc x to i1) 1) -> select (icmp eq (and x, 1), 0)
-            [](Instruction *I, LLVMContext &Ctx) -> Value * {
+            [](Instruction *I, Module &M) -> Value * {
               SelectInst *Sel = dyn_cast<SelectInst>(I);
               if (!Sel)
                 return nullptr;
@@ -1738,7 +1741,7 @@ void PolynomialMultiplyRecognize::setupPreSimplifier(Simplifier &S) {
                     match(C, m_Not(m_Trunc(m_Value(X))))))
                 return nullptr;
 
-              IRBuilder<> B(Ctx);
+              IRBuilder<> B(M);
               Type *Ty = X->getType();
               Value *And = B.CreateAnd(X, ConstantInt::get(Ty, 1));
               Value *Icmp = B.CreateICmp(isa<TruncInst>(C) ? ICmpInst::ICMP_NE
@@ -1751,30 +1754,30 @@ void PolynomialMultiplyRecognize::setupPreSimplifier(Simplifier &S) {
 
 void PolynomialMultiplyRecognize::setupPostSimplifier(Simplifier &S) {
   S.addRule("(and (xor (and x a) y) b) -> (and (xor x y) b), if b == b&a",
-    [](Instruction *I, LLVMContext &Ctx) -> Value* {
-      if (I->getOpcode() != Instruction::And)
-        return nullptr;
-      Instruction *Xor = dyn_cast<Instruction>(I->getOperand(0));
-      ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(1));
-      if (!Xor || !C0)
-        return nullptr;
-      if (Xor->getOpcode() != Instruction::Xor)
-        return nullptr;
-      Instruction *And0 = dyn_cast<Instruction>(Xor->getOperand(0));
-      Instruction *And1 = dyn_cast<Instruction>(Xor->getOperand(1));
-      // Pick the first non-null and.
-      if (!And0 || And0->getOpcode() != Instruction::And)
-        std::swap(And0, And1);
-      ConstantInt *C1 = dyn_cast<ConstantInt>(And0->getOperand(1));
-      if (!C1)
-        return nullptr;
-      uint32_t V0 = C0->getZExtValue();
-      uint32_t V1 = C1->getZExtValue();
-      if (V0 != (V0 & V1))
-        return nullptr;
-      IRBuilder<> B(Ctx);
-      return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1), C0);
-    });
+            [](Instruction *I, Module &M) -> Value * {
+              if (I->getOpcode() != Instruction::And)
+                return nullptr;
+              Instruction *Xor = dyn_cast<Instruction>(I->getOperand(0));
+              ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(1));
+              if (!Xor || !C0)
+                return nullptr;
+              if (Xor->getOpcode() != Instruction::Xor)
+                return nullptr;
+              Instruction *And0 = dyn_cast<Instruction>(Xor->getOperand(0));
+              Instruction *And1 = dyn_cast<Instruction>(Xor->getOperand(1));
+              // Pick the first non-null and.
+              if (!And0 || And0->getOpcode() != Instruction::And)
+                std::swap(And0, And1);
+              ConstantInt *C1 = dyn_cast<ConstantInt>(And0->getOperand(1));
+              if (!C1)
+                return nullptr;
+              uint32_t V0 = C0->getZExtValue();
+              uint32_t V1 = C1->getZExtValue();
+              if (V0 != (V0 & V1))
+                return nullptr;
+              IRBuilder<> B(M);
+              return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1), C0);
+            });
 }
 
 bool PolynomialMultiplyRecognize::recognize() {

diff  --git a/llvm/lib/Target/PowerPC/PPCBoolRetToInt.cpp b/llvm/lib/Target/PowerPC/PPCBoolRetToInt.cpp
index 1652fa42ec89d9..36b5ba5b30d579 100644
--- a/llvm/lib/Target/PowerPC/PPCBoolRetToInt.cpp
+++ b/llvm/lib/Target/PowerPC/PPCBoolRetToInt.cpp
@@ -104,7 +104,7 @@ class PPCBoolRetToInt : public FunctionPass {
       return Q;
     }
 
-    IRBuilder IRB(V->getContext());
+    IRBuilder IRB(*Func->getParent());
     if (auto *I = dyn_cast<Instruction>(V))
       IRB.SetInsertPoint(I->getNextNode());
     else

diff  --git a/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp b/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
index 27675e8e6e75fd..d56e84a9bd2c0d 100644
--- a/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
+++ b/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
@@ -614,7 +614,7 @@ Type *SPIRVEmitIntrinsicsImpl::reconstructType(Value *Op,
 
 CallInst *SPIRVEmitIntrinsicsImpl::buildSpvPtrcast(Function *F, Value *Op,
                                                    Type *ElemTy) {
-  IRBuilder<> B(Op->getContext());
+  IRBuilder<> B(*F->getParent());
   if (auto *OpI = dyn_cast<Instruction>(Op)) {
     // spv_ptrcast's argument Op denotes an instruction that generates
     // a value, and we may use getInsertionPointAfterDef()
@@ -1536,8 +1536,7 @@ void SPIRVEmitIntrinsicsImpl::deduceOperandElementType(
   if (!KnownElemTy || Ops.size() == 0)
     return;
 
-  LLVMContext &Ctx = CurrF->getContext();
-  IRBuilder<> B(Ctx);
+  IRBuilder<> B(*CurrF->getParent());
   for (auto &OpIt : Ops) {
     Value *Op = OpIt.first;
     if (AskOps && !AskOps->contains(Op))
@@ -3765,7 +3764,7 @@ bool SPIRVEmitIntrinsicsImpl::runOnFunction(Function &Func) {
   CanUseAnyVectorRank =
       ST.canUseExtension(SPIRV::Extension::SPV_EXT_long_vector);
   CurrF = &Func;
-  IRBuilder<> B(Func.getContext());
+  IRBuilder<> B(*Func.getParent());
   AggrConsts.clear();
   AggrConstTypes.clear();
   AggrStores.clear();
@@ -4187,7 +4186,7 @@ bool SPIRVEmitIntrinsicsImpl::runOnModule(Module &M) {
     // check if function parameter types are set
     CurrF = &F;
     if (!F.isDeclaration() && !F.isIntrinsic()) {
-      IRBuilder<> B(F.getContext());
+      IRBuilder<> B(M);
       processParamTypes(&F, B);
     }
   }

diff  --git a/llvm/lib/Target/SPIRV/SPIRVLegalizePointerCast.cpp b/llvm/lib/Target/SPIRV/SPIRVLegalizePointerCast.cpp
index 0e86ad2b5108b4..6effed3dae94ff 100644
--- a/llvm/lib/Target/SPIRV/SPIRVLegalizePointerCast.cpp
+++ b/llvm/lib/Target/SPIRV/SPIRVLegalizePointerCast.cpp
@@ -777,7 +777,7 @@ class SPIRVLegalizePointerCastImpl {
     Value *CastedOperand = II;
     Value *OriginalOperand = II->getOperand(0);
 
-    IRBuilder<> B(II->getContext());
+    IRBuilder<> B(*II->getModule());
     std::vector<Value *> Users;
     for (Use &U : II->uses())
       Users.push_back(U.getUser());

diff  --git a/llvm/lib/Target/SPIRV/SPIRVPrepareFunctions.cpp b/llvm/lib/Target/SPIRV/SPIRVPrepareFunctions.cpp
index 537a98c43ec59d..bba56486fb2783 100644
--- a/llvm/lib/Target/SPIRV/SPIRVPrepareFunctions.cpp
+++ b/llvm/lib/Target/SPIRV/SPIRVPrepareFunctions.cpp
@@ -590,7 +590,7 @@ SPIRVPrepareFunctionsImpl::removeAggregateTypesFromSignature(Function *F) {
   if (F->isIntrinsic())
     return F;
 
-  IRBuilder<> B(F->getContext());
+  IRBuilder<> B(*F->getParent());
 
   bool HasAggrArg = llvm::any_of(F->args(), [](Argument &Arg) {
     return Arg.getType()->isAggregateType();
@@ -785,7 +785,7 @@ bool SPIRVPrepareFunctionsImpl::removeAggregateTypesFromCalls(Function *F) {
   if (Calls.empty())
     return false;
 
-  IRBuilder<> B(F->getContext());
+  IRBuilder<> B(*F->getParent());
 
   unsigned MutatedCallIdx = 0;
   for (auto &&[CB, NewFnTy] : Calls) {

diff  --git a/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp b/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
index c885f3ecc443b1..07ddfb1b852f9a 100644
--- a/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
+++ b/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
@@ -478,7 +478,7 @@ static void markAsImported(Function *F) {
 // Returns an integer type for the target architecture's address space.
 // i32 for wasm32 and i64 for wasm64.
 static Type *getAddrIntType(Module *M) {
-  IRBuilder<> IRB(M->getContext());
+  IRBuilder<> IRB(*M);
   return IRB.getIntNTy(M->getDataLayout().getPointerSizeInBits());
 }
 
@@ -493,7 +493,7 @@ static Type *getAddrPtrType(Module *M) {
 // space. Returns (i32 C) for wasm32 and (i64 C) for wasm64, when C is the
 // integer.
 static Value *getAddrSizeInt(Module *M, uint64_t C) {
-  IRBuilder<> IRB(M->getContext());
+  IRBuilder<> IRB(*M);
   return IRB.getIntN(M->getDataLayout().getPointerSizeInBits(), C);
 }
 
@@ -854,8 +854,7 @@ void WebAssemblyLowerEmscriptenEHSjLjImpl::replaceLongjmpWith(
   assert(NewF == EmLongjmpF || NewF == WasmLongjmpF);
   Module *M = LongjmpF->getParent();
   SmallVector<CallInst *, 8> ToErase;
-  LLVMContext &C = LongjmpF->getParent()->getContext();
-  IRBuilder<> IRB(C);
+  IRBuilder<> IRB(*LongjmpF->getParent());
 
   // For calls to longjmp, replace it with emscripten_longjmp/__wasm_longjmp and
   // cast its first argument (jmp_buf*) appropriately
@@ -900,7 +899,7 @@ static bool containsLongjmpableCalls(const Function *F) {
 // returns 0 when called directly.
 static void nullifySetjmp(Function *F) {
   Module &M = *F->getParent();
-  IRBuilder<> IRB(M.getContext());
+  IRBuilder<> IRB(M);
   Function *SetjmpF = M.getFunction("setjmp");
   SmallVector<Instruction *, 1> ToErase;
 
@@ -930,8 +929,7 @@ bool WebAssemblyLowerEmscriptenEHSjLjImpl::runOnModule(Module &M) {
   // threaded in from the TargetMachine.
   EnableEmEH |= M.getExceptionModel() == ExceptionHandling::Emscripten;
 
-  LLVMContext &C = M.getContext();
-  IRBuilder<> IRB(C);
+  IRBuilder<> IRB(M);
 
   Function *SetjmpF = M.getFunction("setjmp");
   Function *LongjmpF = M.getFunction("longjmp");
@@ -1127,7 +1125,7 @@ bool WebAssemblyLowerEmscriptenEHSjLjImpl::runOnModule(Module &M) {
 bool WebAssemblyLowerEmscriptenEHSjLjImpl::runEHOnFunction(Function &F) {
   Module &M = *F.getParent();
   LLVMContext &C = F.getContext();
-  IRBuilder<> IRB(C);
+  IRBuilder<> IRB(M);
   bool Changed = false;
   SmallVector<Instruction *, 64> ToErase;
   SmallPtrSet<LandingPadInst *, 32> LandingPads;
@@ -1319,8 +1317,7 @@ static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
 bool WebAssemblyLowerEmscriptenEHSjLjImpl::runSjLjOnFunction(Function &F) {
   assert(EnableEmSjLj || EnableWasmSjLj);
   Module &M = *F.getParent();
-  LLVMContext &C = F.getContext();
-  IRBuilder<> IRB(C);
+  IRBuilder IRB(M);
   SmallVector<Instruction *, 64> ToErase;
 
   // Setjmp preparation
@@ -1431,7 +1428,7 @@ void WebAssemblyLowerEmscriptenEHSjLjImpl::
         SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
   Module &M = *F.getParent();
   LLVMContext &C = F.getContext();
-  IRBuilder<> IRB(C);
+  IRBuilder<> IRB(M);
   SmallVector<Instruction *, 64> ToErase;
 
   // call.em.longjmp BB that will be shared within the function.
@@ -1626,7 +1623,7 @@ void WebAssemblyLowerEmscriptenEHSjLjImpl::handleLongjmpableCallsForWasmSjLj(
     SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
   Module &M = *F.getParent();
   LLVMContext &C = F.getContext();
-  IRBuilder<> IRB(C);
+  IRBuilder<> IRB(M);
 
   // A function with catchswitch/catchpad instruction should have a personality
   // function attached to it. Search for the wasm personality function, and if

diff  --git a/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp b/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
index 2d62534b186960..7353428a058dea 100644
--- a/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
+++ b/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
@@ -2040,7 +2040,7 @@ bool StrNCmpInliner::optimizeStrNCmp() {
 void StrNCmpInliner::inlineCompare(Value *LHS, StringRef RHS, uint64_t N,
                                    bool Swapped) {
   auto &Ctx = CI->getContext();
-  IRBuilder<> B(Ctx);
+  IRBuilder<> B(*CI->getModule());
   // We want these instructions to be recognized as inlined instructions for the
   // compare call, but we don't have a source location for the definition of
   // that function, since we're generating that code now. Because the generated

diff  --git a/llvm/lib/Transforms/Coroutines/CoroCleanup.cpp b/llvm/lib/Transforms/Coroutines/CoroCleanup.cpp
index 20de75d0ade606..d2d083c4894444 100644
--- a/llvm/lib/Transforms/Coroutines/CoroCleanup.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroCleanup.cpp
@@ -29,7 +29,7 @@ struct Lowerer : coro::LowererBase {
   IRBuilder<> Builder;
   Constant *NoopCoro = nullptr;
 
-  Lowerer(Module &M) : LowererBase(M), Builder(Context) {}
+  Lowerer(Module &M) : LowererBase(M), Builder(M) {}
   bool lower(Function &F);
 
 private:
@@ -43,7 +43,7 @@ class NoopCoroElider : public PtrUseVisitor<NoopCoroElider> {
   IRBuilder<> Builder;
 
 public:
-  NoopCoroElider(const DataLayout &DL, LLVMContext &C) : Base(DL), Builder(C) {}
+  NoopCoroElider(Module &M) : Base(M.getDataLayout()), Builder(M) {}
 
   void run(IntrinsicInst *II);
 
@@ -95,7 +95,7 @@ bool Lowerer::lower(Function &F) {
   bool IsPrivateAndUnprocessed = F.isPresplitCoroutine() && F.hasLocalLinkage();
   bool Changed = false;
 
-  NoopCoroElider NCE(F.getDataLayout(), F.getContext());
+  NoopCoroElider NCE(*F.getParent());
   SmallPtrSet<Instruction *, 8> DeadInsts{};
   for (Instruction &I : instructions(F)) {
     if (auto *II = dyn_cast<IntrinsicInst>(&I)) {

diff  --git a/llvm/lib/Transforms/Coroutines/CoroCloner.h b/llvm/lib/Transforms/Coroutines/CoroCloner.h
index 1e549f122b6ba1..3d01879e4c1ff2 100644
--- a/llvm/lib/Transforms/Coroutines/CoroCloner.h
+++ b/llvm/lib/Transforms/Coroutines/CoroCloner.h
@@ -63,7 +63,7 @@ class BaseCloner {
       : OrigF(OrigF), Suffix(Suffix), Shape(Shape),
         FKind(Shape.ABI == ABI::Async ? CloneKind::Async
                                       : CloneKind::Continuation),
-        Builder(OrigF.getContext()), TTI(TTI), NewF(NewF),
+        Builder(*OrigF.getParent()), TTI(TTI), NewF(NewF),
         ActiveSuspend(ActiveSuspend) {
     assert(Shape.ABI == ABI::Retcon || Shape.ABI == ABI::RetconOnce ||
            Shape.ABI == ABI::Async);
@@ -75,7 +75,7 @@ class BaseCloner {
   BaseCloner(Function &OrigF, const Twine &Suffix, coro::Shape &Shape,
              CloneKind FKind, TargetTransformInfo &TTI)
       : OrigF(OrigF), Suffix(Suffix), Shape(Shape), FKind(FKind),
-        Builder(OrigF.getContext()), TTI(TTI) {}
+        Builder(*OrigF.getParent()), TTI(TTI) {}
 
   virtual ~BaseCloner() = default;
 

diff  --git a/llvm/lib/Transforms/Coroutines/CoroEarly.cpp b/llvm/lib/Transforms/Coroutines/CoroEarly.cpp
index ecb34fa11e0fc9..d15b4dbd7f270b 100644
--- a/llvm/lib/Transforms/Coroutines/CoroEarly.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroEarly.cpp
@@ -29,7 +29,7 @@ class Lowerer : public coro::LowererBase {
 
 public:
   Lowerer(Module &M)
-      : LowererBase(M), Builder(Context),
+      : LowererBase(M), Builder(M),
         AnyResumeFnPtrTy(PointerType::getUnqual(Context)) {}
   void lowerEarlyIntrinsics(Function &F);
 };

diff  --git a/llvm/lib/Transforms/Coroutines/CoroFrame.cpp b/llvm/lib/Transforms/Coroutines/CoroFrame.cpp
index bb11b5ee1038ae..8c0f105b77d6aa 100644
--- a/llvm/lib/Transforms/Coroutines/CoroFrame.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroFrame.cpp
@@ -1065,7 +1065,7 @@ static void handleAccessBeforeCoroBegin(const FrameDataInfo &FrameData,
 static void insertSpills(const FrameDataInfo &FrameData, coro::Shape &Shape) {
   LLVMContext &C = Shape.CoroBegin->getContext();
   Function *F = Shape.CoroBegin->getFunction();
-  IRBuilder<> Builder(C);
+  IRBuilder<> Builder(*F->getParent());
   DominatorTree DT(*F);
   SmallDenseMap<Argument *, AllocaInst *, 4> ArgToAllocaMap;
 
@@ -1830,11 +1830,10 @@ static std::optional<std::pair<Value &, DIExpression &>>
 salvageDebugInfoImpl(SmallDenseMap<Argument *, AllocaInst *, 4> &ArgToAllocaMap,
                      bool UseEntryValue, Function *F, Value *Storage,
                      DIExpression *Expr, bool SkipOutermostLoad) {
-  IRBuilder<> Builder(F->getContext());
   auto InsertPt = F->getEntryBlock().getFirstInsertionPt();
   while (isa<IntrinsicInst>(InsertPt))
     ++InsertPt;
-  Builder.SetInsertPoint(InsertPt);
+  IRBuilder<> Builder(InsertPt);
 
   while (auto *Inst = dyn_cast_or_null<Instruction>(Storage)) {
     if (auto *LdInst = dyn_cast<LoadInst>(Inst)) {

diff  --git a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
index 764e07cd53f2b6..dd7d00b7f0c229 100644
--- a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
@@ -151,7 +151,7 @@ static void lowerAwaitSuspend(IRBuilder<> &Builder, CoroAwaitSuspendInst *CB,
 }
 
 static void lowerAwaitSuspends(Function &F, coro::Shape &Shape) {
-  IRBuilder<> Builder(F.getContext());
+  IRBuilder<> Builder(*F.getParent());
   for (auto *AWS : Shape.CoroAwaitSuspends)
     lowerAwaitSuspend(Builder, AWS, Shape);
 }

diff  --git a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
index ae21725cea2e46..9af51dedab1747 100644
--- a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
+++ b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp
@@ -6934,9 +6934,8 @@ struct AAHeapToStackFunction final : public AAHeapToStack {
       if (SizeAPI) {
         Size = ConstantInt::get(AI.CB->getContext(), *SizeAPI);
       } else {
-        LLVMContext &Ctx = AI.CB->getContext();
         ObjectSizeOpts Opts;
-        ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, Opts);
+        ObjectSizeOffsetEvaluator Eval(*AI.CB->getModule(), TLI, Opts);
         SizeOffsetValue SizeOffsetPair = Eval.compute(AI.CB);
         assert(SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown() &&
                cast<ConstantInt>(SizeOffsetPair.Offset)->isZero());

diff  --git a/llvm/lib/Transforms/IPO/ExpandVariadics.cpp b/llvm/lib/Transforms/IPO/ExpandVariadics.cpp
index 44d944933cc3a6..483492fd0feb71 100644
--- a/llvm/lib/Transforms/IPO/ExpandVariadics.cpp
+++ b/llvm/lib/Transforms/IPO/ExpandVariadics.cpp
@@ -364,9 +364,8 @@ bool ExpandVariadics::runOnModule(Module &M) {
   if (!ABI->enableForTarget())
     return Changed;
 
-  auto &Ctx = M.getContext();
   const DataLayout &DL = M.getDataLayout();
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(M);
 
   // Lowering needs to run on all functions exactly once.
   // Optimize could run on functions containing va_start exactly once.

diff  --git a/llvm/lib/Transforms/IPO/GlobalOpt.cpp b/llvm/lib/Transforms/IPO/GlobalOpt.cpp
index 36563e25cc7f75..3072371b9fedea 100644
--- a/llvm/lib/Transforms/IPO/GlobalOpt.cpp
+++ b/llvm/lib/Transforms/IPO/GlobalOpt.cpp
@@ -1840,7 +1840,7 @@ static void RemovePreallocated(Function *F) {
 
   auto *M = F->getParent();
 
-  IRBuilder<> Builder(M->getContext());
+  IRBuilder<> Builder(*M);
 
   // Cannot modify users() while iterating over it, so make a copy.
   SmallVector<User *, 4> PreallocatedCalls(F->users());

diff  --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index cd95225f5f6575..8893744821f7e6 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -538,7 +538,7 @@ static Value *rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW,
           PHINode::Create(IndexType, PHI->getNumIncomingValues(),
                           PHI->getName() + ".idx", PHI->getIterator());
   }
-  IRBuilder<> Builder(Base->getContext());
+  IRBuilder<> Builder(IC.getModule());
 
   // Create all the other instructions.
   for (Value *Val : Explored) {

diff  --git a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h
index 388530edc10dad..07bc7e302c9ecc 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineInternal.h
+++ b/llvm/lib/Transforms/InstCombine/InstCombineInternal.h
@@ -891,8 +891,8 @@ class Negator final {
 
   SmallDenseMap<Value *, Value *> NegationsCache;
 
-  Negator(LLVMContext &C, const DataLayout &DL, const DominatorTree &DT,
-          bool IsTrulyNegation, unsigned MaxDepth);
+  Negator(Module &M, const DominatorTree &DT, bool IsTrulyNegation,
+          unsigned MaxDepth);
 
 #if LLVM_ENABLE_STATS
   unsigned NumValuesVisitedInThisNegator = 0;

diff  --git a/llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp b/llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp
index 9dceeef7bbab39..5e3eb41862f032 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp
@@ -78,9 +78,9 @@ STATISTIC(NegatorNumInstructionsNegatedSuccess,
 DEBUG_COUNTER(NegatorCounter, "instcombine-negator",
               "Controls Negator transformations in InstCombine pass");
 
-Negator::Negator(LLVMContext &C, const DataLayout &DL, const DominatorTree &DT_,
-                 bool IsTrulyNegation_, unsigned MaxDepth)
-    : Builder(C, TargetFolder(DL),
+Negator::Negator(Module &M, const DominatorTree &DT_, bool IsTrulyNegation_,
+                 unsigned MaxDepth)
+    : Builder(M, TargetFolder(M.getDataLayout()),
               IRBuilderCallbackInserter([&](Instruction *I) {
                 ++NegatorNumInstructionsCreatedTotal;
                 NewInstructions.push_back(I);
@@ -548,8 +548,8 @@ std::array<Value *, 2> Negator::getSortedOperandsOfBinOp(Instruction *I) {
       !DebugCounter::shouldExecute(NegatorCounter))
     return nullptr;
 
-  Negator N(Root->getContext(), IC.getDataLayout(), IC.getDominatorTree(),
-            LHSIsZero, IC.CLOpts.negator_max_depth);
+  Negator N(IC.getModule(), IC.getDominatorTree(), LHSIsZero,
+            IC.CLOpts.negator_max_depth);
   std::optional<Result> Res = N.run(Root, IsNSW);
   if (!Res) { // Negation failed.
     LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root

diff  --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index c70597ced1370f..4d3be3b5834dc8 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -2361,7 +2361,7 @@ StringRef ModuleAddressSanitizer::getGlobalMetadataSection() const {
 }
 
 void ModuleAddressSanitizer::initializeCallbacks() {
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
 
   // Declare our poisoning and unpoisoning functions.
   AsanPoisonGlobals = Inserter.insertFunction(kAsanPoisonGlobalsName,
@@ -2910,7 +2910,7 @@ bool ModuleAddressSanitizer::instrumentModule() {
       IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
       instrumentGlobals(IRB, &CtorComdat);
     } else {
-      IRBuilder<> IRB(*C);
+      IRBuilder<> IRB(M);
       instrumentGlobals(IRB, &CtorComdat);
     }
   }
@@ -2940,7 +2940,7 @@ bool ModuleAddressSanitizer::instrumentModule() {
 }
 
 void AddressSanitizer::initializeCallbacks(const TargetLibraryInfo *TLI) {
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
   // Create __asan_report* callbacks.
   // IsWrite, TypeSize and Exp are encoded in the function name.
   for (int Exp = 0; Exp < 2; Exp++) {
@@ -3273,8 +3273,8 @@ bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
   return true;
 }
 
-void FunctionStackPoisoner::initializeCallbacks(Module &) {
-  IRBuilder<> IRB(*C);
+void FunctionStackPoisoner::initializeCallbacks(Module &M) {
+  IRBuilder<> IRB(M);
   if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always ||
       ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {
     const char *MallocNameTemplate =

diff  --git a/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp b/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
index 3aed97bf8363c1..66e890ee62dbda 100644
--- a/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
+++ b/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
@@ -206,7 +206,7 @@ static bool addBoundsChecking(Function &F, TargetLibraryInfo &TLI,
   ObjectSizeOpts EvalOpts;
   EvalOpts.RoundToAlign = true;
   EvalOpts.EvalMode = ObjectSizeOpts::Mode::ExactUnderlyingSizeAndOffset;
-  ObjectSizeOffsetEvaluator ObjSizeEval(DL, &TLI, F.getContext(), EvalOpts);
+  ObjectSizeOffsetEvaluator ObjSizeEval(*F.getParent(), &TLI, EvalOpts);
 
   // check HANDLE_MEMORY_INST in include/llvm/Instruction.def for memory
   // touching instructions

diff  --git a/llvm/lib/Transforms/Instrumentation/CopyProf.cpp b/llvm/lib/Transforms/Instrumentation/CopyProf.cpp
index c21703145dff8a..840f9c0b7c8b17 100644
--- a/llvm/lib/Transforms/Instrumentation/CopyProf.cpp
+++ b/llvm/lib/Transforms/Instrumentation/CopyProf.cpp
@@ -174,7 +174,7 @@ class CopyProfStores {
 
 CopyProf::CopyProf(Module &M) {
   LLVMContext &Ctx = M.getContext();
-  IRBuilder<> IRB(Ctx);
+  IRBuilder<> IRB(M);
   IntPtrTy = IRB.getIntPtrTy(M.getDataLayout());
   Type *PtrTy = IRB.getPtrTy();
   Type *VoidTy = IRB.getVoidTy();
@@ -254,7 +254,7 @@ void CopyProf::insertCallback(Function &F, size_t ObjSize, unsigned NumArgs,
 
 CopyProfStores::CopyProfStores(Module &M) {
   LLVMContext &Ctx = M.getContext();
-  IRBuilder<> IRB(Ctx);
+  IRBuilder<> IRB(M);
   IntPtrTy = IRB.getIntPtrTy(M.getDataLayout());
   Type *PtrTy = IRB.getPtrTy();
   Type *VoidTy = IRB.getVoidTy();

diff  --git a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
index db6bf996a28c60..3ad957c34a2d4c 100644
--- a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -691,7 +691,7 @@ void HWAddressSanitizer::initializeModule() {
   Mapping.init(TargetTriple, InstrumentWithCalls, CompileKernel);
 
   C = &(M.getContext());
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
 
   HwasanCtorFunction = nullptr;
 
@@ -750,7 +750,7 @@ void HWAddressSanitizer::initializeModule() {
 }
 
 void HWAddressSanitizer::initializeCallbacks(Module &M) {
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
   const std::string MatchAllStr = UseMatchAllCallback ? "_match_all" : "";
   FunctionType *HwasanMemoryAccessCallbackSizedFnTy,
       *HwasanMemoryAccessCallbackFnTy, *HwasanMemTransferFnTy,

diff  --git a/llvm/lib/Transforms/Instrumentation/MemProfInstrumentation.cpp b/llvm/lib/Transforms/Instrumentation/MemProfInstrumentation.cpp
index 72697ffeadf7af..310d8bc77edbc6 100644
--- a/llvm/lib/Transforms/Instrumentation/MemProfInstrumentation.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemProfInstrumentation.cpp
@@ -546,7 +546,7 @@ bool ModuleMemProfiler::instrumentModule(Module &M) {
 }
 
 void MemProfiler::initializeCallbacks(Module &M) {
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
 
   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
     const std::string TypeStr = AccessIsWrite ? "store" : "load";

diff  --git a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
index 360c071bc95f14..59b4903b416d27 100644
--- a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
@@ -858,7 +858,7 @@ MemorySanitizer::getOrInsertMsanMetadataFunction(Module &M, StringRef Name,
 
 /// Create KMSAN API callbacks.
 void MemorySanitizer::createKernelApi(Module &M, const TargetLibraryInfo &TLI) {
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
 
   // These will be initialized in insertKmsanPrologue().
   RetvalTLS = nullptr;
@@ -921,7 +921,7 @@ static Constant *getOrInsertGlobal(Module &M, StringRef Name, Type *Ty) {
 /// Insert declarations for userspace-specific functions and globals.
 void MemorySanitizer::createUserspaceApi(Module &M,
                                          const TargetLibraryInfo &TLI) {
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
 
   // Create the callback.
   // FIXME: this function should have "Cold" calling conv,
@@ -998,7 +998,7 @@ void MemorySanitizer::initializeCallbacks(Module &M,
   if (CallbacksInitialized)
     return;
 
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
   // Initialize callbacks that are common for kernel and userspace
   // instrumentation.
   MsanChainOriginFn = M.getOrInsertFunction(
@@ -1127,7 +1127,7 @@ void MemorySanitizer::initializeModule(Module &M) {
   }
 
   C = &(M.getContext());
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
   IntptrTy = IRB.getIntPtrTy(DL);
   OriginTy = IRB.getInt32Ty();
   PtrTy = IRB.getPtrTy();

diff  --git a/llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp b/llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
index 210b1266de23c8..c320bb61fd8101 100644
--- a/llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
+++ b/llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
@@ -130,7 +130,7 @@ class SanitizerBinaryMetadata {
                           std::unique_ptr<SpecialCaseList> Ignorelist)
       : Mod(M), Options(transformOptionsFromCl(std::move(Opts))),
         Ignorelist(std::move(Ignorelist)), TargetTriple(M.getTargetTriple()),
-        VersionStr(utostr(getVersion())), IRB(M.getContext()) {
+        VersionStr(utostr(getVersion())), IRB(M) {
     // FIXME: Make it work with other formats.
     assert(TargetTriple.isOSBinFormatELF() && "ELF only");
     assert(!TargetTriple.isGPU() && "Device targets are not supported");

diff  --git a/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp b/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
index 9e59f60d3d9265..d97aca5d9c0b90 100644
--- a/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ b/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -443,7 +443,7 @@ bool ModuleSanitizerCoverage::instrumentModule() {
   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
   PtrTy = PointerType::getUnqual(*C);
   Type *VoidTy = Type::getVoidTy(*C);
-  IRBuilder<> IRB(*C);
+  IRBuilder<> IRB(M);
   Int64Ty = IRB.getInt64Ty();
   Int32Ty = IRB.getInt32Ty();
   Int16Ty = IRB.getInt16Ty();

diff  --git a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
index 5f399e25db5ff9..7424307829b853 100644
--- a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
@@ -205,7 +205,7 @@ void ThreadSanitizer::initialize(Module &M, const TargetLibraryInfo &TLI) {
   LLVMContext &Ctx = M.getContext();
   IntptrTy = DL.getIntPtrType(Ctx);
 
-  IRBuilder<> IRB(Ctx);
+  IRBuilder<> IRB(M);
   AttributeList Attr;
   Attr = Attr.addFnAttribute(Ctx, Attribute::NoUnwind);
   // Initialize the callbacks.

diff  --git a/llvm/lib/Transforms/Instrumentation/TypeSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/TypeSanitizer.cpp
index 524a9261fbb1fe..2e1806fd5b9fa7 100644
--- a/llvm/lib/Transforms/Instrumentation/TypeSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/TypeSanitizer.cpp
@@ -145,7 +145,7 @@ TypeSanitizer::TypeSanitizer(Module &M)
 
 void TypeSanitizer::initializeCallbacks(Module &M) {
   LLVMContext &C = M.getContext();
-  IRBuilder<> IRB(C);
+  IRBuilder<> IRB(M);
   OrdTy = IRB.getInt32Ty();
   U64Ty = IRB.getInt64Ty();
   Type *BoolType = IRB.getInt1Ty();

diff  --git a/llvm/lib/Transforms/Scalar/SROA.cpp b/llvm/lib/Transforms/Scalar/SROA.cpp
index 599f9f42f9ca8f..e4c8c3029fe05a 100644
--- a/llvm/lib/Transforms/Scalar/SROA.cpp
+++ b/llvm/lib/Transforms/Scalar/SROA.cpp
@@ -2897,7 +2897,7 @@ class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
         ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy).getFixedValue() / 8
                           : 0),
         PHIUsers(PHIUsers), SelectUsers(SelectUsers),
-        IRB(NewAI.getContext(), ConstantFolder()) {
+        IRB(*NewAI.getModule(), ConstantFolder()) {
     if (VecTy) {
       assert((DL.getTypeSizeInBits(ElementTy).getFixedValue() % 8) == 0 &&
              "Only multiple-of-8 sized vector elements are viable");

diff  --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index a8eae7dcd5ec0f..41c3c2c3c0e192 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -2284,7 +2284,7 @@ inlineRetainOrClaimRVCalls(CallBase &CB, objcarc::ARCInstKind RVCallKind,
   for (auto *RI : Returns) {
     Value *RetOpnd = objcarc::GetRCIdentityRoot(RI->getOperand(0));
     bool InsertRetainCall = IsRetainRV;
-    IRBuilder<> Builder(RI->getContext());
+    IRBuilder<> Builder(*RI->getModule());
 
     // Walk backwards through the basic block looking for either a matching
     // autoreleaseRV call or an unannotated call.

diff  --git a/llvm/lib/Transforms/Utils/LoopVersioning.cpp b/llvm/lib/Transforms/Utils/LoopVersioning.cpp
index f77c4918d15bd8..4a02cf5e8298c1 100644
--- a/llvm/lib/Transforms/Utils/LoopVersioning.cpp
+++ b/llvm/lib/Transforms/Utils/LoopVersioning.cpp
@@ -78,7 +78,7 @@ void LoopVersioning::versionLoop(
       Exp.expandCodeForPredicate(&Preds, RuntimeCheckBB->getTerminator());
 
   IRBuilder<InstSimplifyFolder> Builder(
-      RuntimeCheckBB->getContext(),
+      *RuntimeCheckBB->getModule(),
       InstSimplifyFolder(RuntimeCheckBB->getDataLayout()));
   if (MemRuntimeCheck && SCEVRuntimeCheck) {
     Builder.SetInsertPoint(RuntimeCheckBB->getTerminator());

diff  --git a/llvm/lib/Transforms/Utils/ModuleUtils.cpp b/llvm/lib/Transforms/Utils/ModuleUtils.cpp
index 71e9c70cbf9a5c..78315855e394cf 100644
--- a/llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ b/llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -29,7 +29,7 @@ using namespace llvm;
 
 static void appendToGlobalArray(StringRef ArrayName, Module &M, Function *F,
                                 int Priority, Constant *Data) {
-  IRBuilder<> IRB(M.getContext());
+  IRBuilder<> IRB(M);
 
   // Get the current set of static global constructors and add the new ctor
   // to the list.
@@ -85,7 +85,7 @@ static void transformGlobalArray(StringRef ArrayName, Module &M,
   if (!GVCtor)
     return;
 
-  IRBuilder<> IRB(M.getContext());
+  IRBuilder<> IRB(M);
   SmallVector<Constant *, 16> CurrentCtors;
   bool Changed = false;
   StructType *EltTy =
@@ -264,7 +264,7 @@ std::pair<Function *, FunctionCallee> llvm::createSanitizerCtorAndInitFunctions(
   FunctionCallee InitFunction =
       declareSanitizerInitFunction(M, InitName, InitArgTypes, Weak);
   Function *Ctor = createSanitizerCtor(M, CtorName);
-  IRBuilder<> IRB(M.getContext());
+  IRBuilder<> IRB(M);
 
   BasicBlock *RetBB = &Ctor->getEntryBlock();
   if (Weak) {

diff  --git a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
index e3db3b230c2388..b7b442f64fda06 100644
--- a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
@@ -4139,7 +4139,7 @@ static bool performBranchToCommonDestFolding(CondBrInst *BI, CondBrInst *PBI,
   LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
 
   IRBuilder<ConstantFolder, IRBuilderCallbackInserter> Builder(
-      BB->getContext(), ConstantFolder{},
+      *BB->getModule(), ConstantFolder{},
       IRBuilderCallbackInserter([&BB](Instruction *I) {
         // The builder is used to create instructions to eliminate the branch in
         // BB. If BB's terminator has !annotation metadata, add it to the new

diff  --git a/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp b/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp
index eb0b152f6bb6f2..202670ff815b69 100644
--- a/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoadStoreVectorizer.cpp
@@ -258,8 +258,8 @@ class Vectorizer {
 public:
   Vectorizer(Function &F, AliasAnalysis &AA, AssumptionCache &AC,
              DominatorTree &DT, ScalarEvolution &SE, TargetTransformInfo &TTI)
-      : F(F), AA(AA), AC(AC), DT(DT), SE(SE), TTI(TTI),
-        DL(F.getDataLayout()), Builder(SE.getContext()) {}
+      : F(F), AA(AA), AC(AC), DT(DT), SE(SE), TTI(TTI), DL(F.getDataLayout()),
+        Builder(SE.getModule()) {}
 
   bool run();
 

diff  --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index 3cdc144bace673..326f202fd150f4 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -546,7 +546,7 @@ class InnerLoopVectorizer {
                       ElementCount VecWidth, unsigned UnrollFactor,
                       GeneratedRTChecks &RTChecks, VPlan &Plan)
       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TTI(TTI), AC(AC),
-        VF(VecWidth), UF(UnrollFactor), Builder(PSE.getSE()->getContext()),
+        VF(VecWidth), UF(UnrollFactor), Builder(PSE.getSE()->getModule()),
         RTChecks(RTChecks), Plan(Plan),
         VectorPHVPBB(cast<VPBasicBlock>(
             Plan.getVectorLoopRegion()->getSinglePredecessor())) {}

diff  --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index c7bd38813b72c6..eb9bfb60e2de0e 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -434,7 +434,7 @@ class slpvectorizer::BoUpSLP {
       : AA(Aa), BatchAA(std::in_place, *Aa), F(Func), SE(Se), TTI(Tti),
         TLI(TLi), LI(Li), DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE),
         CostKind(getSLPCostKind(Func)),
-        Builder(Se->getContext(), TargetFolder(*DL)) {
+        Builder(Se->getModule(), TargetFolder(*DL)) {
     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
     // Use the vector register size specified by the target unless overridden
     // by a command-line option.

diff  --git a/llvm/lib/Transforms/Vectorize/VectorCombine.cpp b/llvm/lib/Transforms/Vectorize/VectorCombine.cpp
index 72b72e51dbe6b5..c24bebadb6506a 100644
--- a/llvm/lib/Transforms/Vectorize/VectorCombine.cpp
+++ b/llvm/lib/Transforms/Vectorize/VectorCombine.cpp
@@ -80,7 +80,7 @@ class VectorCombine {
                 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC,
                 const DataLayout *DL, TTI::TargetCostKind CostKind,
                 bool TryEarlyFoldsOnly)
-      : F(F), Builder(F.getContext(), InstSimplifyFolder(*DL)), TTI(TTI),
+      : F(F), Builder(*F.getParent(), InstSimplifyFolder(*DL)), TTI(TTI),
         DT(DT), AA(AA), DL(DL), CostKind(CostKind),
         SQ(*DL, /*TLI=*/nullptr, &DT, &AC),
         TryEarlyFoldsOnly(TryEarlyFoldsOnly) {}

diff  --git a/llvm/tools/lli/lli.cpp b/llvm/tools/lli/lli.cpp
index 6bee74935a1157..3a36043aa0504e 100644
--- a/llvm/tools/lli/lli.cpp
+++ b/llvm/tools/lli/lli.cpp
@@ -375,12 +375,12 @@ class LLIObjectCache : public ObjectCache {
 // an empty '__main' function.
 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
                                   const Triple &TargetTriple) {
-  IRBuilder<> Builder(Context);
-
   // Create a new module.
   std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
   M->setTargetTriple(TargetTriple);
 
+  IRBuilder<> Builder(*M);
+
   // Create an empty function named "__main".
   Type *ReturnTy;
   if (TargetTriple.isArch64Bit())

diff  --git a/llvm/unittests/Analysis/BasicAliasAnalysisTest.cpp b/llvm/unittests/Analysis/BasicAliasAnalysisTest.cpp
index 0541f257b20d2a..2f2bb676053a9c 100644
--- a/llvm/unittests/Analysis/BasicAliasAnalysisTest.cpp
+++ b/llvm/unittests/Analysis/BasicAliasAnalysisTest.cpp
@@ -66,7 +66,7 @@ class BasicAATest : public testing::Test {
 
 public:
   BasicAATest()
-      : M("BasicAATest", C), B(C), DL(DLString), TLII(M.getTargetTriple()),
+      : M("BasicAATest", C), B(M), DL(DLString), TLII(M.getTargetTriple()),
         TLI(TLII), F(nullptr) {}
 };
 

diff  --git a/llvm/unittests/Analysis/MemorySSATest.cpp b/llvm/unittests/Analysis/MemorySSATest.cpp
index 450241963af538..49701aaf0168d9 100644
--- a/llvm/unittests/Analysis/MemorySSATest.cpp
+++ b/llvm/unittests/Analysis/MemorySSATest.cpp
@@ -70,7 +70,7 @@ class MemorySSATest : public testing::Test {
 
 public:
   MemorySSATest()
-      : M("MemorySSATest", C), B(C), DL(DLString), TLII(M.getTargetTriple()),
+      : M("MemorySSATest", C), B(M), DL(DLString), TLII(M.getTargetTriple()),
         TLI(TLII), F(nullptr) {}
 };
 
@@ -896,7 +896,7 @@ TEST_F(MemorySSATest, Irreducible) {
   // }
   // use(x)
 
-  IRBuilder<> B(C);
+  IRBuilder<> B(M);
   F = Function::Create(FunctionType::get(B.getVoidTy(), {B.getPtrTy()}, false),
                        GlobalValue::ExternalLinkage, "F", &M);
 
@@ -935,7 +935,7 @@ TEST_F(MemorySSATest, MoveToBeforeLiveOnEntryInvalidatesCache) {
   //
   // ...And be sure that MSSA's caching doesn't give us `1` for the clobber of
   // `2` after `1` is removed.
-  IRBuilder<> B(C);
+  IRBuilder<> B(M);
   F = Function::Create(FunctionType::get(B.getVoidTy(), {B.getPtrTy()}, false),
                        GlobalValue::ExternalLinkage, "F", &M);
 
@@ -980,7 +980,7 @@ TEST_F(MemorySSATest, RemovingDefInvalidatesCache) {
   //
   // And be sure that MSSA's caching handles the removal of def `1`
   // appropriately.
-  IRBuilder<> B(C);
+  IRBuilder<> B(M);
   F = Function::Create(FunctionType::get(B.getVoidTy(), {B.getPtrTy()}, false),
                        GlobalValue::ExternalLinkage, "F", &M);
 
@@ -1130,7 +1130,7 @@ TEST_F(MemorySSATest, LifetimeMarkersAreClobbers) {
   // should both be clobbered by the lifetime.start call if they're dominated by
   // it.
 
-  IRBuilder<> B(C);
+  IRBuilder<> B(M);
   F = Function::Create(FunctionType::get(B.getVoidTy(), {}, false),
                        GlobalValue::ExternalLinkage, "F", &M);
 
@@ -1188,7 +1188,7 @@ TEST_F(MemorySSATest, LifetimeMarkersAreClobbers) {
 }
 
 TEST_F(MemorySSATest, DefOptimizationsAreInvalidatedOnMoving) {
-  IRBuilder<> B(C);
+  IRBuilder<> B(M);
   F = Function::Create(FunctionType::get(B.getVoidTy(), {B.getInt1Ty()}, false),
                        GlobalValue::ExternalLinkage, "F", &M);
 

diff  --git a/llvm/unittests/Analysis/SparsePropagation.cpp b/llvm/unittests/Analysis/SparsePropagation.cpp
index e302f89c5719fe..872620fa42145a 100644
--- a/llvm/unittests/Analysis/SparsePropagation.cpp
+++ b/llvm/unittests/Analysis/SparsePropagation.cpp
@@ -232,8 +232,7 @@ class SparsePropagationTest : public testing::Test {
   SparseSolver<TestLatticeKey, TestLatticeVal> Solver;
 
 public:
-  SparsePropagationTest()
-      : M("", Context), Builder(Context), Solver(&Lattice) {}
+  SparsePropagationTest() : M("", Context), Builder(M), Solver(&Lattice) {}
 };
 } // namespace
 

diff  --git a/llvm/unittests/Analysis/ValueTrackingTest.cpp b/llvm/unittests/Analysis/ValueTrackingTest.cpp
index 96576875bd7a53..955fa15f6bc62d 100644
--- a/llvm/unittests/Analysis/ValueTrackingTest.cpp
+++ b/llvm/unittests/Analysis/ValueTrackingTest.cpp
@@ -2980,7 +2980,7 @@ TEST_F(ComputeKnownBitsTest, ComputeKnownBitsAddWithRange) {
 
 TEST_F(ComputeKnownBitsTest, ComputeKnownBitsUnknownVScale) {
   Module M("", Context);
-  IRBuilder<> Builder(Context);
+  IRBuilder<> Builder(M);
   Function *TheFn = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::vscale,
                                                       {Builder.getInt32Ty()});
   CallInst *CI = Builder.CreateCall(TheFn, {});

diff  --git a/llvm/unittests/ExecutionEngine/Orc/ReOptimizeLayerTest.cpp b/llvm/unittests/ExecutionEngine/Orc/ReOptimizeLayerTest.cpp
index d10ea6c92c8cbc..3c005181d90364 100644
--- a/llvm/unittests/ExecutionEngine/Orc/ReOptimizeLayerTest.cpp
+++ b/llvm/unittests/ExecutionEngine/Orc/ReOptimizeLayerTest.cpp
@@ -129,7 +129,7 @@ static Function *createRetFunction(Module *M, StringRef Name,
       GlobalValue::ExternalLinkage, Name, M);
 
   BasicBlock *BB = BasicBlock::Create(M->getContext(), Name, Result);
-  IRBuilder<> Builder(M->getContext());
+  IRBuilder<> Builder(*M);
   Builder.SetInsertPoint(BB);
 
   Value *RetValue = ConstantInt::get(M->getContext(), APInt(32, ReturnCode));

diff  --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index 14a3065b989ad0..063ec08c259138 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -1267,7 +1267,7 @@ TEST_F(IRBuilderTest, DebugLoc) {
   auto Br = UncondBrInst::Create(BB2, BB);
   Br->setDebugLoc(DL1);
 
-  IRBuilder<> Builder(Ctx);
+  IRBuilder<> Builder(*M);
   Builder.SetInsertPoint(Br);
   EXPECT_EQ(DL1, Builder.getCurrentDebugLocation());
   auto Call1 = Builder.CreateCall(Callee, {});
@@ -1384,10 +1384,10 @@ TEST_F(IRBuilderTest, CTAD) {
   };
   InstSimplifyFolder Folder(M->getDataLayout());
 
-  IRBuilder Builder1(Ctx, Folder, TestInserter());
+  IRBuilder Builder1(*M, Folder, TestInserter());
   static_assert(std::is_same_v<decltype(Builder1),
                                IRBuilder<InstSimplifyFolder, TestInserter>>);
-  IRBuilder Builder2(Ctx);
+  IRBuilder Builder2(*M);
   static_assert(std::is_same_v<decltype(Builder2), IRBuilder<>>);
   IRBuilder Builder3(BB, Folder);
   static_assert(

diff  --git a/llvm/unittests/IR/InstructionsTest.cpp b/llvm/unittests/IR/InstructionsTest.cpp
index c5a24c1b688a64..fdf46a66afca22 100644
--- a/llvm/unittests/IR/InstructionsTest.cpp
+++ b/llvm/unittests/IR/InstructionsTest.cpp
@@ -543,7 +543,8 @@ TEST(InstructionsTest, VectorGep) {
 
 TEST(InstructionsTest, FPMathOperator) {
   LLVMContext Context;
-  IRBuilder<> Builder(Context);
+  Module M("", Context);
+  IRBuilder<> Builder(M);
   MDBuilder MDHelper(Context);
   Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
   MDNode *MD1 = MDHelper.createFPMath(1.0);
@@ -565,8 +566,7 @@ TEST(InstructionTest, ConstrainedTrans) {
                         false);
   auto *F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
   auto *BB = BasicBlock::Create(Context, "bb", F);
-  IRBuilder<> Builder(Context);
-  Builder.SetInsertPoint(BB);
+  IRBuilder<> Builder(BB);
   auto *Arg0 = F->arg_begin();
   auto *Arg1 = F->arg_begin() + 1;
 
@@ -880,7 +880,7 @@ TEST_F(ModuleWithFunctionTest, DropPoisonGeneratingFlags) {
   auto *OnlyBB = BasicBlock::Create(Ctx, "bb", F);
   auto *Arg0 = &*F->arg_begin();
 
-  IRBuilder<NoFolder> B(Ctx);
+  IRBuilder<NoFolder> B(*M);
   B.SetInsertPoint(OnlyBB);
 
   {
@@ -1629,7 +1629,8 @@ TEST(InstructionsTest, SkipDebug) {
 
 TEST(InstructionsTest, PhiMightNotBeFPMathOperator) {
   LLVMContext Context;
-  IRBuilder<> Builder(Context);
+  Module M("", Context);
+  IRBuilder<> Builder(M);
   MDBuilder MDHelper(Context);
   Instruction *I = Builder.CreatePHI(Builder.getInt32Ty(), 0);
   EXPECT_FALSE(isa<FPMathOperator>(I));
@@ -1800,7 +1801,8 @@ if.end:
 
 TEST(InstructionsTest, UnaryOperator) {
   LLVMContext Context;
-  IRBuilder<> Builder(Context);
+  Module M("", Context);
+  IRBuilder<> Builder(M);
   Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
   Value *F = Builder.CreateFNeg(I);
 

diff  --git a/llvm/unittests/Transforms/Utils/CloningTest.cpp b/llvm/unittests/Transforms/Utils/CloningTest.cpp
index 30318b02007abd..bc5ffd27a3af8a 100644
--- a/llvm/unittests/Transforms/Utils/CloningTest.cpp
+++ b/llvm/unittests/Transforms/Utils/CloningTest.cpp
@@ -476,7 +476,7 @@ class CloneFunc : public ::testing::Test {
 
   void CreateOldFunctionBodyAndDI() {
     DIBuilder DBuilder(*M);
-    IRBuilder<> IBuilder(C);
+    IRBuilder<> IBuilder(*M);
 
     // Function DI
     auto *File = DBuilder.createFile("filename.c", "/file/dir/");
@@ -1115,7 +1115,7 @@ class CloneModule : public ::testing::Test {
     }
 
     DIBuilder DBuilder(*OldM);
-    IRBuilder<> IBuilder(C);
+    IRBuilder<> IBuilder(*OldM);
 
     auto *FuncType = FunctionType::get(Type::getVoidTy(C), false);
     auto *PersFn = Function::Create(FuncType, GlobalValue::ExternalLinkage,

diff  --git a/llvm/unittests/Transforms/Utils/FunctionComparatorTest.cpp b/llvm/unittests/Transforms/Utils/FunctionComparatorTest.cpp
index cd2b4e8046b2e4..6606b59ff2d045 100644
--- a/llvm/unittests/Transforms/Utils/FunctionComparatorTest.cpp
+++ b/llvm/unittests/Transforms/Utils/FunctionComparatorTest.cpp
@@ -24,7 +24,7 @@ struct TestFunction {
   Type *T;
 
   TestFunction(LLVMContext &Ctx, Module &M, int addVal) {
-    IRBuilder<> B(Ctx);
+    IRBuilder<> B(M);
     T = B.getInt8Ty();
     F = Function::Create(FunctionType::get(T, {B.getPtrTy()}, false),
                          GlobalValue::ExternalLinkage, "F", &M);

diff  --git a/llvm/unittests/Transforms/Utils/IntegerDivisionTest.cpp b/llvm/unittests/Transforms/Utils/IntegerDivisionTest.cpp
index 85dae05c35b5ae..7a39f609722341 100644
--- a/llvm/unittests/Transforms/Utils/IntegerDivisionTest.cpp
+++ b/llvm/unittests/Transforms/Utils/IntegerDivisionTest.cpp
@@ -22,7 +22,7 @@ namespace {
 TEST(IntegerDivision, SDiv) {
   LLVMContext C;
   Module M("test division", C);
-  IRBuilder<> Builder(C);
+  IRBuilder<> Builder(M);
 
   SmallVector<Type*, 2> ArgTys(2, Builder.getInt32Ty());
   Function *F = Function::Create(FunctionType::get(Builder.getInt32Ty(),
@@ -52,7 +52,7 @@ TEST(IntegerDivision, SDiv) {
 TEST(IntegerDivision, UDiv) {
   LLVMContext C;
   Module M("test division", C);
-  IRBuilder<> Builder(C);
+  IRBuilder<> Builder(M);
 
   SmallVector<Type*, 2> ArgTys(2, Builder.getInt32Ty());
   Function *F = Function::Create(FunctionType::get(Builder.getInt32Ty(),
@@ -82,7 +82,7 @@ TEST(IntegerDivision, UDiv) {
 TEST(IntegerDivision, SRem) {
   LLVMContext C;
   Module M("test remainder", C);
-  IRBuilder<> Builder(C);
+  IRBuilder<> Builder(M);
 
   SmallVector<Type*, 2> ArgTys(2, Builder.getInt32Ty());
   Function *F = Function::Create(FunctionType::get(Builder.getInt32Ty(),
@@ -112,7 +112,7 @@ TEST(IntegerDivision, SRem) {
 TEST(IntegerDivision, URem) {
   LLVMContext C;
   Module M("test remainder", C);
-  IRBuilder<> Builder(C);
+  IRBuilder<> Builder(M);
 
   SmallVector<Type*, 2> ArgTys(2, Builder.getInt32Ty());
   Function *F = Function::Create(FunctionType::get(Builder.getInt32Ty(),
@@ -143,7 +143,7 @@ TEST(IntegerDivision, URem) {
 TEST(IntegerDivision, SDiv64) {
   LLVMContext C;
   Module M("test division", C);
-  IRBuilder<> Builder(C);
+  IRBuilder<> Builder(M);
 
   SmallVector<Type*, 2> ArgTys(2, Builder.getInt64Ty());
   Function *F = Function::Create(FunctionType::get(Builder.getInt64Ty(),
@@ -173,7 +173,7 @@ TEST(IntegerDivision, SDiv64) {
 TEST(IntegerDivision, UDiv64) {
   LLVMContext C;
   Module M("test division", C);
-  IRBuilder<> Builder(C);
+  IRBuilder<> Builder(M);
 
   SmallVector<Type*, 2> ArgTys(2, Builder.getInt64Ty());
   Function *F = Function::Create(FunctionType::get(Builder.getInt64Ty(),
@@ -203,7 +203,7 @@ TEST(IntegerDivision, UDiv64) {
 TEST(IntegerDivision, SRem64) {
   LLVMContext C;
   Module M("test remainder", C);
-  IRBuilder<> Builder(C);
+  IRBuilder<> Builder(M);
 
   SmallVector<Type*, 2> ArgTys(2, Builder.getInt64Ty());
   Function *F = Function::Create(FunctionType::get(Builder.getInt64Ty(),
@@ -233,7 +233,7 @@ TEST(IntegerDivision, SRem64) {
 TEST(IntegerDivision, URem64) {
   LLVMContext C;
   Module M("test remainder", C);
-  IRBuilder<> Builder(C);
+  IRBuilder<> Builder(M);
 
   SmallVector<Type*, 2> ArgTys(2, Builder.getInt64Ty());
   Function *F = Function::Create(FunctionType::get(Builder.getInt64Ty(),

diff  --git a/llvm/unittests/Transforms/Utils/LocalTest.cpp b/llvm/unittests/Transforms/Utils/LocalTest.cpp
index a497f75c00896e..81c3f20f992dcd 100644
--- a/llvm/unittests/Transforms/Utils/LocalTest.cpp
+++ b/llvm/unittests/Transforms/Utils/LocalTest.cpp
@@ -30,8 +30,9 @@ using namespace llvm;
 
 TEST(Local, RecursivelyDeleteDeadPHINodes) {
   LLVMContext C;
+  Module M("", C);
 
-  IRBuilder<> builder(C);
+  IRBuilder<> builder(M);
 
   // Make blocks
   BasicBlock *bb0 = BasicBlock::Create(C);
@@ -73,7 +74,8 @@ TEST(Local, RecursivelyDeleteDeadPHINodes) {
 
 TEST(Local, RemoveDuplicatePHINodes) {
   LLVMContext C;
-  IRBuilder<> B(C);
+  Module M("", C);
+  IRBuilder<> B(M);
 
   std::unique_ptr<Function> F(
       Function::Create(FunctionType::get(B.getVoidTy(), false),
@@ -1134,7 +1136,7 @@ TEST(LocalTest, TargetTypeInfoHasNoReplacementProperty) {
 TEST(Local, CanReplaceOperandWithVariable) {
   LLVMContext Ctx;
   Module M("test_module", Ctx);
-  IRBuilder<> B(Ctx);
+  IRBuilder<> B(M);
 
   FunctionType *FnType =
     FunctionType::get(Type::getVoidTy(Ctx), {}, false);
@@ -1253,7 +1255,7 @@ TEST(Local, ExpressionForConstant) {
   EXPECT_EQ(Expr->getElement(1), 0x7FFFFFFFFFFFFFFFU);
 
   GlobalVariable *String =
-      IRBuilder<>(Context).CreateGlobalString("hello", "hello", 0, &M);
+      IRBuilder<>(M).CreateGlobalString("hello", "hello", 0, &M);
   Expr = createExpression(ConstantExpr::getPtrToInt(String, Int32Ty), Int32Ty);
   EXPECT_EQ(Expr, nullptr);
 

diff  --git a/llvm/unittests/Transforms/Utils/SSAUpdaterBulkTest.cpp b/llvm/unittests/Transforms/Utils/SSAUpdaterBulkTest.cpp
index 835e5930ed009c..6f494d40674590 100644
--- a/llvm/unittests/Transforms/Utils/SSAUpdaterBulkTest.cpp
+++ b/llvm/unittests/Transforms/Utils/SSAUpdaterBulkTest.cpp
@@ -23,7 +23,7 @@ TEST(SSAUpdaterBulk, SimpleMerge) {
   SSAUpdaterBulk Updater;
   LLVMContext C;
   Module M("SSAUpdaterTest", C);
-  IRBuilder<> B(C);
+  IRBuilder<> B(M);
   Type *I32Ty = B.getInt32Ty();
   auto *F = Function::Create(FunctionType::get(B.getVoidTy(), {I32Ty}, false),
                              GlobalValue::ExternalLinkage, "F", &M);
@@ -112,7 +112,7 @@ TEST(SSAUpdaterBulk, Irreducible) {
   SSAUpdaterBulk Updater;
   LLVMContext C;
   Module M("SSAUpdaterTest", C);
-  IRBuilder<> B(C);
+  IRBuilder<> B(M);
   Type *I32Ty = B.getInt32Ty();
   auto *F = Function::Create(FunctionType::get(B.getVoidTy(), {I32Ty}, false),
                              GlobalValue::ExternalLinkage, "F", &M);

diff  --git a/mlir/lib/ExecutionEngine/ExecutionEngine.cpp b/mlir/lib/ExecutionEngine/ExecutionEngine.cpp
index 27458f9d51e907..c8f4e81ddf07b3 100644
--- a/mlir/lib/ExecutionEngine/ExecutionEngine.cpp
+++ b/mlir/lib/ExecutionEngine/ExecutionEngine.cpp
@@ -143,7 +143,7 @@ static std::string makePackedFunctionName(StringRef name) {
 // pointer to provide a unified invocation interface.
 static void packFunctionArguments(Module *module) {
   auto &ctx = module->getContext();
-  llvm::IRBuilder<> builder(ctx);
+  llvm::IRBuilder<> builder(*module);
   DenseSet<llvm::Function *> interfaceFunctions;
   for (auto &func : module->getFunctionList()) {
     if (func.isDeclaration() || func.hasLocalLinkage())

diff  --git a/mlir/lib/Target/LLVMIR/Dialect/GPU/SelectObjectAttr.cpp b/mlir/lib/Target/LLVMIR/Dialect/GPU/SelectObjectAttr.cpp
index 016159391c33fc..d40a2789a9feb1 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/GPU/SelectObjectAttr.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/GPU/SelectObjectAttr.cpp
@@ -122,7 +122,7 @@ static LogicalResult embedBinaryImpl(StringRef moduleName,
       optLevel = optAttr.getValue();
   }
 
-  IRBuilder<> builder(module.getContext());
+  IRBuilder<> builder(module);
   auto *i32Ty = builder.getInt32Ty();
   auto *i64Ty = builder.getInt64Ty();
   auto *ptrTy = builder.getPtrTy(0);

diff  --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
index 9f992805dc900f..5b1bbcd3bdc31f 100644
--- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -1386,8 +1386,7 @@ LogicalResult ModuleTranslation::convertGlobalsAndAliases() {
   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
     if (Block *initializer = op.getInitializerBlock()) {
       llvm::IRBuilder<llvm::TargetFolder> builder(
-          llvmModule->getContext(),
-          llvm::TargetFolder(llvmModule->getDataLayout()));
+          *llvmModule, llvm::TargetFolder(llvmModule->getDataLayout()));
 
       [[maybe_unused]] int numConstantsHit = 0;
       [[maybe_unused]] int numConstantsErased = 0;
@@ -1478,8 +1477,7 @@ LogicalResult ModuleTranslation::convertGlobalsAndAliases() {
     if ((ctorOp && ctorOp.getCtors().empty()) ||
         (dtorOp && dtorOp.getDtors().empty())) {
       llvm::IRBuilder<llvm::TargetFolder> builder(
-          llvmModule->getContext(),
-          llvm::TargetFolder(llvmModule->getDataLayout()));
+          *llvmModule, llvm::TargetFolder(llvmModule->getDataLayout()));
       llvm::Type *eltTy = llvm::StructType::get(
           builder.getInt32Ty(), builder.getPtrTy(), builder.getPtrTy());
       llvm::ArrayType *at = llvm::ArrayType::get(eltTy, 0);
@@ -1522,8 +1520,7 @@ LogicalResult ModuleTranslation::convertGlobalsAndAliases() {
   for (auto op : getModuleBody(mlirModule).getOps<LLVM::AliasOp>()) {
     Block &initializer = op.getInitializerBlock();
     llvm::IRBuilder<llvm::TargetFolder> builder(
-        llvmModule->getContext(),
-        llvm::TargetFolder(llvmModule->getDataLayout()));
+        *llvmModule, llvm::TargetFolder(llvmModule->getDataLayout()));
 
     for (mlir::Operation &op : initializer.without_terminator()) {
       if (failed(convertOperation(op, builder)))
@@ -1780,7 +1777,7 @@ LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
   // converted before uses.
   auto blocks = getBlocksSortedByDominance(func.getBody());
   for (Block *bb : blocks) {
-    CapturingIRBuilder builder(llvmContext,
+    CapturingIRBuilder builder(*llvmModule,
                                llvm::TargetFolder(llvmModule->getDataLayout()));
     if (failed(convertBlockImpl(*bb, bb->isEntryBlock(), builder,
                                 /*recordInsertions=*/true)))
@@ -2740,7 +2737,7 @@ mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
 
   ModuleTranslation translator(module, std::move(llvmModule), fs);
   llvm::IRBuilder<llvm::TargetFolder> llvmBuilder(
-      llvmContext,
+      *translator.getLLVMModule(),
       llvm::TargetFolder(translator.getLLVMModule()->getDataLayout()));
 
   // Convert module before functions and operations inside, so dialect

diff  --git a/polly/lib/CodeGen/PerfMonitor.cpp b/polly/lib/CodeGen/PerfMonitor.cpp
index 7b559e990b7c03..b3e3b6f1d00e73 100644
--- a/polly/lib/CodeGen/PerfMonitor.cpp
+++ b/polly/lib/CodeGen/PerfMonitor.cpp
@@ -62,8 +62,7 @@ Function *PerfMonitor::getRDTSCP() {
   return Intrinsic::getOrInsertDeclaration(M, Intrinsic::x86_rdtscp);
 }
 
-PerfMonitor::PerfMonitor(const Scop &S, Module *M)
-    : M(M), Builder(M->getContext()), S(S) {
+PerfMonitor::PerfMonitor(const Scop &S, Module *M) : M(M), Builder(*M), S(S) {
   if (M->getTargetTriple().getArch() == llvm::Triple::x86_64)
     Supported = true;
   else


        


More information about the Mlir-commits mailing list