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/lib/Archive/Archive.cpp b/lib/Archive/Archive.cpp
index c6c89d2..e6903b6 100644
--- a/lib/Archive/Archive.cpp
+++ b/lib/Archive/Archive.cpp
@@ -138,9 +138,9 @@
 // Archive constructor - this is the only constructor that gets used for the
 // Archive class. Everything else (default,copy) is deprecated. This just
 // initializes and maps the file into memory, if requested.
-Archive::Archive(const sys::Path& filename)
+Archive::Archive(const sys::Path& filename, LLVMContext* C)
   : archPath(filename), members(), mapfile(0), base(0), symTab(), strtab(),
-    symTabSize(0), firstFileOffset(0), modules(), foreignST(0) {
+    symTabSize(0), firstFileOffset(0), modules(), foreignST(0), Context(C) {
 }
 
 bool
@@ -208,6 +208,7 @@
 
 // Get just the externally visible defined symbols from the bitcode
 bool llvm::GetBitcodeSymbols(const sys::Path& fName,
+                             LLVMContext* Context,
                              std::vector<std::string>& symbols,
                              std::string* ErrMsg) {
   std::auto_ptr<MemoryBuffer> Buffer(
@@ -217,7 +218,7 @@
     return true;
   }
   
-  ModuleProvider *MP = getBitcodeModuleProvider(Buffer.get(), ErrMsg);
+  ModuleProvider *MP = getBitcodeModuleProvider(Buffer.get(), Context, ErrMsg);
   if (!MP)
     return true;
   
@@ -239,13 +240,14 @@
 ModuleProvider*
 llvm::GetBitcodeSymbols(const unsigned char *BufPtr, unsigned Length,
                         const std::string& ModuleID,
+                        LLVMContext* Context,
                         std::vector<std::string>& symbols,
                         std::string* ErrMsg) {
   // Get the module provider
   MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(Length, ModuleID.c_str());
   memcpy((char*)Buffer->getBufferStart(), BufPtr, Length);
   
-  ModuleProvider *MP = getBitcodeModuleProvider(Buffer, ErrMsg);
+  ModuleProvider *MP = getBitcodeModuleProvider(Buffer, Context, ErrMsg);
   if (!MP)
     return 0;
   
diff --git a/lib/Archive/ArchiveInternals.h b/lib/Archive/ArchiveInternals.h
index 7ba3024..cdd8e35 100644
--- a/lib/Archive/ArchiveInternals.h
+++ b/lib/Archive/ArchiveInternals.h
@@ -31,6 +31,8 @@
 
 namespace llvm {
 
+  class LLVMContext;
+
   /// The ArchiveMemberHeader structure is used internally for bitcode
   /// archives.
   /// The header precedes each file member in the archive. This structure is
@@ -71,11 +73,13 @@
   
   // Get just the externally visible defined symbols from the bitcode
   bool GetBitcodeSymbols(const sys::Path& fName,
+                          LLVMContext* Context,
                           std::vector<std::string>& symbols,
                           std::string* ErrMsg);
   
   ModuleProvider* GetBitcodeSymbols(const unsigned char*Buffer,unsigned Length,
                                     const std::string& ModuleID,
+                                    LLVMContext* Context,
                                     std::vector<std::string>& symbols,
                                     std::string* ErrMsg);
 }
diff --git a/lib/Archive/ArchiveReader.cpp b/lib/Archive/ArchiveReader.cpp
index b07e884..4e3e281 100644
--- a/lib/Archive/ArchiveReader.cpp
+++ b/lib/Archive/ArchiveReader.cpp
@@ -327,9 +327,9 @@
 
 // Open and completely load the archive file.
 Archive*
-Archive::OpenAndLoad(const sys::Path& file, std::string* ErrorMessage) 
-{
-  std::auto_ptr<Archive> result ( new Archive(file));
+Archive::OpenAndLoad(const sys::Path& file, LLVMContext* C, 
+                     std::string* ErrorMessage) {
+  std::auto_ptr<Archive> result ( new Archive(file, C));
   if (result->mapToMemory(ErrorMessage))
     return 0;
   if (!result->loadArchive(ErrorMessage))
@@ -339,7 +339,8 @@
 
 // Get all the bitcode modules from the archive
 bool
-Archive::getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage) {
+Archive::getAllModules(std::vector<Module*>& Modules,
+                       std::string* ErrMessage) {
 
   for (iterator I=begin(), E=end(); I != E; ++I) {
     if (I->isBitcode()) {
@@ -349,7 +350,7 @@
         MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
       memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
       
-      Module *M = ParseBitcodeFile(Buffer, ErrMessage);
+      Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage);
       delete Buffer;
       if (!M)
         return true;
@@ -440,9 +441,9 @@
 }
 
 // Open the archive and load just the symbol tables
-Archive*
-Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
-  std::auto_ptr<Archive> result ( new Archive(file) );
+Archive* Archive::OpenAndLoadSymbols(const sys::Path& file, LLVMContext* C,
+                                     std::string* ErrorMessage) {
+  std::auto_ptr<Archive> result ( new Archive(file, C) );
   if (result->mapToMemory(ErrorMessage))
     return 0;
   if (!result->loadSymbolTable(ErrorMessage))
@@ -488,7 +489,7 @@
                                                       FullMemberName.c_str());
   memcpy((char*)Buffer->getBufferStart(), mbr->getData(), mbr->getSize());
   
-  ModuleProvider *mp = getBitcodeModuleProvider(Buffer, ErrMsg);
+  ModuleProvider *mp = getBitcodeModuleProvider(Buffer, Context, ErrMsg);
   if (!mp)
     return 0;
 
@@ -536,7 +537,7 @@
           mbr->getPath().toString() + ")";
         ModuleProvider* MP = 
           GetBitcodeSymbols((const unsigned char*)At, mbr->getSize(),
-                            FullMemberName, symbols, error);
+                            FullMemberName, Context, symbols, error);
 
         if (MP) {
           // Insert the module's symbols into the symbol table
@@ -615,7 +616,7 @@
     MemoryBuffer *Buffer =
       MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
     memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
-    Module *M = ParseBitcodeFile(Buffer);
+    Module *M = ParseBitcodeFile(Buffer, Context);
     delete Buffer;
     if (!M)
       return false;  // Couldn't parse bitcode, not a bitcode archive.
diff --git a/lib/Archive/ArchiveWriter.cpp b/lib/Archive/ArchiveWriter.cpp
index cebb087..641e332 100644
--- a/lib/Archive/ArchiveWriter.cpp
+++ b/lib/Archive/ArchiveWriter.cpp
@@ -64,9 +64,8 @@
 }
 
 // Create an empty archive.
-Archive*
-Archive::CreateEmpty(const sys::Path& FilePath ) {
-  Archive* result = new Archive(FilePath);
+Archive* Archive::CreateEmpty(const sys::Path& FilePath, LLVMContext* C) {
+  Archive* result = new Archive(FilePath, C);
   return result;
 }
 
@@ -229,7 +228,7 @@
       + ")";
     ModuleProvider* MP = 
       GetBitcodeSymbols((const unsigned char*)data,fSize,
-                        FullMemberName, symbols, ErrMsg);
+                        FullMemberName, Context, symbols, ErrMsg);
 
     // If the bitcode parsed successfully
     if ( MP ) {
diff --git a/lib/AsmParser/Parser.cpp b/lib/AsmParser/Parser.cpp
index 759e00e..7759c70 100644
--- a/lib/AsmParser/Parser.cpp
+++ b/lib/AsmParser/Parser.cpp
@@ -20,7 +20,8 @@
 #include <cstring>
 using namespace llvm;
 
-Module *llvm::ParseAssemblyFile(const std::string &Filename, ParseError &Err) {
+Module *llvm::ParseAssemblyFile(const std::string &Filename, ParseError &Err,
+                                LLVMContext* Context) {
   Err.setFilename(Filename);
 
   std::string ErrorStr;
@@ -31,14 +32,14 @@
     return 0;
   }
 
-  OwningPtr<Module> M(new Module(Filename));
+  OwningPtr<Module> M(new Module(Filename, Context));
   if (LLParser(F.get(), Err, M.get()).Run())
     return 0;
   return M.take();
 }
 
 Module *llvm::ParseAssemblyString(const char *AsmString, Module *M,
-                                  ParseError &Err) {
+                                  ParseError &Err, LLVMContext* Context) {
   Err.setFilename("<string>");
 
   OwningPtr<MemoryBuffer>
@@ -50,7 +51,7 @@
     return LLParser(F.get(), Err, M).Run() ? 0 : M;
 
   // Otherwise create a new module.
-  OwningPtr<Module> M2(new Module("<string>"));
+  OwningPtr<Module> M2(new Module("<string>", Context));
   if (LLParser(F.get(), Err, M2.get()).Run())
     return 0;
   return M2.take();
diff --git a/lib/Bitcode/Reader/BitReader.cpp b/lib/Bitcode/Reader/BitReader.cpp
index 52851cd..2baf71b 100644
--- a/lib/Bitcode/Reader/BitReader.cpp
+++ b/lib/Bitcode/Reader/BitReader.cpp
@@ -18,11 +18,12 @@
 /* Builds a module from the bitcode in the specified memory buffer, returning a
    reference to the module via the OutModule parameter. Returns 0 on success.
    Optionally returns a human-readable error message via OutMessage. */ 
-int LLVMParseBitcode(LLVMMemoryBufferRef MemBuf,
+int LLVMParseBitcode(LLVMMemoryBufferRef MemBuf, LLVMContextRef ContextRef,
                      LLVMModuleRef *OutModule, char **OutMessage) {
   std::string Message;
   
-  *OutModule = wrap(ParseBitcodeFile(unwrap(MemBuf), &Message));
+  *OutModule = wrap(ParseBitcodeFile(unwrap(MemBuf), unwrap(ContextRef),  
+                                     &Message));
   if (!*OutModule) {
     if (OutMessage)
       *OutMessage = strdup(Message.c_str());
@@ -36,11 +37,13 @@
    a module provider which performs lazy deserialization. Returns 0 on success.
    Optionally returns a human-readable error message via OutMessage. */ 
 int LLVMGetBitcodeModuleProvider(LLVMMemoryBufferRef MemBuf,
+                                 LLVMContextRef ContextRef,
                                  LLVMModuleProviderRef *OutMP,
                                  char **OutMessage) {
   std::string Message;
   
-  *OutMP = wrap(getBitcodeModuleProvider(unwrap(MemBuf), &Message));
+  *OutMP = wrap(getBitcodeModuleProvider(unwrap(MemBuf), unwrap(ContextRef), 
+                                         &Message));
   if (!*OutMP) {
     if (OutMessage)
       *OutMessage = strdup(Message.c_str());
diff --git a/lib/Bitcode/Reader/BitcodeReader.cpp b/lib/Bitcode/Reader/BitcodeReader.cpp
index 6b9606c..7cf0324 100644
--- a/lib/Bitcode/Reader/BitcodeReader.cpp
+++ b/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1087,7 +1087,7 @@
     return Error("Malformed block record");
 
   // Otherwise, create the module.
-  TheModule = new Module(ModuleID);
+  TheModule = new Module(ModuleID, Context);
   
   SmallVector<uint64_t, 64> Record;
   std::vector<std::string> SectionTable;
@@ -2090,8 +2090,9 @@
 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
 ///
 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
+                                               LLVMContext* Context,
                                                std::string *ErrMsg) {
-  BitcodeReader *R = new BitcodeReader(Buffer);
+  BitcodeReader *R = new BitcodeReader(Buffer, Context);
   if (R->ParseBitcode()) {
     if (ErrMsg)
       *ErrMsg = R->getErrorString();
@@ -2106,9 +2107,11 @@
 
 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
 /// If an error occurs, return null and fill in *ErrMsg if non-null.
-Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
+Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext* Context, 
+                               std::string *ErrMsg){
   BitcodeReader *R;
-  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
+  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context, 
+                                                           ErrMsg));
   if (!R) return 0;
   
   // Read in the entire module.
diff --git a/lib/Bitcode/Reader/BitcodeReader.h b/lib/Bitcode/Reader/BitcodeReader.h
index 0dc470b..498a34a 100644
--- a/lib/Bitcode/Reader/BitcodeReader.h
+++ b/lib/Bitcode/Reader/BitcodeReader.h
@@ -26,6 +26,7 @@
 
 namespace llvm {
   class MemoryBuffer;
+  class LLVMContext;
   
 //===----------------------------------------------------------------------===//
 //                          BitcodeReaderValueList Class
@@ -85,6 +86,7 @@
 };
 
 class BitcodeReader : public ModuleProvider {
+  LLVMContext* Context;
   MemoryBuffer *Buffer;
   BitstreamReader StreamFile;
   BitstreamCursor Stream;
@@ -123,8 +125,8 @@
   /// stream) and what linkage the original function had.
   DenseMap<Function*, std::pair<uint64_t, unsigned> > DeferredFunctionInfo;
 public:
-  explicit BitcodeReader(MemoryBuffer *buffer)
-      : Buffer(buffer), ErrorString(0) {
+  explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext* C)
+      : Context(C), Buffer(buffer), ErrorString(0) {
     HasReversedFunctionsWithBodies = false;
   }
   ~BitcodeReader() {
diff --git a/lib/Debugger/Debugger.cpp b/lib/Debugger/Debugger.cpp
index b12d90a..dbfbbed 100644
--- a/lib/Debugger/Debugger.cpp
+++ b/lib/Debugger/Debugger.cpp
@@ -46,11 +46,11 @@
 }
 
 static Module *
-getMaterializedModuleProvider(const std::string &Filename) {
+getMaterializedModuleProvider(const std::string &Filename, LLVMContext* C) {
   std::auto_ptr<MemoryBuffer> Buffer;
   Buffer.reset(MemoryBuffer::getFileOrSTDIN(Filename.c_str()));
   if (Buffer.get())
-    return ParseBitcodeFile(Buffer.get());
+    return ParseBitcodeFile(Buffer.get(), C);
   return 0;
 }
 
@@ -58,9 +58,9 @@
 /// the PATH for the specified program, loading it when found.  If the
 /// specified program cannot be found, an exception is thrown to indicate the
 /// error.
-void Debugger::loadProgram(const std::string &Filename) {
-  if ((Program = getMaterializedModuleProvider(Filename)) ||
-      (Program = getMaterializedModuleProvider(Filename+".bc")))
+void Debugger::loadProgram(const std::string &Filename, LLVMContext* C) {
+  if ((Program = getMaterializedModuleProvider(Filename, C)) ||
+      (Program = getMaterializedModuleProvider(Filename+".bc", C)))
     return;   // Successfully loaded the program.
 
   // Search the program path for the file...
@@ -69,9 +69,9 @@
 
     std::string Directory = getToken(Path, ":");
     while (!Directory.empty()) {
-      if ((Program = getMaterializedModuleProvider(Directory +"/"+ Filename)) ||
-          (Program = getMaterializedModuleProvider(Directory +"/"+ Filename
-                                                                      + ".bc")))
+      if ((Program = getMaterializedModuleProvider(Directory +"/"+ Filename, C))
+       || (Program = getMaterializedModuleProvider(Directory +"/"+ Filename
+                                                                   + ".bc", C)))
         return;   // Successfully loaded the program.
 
       Directory = getToken(Path, ":");
diff --git a/lib/Linker/LinkArchives.cpp b/lib/Linker/LinkArchives.cpp
index 551cc8c..faf01af 100644
--- a/lib/Linker/LinkArchives.cpp
+++ b/lib/Linker/LinkArchives.cpp
@@ -115,7 +115,7 @@
 
   std::string ErrMsg;
   std::auto_ptr<Archive> AutoArch (
-    Archive::OpenAndLoadSymbols(Filename,&ErrMsg));
+    Archive::OpenAndLoadSymbols(Filename, Context, &ErrMsg));
 
   Archive* arch = AutoArch.get();
 
diff --git a/lib/Linker/LinkItems.cpp b/lib/Linker/LinkItems.cpp
index 7c888aa..dc0f7c1 100644
--- a/lib/Linker/LinkItems.cpp
+++ b/lib/Linker/LinkItems.cpp
@@ -160,7 +160,7 @@
   if (File.toString() == "-") {
     std::auto_ptr<Module> M;
     if (MemoryBuffer *Buffer = MemoryBuffer::getSTDIN()) {
-      M.reset(ParseBitcodeFile(Buffer, &Error));
+      M.reset(ParseBitcodeFile(Buffer, Context, &Error));
       delete Buffer;
       if (M.get())
         if (!LinkInModule(M.get(), &Error))
diff --git a/lib/Linker/Linker.cpp b/lib/Linker/Linker.cpp
index d673772..d0d69d0 100644
--- a/lib/Linker/Linker.cpp
+++ b/lib/Linker/Linker.cpp
@@ -20,24 +20,21 @@
 using namespace llvm;
 
 Linker::Linker(const std::string& progname, const std::string& modname,
-               unsigned flags)
-  : Composite(0)
-  , LibPaths()
-  , Flags(flags)
-  , Error()
-  , ProgramName(progname)
-{
-  Composite = new Module(modname);
-}
+               LLVMContext* C, unsigned flags): 
+  Context(C),
+  Composite(new Module(modname, C)),
+  LibPaths(),
+  Flags(flags),
+  Error(),
+  ProgramName(progname) { }
 
-Linker::Linker(const std::string& progname, Module* aModule, unsigned flags)
-  : Composite(aModule)
-  , LibPaths()
-  , Flags(flags)
-  , Error()
-  , ProgramName(progname)
-{
-}
+Linker::Linker(const std::string& progname, Module* aModule, unsigned flags) : 
+  Context(aModule->getContext()),
+  Composite(aModule),
+  LibPaths(),
+  Flags(flags),
+  Error(),
+  ProgramName(progname) { }
 
 Linker::~Linker() {
   delete Composite;
@@ -106,7 +103,7 @@
   const std::string &FNS = FN.toString();
   std::auto_ptr<MemoryBuffer> Buffer(MemoryBuffer::getFileOrSTDIN(FNS.c_str()));
   if (Buffer.get())
-    Result = ParseBitcodeFile(Buffer.get(), &ParseErrorMessage);
+    Result = ParseBitcodeFile(Buffer.get(), Context, &ParseErrorMessage);
   else
     ParseErrorMessage = "Error reading file '" + FNS + "'";
     
diff --git a/lib/Transforms/Utils/CloneModule.cpp b/lib/Transforms/Utils/CloneModule.cpp
index 337fa8a..82f5b93 100644
--- a/lib/Transforms/Utils/CloneModule.cpp
+++ b/lib/Transforms/Utils/CloneModule.cpp
@@ -35,7 +35,7 @@
 Module *llvm::CloneModule(const Module *M,
                           DenseMap<const Value*, Value*> &ValueMap) {
   // First off, we need to create the new module...
-  Module *New = new Module(M->getModuleIdentifier());
+  Module *New = new Module(M->getModuleIdentifier(), M->getContext());
   New->setDataLayout(M->getDataLayout());
   New->setTargetTriple(M->getTargetTriple());
   New->setModuleInlineAsm(M->getModuleInlineAsm());
diff --git a/lib/VMCore/Core.cpp b/lib/VMCore/Core.cpp
index f85dbe7..1c0a8f7 100644
--- a/lib/VMCore/Core.cpp
+++ b/lib/VMCore/Core.cpp
@@ -18,6 +18,7 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/GlobalVariable.h"
 #include "llvm/GlobalAlias.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/TypeSymbolTable.h"
 #include "llvm/ModuleProvider.h"
 #include "llvm/InlineAsm.h"
@@ -38,10 +39,21 @@
 }
 
 
+/*===-- Operations on contexts --------------------------------------------===*/
+
+LLVMContextRef LLVMContextCreate() {
+  return wrap(new LLVMContext());
+}
+
+void LLVMContextDispose(LLVMContextRef C) {
+  delete unwrap(C);
+}
+
+
 /*===-- Operations on modules ---------------------------------------------===*/
 
-LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID) {
-  return wrap(new Module(ModuleID));
+LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID, LLVMContextRef C) {
+  return wrap(new Module(ModuleID, unwrap(C)));
 }
 
 void LLVMDisposeModule(LLVMModuleRef M) {
diff --git a/lib/VMCore/Module.cpp b/lib/VMCore/Module.cpp
index a598005..96a25a5 100644
--- a/lib/VMCore/Module.cpp
+++ b/lib/VMCore/Module.cpp
@@ -15,6 +15,7 @@
 #include "llvm/InstrTypes.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/LeakDetector.h"
@@ -54,8 +55,8 @@
 // Primitive Module methods.
 //
 
-Module::Module(const std::string &MID)
-  : ModuleID(MID), DataLayout("") {
+Module::Module(const std::string &MID, LLVMContext* C)
+  : Context(C), ModuleID(MID), DataLayout("")  {
   ValSymTab = new ValueSymbolTable();
   TypeSymTab = new TypeSymbolTable();
 }