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/LinkAllVMCore.h"
24 #include "llvm/Linker.h"
25 #include "llvm/System/Program.h"
26 #include "llvm/Module.h"
27 #include "llvm/PassManager.h"
28 #include "llvm/Bytecode/Reader.h"
29 #include "llvm/Bytecode/Writer.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/SystemUtils.h"
36 #include "llvm/System/Signals.h"
43 // Input/Output Options
44 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
45 cl::desc("<input bytecode files>"));
47 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
48 cl::desc("Override output filename"),
49 cl::value_desc("filename"));
51 static cl::opt<bool> Verbose("v",
52 cl::desc("Print information about actions taken"));
54 static cl::list<std::string> LibPaths("L", cl::Prefix,
55 cl::desc("Specify a library search path"),
56 cl::value_desc("directory"));
58 static cl::list<std::string> Libraries("l", cl::Prefix,
59 cl::desc("Specify libraries to link to"),
60 cl::value_desc("library prefix"));
62 static cl::opt<bool> LinkAsLibrary("link-as-library",
63 cl::desc("Link the .bc files together as a library, not an executable"));
65 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
66 cl::desc("Alias for -link-as-library"));
68 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
69 MachineArch("march", cl::desc("Architecture to generate assembly for:"));
71 static cl::opt<bool> Native("native",
72 cl::desc("Generate a native binary instead of a shell script"));
74 static cl::opt<bool>NativeCBE("native-cbe",
75 cl::desc("Generate a native binary with the C backend and GCC"));
77 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
78 cl::desc("Disable writing of compressed bytecode files"));
80 static cl::list<std::string> PostLinkOpts("post-link-opts",
81 cl::value_desc("path"),
82 cl::desc("Run one or more optimization programs after linking"));
84 static cl::list<std::string> XLinker("Xlinker", cl::value_desc("option"),
85 cl::desc("Pass options to the system linker"));
87 // Compatibility options that are ignored but supported by LD
88 static cl::opt<std::string> CO3("soname", cl::Hidden,
89 cl::desc("Compatibility option: ignored"));
91 static cl::opt<std::string> CO4("version-script", cl::Hidden,
92 cl::desc("Compatibility option: ignored"));
94 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
95 cl::desc("Compatibility option: ignored"));
97 static cl::opt<std::string> CO6("h", cl::Hidden,
98 cl::desc("Compatibility option: ignored"));
101 /// This is just for convenience so it doesn't have to be passed around
103 static std::string progname;
105 /// PrintAndReturn - Prints a message to standard error and returns true.
108 /// progname - The name of the program (i.e. argv[0]).
109 /// Message - The message to print to standard error.
111 static int PrintAndReturn(const std::string &Message) {
112 std::cerr << progname << ": " << Message << "\n";
116 /// 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.
121 /// envp - An array of C strings containing an environment.
124 /// NULL - An error occurred.
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).
130 static 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++)
136 // Add one more entry for the NULL pointer that ends the list.
139 // If there are no entries at all, just return NULL.
143 // Allocate a new environment list.
144 char **newenv = new char* [entries];
145 if ((newenv = new char* [entries]) == NULL)
148 // Make a copy of the list. Don't forget the NULL that ends the list.
150 while (envp[entries] != NULL) {
151 newenv[entries] = new char[strlen (envp[entries]) + 1];
152 strcpy (newenv[entries], envp[entries]);
155 newenv[entries] = NULL;
161 /// RemoveEnv - Remove the specified environment variable from the environment
165 /// name - The name of the variable to remove. It cannot be NULL.
166 /// envp - The array of environment variables. It cannot be NULL.
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).
174 static 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], '=');
183 // Compare the two strings. If they are equal, zap this string.
184 // Otherwise, restore it.
185 if (!strcmp(name, envp[index]))
194 /// GenerateBytecode - generates a bytecode file from the module provided
195 void GenerateBytecode(Module* M, const std::string& FileName) {
197 // Create the output file.
198 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
200 std::ofstream Out(FileName.c_str(), io_mode);
202 PrintAndReturn("error opening '" + FileName + "' for writing!");
206 // Ensure that the bytecode file gets removed from the disk if we get a
207 // terminating signal.
208 sys::RemoveFileOnSignal(sys::Path(FileName));
211 WriteBytecodeToFile(M, Out, !DisableCompression);
213 // Close the bytecode file.
217 /// GenerateAssembly - generates a native assembly language source file from the
218 /// specified bytecode file.
221 /// InputFilename - The name of the input bytecode file.
222 /// OutputFilename - The name of the file to generate.
223 /// llc - The pathname to use for LLC.
224 /// envp - The environment to use when running LLC.
226 /// Return non-zero value on error.
228 static int GenerateAssembly(const std::string &OutputFilename,
229 const std::string &InputFilename,
230 const sys::Path &llc,
231 std::string &ErrMsg ) {
232 // Run LLC to convert the bytecode file into assembly code.
233 std::vector<const char*> args;
234 args.push_back(llc.c_str());
235 args.push_back("-f");
236 args.push_back("-o");
237 args.push_back(OutputFilename.c_str());
238 args.push_back(InputFilename.c_str());
241 return sys::Program::ExecuteAndWait(llc,&args[0],0,0,0,&ErrMsg);
244 /// GenerateCFile - generates a C source file from the specified bytecode file.
245 static int GenerateCFile(const std::string &OutputFile,
246 const std::string &InputFile,
247 const sys::Path &llc,
248 std::string& ErrMsg) {
249 // Run LLC to convert the bytecode file into C.
250 std::vector<const char*> args;
251 args.push_back(llc.c_str());
252 args.push_back("-march=c");
253 args.push_back("-f");
254 args.push_back("-o");
255 args.push_back(OutputFile.c_str());
256 args.push_back(InputFile.c_str());
258 return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
261 /// GenerateNative - generates a native object file from the
262 /// specified bytecode file.
265 /// InputFilename - The name of the input bytecode file.
266 /// OutputFilename - The name of the file to generate.
267 /// Libraries - The list of libraries with which to link.
268 /// LibPaths - The list of directories in which to find libraries.
269 /// gcc - The pathname to use for GGC.
270 /// envp - A copy of the process's current environment.
275 /// Returns non-zero value on error.
277 static int GenerateNative(const std::string &OutputFilename,
278 const std::string &InputFilename,
279 const std::vector<std::string> &Libraries,
280 const sys::Path &gcc, char ** const envp,
281 std::string& ErrMsg) {
282 // Remove these environment variables from the environment of the
283 // programs that we will execute. It appears that GCC sets these
284 // environment variables so that the programs it uses can configure
285 // themselves identically.
287 // However, when we invoke GCC below, we want it to use its normal
288 // configuration. Hence, we must sanitize its environment.
289 char ** clean_env = CopyEnv(envp);
290 if (clean_env == NULL)
292 RemoveEnv("LIBRARY_PATH", clean_env);
293 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
294 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
295 RemoveEnv("COMPILER_PATH", clean_env);
296 RemoveEnv("COLLECT_GCC", clean_env);
299 // Run GCC to assemble and link the program into native code.
302 // We can't just assemble and link the file with the system assembler
303 // and linker because we don't know where to put the _start symbol.
304 // GCC mysteriously knows how to do it.
305 std::vector<const char*> args;
306 args.push_back(gcc.c_str());
307 args.push_back("-fno-strict-aliasing");
308 args.push_back("-O3");
309 args.push_back("-o");
310 args.push_back(OutputFilename.c_str());
311 args.push_back(InputFilename.c_str());
313 // Add in the library paths
314 for (unsigned index = 0; index < LibPaths.size(); index++) {
315 args.push_back("-L");
316 args.push_back(LibPaths[index].c_str());
319 // Add the requested options
320 for (unsigned index = 0; index < XLinker.size(); index++) {
321 args.push_back(XLinker[index].c_str());
322 args.push_back(Libraries[index].c_str());
325 // Add in the libraries to link.
326 for (unsigned index = 0; index < Libraries.size(); index++)
327 if (Libraries[index] != "crtend") {
328 args.push_back("-l");
329 args.push_back(Libraries[index].c_str());
334 // Run the compiler to assembly and link together the program.
335 int R = sys::Program::ExecuteAndWait(
336 gcc, &args[0], (const char**)clean_env,0,0,&ErrMsg);
341 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
342 /// bytecode file for the program.
343 static void EmitShellScript(char **argv) {
344 #if defined(_WIN32) || defined(__CYGWIN__)
345 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
346 // support windows systems, we copy the llvm-stub.exe executable from the
347 // build tree to the destination file.
348 sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
349 if (llvmstub.isEmpty()) {
350 std::cerr << "Could not find llvm-stub.exe executable!\n";
353 sys::CopyFile(sys::Path(OutputFilename), llvmstub);
357 // Output the script to start the program...
358 std::ofstream Out2(OutputFilename.c_str());
360 exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
362 Out2 << "#!/bin/sh\n";
363 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
364 Out2 << "lli=${LLVMINTERP-lli}\n";
365 Out2 << "exec $lli \\\n";
366 // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
367 LibPaths.push_back("/lib");
368 LibPaths.push_back("/usr/lib");
369 LibPaths.push_back("/usr/X11R6/lib");
370 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
371 // shared object at all! See RH 8: plain text.
372 std::vector<std::string>::iterator libc =
373 std::find(Libraries.begin(), Libraries.end(), "c");
374 if (libc != Libraries.end()) Libraries.erase(libc);
375 // List all the shared object (native) libraries this executable will need
376 // on the command line, so that we don't have to do this manually!
377 for (std::vector<std::string>::iterator i = Libraries.begin(),
378 e = Libraries.end(); i != e; ++i) {
379 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
380 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
381 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
383 Out2 << " $0.bc ${1+\"$@\"}\n";
387 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
388 // linker function by combining the Files and Libraries in the order they were
389 // declared on the command line.
390 static void BuildLinkItems(
391 Linker::ItemList& Items,
392 const cl::list<std::string>& Files,
393 const cl::list<std::string>& Libraries) {
395 // Build the list of linkage items for LinkItems.
397 cl::list<std::string>::const_iterator fileIt = Files.begin();
398 cl::list<std::string>::const_iterator libIt = Libraries.begin();
400 int libPos = -1, filePos = -1;
401 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
402 if (libIt != Libraries.end())
403 libPos = Libraries.getPosition(libIt - Libraries.begin());
406 if (fileIt != Files.end())
407 filePos = Files.getPosition(fileIt - Files.begin());
411 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
413 Items.push_back(std::make_pair(*fileIt++, false));
414 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
416 Items.push_back(std::make_pair(*libIt++, true));
421 // Rightly this should go in a header file but it just seems such a waste.
423 extern void Optimize(Module*);
426 int main(int argc, char **argv, char **envp) {
428 // Initial global variable above for convenience printing of program name.
429 progname = sys::Path(argv[0]).getBasename();
430 Linker TheLinker(progname, OutputFilename, Verbose);
432 // Parse the command line options
433 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
434 sys::PrintStackTraceOnErrorSignal();
436 // Set up the library paths for the Linker
437 TheLinker.addPaths(LibPaths);
438 TheLinker.addSystemPaths();
440 // Remove any consecutive duplicates of the same library...
441 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
445 std::vector<sys::Path> Files;
446 for (unsigned i = 0; i < InputFilenames.size(); ++i )
447 Files.push_back(sys::Path(InputFilenames[i]));
448 if (TheLinker.LinkInFiles(Files))
449 return 1; // Error already printed
451 // The libraries aren't linked in but are noted as "dependent" in the
453 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
454 E = Libraries.end(); I != E ; ++I) {
455 TheLinker.getModule()->addLibrary(*I);
458 // Build a list of the items from our command line
459 Linker::ItemList Items;
460 Linker::ItemList NativeItems;
461 BuildLinkItems(Items, InputFilenames, Libraries);
463 // Link all the items together
464 if (TheLinker.LinkInItems(Items,NativeItems) )
468 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
470 // Optimize the module
471 Optimize(Composite.get());
473 // Generate the bytecode for the optimized module.
474 std::string RealBytecodeOutput = OutputFilename;
475 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
476 GenerateBytecode(Composite.get(), RealBytecodeOutput);
478 // If we are not linking a library, generate either a native executable
479 // or a JIT shell script, depending upon what the user wants.
480 if (!LinkAsLibrary) {
481 // If the user wants to run a post-link optimization, run it now.
482 if (!PostLinkOpts.empty()) {
483 std::vector<std::string> opts = PostLinkOpts;
484 for (std::vector<std::string>::iterator I = opts.begin(),
485 E = opts.end(); I != E; ++I) {
487 if (!prog.canExecute()) {
488 prog = sys::Program::FindProgramByName(*I);
490 return PrintAndReturn(std::string("Optimization program '") + *I +
491 "' is not found or not executable.");
493 // Get the program arguments
494 sys::Path tmp_output("opt_result");
496 if (tmp_output.createTemporaryFileOnDisk(&ErrMsg)) {
497 return PrintAndReturn(ErrMsg);
500 args[0] = I->c_str();
501 args[1] = RealBytecodeOutput.c_str();
502 args[2] = tmp_output.c_str();
504 if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0, &ErrMsg)) {
505 if (tmp_output.isBytecodeFile()) {
506 sys::Path target(RealBytecodeOutput);
507 target.eraseFromDisk();
508 if (tmp_output.renamePathOnDisk(target, &ErrMsg)) {
509 std::cerr << argv[0] << ": " << ErrMsg << "\n";
513 return PrintAndReturn(
514 "Post-link optimization output is not bytecode");
516 std::cerr << argv[0] << ": " << ErrMsg << "\n";
522 // If the user wants to generate a native executable, compile it from the
525 // Otherwise, create a script that will run the bytecode through the JIT.
527 // Name of the Assembly Language output file
528 sys::Path AssemblyFile ( OutputFilename);
529 AssemblyFile.appendSuffix("s");
531 // Mark the output files for removal if we get an interrupt.
532 sys::RemoveFileOnSignal(AssemblyFile);
533 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
535 // Determine the locations of the llc and gcc programs.
536 sys::Path llc = FindExecutable("llc", argv[0]);
538 return PrintAndReturn("Failed to find llc");
540 sys::Path gcc = FindExecutable("gcc", argv[0]);
542 return PrintAndReturn("Failed to find gcc");
544 // Generate an assembly language file for the bytecode.
545 if (Verbose) std::cout << "Generating Assembly Code\n";
547 if (0 != GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput,
549 std::cerr << argv[0] << ": " << ErrMsg << "\n";
553 if (Verbose) std::cout << "Generating Native Code\n";
554 if (0 != GenerateNative(OutputFilename, AssemblyFile.toString(),
555 Libraries,gcc,envp,ErrMsg)) {
556 std::cerr << argv[0] << ": " << ErrMsg << "\n";
560 // Remove the assembly language file.
561 AssemblyFile.eraseFromDisk();
562 } else if (NativeCBE) {
563 sys::Path CFile (OutputFilename);
564 CFile.appendSuffix("cbe.c");
566 // Mark the output files for removal if we get an interrupt.
567 sys::RemoveFileOnSignal(CFile);
568 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
570 // Determine the locations of the llc and gcc programs.
571 sys::Path llc = FindExecutable("llc", argv[0]);
573 return PrintAndReturn("Failed to find llc");
575 sys::Path gcc = FindExecutable("gcc", argv[0]);
577 return PrintAndReturn("Failed to find gcc");
579 // Generate an assembly language file for the bytecode.
580 if (Verbose) std::cout << "Generating Assembly Code\n";
582 if (0 != GenerateCFile(
583 CFile.toString(), RealBytecodeOutput, llc, ErrMsg)) {
584 std::cerr << argv[0] << ": " << ErrMsg << "\n";
588 if (Verbose) std::cout << "Generating Native Code\n";
589 if (0 != GenerateNative(OutputFilename, CFile.toString(), Libraries,
590 gcc, envp, ErrMsg)) {
591 std::cerr << argv[0] << ": " << ErrMsg << "\n";
595 // Remove the assembly language file.
596 CFile.eraseFromDisk();
599 EmitShellScript(argv);
602 // Make the script executable...
604 if (sys::Path(OutputFilename).makeExecutableOnDisk(&ErrMsg)) {
605 std::cerr << argv[0] << ": " << ErrMsg << "\n";
609 // Make the bytecode file readable and directly executable in LLEE as well
610 if (sys::Path(RealBytecodeOutput).makeExecutableOnDisk(&ErrMsg)) {
611 std::cerr << argv[0] << ": " << ErrMsg << "\n";
614 if (sys::Path(RealBytecodeOutput).makeReadableOnDisk(&ErrMsg)) {
615 std::cerr << argv[0] << ": " << ErrMsg << "\n";
621 } catch (const std::string& msg) {
622 std::cerr << argv[0] << ": " << msg << "\n";
624 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";