1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
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.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/Linker.h"
24 #include "llvm/System/Program.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Bytecode/Reader.h"
28 #include "llvm/Bytecode/Writer.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/System/Signals.h"
42 // Input/Output Options
43 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
44 cl::desc("<input bytecode files>"));
46 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
47 cl::desc("Override output filename"),
48 cl::value_desc("filename"));
50 static cl::opt<bool> Verbose("v",
51 cl::desc("Print information about actions taken"));
53 static cl::list<std::string> LibPaths("L", cl::Prefix,
54 cl::desc("Specify a library search path"),
55 cl::value_desc("directory"));
57 static cl::list<std::string> Libraries("l", cl::Prefix,
58 cl::desc("Specify libraries to link to"),
59 cl::value_desc("library prefix"));
61 static cl::opt<bool> LinkAsLibrary("link-as-library",
62 cl::desc("Link the .bc files together as a library, not an executable"));
64 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
65 cl::desc("Alias for -link-as-library"));
67 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
68 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
70 static cl::opt<bool> Native("native",
71 cl::desc("Generate a native binary instead of a shell script"));
73 static cl::opt<bool>NativeCBE("native-cbe",
74 cl::desc("Generate a native binary with the C backend and GCC"));
76 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
77 cl::desc("Disable writing of compressed bytecode files"));
79 static cl::list<std::string> PostLinkOpts("post-link-opts",
80 cl::value_desc("path to post-link optimization programs"),
81 cl::desc("Run one or more optimization programs after linking"));
83 // Compatibility options that are ignored but supported by LD
84 static cl::opt<std::string> CO3("soname", cl::Hidden,
85 cl::desc("Compatibility option: ignored"));
87 static cl::opt<std::string> CO4("version-script", cl::Hidden,
88 cl::desc("Compatibility option: ignored"));
90 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
91 cl::desc("Compatibility option: ignored"));
93 static cl::opt<std::string> CO6("h", cl::Hidden,
94 cl::desc("Compatibility option: ignored"));
96 /// This is just for convenience so it doesn't have to be passed around
98 static std::string progname;
100 /// PrintAndReturn - Prints a message to standard error and returns true.
103 /// progname - The name of the program (i.e. argv[0]).
104 /// Message - The message to print to standard error.
106 static int PrintAndReturn(const std::string &Message) {
107 std::cerr << progname << ": " << Message << "\n";
111 /// CopyEnv - This function takes an array of environment variables and makes a
112 /// copy of it. This copy can then be manipulated any way the caller likes
113 /// without affecting the process's real environment.
116 /// envp - An array of C strings containing an environment.
119 /// NULL - An error occurred.
121 /// Otherwise, a pointer to a new array of C strings is returned. Every string
122 /// in the array is a duplicate of the one in the original array (i.e. we do
123 /// not copy the char *'s from one array to another).
125 static char ** CopyEnv(char ** const envp) {
126 // Count the number of entries in the old list;
127 unsigned entries; // The number of entries in the old environment list
128 for (entries = 0; envp[entries] != NULL; entries++)
131 // Add one more entry for the NULL pointer that ends the list.
134 // If there are no entries at all, just return NULL.
138 // Allocate a new environment list.
139 char **newenv = new char* [entries];
140 if ((newenv = new char* [entries]) == NULL)
143 // Make a copy of the list. Don't forget the NULL that ends the list.
145 while (envp[entries] != NULL) {
146 newenv[entries] = new char[strlen (envp[entries]) + 1];
147 strcpy (newenv[entries], envp[entries]);
150 newenv[entries] = NULL;
156 /// RemoveEnv - Remove the specified environment variable from the environment
160 /// name - The name of the variable to remove. It cannot be NULL.
161 /// envp - The array of environment variables. It cannot be NULL.
164 /// This is mainly done because functions to remove items from the environment
165 /// are not available across all platforms. In particular, Solaris does not
166 /// seem to have an unsetenv() function or a setenv() function (or they are
167 /// undocumented if they do exist).
169 static void RemoveEnv(const char * name, char ** const envp) {
170 for (unsigned index=0; envp[index] != NULL; index++) {
171 // Find the first equals sign in the array and make it an EOS character.
172 char *p = strchr (envp[index], '=');
178 // Compare the two strings. If they are equal, zap this string.
179 // Otherwise, restore it.
180 if (!strcmp(name, envp[index]))
189 /// GenerateBytecode - generates a bytecode file from the module provided
190 void GenerateBytecode(Module* M, const std::string& FileName) {
192 // Create the output file.
193 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
195 std::ofstream Out(FileName.c_str(), io_mode);
197 PrintAndReturn("error opening '" + FileName + "' for writing!");
201 // Ensure that the bytecode file gets removed from the disk if we get a
202 // terminating signal.
203 sys::RemoveFileOnSignal(sys::Path(FileName));
206 WriteBytecodeToFile(M, Out, !DisableCompression);
208 // Close the bytecode file.
212 /// GenerateAssembly - generates a native assembly language source file from the
213 /// specified bytecode file.
216 /// InputFilename - The name of the output bytecode file.
217 /// OutputFilename - The name of the file to generate.
218 /// llc - The pathname to use for LLC.
219 /// envp - The environment to use when running LLC.
221 /// Return non-zero value on error.
223 static int GenerateAssembly(const std::string &OutputFilename,
224 const std::string &InputFilename,
225 const sys::Path &llc) {
226 // Run LLC to convert the bytecode file into assembly code.
227 std::vector<const char*> args;
228 args.push_back(llc.c_str());
229 args.push_back("-f");
230 args.push_back("-o");
231 args.push_back(OutputFilename.c_str());
232 args.push_back(InputFilename.c_str());
235 return sys::Program::ExecuteAndWait(llc,&args[0]);
238 /// GenerateAssembly - generates a native assembly language source file from the
239 /// specified bytecode file.
240 static int GenerateCFile(const std::string &OutputFile,
241 const std::string &InputFile,
242 const sys::Path &llc) {
243 // Run LLC to convert the bytecode file into C.
244 std::vector<const char*> args;
245 args.push_back(llc.c_str());
246 args.push_back("-march=c");
247 args.push_back("-f");
248 args.push_back("-o");
249 args.push_back(OutputFile.c_str());
250 args.push_back(InputFile.c_str());
252 return sys::Program::ExecuteAndWait(llc, &args[0]);
255 /// GenerateNative - generates a native assembly language source file from the
256 /// specified assembly source file.
259 /// InputFilename - The name of the output bytecode file.
260 /// OutputFilename - The name of the file to generate.
261 /// Libraries - The list of libraries with which to link.
262 /// LibPaths - The list of directories in which to find libraries.
263 /// gcc - The pathname to use for GGC.
264 /// envp - A copy of the process's current environment.
269 /// Returns non-zero value on error.
271 static int GenerateNative(const std::string &OutputFilename,
272 const std::string &InputFilename,
273 const std::vector<std::string> &Libraries,
274 const sys::Path &gcc, char ** const envp) {
275 // Remove these environment variables from the environment of the
276 // programs that we will execute. It appears that GCC sets these
277 // environment variables so that the programs it uses can configure
278 // themselves identically.
280 // However, when we invoke GCC below, we want it to use its normal
281 // configuration. Hence, we must sanitize its environment.
282 char ** clean_env = CopyEnv(envp);
283 if (clean_env == NULL)
285 RemoveEnv("LIBRARY_PATH", clean_env);
286 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
287 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
288 RemoveEnv("COMPILER_PATH", clean_env);
289 RemoveEnv("COLLECT_GCC", clean_env);
292 // Run GCC to assemble and link the program into native code.
295 // We can't just assemble and link the file with the system assembler
296 // and linker because we don't know where to put the _start symbol.
297 // GCC mysteriously knows how to do it.
298 std::vector<const char*> args;
299 args.push_back(gcc.c_str());
300 args.push_back("-fno-strict-aliasing");
301 args.push_back("-O3");
302 args.push_back("-o");
303 args.push_back(OutputFilename.c_str());
304 args.push_back(InputFilename.c_str());
306 // Add in the libraries to link.
307 for (unsigned index = 0; index < Libraries.size(); index++)
308 if (Libraries[index] != "crtend") {
309 args.push_back("-l");
310 args.push_back(Libraries[index].c_str());
314 // Run the compiler to assembly and link together the program.
315 return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
318 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
319 /// bytecode file for the program.
320 static void EmitShellScript(char **argv) {
321 #if defined(_WIN32) || defined(__CYGWIN__)
322 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
323 // support windows systems, we copy the llvm-stub.exe executable from the
324 // build tree to the destination file.
325 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
326 if (llvmstub.isEmpty()) {
327 std::cerr << "Could not find llvm-stub.exe executable!\n";
330 sys::CopyFile(sys::Path(OutputFilename), llvmstub);
334 // Output the script to start the program...
335 std::ofstream Out2(OutputFilename.c_str());
337 exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
339 Out2 << "#!/bin/sh\n";
340 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
341 Out2 << "lli=${LLVMINTERP-lli}\n";
342 Out2 << "exec $lli \\\n";
343 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
344 LibPaths.push_back("/lib");
345 LibPaths.push_back("/usr/lib");
346 LibPaths.push_back("/usr/X11R6/lib");
347 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
348 // shared object at all! See RH 8: plain text.
349 std::vector<std::string>::iterator libc =
350 std::find(Libraries.begin(), Libraries.end(), "c");
351 if (libc != Libraries.end()) Libraries.erase(libc);
352 // List all the shared object (native) libraries this executable will need
353 // on the command line, so that we don't have to do this manually!
354 for (std::vector<std::string>::iterator i = Libraries.begin(),
355 e = Libraries.end(); i != e; ++i) {
356 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
357 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
358 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
360 Out2 << " $0.bc ${1+\"$@\"}\n";
364 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
365 // linker function by combining the Files and Libraries in the order they were
366 // declared on the command line.
367 static void BuildLinkItems(
368 Linker::ItemList& Items,
369 const cl::list<std::string>& Files,
370 const cl::list<std::string>& Libraries) {
372 // Build the list of linkage items for LinkItems.
374 cl::list<std::string>::const_iterator fileIt = Files.begin();
375 cl::list<std::string>::const_iterator libIt = Libraries.begin();
377 int libPos = -1, filePos = -1;
378 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
379 if (libIt != Libraries.end())
380 libPos = Libraries.getPosition(libIt - Libraries.begin());
383 if (fileIt != Files.end())
384 filePos = Files.getPosition(fileIt - Files.begin());
388 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
390 Items.push_back(std::make_pair(*fileIt++, false));
391 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
393 Items.push_back(std::make_pair(*libIt++, true));
398 // Rightly this should go in a header file but it just seems such a waste.
400 extern void Optimize(Module*);
403 int main(int argc, char **argv, char **envp) {
405 // Initial global variable above for convenience printing of program name.
406 progname = sys::Path(argv[0]).getBasename();
407 Linker TheLinker(progname, OutputFilename, Verbose);
409 // Set up the library paths for the Linker
410 TheLinker.addPaths(LibPaths);
411 TheLinker.addSystemPaths();
413 // Parse the command line options
414 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
415 sys::PrintStackTraceOnErrorSignal();
417 // Remove any consecutive duplicates of the same library...
418 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
422 std::vector<sys::Path> Files;
423 for (unsigned i = 0; i < InputFilenames.size(); ++i )
424 Files.push_back(sys::Path(InputFilenames[i]));
425 if (TheLinker.LinkInFiles(Files))
426 return 1; // Error already printed
428 // The libraries aren't linked in but are noted as "dependent" in the
430 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
431 E = Libraries.end(); I != E ; ++I) {
432 TheLinker.getModule()->addLibrary(*I);
435 // Build a list of the items from our command line
436 Linker::ItemList Items;
437 BuildLinkItems(Items, InputFilenames, Libraries);
439 // Link all the items together
440 if (TheLinker.LinkInItems(Items) )
444 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
446 // Optimize the module
447 Optimize(Composite.get());
449 // Generate the bytecode for the optimized module.
450 std::string RealBytecodeOutput = OutputFilename;
451 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
452 GenerateBytecode(Composite.get(), RealBytecodeOutput);
454 // If we are not linking a library, generate either a native executable
455 // or a JIT shell script, depending upon what the user wants.
456 if (!LinkAsLibrary) {
457 // If the user wants to run a post-link optimization, run it now.
458 if (!PostLinkOpts.empty()) {
459 std::vector<std::string> opts = PostLinkOpts;
460 for (std::vector<std::string>::iterator I = opts.begin(),
461 E = opts.end(); I != E; ++I) {
463 if (!prog.canExecute()) {
464 prog = sys::Program::FindProgramByName(*I);
466 return PrintAndReturn(std::string("Optimization program '") + *I +
467 "' is not found or not executable.");
469 // Get the program arguments
470 sys::Path tmp_output("opt_result");
471 if (!tmp_output.createTemporaryFileOnDisk()) {
472 return PrintAndReturn(
473 "Can't create temporary file for post-link optimization");
476 args[0] = I->c_str();
477 args[1] = RealBytecodeOutput.c_str();
478 args[2] = tmp_output.c_str();
480 if (0 == sys::Program::ExecuteAndWait(prog, args)) {
481 if (tmp_output.isBytecodeFile()) {
482 sys::Path target(RealBytecodeOutput);
483 target.eraseFromDisk();
484 tmp_output.renamePathOnDisk(target);
486 return PrintAndReturn(
487 "Post-link optimization output is not bytecode");
492 // If the user wants to generate a native executable, compile it from the
495 // Otherwise, create a script that will run the bytecode through the JIT.
497 // Name of the Assembly Language output file
498 sys::Path AssemblyFile ( OutputFilename);
499 AssemblyFile.appendSuffix("s");
501 // Mark the output files for removal if we get an interrupt.
502 sys::RemoveFileOnSignal(AssemblyFile);
503 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
505 // Determine the locations of the llc and gcc programs.
506 sys::Path llc = FindExecutable("llc", argv[0]);
508 return PrintAndReturn("Failed to find llc");
510 sys::Path gcc = FindExecutable("gcc", argv[0]);
512 return PrintAndReturn("Failed to find gcc");
514 // Generate an assembly language file for the bytecode.
515 if (Verbose) std::cout << "Generating Assembly Code\n";
516 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
517 if (Verbose) std::cout << "Generating Native Code\n";
518 GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
521 // Remove the assembly language file.
522 AssemblyFile.eraseFromDisk();
523 } else if (NativeCBE) {
524 sys::Path CFile (OutputFilename);
525 CFile.appendSuffix("cbe.c");
527 // Mark the output files for removal if we get an interrupt.
528 sys::RemoveFileOnSignal(CFile);
529 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
531 // Determine the locations of the llc and gcc programs.
532 sys::Path llc = FindExecutable("llc", argv[0]);
534 return PrintAndReturn("Failed to find llc");
536 sys::Path gcc = FindExecutable("gcc", argv[0]);
538 return PrintAndReturn("Failed to find gcc");
540 // Generate an assembly language file for the bytecode.
541 if (Verbose) std::cout << "Generating Assembly Code\n";
542 GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
543 if (Verbose) std::cout << "Generating Native Code\n";
544 GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
546 // Remove the assembly language file.
547 CFile.eraseFromDisk();
550 EmitShellScript(argv);
553 // Make the script executable...
554 sys::Path(OutputFilename).makeExecutableOnDisk();
556 // Make the bytecode file readable and directly executable in LLEE as well
557 sys::Path(RealBytecodeOutput).makeExecutableOnDisk();
558 sys::Path(RealBytecodeOutput).makeReadableOnDisk();
562 } catch (const std::string& msg) {
563 std::cerr << argv[0] << ": " << msg << "\n";
565 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";