blob: b9d76d67381a692cc8540153d6cdf6e76f3e4392 [file] [log] [blame]
Devang Patela89d47f2006-08-03 15:44:57 +00001//===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Devang Patel and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implementes link time optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Module.h"
16#include "llvm/PassManager.h"
17#include "llvm/Linker.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/SymbolTable.h"
21#include "llvm/Bytecode/Reader.h"
22#include "llvm/Bytecode/Writer.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/FileUtilities.h"
25#include "llvm/Support/SystemUtils.h"
Devang Patel30235da2006-08-14 22:36:16 +000026#include "llvm/Support/Mangler.h"
Devang Patela89d47f2006-08-03 15:44:57 +000027#include "llvm/System/Program.h"
28#include "llvm/System/Signals.h"
29#include "llvm/Analysis/Passes.h"
30#include "llvm/Analysis/Verifier.h"
31#include "llvm/Target/SubtargetFeature.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetMachineRegistry.h"
35#include "llvm/Transforms/IPO.h"
36#include "llvm/Transforms/Scalar.h"
37#include "llvm/Analysis/LoadValueNumbering.h"
38#include "llvm/LinkTimeOptimizer.h"
39#include <fstream>
40#include <iostream>
41
42using namespace llvm;
43
44extern "C"
45llvm::LinkTimeOptimizer *createLLVMOptimizer()
46{
Devang Patelc7cfbc52006-09-21 17:22:55 +000047 llvm::LTO *l = new llvm::LTO();
Devang Patela89d47f2006-08-03 15:44:57 +000048 return l;
49}
50
51
52
53/// If symbol is not used then make it internal and let optimizer takes
54/// care of it.
55void LLVMSymbol::mayBeNotUsed() {
56 gv->setLinkage(GlobalValue::InternalLinkage);
57}
58
59// Helper routine
60// FIXME : Take advantage of GlobalPrefix from AsmPrinter
61static const char *addUnderscore(const char *name) {
62 size_t namelen = strlen(name);
63 char *symName = (char*)malloc(namelen+2);
64 symName[0] = '_';
65 strcpy(&symName[1], name);
66 return symName;
67}
68
69// Map LLVM LinkageType to LTO LinakgeType
70static LTOLinkageTypes
71getLTOLinkageType(GlobalValue *v)
72{
73 LTOLinkageTypes lt;
74 if (v->hasExternalLinkage())
75 lt = LTOExternalLinkage;
76 else if (v->hasLinkOnceLinkage())
77 lt = LTOLinkOnceLinkage;
78 else if (v->hasWeakLinkage())
79 lt = LTOWeakLinkage;
80 else
81 // Otherwise it is internal linkage for link time optimizer
82 lt = LTOInternalLinkage;
83 return lt;
84}
85
86// Find exeternal symbols referenced by VALUE. This is a recursive function.
87static void
Devang Patel30235da2006-08-14 22:36:16 +000088findExternalRefs(Value *value, std::set<std::string> &references,
Devang Patel2198f9c2006-08-14 23:37:18 +000089 Mangler &mangler) {
Devang Patel304d5f22006-08-04 19:10:26 +000090
91 if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) {
Devang Patela89d47f2006-08-03 15:44:57 +000092 LTOLinkageTypes lt = getLTOLinkageType(gv);
93 if (lt != LTOInternalLinkage && strncmp (gv->getName().c_str(), "llvm.", 5))
Devang Patel30235da2006-08-14 22:36:16 +000094 references.insert(mangler.getValueName(gv));
Devang Patela89d47f2006-08-03 15:44:57 +000095 }
Devang Patel544ea342006-09-14 05:49:10 +000096
97 // GlobalValue, even with InternalLinkage type, may have operands with
98 // ExternalLinkage type. Do not ignore these operands.
Devang Patel97d92d52006-09-14 01:35:13 +000099 if (Constant *c = dyn_cast<Constant>(value))
Devang Patel304d5f22006-08-04 19:10:26 +0000100 // Handle ConstantExpr, ConstantStruct, ConstantArry etc..
101 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
Devang Patel30235da2006-08-14 22:36:16 +0000102 findExternalRefs(c->getOperand(i), references, mangler);
Devang Patela89d47f2006-08-03 15:44:57 +0000103}
104
Devang Patelf2ca21f2006-10-23 23:12:26 +0000105/// If Moduel with InputFilename is available then remove it.
106void
107LTO::removeModule (const std::string &InputFilename)
108{
109 NameToModuleMap::iterator pos = allModules.find(InputFilename.c_str());
110 if (pos != allModules.end()) {
111 Module *m = allModules[InputFilename.c_str()];
112 allModules.erase(pos);
113 delete m;
114 }
115}
116
Devang Patel0701a2f2006-09-06 18:50:26 +0000117/// InputFilename is a LLVM bytecode file. If Module with InputFilename is
118/// available then return it. Otherwise parseInputFilename.
119Module *
Devang Patelc7cfbc52006-09-21 17:22:55 +0000120LTO::getModule(const std::string &InputFilename)
Devang Patel0701a2f2006-09-06 18:50:26 +0000121{
122 Module *m = NULL;
123
124 NameToModuleMap::iterator pos = allModules.find(InputFilename.c_str());
125 if (pos != allModules.end())
126 m = allModules[InputFilename.c_str()];
127 else {
128 m = ParseBytecodeFile(InputFilename);
129 allModules[InputFilename.c_str()] = m;
130 }
131 return m;
132}
133
Devang Patela291a682006-09-06 20:16:28 +0000134/// InputFilename is a LLVM bytecode file. Reade this bytecode file and
135/// set corresponding target triplet string.
136void
Devang Patelc7cfbc52006-09-21 17:22:55 +0000137LTO::getTargetTriple(const std::string &InputFilename,
Devang Patela291a682006-09-06 20:16:28 +0000138 std::string &targetTriple)
139{
140 Module *m = getModule(InputFilename);
141 if (m)
142 targetTriple = m->getTargetTriple();
143}
144
Devang Patela89d47f2006-08-03 15:44:57 +0000145/// InputFilename is a LLVM bytecode file. Read it using bytecode reader.
146/// Collect global functions and symbol names in symbols vector.
147/// Collect external references in references vector.
148/// Return LTO_READ_SUCCESS if there is no error.
149enum LTOStatus
Devang Patelc7cfbc52006-09-21 17:22:55 +0000150LTO::readLLVMObjectFile(const std::string &InputFilename,
Devang Patel2198f9c2006-08-14 23:37:18 +0000151 NameToSymbolMap &symbols,
152 std::set<std::string> &references)
Devang Patela89d47f2006-08-03 15:44:57 +0000153{
Devang Patel0701a2f2006-09-06 18:50:26 +0000154 Module *m = getModule(InputFilename);
Devang Patela89d47f2006-08-03 15:44:57 +0000155 if (!m)
156 return LTO_READ_FAILURE;
Devang Patel30235da2006-08-14 22:36:16 +0000157
158 // Use mangler to add GlobalPrefix to names to match linker names.
159 // FIXME : Instead of hard coding "-" use GlobalPrefix.
160 Mangler mangler(*m, "_");
Devang Patela89d47f2006-08-03 15:44:57 +0000161
162 modules.push_back(m);
163
164 for (Module::iterator f = m->begin(), e = m->end(); f != e; ++f) {
165
166 LTOLinkageTypes lt = getLTOLinkageType(f);
167
168 if (!f->isExternal() && lt != LTOInternalLinkage
Devang Patel2198f9c2006-08-14 23:37:18 +0000169 && strncmp (f->getName().c_str(), "llvm.", 5)) {
Devang Patel30235da2006-08-14 22:36:16 +0000170 LLVMSymbol *newSymbol = new LLVMSymbol(lt, f, f->getName(),
Devang Patel2198f9c2006-08-14 23:37:18 +0000171 mangler.getValueName(f));
Devang Patel30235da2006-08-14 22:36:16 +0000172 symbols[newSymbol->getMangledName()] = newSymbol;
173 allSymbols[newSymbol->getMangledName()] = newSymbol;
Devang Patela89d47f2006-08-03 15:44:57 +0000174 }
Devang Patel30235da2006-08-14 22:36:16 +0000175
Devang Patela89d47f2006-08-03 15:44:57 +0000176 // Collect external symbols referenced by this function.
177 for (Function::iterator b = f->begin(), fe = f->end(); b != fe; ++b)
178 for (BasicBlock::iterator i = b->begin(), be = b->end();
Devang Patel2198f9c2006-08-14 23:37:18 +0000179 i != be; ++i)
180 for (unsigned count = 0, total = i->getNumOperands();
181 count != total; ++count)
182 findExternalRefs(i->getOperand(count), references, mangler);
Devang Patela89d47f2006-08-03 15:44:57 +0000183 }
184
185 for (Module::global_iterator v = m->global_begin(), e = m->global_end();
186 v != e; ++v) {
187 LTOLinkageTypes lt = getLTOLinkageType(v);
188 if (!v->isExternal() && lt != LTOInternalLinkage
Devang Patel2198f9c2006-08-14 23:37:18 +0000189 && strncmp (v->getName().c_str(), "llvm.", 5)) {
Devang Patel30235da2006-08-14 22:36:16 +0000190 LLVMSymbol *newSymbol = new LLVMSymbol(lt, v, v->getName(),
Devang Patel2198f9c2006-08-14 23:37:18 +0000191 mangler.getValueName(v));
Devang Patel30235da2006-08-14 22:36:16 +0000192 symbols[newSymbol->getMangledName()] = newSymbol;
Devang Pateled872862006-09-06 00:45:52 +0000193 allSymbols[newSymbol->getMangledName()] = newSymbol;
Devang Patel304d5f22006-08-04 19:10:26 +0000194
195 for (unsigned count = 0, total = v->getNumOperands();
Devang Patel2198f9c2006-08-14 23:37:18 +0000196 count != total; ++count)
197 findExternalRefs(v->getOperand(count), references, mangler);
Devang Patel304d5f22006-08-04 19:10:26 +0000198
Devang Patela89d47f2006-08-03 15:44:57 +0000199 }
200 }
201
202 return LTO_READ_SUCCESS;
203}
204
205/// Optimize module M using various IPO passes. Use exportList to
206/// internalize selected symbols. Target platform is selected
207/// based on information available to module M. No new target
208/// features are selected.
209static enum LTOStatus lto_optimize(Module *M, std::ostream &Out,
Devang Patel2198f9c2006-08-14 23:37:18 +0000210 std::vector<const char *> &exportList)
Devang Patela89d47f2006-08-03 15:44:57 +0000211{
212 // Instantiate the pass manager to organize the passes.
213 PassManager Passes;
214
215 // Collect Target info
216 std::string Err;
217 const TargetMachineRegistry::Entry* March =
218 TargetMachineRegistry::getClosestStaticTargetForModule(*M, Err);
219
220 if (March == 0)
221 return LTO_NO_TARGET;
222
223 // Create target
224 std::string Features;
225 std::auto_ptr<TargetMachine> target(March->CtorFn(*M, Features));
226 if (!target.get())
227 return LTO_NO_TARGET;
228
229 TargetMachine &Target = *target.get();
230
231 // Start off with a verification pass.
232 Passes.add(createVerifierPass());
233
234 // Add an appropriate TargetData instance for this module...
235 Passes.add(new TargetData(*Target.getTargetData()));
236
237 // Often if the programmer does not specify proper prototypes for the
238 // functions they are calling, they end up calling a vararg version of the
239 // function that does not get a body filled in (the real function has typed
240 // arguments). This pass merges the two functions.
241 Passes.add(createFunctionResolvingPass());
242
243 // Internalize symbols if export list is nonemty
244 if (!exportList.empty())
245 Passes.add(createInternalizePass(exportList));
246
247 // Now that we internalized some globals, see if we can hack on them!
248 Passes.add(createGlobalOptimizerPass());
249
250 // Linking modules together can lead to duplicated global constants, only
251 // keep one copy of each constant...
252 Passes.add(createConstantMergePass());
253
254 // If the -s command line option was specified, strip the symbols out of the
255 // resulting program to make it smaller. -s is a GLD option that we are
256 // supporting.
257 Passes.add(createStripSymbolsPass());
258
259 // Propagate constants at call sites into the functions they call.
260 Passes.add(createIPConstantPropagationPass());
261
262 // Remove unused arguments from functions...
263 Passes.add(createDeadArgEliminationPass());
264
265 Passes.add(createFunctionInliningPass()); // Inline small functions
266
267 Passes.add(createPruneEHPass()); // Remove dead EH info
268
269 Passes.add(createGlobalDCEPass()); // Remove dead functions
270
271 // If we didn't decide to inline a function, check to see if we can
272 // transform it to pass arguments by value instead of by reference.
273 Passes.add(createArgumentPromotionPass());
274
275 // The IPO passes may leave cruft around. Clean up after them.
276 Passes.add(createInstructionCombiningPass());
277
278 Passes.add(createScalarReplAggregatesPass()); // Break up allocas
279
280 // Run a few AA driven optimizations here and now, to cleanup the code.
281 Passes.add(createGlobalsModRefPass()); // IP alias analysis
282
283 Passes.add(createLICMPass()); // Hoist loop invariants
284 Passes.add(createLoadValueNumberingPass()); // GVN for load instrs
285 Passes.add(createGCSEPass()); // Remove common subexprs
286 Passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
287
288 // Cleanup and simplify the code after the scalar optimizations.
289 Passes.add(createInstructionCombiningPass());
290
291 // Delete basic blocks, which optimization passes may have killed...
292 Passes.add(createCFGSimplificationPass());
293
294 // Now that we have optimized the program, discard unreachable functions...
295 Passes.add(createGlobalDCEPass());
296
297 // Make sure everything is still good.
298 Passes.add(createVerifierPass());
299
Devang Patel998051a2006-09-07 21:41:11 +0000300 FunctionPassManager *CodeGenPasses =
301 new FunctionPassManager(new ExistingModuleProvider(M));
302
303 CodeGenPasses->add(new TargetData(*Target.getTargetData()));
304 Target.addPassesToEmitFile(*CodeGenPasses, Out, TargetMachine::AssemblyFile,
305 true);
Devang Patela89d47f2006-08-03 15:44:57 +0000306
307 // Run our queue of passes all at once now, efficiently.
308 Passes.run(*M);
309
Devang Patel998051a2006-09-07 21:41:11 +0000310 // Run the code generator, if present.
311 CodeGenPasses->doInitialization();
312 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
313 if (!I->isExternal())
314 CodeGenPasses->run(*I);
315 }
316 CodeGenPasses->doFinalization();
317
Devang Patela89d47f2006-08-03 15:44:57 +0000318 return LTO_OPT_SUCCESS;
319}
320
321///Link all modules together and optimize them using IPO. Generate
322/// native object file using OutputFilename
323/// Return appropriate LTOStatus.
324enum LTOStatus
Devang Patelc7cfbc52006-09-21 17:22:55 +0000325LTO::optimizeModules(const std::string &OutputFilename,
Devang Patel26810232006-09-06 00:28:22 +0000326 std::vector<const char *> &exportList,
327 std::string &targetTriple)
Devang Patela89d47f2006-08-03 15:44:57 +0000328{
329 if (modules.empty())
330 return LTO_NO_WORK;
331
332 std::ios::openmode io_mode =
333 std::ios::out | std::ios::trunc | std::ios::binary;
334 std::string *errMsg = NULL;
335 Module *bigOne = modules[0];
336 Linker theLinker("LinkTimeOptimizer", bigOne, false);
337 for (unsigned i = 1, e = modules.size(); i != e; ++i)
338 if (theLinker.LinkModules(bigOne, modules[i], errMsg))
339 return LTO_MODULE_MERGE_FAILURE;
340
341#if 0
342 // Enable this when -save-temps is used
343 std::ofstream Out("big.bc", io_mode);
344 WriteBytecodeToFile(bigOne, Out, true);
345#endif
346
347 // Strip leading underscore because it was added to match names
Devang Patel94a0ac92006-08-03 17:25:36 +0000348 // seen by linker.
Devang Patela89d47f2006-08-03 15:44:57 +0000349 for (unsigned i = 0, e = exportList.size(); i != e; ++i) {
350 const char *name = exportList[i];
Devang Pateled872862006-09-06 00:45:52 +0000351 NameToSymbolMap::iterator itr = allSymbols.find(name);
352 if (itr != allSymbols.end())
353 exportList[i] = allSymbols[name]->getName();
Devang Patela89d47f2006-08-03 15:44:57 +0000354 }
355
Devang Patel3f0e5e22006-10-09 19:04:51 +0000356
Reid Spencere5c9cb52006-08-23 00:39:35 +0000357 std::string ErrMsg;
Devang Patel3f0e5e22006-10-09 19:04:51 +0000358 sys::Path TempDir = sys::Path::GetTemporaryDirectory(&ErrMsg);
Devang Patel9f5d48b2006-10-09 20:20:13 +0000359 if (TempDir.isEmpty()) {
360 std::cerr << "lto: " << ErrMsg << "\n";
361 return LTO_WRITE_FAILURE;
362 }
Devang Patel3f0e5e22006-10-09 19:04:51 +0000363 sys::Path tmpAsmFilePath(TempDir);
364 if (!tmpAsmFilePath.appendComponent("lto")) {
365 std::cerr << "lto: " << ErrMsg << "\n";
366 TempDir.eraseFromDisk(true);
367 return LTO_WRITE_FAILURE;
368 }
Reid Spencere5c9cb52006-08-23 00:39:35 +0000369 if (tmpAsmFilePath.createTemporaryFileOnDisk(&ErrMsg)) {
370 std::cerr << "lto: " << ErrMsg << "\n";
Devang Patel3f0e5e22006-10-09 19:04:51 +0000371 TempDir.eraseFromDisk(true);
Devang Patelca640122006-08-23 16:59:25 +0000372 return LTO_WRITE_FAILURE;
Reid Spencere5c9cb52006-08-23 00:39:35 +0000373 }
Devang Patela89d47f2006-08-03 15:44:57 +0000374 sys::RemoveFileOnSignal(tmpAsmFilePath);
375
376 std::ofstream asmFile(tmpAsmFilePath.c_str(), io_mode);
377 if (!asmFile.is_open() || asmFile.bad()) {
Devang Patel3f0e5e22006-10-09 19:04:51 +0000378 if (tmpAsmFilePath.exists()) {
Devang Patela89d47f2006-08-03 15:44:57 +0000379 tmpAsmFilePath.eraseFromDisk();
Devang Patel3f0e5e22006-10-09 19:04:51 +0000380 TempDir.eraseFromDisk(true);
381 }
Devang Patela89d47f2006-08-03 15:44:57 +0000382 return LTO_WRITE_FAILURE;
383 }
384
385 enum LTOStatus status = lto_optimize(bigOne, asmFile, exportList);
386 asmFile.close();
387 if (status != LTO_OPT_SUCCESS) {
388 tmpAsmFilePath.eraseFromDisk();
Devang Patel3f0e5e22006-10-09 19:04:51 +0000389 TempDir.eraseFromDisk(true);
Devang Patela89d47f2006-08-03 15:44:57 +0000390 return status;
391 }
392
Devang Patel26810232006-09-06 00:28:22 +0000393 targetTriple = bigOne->getTargetTriple();
394
Devang Patela89d47f2006-08-03 15:44:57 +0000395 // Run GCC to assemble and link the program into native code.
396 //
397 // Note:
398 // We can't just assemble and link the file with the system assembler
399 // and linker because we don't know where to put the _start symbol.
400 // GCC mysteriously knows how to do it.
Devang Pateldc4c3822006-10-09 21:16:05 +0000401 const sys::Path gcc = sys::Program::FindProgramByName("gcc");
Devang Patela89d47f2006-08-03 15:44:57 +0000402 if (gcc.isEmpty()) {
403 tmpAsmFilePath.eraseFromDisk();
Devang Patel3f0e5e22006-10-09 19:04:51 +0000404 TempDir.eraseFromDisk(true);
Devang Patela89d47f2006-08-03 15:44:57 +0000405 return LTO_ASM_FAILURE;
406 }
407
408 std::vector<const char*> args;
409 args.push_back(gcc.c_str());
410 args.push_back("-c");
411 args.push_back("-x");
412 args.push_back("assembler");
413 args.push_back("-o");
414 args.push_back(OutputFilename.c_str());
415 args.push_back(tmpAsmFilePath.c_str());
416 args.push_back(0);
417
Devang Patel9f5d48b2006-10-09 20:20:13 +0000418 if (sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 1, &ErrMsg)) {
419 std::cerr << "lto: " << ErrMsg << "\n";
420 return LTO_ASM_FAILURE;
421 }
Devang Patela89d47f2006-08-03 15:44:57 +0000422
423 tmpAsmFilePath.eraseFromDisk();
Devang Patel3f0e5e22006-10-09 19:04:51 +0000424 TempDir.eraseFromDisk(true);
Devang Patela89d47f2006-08-03 15:44:57 +0000425
426 return LTO_OPT_SUCCESS;
427}