Index: bindings/ocaml/llvm/llvm.mli
===================================================================
--- bindings/ocaml/llvm/llvm.mli
+++ bindings/ocaml/llvm/llvm.mli
@@ -434,7 +434,7 @@
     [llvm::LLVMContext::~LLVMContext]. *)
 val dispose_context : llcontext -> unit
 
-(** See the function [llvm::getGlobalContext]. *)
+(** See the function [LLVMGetGlobalContext]. *)
 val global_context : unit -> llcontext
 
 (** [mdkind_id context name] returns the MDKind ID that corresponds to the
Index: docs/ProgrammersManual.rst
===================================================================
--- docs/ProgrammersManual.rst
+++ docs/ProgrammersManual.rst
@@ -2419,11 +2419,6 @@
 are adding new entities to LLVM IR, please try to maintain this interface
 design.
 
-For clients that do *not* require the benefits of isolation, LLVM provides a
-convenience API ``getGlobalContext()``.  This returns a global, lazily
-initialized ``LLVMContext`` that may be used in situations where isolation is
-not a concern.
-
 .. _jitthreading:
 
 Threads and the JIT
Index: docs/ReleaseNotes.rst
===================================================================
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -38,6 +38,8 @@
   (other than GlobalValue). This is intended to be used in release builds by
   clients that are interested in saving CPU/memory as much as possible.
 
+* There is no longer a "global context" available in LLVM, except for the C API.
+
 * .. note about autoconf build having been removed.
 
 * .. note about C API functions LLVMParseBitcode,
Index: docs/tutorial/LangImpl3.rst
===================================================================
--- docs/tutorial/LangImpl3.rst
+++ docs/tutorial/LangImpl3.rst
@@ -74,7 +74,7 @@
 .. code-block:: c++
 
     static std::unique_ptr<Module> *TheModule;
-    static IRBuilder<> Builder(getGlobalContext());
+    static IRBuilder<> Builder(LLVMContext);
     static std::map<std::string, Value*> NamedValues;
 
     Value *LogErrorV(const char *Str) {
@@ -116,7 +116,7 @@
 .. code-block:: c++
 
     Value *NumberExprAST::codegen() {
-      return ConstantFP::get(getGlobalContext(), APFloat(Val));
+      return ConstantFP::get(LLVMContext, APFloat(Val));
     }
 
 In the LLVM IR, numeric constants are represented with the
@@ -165,7 +165,7 @@
       case '<':
         L = Builder.CreateFCmpULT(L, R, "cmptmp");
         // Convert bool 0/1 to double 0.0 or 1.0
-        return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+        return Builder.CreateUIToFP(L, Type::getDoubleTy(LLVMContext),
                                     "booltmp");
       default:
         return LogErrorV("invalid binary operator");
@@ -264,9 +264,9 @@
     Function *PrototypeAST::codegen() {
       // Make the function type:  double(double,double) etc.
       std::vector<Type*> Doubles(Args.size(),
-                                 Type::getDoubleTy(getGlobalContext()));
+                                 Type::getDoubleTy(LLVMContext));
       FunctionType *FT =
-        FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
+        FunctionType::get(Type::getDoubleTy(LLVMContext), Doubles, false);
 
       Function *F =
         Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
@@ -340,7 +340,7 @@
 .. code-block:: c++
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(LLVMContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Record the function arguments in the NamedValues map.
Index: docs/tutorial/LangImpl4.rst
===================================================================
--- docs/tutorial/LangImpl4.rst
+++ docs/tutorial/LangImpl4.rst
@@ -131,7 +131,8 @@
 
     void InitializeModuleAndPassManager(void) {
       // Open a new module.
-      TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
+      Context LLVMContext;
+      TheModule = llvm::make_unique<Module>("my cool jit", LLVMContext);
       TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
 
       // Create a new pass manager attached to it.
Index: docs/tutorial/LangImpl5.rst
===================================================================
--- docs/tutorial/LangImpl5.rst
+++ docs/tutorial/LangImpl5.rst
@@ -292,7 +292,7 @@
 
       // Convert condition to a bool by comparing equal to 0.0.
       CondV = Builder.CreateFCmpONE(
-          CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
+          CondV, ConstantFP::get(LLVMContext, APFloat(0.0)), "ifcond");
 
 This code is straightforward and similar to what we saw before. We emit
 the expression for the condition, then compare that value to zero to get
@@ -305,9 +305,9 @@
       // Create blocks for the then and else cases.  Insert the 'then' block at the
       // end of the function.
       BasicBlock *ThenBB =
-          BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-      BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-      BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+          BasicBlock::Create(LLVMContext, "then", TheFunction);
+      BasicBlock *ElseBB = BasicBlock::Create(LLVMContext, "else");
+      BasicBlock *MergeBB = BasicBlock::Create(LLVMContext, "ifcont");
 
       Builder.CreateCondBr(CondV, ThenBB, ElseBB);
 
@@ -400,7 +400,7 @@
       TheFunction->getBasicBlockList().push_back(MergeBB);
       Builder.SetInsertPoint(MergeBB);
       PHINode *PN =
-        Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
+        Builder.CreatePHI(Type::getDoubleTy(LLVMContext), 2, "iftmp");
 
       PN->addIncoming(ThenV, ThenBB);
       PN->addIncoming(ElseV, ElseBB);
@@ -625,7 +625,7 @@
       Function *TheFunction = Builder.GetInsertBlock()->getParent();
       BasicBlock *PreheaderBB = Builder.GetInsertBlock();
       BasicBlock *LoopBB =
-          BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+          BasicBlock::Create(LLVMContext, "loop", TheFunction);
 
       // Insert an explicit fall through from the current block to the LoopBB.
       Builder.CreateBr(LoopBB);
@@ -642,7 +642,7 @@
       Builder.SetInsertPoint(LoopBB);
 
       // Start the PHI node with an entry for Start.
-      PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
+      PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(LLVMContext),
                                             2, VarName.c_str());
       Variable->addIncoming(StartVal, PreheaderBB);
 
@@ -693,7 +693,7 @@
           return nullptr;
       } else {
         // If not specified, use 1.0.
-        StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+        StepVal = ConstantFP::get(LLVMContext, APFloat(1.0));
       }
 
       Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
@@ -712,7 +712,7 @@
 
       // Convert condition to a bool by comparing equal to 0.0.
       EndCond = Builder.CreateFCmpONE(
-          EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
+          EndCond, ConstantFP::get(LLVMContext, APFloat(0.0)), "loopcond");
 
 Finally, we evaluate the exit value of the loop, to determine whether
 the loop should exit. This mirrors the condition evaluation for the
@@ -723,7 +723,7 @@
       // Create the "after loop" block and insert it.
       BasicBlock *LoopEndBB = Builder.GetInsertBlock();
       BasicBlock *AfterBB =
-          BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+          BasicBlock::Create(LLVMContext, "afterloop", TheFunction);
 
       // Insert the conditional branch into the end of LoopEndBB.
       Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -751,7 +751,7 @@
         NamedValues.erase(VarName);
 
       // for expr always returns 0.0.
-      return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+      return Constant::getNullValue(Type::getDoubleTy(LLVMContext));
     }
 
 The final code handles various cleanups: now that we have the "NextVar"
Index: docs/tutorial/LangImpl6.rst
===================================================================
--- docs/tutorial/LangImpl6.rst
+++ docs/tutorial/LangImpl6.rst
@@ -251,7 +251,7 @@
       case '<':
         L = Builder.CreateFCmpULT(L, R, "cmptmp");
         // Convert bool 0/1 to double 0.0 or 1.0
-        return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+        return Builder.CreateUIToFP(L, Type::getDoubleTy(LLVMContext),
                                     "booltmp");
       default:
         break;
@@ -288,7 +288,7 @@
         BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
 
       // Create a new basic block to start insertion into.
-      BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+      BasicBlock *BB = BasicBlock::Create(LLVMContext, "entry", TheFunction);
       Builder.SetInsertPoint(BB);
 
       if (Value *RetVal = Body->codegen()) {
Index: docs/tutorial/LangImpl7.rst
===================================================================
--- docs/tutorial/LangImpl7.rst
+++ docs/tutorial/LangImpl7.rst
@@ -339,7 +339,7 @@
                                               const std::string &VarName) {
       IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                      TheFunction->getEntryBlock().begin());
-      return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+      return TmpB.CreateAlloca(Type::getDoubleTy(LLVMContext), 0,
                                VarName.c_str());
     }
 
@@ -812,7 +812,7 @@
           if (!InitVal)
             return nullptr;
         } else { // If not specified, use 0.0.
-          InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+          InitVal = ConstantFP::get(LLVMContext, APFloat(0.0));
         }
 
         AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Index: examples/BrainF/BrainFDriver.cpp
