Add a Force option to raw_fd_ostream to specify whether opening
[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 is distributed under the University of Illinois Open Source
6 // 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/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/Analysis/Verifier.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/PrettyStackTrace.h"
24 #include "llvm/Support/Streams.h"
25 #include "llvm/System/Signals.h"
26 #include "llvm/System/Path.h"
27 #include <memory>
28 using namespace llvm;
29
30 static cl::list<std::string>
31 InputFilenames(cl::Positional, cl::OneOrMore,
32                cl::desc("<input bitcode files>"));
33
34 static cl::opt<std::string>
35 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
36                cl::value_desc("filename"));
37
38 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
39
40 static cl::opt<bool>
41 Verbose("v", cl::desc("Print information about actions taken"));
42
43 static cl::opt<bool>
44 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
45
46 // LoadFile - Read the specified bitcode file in and return it.  This routine
47 // searches the link path for the specified file to try to find it...
48 //
49 static inline std::auto_ptr<Module> LoadFile(const std::string &FN, 
50                                              LLVMContext& Context) {
51   sys::Path Filename;
52   if (!Filename.set(FN)) {
53     cerr << "Invalid file name: '" << FN << "'\n";
54     return std::auto_ptr<Module>();
55   }
56
57   std::string ErrorMessage;
58   if (Filename.exists()) {
59     if (Verbose) cerr << "Loading '" << Filename.c_str() << "'\n";
60     Module* Result = 0;
61     
62     const std::string &FNStr = Filename.toString();
63     if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(FNStr,
64                                                             &ErrorMessage)) {
65       Result = ParseBitcodeFile(Buffer, Context, &ErrorMessage);
66       delete Buffer;
67     }
68     if (Result) return std::auto_ptr<Module>(Result);   // Load successful!
69
70     if (Verbose) {
71       cerr << "Error opening bitcode file: '" << Filename.c_str() << "'";
72       if (ErrorMessage.size()) cerr << ": " << ErrorMessage;
73       cerr << "\n";
74     }
75   } else {
76     cerr << "Bitcode file: '" << Filename.c_str() << "' does not exist.\n";
77   }
78
79   return std::auto_ptr<Module>();
80 }
81
82 int main(int argc, char **argv) {
83   // Print a stack trace if we signal out.
84   sys::PrintStackTraceOnErrorSignal();
85   PrettyStackTraceProgram X(argc, argv);
86   
87   LLVMContext Context;
88   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
89   cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
90
91   unsigned BaseArg = 0;
92   std::string ErrorMessage;
93
94   std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg], Context));
95   if (Composite.get() == 0) {
96     cerr << argv[0] << ": error loading file '"
97          << InputFilenames[BaseArg] << "'\n";
98     return 1;
99   }
100
101   for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
102     std::auto_ptr<Module> M(LoadFile(InputFilenames[i], Context));
103     if (M.get() == 0) {
104       cerr << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n";
105       return 1;
106     }
107
108     if (Verbose) cerr << "Linking in '" << InputFilenames[i] << "'\n";
109
110     if (Linker::LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
111       cerr << argv[0] << ": link error in '" << InputFilenames[i]
112            << "': " << ErrorMessage << "\n";
113       return 1;
114     }
115   }
116
117   // TODO: Iterate over the -l list and link in any modules containing
118   // global symbols that have not been resolved so far.
119
120   if (DumpAsm) cerr << "Here's the assembly:\n" << *Composite.get();
121
122   // FIXME: cout is not binary!
123   raw_ostream *Out = &outs();  // Default to printing to stdout...
124   if (OutputFilename != "-") {
125     std::string ErrorInfo;
126     Out = new raw_fd_ostream(OutputFilename.c_str(), /*Binary=*/true,
127                              Force, ErrorInfo);
128     if (!ErrorInfo.empty()) {
129       errs() << ErrorInfo << '\n';
130       if (!Force)
131         errs() << "Use -f command line argument to force output\n";
132       delete Out;
133       return 1;
134     }
135
136     // Make sure that the Out file gets unlinked from the disk if we get a
137     // SIGINT
138     sys::RemoveFileOnSignal(sys::Path(OutputFilename));
139   }
140
141   if (verifyModule(*Composite.get())) {
142     cerr << argv[0] << ": linked module is broken!\n";
143     return 1;
144   }
145
146   if (Verbose) cerr << "Writing bitcode...\n";
147   WriteBitcodeToFile(Composite.get(), *Out);
148
149   if (Out != &outs()) delete Out;
150   return 0;
151 }