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