===================================================================
--- examples/BrainF/BrainFDriver.cpp
+++ examples/BrainF/BrainFDriver.cpp
@@ -88,7 +88,7 @@
 int main(int argc, char **argv) {
   cl::ParseCommandLineOptions(argc, argv, " BrainF compiler\n");
 
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
 
   if (InputFilename == "") {
     errs() << "Error: You must specify the filename of the program to "
Index: examples/ExceptionDemo/ExceptionDemo.cpp
===================================================================
--- examples/ExceptionDemo/ExceptionDemo.cpp
+++ examples/ExceptionDemo/ExceptionDemo.cpp
@@ -1951,12 +1951,12 @@
 
   llvm::InitializeNativeTarget();
   llvm::InitializeNativeTargetAsmPrinter();
-  llvm::LLVMContext &context = llvm::getGlobalContext();
-  llvm::IRBuilder<> theBuilder(context);
+  llvm::LLVMContext Context;
+  llvm::IRBuilder<> theBuilder(Context);
 
   // Make the module, which holds all the code.
   std::unique_ptr<llvm::Module> Owner =
-      llvm::make_unique<llvm::Module>("my cool jit", context);
+      llvm::make_unique<llvm::Module>("my cool jit", Context);
   llvm::Module *module = Owner.get();
 
   std::unique_ptr<llvm::RTDyldMemoryManager> MemMgr(new llvm::SectionMemoryManager());
Index: examples/Kaleidoscope/Chapter3/toy.cpp
===================================================================
--- examples/Kaleidoscope/Chapter3/toy.cpp
+++ examples/Kaleidoscope/Chapter3/toy.cpp
@@ -381,7 +381,8 @@
 //===----------------------------------------------------------------------===//
 
 static std::unique_ptr<Module> TheModule;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, Value *> NamedValues;
 
 Value *LogErrorV(const char *Str) {
@@ -390,7 +391,7 @@
 }
 
 Value *NumberExprAST::codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::codegen() {
@@ -417,7 +418,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default:
     return LogErrorV("invalid binary operator");
@@ -447,9 +448,9 @@
 Function *PrototypeAST::codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type *> Doubles(Args.size(),
-                              Type::getDoubleTy(getGlobalContext()));
+                              Type::getDoubleTy(TheContext));
   FunctionType *FT =
-      FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
+      FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
 
   Function *F =
       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
@@ -473,7 +474,7 @@
     return nullptr;
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Record the function arguments in the NamedValues map.
@@ -577,7 +578,7 @@
   getNextToken();
 
   // Make the module, which holds all the code.
-  TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
+  TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
 
   // Run the main "interpreter loop" now.
   MainLoop();
Index: examples/Kaleidoscope/Chapter4/toy.cpp
===================================================================
--- examples/Kaleidoscope/Chapter4/toy.cpp
+++ examples/Kaleidoscope/Chapter4/toy.cpp
@@ -388,7 +388,8 @@
 //===----------------------------------------------------------------------===//
 
 static std::unique_ptr<Module> TheModule;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, Value *> NamedValues;
 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
@@ -415,7 +416,7 @@
 }
 
 Value *NumberExprAST::codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::codegen() {
@@ -442,7 +443,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default:
     return LogErrorV("invalid binary operator");
@@ -472,9 +473,9 @@
 Function *PrototypeAST::codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type *> Doubles(Args.size(),
-                              Type::getDoubleTy(getGlobalContext()));
+                              Type::getDoubleTy(TheContext));
   FunctionType *FT =
-      FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
+      FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
 
   Function *F =
       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
@@ -497,7 +498,7 @@
     return nullptr;
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Record the function arguments in the NamedValues map.
@@ -529,7 +530,7 @@
 
 static void InitializeModuleAndPassManager() {
   // Open a new module.
-  TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
+  TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
   TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
 
   // Create a new pass manager attached to it.
Index: examples/Kaleidoscope/Chapter5/toy.cpp
===================================================================
--- examples/Kaleidoscope/Chapter5/toy.cpp
+++ examples/Kaleidoscope/Chapter5/toy.cpp
@@ -512,7 +512,8 @@
 //===----------------------------------------------------------------------===//
 
 static std::unique_ptr<Module> TheModule;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, Value *> NamedValues;
 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
@@ -539,7 +540,7 @@
 }
 
 Value *NumberExprAST::codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::codegen() {
@@ -566,7 +567,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default:
     return LogErrorV("invalid binary operator");
@@ -600,16 +601,16 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(
-      CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
+      CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
 
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
 
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
   BasicBlock *ThenBB =
-      BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+      BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
 
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
 
@@ -640,7 +641,7 @@
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
   PHINode *PN =
-      Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
+      Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
   PN->addIncoming(ElseV, ElseBB);
@@ -673,7 +674,7 @@
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
   BasicBlock *PreheaderBB = Builder.GetInsertBlock();
   BasicBlock *LoopBB =
-      BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+      BasicBlock::Create(TheContext, "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -682,7 +683,7 @@
   Builder.SetInsertPoint(LoopBB);
 
   // Start the PHI node with an entry for Start.
-  PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
+  PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(TheContext),
                                         2, VarName.c_str());
   Variable->addIncoming(StartVal, PreheaderBB);
 
@@ -705,7 +706,7 @@
       return nullptr;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
 
   Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
@@ -717,12 +718,12 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(
-      EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
+      EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
 
   // Create the "after loop" block and insert it.
   BasicBlock *LoopEndBB = Builder.GetInsertBlock();
   BasicBlock *AfterBB =
-      BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+      BasicBlock::Create(TheContext, "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -740,15 +741,15 @@
     NamedValues.erase(VarName);
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Function *PrototypeAST::codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type *> Doubles(Args.size(),
-                              Type::getDoubleTy(getGlobalContext()));
+                              Type::getDoubleTy(TheContext));
   FunctionType *FT =
-      FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
+      FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
 
   Function *F =
       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
@@ -771,7 +772,7 @@
     return nullptr;
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Record the function arguments in the NamedValues map.
@@ -803,7 +804,7 @@
 
 static void InitializeModuleAndPassManager() {
   // Open a new module.
-  TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
+  TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
   TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
 
   // Create a new pass manager attached to it.
Index: examples/Kaleidoscope/Chapter6/toy.cpp
===================================================================
--- examples/Kaleidoscope/Chapter6/toy.cpp
+++ examples/Kaleidoscope/Chapter6/toy.cpp
@@ -603,7 +603,8 @@
 //===----------------------------------------------------------------------===//
 
 static std::unique_ptr<Module> TheModule;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, Value *> NamedValues;
 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
@@ -630,7 +631,7 @@
 }
 
 Value *NumberExprAST::codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::codegen() {
@@ -669,7 +670,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default:
     break;
@@ -711,16 +712,16 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(
-      CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
+      CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
 
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
 
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
   BasicBlock *ThenBB =
-      BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+      BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
 
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
 
@@ -751,7 +752,7 @@
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
   PHINode *PN =
-      Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
+      Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
   PN->addIncoming(ElseV, ElseBB);
@@ -784,7 +785,7 @@
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
   BasicBlock *PreheaderBB = Builder.GetInsertBlock();
   BasicBlock *LoopBB =
-      BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+      BasicBlock::Create(TheContext, "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -793,7 +794,7 @@
   Builder.SetInsertPoint(LoopBB);
 
   // Start the PHI node with an entry for Start.
-  PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
+  PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(TheContext),
                                         2, VarName.c_str());
   Variable->addIncoming(StartVal, PreheaderBB);
 
@@ -816,7 +817,7 @@
       return nullptr;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
 
   Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
@@ -828,12 +829,12 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(
-      EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
+      EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
 
   // Create the "after loop" block and insert it.
   BasicBlock *LoopEndBB = Builder.GetInsertBlock();
   BasicBlock *AfterBB =
-      BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+      BasicBlock::Create(TheContext, "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -851,15 +852,15 @@
     NamedValues.erase(VarName);
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Function *PrototypeAST::codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type *> Doubles(Args.size(),
-                              Type::getDoubleTy(getGlobalContext()));
+                              Type::getDoubleTy(TheContext));
   FunctionType *FT =
-      FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
+      FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
 
   Function *F =
       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
@@ -886,7 +887,7 @@
     BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Record the function arguments in the NamedValues map.
@@ -921,7 +922,7 @@
 
 static void InitializeModuleAndPassManager() {
   // Open a new module.
-  TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
+  TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
   TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
 
   // Create a new pass manager attached to it.
Index: examples/Kaleidoscope/Chapter7/toy.cpp
===================================================================
--- examples/Kaleidoscope/Chapter7/toy.cpp
+++ examples/Kaleidoscope/Chapter7/toy.cpp
@@ -673,7 +673,8 @@
 //===----------------------------------------------------------------------===//
 
 static std::unique_ptr<Module> TheModule;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, AllocaInst *> NamedValues;
 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
@@ -705,12 +706,12 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                    TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), nullptr,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), nullptr,
                            VarName.c_str());
 }
 
 Value *NumberExprAST::codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::codegen() {
@@ -774,7 +775,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default:
     break;
@@ -816,16 +817,16 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(
-      CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
+      CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
 
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
 
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
   BasicBlock *ThenBB =
-      BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+      BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
 
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
 
@@ -856,7 +857,7 @@
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
   PHINode *PN =
-      Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
+      Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
   PN->addIncoming(ElseV, ElseBB);
@@ -899,7 +900,7 @@
   // Make the new basic block for the loop header, inserting after current
   // block.
   BasicBlock *LoopBB =
-      BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+      BasicBlock::Create(TheContext, "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -926,7 +927,7 @@
       return nullptr;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -942,11 +943,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(
-      EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
+      EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
 
   // Create the "after loop" block and insert it.
   BasicBlock *AfterBB =
-      BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+      BasicBlock::Create(TheContext, "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -961,7 +962,7 @@
     NamedValues.erase(VarName);
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Value *VarExprAST::codegen() {
@@ -985,7 +986,7 @@
       if (!InitVal)
         return nullptr;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(TheContext, APFloat(0.0));
     }
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -1015,9 +1016,9 @@
 Function *PrototypeAST::codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type *> Doubles(Args.size(),
-                              Type::getDoubleTy(getGlobalContext()));
+                              Type::getDoubleTy(TheContext));
   FunctionType *FT =
-      FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
+      FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
 
   Function *F =
       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
@@ -1044,7 +1045,7 @@
     BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Record the function arguments in the NamedValues map.
@@ -1087,7 +1088,7 @@
 
 static void InitializeModuleAndPassManager() {
   // Open a new module.
-  TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
+  TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
   TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
 
   // Create a new pass manager attached to it.
Index: examples/Kaleidoscope/Chapter8/toy.cpp
===================================================================
--- examples/Kaleidoscope/Chapter8/toy.cpp
+++ examples/Kaleidoscope/Chapter8/toy.cpp
@@ -87,7 +87,8 @@
 class PrototypeAST;
 class ExprAST;
 }
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 struct DebugInfo {
   DICompileUnit *TheCU;
   DIType *DblTy;
@@ -886,13 +887,13 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                    TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), nullptr,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), nullptr,
                            VarName.c_str());
 }
 
 Value *NumberExprAST::codegen() {
   KSDbgInfo.emitLocation(this);
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::codegen() {
@@ -960,7 +961,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default:
     break;
@@ -1006,16 +1007,16 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(
-      CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
+      CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
 
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
 
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
   BasicBlock *ThenBB =
-      BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+      BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
 
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
 
@@ -1046,7 +1047,7 @@
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
   PHINode *PN =
-      Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
+      Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
   PN->addIncoming(ElseV, ElseBB);
@@ -1091,7 +1092,7 @@
   // Make the new basic block for the loop header, inserting after current
   // block.
   BasicBlock *LoopBB =
-      BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+      BasicBlock::Create(TheContext, "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -1118,7 +1119,7 @@
       return nullptr;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -1134,11 +1135,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(
-      EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
+      EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
 
   // Create the "after loop" block and insert it.
   BasicBlock *AfterBB =
-      BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+      BasicBlock::Create(TheContext, "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -1153,7 +1154,7 @@
     NamedValues.erase(VarName);
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Value *VarExprAST::codegen() {
@@ -1177,7 +1178,7 @@
       if (!InitVal)
         return nullptr;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(TheContext, APFloat(0.0));
     }
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -1209,9 +1210,9 @@
 Function *PrototypeAST::codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type *> Doubles(Args.size(),
-                              Type::getDoubleTy(getGlobalContext()));
+                              Type::getDoubleTy(TheContext));
   FunctionType *FT =
-      FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
+      FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
 
   Function *F =
       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
@@ -1238,7 +1239,7 @@
     BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Create a subprogram DIE for this function.
@@ -1319,7 +1320,7 @@
 
 static void InitializeModule() {
   // Open a new module.
-  TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
+  TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
   TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
 }
 
Index: examples/Kaleidoscope/MCJIT/cached/toy-jit.cpp
===================================================================
--- examples/Kaleidoscope/MCJIT/cached/toy-jit.cpp
+++ examples/Kaleidoscope/MCJIT/cached/toy-jit.cpp
@@ -623,7 +623,8 @@
 
 static Module *TheModule;
 static FunctionPassManager *TheFPM;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, AllocaInst*> NamedValues;
 
 Value *ErrorV(const char *Str) { Error(Str); return 0; }
@@ -634,12 +635,12 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), 0,
                            VarName.c_str());
 }
 
 Value *NumberExprAST::Codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::Codegen() {
@@ -699,7 +700,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default: break;
   }
@@ -741,16 +742,16 @@
   
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(CondV, 
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                 "ifcond");
   
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
   
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
-  BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+  BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
   
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
   
@@ -778,7 +779,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
-  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2,
                                   "iftmp");
   
   PN->addIncoming(ThenV, ThenBB);
@@ -821,7 +822,7 @@
   
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
   
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -847,7 +848,7 @@
     if (StepVal == 0) return 0;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
   
   // Compute the end condition.
@@ -862,11 +863,11 @@
   
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(EndCond, 
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                   "loopcond");
   
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(TheContext, "afterloop", TheFunction);
   
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -882,7 +883,7 @@
 
   
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Value *VarExprAST::Codegen() {
@@ -905,7 +906,7 @@
       InitVal = Init->Codegen();
       if (InitVal == 0) return 0;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(TheContext, APFloat(0.0));
     }
     
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -934,8 +935,8 @@
 Function *PrototypeAST::Codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(), 
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(TheContext));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(TheContext),
                                        Doubles, false);
 
   Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
@@ -994,7 +995,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
   
   // Add all arguments to the symbol table and create their allocas.
@@ -1122,7 +1123,7 @@
 
 Module* parseInputIR(std::string InputFile) {
   SMDiagnostic Err;
-  Module *M = ParseIRFile(InputFile, Err, getGlobalContext());
+  Module *M = ParseIRFile(InputFile, Err, TheContext);
   if (!M) {
     Err.print("IR parsing failed: ", errs());
     return NULL;
@@ -1137,7 +1138,7 @@
 
 int main(int argc, char **argv) {
   InitializeNativeTarget();
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext &Context = TheContext;
 
   cl::ParseCommandLineOptions(argc, argv,
                               "Kaleidoscope example program\n");
Index: examples/Kaleidoscope/MCJIT/cached/toy.cpp
===================================================================
--- examples/Kaleidoscope/MCJIT/cached/toy.cpp
+++ examples/Kaleidoscope/MCJIT/cached/toy.cpp
@@ -994,7 +994,8 @@
 //===----------------------------------------------------------------------===//
 
 static MCJITHelper *TheHelper;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, AllocaInst*> NamedValues;
 
 Value *ErrorV(const char *Str) { Error(Str); return 0; }
@@ -1005,12 +1006,12 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), 0,
                            VarName.c_str());
 }
 
 Value *NumberExprAST::Codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::Codegen() {
@@ -1066,7 +1067,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default: break;
   }
@@ -1105,16 +1106,16 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(CondV,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                 "ifcond");
 
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
 
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
-  BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+  BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
 
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
 
@@ -1142,7 +1143,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
-  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2,
                                   "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
@@ -1185,7 +1186,7 @@
 
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -1211,7 +1212,7 @@
     if (StepVal == 0) return 0;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -1226,11 +1227,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(EndCond,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                   "loopcond");
 
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(TheContext, "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -1246,7 +1247,7 @@
 
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Value *VarExprAST::Codegen() {
@@ -1269,7 +1270,7 @@
       InitVal = Init->Codegen();
       if (InitVal == 0) return 0;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(TheContext, APFloat(0.0));
     }
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -1298,8 +1299,8 @@
 Function *PrototypeAST::Codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(),
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(TheContext));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(TheContext),
                                        Doubles, false);
 
   std::string FnName = MakeLegalFunctionName(Name);
@@ -1365,7 +1366,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Add all arguments to the symbol table and create their allocas.
@@ -1490,7 +1491,7 @@
 
 Module* parseInputIR(std::string InputFile) {
   SMDiagnostic Err;
-  Module *M = ParseIRFile(InputFile, Err, getGlobalContext());
+  Module *M = ParseIRFile(InputFile, Err, TheContext);
   if (!M) {
     Err.print("IR parsing failed: ", errs());
     return NULL;
@@ -1512,7 +1513,7 @@
   InitializeNativeTarget();
   InitializeNativeTargetAsmPrinter();
   InitializeNativeTargetAsmParser();
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext &Context = TheContext;
 
   cl::ParseCommandLineOptions(argc, argv,
                               "Kaleidoscope example program\n");
Index: examples/Kaleidoscope/MCJIT/complete/toy.cpp
===================================================================
--- examples/Kaleidoscope/MCJIT/complete/toy.cpp
+++ examples/Kaleidoscope/MCJIT/complete/toy.cpp
@@ -1066,7 +1066,8 @@
 //===----------------------------------------------------------------------===//
 
 static BaseHelper *TheHelper;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, AllocaInst*> NamedValues;
 
 Value *ErrorV(const char *Str) { Error(Str); return 0; }
@@ -1077,12 +1078,12 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), 0,
                            VarName.c_str());
 }
 
 Value *NumberExprAST::Codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::Codegen() {
@@ -1140,7 +1141,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default: break;
   }
@@ -1183,16 +1184,16 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(CondV,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                 "ifcond");
 
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
 
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
-  BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+  BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
 
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
 
@@ -1220,7 +1221,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
-  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2,
                                   "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
@@ -1263,7 +1264,7 @@
 
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -1289,7 +1290,7 @@
     if (StepVal == 0) return 0;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -1304,11 +1305,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(EndCond,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                   "loopcond");
 
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(TheContext, "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -1324,7 +1325,7 @@
 
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Value *VarExprAST::Codegen() {
@@ -1347,7 +1348,7 @@
       InitVal = Init->Codegen();
       if (InitVal == 0) return 0;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(TheContext, APFloat(0.0));
     }
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -1376,8 +1377,8 @@
 Function *PrototypeAST::Codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(),
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(TheContext));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(TheContext),
                                        Doubles, false);
 
   std::string FnName;
@@ -1443,7 +1444,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Add all arguments to the symbol table and create their allocas.
@@ -1565,7 +1566,7 @@
   InitializeNativeTarget();
   InitializeNativeTargetAsmPrinter();
   InitializeNativeTargetAsmParser();
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext &Context = TheContext;
 
   cl::ParseCommandLineOptions(argc, argv,
                               "Kaleidoscope example program\n");
Index: examples/Kaleidoscope/MCJIT/initial/toy.cpp
===================================================================
--- examples/Kaleidoscope/MCJIT/initial/toy.cpp
+++ examples/Kaleidoscope/MCJIT/initial/toy.cpp
@@ -852,7 +852,8 @@
 //===----------------------------------------------------------------------===//
 
 static MCJITHelper *TheHelper;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, AllocaInst*> NamedValues;
 
 Value *ErrorV(const char *Str) { Error(Str); return 0; }
@@ -863,12 +864,12 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), 0,
                            VarName.c_str());
 }
 
 Value *NumberExprAST::Codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::Codegen() {
@@ -924,7 +925,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default: break;
   }
@@ -963,16 +964,16 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(CondV,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                 "ifcond");
 
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
 
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
-  BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+  BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
 
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
 
@@ -1000,7 +1001,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
-  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2,
                                   "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
@@ -1043,7 +1044,7 @@
 
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -1069,7 +1070,7 @@
     if (StepVal == 0) return 0;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -1084,11 +1085,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(EndCond,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                   "loopcond");
 
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(TheContext, "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -1104,7 +1105,7 @@
 
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Value *VarExprAST::Codegen() {
@@ -1127,7 +1128,7 @@
       InitVal = Init->Codegen();
       if (InitVal == 0) return 0;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(TheContext, APFloat(0.0));
     }
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -1156,8 +1157,8 @@
 Function *PrototypeAST::Codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(),
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(TheContext));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(TheContext),
                                        Doubles, false);
 
   std::string FnName = MakeLegalFunctionName(Name);
@@ -1223,7 +1224,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Add all arguments to the symbol table and create their allocas.
@@ -1349,7 +1350,7 @@
   InitializeNativeTarget();
   InitializeNativeTargetAsmPrinter();
   InitializeNativeTargetAsmParser();
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext &Context = TheContext;
 
   // Install standard binary operators.
   // 1 is lowest precedence.
Index: examples/Kaleidoscope/MCJIT/lazy/toy-jit.cpp
===================================================================
--- examples/Kaleidoscope/MCJIT/lazy/toy-jit.cpp
+++ examples/Kaleidoscope/MCJIT/lazy/toy-jit.cpp
@@ -608,7 +608,8 @@
 
 static Module *TheModule;
 static FunctionPassManager *TheFPM;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, AllocaInst*> NamedValues;
 
 Value *ErrorV(const char *Str) { Error(Str); return 0; }
@@ -619,12 +620,12 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), 0,
                            VarName.c_str());
 }
 
 Value *NumberExprAST::Codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::Codegen() {
@@ -681,7 +682,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default: break;
   }
@@ -723,16 +724,16 @@
   
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(CondV, 
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                 "ifcond");
   
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
   
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
-  BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+  BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
   
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
   
@@ -760,7 +761,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
-  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2,
                                   "iftmp");
   
   PN->addIncoming(ThenV, ThenBB);
@@ -803,7 +804,7 @@
   
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
   
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -829,7 +830,7 @@
     if (StepVal == 0) return 0;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
   
   // Compute the end condition.
@@ -844,11 +845,11 @@
   
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(EndCond, 
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                   "loopcond");
   
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(TheContext, "afterloop", TheFunction);
   
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -864,7 +865,7 @@
 
   
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Value *VarExprAST::Codegen() {
@@ -887,7 +888,7 @@
       InitVal = Init->Codegen();
       if (InitVal == 0) return 0;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(TheContext, APFloat(0.0));
     }
     
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -916,8 +917,8 @@
 Function *PrototypeAST::Codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(), 
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(TheContext));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(TheContext),
                                        Doubles, false);
 
   Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
@@ -976,7 +977,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
   
   // Add all arguments to the symbol table and create their allocas.
@@ -1104,7 +1105,7 @@
 
 int main(int argc, char **argv) {
   InitializeNativeTarget();
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext &Context = TheContext;
 
   // Install standard binary operators.
   // 1 is lowest precedence.
Index: examples/Kaleidoscope/MCJIT/lazy/toy.cpp
===================================================================
--- examples/Kaleidoscope/MCJIT/lazy/toy.cpp
+++ examples/Kaleidoscope/MCJIT/lazy/toy.cpp
@@ -892,7 +892,8 @@
 //===----------------------------------------------------------------------===//
 
 static MCJITHelper *TheHelper;
-static IRBuilder<> Builder(getGlobalContext());
+static LLVMContext TheContext;
+static IRBuilder<> Builder(TheContext);
 static std::map<std::string, AllocaInst*> NamedValues;
 
 Value *ErrorV(const char *Str) { Error(Str); return 0; }
@@ -903,12 +904,12 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), 0,
                            VarName.c_str());
 }
 
 Value *NumberExprAST::Codegen() {
-  return ConstantFP::get(getGlobalContext(), APFloat(Val));
+  return ConstantFP::get(TheContext, APFloat(Val));
 }
 
 Value *VariableExprAST::Codegen() {
@@ -964,7 +965,7 @@
   case '<':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
                                 "booltmp");
   default: break;
   }
@@ -1003,16 +1004,16 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(CondV,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                 "ifcond");
 
   Function *TheFunction = Builder.GetInsertBlock()->getParent();
 
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
-  BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
-  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
-  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
+  BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
+  BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
 
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
 
@@ -1040,7 +1041,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
-  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2,
                                   "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
@@ -1083,7 +1084,7 @@
 
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -1109,7 +1110,7 @@
     if (StepVal == 0) return 0;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -1124,11 +1125,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(EndCond,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(TheContext, APFloat(0.0)),
                                   "loopcond");
 
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(TheContext, "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -1144,7 +1145,7 @@
 
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(TheContext));
 }
 
 Value *VarExprAST::Codegen() {
@@ -1167,7 +1168,7 @@
       InitVal = Init->Codegen();
       if (InitVal == 0) return 0;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(TheContext, APFloat(0.0));
     }
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -1196,8 +1197,8 @@
 Function *PrototypeAST::Codegen() {
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(),
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(TheContext));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(TheContext),
                                        Doubles, false);
 
   std::string FnName = MakeLegalFunctionName(Name);
@@ -1263,7 +1264,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
   Builder.SetInsertPoint(BB);
 
   // Add all arguments to the symbol table and create their allocas.
@@ -1390,7 +1391,7 @@
   InitializeNativeTarget();
   InitializeNativeTargetAsmPrinter();
   InitializeNativeTargetAsmParser();
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext &Context = TheContext;
 
   // Install standard binary operators.
   // 1 is lowest precedence.
Index: examples/Kaleidoscope/Orc/fully_lazy/toy.cpp
===================================================================
--- examples/Kaleidoscope/Orc/fully_lazy/toy.cpp
+++ examples/Kaleidoscope/Orc/fully_lazy/toy.cpp
@@ -747,7 +747,7 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), nullptr,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheFunction->getContext()), nullptr,
                            VarName.c_str());
 }
 
@@ -807,7 +807,7 @@
   case '<':
     L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(C.getLLVMContext()),
                                 "booltmp");
   default: break;
   }
@@ -885,7 +885,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   C.getBuilder().SetInsertPoint(MergeBB);
-  PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(C.getLLVMContext()), 2,
                                   "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
