Switching TargetMachineRegistry to use the new generic Registry.
[oota-llvm.git] / tools / lto / lto.cpp
index a64130dc7ad730fd6137f4adf7eaab550b281ea9..e7e00e7f62c774727b74ab4192d47599d2810b99 100644 (file)
@@ -7,7 +7,7 @@
 // 
 //===----------------------------------------------------------------------===//
 //
-// This file implementes link time optimization library. This library is 
+// This file implements the Link Time Optimization library. This library is 
 // intended to be used by linker to optimize code at link time.
 //
 //===----------------------------------------------------------------------===//
 #include "llvm/Linker.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
-#include "llvm/SymbolTable.h"
-#include "llvm/Bytecode/Reader.h"
-#include "llvm/Bytecode/Writer.h"
+#include "llvm/ModuleProvider.h"
+#include "llvm/Bitcode/ReaderWriter.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/SystemUtils.h"
 #include "llvm/Support/Mangler.h"
+#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/System/Program.h"
 #include "llvm/System/Signals.h"
 #include "llvm/Analysis/Passes.h"
+#include "llvm/Analysis/LoopPass.h"
 #include "llvm/Analysis/Verifier.h"
+#include "llvm/CodeGen/FileWriters.h"
 #include "llvm/Target/SubtargetFeature.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetMachineRegistry.h"
+#include "llvm/Target/TargetAsmInfo.h"
 #include "llvm/Transforms/IPO.h"
 #include "llvm/Transforms/Scalar.h"
 #include "llvm/Analysis/LoadValueNumbering.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/LinkTimeOptimizer.h"
 #include <fstream>
-#include <iostream>
-
+#include <ostream>
 using namespace llvm;
 
 extern "C"
@@ -48,24 +51,12 @@ llvm::LinkTimeOptimizer *createLLVMOptimizer()
   return l;
 }
 
-
-
 /// If symbol is not used then make it internal and let optimizer takes 
 /// care of it.
 void LLVMSymbol::mayBeNotUsed() { 
   gv->setLinkage(GlobalValue::InternalLinkage); 
 }
 
-// Helper routine
-// FIXME : Take advantage of GlobalPrefix from AsmPrinter
-static const char *addUnderscore(const char *name) {
-  size_t namelen = strlen(name);
-  char *symName = (char*)malloc(namelen+2);
-  symName[0] = '_';
-  strcpy(&symName[1], name);
-  return symName;
-}
-
 // Map LLVM LinkageType to LTO LinakgeType
 static LTOLinkageTypes
 getLTOLinkageType(GlobalValue *v)
@@ -102,7 +93,21 @@ findExternalRefs(Value *value, std::set<std::string> &references,
       findExternalRefs(c->getOperand(i), references, mangler);
 }
 
-/// InputFilename is a LLVM bytecode file. If Module with InputFilename is
+/// If Module with InputFilename is available then remove it from allModules
+/// and call delete on it.
+void
+LTO::removeModule (const std::string &InputFilename)
+{
+  NameToModuleMap::iterator pos = allModules.find(InputFilename.c_str());
+  if (pos == allModules.end()) 
+    return;
+
+  Module *m = pos->second;
+  allModules.erase(pos);
+  delete m;
+}
+
+/// InputFilename is a LLVM bitcode file. If Module with InputFilename is
 /// available then return it. Otherwise parseInputFilename.
 Module *
 LTO::getModule(const std::string &InputFilename)
@@ -113,50 +118,61 @@ LTO::getModule(const std::string &InputFilename)
   if (pos != allModules.end())
     m = allModules[InputFilename.c_str()];
   else {
-    m = ParseBytecodeFile(InputFilename);
+    if (MemoryBuffer *Buffer
+        = MemoryBuffer::getFile(&InputFilename[0], InputFilename.size())) {
+      m = ParseBitcodeFile(Buffer);
+      delete Buffer;
+    }
     allModules[InputFilename.c_str()] = m;
   }
   return m;
 }
 
-/// InputFilename is a LLVM bytecode file. Reade this bytecode file and 
+/// InputFilename is a LLVM bitcode file. Reade this bitcode file and 
 /// set corresponding target triplet string.
 void
 LTO::getTargetTriple(const std::string &InputFilename, 
-                                  std::string &targetTriple)
+                     std::string &targetTriple)
 {
   Module *m = getModule(InputFilename);
   if (m)
     targetTriple = m->getTargetTriple();
 }
 
