cd9380d70b5252ae9a81e0514a664f06986aaf6d
[oota-llvm.git] / tools / llvm-link / llvm-link.cpp
1 //===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility may be invoked in the following manner:
11 //  llvm-link a.bc b.bc c.bc -o x.bc
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Linker.h"
16 #include "llvm/Module.h"
17 #include "llvm/Analysis/Verifier.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/Bytecode/Reader.h"
20 #include "llvm/Bytecode/Writer.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Streams.h"
25 #include "llvm/System/Signals.h"
26 #include "llvm/System/Path.h"
27 #include <fstream>
28 #include <iostream>
29 #include <memory>
30 using namespace llvm;
31
32 cl::opt<bool> Bitcode("bitcode");
33
34 static cl::list<std::string>
35 InputFilenames(cl::Positional, cl::OneOrMore,
36                cl::desc("<input bytecode files>"));
37
38 static cl::opt<std::string>
39 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
40                cl::value_desc("filename"));
41
42 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
43
44 static cl::opt<bool>
45 Verbose("v", cl::desc("Print information about actions taken"));
46
47 static cl::opt<bool>
48 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
49
50 static cl::opt<bool> NoCompress("disable-compression", cl::init(true),
51        cl::desc("Don't compress the generated bytecode"));
52
53 // LoadFile - Read the specified bytecode file in and return it.  This routine
54 // searches the link path for the specified file to try to find it...
55 //
56 static inline std::auto_ptr<Module> LoadFile(const std::string &FN) {
57   sys::Path Filename;
58   if (!Filename.set(FN)) {
59     cerr << "Invalid file name: '" << FN << "'\n";
60     return std::auto_ptr<Module>();
61   }
62
63   std::string ErrorMessage;
64   if (Filename.exists()) {
65     if (Verbose) cerr << "Loading '" << Filename.c_str() << "'\n";
66     Module* Result = 0;
67     
68     if (Bitcode) {
69       const std::string &FNStr = Filename.toString();
70       MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(&FNStr[0],
71                                                           FNStr.size());
72       if (Buffer == 0)
73         ErrorMessage = "Error reading file '" + FNStr + "'";
74       else
75         Result = ParseBitcodeFile(Buffer, &ErrorMessage);
76       delete Buffer;
77     } else {
78       Result = ParseBytecodeFile(Filename.toString(), 
79                                  Compressor::decompressToNewBuffer,
80                                  &ErrorMessage);
81     }
82     if (Result) return std::auto_ptr<Module>(Result);   // Load successful!
83
84     if (Verbose) {
85       cerr << "Error opening bytecode file: '" << Filename.c_str() << "'";
86       if (ErrorMessage.size()) cerr << ": " << ErrorMessage;
87       cerr << "\n";
88     }
89   } else {
90     cerr << "Bytecode file: '" << Filename.c_str() << "' does not exist.\n";
91   }
92
93   return std::auto_ptr<Module>();
94 }
95
96 int main(int argc, char **argv) {
97   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
98   cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
99   sys::PrintStackTraceOnErrorSignal();
100   assert(InputFilenames.size() > 0 && "OneOrMore is not working");
101
102   unsigned BaseArg = 0;
103   std::string ErrorMessage;
104
105   std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg]));
106   if (Composite.get() == 0) {
107     cerr << argv[0] << ": error loading file '"
108          << InputFilenames[BaseArg] << "'\n";
109     return 1;
110   }
111
112   for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
113     std::auto_ptr<Module> M(LoadFile(InputFilenames[i]));
114     if (M.get() == 0) {
115       cerr << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n";
116       return 1;
117     }
118
119     if (Verbose) cerr << "Linking in '" << InputFilenames[i] << "'\n";
120
121     if (Linker::LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
122       cerr << argv[0] << ": link error in '" << InputFilenames[i]
123            << "': " << ErrorMessage << "\n";
124       return 1;
125     }
126   }
127
128   // TODO: Iterate over the -l list and link in any modules containing
129   // global symbols that have not been resolved so far.
130
131   if (DumpAsm) cerr << "Here's the assembly:\n" << *Composite.get();
132
133   // FIXME: cout is not binary!
134   std::ostream *Out = &std::cout;  // Default to printing to stdout...
135   if (OutputFilename != "-") {
136     if (!Force && std::ifstream(OutputFilename.c_str())) {
137       // If force is not specified, make sure not to overwrite a file!
138       cerr << argv[0] << ": error opening '" << OutputFilename
139            << "': file exists!\n"
140            << "Use -f command line argument to force output\n";
141       return 1;
142     }
143     std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
144                                  std::ios::binary;
145     Out = new std::ofstream(OutputFilename.c_str(), io_mode);
146     if (!Out->good()) {
147       cerr << argv[0] << ": error opening '" << OutputFilename << "'!\n";
148       return 1;
149     }
150
151     // Make sure that the Out file gets unlinked from the disk if we get a
152     // SIGINT
153     sys::RemoveFileOnSignal(sys::Path(OutputFilename));
154   }
155
156   if (verifyModule(*Composite.get())) {
157     cerr << argv[0] << ": linked module is broken!\n";
158     return 1;
159   }
160
161   if (Verbose) cerr << "Writing bytecode...\n";
162   if (Bitcode) {
163     WriteBitcodeToFile(Composite.get(), *Out);
164   } else {
165     OStream L(*Out);
166     WriteBytecodeToFile(Composite.get(), L, !NoCompress);
167   }
168
169   if (Out != &std::cout) delete Out;
170   return 0;
171 }