blob: 6c3953aad518543c64e4e7a5813c8d9f2b8f8cb4 [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//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Gabor Greifa99be512007-07-05 17:07:56 +000014// example), is directly executable, whereas the bitcode file actually lives in
Dan Gohmanbaa26392009-08-25 15:34:52 +000015// the a.out.bc file generated by this program.
Reid Spencerc0af3f02004-09-13 01:27:53 +000016//
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"
Owen Anderson8b477ed2009-07-01 16:58:40 +000025#include "llvm/LLVMContext.h"
Reid Spencer6da1e0d2004-12-14 04:20:08 +000026#include "llvm/System/Program.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000027#include "llvm/Module.h"
28#include "llvm/PassManager.h"
Chris Lattnerbb3f3d32007-05-06 05:56:58 +000029#include "llvm/Bitcode/ReaderWriter.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"
Reid Spencerc0af3f02004-09-13 01:27:53 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/FileUtilities.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000034#include "llvm/Support/ManagedStatic.h"
Chris Lattnerbb3f3d32007-05-06 05:56:58 +000035#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercc14d252009-03-06 05:34:10 +000036#include "llvm/Support/PrettyStackTrace.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000037#include "llvm/Support/SystemUtils.h"
Chris Lattner74382b72009-08-23 22:45:37 +000038#include "llvm/Support/raw_ostream.h"
Reid Spencer445564a2004-11-20 20:02:56 +000039#include "llvm/System/Signals.h"
Chris Lattner5d5a8972009-01-05 19:01:32 +000040#include "llvm/Config/config.h"
Reid Spencerc0af3f02004-09-13 01:27:53 +000041#include <memory>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000042#include <cstring>
Reid Spencerc0af3f02004-09-13 01:27:53 +000043using namespace llvm;
44
Dan Gohman197f7282009-08-05 20:21:17 +000045// Rightly this should go in a header file but it just seems such a waste.
46namespace llvm {
47extern void Optimize(Module*);
48}
49
Reid Spencer445564a2004-11-20 20:02:56 +000050// Input/Output Options
51static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
Gabor Greifa99be512007-07-05 17:07:56 +000052 cl::desc("<input bitcode files>"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000053
Reid Spencer445564a2004-11-20 20:02:56 +000054static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
Misha Brukman3da94ae2005-04-22 00:00:37 +000055 cl::desc("Override output filename"),
Reid Spencer445564a2004-11-20 20:02:56 +000056 cl::value_desc("filename"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000057
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +000058static cl::opt<std::string> BitcodeOutputFilename("b", cl::init(""),
59 cl::desc("Override bitcode output filename"),
60 cl::value_desc("filename"));
61
Misha Brukman3da94ae2005-04-22 00:00:37 +000062static cl::opt<bool> Verbose("v",
Reid Spencer445564a2004-11-20 20:02:56 +000063 cl::desc("Print information about actions taken"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000064
Reid Spencer445564a2004-11-20 20:02:56 +000065static cl::list<std::string> LibPaths("L", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000066 cl::desc("Specify a library search path"),
Reid Spencer445564a2004-11-20 20:02:56 +000067 cl::value_desc("directory"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000068
Chris Lattner3992f522008-01-27 22:58:59 +000069static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
70 cl::desc("Specify a framework search path"),
71 cl::value_desc("directory"));
72
Reid Spencer445564a2004-11-20 20:02:56 +000073static cl::list<std::string> Libraries("l", cl::Prefix,
Misha Brukman3da94ae2005-04-22 00:00:37 +000074 cl::desc("Specify libraries to link to"),
Reid Spencer445564a2004-11-20 20:02:56 +000075 cl::value_desc("library prefix"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000076
Chris Lattner3992f522008-01-27 22:58:59 +000077static cl::list<std::string> Frameworks("framework",
78 cl::desc("Specify frameworks to link to"),
79 cl::value_desc("framework"));
80
Reid Spencer708585a2007-02-09 03:08:06 +000081// Options to control the linking, optimization, and code gen processes
Misha Brukman3da94ae2005-04-22 00:00:37 +000082static cl::opt<bool> LinkAsLibrary("link-as-library",
Reid Spencer445564a2004-11-20 20:02:56 +000083 cl::desc("Link the .bc files together as a library, not an executable"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000084
Reid Spencer445564a2004-11-20 20:02:56 +000085static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
86 cl::desc("Alias for -link-as-library"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000087
Reid Spencer445564a2004-11-20 20:02:56 +000088static cl::opt<bool> Native("native",
89 cl::desc("Generate a native binary instead of a shell script"));
Reid Spencerc0af3f02004-09-13 01:27:53 +000090
Reid Spencer445564a2004-11-20 20:02:56 +000091static cl::opt<bool>NativeCBE("native-cbe",
92 cl::desc("Generate a native binary with the C backend and GCC"));
93
Reid Spencer73a74be2005-12-21 05:03:23 +000094static cl::list<std::string> PostLinkOpts("post-link-opts",
Reid Spenceraf303d52006-06-07 23:03:13 +000095 cl::value_desc("path"),
Reid Spencer73a74be2005-12-21 05:03:23 +000096 cl::desc("Run one or more optimization programs after linking"));
97
Reid Spenceraf303d52006-06-07 23:03:13 +000098static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
99 cl::desc("Pass options to the system linker"));
100
Reid Spencer708585a2007-02-09 03:08:06 +0000101// Compatibility options that llvm-ld ignores but are supported for
102// compatibility with LD
Misha Brukman3da94ae2005-04-22 00:00:37 +0000103static cl::opt<std::string> CO3("soname", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000104 cl::desc("Compatibility option: ignored"));
105
Misha Brukman3da94ae2005-04-22 00:00:37 +0000106static cl::opt<std::string> CO4("version-script", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000107 cl::desc("Compatibility option: ignored"));
108
Misha Brukman3da94ae2005-04-22 00:00:37 +0000109static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000110 cl::desc("Compatibility option: ignored"));
111
Misha Brukman3da94ae2005-04-22 00:00:37 +0000112static cl::opt<std::string> CO6("h", cl::Hidden,
Reid Spencer445564a2004-11-20 20:02:56 +0000113 cl::desc("Compatibility option: ignored"));
114
Reid Spencer98a030c2007-02-08 19:03:11 +0000115static cl::opt<bool> CO7("start-group", cl::Hidden,
116 cl::desc("Compatibility option: ignored"));
117
118static cl::opt<bool> CO8("end-group", cl::Hidden,
119 cl::desc("Compatibility option: ignored"));
Reid Spenceraf303d52006-06-07 23:03:13 +0000120
Andrew Lenharth0c6ba442008-11-19 17:00:08 +0000121static cl::opt<std::string> CO9("m", cl::Hidden,
122 cl::desc("Compatibility option: ignored"));
123
Reid Spencer445564a2004-11-20 20:02:56 +0000124/// This is just for convenience so it doesn't have to be passed around
125/// everywhere.
Reid Spencerc4064132004-12-13 03:01:14 +0000126static std::string progname;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000127
Reid Spencer708585a2007-02-09 03:08:06 +0000128/// PrintAndExit - Prints a message to standard error and exits with error code
Reid Spencerc0af3f02004-09-13 01:27:53 +0000129///
130/// Inputs:
Reid Spencerc0af3f02004-09-13 01:27:53 +0000131/// Message - The message to print to standard error.
132///
Chris Lattner25c54c02010-03-23 21:59:43 +0000133static void PrintAndExit(const std::string &Message, Module *M, int errcode = 1) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000134 errs() << progname << ": " << Message << "\n";
Chris Lattner25c54c02010-03-23 21:59:43 +0000135 delete M;
Reid Spencer708585a2007-02-09 03:08:06 +0000136 llvm_shutdown();
137 exit(errcode);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000138}
139
Reid Spencer3b726392007-04-29 23:59:47 +0000140static void PrintCommand(const std::vector<const char*> &args) {
141 std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
142 for (; I != E; ++I)
143 if (*I)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000144 outs() << "'" << *I << "'" << " ";
145 outs() << "\n"; outs().flush();
Reid Spencer3b726392007-04-29 23:59:47 +0000146}
147
Reid Spencer445564a2004-11-20 20:02:56 +0000148/// CopyEnv - This function takes an array of environment variables and makes a
149/// copy of it. This copy can then be manipulated any way the caller likes
150/// without affecting the process's real environment.
151///
152/// Inputs:
153/// envp - An array of C strings containing an environment.
154///
155/// Return value:
156/// NULL - An error occurred.
157///
158/// Otherwise, a pointer to a new array of C strings is returned. Every string
159/// in the array is a duplicate of the one in the original array (i.e. we do
160/// not copy the char *'s from one array to another).
161///
162static char ** CopyEnv(char ** const envp) {
163 // Count the number of entries in the old list;
164 unsigned entries; // The number of entries in the old environment list
165 for (entries = 0; envp[entries] != NULL; entries++)
166 /*empty*/;
167
168 // Add one more entry for the NULL pointer that ends the list.
169 ++entries;
170
171 // If there are no entries at all, just return NULL.
172 if (entries == 0)
173 return NULL;
174
175 // Allocate a new environment list.
176 char **newenv = new char* [entries];
177 if ((newenv = new char* [entries]) == NULL)
178 return NULL;
179
180 // Make a copy of the list. Don't forget the NULL that ends the list.
181 entries = 0;
182 while (envp[entries] != NULL) {
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000183 size_t len = strlen(envp[entries]) + 1;
184 newenv[entries] = new char[len];
185 memcpy(newenv[entries], envp[entries], len);
Reid Spencer445564a2004-11-20 20:02:56 +0000186 ++entries;
187 }
188 newenv[entries] = NULL;
189
190 return newenv;
191}
192
193
194/// RemoveEnv - Remove the specified environment variable from the environment
195/// array.
196///
197/// Inputs:
198/// name - The name of the variable to remove. It cannot be NULL.
199/// envp - The array of environment variables. It cannot be NULL.
200///
201/// Notes:
202/// This is mainly done because functions to remove items from the environment
203/// are not available across all platforms. In particular, Solaris does not
204/// seem to have an unsetenv() function or a setenv() function (or they are
205/// undocumented if they do exist).
206///
207static void RemoveEnv(const char * name, char ** const envp) {
208 for (unsigned index=0; envp[index] != NULL; index++) {
209 // Find the first equals sign in the array and make it an EOS character.
210 char *p = strchr (envp[index], '=');
211 if (p == NULL)
212 continue;
213 else
214 *p = '\0';
215
216 // Compare the two strings. If they are equal, zap this string.
217 // Otherwise, restore it.
218 if (!strcmp(name, envp[index]))
219 *envp[index] = '\0';
220 else
221 *p = '=';
222 }
223
224 return;
225}
226
Gabor Greifa99be512007-07-05 17:07:56 +0000227/// GenerateBitcode - generates a bitcode file from the module provided
228void GenerateBitcode(Module* M, const std::string& FileName) {
Reid Spencer445564a2004-11-20 20:02:56 +0000229
Reid Spencer3b726392007-04-29 23:59:47 +0000230 if (Verbose)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000231 outs() << "Generating Bitcode To " << FileName << '\n';
Reid Spencer3b726392007-04-29 23:59:47 +0000232
Reid Spencer445564a2004-11-20 20:02:56 +0000233 // Create the output file.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000234 std::string ErrorInfo;
Chris Lattner17e9edc2009-08-23 02:51:22 +0000235 raw_fd_ostream Out(FileName.c_str(), ErrorInfo,
Dan Gohmanbaa26392009-08-25 15:34:52 +0000236 raw_fd_ostream::F_Binary);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000237 if (!ErrorInfo.empty())
Chris Lattner25c54c02010-03-23 21:59:43 +0000238 PrintAndExit(ErrorInfo, M);
Reid Spencer445564a2004-11-20 20:02:56 +0000239
Gabor Greifa99be512007-07-05 17:07:56 +0000240 // Ensure that the bitcode file gets removed from the disk if we get a
Reid Spencer445564a2004-11-20 20:02:56 +0000241 // terminating signal.
242 sys::RemoveFileOnSignal(sys::Path(FileName));
243
244 // Write it out
Chris Lattner44dadff2007-05-06 09:29:57 +0000245 WriteBitcodeToFile(M, Out);
Reid Spencer445564a2004-11-20 20:02:56 +0000246
Gabor Greifa99be512007-07-05 17:07:56 +0000247 // Close the bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000248 Out.close();
249}
250
251/// GenerateAssembly - generates a native assembly language source file from the
Gabor Greifa99be512007-07-05 17:07:56 +0000252/// specified bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000253///
254/// Inputs:
Gabor Greifa99be512007-07-05 17:07:56 +0000255/// InputFilename - The name of the input bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000256/// OutputFilename - The name of the file to generate.
257/// llc - The pathname to use for LLC.
258/// envp - The environment to use when running LLC.
259///
260/// Return non-zero value on error.
261///
262static int GenerateAssembly(const std::string &OutputFilename,
263 const std::string &InputFilename,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000264 const sys::Path &llc,
265 std::string &ErrMsg ) {
Gabor Greifa99be512007-07-05 17:07:56 +0000266 // Run LLC to convert the bitcode file into assembly code.
Reid Spencerf6358c72004-12-19 18:00:56 +0000267 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000268 args.push_back(llc.c_str());
Argyrios Kyrtzidisca29dff2008-06-27 15:08:59 +0000269 // We will use GCC to assemble the program so set the assembly syntax to AT&T,
270 // regardless of what the target in the bitcode file is.
271 args.push_back("-x86-asm-syntax=att");
Chris Lattnerbf9add42005-04-10 20:59:38 +0000272 args.push_back("-f");
273 args.push_back("-o");
274 args.push_back(OutputFilename.c_str());
275 args.push_back(InputFilename.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000276 args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000277
Reid Spencer3b726392007-04-29 23:59:47 +0000278 if (Verbose) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000279 outs() << "Generating Assembly With: \n";
Reid Spencer3b726392007-04-29 23:59:47 +0000280 PrintCommand(args);
281 }
282
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000283 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000284}
285
Gabor Greifa99be512007-07-05 17:07:56 +0000286/// GenerateCFile - generates a C source file from the specified bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000287static int GenerateCFile(const std::string &OutputFile,
288 const std::string &InputFile,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000289 const sys::Path &llc,
290 std::string& ErrMsg) {
Gabor Greifa99be512007-07-05 17:07:56 +0000291 // Run LLC to convert the bitcode file into C.
Reid Spencerf6358c72004-12-19 18:00:56 +0000292 std::vector<const char*> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000293 args.push_back(llc.c_str());
294 args.push_back("-march=c");
295 args.push_back("-f");
296 args.push_back("-o");
297 args.push_back(OutputFile.c_str());
298 args.push_back(InputFile.c_str());
Chris Lattner7456e3c2005-02-13 23:10:45 +0000299 args.push_back(0);
Reid Spencer3b726392007-04-29 23:59:47 +0000300
301 if (Verbose) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000302 outs() << "Generating C Source With: \n";
Reid Spencer3b726392007-04-29 23:59:47 +0000303 PrintCommand(args);
304 }
305
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000306 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
Reid Spencer445564a2004-11-20 20:02:56 +0000307}
308
Devang Patele2f8ad82006-06-27 18:07:29 +0000309/// GenerateNative - generates a native object file from the
Gabor Greifa99be512007-07-05 17:07:56 +0000310/// specified bitcode file.
Reid Spencer445564a2004-11-20 20:02:56 +0000311///
312/// Inputs:
Gabor Greifa99be512007-07-05 17:07:56 +0000313/// InputFilename - The name of the input bitcode file.
Reid Spencerc82a5da2007-04-04 06:34:22 +0000314/// OutputFilename - The name of the file to generate.
315/// NativeLinkItems - The native libraries, files, code with which to link
316/// LibPaths - The list of directories in which to find libraries.
Chris Lattner3992f522008-01-27 22:58:59 +0000317/// FrameworksPaths - The list of directories in which to find frameworks.
318/// Frameworks - The list of frameworks (dynamic libraries)
Reid Spencerc82a5da2007-04-04 06:34:22 +0000319/// gcc - The pathname to use for GGC.
320/// envp - A copy of the process's current environment.
Reid Spencer445564a2004-11-20 20:02:56 +0000321///
322/// Outputs:
323/// None.
324///
325/// Returns non-zero value on error.
326///
327static int GenerateNative(const std::string &OutputFilename,
328 const std::string &InputFilename,
Reid Spencer49521432006-11-11 11:54:25 +0000329 const Linker::ItemList &LinkItems,
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000330 const sys::Path &gcc, char ** const envp,
331 std::string& ErrMsg) {
Reid Spencer445564a2004-11-20 20:02:56 +0000332 // Remove these environment variables from the environment of the
333 // programs that we will execute. It appears that GCC sets these
334 // environment variables so that the programs it uses can configure
335 // themselves identically.
336 //
337 // However, when we invoke GCC below, we want it to use its normal
338 // configuration. Hence, we must sanitize its environment.
339 char ** clean_env = CopyEnv(envp);
340 if (clean_env == NULL)
341 return 1;
342 RemoveEnv("LIBRARY_PATH", clean_env);
343 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
344 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
345 RemoveEnv("COMPILER_PATH", clean_env);
346 RemoveEnv("COLLECT_GCC", clean_env);
347
Reid Spencer445564a2004-11-20 20:02:56 +0000348
349 // Run GCC to assemble and link the program into native code.
350 //
351 // Note:
352 // We can't just assemble and link the file with the system assembler
353 // and linker because we don't know where to put the _start symbol.
354 // GCC mysteriously knows how to do it.
Chris Lattner3f931b82007-06-19 16:46:48 +0000355 std::vector<std::string> args;
Chris Lattnerbf9add42005-04-10 20:59:38 +0000356 args.push_back(gcc.c_str());
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000357 args.push_back("-fno-strict-aliasing");
358 args.push_back("-O3");
359 args.push_back("-o");
Chris Lattner3f931b82007-06-19 16:46:48 +0000360 args.push_back(OutputFilename);
361 args.push_back(InputFilename);
Reid Spencer445564a2004-11-20 20:02:56 +0000362
Chris Lattner3992f522008-01-27 22:58:59 +0000363 // Add in the library and framework paths
Reid Spenceraf303d52006-06-07 23:03:13 +0000364 for (unsigned index = 0; index < LibPaths.size(); index++) {
Chris Lattner3992f522008-01-27 22:58:59 +0000365 args.push_back("-L" + LibPaths[index]);
366 }
367 for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
368 args.push_back("-F" + FrameworkPaths[index]);
Reid Spenceraf303d52006-06-07 23:03:13 +0000369 }
370
371 // Add the requested options
Chris Lattner03a1c7a2008-01-09 01:01:17 +0000372 for (unsigned index = 0; index < XLinker.size(); index++)
Chris Lattner3f931b82007-06-19 16:46:48 +0000373 args.push_back(XLinker[index]);
Reid Spenceraf303d52006-06-07 23:03:13 +0000374
Reid Spencer445564a2004-11-20 20:02:56 +0000375 // Add in the libraries to link.
Reid Spencer49521432006-11-11 11:54:25 +0000376 for (unsigned index = 0; index < LinkItems.size(); index++)
377 if (LinkItems[index].first != "crtend") {
Chris Lattner3f931b82007-06-19 16:46:48 +0000378 if (LinkItems[index].second)
379 args.push_back("-l" + LinkItems[index].first);
380 else
381 args.push_back(LinkItems[index].first);
Reid Spencerf6358c72004-12-19 18:00:56 +0000382 }
Reid Spenceraf303d52006-06-07 23:03:13 +0000383
Chris Lattner3992f522008-01-27 22:58:59 +0000384 // Add in frameworks to link.
385 for (unsigned index = 0; index < Frameworks.size(); index++) {
386 args.push_back("-framework");
387 args.push_back(Frameworks[index]);
388 }
Chris Lattner3f931b82007-06-19 16:46:48 +0000389
390 // Now that "args" owns all the std::strings for the arguments, call the c_str
391 // method to get the underlying string array. We do this game so that the
392 // std::string array is guaranteed to outlive the const char* array.
393 std::vector<const char *> Args;
394 for (unsigned i = 0, e = args.size(); i != e; ++i)
395 Args.push_back(args[i].c_str());
396 Args.push_back(0);
Reid Spencer445564a2004-11-20 20:02:56 +0000397
Reid Spencer3b726392007-04-29 23:59:47 +0000398 if (Verbose) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000399 outs() << "Generating Native Executable With:\n";
Chris Lattner3f931b82007-06-19 16:46:48 +0000400 PrintCommand(Args);
Reid Spencer3b726392007-04-29 23:59:47 +0000401 }
402
Reid Spencer445564a2004-11-20 20:02:56 +0000403 // Run the compiler to assembly and link together the program.
Reid Spencer8ea5ecb2006-08-21 06:04:45 +0000404 int R = sys::Program::ExecuteAndWait(
Chris Lattner3f931b82007-06-19 16:46:48 +0000405 gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
Chris Lattner2f863622006-05-14 18:38:13 +0000406 delete [] clean_env;
407 return R;
Reid Spencer445564a2004-11-20 20:02:56 +0000408}
409
Reid Spencerc0af3f02004-09-13 01:27:53 +0000410/// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
Gabor Greifa99be512007-07-05 17:07:56 +0000411/// bitcode file for the program.
Chris Lattner25c54c02010-03-23 21:59:43 +0000412static void EmitShellScript(char **argv, Module *M) {
Reid Spencer3b726392007-04-29 23:59:47 +0000413 if (Verbose)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000414 outs() << "Emitting Shell Script\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000415#if defined(_WIN32) || defined(__CYGWIN__)
416 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
417 // support windows systems, we copy the llvm-stub.exe executable from the
418 // build tree to the destination file.
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000419 std::string ErrMsg;
Dan Gohman197f7282009-08-05 20:21:17 +0000420 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0],
Dan Gohman8608cf22009-08-05 21:03:39 +0000421 (void *)(intptr_t)&Optimize);
Reid Spencer708585a2007-02-09 03:08:06 +0000422 if (llvmstub.isEmpty())
Chris Lattner25c54c02010-03-23 21:59:43 +0000423 PrintAndExit("Could not find llvm-stub.exe executable!", M);
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000424
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000425 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000426 PrintAndExit(ErrMsg, M);
Anton Korobeynikov7d515442006-09-01 20:35:17 +0000427
Reid Spencerc0af3f02004-09-13 01:27:53 +0000428 return;
429#endif
430
431 // Output the script to start the program...
Dan Gohmanac95cc72009-07-16 15:30:09 +0000432 std::string ErrorInfo;
Dan Gohmanbaa26392009-08-25 15:34:52 +0000433 raw_fd_ostream Out2(OutputFilename.c_str(), ErrorInfo);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000434 if (!ErrorInfo.empty())
Chris Lattner25c54c02010-03-23 21:59:43 +0000435 PrintAndExit(ErrorInfo, M);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000436
437 Out2 << "#!/bin/sh\n";
438 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
439 Out2 << "lli=${LLVMINTERP-lli}\n";
440 Out2 << "exec $lli \\\n";
441 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
442 LibPaths.push_back("/lib");
443 LibPaths.push_back("/usr/lib");
444 LibPaths.push_back("/usr/X11R6/lib");
445 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
446 // shared object at all! See RH 8: plain text.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000447 std::vector<std::string>::iterator libc =
Reid Spencerc0af3f02004-09-13 01:27:53 +0000448 std::find(Libraries.begin(), Libraries.end(), "c");
449 if (libc != Libraries.end()) Libraries.erase(libc);
450 // List all the shared object (native) libraries this executable will need
451 // on the command line, so that we don't have to do this manually!
Misha Brukman3da94ae2005-04-22 00:00:37 +0000452 for (std::vector<std::string>::iterator i = Libraries.begin(),
Reid Spencerc0af3f02004-09-13 01:27:53 +0000453 e = Libraries.end(); i != e; ++i) {
Chris Lattner5d5a8972009-01-05 19:01:32 +0000454 // try explicit -L arguments first:
455 sys::Path FullLibraryPath;
456 for (cl::list<std::string>::const_iterator P = LibPaths.begin(),
457 E = LibPaths.end(); P != E; ++P) {
458 FullLibraryPath = *P;
459 FullLibraryPath.appendComponent("lib" + *i);
460 FullLibraryPath.appendSuffix(&(LTDL_SHLIB_EXT[1]));
461 if (!FullLibraryPath.isEmpty()) {
462 if (!FullLibraryPath.isDynamicLibrary()) {
463 // Not a native shared library; mark as invalid
464 FullLibraryPath = sys::Path();
465 } else break;
466 }
467 }
468 if (FullLibraryPath.isEmpty())
469 FullLibraryPath = sys::Path::FindLibrary(*i);
470 if (!FullLibraryPath.isEmpty())
Chris Lattner74382b72009-08-23 22:45:37 +0000471 Out2 << " -load=" << FullLibraryPath.str() << " \\\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000472 }
Sanjiv Guptad7de7bc2009-07-22 18:41:45 +0000473 Out2 << " " << BitcodeOutputFilename << " ${1+\"$@\"}\n";
Reid Spencerc0af3f02004-09-13 01:27:53 +0000474 Out2.close();
475}
476
Reid Spencerc4064132004-12-13 03:01:14 +0000477// BuildLinkItems -- This function generates a LinkItemList for the LinkItems
478// linker function by combining the Files and Libraries in the order they were
479// declared on the command line.
480static void BuildLinkItems(
481 Linker::ItemList& Items,
482 const cl::list<std::string>& Files,
483 const cl::list<std::string>& Libraries) {
484
Misha Brukman3da94ae2005-04-22 00:00:37 +0000485 // Build the list of linkage items for LinkItems.
Reid Spencerc4064132004-12-13 03:01:14 +0000486
487 cl::list<std::string>::const_iterator fileIt = Files.begin();
488 cl::list<std::string>::const_iterator libIt = Libraries.begin();
489
490 int libPos = -1, filePos = -1;
Reid Spencer05f7e792004-12-13 17:18:19 +0000491 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
Reid Spencerc4064132004-12-13 03:01:14 +0000492 if (libIt != Libraries.end())
493 libPos = Libraries.getPosition(libIt - Libraries.begin());
494 else
495 libPos = -1;
496 if (fileIt != Files.end())
497 filePos = Files.getPosition(fileIt - Files.begin());
498 else
499 filePos = -1;
500
501 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
502 // Add a source file
503 Items.push_back(std::make_pair(*fileIt++, false));
504 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
505 // Add a library
506 Items.push_back(std::make_pair(*libIt++, true));
Reid Spencerc4064132004-12-13 03:01:14 +0000507 }
508 }
509}
510
Reid Spencerc0af3f02004-09-13 01:27:53 +0000511int main(int argc, char **argv, char **envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000512 // Print a stack trace if we signal out.
513 sys::PrintStackTraceOnErrorSignal();
514 PrettyStackTraceProgram X(argc, argv);
Owen Anderson8b477ed2009-07-01 16:58:40 +0000515
Owen Anderson0d7c6952009-07-15 22:16:10 +0000516 LLVMContext &Context = getGlobalContext();
Chris Lattnercc14d252009-03-06 05:34:10 +0000517 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
Chris Lattner316e3262009-10-22 00:52:28 +0000518
519 // Initial global variable above for convenience printing of program name.
520 progname = sys::Path(argv[0]).getBasename();
Misha Brukman3da94ae2005-04-22 00:00:37 +0000521
Chris Lattner316e3262009-10-22 00:52:28 +0000522 // Parse the command line options
523 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
Reid Spencerc0af3f02004-09-13 01:27:53 +0000524
Chris Lattner316e3262009-10-22 00:52:28 +0000525 // Construct a Linker (now that Verbose is set)
526 Linker TheLinker(progname, OutputFilename, Context, Verbose);
Reid Spencerc82a5da2007-04-04 06:34:22 +0000527
Chris Lattner316e3262009-10-22 00:52:28 +0000528 // Keep track of the native link items (versus the bitcode items)
529 Linker::ItemList NativeLinkItems;
Reid Spencer49521432006-11-11 11:54:25 +0000530
Chris Lattner316e3262009-10-22 00:52:28 +0000531 // Add library paths to the linker
532 TheLinker.addPaths(LibPaths);
533 TheLinker.addSystemPaths();
Reid Spencer78df5c32006-03-06 06:38:19 +0000534
Chris Lattner316e3262009-10-22 00:52:28 +0000535 // Remove any consecutive duplicates of the same library...
536 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
537 Libraries.end());
Reid Spencerc0af3f02004-09-13 01:27:53 +0000538
Chris Lattner316e3262009-10-22 00:52:28 +0000539 if (LinkAsLibrary) {
540 std::vector<sys::Path> Files;
541 for (unsigned i = 0; i < InputFilenames.size(); ++i )
542 Files.push_back(sys::Path(InputFilenames[i]));
543 if (TheLinker.LinkInFiles(Files))
544 return 1; // Error already printed
Reid Spencer6b463b22004-12-08 05:17:40 +0000545
Chris Lattner316e3262009-10-22 00:52:28 +0000546 // The libraries aren't linked in but are noted as "dependent" in the
547 // module.
548 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
549 E = Libraries.end(); I != E ; ++I) {
550 TheLinker.getModule()->addLibrary(*I);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000551 }
Chris Lattner316e3262009-10-22 00:52:28 +0000552 } else {
553 // Build a list of the items from our command line
554 Linker::ItemList Items;
555 BuildLinkItems(Items, InputFilenames, Libraries);
Reid Spencerc0af3f02004-09-13 01:27:53 +0000556
Chris Lattner316e3262009-10-22 00:52:28 +0000557 // Link all the items together
558 if (TheLinker.LinkInItems(Items, NativeLinkItems) )
559 return 1; // Error already printed
560 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000561
Chris Lattner316e3262009-10-22 00:52:28 +0000562 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
563
564 // Optimize the module
565 Optimize(Composite.get());
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000566
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000567#if defined(_WIN32) || defined(__CYGWIN__)
Chris Lattner316e3262009-10-22 00:52:28 +0000568 if (!LinkAsLibrary) {
569 // Default to "a.exe" instead of "a.out".
570 if (OutputFilename.getNumOccurrences() == 0)
571 OutputFilename = "a.exe";
Argyrios Kyrtzidis48cca1f2008-06-15 15:20:16 +0000572
Chris Lattner316e3262009-10-22 00:52:28 +0000573 // If there is no suffix add an "exe" one.
574 sys::Path ExeFile( OutputFilename );
575 if (ExeFile.getSuffix() == "") {
576 ExeFile.appendSuffix("exe");
577 OutputFilename = ExeFile.str();
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000578 }
Chris Lattner316e3262009-10-22 00:52:28 +0000579 }
Argyrios Kyrtzidis16621832008-06-15 13:48:12 +0000580#endif
581
Chris Lattner316e3262009-10-22 00:52:28 +0000582 // Generate the bitcode for the optimized module.
583 // If -b wasn't specified, use the name specified
584 // with -o to construct BitcodeOutputFilename.
585 if (BitcodeOutputFilename.empty()) {
586 BitcodeOutputFilename = OutputFilename;
587 if (!LinkAsLibrary) BitcodeOutputFilename += ".bc";
588 }
Argyrios Kyrtzidis5b90a722008-06-15 12:01:16 +0000589
Chris Lattner316e3262009-10-22 00:52:28 +0000590 GenerateBitcode(Composite.get(), BitcodeOutputFilename);
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000591
Chris Lattner316e3262009-10-22 00:52:28 +0000592 // If we are not linking a library, generate either a native executable
593 // or a JIT shell script, depending upon what the user wants.
594 if (!LinkAsLibrary) {
595 // If the user wants to run a post-link optimization, run it now.
596 if (!PostLinkOpts.empty()) {
597 std::vector<std::string> opts = PostLinkOpts;
598 for (std::vector<std::string>::iterator I = opts.begin(),
599 E = opts.end(); I != E; ++I) {
600 sys::Path prog(*I);
601 if (!prog.canExecute()) {
602 prog = sys::Program::FindProgramByName(*I);
603 if (prog.isEmpty())
604 PrintAndExit(std::string("Optimization program '") + *I +
Chris Lattner25c54c02010-03-23 21:59:43 +0000605 "' is not found or not executable.", Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000606 }
607 // Get the program arguments
608 sys::Path tmp_output("opt_result");
609 std::string ErrMsg;
610 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000611 PrintAndExit(ErrMsg, Composite.get());
Reid Spencer708585a2007-02-09 03:08:06 +0000612
Chris Lattner316e3262009-10-22 00:52:28 +0000613 const char* args[4];
614 args[0] = I->c_str();
615 args[1] = BitcodeOutputFilename.c_str();
616 args[2] = tmp_output.c_str();
617 args[3] = 0;
618 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
619 if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
620 sys::Path target(BitcodeOutputFilename);
621 target.eraseFromDisk();
622 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000623 PrintAndExit(ErrMsg, Composite.get(), 2);
Chris Lattner316e3262009-10-22 00:52:28 +0000624 } else
Chris Lattner25c54c02010-03-23 21:59:43 +0000625 PrintAndExit("Post-link optimization output is not bitcode",
626 Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000627 } else {
Chris Lattner25c54c02010-03-23 21:59:43 +0000628 PrintAndExit(ErrMsg, Composite.get());
Reid Spencer73a74be2005-12-21 05:03:23 +0000629 }
630 }
Reid Spencer708585a2007-02-09 03:08:06 +0000631 }
Chris Lattner316e3262009-10-22 00:52:28 +0000632
633 // If the user wants to generate a native executable, compile it from the
634 // bitcode file.
635 //
636 // Otherwise, create a script that will run the bitcode through the JIT.
637 if (Native) {
638 // Name of the Assembly Language output file
639 sys::Path AssemblyFile ( OutputFilename);
640 AssemblyFile.appendSuffix("s");
641
642 // Mark the output files for removal if we get an interrupt.
643 sys::RemoveFileOnSignal(AssemblyFile);
644 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
645
646 // Determine the locations of the llc and gcc programs.
647 sys::Path llc = FindExecutable("llc", argv[0],
648 (void *)(intptr_t)&Optimize);
649 if (llc.isEmpty())
Chris Lattner25c54c02010-03-23 21:59:43 +0000650 PrintAndExit("Failed to find llc", Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000651
652 sys::Path gcc = sys::Program::FindProgramByName("gcc");
653 if (gcc.isEmpty())
Chris Lattner25c54c02010-03-23 21:59:43 +0000654 PrintAndExit("Failed to find gcc", Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000655
656 // Generate an assembly language file for the bitcode.
657 std::string ErrMsg;
658 if (0 != GenerateAssembly(AssemblyFile.str(), BitcodeOutputFilename,
659 llc, ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000660 PrintAndExit(ErrMsg, Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000661
662 if (0 != GenerateNative(OutputFilename, AssemblyFile.str(),
663 NativeLinkItems, gcc, envp, ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000664 PrintAndExit(ErrMsg, Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000665
666 // Remove the assembly language file.
667 AssemblyFile.eraseFromDisk();
668 } else if (NativeCBE) {
669 sys::Path CFile (OutputFilename);
670 CFile.appendSuffix("cbe.c");
671
672 // Mark the output files for removal if we get an interrupt.
673 sys::RemoveFileOnSignal(CFile);
674 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
675
676 // Determine the locations of the llc and gcc programs.
677 sys::Path llc = FindExecutable("llc", argv[0],
678 (void *)(intptr_t)&Optimize);
679 if (llc.isEmpty())
Chris Lattner25c54c02010-03-23 21:59:43 +0000680 PrintAndExit("Failed to find llc", Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000681
682 sys::Path gcc = sys::Program::FindProgramByName("gcc");
683 if (gcc.isEmpty())
Chris Lattner25c54c02010-03-23 21:59:43 +0000684 PrintAndExit("Failed to find gcc", Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000685
686 // Generate an assembly language file for the bitcode.
687 std::string ErrMsg;
688 if (GenerateCFile(CFile.str(), BitcodeOutputFilename, llc, ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000689 PrintAndExit(ErrMsg, Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000690
691 if (GenerateNative(OutputFilename, CFile.str(),
692 NativeLinkItems, gcc, envp, ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000693 PrintAndExit(ErrMsg, Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000694
695 // Remove the assembly language file.
696 CFile.eraseFromDisk();
697
698 } else {
Chris Lattner25c54c02010-03-23 21:59:43 +0000699 EmitShellScript(argv, Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000700 }
701
702 // Make the script executable...
703 std::string ErrMsg;
704 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000705 PrintAndExit(ErrMsg, Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000706
707 // Make the bitcode file readable and directly executable in LLEE as well
708 if (sys::Path(BitcodeOutputFilename).makeExecutableOnDisk(&ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000709 PrintAndExit(ErrMsg, Composite.get());
Chris Lattner316e3262009-10-22 00:52:28 +0000710
711 if (sys::Path(BitcodeOutputFilename).makeReadableOnDisk(&ErrMsg))
Chris Lattner25c54c02010-03-23 21:59:43 +0000712 PrintAndExit(ErrMsg, Composite.get());
Reid Spencerc0af3f02004-09-13 01:27:53 +0000713 }
Reid Spencer708585a2007-02-09 03:08:06 +0000714
715 // Graceful exit
716 return 0;
Reid Spencerc0af3f02004-09-13 01:27:53 +0000717}