-/// InputFilename is a LLVM bytecode file. Read it using bytecode reader.
+/// InputFilename is a LLVM bitcode file. Read it using bitcode reader.
 /// Collect global functions and symbol names in symbols vector.
 /// Collect external references in references vector.
 /// Return LTO_READ_SUCCESS if there is no error.
 enum LTOStatus
 LTO::readLLVMObjectFile(const std::string &InputFilename,
-                                      NameToSymbolMap &symbols,
-                                      std::set<std::string> &references)
+                        NameToSymbolMap &symbols,
+                        std::set<std::string> &references)
 {
   Module *m = getModule(InputFilename);
   if (!m)
     return LTO_READ_FAILURE;
 
+  // Collect Target info
+  getTarget(m);
+
+  if (!Target)
+    return LTO_READ_FAILURE;
+  
   // Use mangler to add GlobalPrefix to names to match linker names.
   // FIXME : Instead of hard coding "-" use GlobalPrefix.
-  Mangler mangler(*m, "_");
-  
+  Mangler mangler(*m, Target->getTargetAsmInfo()->getGlobalPrefix());
   modules.push_back(m);
   
   for (Module::iterator f = m->begin(), e = m->end(); f != e; ++f) {
 
     LTOLinkageTypes lt = getLTOLinkageType(f);
 
-    if (!f->isExternal() && lt != LTOInternalLinkage
+    if (!f->isDeclaration() && lt != LTOInternalLinkage
         && strncmp (f->getName().c_str(), "llvm.", 5)) {
+      int alignment = ( 16 > f->getAlignment() ? 16 : f->getAlignment());
       LLVMSymbol *newSymbol = new LLVMSymbol(lt, f, f->getName(), 
-                                             mangler.getValueName(f));
+                                             mangler.getValueName(f),
+                                             Log2_32(alignment));
       symbols[newSymbol->getMangledName()] = newSymbol;
       allSymbols[newSymbol->getMangledName()] = newSymbol;
     }
@@ -173,10 +189,12 @@ LTO::readLLVMObjectFile(const std::string &InputFilename,
   for (Module::global_iterator v = m->global_begin(), e = m->global_end();
        v !=  e; ++v) {
     LTOLinkageTypes lt = getLTOLinkageType(v);
-    if (!v->isExternal() && lt != LTOInternalLinkage
+    if (!v->isDeclaration() && lt != LTOInternalLinkage
         && strncmp (v->getName().c_str(), "llvm.", 5)) {
+      const TargetData *TD = Target->getTargetData();
       LLVMSymbol *newSymbol = new LLVMSymbol(lt, v, v->getName(), 
-                                             mangler.getValueName(v));
+                                             mangler.getValueName(v),
+                                             TD->getPreferredAlignmentLog(v));
       symbols[newSymbol->getMangledName()] = newSymbol;
       allSymbols[newSymbol->getMangledName()] = newSymbol;
 
@@ -190,43 +208,48 @@ LTO::readLLVMObjectFile(const std::string &InputFilename,
   return LTO_READ_SUCCESS;
 }
 
+/// Get TargetMachine.
+/// Use module M to find appropriate Target.
+void
+LTO::getTarget (Module *M) {
+
+  if (Target)
+    return;
+
+  std::string Err;
+  const TargetMachineRegistry::entry* March = 
+    TargetMachineRegistry::getClosestStaticTargetForModule(*M, Err);
+  
+  if (March == 0)
+    return;
+  
+  // Create target
+  std::string Features;
+  Target = March->CtorFn(*M, Features);
+}
+
 /// Optimize module M using various IPO passes. Use exportList to 
 /// internalize selected symbols. Target platform is selected
 /// based on information available to module M. No new target
 /// features are selected. 
-static enum LTOStatus lto_optimize(Module *M, std::ostream &Out,
-                                   std::vector<const char *> &exportList)
+enum LTOStatus 
+LTO::optimize(Module *M, std::ostream &Out,
+              std::vector<const char *> &exportList)
 {
   // Instantiate the pass manager to organize the passes.
   PassManager Passes;
   
   // Collect Target info
-  std::string Err;
-  const TargetMachineRegistry::Entry* March = 
-    TargetMachineRegistry::getClosestStaticTargetForModule(*M, Err);
-  
-  if (March == 0)
-    return LTO_NO_TARGET;
-  
-  // Create target
-  std::string Features;
-  std::auto_ptr<TargetMachine> target(March->CtorFn(*M, Features));
-  if (!target.get())
+  getTarget(M);
+
+  if (!Target)
     return LTO_NO_TARGET;
   
-  TargetMachine &Target = *target.get();
-  
   // Start off with a verification pass.
   Passes.add(createVerifierPass());
   
   // Add an appropriate TargetData instance for this module...
-  Passes.add(new TargetData(*Target.getTargetData()));
-  
-  // Often if the programmer does not specify proper prototypes for the
-  // functions they are calling, they end up calling a vararg version of the
-  // function that does not get a body filled in (the real function has typed
-  // arguments).  This pass merges the two functions.
-  Passes.add(createFunctionResolvingPass());
+  Passes.add(new TargetData(*Target->getTargetData()));
   
   // Internalize symbols if export list is nonemty
   if (!exportList.empty())
@@ -288,9 +311,27 @@ static enum LTOStatus lto_optimize(Module *M, std::ostream &Out,
   FunctionPassManager *CodeGenPasses =
     new FunctionPassManager(new ExistingModuleProvider(M));
 
-  CodeGenPasses->add(new TargetData(*Target.getTargetData()));
-  Target.addPassesToEmitFile(*CodeGenPasses, Out, TargetMachine::AssemblyFile, 
-                            true);
+  CodeGenPasses->add(new TargetData(*Target->getTargetData()));
+
+  MachineCodeEmitter *MCE = 0;
+
+  switch (Target->addPassesToEmitFile(*CodeGenPasses, Out,
+                                      TargetMachine::AssemblyFile, true)) {
+  default:
+  case FileModel::Error:
+    return LTO_WRITE_FAILURE;
+  case FileModel::AsmFile:
+    break;
+  case FileModel::MachOFile:
+    MCE = AddMachOWriter(*CodeGenPasses, Out, *Target);
+    break;
+  case FileModel::ElfFile:
+    MCE = AddELFWriter(*CodeGenPasses, Out, *Target);
+    break;
+  }
+
+  if (Target->addPassesToEmitFileFinish(*CodeGenPasses, MCE, true))
+    return LTO_WRITE_FAILURE;
 
   // Run our queue of passes all at once now, efficiently.
   Passes.run(*M);
@@ -298,7 +339,7 @@ static enum LTOStatus lto_optimize(Module *M, std::ostream &Out,
   // Run the code generator, if present.
   CodeGenPasses->doInitialization();
   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
-    if (!I->isExternal())
+    if (!I->isDeclaration())
       CodeGenPasses->run(*I);
   }
   CodeGenPasses->doFinalization();
@@ -311,8 +352,10 @@ static enum LTOStatus lto_optimize(Module *M, std::ostream &Out,
 /// Return appropriate LTOStatus.
 enum LTOStatus
 LTO::optimizeModules(const std::string &OutputFilename,
-                                   std::vector<const char *> &exportList,
-                                   std::string &targetTriple)
+                     std::vector<const char *> &exportList,
+                     std::string &targetTriple,
+                     bool saveTemps,
+                     const char *FinalOutputFilename)
 {
   if (modules.empty())
     return LTO_NO_WORK;
@@ -325,12 +368,18 @@ LTO::optimizeModules(const std::string &OutputFilename,
   for (unsigned i = 1, e = modules.size(); i != e; ++i)
     if (theLinker.LinkModules(bigOne, modules[i], errMsg))
       return LTO_MODULE_MERGE_FAILURE;
+  //  all modules have been handed off to the linker.
+  modules.clear();
+
+  sys::Path FinalOutputPath(FinalOutputFilename);
+  FinalOutputPath.eraseSuffix();
 
-#if 0
-  // Enable this when -save-temps is used
-  std::ofstream Out("big.bc", io_mode);
-  WriteBytecodeToFile(bigOne, Out, true);
-#endif
+  if (saveTemps) {
+    std::string tempFileName(FinalOutputPath.c_str());
+    tempFileName += "0.bc";
+    std::ofstream Out(tempFileName.c_str(), io_mode);
+    WriteBitcodeToFile(bigOne, Out);
+  }
 
   // Strip leading underscore because it was added to match names
   // seen by linker.
@@ -345,17 +394,17 @@ LTO::optimizeModules(const std::string &OutputFilename,
   std::string ErrMsg;
   sys::Path TempDir = sys::Path::GetTemporaryDirectory(&ErrMsg);
   if (TempDir.isEmpty()) {
-    std::cerr << "lto: " << ErrMsg << "\n";
+    cerr << "lto: " << ErrMsg << "\n";
     return LTO_WRITE_FAILURE;
   }
   sys::Path tmpAsmFilePath(TempDir);
   if (!tmpAsmFilePath.appendComponent("lto")) {
-    std::cerr << "lto: " << ErrMsg << "\n";
+    cerr << "lto: " << ErrMsg << "\n";
     TempDir.eraseFromDisk(true);
     return LTO_WRITE_FAILURE;
   }
-  if (tmpAsmFilePath.createTemporaryFileOnDisk(&ErrMsg)) {
-    std::cerr << "lto: " << ErrMsg << "\n";
+  if (tmpAsmFilePath.createTemporaryFileOnDisk(true, &ErrMsg)) {
+    cerr << "lto: " << ErrMsg << "\n";
     TempDir.eraseFromDisk(true);
     return LTO_WRITE_FAILURE;
   }
@@ -370,7 +419,7 @@ LTO::optimizeModules(const std::string &OutputFilename,
     return LTO_WRITE_FAILURE;
   }
 
-  enum LTOStatus status = lto_optimize(bigOne, asmFile, exportList);
+  enum LTOStatus status = optimize(bigOne, asmFile, exportList);
   asmFile.close();
   if (status != LTO_OPT_SUCCESS) {
     tmpAsmFilePath.eraseFromDisk();
@@ -378,6 +427,13 @@ LTO::optimizeModules(const std::string &OutputFilename,
     return status;
   }
 
+  if (saveTemps) {
+    std::string tempFileName(FinalOutputPath.c_str());
+    tempFileName += "1.bc";
+    std::ofstream Out(tempFileName.c_str(), io_mode);
+    WriteBitcodeToFile(bigOne, Out);
+  }
+
   targetTriple = bigOne->getTargetTriple();
 
   // Run GCC to assemble and link the program into native code.
@@ -386,7 +442,7 @@ LTO::optimizeModules(const std::string &OutputFilename,
   //  We can't just assemble and link the file with the system assembler
   //  and linker because we don't know where to put the _start symbol.
   //  GCC mysteriously knows how to do it.
-  const sys::Path gcc = FindExecutable("gcc", "/");
+  const sys::Path gcc = sys::Program::FindProgramByName("gcc");
   if (gcc.isEmpty()) {
     tmpAsmFilePath.eraseFromDisk();
     TempDir.eraseFromDisk(true);
@@ -403,8 +459,8 @@ LTO::optimizeModules(const std::string &OutputFilename,
   args.push_back(tmpAsmFilePath.c_str());
   args.push_back(0);
 
-  if (sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 1, &ErrMsg)) {
-    std::cerr << "lto: " << ErrMsg << "\n";
+  if (sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 1, 0, &ErrMsg)) {
+    cerr << "lto: " << ErrMsg << "\n";
     return LTO_ASM_FAILURE;
   }
 
@@ -413,3 +469,28 @@ LTO::optimizeModules(const std::string &OutputFilename,
 
   return LTO_OPT_SUCCESS;
 }
+
+void LTO::printVersion() {
+    cl::PrintVersionMessage();
+}
+
+/// Unused pure-virtual destructor. Must remain empty.
+LinkTimeOptimizer::~LinkTimeOptimizer() {}
+
+/// Destruct LTO. Delete all modules, symbols and target.
+LTO::~LTO() {
+  
+  for (std::vector<Module *>::iterator itr = modules.begin(), e = modules.end();
+       itr != e; ++itr)
+    delete *itr;
+
+  modules.clear();
+
+  for (NameToSymbolMap::iterator itr = allSymbols.begin(), e = allSymbols.end(); 
+       itr != e; ++itr)
+    delete itr->second;
+
+  allSymbols.clear();
+
+  delete Target;
+}