@@ -928,7 +928,7 @@
 
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(C.getLLVMContext(), "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   C.getBuilder().CreateBr(LoopBB);
@@ -954,7 +954,7 @@
     if (!StepVal) return nullptr;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(C.getLLVMContext(), APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -969,11 +969,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = C.getBuilder().CreateFCmpONE(EndCond,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(C.getLLVMContext(), APFloat(0.0)),
                                   "loopcond");
 
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(C.getLLVMContext(), "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -988,7 +988,7 @@
     C.NamedValues.erase(VarName);
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(C.getLLVMContext()));
 }
 
 Value *VarExprAST::IRGen(IRGenContext &C) const {
@@ -1011,7 +1011,7 @@
       InitVal = Init->IRGen(C);
       if (!InitVal) return nullptr;
     } else // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
     C.getBuilder().CreateStore(InitVal, Alloca);
@@ -1041,8 +1041,8 @@
 
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(),
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(C.getLLVMContext()));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(C.getLLVMContext()),
                                        Doubles, false);
   Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
                                  &C.getM());
@@ -1104,7 +1104,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(C.getLLVMContext(), "entry", TheFunction);
   C.getBuilder().SetInsertPoint(BB);
 
   // Add all arguments to the symbol table and create their allocas.
@@ -1366,7 +1366,8 @@
 
 /// top ::= definition | external | expression | ';'
 static void MainLoop() {
-  SessionContext S(getGlobalContext());
+  LLVMContext TheContext;
+  SessionContext S(TheContext);
   KaleidoscopeJIT J(S);
 
   while (1) {
Index: examples/Kaleidoscope/Orc/initial/toy.cpp
===================================================================
--- examples/Kaleidoscope/Orc/initial/toy.cpp
+++ examples/Kaleidoscope/Orc/initial/toy.cpp
@@ -746,7 +746,7 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), nullptr,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheFunction->getContext()), nullptr,
                            VarName.c_str());
 }
 
@@ -806,7 +806,7 @@
   case '<':
     L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(C.getLLVMContext()),
                                 "booltmp");
   default: break;
   }
@@ -884,7 +884,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   C.getBuilder().SetInsertPoint(MergeBB);
-  PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(C.getLLVMContext()), 2,
                                   "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
@@ -927,7 +927,7 @@
 
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(C.getLLVMContext(), "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   C.getBuilder().CreateBr(LoopBB);
@@ -953,7 +953,7 @@
     if (!StepVal) return nullptr;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(C.getLLVMContext(), APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -968,11 +968,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = C.getBuilder().CreateFCmpONE(EndCond,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(C.getLLVMContext(), APFloat(0.0)),
                                   "loopcond");
 
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(C.getLLVMContext(), "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -987,7 +987,7 @@
     C.NamedValues.erase(VarName);
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(C.getLLVMContext()));
 }
 
 Value *VarExprAST::IRGen(IRGenContext &C) const {
@@ -1010,7 +1010,7 @@
       InitVal = Init->IRGen(C);
       if (!InitVal) return nullptr;
     } else // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
     C.getBuilder().CreateStore(InitVal, Alloca);
@@ -1040,8 +1040,8 @@
 
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(),
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(C.getLLVMContext()));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(C.getLLVMContext()),
                                        Doubles, false);
   Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
                                  &C.getM());
@@ -1103,7 +1103,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(C.getLLVMContext(), "entry", TheFunction);
   C.getBuilder().SetInsertPoint(BB);
 
   // Add all arguments to the symbol table and create their allocas.
@@ -1261,7 +1261,8 @@
 
 /// top ::= definition | external | expression | ';'
 static void MainLoop() {
-  SessionContext S(getGlobalContext());
+  LLVMContext TheContext;
+  SessionContext S(TheContext);
   KaleidoscopeJIT J(S);
 
   while (1) {
Index: examples/Kaleidoscope/Orc/lazy_codegen/toy.cpp
===================================================================
--- examples/Kaleidoscope/Orc/lazy_codegen/toy.cpp
+++ examples/Kaleidoscope/Orc/lazy_codegen/toy.cpp
@@ -746,7 +746,7 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), nullptr,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheFunction->getContext()), nullptr,
                            VarName.c_str());
 }
 
@@ -806,7 +806,7 @@
   case '<':
     L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(C.getLLVMContext()),
                                 "booltmp");
   default: break;
   }
@@ -884,7 +884,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   C.getBuilder().SetInsertPoint(MergeBB);
-  PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(C.getLLVMContext()), 2,
                                   "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
@@ -927,7 +927,7 @@
 
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(C.getLLVMContext(), "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   C.getBuilder().CreateBr(LoopBB);
@@ -953,7 +953,7 @@
     if (!StepVal) return nullptr;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(C.getLLVMContext(), APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -968,11 +968,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = C.getBuilder().CreateFCmpONE(EndCond,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(C.getLLVMContext(), APFloat(0.0)),
                                   "loopcond");
 
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(C.getLLVMContext(), "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -987,7 +987,7 @@
     C.NamedValues.erase(VarName);
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(C.getLLVMContext()));
 }
 
 Value *VarExprAST::IRGen(IRGenContext &C) const {
@@ -1010,7 +1010,7 @@
       InitVal = Init->IRGen(C);
       if (!InitVal) return nullptr;
     } else // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
     C.getBuilder().CreateStore(InitVal, Alloca);
@@ -1040,8 +1040,8 @@
 
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(),
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(C.getLLVMContext()));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(C.getLLVMContext()),
                                        Doubles, false);
   Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
                                  &C.getM());
@@ -1103,7 +1103,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(C.getLLVMContext(), "entry", TheFunction);
   C.getBuilder().SetInsertPoint(BB);
 
   // Add all arguments to the symbol table and create their allocas.
@@ -1265,7 +1265,8 @@
 
 /// top ::= definition | external | expression | ';'
 static void MainLoop() {
-  SessionContext S(getGlobalContext());
+  LLVMContext TheContext;
+  SessionContext S(TheContext);
   KaleidoscopeJIT J(S);
 
   while (1) {
Index: examples/Kaleidoscope/Orc/lazy_irgen/toy.cpp
===================================================================
--- examples/Kaleidoscope/Orc/lazy_irgen/toy.cpp
+++ examples/Kaleidoscope/Orc/lazy_irgen/toy.cpp
@@ -746,7 +746,7 @@
                                           const std::string &VarName) {
   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
                  TheFunction->getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), nullptr,
+  return TmpB.CreateAlloca(Type::getDoubleTy(TheFunction->getContext()), nullptr,
                            VarName.c_str());
 }
 
@@ -806,7 +806,7 @@
   case '<':
     L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+    return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(C.getLLVMContext()),
                                 "booltmp");
   default: break;
   }
@@ -884,7 +884,7 @@
   // Emit merge block.
   TheFunction->getBasicBlockList().push_back(MergeBB);
   C.getBuilder().SetInsertPoint(MergeBB);
-  PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+  PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(C.getLLVMContext()), 2,
                                   "iftmp");
 
   PN->addIncoming(ThenV, ThenBB);
@@ -927,7 +927,7 @@
 
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(C.getLLVMContext(), "loop", TheFunction);
 
   // Insert an explicit fall through from the current block to the LoopBB.
   C.getBuilder().CreateBr(LoopBB);
@@ -953,7 +953,7 @@
     if (!StepVal) return nullptr;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
+    StepVal = ConstantFP::get(C.getLLVMContext(), APFloat(1.0));
   }
 
   // Compute the end condition.
@@ -968,11 +968,11 @@
 
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = C.getBuilder().CreateFCmpONE(EndCond,
-                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
+                              ConstantFP::get(C.getLLVMContext(), APFloat(0.0)),
                                   "loopcond");
 
   // Create the "after loop" block and insert it.
-  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(C.getLLVMContext(), "afterloop", TheFunction);
 
   // Insert the conditional branch into the end of LoopEndBB.
   C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -987,7 +987,7 @@
     C.NamedValues.erase(VarName);
 
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
+  return Constant::getNullValue(Type::getDoubleTy(C.getLLVMContext()));
 }
 
 Value *VarExprAST::IRGen(IRGenContext &C) const {
@@ -1010,7 +1010,7 @@
       InitVal = Init->IRGen(C);
       if (!InitVal) return nullptr;
     } else // If not specified, use 0.0.
-      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
+      InitVal = ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
 
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
     C.getBuilder().CreateStore(InitVal, Alloca);
@@ -1040,8 +1040,8 @@
 
   // Make the function type:  double(double,double) etc.
   std::vector<Type*> Doubles(Args.size(),
-                             Type::getDoubleTy(getGlobalContext()));
-  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                             Type::getDoubleTy(C.getLLVMContext()));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(C.getLLVMContext()),
                                        Doubles, false);
   Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
                                  &C.getM());
@@ -1103,7 +1103,7 @@
     BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
 
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(C.getLLVMContext(), "entry", TheFunction);
   C.getBuilder().SetInsertPoint(BB);
 
   // Add all arguments to the symbol table and create their allocas.
@@ -1296,7 +1296,8 @@
 
 /// top ::= definition | external | expression | ';'
 static void MainLoop() {
-  SessionContext S(getGlobalContext());
+  LLVMContext TheContext;
+  SessionContext S(TheContext);
   KaleidoscopeJIT J(S);
 
   while (1) {
Index: include/llvm/IR/LLVMContext.h
===================================================================
--- include/llvm/IR/LLVMContext.h
+++ include/llvm/IR/LLVMContext.h
@@ -235,10 +235,6 @@
   friend class Module;
 };
 
-/// getGlobalContext - Returns a global context.  This is for LLVM clients that
-/// only care about operating on a single thread.
-extern LLVMContext &getGlobalContext();
-
 // Create wrappers for C Binding types (see CBindingWrapping.h).
 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)
 
Index: include/llvm/LinkAllIR.h
===================================================================
--- include/llvm/LinkAllIR.h
+++ include/llvm/LinkAllIR.h
@@ -43,8 +43,9 @@
       // to know that getenv() never returns -1, this will do the job.
       if (std::getenv("bar") != (char*) -1)
         return;
-      (void)new llvm::Module("", llvm::getGlobalContext());
-      (void)new llvm::UnreachableInst(llvm::getGlobalContext());
+      llvm::LLVMContext Context;
+      (void)new llvm::Module("", Context);
+      (void)new llvm::UnreachableInst(Context);
       (void)    llvm::createVerifierPass(); 
     }
   } ForceVMCoreLinking;
