blob: 20ea4636339835d772de8c92a19d23e77ed6141e [file] [log] [blame]
Reid Spencerc0af3f02004-09-13 01:27:53 +00001//===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
Reid Spencerc0af3f02004-09-13 01:27:53 +00003// 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.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
Reid Spencerc0af3f02004-09-13 01:27:53 +00008//===----------------------------------------------------------------------===//
9//
10// This utility is intended to be compatible with GCC, and follows standard
11// system 'ld' conventions. As such, the default output file is ./a.out.
12// Additionally, this program outputs a shell script that is used to invoke LLI
13// to execute the program. In this manner, the generated executable (a.out for
14// example), is directly executable, whereas the bytecode file actually lives in
15// the a.out.bc file generated by this program. Also, Force is on by default.
16//
17// Note that if someone (or a script) deletes the executable program generated,
18// the .bc file will be left around. Considering that this is a temporary hack,
19// I'm not too worried about this.
20//
21//===----------------------------------------------------------------------===//
22
Reid Spenceraf303d52006-06-07 23:03:13 +000023#include "llvm/LinkAllVMCore.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000024#include "llvm/Linker.h"
Reid Spencer6da1e0d2004-12-14 04:20:08 +000025#include "llvm/System/Program.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000026#include "llvm/Module.h"
27#include "llvm/PassManager.h"
28#include "llvm/Bytecode/Reader.h"
Reid Spencer445564a2004-11-20 20:02:56 +000029#include "llvm/Bytecode/Writer.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000030#include "llvm/Target/TargetData.h"
Reid Spenceraefd04b2004-09-25 16:00:07 +000031#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetMachineRegistry.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/FileUtilities.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000035#include "llvm/Support/ManagedStatic.h"
Bill Wendling68fe61d2006-11-29 00:19:40 +000036#include "llvm/Support/Streams.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000037#include "llvm/Support/SystemUtils.h"
Reid Spencer445564a2004-11-20 20:02:56 +000038#include "llvm/System/Signals.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000039#include <fstream>
40#include <memory>
41using namespace llvm;
42
Reid Spencer445564a2004-11-20 20:02:56 +000043// Input/Output Options
44static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
45 cl::desc("<input bytecode files>"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000046
Reid Spencer445564a2004-11-20 20:02:56 +000047static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
Misha Brukman3da94ae2005-04-22 00:00:37 +000048 cl::desc("Override output filename"),
Reid Spencer445564a2004-11-20 20:02:56 +000049 cl::value_desc("filename"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000050
Misha Brukman3da94ae2005-04-22 00:00:37 +000051static cl::opt<bool> Verbose("v",
Reid Spencer445564a2004-11-20 20:02:56 +000052 cl::desc("Print information about actions taken"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000053
Reid Spencer445564a2004-11-20 20:02:56 +000054static cl::list<std::string> LibPaths("L", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000055 cl::desc("Specify a library search path"),
Reid Spencer445564a2004-11-20 20:02:56 +000056 cl::value_desc("directory"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000057
Reid Spencer445564a2004-11-20 20:02:56 +000058static cl::list<std::string> Libraries("l", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000059 cl::desc("Specify libraries to link to"),
Reid Spencer445564a2004-11-20 20:02:56 +000060 cl::value_desc("library prefix"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000061
Misha Brukman3da94ae2005-04-22 00:00:37 +000062static cl::opt<bool> LinkAsLibrary("link-as-library",
Reid Spencer445564a2004-11-20 20:02:56 +000063 cl::desc("Link the .bc files together as a library, not an executable"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000064
Reid Spencer445564a2004-11-20 20:02:56 +000065static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
66 cl::desc("Alias for -link-as-library"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000067
Reid Spencer445564a2004-11-20 20:02:56 +000068static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
Reid Spenceraefd04b2004-09-25 16:00:07 +000069 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
70
Reid Spencer445564a2004-11-20 20:02:56 +000071static cl::opt<bool> Native("native",
72 cl::desc("Generate a native binary instead of a shell script"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000073
Reid Spencer445564a2004-11-20 20:02:56 +000074static cl::opt<bool>NativeCBE("native-cbe",
75 cl::desc("Generate a native binary with the C backend and GCC"));
76
77static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
78 cl::desc("Disable writing of compressed bytecode files"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000079
Reid Spencer73a74be2005-12-21 05:03:23 +000080static cl::list<std::string> PostLinkOpts("post-link-opts",
Reid Spenceraf303d52006-06-07 23:03:13 +000081 cl::value_desc("path"),
Reid Spencer73a74be2005-12-21 05:03:23 +000082 cl::desc("Run one or more optimization programs after linking"));
83
Reid Spenceraf303d52006-06-07 23:03:13 +000084static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
85 cl::desc("Pass options to the system linker"));
86
Reid Spencer445564a2004-11-20 20:02:56 +000087// Compatibility options that are ignored but supported by LD
Misha Brukman3da94ae2005-04-22 00:00:37 +000088static cl::opt<std::string> CO3("soname", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000089 cl::desc("Compatibility option: ignored"));
90
Misha Brukman3da94ae2005-04-22 00:00:37 +000091static cl::opt<std::string> CO4("version-script", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000092 cl::desc("Compatibility option: ignored"));
93
Misha Brukman3da94ae2005-04-22 00:00:37 +000094static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000095 cl::desc("Compatibility option: ignored"));
96
Misha Brukman3da94ae2005-04-22 00:00:37 +000097static cl::opt<std::string> CO6("h", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +000098 cl::desc("Compatibility option: ignored"));
99
Reid Spenceraf303d52006-06-07 23:03:13 +0000100
Reid Spencer445564a2004-11-20 20:02:56 +0000101/// This is just for convenience so it doesn't have to be passed around
102/// everywhere.
Reid Spencerc4064132004-12-13 03:01:14 +0000103static std::string progname;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000104
105/// PrintAndReturn - Prints a message to standard error and returns true.
106///
107/// Inputs:
108/// progname - The name of the program (i.e. argv[0]).
109/// Message - The message to print to standard error.
110///
Reid Spencer445564a2004-11-20 20:02:56 +0000111static int PrintAndReturn(const std::string &Message) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000112 llvm_cerr << progname << ": " << Message << "\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000113 return 1;
114}
115
Reid Spencer445564a2004-11-20 20:02:56 +0000116/// CopyEnv - This function takes an array of environment variables and makes a
117/// copy of it. This copy can then be manipulated any way the caller likes
118/// without affecting the process's real environment.
119///
120/// Inputs:
121/// envp - An array of C strings containing an environment.
122///
123/// Return value:
124/// NULL - An error occurred.
125///
126/// Otherwise, a pointer to a new array of C strings is returned. Every string
127/// in the array is a duplicate of the one in the original array (i.e. we do
128/// not copy the char *'s from one array to another).
129///
130static char ** CopyEnv(char ** const envp) {
131 // Count the number of entries in the old list;
132 unsigned entries; // The number of entries in the old environment list
133 for (entries = 0; envp[entries] != NULL; entries++)
134 /*empty*/;
135
136 // Add one more entry for the NULL pointer that ends the list.
137 ++entries;
138
139 // If there are no entries at all, just return NULL.
140 if (entries == 0)
141 return NULL;
142
143 // Allocate a new environment list.
144 char **newenv = new char* [entries];
145 if ((newenv = new char* [entries]) == NULL)
146 return NULL;
147
148 // Make a copy of the list. Don't forget the NULL that ends the list.
149 entries = 0;
150 while (envp[entries] != NULL) {
151 newenv[entries] = new char[strlen (envp[entries]) + 1];
152 strcpy (newenv[entries], envp[entries]);
153 ++entries;
154 }
155 newenv[entries] = NULL;
156
157 return newenv;
158}
159
160
161/// RemoveEnv - Remove the specified environment variable from the environment
162/// array.
163///
164/// Inputs:
165/// name - The name of the variable to remove. It cannot be NULL.
166/// envp - The array of environment variables. It cannot be NULL.
167///
168/// Notes:
169/// This is mainly done because functions to remove items from the environment
170/// are not available across all platforms. In particular, Solaris does not
171/// seem to have an unsetenv() function or a setenv() function (or they are
172/// undocumented if they do exist).
173///
174static void RemoveEnv(const char * name, char ** const envp) {
175 for (unsigned index=0; envp[index] != NULL; index++) {
176 // Find the first equals sign in the array and make it an EOS character.
177 char *p = strchr (envp[index], '=');
178 if (p == NULL)
179 continue;
180 else
181 *p = '\0';
182
183 // Compare the two strings. If they are equal, zap this string.
184 // Otherwise, restore it.
185 if (!strcmp(name, envp[index]))
186 *envp[index] = '\0';
187 else
188 *p = '=';
189 }
190
191 return;
192}
193
194/// GenerateBytecode - generates a bytecode file from the module provided
195void GenerateBytecode(Module* M, const std::string& FileName) {
196
197 // Create the output file.
Jeff Cohen5fb6ed42005-01-22 17:36:17 +0000198 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
199 std::ios::binary;
200 std::ofstream Out(FileName.c_str(), io_mode);
Reid Spencer445564a2004-11-20 20:02:56 +0000201 if (!Out.good()) {
202 PrintAndReturn("error opening '" + FileName + "' for writing!");
203 return;
204 }
205
206 // Ensure that the bytecode file gets removed from the disk if we get a
207 // terminating signal.
208 sys::RemoveFileOnSignal(sys::Path(FileName));
209
210 // Write it out
Bill Wendling68fe61d2006-11-29 00:19:40 +0000211 llvm_ostream L(Out);
212 WriteBytecodeToFile(M, L, !DisableCompression);
Reid Spencer445564a2004-11-20 20:02:56 +0000213
214 // Close the bytecode file.
215 Out.close();
216}
217
218/// GenerateAssembly - generates a native assembly language source file from the
219/// specified bytecode file.
220///
221/// Inputs:
Devang Patele2f8ad82006-06-27 18:07:29 +0000222/// InputFilename - The name of the input bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000223/// OutputFilename - The name of the file to generate.
224/// llc - The pathname to use for LLC.
225/// envp - The environment to use when running LLC.
226///
227/// Return non-zero value on error.
228///
229static int GenerateAssembly(const std::string &OutputFilename,
230 const std::string &InputFilename,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000231 const sys::Path &llc,
232 std::string &ErrMsg ) {
Reid Spencer445564a2004-11-20 20:02:56 +0000233 // Run LLC to convert the bytecode file into assembly code.
Reid Spencerf6358c72004-12-19 18:00:56 +0000234 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000235 args.push_back(llc.c_str());
236 args.push_back("-f");
237 args.push_back("-o");
238 args.push_back(OutputFilename.c_str());
239 args.push_back(InputFilename.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000240 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000241
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000242 return sys::Program::ExecuteAndWait(llc,&args[0],0,0,0,&ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000243}
244
Devang Patele2f8ad82006-06-27 18:07:29 +0000245/// GenerateCFile - generates a C source file from the specified bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000246static int GenerateCFile(const std::string &OutputFile,
247 const std::string &InputFile,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000248 const sys::Path &llc,
249 std::string& ErrMsg) {
Reid Spencer445564a2004-11-20 20:02:56 +0000250 // Run LLC to convert the bytecode file into C.
Reid Spencerf6358c72004-12-19 18:00:56 +0000251 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000252 args.push_back(llc.c_str());
253 args.push_back("-march=c");
254 args.push_back("-f");
255 args.push_back("-o");
256 args.push_back(OutputFile.c_str());
257 args.push_back(InputFile.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000258 args.push_back(0);
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000259 return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000260}
261
Devang Patele2f8ad82006-06-27 18:07:29 +0000262/// GenerateNative - generates a native object file from the
263/// specified bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000264///
265/// Inputs:
Devang Patele2f8ad82006-06-27 18:07:29 +0000266/// InputFilename - The name of the input bytecode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000267/// OutputFilename - The name of the file to generate.
Reid Spencer49521432006-11-11 11:54:25 +0000268/// LinkItems - The native libraries, files, code with which to link
Reid Spencer445564a2004-11-20 20:02:56 +0000269/// LibPaths - The list of directories in which to find libraries.
270/// gcc - The pathname to use for GGC.
271/// envp - A copy of the process's current environment.
272///
273/// Outputs:
274/// None.
275///
276/// Returns non-zero value on error.
277///
278static int GenerateNative(const std::string &OutputFilename,
279 const std::string &InputFilename,
Reid Spencer49521432006-11-11 11:54:25 +0000280 const Linker::ItemList &LinkItems,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000281 const sys::Path &gcc, char ** const envp,
282 std::string& ErrMsg) {
Reid Spencer445564a2004-11-20 20:02:56 +0000283 // Remove these environment variables from the environment of the
284 // programs that we will execute. It appears that GCC sets these
285 // environment variables so that the programs it uses can configure
286 // themselves identically.
287 //
288 // However, when we invoke GCC below, we want it to use its normal
289 // configuration. Hence, we must sanitize its environment.
290 char ** clean_env = CopyEnv(envp);
291 if (clean_env == NULL)
292 return 1;
293 RemoveEnv("LIBRARY_PATH", clean_env);
294 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
295 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
296 RemoveEnv("COMPILER_PATH", clean_env);
297 RemoveEnv("COLLECT_GCC", clean_env);
298
Reid Spencer445564a2004-11-20 20:02:56 +0000299
300 // Run GCC to assemble and link the program into native code.
301 //
302 // Note:
303 // We can't just assemble and link the file with the system assembler
304 // and linker because we don't know where to put the _start symbol.
305 // GCC mysteriously knows how to do it.
Reid Spencerf6358c72004-12-19 18:00:56 +0000306 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000307 args.push_back(gcc.c_str());
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000308 args.push_back("-fno-strict-aliasing");
309 args.push_back("-O3");
310 args.push_back("-o");
Reid Spencerf6358c72004-12-19 18:00:56 +0000311 args.push_back(OutputFilename.c_str());
312 args.push_back(InputFilename.c_str());
Reid Spencer445564a2004-11-20 20:02:56 +0000313
Reid Spenceraf303d52006-06-07 23:03:13 +0000314 // Add in the library paths
315 for (unsigned index = 0; index < LibPaths.size(); index++) {
316 args.push_back("-L");
317 args.push_back(LibPaths[index].c_str());
318 }
319
320 // Add the requested options
321 for (unsigned index = 0; index < XLinker.size(); index++) {
322 args.push_back(XLinker[index].c_str());
323 args.push_back(Libraries[index].c_str());
324 }
325
Reid Spencer445564a2004-11-20 20:02:56 +0000326 // Add in the libraries to link.
Reid Spencer49521432006-11-11 11:54:25 +0000327 for (unsigned index = 0; index < LinkItems.size(); index++)
328 if (LinkItems[index].first != "crtend") {
329 if (LinkItems[index].second) {
Reid Spencer2803b4c2006-11-11 19:59:25 +0000330 std::string lib_name = "-l" + LinkItems[index].first;
331 args.push_back(lib_name.c_str());
Reid Spencer49521432006-11-11 11:54:25 +0000332 } else
Reid Spencer2803b4c2006-11-11 19:59:25 +0000333 args.push_back(LinkItems[index].first.c_str());
Reid Spencerf6358c72004-12-19 18:00:56 +0000334 }
Reid Spenceraf303d52006-06-07 23:03:13 +0000335
Chris Lattner7456e3c2005-02-13 23:10:45 +0000336 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000337
338 // Run the compiler to assembly and link together the program.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000339 int R = sys::Program::ExecuteAndWait(
340 gcc, &args[0], (const char**)clean_env,0,0,&ErrMsg);
Chris Lattner2f863622006-05-14 18:38:13 +0000341 delete [] clean_env;
342 return R;
Reid Spencer445564a2004-11-20 20:02:56 +0000343}
344
Reid Spencerc0af3f02004-09-13 01:27:53 +0000345/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
346/// bytecode file for the program.
347static void EmitShellScript(char **argv) {
348#if defined(_WIN32) || defined(__CYGWIN__)
349 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
350 // support windows systems, we copy the llvm-stub.exe executable from the
351 // build tree to the destination file.
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000352 std::string ErrMsg;
Reid Spencer8d8b41d2004-12-22 13:50:17 +0000353 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
354 if (llvmstub.isEmpty()) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000355 llvm_cerr << "Could not find llvm-stub.exe executable!\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000356 exit(1);
357 }
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000358
359 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg)) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000360 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000361 exit(1);
362 }
363
Reid Spencerc0af3f02004-09-13 01:27:53 +0000364 return;
365#endif
366
367 // Output the script to start the program...
368 std::ofstream Out2(OutputFilename.c_str());
369 if (!Out2.good())
Reid Spencer445564a2004-11-20 20:02:56 +0000370 exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
Reid Spencerc0af3f02004-09-13 01:27:53 +0000371
372 Out2 << "#!/bin/sh\n";
373 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
374 Out2 << "lli=${LLVMINTERP-lli}\n";
375 Out2 << "exec $lli \\\n";
376 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
377 LibPaths.push_back("/lib");
378 LibPaths.push_back("/usr/lib");
379 LibPaths.push_back("/usr/X11R6/lib");
380 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
381 // shared object at all! See RH 8: plain text.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000382 std::vector<std::string>::iterator libc =
Reid Spencerc0af3f02004-09-13 01:27:53 +0000383 std::find(Libraries.begin(), Libraries.end(), "c");
384 if (libc != Libraries.end()) Libraries.erase(libc);
385 // List all the shared object (native) libraries this executable will need
386 // on the command line, so that we don't have to do this manually!
Misha Brukman3da94ae2005-04-22 00:00:37 +0000387 for (std::vector<std::string>::iterator i = Libraries.begin(),
Reid Spencerc0af3f02004-09-13 01:27:53 +0000388 e = Libraries.end(); i != e; ++i) {
Reid Spencerc4064132004-12-13 03:01:14 +0000389 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
390 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
391 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000392 }
393 Out2 << " $0.bc ${1+\"$@\"}\n";
394 Out2.close();
395}
396
Reid Spencerc4064132004-12-13 03:01:14 +0000397// BuildLinkItems -- This function generates a LinkItemList for the LinkItems
398// linker function by combining the Files and Libraries in the order they were
399// declared on the command line.
400static void BuildLinkItems(
401 Linker::ItemList& Items,
402 const cl::list<std::string>& Files,
403 const cl::list<std::string>& Libraries) {
404
Misha Brukman3da94ae2005-04-22 00:00:37 +0000405 // Build the list of linkage items for LinkItems.
Reid Spencerc4064132004-12-13 03:01:14 +0000406
407 cl::list<std::string>::const_iterator fileIt = Files.begin();
408 cl::list<std::string>::const_iterator libIt = Libraries.begin();
409
410 int libPos = -1, filePos = -1;
Reid Spencer05f7e792004-12-13 17:18:19 +0000411 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
Reid Spencerc4064132004-12-13 03:01:14 +0000412 if (libIt != Libraries.end())
413 libPos = Libraries.getPosition(libIt - Libraries.begin());
414 else
415 libPos = -1;
416 if (fileIt != Files.end())
417 filePos = Files.getPosition(fileIt - Files.begin());
418 else
419 filePos = -1;
420
421 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
422 // Add a source file
423 Items.push_back(std::make_pair(*fileIt++, false));
424 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
425 // Add a library
426 Items.push_back(std::make_pair(*libIt++, true));
Reid Spencerc4064132004-12-13 03:01:14 +0000427 }
428 }
429}
430
Reid Spencer445564a2004-11-20 20:02:56 +0000431// Rightly this should go in a header file but it just seems such a waste.
432namespace llvm {
433extern void Optimize(Module*);
434}
435
Reid Spencerc0af3f02004-09-13 01:27:53 +0000436int main(int argc, char **argv, char **envp) {
Chris Lattnerc30598b2006-12-06 01:18:01 +0000437 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000438 try {
439 // Initial global variable above for convenience printing of program name.
440 progname = sys::Path(argv[0]).getBasename();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000441
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000442 // Parse the command line options
443 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
444 sys::PrintStackTraceOnErrorSignal();
Reid Spencerc0af3f02004-09-13 01:27:53 +0000445
Reid Spencer49521432006-11-11 11:54:25 +0000446 // Construct a Linker (now that Verbose is set)
447 Linker TheLinker(progname, OutputFilename, Verbose);
448 // Keep track of the native link items (vice the bytecode items)
449 Linker::ItemList LinkItems;
450
451 // Add library paths to the linker
Reid Spencer78df5c32006-03-06 06:38:19 +0000452 TheLinker.addPaths(LibPaths);
453 TheLinker.addSystemPaths();
454
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000455 // Remove any consecutive duplicates of the same library...
456 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
457 Libraries.end());
Reid Spencerc0af3f02004-09-13 01:27:53 +0000458
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000459 if (LinkAsLibrary) {
460 std::vector<sys::Path> Files;
461 for (unsigned i = 0; i < InputFilenames.size(); ++i )
462 Files.push_back(sys::Path(InputFilenames[i]));
463 if (TheLinker.LinkInFiles(Files))
464 return 1; // Error already printed
Reid Spencer6b463b22004-12-08 05:17:40 +0000465
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000466 // The libraries aren't linked in but are noted as "dependent" in the
467 // module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000468 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000469 E = Libraries.end(); I != E ; ++I) {
470 TheLinker.getModule()->addLibrary(*I);
471 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000472 } else {
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000473 // Build a list of the items from our command line
474 Linker::ItemList Items;
475 BuildLinkItems(Items, InputFilenames, Libraries);
476
477 // Link all the items together
Reid Spencer49521432006-11-11 11:54:25 +0000478 if (TheLinker.LinkInItems(Items,LinkItems) )
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000479 return 1;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000480 }
Reid Spencerc0af3f02004-09-13 01:27:53 +0000481
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000482 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
483
484 // Optimize the module
485 Optimize(Composite.get());
486
487 // Generate the bytecode for the optimized module.
488 std::string RealBytecodeOutput = OutputFilename;
489 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
490 GenerateBytecode(Composite.get(), RealBytecodeOutput);
491
492 // If we are not linking a library, generate either a native executable
493 // or a JIT shell script, depending upon what the user wants.
494 if (!LinkAsLibrary) {
Reid Spencer73a74be2005-12-21 05:03:23 +0000495 // If the user wants to run a post-link optimization, run it now.
496 if (!PostLinkOpts.empty()) {
497 std::vector<std::string> opts = PostLinkOpts;
498 for (std::vector<std::string>::iterator I = opts.begin(),
499 E = opts.end(); I != E; ++I) {
500 sys::Path prog(*I);
501 if (!prog.canExecute()) {
502 prog = sys::Program::FindProgramByName(*I);
503 if (prog.isEmpty())
504 return PrintAndReturn(std::string("Optimization program '") + *I +
505 "' is not found or not executable.");
506 }
507 // Get the program arguments
508 sys::Path tmp_output("opt_result");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000509 std::string ErrMsg;
Reid Spencer7b289552006-11-05 19:53:08 +0000510 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg)) {
Reid Spencere5c9cb52006-08-23 00:39:35 +0000511 return PrintAndReturn(ErrMsg);
Reid Spencer73a74be2005-12-21 05:03:23 +0000512 }
513 const char* args[4];
514 args[0] = I->c_str();
515 args[1] = RealBytecodeOutput.c_str();
516 args[2] = tmp_output.c_str();
517 args[3] = 0;
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000518 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0, &ErrMsg)) {
Reid Spencer73a74be2005-12-21 05:03:23 +0000519 if (tmp_output.isBytecodeFile()) {
520 sys::Path target(RealBytecodeOutput);
521 target.eraseFromDisk();
Reid Spencer5a060772006-08-23 07:30:48 +0000522 if (tmp_output.renamePathOnDisk(target, &ErrMsg)) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000523 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Reid Spencer5a060772006-08-23 07:30:48 +0000524 return 2;
525 }
Reid Spencer73a74be2005-12-21 05:03:23 +0000526 } else
527 return PrintAndReturn(
528 "Post-link optimization output is not bytecode");
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000529 } else {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000530 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000531 return 2;
Reid Spencer73a74be2005-12-21 05:03:23 +0000532 }
533 }
534 }
535
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000536 // If the user wants to generate a native executable, compile it from the
537 // bytecode file.
538 //
539 // Otherwise, create a script that will run the bytecode through the JIT.
540 if (Native) {
541 // Name of the Assembly Language output file
542 sys::Path AssemblyFile ( OutputFilename);
543 AssemblyFile.appendSuffix("s");
544
545 // Mark the output files for removal if we get an interrupt.
546 sys::RemoveFileOnSignal(AssemblyFile);
547 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
548
549 // Determine the locations of the llc and gcc programs.
550 sys::Path llc = FindExecutable("llc", argv[0]);
551 if (llc.isEmpty())
552 return PrintAndReturn("Failed to find llc");
553
554 sys::Path gcc = FindExecutable("gcc", argv[0]);
555 if (gcc.isEmpty())
556 return PrintAndReturn("Failed to find gcc");
557
558 // Generate an assembly language file for the bytecode.
Bill Wendling68fe61d2006-11-29 00:19:40 +0000559 if (Verbose) llvm_cout << "Generating Assembly Code\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000560 std::string ErrMsg;
561 if (0 != GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput,
562 llc, ErrMsg)) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000563 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000564 return 1;
565 }
566
Bill Wendling68fe61d2006-11-29 00:19:40 +0000567 if (Verbose) llvm_cout << "Generating Native Code\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000568 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
Reid Spencer49521432006-11-11 11:54:25 +0000569 LinkItems,gcc,envp,ErrMsg)) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000570 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000571 return 1;
572 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000573
574 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000575 AssemblyFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000576 } else if (NativeCBE) {
577 sys::Path CFile (OutputFilename);
578 CFile.appendSuffix("cbe.c");
579
580 // Mark the output files for removal if we get an interrupt.
581 sys::RemoveFileOnSignal(CFile);
582 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
583
584 // Determine the locations of the llc and gcc programs.
585 sys::Path llc = FindExecutable("llc", argv[0]);
586 if (llc.isEmpty())
587 return PrintAndReturn("Failed to find llc");
588
589 sys::Path gcc = FindExecutable("gcc", argv[0]);
590 if (gcc.isEmpty())
591 return PrintAndReturn("Failed to find gcc");
592
593 // Generate an assembly language file for the bytecode.
Bill Wendling68fe61d2006-11-29 00:19:40 +0000594 if (Verbose) llvm_cout << "Generating Assembly Code\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000595 std::string ErrMsg;
596 if (0 != GenerateCFile(
597 CFile.toString(), RealBytecodeOutput, llc, ErrMsg)) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000598 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000599 return 1;
600 }
601
Bill Wendling68fe61d2006-11-29 00:19:40 +0000602 if (Verbose) llvm_cout << "Generating Native Code\n";
Reid Spencer49521432006-11-11 11:54:25 +0000603 if (0 != GenerateNative(OutputFilename, CFile.toString(), LinkItems,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000604 gcc, envp, ErrMsg)) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000605 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000606 return 1;
607 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000608
609 // Remove the assembly language file.
Reid Spencera229c5c2005-07-08 03:08:58 +0000610 CFile.eraseFromDisk();
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000611
612 } else {
613 EmitShellScript(argv);
614 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000615
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000616 // Make the script executable...
Reid Spencere1647f42006-08-22 23:27:23 +0000617 std::string ErrMsg;
618 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg)) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000619 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Reid Spencere1647f42006-08-22 23:27:23 +0000620 return 1;
621 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000622
623 // Make the bytecode file readable and directly executable in LLEE as well
Reid Spencere1647f42006-08-22 23:27:23 +0000624 if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg)) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000625 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Reid Spencere1647f42006-08-22 23:27:23 +0000626 return 1;
627 }
628 if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg)) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000629 llvm_cerr << argv[0] << ": " << ErrMsg << "\n";
Reid Spencere1647f42006-08-22 23:27:23 +0000630 return 1;
631 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000632 }
633
634 return 0;
635 } catch (const std::string& msg) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000636 llvm_cerr << argv[0] << ": " << msg << "\n";
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000637 } catch (...) {
Bill Wendling68fe61d2006-11-29 00:19:40 +0000638 llvm_cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000639 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000640 return 1;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000641}