Add a pointer to the owning LLVMContext to Module.  This requires threading LLVMContext through a lot
of the bitcode reader and ASM parser APIs, as well as supporting it in all of the tools.

Patches for Clang and LLVM-GCC to follow.


git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@74614 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/tools/bugpoint/BugDriver.cpp b/tools/bugpoint/BugDriver.cpp
index d050b59..340522a 100644
--- a/tools/bugpoint/BugDriver.cpp
+++ b/tools/bugpoint/BugDriver.cpp
@@ -64,24 +64,24 @@
 }
 
 BugDriver::BugDriver(const char *toolname, bool as_child, bool find_bugs,
-                     unsigned timeout, unsigned memlimit)
-  : ToolName(toolname), ReferenceOutputFile(OutputFile),
+                     unsigned timeout, unsigned memlimit, LLVMContext* ctxt)
+  : Context(ctxt), ToolName(toolname), ReferenceOutputFile(OutputFile),
     Program(0), Interpreter(0), SafeInterpreter(0), gcc(0),
-    run_as_child(as_child),
-    run_find_bugs(find_bugs), Timeout(timeout), MemoryLimit(memlimit) {}
+    run_as_child(as_child), run_find_bugs(find_bugs), Timeout(timeout), 
+    MemoryLimit(memlimit)  {}
 
 
 /// ParseInputFile - Given a bitcode or assembly input filename, parse and
 /// return it, or return null if not possible.
 ///