Index: lib/Bitcode/Reader/BitReader.cpp
===================================================================
--- lib/Bitcode/Reader/BitReader.cpp
+++ lib/Bitcode/Reader/BitReader.cpp
@@ -25,13 +25,13 @@
    Optionally returns a human-readable error message via OutMessage. */
 LLVMBool LLVMParseBitcode(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutModule,
                           char **OutMessage) {
-  return LLVMParseBitcodeInContext(wrap(&getGlobalContext()), MemBuf, OutModule,
+  return LLVMParseBitcodeInContext(LLVMGetGlobalContext(), MemBuf, OutModule,
                                    OutMessage);
 }
 
 LLVMBool LLVMParseBitcode2(LLVMMemoryBufferRef MemBuf,
                            LLVMModuleRef *OutModule) {
-  return LLVMParseBitcodeInContext2(wrap(&getGlobalContext()), MemBuf,
+  return LLVMParseBitcodeInContext2(LLVMGetGlobalContext(), MemBuf,
                                     OutModule);
 }
 
Index: lib/IR/Core.cpp
===================================================================
--- lib/IR/Core.cpp
+++ lib/IR/Core.cpp
@@ -73,12 +73,14 @@
 
 /*===-- Operations on contexts --------------------------------------------===*/
 
+static ManagedStatic<LLVMContext> GlobalContext;
+
 LLVMContextRef LLVMContextCreate() {
   return wrap(new LLVMContext());
 }
 
 LLVMContextRef LLVMGetGlobalContext() {
-  return wrap(&getGlobalContext());
+  return wrap(&*GlobalContext);
 }
 
 void LLVMContextSetDiagnosticHandler(LLVMContextRef C,
@@ -155,7 +157,7 @@
 /*===-- Operations on modules ---------------------------------------------===*/
 
 LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID) {
-  return wrap(new Module(ModuleID, getGlobalContext()));
+  return wrap(new Module(ModuleID, *GlobalContext));
 }
 
 LLVMModuleRef LLVMModuleCreateWithNameInContext(const char *ModuleID,
Index: lib/IR/LLVMContext.cpp
===================================================================
--- lib/IR/LLVMContext.cpp
+++ lib/IR/LLVMContext.cpp
@@ -25,12 +25,6 @@
 #include <cctype>
 using namespace llvm;
 
-static ManagedStatic<LLVMContext> GlobalContext;
-
-LLVMContext& llvm::getGlobalContext() {
-  return *GlobalContext;
-}
-
 LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) {
   // Create the fixed metadata kinds. This is done in the same order as the
   // MD_* enum values so that they correspond.
Index: lib/Target/CppBackend/CPPBackend.cpp
===================================================================
--- lib/Target/CppBackend/CPPBackend.cpp
+++ lib/Target/CppBackend/CPPBackend.cpp
@@ -1947,6 +1947,7 @@
   Out << "#include <llvm/Support/MathExtras.h>\n";
   Out << "#include <algorithm>\n";
   Out << "using namespace llvm;\n\n";
+  Out << "static LLVMContext TheContext;\n\n";
   Out << "Module* " << fname << "();\n\n";
   Out << "int main(int argc, char**argv) {\n";
   Out << "  Module* Mod = " << fname << "();\n";
@@ -1965,7 +1966,7 @@
   nl(Out,1) << "// Module Construction";
   nl(Out) << "Module* mod = new Module(\"";
   printEscapedString(mName);
-  Out << "\", getGlobalContext());";
+  Out << "\", TheContext);";
   if (!TheModule->getTargetTriple().empty()) {
     nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayoutStr()
             << "\");";
Index: lib/Target/Target.cpp
===================================================================
--- lib/Target/Target.cpp
+++ lib/Target/Target.cpp
@@ -13,6 +13,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm-c/Target.h"
+#include "llvm-c/Core.h"
 #include "llvm-c/Initialization.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/LLVMContext.h"
@@ -81,11 +82,11 @@
 }
 
 LLVMTypeRef LLVMIntPtrType(LLVMTargetDataRef TD) {
-  return wrap(unwrap(TD)->getIntPtrType(getGlobalContext()));
+  return wrap(unwrap(TD)->getIntPtrType(*unwrap(LLVMGetGlobalContext())));
 }
 
 LLVMTypeRef LLVMIntPtrTypeForAS(LLVMTargetDataRef TD, unsigned AS) {
-  return wrap(unwrap(TD)->getIntPtrType(getGlobalContext(), AS));
+  return wrap(unwrap(TD)->getIntPtrType(*unwrap(LLVMGetGlobalContext()), AS));
 }
 
 LLVMTypeRef LLVMIntPtrTypeInContext(LLVMContextRef C, LLVMTargetDataRef TD) {
Index: tools/bugpoint/bugpoint.cpp
===================================================================
--- tools/bugpoint/bugpoint.cpp
+++ tools/bugpoint/bugpoint.cpp
@@ -143,7 +143,7 @@
   sys::SetInterruptFunction(BugpointInterruptFunction);
 #endif
 
-  LLVMContext& Context = getGlobalContext();
+  LLVMContext Context;
   // If we have an override, set it and then track the triple we want Modules
   // to use.
   if (!OverrideTriple.empty()) {
Index: tools/llc/llc.cpp
===================================================================
--- tools/llc/llc.cpp
+++ tools/llc/llc.cpp
@@ -187,7 +187,7 @@
   // Enable debug stream buffering.
   EnableDebugBuffering = true;
 
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
 
   // Initialize targets first, so that --version shows registered targets.
Index: tools/lli/lli.cpp
===================================================================
--- tools/lli/lli.cpp
+++ tools/lli/lli.cpp
@@ -385,7 +385,7 @@
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
 
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
 
   // If we have a native target, initialize it to ensure it is linked in and
Index: tools/llvm-as-fuzzer/llvm-as-fuzzer.cpp
===================================================================
--- tools/llvm-as-fuzzer/llvm-as-fuzzer.cpp
+++ tools/llvm-as-fuzzer/llvm-as-fuzzer.cpp
@@ -53,7 +53,7 @@
   // parsed is always null terminated.
   std::unique_ptr<MemoryBuffer> MemBuf = MemoryBuffer::getMemBufferCopy(Input);
   SMDiagnostic Err;
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   std::unique_ptr<Module> M;
 
   if (setjmp(JmpBuf))
Index: tools/llvm-as/llvm-as.cpp
===================================================================
--- tools/llvm-as/llvm-as.cpp
+++ tools/llvm-as/llvm-as.cpp
@@ -91,7 +91,7 @@
   // Print a stack trace if we signal out.
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
   cl::ParseCommandLineOptions(argc, argv, "llvm .ll -> .bc assembler\n");
 
Index: tools/llvm-dis/llvm-dis.cpp
===================================================================
--- tools/llvm-dis/llvm-dis.cpp
+++ tools/llvm-dis/llvm-dis.cpp
@@ -137,7 +137,7 @@
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
 
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
 
   Context.setDiagnosticHandler(diagnosticHandler, argv[0]);
Index: tools/llvm-extract/llvm-extract.cpp
===================================================================
--- tools/llvm-extract/llvm-extract.cpp
+++ tools/llvm-extract/llvm-extract.cpp
@@ -105,7 +105,7 @@
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
 
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
 
Index: tools/llvm-jitlistener/llvm-jitlistener.cpp
===================================================================
--- tools/llvm-jitlistener/llvm-jitlistener.cpp
+++ tools/llvm-jitlistener/llvm-jitlistener.cpp
@@ -105,8 +105,6 @@
 class JitEventListenerTest {
 protected:
   void InitEE(const std::string &IRFile) {
-    LLVMContext &Context = getGlobalContext();
-
     // If we have a native target, initialize it to ensure it is linked in and
     // usable by the JIT.
     InitializeNativeTarget();
Index: tools/llvm-link/llvm-link.cpp
===================================================================
--- tools/llvm-link/llvm-link.cpp
+++ tools/llvm-link/llvm-link.cpp
@@ -331,7 +331,7 @@
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
 
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
 
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
Index: tools/llvm-nm/llvm-nm.cpp
===================================================================
--- tools/llvm-nm/llvm-nm.cpp
+++ tools/llvm-nm/llvm-nm.cpp
@@ -1020,7 +1020,7 @@
   if (error(BufferOrErr.getError(), Filename))
     return;
 
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   Expected<std::unique_ptr<Binary>> BinaryOrErr = createBinary(
       BufferOrErr.get()->getMemBufferRef(), NoLLVMBitcode ? nullptr : &Context);
   if (!BinaryOrErr) {
Index: tools/llvm-profdata/llvm-profdata.cpp
===================================================================
--- tools/llvm-profdata/llvm-profdata.cpp
+++ tools/llvm-profdata/llvm-profdata.cpp
@@ -164,9 +164,10 @@
   auto Writer = std::move(WriterOrErr.get());
   StringMap<FunctionSamples> ProfileMap;
   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
+  LLVMContext Context;
   for (const auto &Input : Inputs) {
     auto ReaderOrErr =
-        SampleProfileReader::create(Input.Filename, getGlobalContext());
+        SampleProfileReader::create(Input.Filename, Context);
     if (std::error_code EC = ReaderOrErr.getError())
       exitWithErrorCode(EC, Input.Filename);
 
@@ -365,7 +366,8 @@
                              bool ShowAllFunctions, std::string ShowFunction,
                              raw_fd_ostream &OS) {
   using namespace sampleprof;
-  auto ReaderOrErr = SampleProfileReader::create(Filename, getGlobalContext());
+  LLVMContext Context;
+  auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
   if (std::error_code EC = ReaderOrErr.getError())
     exitWithErrorCode(EC, Filename);
 
Index: tools/llvm-split/llvm-split.cpp
===================================================================
--- tools/llvm-split/llvm-split.cpp
+++ tools/llvm-split/llvm-split.cpp
@@ -41,7 +41,7 @@
                    cl::desc("Split without externalizing locals"));
 
 int main(int argc, char **argv) {
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   SMDiagnostic Err;
   cl::ParseCommandLineOptions(argc, argv, "LLVM module splitter\n");
 
Index: tools/llvm-stress/llvm-stress.cpp
===================================================================
--- tools/llvm-stress/llvm-stress.cpp
+++ tools/llvm-stress/llvm-stress.cpp
@@ -43,6 +43,8 @@
 OutputFilename("o", cl::desc("Override output filename"),
                cl::value_desc("filename"));
 
+static LLVMContext Context;
+
 namespace cl {
 template <> class parser<Type*> final : public basic_parser<Type*> {
 public:
@@ -50,7 +52,6 @@
 
   // Parse options as IR types. Return true on error.
   bool parse(Option &O, StringRef, StringRef Arg, Type *&Value) {
-    auto &Context = getGlobalContext();
     if      (Arg == "half")      Value = Type::getHalfTy(Context);
     else if (Arg == "fp128")     Value = Type::getFP128Ty(Context);
     else if (Arg == "x86_fp80")  Value = Type::getX86_FP80Ty(Context);
@@ -687,7 +688,7 @@
   cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
   llvm_shutdown_obj Y;
 
-  auto M = make_unique<Module>("/tmp/autogen.bc", getGlobalContext());
+  auto M = make_unique<Module>("/tmp/autogen.bc", Context);
   Function *F = GenEmptyFunction(M.get());
 
   // Pick an initial seed value
Index: tools/lto/lto.cpp
===================================================================
--- tools/lto/lto.cpp
+++ tools/lto/lto.cpp
@@ -101,7 +101,8 @@
     InitializeAllAsmPrinters();
     InitializeAllDisassemblers();
 
-    LTOContext = &getGlobalContext();
+    static LLVMContext Context;
+    LTOContext = &Context;
     LTOContext->setDiagnosticHandler(diagnosticHandler, nullptr, true);
     initialized = true;
   }
Index: tools/opt/opt.cpp
===================================================================
--- tools/opt/opt.cpp
+++ tools/opt/opt.cpp
@@ -316,7 +316,7 @@
   EnableDebugBuffering = true;
 
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
 
   InitializeAllTargets();
   InitializeAllTargetMCs();
Index: tools/verify-uselistorder/verify-uselistorder.cpp
===================================================================
--- tools/verify-uselistorder/verify-uselistorder.cpp
+++ tools/verify-uselistorder/verify-uselistorder.cpp
@@ -525,7 +525,7 @@
   EnableDebugBuffering = true;
 
   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
 
   cl::ParseCommandLineOptions(argc, argv,
                               "llvm tool to verify use-list order\n");
Index: unittests/Analysis/AliasAnalysisTest.cpp
===================================================================
--- unittests/Analysis/AliasAnalysisTest.cpp
+++ unittests/Analysis/AliasAnalysisTest.cpp
@@ -207,14 +207,13 @@
 
 class AAPassInfraTest : public testing::Test {
 protected:
-  LLVMContext &C;
+  LLVMContext C;
   SMDiagnostic Err;
   std::unique_ptr<Module> M;
 
 public:
   AAPassInfraTest()
-      : C(getGlobalContext()),
-        M(parseAssemblyString("define i32 @f(i32* %x, i32* %y) {\n"
+      : M(parseAssemblyString("define i32 @f(i32* %x, i32* %y) {\n"
                               "entry:\n"
                               "  %lx = load i32, i32* %x\n"
                               "  %ly = load i32, i32* %y\n"
Index: unittests/Analysis/BlockFrequencyInfoTest.cpp
===================================================================
--- unittests/Analysis/BlockFrequencyInfoTest.cpp
+++ unittests/Analysis/BlockFrequencyInfoTest.cpp
@@ -30,6 +30,7 @@
   std::unique_ptr<BranchProbabilityInfo> BPI;
   std::unique_ptr<DominatorTree> DT;
   std::unique_ptr<LoopInfo> LI;
+  LLVMContext C;
 
   BlockFrequencyInfo buildBFI(Function &F) {
     DT.reset(new DominatorTree(F));
@@ -50,7 +51,6 @@
                               "  %y2 = phi i32 [0, %bb1], [1, %bb2] \n"
                               "  ret i32 %y2\n"
                               "}\n";
-    LLVMContext &C = getGlobalContext();
     SMDiagnostic Err;
     return parseAssemblyString(ModuleStrig, Err, C);
   }
Index: unittests/Analysis/CFGTest.cpp
===================================================================
--- unittests/Analysis/CFGTest.cpp
+++ unittests/Analysis/CFGTest.cpp
@@ -31,7 +31,7 @@
 protected:
   void ParseAssembly(const char *Assembly) {
     SMDiagnostic Error;
-    M = parseAssemblyString(Assembly, Error, getGlobalContext());
+    M = parseAssemblyString(Assembly, Error, Context);
 
     std::string errMsg;
     raw_string_ostream os(errMsg);
@@ -112,6 +112,7 @@
     PM.run(*M);
   }
 
+  LLVMContext Context;
   std::unique_ptr<Module> M;
   Instruction *A, *B;
 };
Index: unittests/Analysis/CGSCCPassManagerTest.cpp
===================================================================
--- unittests/Analysis/CGSCCPassManagerTest.cpp
+++ unittests/Analysis/CGSCCPassManagerTest.cpp
@@ -209,19 +209,20 @@
   int &RunCount;
 };
 
-std::unique_ptr<Module> parseIR(const char *IR) {
-  LLVMContext &C = getGlobalContext();
+std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
   SMDiagnostic Err;
   return parseAssemblyString(IR, Err, C);
 }
 
 class CGSCCPassManagerTest : public ::testing::Test {
 protected:
+  LLVMContext Context;
   std::unique_ptr<Module> M;
 
 public:
   CGSCCPassManagerTest()
-      : M(parseIR("define void @f() {\n"
+      : M(parseIR(Context,
+                  "define void @f() {\n"
                   "entry:\n"
                   "  call void @g()\n"
                   "  call void @h1()\n"
Index: unittests/Analysis/CallGraphTest.cpp
===================================================================
--- unittests/Analysis/CallGraphTest.cpp
+++ unittests/Analysis/CallGraphTest.cpp
@@ -44,14 +44,16 @@
 }
 
 TEST(CallGraphTest, GraphTraitsSpecialization) {
-  Module M("", getGlobalContext());
+  LLVMContext Context;
+  Module M("", Context);
   CallGraph CG(M);
 
   canSpecializeGraphTraitsIterators(&CG);
 }
 
 TEST(CallGraphTest, GraphTraitsConstSpecialization) {
-  Module M("", getGlobalContext());
+  LLVMContext Context;
+  Module M("", Context);
   CallGraph CG(M);
 
   canSpecializeGraphTraitsIterators(const_cast<const CallGraph *>(&CG));
Index: unittests/Analysis/LazyCallGraphTest.cpp
===================================================================
--- unittests/Analysis/LazyCallGraphTest.cpp
+++ unittests/Analysis/LazyCallGraphTest.cpp
@@ -21,10 +21,10 @@
 
 namespace {
 
-std::unique_ptr<Module> parseAssembly(const char *Assembly) {
+std::unique_ptr<Module> parseAssembly(LLVMContext &Context, const char *Assembly) {
   SMDiagnostic Error;
   std::unique_ptr<Module> M =
-      parseAssemblyString(Assembly, Error, getGlobalContext());
+      parseAssemblyString(Assembly, Error, Context);
 
   std::string ErrMsg;
   raw_string_ostream OS(ErrMsg);
@@ -121,7 +121,8 @@
      "}\n";
 
 TEST(LazyCallGraphTest, BasicGraphFormation) {
-  std::unique_ptr<Module> M = parseAssembly(DiamondOfTriangles);
+  LLVMContext Context;
+  std::unique_ptr<Module> M = parseAssembly(Context, DiamondOfTriangles);
   LazyCallGraph CG(*M);
 
   // The order of the entry nodes should be stable w.r.t. the source order of
@@ -280,7 +281,8 @@
 }
 
 TEST(LazyCallGraphTest, BasicGraphMutation) {
-  std::unique_ptr<Module> M = parseAssembly(
+  LLVMContext Context;
+  std::unique_ptr<Module> M = parseAssembly(Context,
       "define void @a() {\n"
       "entry:\n"
       "  call void @b()\n"
@@ -328,7 +330,8 @@
 }
 
 TEST(LazyCallGraphTest, InnerSCCFormation) {
-  std::unique_ptr<Module> M = parseAssembly(DiamondOfTriangles);
+  LLVMContext Context;
+  std::unique_ptr<Module> M = parseAssembly(Context, DiamondOfTriangles);
   LazyCallGraph CG(*M);
 
   // Now mutate the graph to connect every node into a single RefSCC to ensure
@@ -391,11 +394,12 @@
 }
 
 TEST(LazyCallGraphTest, MultiArmSCC) {
+  LLVMContext Context;
   // Two interlocking cycles. The really useful thing about this SCC is that it
   // will require Tarjan's DFS to backtrack and finish processing all of the
   // children of each node in the SCC. Since this involves call edges, both
   // Tarjan implementations will have to successfully navigate the structure.
-  std::unique_ptr<Module> M = parseAssembly(
+  std::unique_ptr<Module> M = parseAssembly(Context,
       "define void @f1() {\n"
       "entry:\n"
       "  call void @f2()\n"
@@ -451,7 +455,8 @@
 }
 
 TEST(LazyCallGraphTest, OutgoingEdgeMutation) {
-  std::unique_ptr<Module> M = parseAssembly(
+  LLVMContext Context;
+  std::unique_ptr<Module> M = parseAssembly(Context,
       "define void @a() {\n"
       "entry:\n"
       "  call void @b()\n"
@@ -575,6 +580,7 @@
 }
 
 TEST(LazyCallGraphTest, IncomingEdgeInsertion) {
+  LLVMContext Context;
   // We want to ensure we can add edges even across complex diamond graphs, so
   // we use the diamond of triangles graph defined above. The ascii diagram is
   // repeated here for easy reference.
@@ -591,7 +597,7 @@
   //       /  \       |
   //      a3--a2      |
   //
-  std::unique_ptr<Module> M = parseAssembly(DiamondOfTriangles);
+  std::unique_ptr<Module> M = parseAssembly(Context, DiamondOfTriangles);
   LazyCallGraph CG(*M);
 
   // Force the graph to be fully expanded.
@@ -668,9 +674,10 @@
 }
 
 TEST(LazyCallGraphTest, IncomingEdgeInsertionMidTraversal) {
+  LLVMContext Context;
   // This is the same fundamental test as the previous, but we perform it
   // having only partially walked the RefSCCs of the graph.
-  std::unique_ptr<Module> M = parseAssembly(DiamondOfTriangles);
+  std::unique_ptr<Module> M = parseAssembly(Context, DiamondOfTriangles);
   LazyCallGraph CG(*M);
 
   // Walk the RefSCCs until we find the one containing 'c1'.
@@ -744,7 +751,8 @@
 }
 
 TEST(LazyCallGraphTest, InternalEdgeMutation) {
-  std::unique_ptr<Module> M = parseAssembly(
+  LLVMContext Context;
+  std::unique_ptr<Module> M = parseAssembly(Context,
       "define void @a() {\n"
       "entry:\n"
       "  call void @b()\n"
@@ -824,8 +832,9 @@
 }
 
 TEST(LazyCallGraphTest, InternalEdgeRemoval) {
+  LLVMContext Context;
   // A nice fully connected (including self-edges) RefSCC.
-  std::unique_ptr<Module> M = parseAssembly(
+  std::unique_ptr<Module> M = parseAssembly(Context,
       "define void @a(i8** %ptr) {\n"
       "entry:\n"
       "  store i8* bitcast (void(i8**)* @a to i8*), i8** %ptr\n"
@@ -882,8 +891,9 @@
 }
 
 TEST(LazyCallGraphTest, InternalCallEdgeToRef) {
+  LLVMContext Context;
   // A nice fully connected (including self-edges) SCC (and RefSCC)
-  std::unique_ptr<Module> M = parseAssembly(
+  std::unique_ptr<Module> M = parseAssembly(Context,
       "define void @a() {\n"
       "entry:\n"
       "  call void @a()\n"
@@ -964,9 +974,10 @@
 }
 
 TEST(LazyCallGraphTest, InternalRefEdgeToCall) {
+  LLVMContext Context;
   // Basic tests for making a ref edge a call. This hits the basics of the
   // process only.
-  std::unique_ptr<Module> M = parseAssembly(
+  std::unique_ptr<Module> M = parseAssembly(Context,
       "define void @a() {\n"
       "entry:\n"
       "  call void @b()\n"
@@ -1049,12 +1060,13 @@
 }
 
 TEST(LazyCallGraphTest, InternalRefEdgeToCallNoCycleInterleaved) {
+  LLVMContext Context;
   // Test for having a post-order prior to changing a ref edge to a call edge
   // with SCCs connecting to the source and connecting to the target, but not
   // connecting to both, interleaved between the source and target. This
   // ensures we correctly partition the range rather than simply moving one or
   // the other.
-  std::unique_ptr<Module> M = parseAssembly(
+  std::unique_ptr<Module> M = parseAssembly(Context,
       "define void @a() {\n"
       "entry:\n"
       "  call void @b1()\n"
@@ -1163,6 +1175,7 @@
 }
 
 TEST(LazyCallGraphTest, InternalRefEdgeToCallBothPartitionAndMerge) {
+  LLVMContext Context;
   // Test for having a postorder where between the source and target are all
   // three kinds of other SCCs:
   // 1) One connected to the target only that have to be shifted below the
@@ -1190,7 +1203,7 @@
   //   G    |    G    |
   //
   // And we form a cycle by connecting F to B.
-  std::unique_ptr<Module> M = parseAssembly(
+  std::unique_ptr<Module> M = parseAssembly(Context,
       "define void @a() {\n"
       "entry:\n"
       "  call void @b()\n"
Index: unittests/Analysis/LoopPassManagerTest.cpp
===================================================================
--- unittests/Analysis/LoopPassManagerTest.cpp
+++ unittests/Analysis/LoopPassManagerTest.cpp
@@ -99,19 +99,20 @@
   static StringRef name() { return "TestLoopInvalidatingPass"; }
 };
 
-std::unique_ptr<Module> parseIR(const char *IR) {
-  LLVMContext &C = getGlobalContext();
+std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
   SMDiagnostic Err;
   return parseAssemblyString(IR, Err, C);
 }
 
 class LoopPassManagerTest : public ::testing::Test {
 protected:
+  LLVMContext Context;
   std::unique_ptr<Module> M;
 
 public:
   LoopPassManagerTest()
-      : M(parseIR("define void @f() {\n"
+      : M(parseIR(Context,
+                  "define void @f() {\n"
                   "entry:\n"
                   "  br label %loop.0\n"
                   "loop.0:\n"
Index: unittests/Analysis/UnrollAnalyzer.cpp
===================================================================
--- unittests/Analysis/UnrollAnalyzer.cpp
+++ unittests/Analysis/UnrollAnalyzer.cpp
@@ -60,11 +60,11 @@
 
 char UnrollAnalyzerTest::ID = 0;
 
-std::unique_ptr<Module> makeLLVMModule(UnrollAnalyzerTest *P,
+std::unique_ptr<Module> makeLLVMModule(LLVMContext &Context,
+                                       UnrollAnalyzerTest *P,
                                        const char *ModuleStr) {
-  LLVMContext &C = getGlobalContext();
   SMDiagnostic Err;
-  return parseAssemblyString(ModuleStr, Err, C);
+  return parseAssemblyString(ModuleStr, Err, Context);
 }
 
 TEST(UnrollAnalyzerTest, BasicSimplifications) {
@@ -86,7 +86,8 @@
       "  ret i64 %x.lcssa\n"
       "}\n";
   UnrollAnalyzerTest *P = new UnrollAnalyzerTest();
-  std::unique_ptr<Module> M = makeLLVMModule(P, ModuleStr);
+  LLVMContext Context;
+  std::unique_ptr<Module> M = makeLLVMModule(Context, P, ModuleStr);
   legacy::PassManager Passes;
   Passes.add(P);
   Passes.run(*M);
@@ -148,7 +149,8 @@
       "}\n";
 
   UnrollAnalyzerTest *P = new UnrollAnalyzerTest();
-  std::unique_ptr<Module> M = makeLLVMModule(P, ModuleStr);
+  LLVMContext Context;
+  std::unique_ptr<Module> M = makeLLVMModule(Context, P, ModuleStr);
   legacy::PassManager Passes;
   Passes.add(P);
   Passes.run(*M);
@@ -188,7 +190,8 @@
       "  ret void\n"
       "}\n";
   UnrollAnalyzerTest *P = new UnrollAnalyzerTest();
-  std::unique_ptr<Module> M = makeLLVMModule(P, ModuleStr);
+  LLVMContext Context;
+  std::unique_ptr<Module> M = makeLLVMModule(Context, P, ModuleStr);
   legacy::PassManager Passes;
   Passes.add(P);
   Passes.run(*M);
@@ -234,7 +237,8 @@
       "  ret void\n"
       "}\n";
   UnrollAnalyzerTest *P = new UnrollAnalyzerTest();
-  std::unique_ptr<Module> M = makeLLVMModule(P, ModuleStr);
+  LLVMContext Context;
+  std::unique_ptr<Module> M = makeLLVMModule(Context, P, ModuleStr);
   legacy::PassManager Passes;
   Passes.add(P);
   Passes.run(*M);
@@ -279,7 +283,8 @@
       "}\n";
 
   UnrollAnalyzerTest *P = new UnrollAnalyzerTest();
-  std::unique_ptr<Module> M = makeLLVMModule(P, ModuleStr);
+  LLVMContext Context;
+  std::unique_ptr<Module> M = makeLLVMModule(Context, P, ModuleStr);
   legacy::PassManager Passes;
   Passes.add(P);
   Passes.run(*M);
Index: unittests/Analysis/ValueTrackingTest.cpp
===================================================================
--- unittests/Analysis/ValueTrackingTest.cpp
+++ unittests/Analysis/ValueTrackingTest.cpp
@@ -25,7 +25,7 @@
 protected:
   void parseAssembly(const char *Assembly) {
     SMDiagnostic Error;
-    M = parseAssemblyString(Assembly, Error, getGlobalContext());
+    M = parseAssemblyString(Assembly, Error, Context);
 
     std::string errMsg;
     raw_string_ostream os(errMsg);
@@ -59,6 +59,7 @@
     EXPECT_EQ(P.Ordered, R.Ordered);
   }
 
+  LLVMContext Context;
   std::unique_ptr<Module> M;
   Instruction *A, *B;
 };
Index: unittests/AsmParser/AsmParserTest.cpp
===================================================================
--- unittests/AsmParser/AsmParserTest.cpp
+++ unittests/AsmParser/AsmParserTest.cpp
@@ -21,7 +21,7 @@
 namespace {
 
 TEST(AsmParserTest, NullTerminatedInput) {
-  LLVMContext &Ctx = getGlobalContext();
+  LLVMContext Ctx;
   StringRef Source = "; Empty module \n";
   SMDiagnostic Error;
   auto Mod = parseAssemblyString(Source, Error, Ctx);
@@ -34,7 +34,7 @@
 #ifndef NDEBUG
 
 TEST(AsmParserTest, NonNullTerminatedInput) {
-  LLVMContext &Ctx = getGlobalContext();
+  LLVMContext Ctx;
   StringRef Source = "; Empty module \n\1\2";
   SMDiagnostic Error;
   std::unique_ptr<Module> Mod;
@@ -47,7 +47,7 @@
 #endif
 
 TEST(AsmParserTest, SlotMappingTest) {
-  LLVMContext &Ctx = getGlobalContext();
+  LLVMContext Ctx;
   StringRef Source = "@0 = global i32 0\n !0 = !{}\n !42 = !{i32 42}";
   SMDiagnostic Error;
   SlotMapping Mapping;
@@ -66,7 +66,7 @@
 }
 
 TEST(AsmParserTest, TypeAndConstantValueParsing) {
-  LLVMContext &Ctx = getGlobalContext();
+  LLVMContext Ctx;
   SMDiagnostic Error;
   StringRef Source = "define void @test() {\n  entry:\n  ret void\n}";
   auto Mod = parseAssemblyString(Source, Error, Ctx);
@@ -117,7 +117,7 @@
 }
 
 TEST(AsmParserTest, TypeAndConstantValueWithSlotMappingParsing) {
-  LLVMContext &Ctx = getGlobalContext();
+  LLVMContext Ctx;
   SMDiagnostic Error;
   StringRef Source =
       "%st = type { i32, i32 }\n"
@@ -153,7 +153,7 @@
 }
 
 TEST(AsmParserTest, TypeWithSlotMappingParsing) {
-  LLVMContext &Ctx = getGlobalContext();
+  LLVMContext Ctx;
   SMDiagnostic Error;
   StringRef Source =
       "%st = type { i32, i32 }\n"
@@ -277,7 +277,7 @@
 }
 
 TEST(AsmParserTest, TypeAtBeginningWithSlotMappingParsing) {
-  LLVMContext &Ctx = getGlobalContext();
+  LLVMContext Ctx;
   SMDiagnostic Error;
   StringRef Source =
       "%st = type { i32, i32 }\n"
Index: unittests/Bitcode/BitReaderTest.cpp
===================================================================
--- unittests/Bitcode/BitReaderTest.cpp
+++ unittests/Bitcode/BitReaderTest.cpp
@@ -29,10 +29,10 @@
 
 namespace {
 
-std::unique_ptr<Module> parseAssembly(const char *Assembly) {
+std::unique_ptr<Module> parseAssembly(LLVMContext &Context, const char *Assembly) {
   SMDiagnostic Error;
   std::unique_ptr<Module> M =
-      parseAssemblyString(Assembly, Error, getGlobalContext());
+      parseAssemblyString(Assembly, Error, Context);
 
   std::string ErrMsg;
   raw_string_ostream OS(ErrMsg);
@@ -54,7 +54,7 @@
 static std::unique_ptr<Module> getLazyModuleFromAssembly(LLVMContext &Context,
                                                          SmallString<1024> &Mem,
                                                          const char *Assembly) {
-  writeModuleToBuffer(parseAssembly(Assembly), Mem);
+  writeModuleToBuffer(parseAssembly(Context, Assembly), Mem);
   std::unique_ptr<MemoryBuffer> Buffer =
       MemoryBuffer::getMemBuffer(Mem.str(), "test", false);
   ErrorOr<std::unique_ptr<Module>> ModuleOrErr =
@@ -82,7 +82,7 @@
 static std::unique_ptr<Module>
 getStreamedModuleFromAssembly(LLVMContext &Context, SmallString<1024> &Mem,
                               const char *Assembly) {
-  writeModuleToBuffer(parseAssembly(Assembly), Mem);
+  writeModuleToBuffer(parseAssembly(Context, Assembly), Mem);
   std::unique_ptr<MemoryBuffer> Buffer =
       MemoryBuffer::getMemBuffer(Mem.str(), "test", false);
   auto Streamer = llvm::make_unique<BufferDataStreamer>(std::move(Buffer));
Index: unittests/ExecutionEngine/ExecutionEngineTest.cpp
===================================================================
--- unittests/ExecutionEngine/ExecutionEngineTest.cpp
+++ unittests/ExecutionEngine/ExecutionEngineTest.cpp
@@ -28,7 +28,7 @@
 
 protected:
   ExecutionEngineTest() {
-    auto Owner = make_unique<Module>("<main>", getGlobalContext());
+    auto Owner = make_unique<Module>("<main>", Context);
     M = Owner.get();
     Engine.reset(EngineBuilder(std::move(Owner)).setErrorStr(&Error).create());
   }
@@ -44,13 +44,14 @@
   }
 
   std::string Error;
+  LLVMContext Context;
   Module *M;  // Owned by ExecutionEngine.
   std::unique_ptr<ExecutionEngine> Engine;
 };
 
 TEST_F(ExecutionEngineTest, ForwardGlobalMapping) {
   GlobalVariable *G1 =
-      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
+      NewExtGlobal(Type::getInt32Ty(Context), "Global1");
   int32_t Mem1 = 3;
   Engine->addGlobalMapping(G1, &Mem1);
   EXPECT_EQ(&Mem1, Engine->getPointerToGlobalIfAvailable(G1));
@@ -64,7 +65,7 @@
   EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1));
 
   GlobalVariable *G2 =
-      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
+      NewExtGlobal(Type::getInt32Ty(Context), "Global1");
   EXPECT_EQ(nullptr, Engine->getPointerToGlobalIfAvailable(G2))
     << "The NULL return shouldn't depend on having called"
     << " updateGlobalMapping(..., NULL)";
@@ -77,7 +78,7 @@
 
 TEST_F(ExecutionEngineTest, ReverseGlobalMapping) {
   GlobalVariable *G1 =
-      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
+      NewExtGlobal(Type::getInt32Ty(Context), "Global1");
 
   int32_t Mem1 = 3;
   Engine->addGlobalMapping(G1, &Mem1);
@@ -88,7 +89,7 @@
   EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));
 
   GlobalVariable *G2 =
-      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
+      NewExtGlobal(Type::getInt32Ty(Context), "Global2");
   Engine->updateGlobalMapping(G2, &Mem1);
   EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1));
   EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));
@@ -105,7 +106,7 @@
 
 TEST_F(ExecutionEngineTest, ClearModuleMappings) {
   GlobalVariable *G1 =
-      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
+      NewExtGlobal(Type::getInt32Ty(Context), "Global1");
 
   int32_t Mem1 = 3;
   Engine->addGlobalMapping(G1, &Mem1);
@@ -116,7 +117,7 @@
   EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem1));
 
   GlobalVariable *G2 =
-      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
+      NewExtGlobal(Type::getInt32Ty(Context), "Global2");
   // After clearing the module mappings, we can assign a new GV to the
   // same address.
   Engine->addGlobalMapping(G2, &Mem1);
@@ -125,7 +126,7 @@
 
 TEST_F(ExecutionEngineTest, DestructionRemovesGlobalMapping) {
   GlobalVariable *G1 =
-    NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
+    NewExtGlobal(Type::getInt32Ty(Context), "Global1");
   int32_t Mem1 = 3;
   Engine->addGlobalMapping(G1, &Mem1);
   // Make sure the reverse mapping is enabled.
Index: unittests/ExecutionEngine/Orc/IndirectionUtilsTest.cpp
===================================================================
--- unittests/ExecutionEngine/Orc/IndirectionUtilsTest.cpp
+++ unittests/ExecutionEngine/Orc/IndirectionUtilsTest.cpp
@@ -17,7 +17,8 @@
 namespace {
 
 TEST(IndirectionUtilsTest, MakeStub) {
-  ModuleBuilder MB(getGlobalContext(), "x86_64-apple-macosx10.10", "");
+  LLVMContext Context;
+  ModuleBuilder MB(Context, "x86_64-apple-macosx10.10", "");
   Function *F = MB.createFunctionDecl<void(DummyStruct, DummyStruct)>("");
   SmallVector<AttributeSet, 4> Attrs;
   Attrs.push_back(
Index: unittests/ExecutionEngine/Orc/ObjectLinkingLayerTest.cpp
===================================================================
--- unittests/ExecutionEngine/Orc/ObjectLinkingLayerTest.cpp
+++ unittests/ExecutionEngine/Orc/ObjectLinkingLayerTest.cpp
@@ -25,6 +25,7 @@
 
 class ObjectLinkingLayerExecutionTest : public testing::Test,
                                         public OrcExecutionTest {
+
 };
 
 class SectionMemoryManagerWrapper : public SectionMemoryManager {
@@ -64,9 +65,10 @@
 
   ObjectLinkingLayer<> ObjLayer;
 
-  auto M = llvm::make_unique<Module>("", getGlobalContext());
+  LLVMContext Context;
+  auto M = llvm::make_unique<Module>("", Context);
   M->setTargetTriple("x86_64-unknown-linux-gnu");
-  Type *Int32Ty = IntegerType::get(getGlobalContext(), 32);
+  Type *Int32Ty = IntegerType::get(Context, 32);
   GlobalVariable *GV =
     new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
                          ConstantInt::get(Int32Ty, 42), "foo");
@@ -131,14 +133,14 @@
   // instance (for Module 1) which is unsafe, as it will prevent relocation of
   // Module 2.
 
-  ModuleBuilder MB1(getGlobalContext(), "", "dummy");
+  ModuleBuilder MB1(Context, "", "dummy");
   {
     MB1.getModule()->setDataLayout(TM->createDataLayout());
     Function *BarImpl = MB1.createFunctionDecl<int32_t(void)>("bar");
-    BasicBlock *BarEntry = BasicBlock::Create(getGlobalContext(), "entry",
+    BasicBlock *BarEntry = BasicBlock::Create(Context, "entry",
                                               BarImpl);
     IRBuilder<> Builder(BarEntry);
-    IntegerType *Int32Ty = IntegerType::get(getGlobalContext(), 32);
+    IntegerType *Int32Ty = IntegerType::get(Context, 32);
     Value *FourtyTwo = ConstantInt::getSigned(Int32Ty, 42);
     Builder.CreateRet(FourtyTwo);
   }
@@ -147,12 +149,12 @@
   std::vector<object::ObjectFile*> Obj1Set;
   Obj1Set.push_back(Obj1.getBinary());
 
-  ModuleBuilder MB2(getGlobalContext(), "", "dummy");
+  ModuleBuilder MB2(Context, "", "dummy");
   {
     MB2.getModule()->setDataLayout(TM->createDataLayout());
     Function *BarDecl = MB2.createFunctionDecl<int32_t(void)>("bar");
     Function *FooImpl = MB2.createFunctionDecl<int32_t(void)>("foo");
-    BasicBlock *FooEntry = BasicBlock::Create(getGlobalContext(), "entry",
+    BasicBlock *FooEntry = BasicBlock::Create(Context, "entry",
                                               FooImpl);
     IRBuilder<> Builder(FooEntry);
     Builder.CreateRet(Builder.CreateCall(BarDecl));
@@ -203,14 +205,14 @@
   // RuntimeDyld::MemoryManager::needsToReserveAllocationSpace hook, which is
   // called once per object before any sections are allocated.
 
-  ModuleBuilder MB1(getGlobalContext(), "", "dummy");
+  ModuleBuilder MB1(Context, "", "dummy");
   {
     MB1.getModule()->setDataLayout(TM->createDataLayout());
     Function *BarImpl = MB1.createFunctionDecl<int32_t(void)>("foo");
-    BasicBlock *BarEntry = BasicBlock::Create(getGlobalContext(), "entry",
+    BasicBlock *BarEntry = BasicBlock::Create(Context, "entry",
                                               BarImpl);
     IRBuilder<> Builder(BarEntry);
-    IntegerType *Int32Ty = IntegerType::get(getGlobalContext(), 32);
+    IntegerType *Int32Ty = IntegerType::get(Context, 32);
     Value *FourtyTwo = ConstantInt::getSigned(Int32Ty, 42);
     Builder.CreateRet(FourtyTwo);
   }
@@ -219,14 +221,14 @@
   std::vector<object::ObjectFile*> Obj1Set;
   Obj1Set.push_back(Obj1.getBinary());
 
-  ModuleBuilder MB2(getGlobalContext(), "", "dummy");
+  ModuleBuilder MB2(Context, "", "dummy");
   {
     MB2.getModule()->setDataLayout(TM->createDataLayout());
     Function *BarImpl = MB2.createFunctionDecl<int32_t(void)>("bar");
-    BasicBlock *BarEntry = BasicBlock::Create(getGlobalContext(), "entry",
+    BasicBlock *BarEntry = BasicBlock::Create(Context, "entry",
                                               BarImpl);
     IRBuilder<> Builder(BarEntry);
-    IntegerType *Int32Ty = IntegerType::get(getGlobalContext(), 32);
+    IntegerType *Int32Ty = IntegerType::get(Context, 32);
     Value *Seven = ConstantInt::getSigned(Int32Ty, 7);
     Builder.CreateRet(Seven);
   }
Index: unittests/ExecutionEngine/Orc/OrcCAPITest.cpp
===================================================================
--- unittests/ExecutionEngine/Orc/OrcCAPITest.cpp
+++ unittests/ExecutionEngine/Orc/OrcCAPITest.cpp
@@ -25,11 +25,11 @@
 class OrcCAPIExecutionTest : public testing::Test, public OrcExecutionTest {
 protected:
   std::unique_ptr<Module> createTestModule(const Triple &TT) {
-    ModuleBuilder MB(getGlobalContext(), TT.str(), "");
+    ModuleBuilder MB(Context, TT.str(), "");
     Function *TestFunc = MB.createFunctionDecl<int()>("testFunc");
     Function *Main = MB.createFunctionDecl<int(int, char*[])>("main");
 
-    Main->getBasicBlockList().push_back(BasicBlock::Create(getGlobalContext()));
+    Main->getBasicBlockList().push_back(BasicBlock::Create(Context));
     IRBuilder<> B(&Main->back());
     Value* Result = B.CreateCall(TestFunc);
     B.CreateRet(Result);
Index: unittests/ExecutionEngine/Orc/OrcTestCommon.h
===================================================================
--- unittests/ExecutionEngine/Orc/OrcTestCommon.h
+++ unittests/ExecutionEngine/Orc/OrcTestCommon.h
@@ -54,6 +54,7 @@
   };
 
 protected:
+  LLVMContext Context;
   std::unique_ptr<TargetMachine> TM;
 private:
   static bool NativeTargetInitialized;
Index: unittests/IR/ConstantsTest.cpp
===================================================================
--- unittests/IR/ConstantsTest.cpp
+++ unittests/IR/ConstantsTest.cpp
@@ -22,7 +22,8 @@
 namespace {
 
 TEST(ConstantsTest, Integer_i1) {
-  IntegerType* Int1 = IntegerType::get(getGlobalContext(), 1);
+  LLVMContext Context;
+  IntegerType* Int1 = IntegerType::get(Context, 1);
   Constant* One = ConstantInt::get(Int1, 1, true);
   Constant* Zero = ConstantInt::get(Int1, 0);
   Constant* NegOne = ConstantInt::get(Int1, static_cast<uint64_t>(-1), true);
@@ -103,7 +104,8 @@
 }
 
 TEST(ConstantsTest, IntSigns) {
-  IntegerType* Int8Ty = Type::getInt8Ty(getGlobalContext());
+  LLVMContext Context;
+  IntegerType* Int8Ty = Type::getInt8Ty(Context);
   EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, false)->getSExtValue());
   EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, true)->getSExtValue());
   EXPECT_EQ(100, ConstantInt::getSigned(Int8Ty, 100)->getSExtValue());
@@ -116,16 +118,17 @@
 }
 
 TEST(ConstantsTest, FP128Test) {
-  Type *FP128Ty = Type::getFP128Ty(getGlobalContext());
+  LLVMContext Context;
+  Type *FP128Ty = Type::getFP128Ty(Context);
 
-  IntegerType *Int128Ty = Type::getIntNTy(getGlobalContext(), 128);
+  IntegerType *Int128Ty = Type::getIntNTy(Context, 128);
   Constant *Zero128 = Constant::getNullValue(Int128Ty);
   Constant *X = ConstantExpr::getUIToFP(Zero128, FP128Ty);
   EXPECT_TRUE(isa<ConstantFP>(X));
 }
 
 TEST(ConstantsTest, PointerCast) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Type *Int8PtrTy = Type::getInt8PtrTy(C);
   Type *Int32PtrTy = Type::getInt32PtrTy(C);
   Type *Int64Ty = Type::getInt64Ty(C);
@@ -165,14 +168,15 @@
   }
 
 TEST(ConstantsTest, AsInstructionsTest) {
-  std::unique_ptr<Module> M(new Module("MyModule", getGlobalContext()));
+  LLVMContext Context;
+  std::unique_ptr<Module> M(new Module("MyModule", Context));
 
-  Type *Int64Ty = Type::getInt64Ty(getGlobalContext());
-  Type *Int32Ty = Type::getInt32Ty(getGlobalContext());
-  Type *Int16Ty = Type::getInt16Ty(getGlobalContext());
-  Type *Int1Ty = Type::getInt1Ty(getGlobalContext());
-  Type *FloatTy = Type::getFloatTy(getGlobalContext());
-  Type *DoubleTy = Type::getDoubleTy(getGlobalContext());
+  Type *Int64Ty = Type::getInt64Ty(Context);
+  Type *Int32Ty = Type::getInt32Ty(Context);
+  Type *Int16Ty = Type::getInt16Ty(Context);
+  Type *Int1Ty = Type::getInt1Ty(Context);
+  Type *FloatTy = Type::getFloatTy(Context);
+  Type *DoubleTy = Type::getDoubleTy(Context);
 
   Constant *Global = M->getOrInsertGlobal("dummy",
                                          PointerType::getUnqual(Int32Ty));
@@ -189,7 +193,7 @@
 
   Constant *One = ConstantInt::get(Int32Ty, 1);
   Constant *Two = ConstantInt::get(Int64Ty, 2);
-  Constant *Big = ConstantInt::get(getGlobalContext(),
+  Constant *Big = ConstantInt::get(Context,
                                    APInt{256, uint64_t(-1), true});
   Constant *Elt = ConstantInt::get(Int16Ty, 2015);
   Constant *Undef16  = UndefValue::get(Int16Ty);
@@ -278,9 +282,10 @@
 #ifdef GTEST_HAS_DEATH_TEST
 #ifndef NDEBUG
 TEST(ConstantsTest, ReplaceWithConstantTest) {
-  std::unique_ptr<Module> M(new Module("MyModule", getGlobalContext()));
+  LLVMContext Context;
+  std::unique_ptr<Module> M(new Module("MyModule", Context));
 
-  Type *Int32Ty = Type::getInt32Ty(getGlobalContext());
+  Type *Int32Ty = Type::getInt32Ty(Context);
   Constant *One = ConstantInt::get(Int32Ty, 1);
 
   Constant *Global =
Index: unittests/IR/DominatorTreeTest.cpp
===================================================================
--- unittests/IR/DominatorTreeTest.cpp
+++ unittests/IR/DominatorTreeTest.cpp
@@ -215,7 +215,7 @@
     };
     char DPass::ID = 0;
 
-    std::unique_ptr<Module> makeLLVMModule(DPass *P) {
+    std::unique_ptr<Module> makeLLVMModule(LLVMContext &Context, DPass *P) {
       const char *ModuleStrig =
         "declare i32 @g()\n" \
         "define void @f(i32 %x) personality i32 ()* @g {\n" \
@@ -239,14 +239,14 @@
         "  %y9 = phi i32 [0, %bb2], [%y4, %bb1]\n"
         "  ret void\n" \
         "}\n";
-      LLVMContext &C = getGlobalContext();
       SMDiagnostic Err;
-      return parseAssemblyString(ModuleStrig, Err, C);
+      return parseAssemblyString(ModuleStrig, Err, Context);
     }
 
     TEST(DominatorTree, Unreachable) {
       DPass *P = new DPass();
-      std::unique_ptr<Module> M = makeLLVMModule(P);
+      LLVMContext Context;
+      std::unique_ptr<Module> M = makeLLVMModule(Context, P);
       legacy::PassManager Passes;
       Passes.add(P);
       Passes.run(*M);
Index: unittests/IR/InstructionsTest.cpp
===================================================================
--- unittests/IR/InstructionsTest.cpp
+++ unittests/IR/InstructionsTest.cpp
@@ -27,7 +27,7 @@
 namespace {
 
 TEST(InstructionsTest, ReturnInst) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
 
   // test for PR6589
   const ReturnInst* r0 = ReturnInst::Create(C);
@@ -103,7 +103,7 @@
 }
 
 TEST(InstructionsTest, BranchInst) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
 
   // Make a BasicBlocks
   BasicBlock* bb0 = BasicBlock::Create(C);
@@ -169,7 +169,7 @@
 }
 
 TEST(InstructionsTest, CastInst) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
 
   Type *Int8Ty = Type::getInt8Ty(C);
   Type *Int16Ty = Type::getInt16Ty(C);
@@ -281,14 +281,18 @@
   // First form
   BasicBlock *BB = BasicBlock::Create(C);
   Constant *NullV2I32Ptr = Constant::getNullValue(V2Int32PtrTy);
-  CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty, "foo", BB);
+  auto Inst1 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty, "foo", BB);
 
   // Second form
-  CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty);
+  auto Inst2 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty);
+
+  delete Inst2;
+  Inst1->eraseFromParent();
+  delete BB;
 }
 
 TEST(InstructionsTest, VectorGep) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
 
   // Type Definitions
   Type *I8Ty = IntegerType::get(C, 8);
@@ -391,7 +395,7 @@
 }
 
 TEST(InstructionsTest, FPMathOperator) {
-  LLVMContext &Context = getGlobalContext();
+  LLVMContext Context;
   IRBuilder<> Builder(Context);
   MDBuilder MDHelper(Context);
   Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
@@ -406,7 +410,7 @@
 
 
 TEST(InstructionsTest, isEliminableCastPair) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
 
   Type* Int16Ty = Type::getInt16Ty(C);
   Type* Int32Ty = Type::getInt32Ty(C);
@@ -486,7 +490,7 @@
 }
 
 TEST(InstructionsTest, CloneCall) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Type *Int32Ty = Type::getInt32Ty(C);
   Type *ArgTys[] = {Int32Ty, Int32Ty, Int32Ty};
   Type *FnTy = FunctionType::get(Int32Ty, ArgTys, /*isVarArg=*/false);
@@ -519,7 +523,7 @@
 }
 
 TEST(InstructionsTest, AlterCallBundles) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Type *Int32Ty = Type::getInt32Ty(C);
   Type *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
   Value *Callee = Constant::getNullValue(FnTy->getPointerTo());
@@ -546,7 +550,7 @@
 }
 
 TEST(InstructionsTest, AlterInvokeBundles) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Type *Int32Ty = Type::getInt32Ty(C);
   Type *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
   Value *Callee = Constant::getNullValue(FnTy->getPointerTo());
Index: unittests/IR/LegacyPassManagerTest.cpp
===================================================================
--- unittests/IR/LegacyPassManagerTest.cpp
+++ unittests/IR/LegacyPassManagerTest.cpp
@@ -288,7 +288,8 @@
     char OnTheFlyTest::ID=0;
 
     TEST(PassManager, RunOnce) {
-      Module M("test-once", getGlobalContext());
+      LLVMContext Context;
+      Module M("test-once", Context);
       struct ModuleNDNM *mNDNM = new ModuleNDNM();
       struct ModuleDNM *mDNM = new ModuleDNM();
       struct ModuleNDM *mNDM = new ModuleNDM();
@@ -311,7 +312,8 @@
     }
 
     TEST(PassManager, ReRun) {
-      Module M("test-rerun", getGlobalContext());
+      LLVMContext Context;
+      Module M("test-rerun", Context);
       struct ModuleNDNM *mNDNM = new ModuleNDNM();
       struct ModuleDNM *mDNM = new ModuleDNM();
       struct ModuleNDM *mNDM = new ModuleNDM();
@@ -334,11 +336,12 @@
       EXPECT_EQ(1, mDNM->run);
     }
 
-    Module* makeLLVMModule();
+    Module* makeLLVMModule(LLVMContext &Context);
 
     template<typename T>
     void MemoryTestHelper(int run) {
-      std::unique_ptr<Module> M(makeLLVMModule());
+      LLVMContext Context;
+      std::unique_ptr<Module> M(makeLLVMModule(Context));
       T *P = new T();
       legacy::PassManager Passes;
       Passes.add(P);
@@ -348,7 +351,8 @@
 
     template<typename T>
     void MemoryTestHelper(int run, int N) {
-      Module *M = makeLLVMModule();
+      LLVMContext Context;
+      Module *M = makeLLVMModule(Context);
       T *P = new T();
       legacy::PassManager Passes;
       Passes.add(P);
@@ -383,7 +387,8 @@
     }
 
     TEST(PassManager, MemoryOnTheFly) {
-      Module *M = makeLLVMModule();
+      LLVMContext Context;
+      Module *M = makeLLVMModule(Context);
       {
         SCOPED_TRACE("Running OnTheFlyTest");
         struct OnTheFlyTest *O = new OnTheFlyTest();
@@ -396,9 +401,9 @@
       delete M;
     }
 
-    Module* makeLLVMModule() {
+    Module* makeLLVMModule(LLVMContext &Context) {
       // Module Construction
-      Module* mod = new Module("test-mem", getGlobalContext());
+      Module* mod = new Module("test-mem", Context);
       mod->setDataLayout("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
                          "i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-"
                          "a:0:64-s:64:64-f80:128:128");
@@ -407,14 +412,14 @@
       // Type Definitions
       std::vector<Type*>FuncTy_0_args;
       FunctionType* FuncTy_0 = FunctionType::get(
-        /*Result=*/IntegerType::get(getGlobalContext(), 32),
+        /*Result=*/IntegerType::get(Context, 32),
         /*Params=*/FuncTy_0_args,
         /*isVarArg=*/false);
 
       std::vector<Type*>FuncTy_2_args;
-      FuncTy_2_args.push_back(IntegerType::get(getGlobalContext(), 1));
+      FuncTy_2_args.push_back(IntegerType::get(Context, 1));
       FunctionType* FuncTy_2 = FunctionType::get(
-        /*Result=*/Type::getVoidTy(getGlobalContext()),
+        /*Result=*/Type::getVoidTy(Context),
         /*Params=*/FuncTy_2_args,
         /*isVarArg=*/false);
 
@@ -465,7 +470,7 @@
       // Function: test1 (func_test1)
       {
 
-        BasicBlock* label_entry = BasicBlock::Create(getGlobalContext(), "entry",func_test1,nullptr);
+        BasicBlock* label_entry = BasicBlock::Create(Context, "entry",func_test1,nullptr);
 
         // Block entry (label_entry)
         CallInst* int32_3 = CallInst::Create(func_test2, "", label_entry);
@@ -473,14 +478,14 @@
         int32_3->setTailCall(false);AttributeSet int32_3_PAL;
         int32_3->setAttributes(int32_3_PAL);
 
-        ReturnInst::Create(getGlobalContext(), int32_3, label_entry);
+        ReturnInst::Create(Context, int32_3, label_entry);
 
       }
 
       // Function: test2 (func_test2)
       {
 
-        BasicBlock* label_entry_5 = BasicBlock::Create(getGlobalContext(), "entry",func_test2,nullptr);
+        BasicBlock* label_entry_5 = BasicBlock::Create(Context, "entry",func_test2,nullptr);
 
         // Block entry (label_entry_5)
         CallInst* int32_6 = CallInst::Create(func_test3, "", label_entry_5);
@@ -488,14 +493,14 @@
         int32_6->setTailCall(false);AttributeSet int32_6_PAL;
         int32_6->setAttributes(int32_6_PAL);
 
-        ReturnInst::Create(getGlobalContext(), int32_6, label_entry_5);
+        ReturnInst::Create(Context, int32_6, label_entry_5);
 
       }
 
       // Function: test3 (func_test3)
       {
 
-        BasicBlock* label_entry_8 = BasicBlock::Create(getGlobalContext(), "entry",func_test3,nullptr);
+        BasicBlock* label_entry_8 = BasicBlock::Create(Context, "entry",func_test3,nullptr);
 
         // Block entry (label_entry_8)
         CallInst* int32_9 = CallInst::Create(func_test1, "", label_entry_8);
@@ -503,7 +508,7 @@
         int32_9->setTailCall(false);AttributeSet int32_9_PAL;
         int32_9->setAttributes(int32_9_PAL);
 
-        ReturnInst::Create(getGlobalContext(), int32_9, label_entry_8);
+        ReturnInst::Create(Context, int32_9, label_entry_8);
 
       }
 
@@ -513,10 +518,10 @@
         Value *int1_f = &*args++;
         int1_f->setName("f");
 
-        BasicBlock* label_entry_11 = BasicBlock::Create(getGlobalContext(), "entry",func_test4,nullptr);
-        BasicBlock* label_bb = BasicBlock::Create(getGlobalContext(), "bb",func_test4,nullptr);
-        BasicBlock* label_bb1 = BasicBlock::Create(getGlobalContext(), "bb1",func_test4,nullptr);
-        BasicBlock* label_return = BasicBlock::Create(getGlobalContext(), "return",func_test4,nullptr);
+        BasicBlock* label_entry_11 = BasicBlock::Create(Context, "entry",func_test4,nullptr);
+        BasicBlock* label_bb = BasicBlock::Create(Context, "bb",func_test4,nullptr);
+        BasicBlock* label_bb1 = BasicBlock::Create(Context, "bb1",func_test4,nullptr);
+        BasicBlock* label_return = BasicBlock::Create(Context, "return",func_test4,nullptr);
 
         // Block entry (label_entry_11)
         BranchInst::Create(label_bb, label_entry_11);
@@ -528,7 +533,7 @@
         BranchInst::Create(label_bb1, label_return, int1_f, label_bb1);
 
         // Block return (label_return)
-        ReturnInst::Create(getGlobalContext(), label_return);
+        ReturnInst::Create(Context, label_return);
 
       }
       return mod;
Index: unittests/IR/MetadataTest.cpp
===================================================================
--- unittests/IR/MetadataTest.cpp
+++ unittests/IR/MetadataTest.cpp
@@ -175,7 +175,7 @@
   MDString *s1 = MDString::get(Context, StringRef(&x[0], 3));
   MDString *s2 = MDString::get(Context, StringRef(&y[0], 3));
   ConstantAsMetadata *CI = ConstantAsMetadata::get(
-      ConstantInt::get(getGlobalContext(), APInt(8, 0)));
+      ConstantInt::get(Context, APInt(8, 0)));
 
   std::vector<Metadata *> V;
   V.push_back(s1);
@@ -206,8 +206,8 @@
 }
 
 TEST_F(MDNodeTest, Delete) {
-  Constant *C = ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 1);
-  Instruction *I = new BitCastInst(C, Type::getInt32Ty(getGlobalContext()));
+  Constant *C = ConstantInt::get(Type::getInt32Ty(Context), 1);
+  Instruction *I = new BitCastInst(C, Type::getInt32Ty(Context));
 
   Metadata *const V = LocalAsMetadata::get(I);
   MDNode *n = MDNode::get(Context, V);
@@ -2063,7 +2063,7 @@
 TEST_F(ValueAsMetadataTest, TempTempReplacement) {
   // Create a constant.
   ConstantAsMetadata *CI = ConstantAsMetadata::get(
-      ConstantInt::get(getGlobalContext(), APInt(8, 0)));
+      ConstantInt::get(Context, APInt(8, 0)));
 
   auto Temp1 = MDTuple::getTemporary(Context, None);
   auto Temp2 = MDTuple::getTemporary(Context, {CI});
@@ -2080,7 +2080,7 @@
 TEST_F(ValueAsMetadataTest, CollidingDoubleUpdates) {
   // Create a constant.
   ConstantAsMetadata *CI = ConstantAsMetadata::get(
-      ConstantInt::get(getGlobalContext(), APInt(8, 0)));
+      ConstantInt::get(Context, APInt(8, 0)));
 
   // Create a temporary to prevent nodes from resolving.
   auto Temp = MDTuple::getTemporary(Context, None);
Index: unittests/IR/PassManagerTest.cpp
===================================================================
--- unittests/IR/PassManagerTest.cpp
+++ unittests/IR/PassManagerTest.cpp
@@ -153,19 +153,20 @@
   StringRef Name;
 };
 
-std::unique_ptr<Module> parseIR(const char *IR) {
-  LLVMContext &C = getGlobalContext();
+std::unique_ptr<Module> parseIR(LLVMContext &Context, const char *IR) {
   SMDiagnostic Err;
-  return parseAssemblyString(IR, Err, C);
+  return parseAssemblyString(IR, Err, Context);
 }
 
 class PassManagerTest : public ::testing::Test {
 protected:
+  LLVMContext Context;
   std::unique_ptr<Module> M;
 
 public:
   PassManagerTest()
-      : M(parseIR("define void @f() {\n"
+      : M(parseIR(Context,
+                  "define void @f() {\n"
                   "entry:\n"
                   "  call void @g()\n"
                   "  call void @h()\n"
Index: unittests/IR/TypeBuilderTest.cpp
===================================================================
--- unittests/IR/TypeBuilderTest.cpp
+++ unittests/IR/TypeBuilderTest.cpp
@@ -17,141 +17,147 @@
 namespace {
 
 TEST(TypeBuilderTest, Void) {
-  EXPECT_EQ(Type::getVoidTy(getGlobalContext()), (TypeBuilder<void, true>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getVoidTy(getGlobalContext()), (TypeBuilder<void, false>::get(getGlobalContext())));
+  LLVMContext Context;
+  EXPECT_EQ(Type::getVoidTy(Context), (TypeBuilder<void, true>::get(Context)));
+  EXPECT_EQ(Type::getVoidTy(Context), (TypeBuilder<void, false>::get(Context)));
   // Special cases for C compatibility:
-  EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()),
-            (TypeBuilder<void*, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()),
-            (TypeBuilder<const void*, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()),
-            (TypeBuilder<volatile void*, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()),
+  EXPECT_EQ(Type::getInt8PtrTy(Context),
+            (TypeBuilder<void*, false>::get(Context)));
+  EXPECT_EQ(Type::getInt8PtrTy(Context),
+            (TypeBuilder<const void*, false>::get(Context)));
+  EXPECT_EQ(Type::getInt8PtrTy(Context),
+            (TypeBuilder<volatile void*, false>::get(Context)));
+  EXPECT_EQ(Type::getInt8PtrTy(Context),
             (TypeBuilder<const volatile void*, false>::get(
-              getGlobalContext())));
+              Context)));
 }
 
 TEST(TypeBuilderTest, HostIntegers) {
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<int8_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<uint8_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt16Ty(getGlobalContext()), (TypeBuilder<int16_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt16Ty(getGlobalContext()), (TypeBuilder<uint16_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), (TypeBuilder<int32_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), (TypeBuilder<uint32_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt64Ty(getGlobalContext()), (TypeBuilder<int64_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt64Ty(getGlobalContext()), (TypeBuilder<uint64_t, false>::get(getGlobalContext())));
-
-  EXPECT_EQ(IntegerType::get(getGlobalContext(), sizeof(size_t) * CHAR_BIT),
-            (TypeBuilder<size_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(IntegerType::get(getGlobalContext(), sizeof(ptrdiff_t) * CHAR_BIT),
-            (TypeBuilder<ptrdiff_t, false>::get(getGlobalContext())));
+  LLVMContext Context;
+  EXPECT_EQ(Type::getInt8Ty(Context), (TypeBuilder<int8_t, false>::get(Context)));
+  EXPECT_EQ(Type::getInt8Ty(Context), (TypeBuilder<uint8_t, false>::get(Context)));
+  EXPECT_EQ(Type::getInt16Ty(Context), (TypeBuilder<int16_t, false>::get(Context)));
+  EXPECT_EQ(Type::getInt16Ty(Context), (TypeBuilder<uint16_t, false>::get(Context)));
+  EXPECT_EQ(Type::getInt32Ty(Context), (TypeBuilder<int32_t, false>::get(Context)));
+  EXPECT_EQ(Type::getInt32Ty(Context), (TypeBuilder<uint32_t, false>::get(Context)));
+  EXPECT_EQ(Type::getInt64Ty(Context), (TypeBuilder<int64_t, false>::get(Context)));
+  EXPECT_EQ(Type::getInt64Ty(Context), (TypeBuilder<uint64_t, false>::get(Context)));
+
+  EXPECT_EQ(IntegerType::get(Context, sizeof(size_t) * CHAR_BIT),
+            (TypeBuilder<size_t, false>::get(Context)));
+  EXPECT_EQ(IntegerType::get(Context, sizeof(ptrdiff_t) * CHAR_BIT),
+            (TypeBuilder<ptrdiff_t, false>::get(Context)));
 }
 
 TEST(TypeBuilderTest, CrossCompilableIntegers) {
-  EXPECT_EQ(IntegerType::get(getGlobalContext(), 1), (TypeBuilder<types::i<1>, true>::get(getGlobalContext())));
-  EXPECT_EQ(IntegerType::get(getGlobalContext(), 1), (TypeBuilder<types::i<1>, false>::get(getGlobalContext())));
-  EXPECT_EQ(IntegerType::get(getGlobalContext(), 72), (TypeBuilder<types::i<72>, true>::get(getGlobalContext())));
-  EXPECT_EQ(IntegerType::get(getGlobalContext(), 72), (TypeBuilder<types::i<72>, false>::get(getGlobalContext())));
+  LLVMContext Context;
+  EXPECT_EQ(IntegerType::get(Context, 1), (TypeBuilder<types::i<1>, true>::get(Context)));
+  EXPECT_EQ(IntegerType::get(Context, 1), (TypeBuilder<types::i<1>, false>::get(Context)));
+  EXPECT_EQ(IntegerType::get(Context, 72), (TypeBuilder<types::i<72>, true>::get(Context)));
+  EXPECT_EQ(IntegerType::get(Context, 72), (TypeBuilder<types::i<72>, false>::get(Context)));
 }
 
 TEST(TypeBuilderTest, Float) {
-  EXPECT_EQ(Type::getFloatTy(getGlobalContext()), (TypeBuilder<float, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getDoubleTy(getGlobalContext()), (TypeBuilder<double, false>::get(getGlobalContext())));
+  LLVMContext Context;
+  EXPECT_EQ(Type::getFloatTy(Context), (TypeBuilder<float, false>::get(Context)));
+  EXPECT_EQ(Type::getDoubleTy(Context), (TypeBuilder<double, false>::get(Context)));
   // long double isn't supported yet.
-  EXPECT_EQ(Type::getFloatTy(getGlobalContext()), (TypeBuilder<types::ieee_float, true>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getFloatTy(getGlobalContext()), (TypeBuilder<types::ieee_float, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getDoubleTy(getGlobalContext()), (TypeBuilder<types::ieee_double, true>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getDoubleTy(getGlobalContext()), (TypeBuilder<types::ieee_double, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getX86_FP80Ty(getGlobalContext()), (TypeBuilder<types::x86_fp80, true>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getX86_FP80Ty(getGlobalContext()), (TypeBuilder<types::x86_fp80, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getFP128Ty(getGlobalContext()), (TypeBuilder<types::fp128, true>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getFP128Ty(getGlobalContext()), (TypeBuilder<types::fp128, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getPPC_FP128Ty(getGlobalContext()), (TypeBuilder<types::ppc_fp128, true>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getPPC_FP128Ty(getGlobalContext()), (TypeBuilder<types::ppc_fp128, false>::get(getGlobalContext())));
+  EXPECT_EQ(Type::getFloatTy(Context), (TypeBuilder<types::ieee_float, true>::get(Context)));
+  EXPECT_EQ(Type::getFloatTy(Context), (TypeBuilder<types::ieee_float, false>::get(Context)));
+  EXPECT_EQ(Type::getDoubleTy(Context), (TypeBuilder<types::ieee_double, true>::get(Context)));
+  EXPECT_EQ(Type::getDoubleTy(Context), (TypeBuilder<types::ieee_double, false>::get(Context)));
+  EXPECT_EQ(Type::getX86_FP80Ty(Context), (TypeBuilder<types::x86_fp80, true>::get(Context)));
+  EXPECT_EQ(Type::getX86_FP80Ty(Context), (TypeBuilder<types::x86_fp80, false>::get(Context)));
+  EXPECT_EQ(Type::getFP128Ty(Context), (TypeBuilder<types::fp128, true>::get(Context)));
+  EXPECT_EQ(Type::getFP128Ty(Context), (TypeBuilder<types::fp128, false>::get(Context)));
+  EXPECT_EQ(Type::getPPC_FP128Ty(Context), (TypeBuilder<types::ppc_fp128, true>::get(Context)));
+  EXPECT_EQ(Type::getPPC_FP128Ty(Context), (TypeBuilder<types::ppc_fp128, false>::get(Context)));
 }
 
 TEST(TypeBuilderTest, Derived) {
-  EXPECT_EQ(PointerType::getUnqual(Type::getInt8PtrTy(getGlobalContext())),
-            (TypeBuilder<int8_t**, false>::get(getGlobalContext())));
-  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 7),
-            (TypeBuilder<int8_t[7], false>::get(getGlobalContext())));
-  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 0),
-            (TypeBuilder<int8_t[], false>::get(getGlobalContext())));
-
-  EXPECT_EQ(PointerType::getUnqual(Type::getInt8PtrTy(getGlobalContext())),
-            (TypeBuilder<types::i<8>**, false>::get(getGlobalContext())));
-  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 7),
-            (TypeBuilder<types::i<8>[7], false>::get(getGlobalContext())));
-  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 0),
-            (TypeBuilder<types::i<8>[], false>::get(getGlobalContext())));
-
-  EXPECT_EQ(PointerType::getUnqual(Type::getInt8PtrTy(getGlobalContext())),
-            (TypeBuilder<types::i<8>**, true>::get(getGlobalContext())));
-  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 7),
-            (TypeBuilder<types::i<8>[7], true>::get(getGlobalContext())));
-  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 0),
-            (TypeBuilder<types::i<8>[], true>::get(getGlobalContext())));
-
-
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()),
-            (TypeBuilder<const int8_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()),
-            (TypeBuilder<volatile int8_t, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()),
-            (TypeBuilder<const volatile int8_t, false>::get(getGlobalContext())));
-
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()),
-            (TypeBuilder<const types::i<8>, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()),
-            (TypeBuilder<volatile types::i<8>, false>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()),
-            (TypeBuilder<const volatile types::i<8>, false>::get(getGlobalContext())));
-
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()),
-            (TypeBuilder<const types::i<8>, true>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()),
-            (TypeBuilder<volatile types::i<8>, true>::get(getGlobalContext())));
-  EXPECT_EQ(Type::getInt8Ty(getGlobalContext()),
-            (TypeBuilder<const volatile types::i<8>, true>::get(getGlobalContext())));
-
-  EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()),
-            (TypeBuilder<const volatile int8_t*const volatile, false>::get(getGlobalContext())));
+  LLVMContext Context;
+  EXPECT_EQ(PointerType::getUnqual(Type::getInt8PtrTy(Context)),
+            (TypeBuilder<int8_t**, false>::get(Context)));
+  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(Context), 7),
+            (TypeBuilder<int8_t[7], false>::get(Context)));
+  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(Context), 0),
+            (TypeBuilder<int8_t[], false>::get(Context)));
+
+  EXPECT_EQ(PointerType::getUnqual(Type::getInt8PtrTy(Context)),
+            (TypeBuilder<types::i<8>**, false>::get(Context)));
+  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(Context), 7),
+            (TypeBuilder<types::i<8>[7], false>::get(Context)));
+  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(Context), 0),
+            (TypeBuilder<types::i<8>[], false>::get(Context)));
+
+  EXPECT_EQ(PointerType::getUnqual(Type::getInt8PtrTy(Context)),
+            (TypeBuilder<types::i<8>**, true>::get(Context)));
+  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(Context), 7),
+            (TypeBuilder<types::i<8>[7], true>::get(Context)));
+  EXPECT_EQ(ArrayType::get(Type::getInt8Ty(Context), 0),
+            (TypeBuilder<types::i<8>[], true>::get(Context)));
+
+
+  EXPECT_EQ(Type::getInt8Ty(Context),
+            (TypeBuilder<const int8_t, false>::get(Context)));
+  EXPECT_EQ(Type::getInt8Ty(Context),
+            (TypeBuilder<volatile int8_t, false>::get(Context)));
+  EXPECT_EQ(Type::getInt8Ty(Context),
+            (TypeBuilder<const volatile int8_t, false>::get(Context)));
+
+  EXPECT_EQ(Type::getInt8Ty(Context),
+            (TypeBuilder<const types::i<8>, false>::get(Context)));
+  EXPECT_EQ(Type::getInt8Ty(Context),
+            (TypeBuilder<volatile types::i<8>, false>::get(Context)));
+  EXPECT_EQ(Type::getInt8Ty(Context),
+            (TypeBuilder<const volatile types::i<8>, false>::get(Context)));
+
+  EXPECT_EQ(Type::getInt8Ty(Context),
+            (TypeBuilder<const types::i<8>, true>::get(Context)));
+  EXPECT_EQ(Type::getInt8Ty(Context),
+            (TypeBuilder<volatile types::i<8>, true>::get(Context)));
+  EXPECT_EQ(Type::getInt8Ty(Context),
+            (TypeBuilder<const volatile types::i<8>, true>::get(Context)));
+
+  EXPECT_EQ(Type::getInt8PtrTy(Context),
+            (TypeBuilder<const volatile int8_t*const volatile, false>::get(Context)));
 }
 
 TEST(TypeBuilderTest, Functions) {
+  LLVMContext Context;
   std::vector<Type*> params;
-  EXPECT_EQ(FunctionType::get(Type::getVoidTy(getGlobalContext()), params, false),
-            (TypeBuilder<void(), true>::get(getGlobalContext())));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true),
-            (TypeBuilder<int8_t(...), false>::get(getGlobalContext())));
-  params.push_back(TypeBuilder<int32_t*, false>::get(getGlobalContext()));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false),
-            (TypeBuilder<int8_t(const int32_t*), false>::get(getGlobalContext())));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true),
-            (TypeBuilder<int8_t(const int32_t*, ...), false>::get(getGlobalContext())));
-  params.push_back(TypeBuilder<char*, false>::get(getGlobalContext()));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false),
-            (TypeBuilder<int8_t(int32_t*, void*), false>::get(getGlobalContext())));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true),
-            (TypeBuilder<int8_t(int32_t*, char*, ...), false>::get(getGlobalContext())));
-  params.push_back(TypeBuilder<char, false>::get(getGlobalContext()));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false),
-            (TypeBuilder<int8_t(int32_t*, void*, char), false>::get(getGlobalContext())));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true),
-            (TypeBuilder<int8_t(int32_t*, char*, char, ...), false>::get(getGlobalContext())));
-  params.push_back(TypeBuilder<char, false>::get(getGlobalContext()));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false),
-            (TypeBuilder<int8_t(int32_t*, void*, char, char), false>::get(getGlobalContext())));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true),
+  EXPECT_EQ(FunctionType::get(Type::getVoidTy(Context), params, false),
+            (TypeBuilder<void(), true>::get(Context)));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, true),
+            (TypeBuilder<int8_t(...), false>::get(Context)));
+  params.push_back(TypeBuilder<int32_t*, false>::get(Context));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, false),
+            (TypeBuilder<int8_t(const int32_t*), false>::get(Context)));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, true),
+            (TypeBuilder<int8_t(const int32_t*, ...), false>::get(Context)));
+  params.push_back(TypeBuilder<char*, false>::get(Context));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, false),
+            (TypeBuilder<int8_t(int32_t*, void*), false>::get(Context)));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, true),
+            (TypeBuilder<int8_t(int32_t*, char*, ...), false>::get(Context)));
+  params.push_back(TypeBuilder<char, false>::get(Context));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, false),
+            (TypeBuilder<int8_t(int32_t*, void*, char), false>::get(Context)));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, true),
+            (TypeBuilder<int8_t(int32_t*, char*, char, ...), false>::get(Context)));
+  params.push_back(TypeBuilder<char, false>::get(Context));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, false),
+            (TypeBuilder<int8_t(int32_t*, void*, char, char), false>::get(Context)));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, true),
             (TypeBuilder<int8_t(int32_t*, char*, char, char, ...),
-                         false>::get(getGlobalContext())));
-  params.push_back(TypeBuilder<char, false>::get(getGlobalContext()));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false),
+                         false>::get(Context)));
+  params.push_back(TypeBuilder<char, false>::get(Context));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, false),
             (TypeBuilder<int8_t(int32_t*, void*, char, char, char),
-                         false>::get(getGlobalContext())));
-  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true),
+                         false>::get(Context)));
+  EXPECT_EQ(FunctionType::get(Type::getInt8Ty(Context), params, true),
             (TypeBuilder<int8_t(int32_t*, char*, char, char, char, ...),
-                         false>::get(getGlobalContext())));
+                         false>::get(Context)));
 }
 
 TEST(TypeBuilderTest, Context) {
@@ -230,24 +236,25 @@
 namespace {
 
 TEST(TypeBuilderTest, Extensions) {
+  LLVMContext Context;
   EXPECT_EQ(PointerType::getUnqual(StructType::get(
-                                     TypeBuilder<int, false>::get(getGlobalContext()),
-                                     TypeBuilder<int*, false>::get(getGlobalContext()),
-                                     TypeBuilder<void*[], false>::get(getGlobalContext()),
+                                     TypeBuilder<int, false>::get(Context),
+                                     TypeBuilder<int*, false>::get(Context),
+                                     TypeBuilder<void*[], false>::get(Context),
                                      (void*)nullptr)),
-            (TypeBuilder<MyType*, false>::get(getGlobalContext())));
+            (TypeBuilder<MyType*, false>::get(Context)));
   EXPECT_EQ(PointerType::getUnqual(StructType::get(
-                                     TypeBuilder<types::i<32>, false>::get(getGlobalContext()),
-                                     TypeBuilder<types::i<32>*, false>::get(getGlobalContext()),
-                                     TypeBuilder<types::i<8>*[], false>::get(getGlobalContext()),
+                                     TypeBuilder<types::i<32>, false>::get(Context),
+                                     TypeBuilder<types::i<32>*, false>::get(Context),
+                                     TypeBuilder<types::i<8>*[], false>::get(Context),
                                      (void*)nullptr)),
-            (TypeBuilder<MyPortableType*, false>::get(getGlobalContext())));
+            (TypeBuilder<MyPortableType*, false>::get(Context)));
   EXPECT_EQ(PointerType::getUnqual(StructType::get(
-                                     TypeBuilder<types::i<32>, false>::get(getGlobalContext()),
-                                     TypeBuilder<types::i<32>*, false>::get(getGlobalContext()),
-                                     TypeBuilder<types::i<8>*[], false>::get(getGlobalContext()),
+                                     TypeBuilder<types::i<32>, false>::get(Context),
+                                     TypeBuilder<types::i<32>*, false>::get(Context),
+                                     TypeBuilder<types::i<8>*[], false>::get(Context),
                                      (void*)nullptr)),
-            (TypeBuilder<MyPortableType*, true>::get(getGlobalContext())));
+            (TypeBuilder<MyPortableType*, true>::get(Context)));
 }
 
 }  // anonymous namespace
