*** empty log message ***
[oota-llvm.git] / tools / gccld / gccld.cpp
1 //===----------------------------------------------------------------------===//
2 // LLVM 'GCCLD' UTILITY 
3 //
4 // This utility is intended to be compatible with GCC, and follows standard
5 // system ld conventions.  As such, the default output file is ./a.out.
6 // Additionally, this program outputs a shell script that is used to invoke LLI
7 // to execute the program.  In this manner, the generated executable (a.out for
8 // example), is directly executable, whereas the bytecode file actually lives in
9 // the a.out.bc file generated by this program.  Also, Force is on by default.
10 //
11 // Note that if someone (or a script) deletes the executable program generated,
12 // the .bc file will be left around.  Considering that this is a temporary hack,
13 // I'm not to worried about this.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/Utils/Linker.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Bytecode/Reader.h"
21 #include "llvm/Bytecode/WriteBytecodePass.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Transforms/IPO/GlobalDCE.h"
24 #include "llvm/Transforms/IPO/Internalize.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "Support/CommandLine.h"
27 #include "Support/Signals.h"
28 #include <fstream>
29 #include <memory>
30 #include <algorithm>
31 #include <sys/types.h>     // For FileExists
32 #include <sys/stat.h>
33 using std::cerr;
34
35 static cl::list<string> 
36 InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
37                cl::OneOrMore);
38
39 static cl::opt<string> 
40 OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
41                cl::value_desc("filename"));
42
43 static cl::opt<bool>    
44 Verbose("v", cl::desc("Print information about actions taken"));
45
46 static cl::list<string> 
47 LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
48          cl::value_desc("directory"));
49
50 static cl::list<string> 
51 Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
52           cl::value_desc("library prefix"));
53
54 static cl::opt<bool>
55 Strip("s", cl::desc("Strip symbol info from executable"));
56
57
58 // FileExists - Return true if the specified string is an openable file...
59 static inline bool FileExists(const std::string &FN) {
60   struct stat StatBuf;
61   return stat(FN.c_str(), &StatBuf) != -1;
62 }
63
64 // LoadFile - Read the specified bytecode file in and return it.  This routine
65 // searches the link path for the specified file to try to find it...
66 //
67 static inline std::auto_ptr<Module> LoadFile(const std::string &FN) {
68   std::string Filename = FN;
69   std::string ErrorMessage;
70
71   unsigned NextLibPathIdx = 0;
72   bool FoundAFile = false;
73
74   while (1) {
75     if (Verbose) cerr << "Loading '" << Filename << "'\n";
76     if (FileExists(Filename)) FoundAFile = true;
77     Module *Result = ParseBytecodeFile(Filename, &ErrorMessage);
78     if (Result) return std::auto_ptr<Module>(Result);   // Load successful!
79
80     if (Verbose) {
81       cerr << "Error opening bytecode file: '" << Filename << "'";
82       if (ErrorMessage.size()) cerr << ": " << ErrorMessage;
83       cerr << "\n";
84     }
85     
86     if (NextLibPathIdx == LibPaths.size()) break;
87     Filename = LibPaths[NextLibPathIdx++] + "/" + FN;
88   }
89
90   if (FoundAFile)
91     cerr << "Bytecode file '" << FN << "' corrupt!  "
92          << "Use 'gccld -v ...' for more info.\n";
93   else
94     cerr << "Could not locate bytecode file: '" << FN << "'\n";
95   return std::auto_ptr<Module>();
96 }
97
98
99 int main(int argc, char **argv) {
100   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
101
102   unsigned BaseArg = 0;
103   std::string ErrorMessage;
104
105   if (!Libraries.empty()) {
106     // Sort libraries list...
107     std::sort(Libraries.begin(), Libraries.end());
108
109     // Remove duplicate libraries entries...
110     Libraries.erase(unique(Libraries.begin(), Libraries.end()),
111                     Libraries.end());
112
113     // Add all of the libraries to the end of the link line...
114     for (unsigned i = 0; i < Libraries.size(); ++i)
115       InputFilenames.push_back("lib" + Libraries[i] + ".bc");
116   }
117
118   std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg]));
119   if (Composite.get() == 0) return 1;
120
121   for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
122     std::auto_ptr<Module> M(LoadFile(InputFilenames[i]));
123     if (M.get() == 0) return 1;
124
125     if (Verbose) cerr << "Linking in '" << InputFilenames[i] << "'\n";
126
127     if (LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
128       cerr << "Error linking in '" << InputFilenames[i] << "': "
129            << ErrorMessage << "\n";
130       return 1;
131     }
132   }
133
134   // In addition to just linking the input from GCC, we also want to spiff it up
135   // a little bit.  Do this now.
136   //
137   PassManager Passes;
138
139   // Linking modules together can lead to duplicated global constants, only keep
140   // one copy of each constant...
141   //
142   Passes.add(createConstantMergePass());
143
144   // If the -s command line option was specified, strip the symbols out of the
145   // resulting program to make it smaller.  -s is a GCC option that we are
146   // supporting.
147   //
148   if (Strip)
149     Passes.add(createSymbolStrippingPass());
150
151   // Often if the programmer does not specify proper prototypes for the
152   // functions they are calling, they end up calling a vararg version of the
153   // function that does not get a body filled in (the real function has typed
154   // arguments).  This pass merges the two functions.
155   //
156   Passes.add(createFunctionResolvingPass());
157
158   // Now that composite has been compiled, scan through the module, looking for
159   // a main function.  If main is defined, mark all other functions internal.
160   //
161   Passes.add(createInternalizePass());
162
163   // Now that we have optimized the program, discard unreachable functions...
164   //
165   Passes.add(createGlobalDCEPass());
166
167   // Add the pass that writes bytecode to the output file...
168   std::ofstream Out((OutputFilename+".bc").c_str());
169   if (!Out.good()) {
170     cerr << "Error opening '" << OutputFilename << ".bc' for writing!\n";
171     return 1;
172   }
173   Passes.add(new WriteBytecodePass(&Out));        // Write bytecode to file...
174
175   // Make sure that the Out file gets unlink'd from the disk if we get a SIGINT
176   RemoveFileOnSignal(OutputFilename+".bc");
177
178   // Run our queue of passes all at once now, efficiently.
179   Passes.run(*Composite.get());
180   Out.close();
181
182   // Output the script to start the program...
183   std::ofstream Out2(OutputFilename.c_str());
184   if (!Out2.good()) {
185     cerr << "Error opening '" << OutputFilename << "' for writing!\n";
186     return 1;
187   }
188   Out2 << "#!/bin/sh\nlli -q $0.bc $*\n";
189   Out2.close();
190   
191   // Make the script executable...
192   chmod(OutputFilename.c_str(), 0755);
193
194   return 0;
195 }