1 //===- gccld.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 //===----------------------------------------------------------------------===//
24 #include "llvm/Linker.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Bytecode/Reader.h"
28 #include "llvm/Bytecode/WriteBytecodePass.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Transforms/IPO.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/System/Signals.h"
35 #include "llvm/Support/SystemUtils.h"
42 InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
46 OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
47 cl::value_desc("filename"));
50 Verbose("v", cl::desc("Print information about actions taken"));
53 LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
54 cl::value_desc("directory"));
57 Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
58 cl::value_desc("library prefix"));
61 Strip("strip-all", cl::desc("Strip all symbol info from executable"));
63 StripDebug("strip-debug",
64 cl::desc("Strip debugger symbol info from executable"));
67 NoInternalize("disable-internalize",
68 cl::desc("Do not mark all symbols as internal"));
70 ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
71 cl::aliasopt(NoInternalize));
74 LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
75 " library, not an executable"));
77 Relink("r", cl::desc("Alias for -link-as-library"),
78 cl::aliasopt(LinkAsLibrary));
81 Native("native", cl::ZeroOrMore,
82 cl::desc("Generate a native binary instead of a shell script"));
84 NativeCBE("native-cbe", cl::ZeroOrMore,
85 cl::desc("Generate a native binary with the C backend and GCC"));
88 SaveTemps("save-temps",
89 cl::desc("Do not delete temporary files"));
93 cl::desc("Set runtime shared library search path (requires -native or"
95 cl::Prefix, cl::value_desc("directory"));
99 cl::desc("Set internal name of shared library (requires -native or"
101 cl::Prefix, cl::value_desc("name"));
103 // Compatibility options that are ignored but supported by LD
105 CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
107 CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
109 CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
111 CO7("start-group", cl::Hidden, cl::desc("Compatibility option: ignored"));
113 CO8("end-group", cl::Hidden, cl::desc("Compatibility option: ignored"));
115 cl::alias A0("s", cl::desc("Alias for --strip-all"),
116 cl::aliasopt(Strip));
117 cl::alias A1("S", cl::desc("Alias for --strip-debug"),
118 cl::aliasopt(StripDebug));
122 /// PrintAndReturn - Prints a message to standard error and returns true.
125 /// progname - The name of the program (i.e. argv[0]).
126 /// Message - The message to print to standard error.
128 static int PrintAndReturn(const char *progname, const std::string &Message) {
129 std::cerr << progname << ": " << Message << "\n";
133 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
134 /// bytecode file for the program.
135 static void EmitShellScript(char **argv) {
136 #if defined(_WIN32) || defined(__CYGWIN__)
137 // Windows doesn't support #!/bin/sh style shell scripts in .exe files. To
138 // support windows systems, we copy the llvm-stub.exe executable from the
139 // build tree to the destination file.
140 std::string llvmstub = FindExecutable("llvm-stub.exe", argv[0]).toString();
141 if (llvmstub.empty()) {
142 std::cerr << "Could not find llvm-stub.exe executable!\n";
145 sys::CopyFile(sys::Path(OutputFilename), sys::Path(llvmstub));
149 // Output the script to start the program...
150 std::ofstream Out2(OutputFilename.c_str());
152 exit(PrintAndReturn(argv[0], "error opening '" + OutputFilename +
155 Out2 << "#!/bin/sh\n";
156 // Allow user to setenv LLVMINTERP if lli is not in their PATH.
157 Out2 << "lli=${LLVMINTERP-lli}\n";
158 Out2 << "exec $lli \\\n";
160 // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
161 // shared object at all! See RH 8: plain text.
162 std::vector<std::string>::iterator libc =
163 std::find(Libraries.begin(), Libraries.end(), "c");
164 if (libc != Libraries.end()) Libraries.erase(libc);
165 // List all the shared object (native) libraries this executable will need
166 // on the command line, so that we don't have to do this manually!
167 for (std::vector<std::string>::iterator i = Libraries.begin(),
168 e = Libraries.end(); i != e; ++i) {
169 sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
170 if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
171 Out2 << " -load=" << FullLibraryPath.toString() << " \\\n";
173 Out2 << " $0.bc ${1+\"$@\"}\n";
177 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
178 // linker function by combining the Files and Libraries in the order they were
179 // declared on the command line.
180 static void BuildLinkItems(
181 Linker::ItemList& Items,
182 const cl::list<std::string>& Files,
183 const cl::list<std::string>& Libraries) {
185 // Build the list of linkage items for LinkItems.
187 cl::list<std::string>::const_iterator fileIt = Files.begin();
188 cl::list<std::string>::const_iterator libIt = Libraries.begin();
190 int libPos = -1, filePos = -1;
191 while ( libIt != Libraries.end() || fileIt != Files.end() ) {
192 if (libIt != Libraries.end())
193 libPos = Libraries.getPosition(libIt - Libraries.begin());
196 if (fileIt != Files.end())
197 filePos = Files.getPosition(fileIt - Files.begin());
201 if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
203 Items.push_back(std::make_pair(*fileIt++, false));
204 } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
206 Items.push_back(std::make_pair(*libIt++, true));
211 int main(int argc, char **argv, char **envp ) {
212 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
213 sys::PrintStackTraceOnErrorSignal();
217 std::string ProgName = sys::Path(argv[0]).getBasename();
218 Linker TheLinker(ProgName, OutputFilename, Verbose);
221 // Remove any consecutive duplicates of the same library...
222 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
225 TheLinker.addPaths(LibPaths);
226 TheLinker.addSystemPaths();
229 std::vector<sys::Path> Files;
230 for (unsigned i = 0; i < InputFilenames.size(); ++i )
231 Files.push_back(sys::Path(InputFilenames[i]));
233 if (TheLinker.LinkInFiles(Files))
234 return 1; // Error already printed by linker
236 // The libraries aren't linked in but are noted as "dependent" in the
238 for (cl::list<std::string>::const_iterator I = Libraries.begin(),
239 E = Libraries.end(); I != E ; ++I) {
240 TheLinker.getModule()->addLibrary(*I);
244 // Build a list of the items from our command line
245 Linker::ItemList Items;
246 BuildLinkItems(Items, InputFilenames, Libraries);
248 // Link all the items together
249 if (TheLinker.LinkInItems(Items))
250 return 1; // Error already printed
253 // We're done with the Linker, so tell it to release its module
254 std::auto_ptr<Module> Composite(TheLinker.releaseModule());
256 // Create the output file.
257 std::string RealBytecodeOutput = OutputFilename;
258 if (!LinkAsLibrary || Native || NativeCBE) RealBytecodeOutput += ".bc";
259 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
261 std::ofstream Out(RealBytecodeOutput.c_str(), io_mode);
263 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
266 // Ensure that the bytecode file gets removed from the disk if we get a
268 sys::RemoveFileOnSignal(sys::Path(RealBytecodeOutput));
270 // Strip everything if Strip is set, otherwise if stripdebug is set, just
272 int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
274 // Internalize the module if neither -disable-internalize nor
275 // -link-as-library are passed in.
276 bool ShouldInternalize = !NoInternalize & !LinkAsLibrary;
278 // Generate the bytecode file.
279 if (GenerateBytecode(Composite.get(), StripLevel, ShouldInternalize, &Out)){
281 return PrintAndReturn(argv[0], "error generating bytecode");
284 // Close the bytecode file.
287 // Generate either a native file or a JIT shell script. If the user wants
288 // to generate a native file, compile it from the bytecode file. Otherwise,
289 // if the target is not a library, create a script that will run the
290 // bytecode through the JIT.
292 // Name of the Assembly Language output file
293 sys::Path AssemblyFile (OutputFilename);
294 AssemblyFile.appendSuffix("s");
296 // Mark the output files for removal if we get an interrupt.
297 sys::RemoveFileOnSignal(AssemblyFile);
298 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
300 // Determine the locations of the llc and gcc programs.
301 sys::Path llc = FindExecutable("llc", argv[0]);
303 return PrintAndReturn(argv[0], "Failed to find llc");
305 sys::Path gcc = FindExecutable("gcc", argv[0]);
307 return PrintAndReturn(argv[0], "Failed to find gcc");
309 // Generate an assembly language file for the bytecode.
310 if (Verbose) std::cout << "Generating Assembly Code\n";
311 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc,
313 if (Verbose) std::cout << "Generating Native Code\n";
314 GenerateNative(OutputFilename, AssemblyFile.toString(),
315 LibPaths, Libraries, gcc, envp, LinkAsLibrary,
316 NoInternalize, RPath, SOName, Verbose);
319 // Remove the assembly language file.
320 AssemblyFile.eraseFromDisk();
321 // Remove the bytecode language file.
322 sys::Path(RealBytecodeOutput).eraseFromDisk();
325 } else if (NativeCBE) {
326 sys::Path CFile (OutputFilename);
327 CFile.appendSuffix("cbe.c");
329 // Mark the output files for removal if we get an interrupt.
330 sys::RemoveFileOnSignal(CFile);
331 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
333 // Determine the locations of the llc and gcc programs.
334 sys::Path llc = FindExecutable("llc", argv[0]);
336 return PrintAndReturn(argv[0], "Failed to find llc");
338 sys::Path gcc = FindExecutable("gcc", argv[0]);
340 return PrintAndReturn(argv[0], "Failed to find gcc");
342 // Generate an assembly language file for the bytecode.
343 if (Verbose) std::cout << "Generating C Source Code\n";
344 GenerateCFile(CFile.toString(), RealBytecodeOutput, llc, Verbose);
345 if (Verbose) std::cout << "Generating Native Code\n";
346 GenerateNative(OutputFilename, CFile.toString(),
347 LibPaths, Libraries, gcc, envp, LinkAsLibrary,
348 NoInternalize, RPath, SOName, Verbose);
351 // Remove the assembly language file.
352 CFile.eraseFromDisk();
353 // Remove the bytecode language file.
354 sys::Path(RealBytecodeOutput).eraseFromDisk();
357 } else if (!LinkAsLibrary) {
358 EmitShellScript(argv);
360 // Make the bytecode file readable and directly executable in LLEE
361 sys::Path(RealBytecodeOutput).makeExecutableOnDisk();
362 sys::Path(RealBytecodeOutput).makeReadableOnDisk();
365 // Make the output, whether native or script, executable as well...
366 sys::Path(OutputFilename).makeExecutableOnDisk();
368 } catch (const char*msg) {
369 std::cerr << argv[0] << ": " << msg << "\n";
371 } catch (const std::string& msg) {
372 std::cerr << argv[0] << ": " << msg << "\n";
375 // This really shouldn't happen, but just in case ....
376 std::cerr << argv[0] << ": An unexpected unknown exception occurred.\n";