Index: unittests/IR/UserTest.cpp
===================================================================
--- unittests/IR/UserTest.cpp
+++ unittests/IR/UserTest.cpp
@@ -94,9 +94,10 @@
 }
 
 TEST(UserTest, PersonalityUser) {
-  Module M("", getGlobalContext());
+  LLVMContext Context;
+  Module M("", Context);
   FunctionType *RetVoidTy =
-      FunctionType::get(Type::getVoidTy(getGlobalContext()), false);
+      FunctionType::get(Type::getVoidTy(Context), false);
   Function *PersonalityF = Function::Create(
       RetVoidTy, GlobalValue::ExternalLinkage, "PersonalityFn", &M);
   Function *TestF =
Index: unittests/IR/ValueHandleTest.cpp
===================================================================
--- unittests/IR/ValueHandleTest.cpp
+++ unittests/IR/ValueHandleTest.cpp
@@ -20,12 +20,13 @@
 
 class ValueHandle : public testing::Test {
 protected:
+  LLVMContext Context;
   Constant *ConstantV;
   std::unique_ptr<BitCastInst> BitcastV;
 
   ValueHandle() :
-    ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)),
-    BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))) {
+    ConstantV(ConstantInt::get(Type::getInt32Ty(Context), 0)),
+    BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(Context))) {
   }
 };
 
