Check to see if all blocks are extractible first.
[oota-llvm.git] / tools / gccld / gccld.cpp
1 //===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
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
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.
16 //
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
23 #include "gccld.h"
24 #include "llvm/Module.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/Bytecode/Reader.h"
27 #include "llvm/Bytecode/WriteBytecodePass.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Transforms/Utils/Linker.h"
32 #include "Support/CommandLine.h"
33 #include "Support/FileUtilities.h"
34 #include "Support/Signals.h"
35 #include "Support/SystemUtils.h"
36 #include <fstream>
37 #include <memory>
38
39 using namespace llvm;
40
41 namespace {
42   cl::list<std::string> 
43   InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
44                  cl::OneOrMore);
45
46   cl::opt<std::string> 
47   OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
48                  cl::value_desc("filename"));
49
50   cl::opt<bool>    
51   Verbose("v", cl::desc("Print information about actions taken"));
52   
53   cl::list<std::string> 
54   LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
55            cl::value_desc("directory"));
56
57   cl::list<std::string> 
58   Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
59             cl::value_desc("library prefix"));
60
61   cl::opt<bool>
62   Strip("s", cl::desc("Strip symbol info from executable"));
63
64   cl::opt<bool>
65   NoInternalize("disable-internalize",
66                 cl::desc("Do not mark all symbols as internal"));
67   cl::alias
68   ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
69                 cl::aliasopt(NoInternalize));
70
71   cl::opt<bool>
72   LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
73                                             " library, not an executable"));
74   cl::alias
75   Relink("r", cl::desc("Alias for -link-as-library"),
76          cl::aliasopt(LinkAsLibrary));
77
78   cl::opt<bool>    
79   Native("native",
80          cl::desc("Generate a native binary instead of a shell script"));
81   cl::opt<bool>    
82   NativeCBE("native-cbe",
83             cl::desc("Generate a native binary with the C backend and GCC"));
84   
85   // Compatibility options that are ignored but supported by LD
86   cl::opt<std::string>
87   CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
88   cl::opt<std::string>
89   CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
90   cl::opt<bool>
91   CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
92   cl::opt<std::string>
93   CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
94 }
95
96 namespace llvm {
97
98 /// PrintAndReturn - Prints a message to standard error and returns a value
99 /// usable for an exit status.
100 ///
101 /// Inputs:
102 ///  progname - The name of the program (i.e. argv[0]).
103 ///  Message  - The message to print to standard error.
104 ///  Extra    - Extra information to print between the program name and thei
105 ///             message.  It is optional.
106 ///
107 /// Return value:
108 ///  Returns a value that can be used as the exit status (i.e. for exit()).
109 ///
110 int
111 PrintAndReturn(const char *progname,
112                const std::string &Message,
113                const std::string &Extra)
114 {
115   std::cerr << progname << Extra << ": " << Message << "\n";
116   return 1;
117 }
118
119 /// CopyEnv - This function takes an array of environment variables and makes a
120 /// copy of it.  This copy can then be manipulated any way the caller likes
121 /// without affecting the process's real environment.
122 ///
123 /// Inputs:
124 ///  envp - An array of C strings containing an environment.
125 ///
126 /// Return value:
127 ///  NULL - An error occurred.
128 ///
129 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
130 ///  in the array is a duplicate of the one in the original array (i.e. we do
131 ///  not copy the char *'s from one array to another).
132 ///
133 char ** CopyEnv(char ** const envp) {
134   // Count the number of entries in the old list;
135   unsigned entries;   // The number of entries in the old environment list
136   for (entries = 0; envp[entries] != NULL; entries++)
137     /*empty*/;
138
139   // Add one more entry for the NULL pointer that ends the list.
140   ++entries;
141
142   // If there are no entries at all, just return NULL.
143   if (entries == 0)
144     return NULL;
145
146   // Allocate a new environment list.
147   char **newenv = new char* [entries];
148   if ((newenv = new char* [entries]) == NULL)
149     return NULL;
150
151   // Make a copy of the list.  Don't forget the NULL that ends the list.
152   entries = 0;
153   while (envp[entries] != NULL) {
154     newenv[entries] = new char[strlen (envp[entries]) + 1];
155     strcpy (newenv[entries], envp[entries]);
156     ++entries;
157   }
158   newenv[entries] = NULL;
159
160   return newenv;
161 }
162
163
164 /// RemoveEnv - Remove the specified environment variable from the environment
165 /// array.
166 ///
167 /// Inputs:
168 ///  name - The name of the variable to remove.  It cannot be NULL.
169 ///  envp - The array of environment variables.  It cannot be NULL.
170 ///
171 /// Notes:
172 ///  This is mainly done because functions to remove items from the environment
173 ///  are not available across all platforms.  In particular, Solaris does not
174 ///  seem to have an unsetenv() function or a setenv() function (or they are
175 ///  undocumented if they do exist).
176 ///
177 void RemoveEnv(const char * name, char ** const envp) {
178   for (unsigned index=0; envp[index] != NULL; index++) {
179     // Find the first equals sign in the array and make it an EOS character.
180     char *p = strchr (envp[index], '=');
181     if (p == NULL)
182       continue;
183     else
184       *p = '\0';
185
186     // Compare the two strings.  If they are equal, zap this string.
187     // Otherwise, restore it.
188     if (!strcmp(name, envp[index]))
189       *envp[index] = '\0';
190     else
191       *p = '=';
192   }
193
194   return;
195 }
196
197 } // End llvm namespace
198
199 int main(int argc, char **argv, char **envp) {
200   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
201   PrintStackTraceOnErrorSignal();
202
203   std::string ModuleID("gccld-output");
204   std::auto_ptr<Module> Composite(new Module(ModuleID));
205
206   // We always look first in the current directory when searching for libraries.
207   LibPaths.insert(LibPaths.begin(), ".");
208
209   // If the user specified an extra search path in their environment, respect
210   // it.
211   if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
212     LibPaths.push_back(SearchPath);
213
214   // Remove any consecutive duplicates of the same library...
215   Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
216                   Libraries.end());
217
218   // Link in all of the files
219   if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
220     return 1; // Error already printed
221
222   if (!LinkAsLibrary)
223     LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,
224                   Verbose, Native);
225
226   // Link in all of the libraries next...
227
228   // Create the output file.
229   std::string RealBytecodeOutput = OutputFilename;
230   if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
231   std::ofstream Out(RealBytecodeOutput.c_str());
232   if (!Out.good())
233     return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
234                                    "' for writing!");
235
236   // Ensure that the bytecode file gets removed from the disk if we get a
237   // SIGINT signal.
238   RemoveFileOnSignal(RealBytecodeOutput);
239
240   // Generate the bytecode file.
241   if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
242     Out.close();
243     return PrintAndReturn(argv[0], "error generating bytecode");
244   }
245
246   // Close the bytecode file.
247   Out.close();
248
249   // If we are not linking a library, generate either a native executable
250   // or a JIT shell script, depending upon what the user wants.
251   if (!LinkAsLibrary) {
252     // If the user wants to generate a native executable, compile it from the
253     // bytecode file.
254     //
255     // Otherwise, create a script that will run the bytecode through the JIT.
256     if (Native) {
257       // Name of the Assembly Language output file
258       std::string AssemblyFile = OutputFilename + ".s";
259
260       // Mark the output files for removal if we get an interrupt.
261       RemoveFileOnSignal(AssemblyFile);
262       RemoveFileOnSignal(OutputFilename);
263
264       // Determine the locations of the llc and gcc programs.
265       std::string llc = FindExecutable("llc", argv[0]);
266       std::string gcc = FindExecutable("gcc", argv[0]);
267       if (llc.empty())
268         return PrintAndReturn(argv[0], "Failed to find llc");
269
270       if (gcc.empty())
271         return PrintAndReturn(argv[0], "Failed to find gcc");
272
273       // Generate an assembly language file for the bytecode.
274       if (Verbose) std::cout << "Generating Assembly Code\n";
275       GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
276       if (Verbose) std::cout << "Generating Native Code\n";
277       GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
278                      gcc, envp);
279
280       // Remove the assembly language file.
281       removeFile (AssemblyFile);
282     } else if (NativeCBE) {
283       std::string CFile = OutputFilename + ".cbe.c";
284
285       // Mark the output files for removal if we get an interrupt.
286       RemoveFileOnSignal(CFile);
287       RemoveFileOnSignal(OutputFilename);
288
289       // Determine the locations of the llc and gcc programs.
290       std::string llc = FindExecutable("llc", argv[0]);
291       std::string gcc = FindExecutable("gcc", argv[0]);
292       if (llc.empty())
293         return PrintAndReturn(argv[0], "Failed to find llc");
294       if (gcc.empty())
295         return PrintAndReturn(argv[0], "Failed to find gcc");
296
297       // Generate an assembly language file for the bytecode.
298       if (Verbose) std::cout << "Generating Assembly Code\n";
299       GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
300       if (Verbose) std::cout << "Generating Native Code\n";
301       GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);
302
303       // Remove the assembly language file.
304       removeFile(CFile);
305
306     } else {
307       // Output the script to start the program...
308       std::ofstream Out2(OutputFilename.c_str());
309       if (!Out2.good())
310         return PrintAndReturn(argv[0], "error opening '" + OutputFilename +
311                                        "' for writing!");
312       Out2 << "#!/bin/sh\n";
313       // Allow user to setenv LLVMINTERP if lli is not in their PATH.
314       Out2 << "lli=${LLVMINTERP-lli}\n";
315       Out2 << "exec $lli \\\n";
316       // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
317       LibPaths.push_back("/lib");
318       LibPaths.push_back("/usr/lib");
319       LibPaths.push_back("/usr/X11R6/lib");
320       // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
321       // shared object at all! See RH 8: plain text.
322       std::vector<std::string>::iterator libc = 
323         std::find(Libraries.begin(), Libraries.end(), "c");
324       if (libc != Libraries.end()) Libraries.erase(libc);
325       // List all the shared object (native) libraries this executable will need
326       // on the command line, so that we don't have to do this manually!
327       for (std::vector<std::string>::iterator i = Libraries.begin(), 
328              e = Libraries.end(); i != e; ++i) {
329         std::string FullLibraryPath = FindLib(*i, LibPaths, true);
330         if (!FullLibraryPath.empty() && IsSharedObject(FullLibraryPath))
331           Out2 << "    -load=" << FullLibraryPath << " \\\n";
332       }
333       Out2 << "    $0.bc ${1+\"$@\"}\n";
334       Out2.close();
335     }
336   
337     // Make the script executable...
338     MakeFileExecutable(OutputFilename);
339
340     // Make the bytecode file readable and directly executable in LLEE as well
341     MakeFileExecutable(RealBytecodeOutput);
342     MakeFileReadable(RealBytecodeOutput);
343   }
344
345   return 0;
346 }