-Module *llvm::ParseInputFile(const std::string &Filename) {
+Module *llvm::ParseInputFile(const std::string &Filename, LLVMContext* Ctxt) {
   std::auto_ptr<MemoryBuffer> Buffer(MemoryBuffer::getFileOrSTDIN(Filename));
   Module *Result = 0;
   if (Buffer.get())
-    Result = ParseBitcodeFile(Buffer.get());
+    Result = ParseBitcodeFile(Buffer.get(), Ctxt);
   
   ParseError Err;
-  if (!Result && !(Result = ParseAssemblyFile(Filename, Err))) {
+  if (!Result && !(Result = ParseAssemblyFile(Filename, Err, Ctxt))) {
     Err.PrintError("bugpoint", errs()); 
     Result = 0;
   }
@@ -100,14 +100,14 @@
 
   try {
     // Load the first input file.
-    Program = ParseInputFile(Filenames[0]);
+    Program = ParseInputFile(Filenames[0], Context);
     if (Program == 0) return true;
     
     if (!run_as_child)
       std::cout << "Read input file      : '" << Filenames[0] << "'\n";
 
     for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {
-      std::auto_ptr<Module> M(ParseInputFile(Filenames[i]));
+      std::auto_ptr<Module> M(ParseInputFile(Filenames[i], Context));
       if (M.get() == 0) return true;
 
       if (!run_as_child)
diff --git a/tools/bugpoint/BugDriver.h b/tools/bugpoint/BugDriver.h
index 96e9fb9..4c81cc2 100644
--- a/tools/bugpoint/BugDriver.h
+++ b/tools/bugpoint/BugDriver.h
@@ -30,6 +30,7 @@
 class BasicBlock;
 class AbstractInterpreter;
 class Instruction;
+class LLVMContext;
 
 class DebugCrashes;
 
@@ -42,6 +43,7 @@
 extern bool BugpointIsInterrupted;
 
 class BugDriver {
+  LLVMContext* Context;
   const std::string ToolName;  // Name of bugpoint
   std::string ReferenceOutputFile; // Name of `good' output file
   Module *Program;             // The raw program, linked together
@@ -60,10 +62,12 @@
 
 public:
   BugDriver(const char *toolname, bool as_child, bool find_bugs,
-            unsigned timeout, unsigned memlimit);
+            unsigned timeout, unsigned memlimit, LLVMContext* ctxt);
 
   const std::string &getToolName() const { return ToolName; }
 
+  LLVMContext* getContext() { return Context; }
+
   // Set up methods... these methods are used to copy information about the
   // command line arguments into instance variables of BugDriver.
   //
@@ -290,7 +294,7 @@
 /// ParseInputFile - Given a bitcode or assembly input filename, parse and
 /// return it, or return null if not possible.
 ///
-Module *ParseInputFile(const std::string &InputFilename);
+Module *ParseInputFile(const std::string &InputFilename, LLVMContext* ctxt);
 
 
 /// getPassesString - Turn a list of passes into a string which indicates the
diff --git a/tools/bugpoint/CrashDebugger.cpp b/tools/bugpoint/CrashDebugger.cpp
index 7daf57c..9697b34 100644
--- a/tools/bugpoint/CrashDebugger.cpp
+++ b/tools/bugpoint/CrashDebugger.cpp
@@ -73,7 +73,7 @@
     PrefixOutput.set(PfxOutput);
     OrigProgram = BD.Program;
 
-    BD.Program = ParseInputFile(PrefixOutput.toString());
+    BD.Program = ParseInputFile(PrefixOutput.toString(), BD.getContext());
     if (BD.Program == 0) {
       std::cerr << BD.getToolName() << ": Error reading bitcode file '"
                 << PrefixOutput << "'!\n";
diff --git a/tools/bugpoint/Miscompilation.cpp b/tools/bugpoint/Miscompilation.cpp
index 7e8ff78..b3260e1 100644
--- a/tools/bugpoint/Miscompilation.cpp
+++ b/tools/bugpoint/Miscompilation.cpp
@@ -112,7 +112,7 @@
   // Ok, so now we know that the prefix passes work, try running the suffix
   // passes on the result of the prefix passes.
   //
-  Module *PrefixOutput = ParseInputFile(BitcodeResult);
+  Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
   if (PrefixOutput == 0) {
     std::cerr << BD.getToolName() << ": Error reading bitcode file '"
               << BitcodeResult << "'!\n";
diff --git a/tools/bugpoint/OptimizerDriver.cpp b/tools/bugpoint/OptimizerDriver.cpp
index 3ded5e8..741be24 100644
--- a/tools/bugpoint/OptimizerDriver.cpp
+++ b/tools/bugpoint/OptimizerDriver.cpp
@@ -255,7 +255,7 @@
   // Restore the current program.
   swapProgramIn(OldProgram);
 
-  Module *Ret = ParseInputFile(BitcodeResult);
+  Module *Ret = ParseInputFile(BitcodeResult, Context);
   if (Ret == 0) {
     cerr << getToolName() << ": Error reading bitcode file '"
          << BitcodeResult << "'!\n";
diff --git a/tools/bugpoint/bugpoint.cpp b/tools/bugpoint/bugpoint.cpp
index 20f0e99..57007e0 100644
--- a/tools/bugpoint/bugpoint.cpp
+++ b/tools/bugpoint/bugpoint.cpp
@@ -16,6 +16,7 @@
 #include "BugDriver.h"
 #include "ToolRunner.h"
 #include "llvm/LinkAllPasses.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Support/PassNameParser.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ManagedStatic.h"
@@ -73,8 +74,9 @@
                               "llvm.org/cmds/bugpoint.html"
                               " for more information.\n");
   sys::SetInterruptFunction(BugpointInterruptFunction);
-  
-  BugDriver D(argv[0], AsChild, FindBugs, TimeoutValue, MemoryLimit);
+
+  LLVMContext Context;
+  BugDriver D(argv[0], AsChild, FindBugs, TimeoutValue, MemoryLimit, &Context);
   if (D.addSources(InputFilenames)) return 1;
   D.addPasses(PassList.begin(), PassList.end());
 
diff --git a/tools/llc/llc.cpp b/tools/llc/llc.cpp
index e71b378..d0d88c5 100644
--- a/tools/llc/llc.cpp
+++ b/tools/llc/llc.cpp
@@ -22,6 +22,7 @@
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetMachineRegistry.h"
 #include "llvm/Transforms/Scalar.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/ModuleProvider.h"
 #include "llvm/PassManager.h"
@@ -212,6 +213,7 @@
 int main(int argc, char **argv) {
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
 
@@ -225,7 +227,7 @@
   std::auto_ptr<MemoryBuffer> Buffer(
                    MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
   if (Buffer.get())
-    M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
+    M.reset(ParseBitcodeFile(Buffer.get(), &Context, &ErrorMessage));
   if (M.get() == 0) {
     std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
     std::cerr << "Reason: " << ErrorMessage << "\n";
diff --git a/tools/lli/lli.cpp b/tools/lli/lli.cpp
index 2553674..10b8638 100644
--- a/tools/lli/lli.cpp
+++ b/tools/lli/lli.cpp
@@ -13,6 +13,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/ModuleProvider.h"
 #include "llvm/Type.h"
@@ -93,6 +94,7 @@
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
   
+  LLVMContext Context;
   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
   cl::ParseCommandLineOptions(argc, argv,
                               "llvm interpreter & dynamic compiler\n");
@@ -104,8 +106,8 @@
   // Load the bitcode...
   std::string ErrorMsg;
   ModuleProvider *MP = NULL;
-  if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)) {
-    MP = getBitcodeModuleProvider(Buffer, &ErrorMsg);
+  if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)){
+    MP = getBitcodeModuleProvider(Buffer, &Context, &ErrorMsg);
     if (!MP) delete Buffer;
   }
   
diff --git a/tools/llvm-ar/llvm-ar.cpp b/tools/llvm-ar/llvm-ar.cpp
index 5d81fc7..960f8e3 100644
--- a/tools/llvm-ar/llvm-ar.cpp
+++ b/tools/llvm-ar/llvm-ar.cpp
@@ -12,6 +12,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/Bitcode/Archive.h"
 #include "llvm/Support/CommandLine.h"
@@ -690,6 +691,7 @@
   // Print a stack trace if we signal out.
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
 
   // Have the command line options parsed and handle things
@@ -717,11 +719,11 @@
       // Produce a warning if we should and we're creating the archive
       if (!Create)
         std::cerr << argv[0] << ": creating " << ArchivePath.toString() << "\n";
-      TheArchive = Archive::CreateEmpty(ArchivePath);
+      TheArchive = Archive::CreateEmpty(ArchivePath, &Context);
       TheArchive->writeToDisk();
     } else {
       std::string Error;
-      TheArchive = Archive::OpenAndLoad(ArchivePath, &Error);
+      TheArchive = Archive::OpenAndLoad(ArchivePath, &Context, &Error);
       if (TheArchive == 0) {
         std::cerr << argv[0] << ": error loading '" << ArchivePath << "': "
                   << Error << "!\n";
diff --git a/tools/llvm-as/llvm-as.cpp b/tools/llvm-as/llvm-as.cpp
index 79ece8f..06798cb 100644
--- a/tools/llvm-as/llvm-as.cpp
+++ b/tools/llvm-as/llvm-as.cpp
@@ -15,6 +15,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/Assembly/Parser.h"
 #include "llvm/Analysis/Verifier.h"
@@ -55,6 +56,7 @@
   // Print a stack trace if we signal out.
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   cl::ParseCommandLineOptions(argc, argv, "llvm .ll -> .bc assembler\n");
 
@@ -63,7 +65,7 @@
   try {
     // Parse the file now...
     ParseError Err;
-    std::auto_ptr<Module> M(ParseAssemblyFile(InputFilename, Err));
+    std::auto_ptr<Module> M(ParseAssemblyFile(InputFilename, Err, &Context));
     if (M.get() == 0) {
       Err.PrintError(argv[0], errs());
       return 1;
diff --git a/tools/llvm-db/CLIDebugger.cpp b/tools/llvm-db/CLIDebugger.cpp
index 1d2a838..c7aedd1 100644
--- a/tools/llvm-db/CLIDebugger.cpp
+++ b/tools/llvm-db/CLIDebugger.cpp
@@ -22,8 +22,9 @@
 /// CLIDebugger constructor - This initializes the debugger to its default
 /// state, and initializes the command table.
 ///
-CLIDebugger::CLIDebugger()
-  : TheProgramInfo(0), TheRuntimeInfo(0), Prompt("(llvm-db) "), ListSize(10) {
+CLIDebugger::CLIDebugger(LLVMContext* ctxt)
+  : Context(ctxt), TheProgramInfo(0), TheRuntimeInfo(0),
+    Prompt("(llvm-db) "), ListSize(10) {
   // Initialize instance variables
   CurrentFile = 0;
   LineListedStart = 1;
diff --git a/tools/llvm-db/CLIDebugger.h b/tools/llvm-db/CLIDebugger.h
index 56ea14d..b1a31a4 100644
--- a/tools/llvm-db/CLIDebugger.h
+++ b/tools/llvm-db/CLIDebugger.h
@@ -24,10 +24,13 @@
   class SourceLanguage;
   class ProgramInfo;
   class RuntimeInfo;
+  class LLVMContext;
 
   /// CLIDebugger - This class implements the command line interface for the
   /// LLVM debugger.
   class CLIDebugger {
+    LLVMContext* Context;
+    
     /// Dbg - The low-level LLVM debugger object that we use to do our dirty
     /// work.
     Debugger Dbg;
@@ -79,7 +82,7 @@
     const SourceLanguage *CurrentLanguage;
 
   public:
-    CLIDebugger();
+    CLIDebugger(LLVMContext* ctxt);
 
     /// getDebugger - Return the current LLVM debugger implementation being
     /// used.
diff --git a/tools/llvm-db/Commands.cpp b/tools/llvm-db/Commands.cpp
index ffebdd5..4c916f4 100644
--- a/tools/llvm-db/Commands.cpp
+++ b/tools/llvm-db/Commands.cpp
@@ -64,7 +64,7 @@
     TheProgramInfo = 0;
     CurrentFile = 0;
 
-    Dbg.loadProgram(Program.toString());
+    Dbg.loadProgram(Program.toString(), Context);
     TheProgramInfo = new ProgramInfo(Dbg.getProgram());
   }
 
@@ -244,7 +244,7 @@
     std::cout << "Unloaded program.\n";
   } else {
     std::cout << "Loading program... " << std::flush;
-    Dbg.loadProgram(Prog);
+    Dbg.loadProgram(Prog, Context);
     assert(Dbg.isProgramLoaded() &&
            "loadProgram succeeded, but not program loaded!");
     TheProgramInfo = new ProgramInfo(Dbg.getProgram());
diff --git a/tools/llvm-db/llvm-db.cpp b/tools/llvm-db/llvm-db.cpp
index 04e6162..62ee325 100644
--- a/tools/llvm-db/llvm-db.cpp
+++ b/tools/llvm-db/llvm-db.cpp
@@ -13,6 +13,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "CLIDebugger.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/PrettyStackTrace.h"
@@ -54,6 +55,7 @@
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
   
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   std::cout << "NOTE: llvm-db is known useless right now.\n";
   try {
@@ -68,7 +70,7 @@
       InputArgs.push_back(InputFile);
 
     // Create the CLI debugger...
-    CLIDebugger D;
+    CLIDebugger D(&Context);
 
     // Initialize the debugger with the command line options we read...
     Debugger &Dbg = D.getDebugger();
diff --git a/tools/llvm-dis/llvm-dis.cpp b/tools/llvm-dis/llvm-dis.cpp
index 471e5e2..3460f7e 100644
--- a/tools/llvm-dis/llvm-dis.cpp
+++ b/tools/llvm-dis/llvm-dis.cpp
@@ -16,6 +16,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/PassManager.h"
 #include "llvm/Bitcode/ReaderWriter.h"
@@ -50,6 +51,7 @@
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
   
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   try {
     cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
@@ -61,7 +63,7 @@
    
     if (MemoryBuffer *Buffer
            = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
-      M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
+      M.reset(ParseBitcodeFile(Buffer, &Context, &ErrorMessage));
       delete Buffer;
     }
 
diff --git a/tools/llvm-extract/llvm-extract.cpp b/tools/llvm-extract/llvm-extract.cpp
index 46840f2..a977211 100644
--- a/tools/llvm-extract/llvm-extract.cpp
+++ b/tools/llvm-extract/llvm-extract.cpp
@@ -12,6 +12,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/PassManager.h"
 #include "llvm/Bitcode/ReaderWriter.h"
@@ -60,7 +61,8 @@
   // Print a stack trace if we signal out.
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
-  
+
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
 
@@ -71,7 +73,7 @@
     cerr << argv[0] << ": Error reading file '" + InputFilename + "'\n";
     return 1;
   } else {
-    M.reset(ParseBitcodeFile(Buffer));
+    M.reset(ParseBitcodeFile(Buffer, &Context));
   }
   delete Buffer;
   
diff --git a/tools/llvm-ld/llvm-ld.cpp b/tools/llvm-ld/llvm-ld.cpp
index fd2e0f7..435de0f 100644
--- a/tools/llvm-ld/llvm-ld.cpp
+++ b/tools/llvm-ld/llvm-ld.cpp
@@ -22,6 +22,7 @@
 
 #include "llvm/LinkAllVMCore.h"
 #include "llvm/Linker.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/System/Program.h"
 #include "llvm/Module.h"
 #include "llvm/PassManager.h"
@@ -505,7 +506,8 @@
   // Print a stack trace if we signal out.
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
-  
+
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   try {
     // Initial global variable above for convenience printing of program name.
@@ -515,7 +517,7 @@
     cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
 
     // Construct a Linker (now that Verbose is set)
-    Linker TheLinker(progname, OutputFilename, Verbose);
+    Linker TheLinker(progname, OutputFilename, &Context, Verbose);
 
     // Keep track of the native link items (versus the bitcode items)
     Linker::ItemList NativeLinkItems;
diff --git a/tools/llvm-link/llvm-link.cpp b/tools/llvm-link/llvm-link.cpp
index 15850f4..ae5fa40 100644
--- a/tools/llvm-link/llvm-link.cpp
+++ b/tools/llvm-link/llvm-link.cpp
@@ -13,6 +13,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Linker.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/Analysis/Verifier.h"
 #include "llvm/Bitcode/ReaderWriter.h"
@@ -47,7 +48,8 @@
 // LoadFile - Read the specified bitcode file in and return it.  This routine
 // searches the link path for the specified file to try to find it...
 //
-static inline std::auto_ptr<Module> LoadFile(const std::string &FN) {
+static inline std::auto_ptr<Module> LoadFile(const std::string &FN, 
+                                             LLVMContext* Context) {
   sys::Path Filename;
   if (!Filename.set(FN)) {
     cerr << "Invalid file name: '" << FN << "'\n";
@@ -62,7 +64,7 @@
     const std::string &FNStr = Filename.toString();
     if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(FNStr,
                                                             &ErrorMessage)) {
-      Result = ParseBitcodeFile(Buffer, &ErrorMessage);
+      Result = ParseBitcodeFile(Buffer, Context, &ErrorMessage);
       delete Buffer;
     }
     if (Result) return std::auto_ptr<Module>(Result);   // Load successful!
@@ -84,13 +86,14 @@
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
   
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
 
   unsigned BaseArg = 0;
   std::string ErrorMessage;
 
-  std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg]));
+  std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg], &Context));
   if (Composite.get() == 0) {
     cerr << argv[0] << ": error loading file '"
          << InputFilenames[BaseArg] << "'\n";
@@ -98,7 +101,7 @@
   }
 
   for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
-    std::auto_ptr<Module> M(LoadFile(InputFilenames[i]));
+    std::auto_ptr<Module> M(LoadFile(InputFilenames[i], &Context));
     if (M.get() == 0) {
       cerr << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n";
       return 1;
diff --git a/tools/llvm-nm/llvm-nm.cpp b/tools/llvm-nm/llvm-nm.cpp
index 324e0f6..3f19940 100644
--- a/tools/llvm-nm/llvm-nm.cpp
+++ b/tools/llvm-nm/llvm-nm.cpp
@@ -16,6 +16,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/Bitcode/ReaderWriter.h"
 #include "llvm/Bitcode/Archive.h"
@@ -132,6 +133,7 @@
 }
 
 static void DumpSymbolNamesFromFile(std::string &Filename) {
+  LLVMContext Context;
   std::string ErrorMessage;
   sys::Path aPath(Filename);
   // Note: Currently we do not support reading an archive from stdin.
@@ -140,7 +142,7 @@
                    MemoryBuffer::getFileOrSTDIN(Filename, &ErrorMessage));
     Module *Result = 0;
     if (Buffer.get())
-      Result = ParseBitcodeFile(Buffer.get(), &ErrorMessage);
+      Result = ParseBitcodeFile(Buffer.get(), &Context, &ErrorMessage);
     
     if (Result)
       DumpSymbolNamesFromModule(Result);
@@ -151,7 +153,8 @@
     
   } else if (aPath.isArchive()) {
     std::string ErrMsg;
-    Archive* archive = Archive::OpenAndLoad(sys::Path(Filename), &ErrorMessage);
+    Archive* archive = Archive::OpenAndLoad(sys::Path(Filename), &Context,
+                                            &ErrorMessage);
     if (!archive)
       std::cerr << ToolName << ": " << Filename << ": " << ErrorMessage << "\n";
     std::vector<Module *> Modules;
diff --git a/tools/llvm-prof/llvm-prof.cpp b/tools/llvm-prof/llvm-prof.cpp
index 119dc1a..104d8794 100644
--- a/tools/llvm-prof/llvm-prof.cpp
+++ b/tools/llvm-prof/llvm-prof.cpp
@@ -14,6 +14,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/InstrTypes.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/Assembly/AsmAnnotationWriter.h"
 #include "llvm/Analysis/ProfileInfoLoader.h"
@@ -115,7 +116,8 @@
   // Print a stack trace if we signal out.
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
-  
+
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   try {
     cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");
@@ -125,7 +127,7 @@
     Module *M = 0;
     if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile,
                                                             &ErrorMessage)) {
-      M = ParseBitcodeFile(Buffer, &ErrorMessage);
+      M = ParseBitcodeFile(Buffer, &Context, &ErrorMessage);
       delete Buffer;
     }
     if (M == 0) {
diff --git a/tools/llvm-ranlib/llvm-ranlib.cpp b/tools/llvm-ranlib/llvm-ranlib.cpp
index 7210610..7b1b413 100644
--- a/tools/llvm-ranlib/llvm-ranlib.cpp
+++ b/tools/llvm-ranlib/llvm-ranlib.cpp
@@ -11,6 +11,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/Bitcode/Archive.h"
 #include "llvm/Support/CommandLine.h"
@@ -46,7 +47,8 @@
   // Print a stack trace if we signal out.
   llvm::sys::PrintStackTraceOnErrorSignal();
   llvm::PrettyStackTraceProgram X(argc, argv);
-  
+
+  LLVMContext Context;
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
 
   // Have the command line options parsed and handle things
@@ -73,7 +75,7 @@
 
     std::string err_msg;
     std::auto_ptr<Archive>
-      AutoArchive(Archive::OpenAndLoad(ArchivePath,&err_msg));
+      AutoArchive(Archive::OpenAndLoad(ArchivePath, &Context, &err_msg));
     Archive* TheArchive = AutoArchive.get();
     if (!TheArchive)
       throw err_msg;
diff --git a/tools/lto/LTOCodeGenerator.cpp b/tools/lto/LTOCodeGenerator.cpp
index 52624eb..8ae196f 100644
--- a/tools/lto/LTOCodeGenerator.cpp
+++ b/tools/lto/LTOCodeGenerator.cpp
@@ -70,7 +70,8 @@
 
 
 LTOCodeGenerator::LTOCodeGenerator() 
-    : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
+    : _context(new LLVMContext()),
+      _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
       _nativeObjectFile(NULL), _gccPath(NULL), _assemblerPath(NULL)
diff --git a/tools/lto/LTOCodeGenerator.h b/tools/lto/LTOCodeGenerator.h
index e02a7ab..d412626 100644
--- a/tools/lto/LTOCodeGenerator.h
+++ b/tools/lto/LTOCodeGenerator.h
@@ -16,6 +16,7 @@
 #define LTO_CODE_GENERATOR_H
 
 #include "llvm/Linker.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/SmallVector.h"
 
@@ -53,6 +54,7 @@
     
     typedef llvm::StringMap<uint8_t> StringSet;
 
+    llvm::LLVMContext*          _context;
     llvm::Linker                _linker;
     llvm::TargetMachine*        _target;
     bool                        _emitDwarfDebugInfo;
diff --git a/tools/lto/LTOModule.cpp b/tools/lto/LTOModule.cpp
index 939d0ea..64e7950 100644
--- a/tools/lto/LTOModule.cpp
+++ b/tools/lto/LTOModule.cpp
@@ -15,6 +15,7 @@
 #include "LTOModule.h"
 
 #include "llvm/Constants.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/ModuleProvider.h"
 #include "llvm/ADT/OwningPtr.h"
@@ -67,7 +68,8 @@
 // takes ownership of buffer
 bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
 {
-    OwningPtr<ModuleProvider> mp(getBitcodeModuleProvider(buffer));
+    OwningPtr<ModuleProvider> mp(getBitcodeModuleProvider(buffer,
+                                                          new LLVMContext()));
     // on success, mp owns buffer and both are deleted at end of this method
     if ( !mp ) {
         delete buffer;
@@ -84,12 +86,13 @@
 {
 }
 
-LTOModule* LTOModule::makeLTOModule(const char* path, std::string& errMsg)
+LTOModule* LTOModule::makeLTOModule(const char* path, LLVMContext* Context,
+                                    std::string& errMsg)
 {
     OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getFile(path, &errMsg));
     if ( !buffer )
         return NULL;
-    return makeLTOModule(buffer.get(), errMsg);
+    return makeLTOModule(buffer.get(), Context, errMsg);
 }
 
 /// makeBuffer - create a MemoryBuffer from a memory range.
@@ -109,12 +112,13 @@
 
 
 LTOModule* LTOModule::makeLTOModule(const void* mem, size_t length, 
+                                    LLVMContext* Context,
                                     std::string& errMsg)
 {
     OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
     if ( !buffer )
         return NULL;
-    return makeLTOModule(buffer.get(), errMsg);
+    return makeLTOModule(buffer.get(), Context, errMsg);
 }
 
 /// getFeatureString - Return a string listing the features associated with the
@@ -136,10 +140,11 @@
   return Features.getString();
 }
 
-LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer, std::string& errMsg)
+LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer, LLVMContext* Context,
+                                    std::string& errMsg)
 {
     // parse bitcode buffer
-    OwningPtr<Module> m(ParseBitcodeFile(buffer, &errMsg));
+    OwningPtr<Module> m(ParseBitcodeFile(buffer, Context, &errMsg));
     if ( !m )
         return NULL;
     // find machine architecture for this module
diff --git a/tools/lto/LTOModule.h b/tools/lto/LTOModule.h
index 9de02a2..bfdf6e7 100644
--- a/tools/lto/LTOModule.h
+++ b/tools/lto/LTOModule.h
@@ -32,6 +32,7 @@
     class GlobalValue;
     class Value;
     class Function;
+    class LLVMContext;
 }
 
 
@@ -50,9 +51,12 @@
     static bool              isBitcodeFileForTarget(const char* path, 
                                                     const char* triplePrefix);
 
-    static LTOModule*        makeLTOModule(const char* path, std::string& errMsg);
+    static LTOModule*        makeLTOModule(const char* path,
+                                          llvm::LLVMContext* Context,
+                                          std::string& errMsg);
     static LTOModule*        makeLTOModule(const void* mem, size_t length,
-                                                            std::string& errMsg);
+                                           llvm::LLVMContext* Context,
+                                           std::string& errMsg);
 
     const char*              getTargetTriple();
     uint32_t                 getSymbolCount();
@@ -83,10 +87,11 @@
     bool                    objcClassNameFromExpression(llvm::Constant* c, 
                                                     std::string& name);
 
-    static bool             isTargetMatch(llvm::MemoryBuffer* memBuffer, 
+    static bool             isTargetMatch(llvm::MemoryBuffer* memBuffer,
                                                     const char* triplePrefix);
 
-    static LTOModule*       makeLTOModule(llvm::MemoryBuffer* buffer, 
+    static LTOModule*       makeLTOModule(llvm::MemoryBuffer* buffer,
+                                          llvm::LLVMContext* Context,
                                                         std::string& errMsg);
     static llvm::MemoryBuffer* makeBuffer(const void* mem, size_t length);
 
diff --git a/tools/lto/lto.cpp b/tools/lto/lto.cpp
index a0f67b4..c25f87c 100644
--- a/tools/lto/lto.cpp
+++ b/tools/lto/lto.cpp
@@ -13,6 +13,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm-c/lto.h"
+#include "llvm-c/Core.h"
 
 #include "LTOModule.h"
 #include "LTOCodeGenerator.h"
@@ -85,9 +86,10 @@
 // loads an object file from disk  
 // returns NULL on error (check lto_get_error_message() for details)
 //
-lto_module_t lto_module_create(const char* path)
+lto_module_t lto_module_create(const char* path, LLVMContextRef Ctxt)
 {
-     return LTOModule::makeLTOModule(path, sLastErrorString);
+     return LTOModule::makeLTOModule(path, llvm::unwrap(Ctxt), 
+                                     sLastErrorString);
 }
 
 
@@ -95,9 +97,11 @@
 // loads an object file from memory 
 // returns NULL on error (check lto_get_error_message() for details)
 //
-lto_module_t lto_module_create_from_memory(const void* mem, size_t length)
+lto_module_t lto_module_create_from_memory(const void* mem, size_t length,
+                                           LLVMContextRef Ctxt)
 {
-     return LTOModule::makeLTOModule(mem, length, sLastErrorString);
+     return LTOModule::makeLTOModule(mem, length, llvm::unwrap(Ctxt),
+                                     sLastErrorString);
 }
 
 
diff --git a/tools/opt/opt.cpp b/tools/opt/opt.cpp
index 0c36e21..b469606 100644
--- a/tools/opt/opt.cpp
+++ b/tools/opt/opt.cpp
@@ -12,6 +12,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/ModuleProvider.h"
 #include "llvm/PassManager.h"
@@ -310,6 +311,7 @@
 //
 int main(int argc, char **argv) {
   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
+  LLVMContext Context;
   try {
     cl::ParseCommandLineOptions(argc, argv,
       "llvm .bc -> .bc modular optimizer and analysis printer\n");
@@ -325,7 +327,7 @@
     std::auto_ptr<Module> M;
     if (MemoryBuffer *Buffer
           = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
-      M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
+      M.reset(ParseBitcodeFile(Buffer, &Context, &ErrorMessage));
       delete Buffer;
     }