@@ -42,8 +43,8 @@
 
   // Make sure I can call a method on the underlying Value.  It
   // doesn't matter which method.
-  EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), WVH->getType());
-  EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), (*WVH).getType());
+  EXPECT_EQ(Type::getInt32Ty(Context), WVH->getType());
+  EXPECT_EQ(Type::getInt32Ty(Context), (*WVH).getType());
 }
 
 TEST_F(ValueHandle, WeakVH_Comparisons) {
@@ -197,8 +198,8 @@
 
   // Make sure I can call a method on the underlying Value.  It
   // doesn't matter which method.
-  EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), CVH->getType());
-  EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), (*CVH).getType());
+  EXPECT_EQ(Type::getInt32Ty(Context), CVH->getType());
+  EXPECT_EQ(Type::getInt32Ty(Context), (*CVH).getType());
 }
 
 TEST_F(ValueHandle, CallbackVH_Comparisons) {
@@ -297,15 +298,16 @@
     Value *AURWArgument;
     LLVMContext *Context;
 
-    RecoveringVH() : DeletedCalls(0), AURWArgument(nullptr), 
-                     Context(&getGlobalContext()) {}
-    RecoveringVH(Value *V)
-      : CallbackVH(V), DeletedCalls(0), AURWArgument(nullptr), 
-        Context(&getGlobalContext()) {}
+    RecoveringVH(LLVMContext &TheContext) : DeletedCalls(0), AURWArgument(nullptr),
+                     Context(&TheContext) {}
+
+    RecoveringVH(LLVMContext &TheContext, Value *V)
+      : CallbackVH(V), DeletedCalls(0), AURWArgument(nullptr),
+          Context(&TheContext) {}
 
   private:
     void deleted() override {
-      getValPtr()->replaceAllUsesWith(Constant::getNullValue(Type::getInt32Ty(getGlobalContext())));
+      getValPtr()->replaceAllUsesWith(Constant::getNullValue(Type::getInt32Ty(*Context)));
       setValPtr(nullptr);
     }
     void allUsesReplacedWith(Value *new_value) override {
@@ -318,15 +320,15 @@
 
   // Normally, if a value has uses, deleting it will crash.  However, we can use
   // a CallbackVH to remove the uses before the check for no uses.
-  RecoveringVH RVH;
-  RVH = BitcastV.get();
+  RecoveringVH RVH(Context);
+  RVH = RecoveringVH(Context, BitcastV.get());
   std::unique_ptr<BinaryOperator> BitcastUser(
     BinaryOperator::CreateAdd(RVH, 
-                              Constant::getNullValue(Type::getInt32Ty(getGlobalContext()))));
+                              Constant::getNullValue(Type::getInt32Ty(Context))));
   EXPECT_EQ(BitcastV.get(), BitcastUser->getOperand(0));
   BitcastV.reset();  // Would crash without the ValueHandler.
