1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 bitcode 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/LinkAllVMCore.h"
24 #include "llvm/Linker.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/System/Program.h"
27 #include "llvm/Module.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Bitcode/ReaderWriter.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetMachineRegistry.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileUtilities.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/Streams.h"
39 #include "llvm/Support/SystemUtils.h"
40 #include "llvm/System/Signals.h"
41 #include "llvm/Config/config.h"
47 // Input/Output Options
48 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
49 cl::desc("<input bitcode files>"));
51 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
52 cl::desc("Override output filename"),
53 cl::value_desc("filename"));
55 static cl::opt<bool> Verbose("v",
56 cl::desc("Print information about actions taken"));
58 static cl::list<std::string> LibPaths("L", cl::Prefix,
59 cl::desc("Specify a library search path"),
60 cl::value_desc("directory"));
62 static cl::list<std::string> FrameworkPaths("F", cl::Prefix,
63 cl::desc("Specify a framework search path"),
64 cl::value_desc("directory"));
66 static cl::list<std::string> Libraries("l", cl::Prefix,
67 cl::desc("Specify libraries to link to"),
68 cl::value_desc("library prefix"));
70 static cl::list<std::string> Frameworks("framework",
71 cl::desc("Specify frameworks to link to"),
72 cl::value_desc("framework"));
74 // Options to control the linking, optimization, and code gen processes
75 static cl::opt<bool> LinkAsLibrary("link-as-library",
76 cl::desc("Link the .bc files together as a library, not an executable"));
78 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
79 cl::desc("Alias for -link-as-library"));
81 static cl::opt<bool> Native("native",
82 cl::desc("Generate a native binary instead of a shell script"));
84 static cl::opt<bool>NativeCBE("native-cbe",
85 cl::desc("Generate a native binary with the C backend and GCC"));
87 static cl::list<std::string> PostLinkOpts("post-link-opts",
88 cl::value_desc("path"),
89 cl::desc("Run one or more optimization programs after linking"));
91 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
92 cl::desc("Pass options to the system linker"));
94 // Compatibility options that llvm-ld ignores but are supported for
95 // compatibility with LD
96 static cl::opt<std::string> CO3("soname", cl::Hidden,
97 cl::desc("Compatibility option: ignored"));
99 static cl::opt<std::string> CO4("version-script", cl::Hidden,
100 cl::desc("Compatibility option: ignored"));
102 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
103 cl::desc("Compatibility option: ignored"));
105 static cl::opt<std::string> CO6("h", cl::Hidden,
106 cl::desc("Compatibility option: ignored"));
108 static cl::opt<bool> CO7("start-group", cl::Hidden,
109 cl::desc("Compatibility option: ignored"));
111 static cl::opt<bool> CO8("end-group", cl::Hidden,
112 cl::desc("Compatibility option: ignored"));
114 static cl::opt<std::string> CO9("m", cl::Hidden,
115 cl::desc("Compatibility option: ignored"));
117 /// This is just for convenience so it doesn't have to be passed around
119 static std::string progname;
121 /// PrintAndExit - Prints a message to standard error and exits with error code
124 /// Message - The message to print to standard error.
126 static void PrintAndExit(const std::string &Message, int errcode = 1) {
127 cerr << progname << ": " << Message << "\n";
132 static void PrintCommand(const std::vector<const char*> &args) {
133 std::vector<const char*>::const_iterator I = args.begin(), E = args.end();
136 cout << "'" << *I << "'" << " ";
137 cout << "\n" << std::flush;
140 /// CopyEnv - This function takes an array of environment variables and makes a
141 /// copy of it. This copy can then be manipulated any way the caller likes
142 /// without affecting the process's real environment.
145 /// envp - An array of C strings containing an environment.
148 /// NULL - An error occurred.
150 /// Otherwise, a pointer to a new array of C strings is returned. Every string
151 /// in the array is a duplicate of the one in the original array (i.e. we do
152 /// not copy the char *'s from one array to another).
154 static char ** CopyEnv(char ** const envp) {
155 // Count the number of entries in the old list;
156 unsigned entries; // The number of entries in the old environment list
157 for (entries = 0; envp[entries] != NULL; entries++)
160 // Add one more entry for the NULL pointer that ends the list.
163 // If there are no entries at all, just return NULL.
167 // Allocate a new environment list.
168 char **newenv = new char* [entries];
169 if ((newenv = new char* [entries]) == NULL)
172 // Make a copy of the list. Don't forget the NULL that ends the list.
174 while (envp[entries] != NULL) {
175 newenv[entries] = new char[strlen (envp[entries]) + 1];
176 strcpy (newenv[entries], envp[entries]);
179 newenv[entries] = NULL;
185 /// RemoveEnv - Remove the specified environment variable from the environment
189 /// name - The name of the variable to remove. It cannot be NULL.
190 /// envp - The array of environment variables. It cannot be NULL.
193 /// This is mainly done because functions to remove items from the environment
194 /// are not available across all platforms. In particular, Solaris does not
195 /// seem to have an unsetenv() function or a setenv() function (or they are
196 /// undocumented if they do exist).
198 static void RemoveEnv(const char * name, char ** const envp) {
199 for (unsigned index=0; envp[index] != NULL; index++) {
200 // Find the first equals sign in the array and make it an EOS character.
201 char *p = strchr (envp[index], '=');
207 // Compare the two strings. If they are equal, zap this string.
208 // Otherwise, restore it.
209 if (!strcmp(name, envp[index]))
218 /// GenerateBitcode - generates a bitcode file from the module provided
219 void GenerateBitcode(Module* M, const std::string& FileName) {
222 cout << "Generating Bitcode To " << FileName << '\n';
224 // Create the output file.
225 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
227 std::ofstream Out(FileName.c_str(), io_mode);
229 PrintAndExit("error opening '" + FileName + "' for writing!");
231 // Ensure that the bitcode file gets removed from the disk if we get a
232 // terminating signal.
233 sys::RemoveFileOnSignal(sys::Path(FileName));
236 WriteBitcodeToFile(M, Out);
238 // Close the bitcode file.
242 /// GenerateAssembly - generates a native assembly language source file from the
243 /// specified bitcode file.
246 /// InputFilename - The name of the input bitcode file.
247 /// OutputFilename - The name of the file to generate.
248 /// llc - The pathname to use for LLC.
249 /// envp - The environment to use when running LLC.
251 /// Return non-zero value on error.
253 static int GenerateAssembly(const std::string &OutputFilename,
254 const std::string &InputFilename,
255 const sys::Path &llc,
256 std::string &ErrMsg ) {
257 // Run LLC to convert the bitcode file into assembly code.
258 std::vector<const char*> args;
259 args.push_back(llc.c_str());
260 // We will use GCC to assemble the program so set the assembly syntax to AT&T,
261 // regardless of what the target in the bitcode file is.
262 args.push_back("-x86-asm-syntax=att");
263 args.push_back("-f");
264 args.push_back("-o");
265 args.push_back(OutputFilename.c_str());
266 args.push_back(InputFilename.c_str());
270 cout << "Generating Assembly With: \n";
274 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
277 /// GenerateCFile - generates a C source file from the specified bitcode file.
278 static int GenerateCFile(const std::string &OutputFile,
279 const std::string &InputFile,
280 const sys::Path &llc,
281 std::string& ErrMsg) {
282 // Run LLC to convert the bitcode file into C.
283 std::vector<const char*> args;
284 args.push_back(llc.c_str());
285 args.push_back("-march=c");
286 args.push_back("-f");
287 args.push_back("-o");
288 args.push_back(OutputFile.c_str());
289 args.push_back(InputFile.c_str());
293 cout << "Generating C Source With: \n";
297 return sys::Program::ExecuteAndWait(llc, &args[0], 0, 0, 0, 0, &ErrMsg);
300 /// GenerateNative - generates a native object file from the
301 /// specified bitcode file.
304 /// InputFilename - The name of the input bitcode file.
305 /// OutputFilename - The name of the file to generate.
306 /// NativeLinkItems - The native libraries, files, code with which to link
307 /// LibPaths - The list of directories in which to find libraries.
308 /// FrameworksPaths - The list of directories in which to find frameworks.
309 /// Frameworks - The list of frameworks (dynamic libraries)
310 /// gcc - The pathname to use for GGC.
311 /// envp - A copy of the process's current environment.
316 /// Returns non-zero value on error.
318 static int GenerateNative(const std::string &OutputFilename,
319 const std::string &InputFilename,
320 const Linker::ItemList &LinkItems,
321 const sys::Path &gcc, char ** const envp,
322 std::string& ErrMsg) {
323 // Remove these environment variables from the environment of the
324 // programs that we will execute. It appears that GCC sets these
325 // environment variables so that the programs it uses can configure
326 // themselves identically.
328 // However, when we invoke GCC below, we want it to use its normal
329 // configuration. Hence, we must sanitize its environment.
330 char ** clean_env = CopyEnv(envp);
331 if (clean_env == NULL)
333 RemoveEnv("LIBRARY_PATH", clean_env);
334 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
335 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
336 RemoveEnv("COMPILER_PATH", clean_env);
337 RemoveEnv("COLLECT_GCC", clean_env);
340 // Run GCC to assemble and link the program into native code.
343 // We can't just assemble and link the file with the system assembler
344 // and linker because we don't know where to put the _start symbol.
345 // GCC mysteriously knows how to do it.
346 std::vector<std::string> args;
347 args.push_back(gcc.c_str());
348 args.push_back("-fno-strict-aliasing");
349 args.push_back("-O3");
350 args.push_back("-o");
351 args.push_back(OutputFilename);
352 args.push_back(InputFilename);
354 // Add in the library and framework paths
355 for (unsigned index = 0; index < LibPaths.size(); index++) {
356 args.push_back("-L" + LibPaths[index]);
358 for (unsigned index = 0; index < FrameworkPaths.size(); index++) {
359 args.push_back("-F" + FrameworkPaths[index]);
362 // Add the requested options
363 for (unsigned index = 0; index < XLinker.size(); index++)
364 args.push_back(XLinker[index]);
366 // Add in the libraries to link.
367 for (unsigned index = 0; index < LinkItems.size(); index++)
368 if (LinkItems[index].first != "crtend") {
369 if (LinkItems[index].second)
370 args.push_back("-l" + LinkItems[index].first);
372 args.push_back(LinkItems[index].first);
375 // Add in frameworks to link.
376 for (unsigned index = 0; index < Frameworks.size(); index++) {
377 args.push_back("-framework");
378 args.push_back(Frameworks[index]);
381 // Now that "args" owns all the std::strings for the arguments, call the c_str
382 // method to get the underlying string array. We do this game so that the
383 // std::string array is guaranteed to outlive the const char* array.
384 std::vector<const char *> Args;
385 for (unsigned i = 0, e = args.size(); i != e; ++i)
386 Args.push_back(args[i].c_str());
390 cout << "Generating Native Executable With:\n";
394 // Run the compiler to assembly and link together the program.
395 int R = sys::Program::ExecuteAndWait(
396 gcc, &Args[0], (const char**)clean_env, 0, 0, 0, &ErrMsg);
401 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
402 /// bitcode file for the program.
403 static void EmitShellScript(char **argv) {
405 cout << "Emitting Shell Script\n";
406 #if defined(_WIN32) || defined(__CYGWIN__)
407 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
408 // support windows systems, we copy the llvm-stub.exe executable from the
409 // build tree to the destination file.
411 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
412 if (llvmstub.isEmpty())
413 PrintAndExit("Could not find llvm-stub.exe executable!");
415 if (0 != sys::CopyFile(sys::Path(OutputFilename), llvmstub, &ErrMsg))
416 PrintAndExit(ErrMsg);
421 // Output the script to start the program...
422 std::ofstream Out2(OutputFilename.c_str());
424 PrintAndExit("error opening '" + OutputFilename + "' for writing!");
426 Out2 << "#!/bin/sh\n";
427 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
428 Out2 << "lli=${LLVMINTERP-lli}\n";
429 Out2 << "exec $lli \\\n";
430 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
431 LibPaths.push_back("/lib");
432 LibPaths.push_back("/usr/lib");
433 LibPaths.push_back("/usr/X11R6/lib");
434 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
435 // shared object at all! See RH 8: plain text.
436 std::vector<std::string>::iterator libc =
437 std::find(Libraries.begin(), Libraries.end(), "c");
438 if (libc != Libraries.end()) Libraries.erase(libc);
439 // List all the shared object (native) libraries this executable will need
440 // on the command line, so that we don't have to do this manually!
441 for (std::vector<std::string>::iterator i = Libraries.begin(),
442 e = Libraries.end(); i != e; ++i) {
443 // try explicit -L arguments first:
444 sys::Path FullLibraryPath;
445 for (cl::list<std::string>::const_iterator P = LibPaths.begin(),
446 E = LibPaths.end(); P != E; ++P) {
447 FullLibraryPath = *P;
448 FullLibraryPath.appendComponent("lib" + *i);
449 FullLibraryPath.appendSuffix(&(LTDL_SHLIB_EXT[1]));
450 if (!FullLibraryPath.isEmpty()) {
451 if (!FullLibraryPath.isDynamicLibrary()) {
452 // Not a native shared library; mark as invalid
453 FullLibraryPath = sys::Path();
457 if (FullLibraryPath.isEmpty())
458 FullLibraryPath = sys::Path::FindLibrary(*i);
459 if (!FullLibraryPath.isEmpty())
460 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
462 Out2 << " $0.bc ${1+\"$@\"}\n";
466 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
467 // linker function by combining the Files and Libraries in the order they were
468 // declared on the command line.
469 static void BuildLinkItems(
470 Linker::ItemList& Items,
471 const cl::list<std::string>& Files,
472 const cl::list<std::string>& Libraries) {
474 // Build the list of linkage items for LinkItems.
476 cl::list<std::string>::const_iterator fileIt = Files.begin();
477 cl::list<std::string>::const_iterator libIt = Libraries.begin();
479 int libPos = -1, filePos = -1;
480 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
481 if (libIt != Libraries.end())
482 libPos = Libraries.getPosition(libIt - Libraries.begin());
485 if (fileIt != Files.end())
486 filePos = Files.getPosition(fileIt - Files.begin());
490 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
492 Items.push_back(std::make_pair(*fileIt++, false));
493 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
495 Items.push_back(std::make_pair(*libIt++, true));
500 // Rightly this should go in a header file but it just seems such a waste.
502 extern void Optimize(Module*);
505 int main(int argc, char **argv, char **envp) {
506 // Print a stack trace if we signal out.
507 sys::PrintStackTraceOnErrorSignal();
508 PrettyStackTraceProgram X(argc, argv);
511 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
513 // Initial global variable above for convenience printing of program name.
514 progname = sys::Path(argv[0]).getBasename();
516 // Parse the command line options
517 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
519 // Construct a Linker (now that Verbose is set)
520 Linker TheLinker(progname, OutputFilename, &Context, Verbose);
522 // Keep track of the native link items (versus the bitcode items)
523 Linker::ItemList NativeLinkItems;
525 // Add library paths to the linker
526 TheLinker.addPaths(LibPaths);
527 TheLinker.addSystemPaths();
529 // Remove any consecutive duplicates of the same library...
530 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
534 std::vector<sys::Path> Files;
535 for (unsigned i = 0; i < InputFilenames.size(); ++i )
536 Files.push_back(sys::Path(InputFilenames[i]));
537 if (TheLinker.LinkInFiles(Files))
538 return 1; // Error already printed
540 // The libraries aren't linked in but are noted as "dependent" in the
542 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
543 E = Libraries.end(); I != E ; ++I) {
544 TheLinker.getModule()->addLibrary(*I);
547 // Build a list of the items from our command line
548 Linker::ItemList Items;
549 BuildLinkItems(Items, InputFilenames, Libraries);
551 // Link all the items together
552 if (TheLinker.LinkInItems(Items, NativeLinkItems) )
553 return 1; // Error already printed
556 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
558 // Optimize the module
559 Optimize(Composite.get());
561 #if defined(_WIN32) || defined(__CYGWIN__)
562 if (!LinkAsLibrary) {
563 // Default to "a.exe" instead of "a.out".
564 if (OutputFilename.getNumOccurrences() == 0)
565 OutputFilename = "a.exe";
567 // If there is no suffix add an "exe" one.
568 sys::Path ExeFile( OutputFilename );
569 if (ExeFile.getSuffix() == "") {
570 ExeFile.appendSuffix("exe");
571 OutputFilename = ExeFile.toString();
576 // Generate the bitcode for the optimized module.
577 std::string RealBitcodeOutput = OutputFilename;
579 if (!LinkAsLibrary) RealBitcodeOutput += ".bc";
580 GenerateBitcode(Composite.get(), RealBitcodeOutput);
582 // If we are not linking a library, generate either a native executable
583 // or a JIT shell script, depending upon what the user wants.
584 if (!LinkAsLibrary) {
585 // If the user wants to run a post-link optimization, run it now.
586 if (!PostLinkOpts.empty()) {
587 std::vector<std::string> opts = PostLinkOpts;
588 for (std::vector<std::string>::iterator I = opts.begin(),
589 E = opts.end(); I != E; ++I) {
591 if (!prog.canExecute()) {
592 prog = sys::Program::FindProgramByName(*I);
594 PrintAndExit(std::string("Optimization program '") + *I +
595 "' is not found or not executable.");
597 // Get the program arguments
598 sys::Path tmp_output("opt_result");
600 if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
601 PrintAndExit(ErrMsg);
604 args[0] = I->c_str();
605 args[1] = RealBitcodeOutput.c_str();
606 args[2] = tmp_output.c_str();
608 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
609 if (tmp_output.isBitcodeFile() || tmp_output.isBitcodeFile()) {
610 sys::Path target(RealBitcodeOutput);
611 target.eraseFromDisk();
612 if (tmp_output.renamePathOnDisk(target, &ErrMsg))
613 PrintAndExit(ErrMsg, 2);
615 PrintAndExit("Post-link optimization output is not bitcode");
617 PrintAndExit(ErrMsg);
622 // If the user wants to generate a native executable, compile it from the
625 // Otherwise, create a script that will run the bitcode through the JIT.
627 // Name of the Assembly Language output file
628 sys::Path AssemblyFile ( OutputFilename);
629 AssemblyFile.appendSuffix("s");
631 // Mark the output files for removal if we get an interrupt.
632 sys::RemoveFileOnSignal(AssemblyFile);
633 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
635 // Determine the locations of the llc and gcc programs.
636 sys::Path llc = FindExecutable("llc", argv[0]);
638 PrintAndExit("Failed to find llc");
640 sys::Path gcc = FindExecutable("gcc", argv[0]);
642 PrintAndExit("Failed to find gcc");
644 // Generate an assembly language file for the bitcode.
646 if (0 != GenerateAssembly(AssemblyFile.toString(), RealBitcodeOutput,
648 PrintAndExit(ErrMsg);
650 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
651 NativeLinkItems, gcc, envp, ErrMsg))
652 PrintAndExit(ErrMsg);
654 // Remove the assembly language file.
655 AssemblyFile.eraseFromDisk();
656 } else if (NativeCBE) {
657 sys::Path CFile (OutputFilename);
658 CFile.appendSuffix("cbe.c");
660 // Mark the output files for removal if we get an interrupt.
661 sys::RemoveFileOnSignal(CFile);
662 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
664 // Determine the locations of the llc and gcc programs.
665 sys::Path llc = FindExecutable("llc", argv[0]);
667 PrintAndExit("Failed to find llc");
669 sys::Path gcc = FindExecutable("gcc", argv[0]);
671 PrintAndExit("Failed to find gcc");
673 // Generate an assembly language file for the bitcode.
675 if (0 != GenerateCFile(
676 CFile.toString(), RealBitcodeOutput, llc, ErrMsg))
677 PrintAndExit(ErrMsg);
679 if (0 != GenerateNative(OutputFilename, CFile.toString(),
680 NativeLinkItems, gcc, envp, ErrMsg))
681 PrintAndExit(ErrMsg);
683 // Remove the assembly language file.
684 CFile.eraseFromDisk();
687 EmitShellScript(argv);
690 // Make the script executable...
692 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg))
693 PrintAndExit(ErrMsg);
695 // Make the bitcode file readable and directly executable in LLEE as well
696 if (sys::Path(RealBitcodeOutput).makeExecutableOnDisk(&ErrMsg))
697 PrintAndExit(ErrMsg);
699 if (sys::Path(RealBitcodeOutput).makeReadableOnDisk(&ErrMsg))
700 PrintAndExit(ErrMsg);
702 } catch (const std::string& msg) {
705 PrintAndExit("Unexpected unknown exception occurred.", 2);