-  EXPECT_EQ(Constant::getNullValue(Type::getInt32Ty(getGlobalContext())), RVH.AURWArgument);
-  EXPECT_EQ(Constant::getNullValue(Type::getInt32Ty(getGlobalContext())),
+  EXPECT_EQ(Constant::getNullValue(Type::getInt32Ty(Context)), RVH.AURWArgument);
+  EXPECT_EQ(Constant::getNullValue(Type::getInt32Ty(Context)),
             BitcastUser->getOperand(0));
 }
 
Index: unittests/IR/ValueMapTest.cpp
===================================================================
--- unittests/IR/ValueMapTest.cpp
+++ unittests/IR/ValueMapTest.cpp
@@ -22,13 +22,14 @@
 template<typename T>
 class ValueMapTest : public testing::Test {
 protected:
+  LLVMContext Context;
   Constant *ConstantV;
   std::unique_ptr<BitCastInst> BitcastV;
   std::unique_ptr<BinaryOperator> AddV;
 
   ValueMapTest() :
-    ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)),
-    BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))),
+    ConstantV(ConstantInt::get(Type::getInt32Ty(Context), 0)),
+    BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(Context))),
     AddV(BinaryOperator::CreateAdd(ConstantV, ConstantV)) {
   }
 };
Index: unittests/IR/ValueTest.cpp
===================================================================
--- unittests/IR/ValueTest.cpp
+++ unittests/IR/ValueTest.cpp
@@ -45,7 +45,7 @@
 }
 
 TEST(GlobalTest, CreateAddressSpace) {
-  LLVMContext &Ctx = getGlobalContext();
+  LLVMContext Ctx;
   std::unique_ptr<Module> M(new Module("TestModule", Ctx));
   Type *Int8Ty = Type::getInt8Ty(Ctx);
   Type *Int32Ty = Type::getInt32Ty(Ctx);
@@ -92,7 +92,7 @@
 #ifdef GTEST_HAS_DEATH_TEST
 #ifndef NDEBUG
 TEST(GlobalTest, AlignDeath) {
-  LLVMContext &Ctx = getGlobalContext();
+  LLVMContext Ctx;
   std::unique_ptr<Module> M(new Module("TestModule", Ctx));
   Type *Int32Ty = Type::getInt32Ty(Ctx);
   GlobalVariable *Var =
Index: unittests/IR/VerifierTest.cpp
===================================================================
--- unittests/IR/VerifierTest.cpp
+++ unittests/IR/VerifierTest.cpp
@@ -23,7 +23,7 @@
 namespace {
 
 TEST(VerifierTest, Branch_i1) {
-  LLVMContext &C = getGlobalContext();
+  LLVMContext C;
   Module M("M", C);
   FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg=*/false);
   Function *F = cast<Function>(M.getOrInsertFunction("foo", FTy));
@@ -46,7 +46,7 @@
 }
 
 TEST(VerifierTest, InvalidRetAttribute) {
-  LLVMContext &C = getGlobalContext();
+  LLVMContext C;
   Module M("M", C);
   FunctionType *FTy = FunctionType::get(Type::getInt32Ty(C), /*isVarArg=*/false);
   Function *F = cast<Function>(M.getOrInsertFunction("foo", FTy));
@@ -62,7 +62,7 @@
 }
 
 TEST(VerifierTest, CrossModuleRef) {
-  LLVMContext &C = getGlobalContext();
+  LLVMContext C;
   Module M1("M1", C);
   Module M2("M2", C);
   Module M3("M3", C);
@@ -121,7 +121,7 @@
 }
 
 TEST(VerifierTest, CrossModuleMetadataRef) {
-  LLVMContext &C = getGlobalContext();
+  LLVMContext C;
   Module M1("M1", C);
   Module M2("M2", C);
   GlobalVariable *newGV =
Index: unittests/IR/WaymarkTest.cpp
===================================================================
--- unittests/IR/WaymarkTest.cpp
+++ unittests/IR/WaymarkTest.cpp
@@ -19,16 +19,14 @@
 namespace llvm {
 namespace {
 
-Constant *char2constant(char c) {
-  return ConstantInt::get(Type::getInt8Ty(getGlobalContext()), c);
-}
-
-
 TEST(WaymarkTest, NativeArray) {
+  LLVMContext Context;
   static uint8_t tail[22] = "s02s33s30y2y0s1x0syxS";
   Value * values[22];
-  std::transform(tail, tail + 22, values, char2constant);
-  FunctionType *FT = FunctionType::get(Type::getVoidTy(getGlobalContext()), true);
+  std::transform(tail, tail + 22, values, [&] (char c) {
+    return ConstantInt::get(Type::getInt8Ty(Context), c);
+  });
+  FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), true);
   std::unique_ptr<Function> F(
       Function::Create(FT, GlobalValue::ExternalLinkage));
   const CallInst *A = CallInst::Create(F.get(), makeArrayRef(values));
Index: unittests/ProfileData/InstrProfTest.cpp
===================================================================
--- unittests/ProfileData/InstrProfTest.cpp
+++ unittests/ProfileData/InstrProfTest.cpp
@@ -180,7 +180,8 @@
   VerifySummary(PS);
 
   // Test that conversion of summary to and from Metadata works.
-  Metadata *MD = PS.getMD(getGlobalContext());
+  LLVMContext Context;
+  Metadata *MD = PS.getMD(Context);
   ASSERT_TRUE(MD);
   ProfileSummary *PSFromMD = ProfileSummary::getFromMD(MD);
   ASSERT_TRUE(PSFromMD);
@@ -190,7 +191,7 @@
   delete IPS;
 
   // Test that summary can be attached to and read back from module.
-  Module M("my_module", getGlobalContext());
+  Module M("my_module", Context);
   M.setProfileSummary(MD);
   MD = M.getProfileSummary();
   ASSERT_TRUE(MD);
Index: unittests/ProfileData/SampleProfTest.cpp
===================================================================
--- unittests/ProfileData/SampleProfTest.cpp
+++ unittests/ProfileData/SampleProfTest.cpp
@@ -29,6 +29,7 @@
 
 struct SampleProfTest : ::testing::Test {
   std::string Data;
+  LLVMContext Context;
   std::unique_ptr<raw_ostream> OS;
   std::unique_ptr<SampleProfileWriter> Writer;
   std::unique_ptr<SampleProfileReader> Reader;
@@ -43,7 +44,7 @@
   }
 
   void readProfile(std::unique_ptr<MemoryBuffer> &Profile) {
-    auto ReaderOrErr = SampleProfileReader::create(Profile, getGlobalContext());
+    auto ReaderOrErr = SampleProfileReader::create(Profile, Context);
     ASSERT_TRUE(NoError(ReaderOrErr.getError()));
     Reader = std::move(ReaderOrErr.get());
   }
@@ -127,7 +128,7 @@
     VerifySummary(Summary);
 
     // Test that conversion of summary to and from Metadata works.
-    Metadata *MD = Summary.getMD(getGlobalContext());
+    Metadata *MD = Summary.getMD(Context);
     ASSERT_TRUE(MD);
     ProfileSummary *PS = ProfileSummary::getFromMD(MD);
     ASSERT_TRUE(PS);
@@ -137,7 +138,7 @@
     delete SPS;
 
     // Test that summary can be attached to and read back from module.
-    Module M("my_module", getGlobalContext());
+    Module M("my_module", Context);
     M.setProfileSummary(MD);
     MD = M.getProfileSummary();
     ASSERT_TRUE(MD);
Index: unittests/Transforms/Utils/IntegerDivision.cpp
===================================================================
--- unittests/Transforms/Utils/IntegerDivision.cpp
+++ unittests/Transforms/Utils/IntegerDivision.cpp
@@ -21,7 +21,7 @@
 
 
 TEST(IntegerDivision, SDiv) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Module M("test division", C);
   IRBuilder<> Builder(C);
 
@@ -51,7 +51,7 @@
 }
 
 TEST(IntegerDivision, UDiv) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Module M("test division", C);
   IRBuilder<> Builder(C);
 
@@ -81,7 +81,7 @@
 }
 
 TEST(IntegerDivision, SRem) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Module M("test remainder", C);
   IRBuilder<> Builder(C);
 
@@ -111,7 +111,7 @@
 }
 
 TEST(IntegerDivision, URem) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Module M("test remainder", C);
   IRBuilder<> Builder(C);
 
@@ -142,7 +142,7 @@
 
 
 TEST(IntegerDivision, SDiv64) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Module M("test division", C);
   IRBuilder<> Builder(C);
 
@@ -172,7 +172,7 @@
 }
 
 TEST(IntegerDivision, UDiv64) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Module M("test division", C);
   IRBuilder<> Builder(C);
 
@@ -202,7 +202,7 @@
 }
 
 TEST(IntegerDivision, SRem64) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Module M("test remainder", C);
   IRBuilder<> Builder(C);
 
@@ -232,7 +232,7 @@
 }
 
 TEST(IntegerDivision, URem64) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   Module M("test remainder", C);
   IRBuilder<> Builder(C);
 
Index: unittests/Transforms/Utils/Local.cpp
===================================================================
--- unittests/Transforms/Utils/Local.cpp
+++ unittests/Transforms/Utils/Local.cpp
@@ -17,7 +17,7 @@
 using namespace llvm;
 
 TEST(Local, RecursivelyDeleteDeadPHINodes) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
 
   IRBuilder<> builder(C);
 
@@ -60,7 +60,7 @@
 }
 
 TEST(Local, RemoveDuplicatePHINodes) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   IRBuilder<> B(C);
 
   std::unique_ptr<Function> F(
Index: unittests/Transforms/Utils/MemorySSA.cpp
===================================================================
--- unittests/Transforms/Utils/MemorySSA.cpp
+++ unittests/Transforms/Utils/MemorySSA.cpp
@@ -20,7 +20,7 @@
 using namespace llvm;
 
 TEST(MemorySSA, RemoveMemoryAccess) {
-  LLVMContext &C(getGlobalContext());
+  LLVMContext C;
   std::unique_ptr<Module> M(new Module("Remove memory access", C));
   IRBuilder<> B(C);
   DataLayout DL("e-i64:64-f80:128-n8:16:32:64-S128");