blob: c4d7e8abe72ca13a38a50e75582d58a2ba0f5b43 [file] [log] [blame]
Nick Kledzik77595fc2008-02-26 20:26:43 +00001//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Nick Kledzikef194ed2008-02-27 22:25:36 +000015#include "LTOModule.h"
16#include "LTOCodeGenerator.h"
17
Nick Kledzik77595fc2008-02-26 20:26:43 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000020#include "llvm/Linker.h"
Owen Anderson0e7a5462009-07-02 00:31:14 +000021#include "llvm/LLVMContext.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000022#include "llvm/Module.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000023#include "llvm/PassManager.h"
24#include "llvm/ADT/StringExtras.h"
Viktor Kutuzov51cdac02009-11-17 18:48:27 +000025#include "llvm/ADT/Triple.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000026#include "llvm/Analysis/Passes.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000027#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000028#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCContext.h"
30#include "llvm/Target/Mangler.h"
31#include "llvm/Target/SubtargetFeature.h"
32#include "llvm/Target/TargetOptions.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetRegistry.h"
36#include "llvm/Target/TargetSelect.h"
Nick Kledzik920ae982008-07-08 21:14:10 +000037#include "llvm/Support/CommandLine.h"
David Greene71847812009-07-14 20:18:05 +000038#include "llvm/Support/FormattedStream.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000039#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar006a0342009-06-03 21:06:14 +000040#include "llvm/Support/StandardPasses.h"
41#include "llvm/Support/SystemUtils.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000042#include "llvm/System/Host.h"
Chris Lattnerb683ea42009-08-23 21:36:09 +000043#include "llvm/System/Program.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000044#include "llvm/System/Signals.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000045#include "llvm/Config/config.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000046#include <cstdlib>
Nick Kledzik77595fc2008-02-26 20:26:43 +000047#include <unistd.h>
Nick Kledzik77595fc2008-02-26 20:26:43 +000048#include <fcntl.h>
49
50
51using namespace llvm;
52
Nick Kledzik920ae982008-07-08 21:14:10 +000053static cl::opt<bool> DisableInline("disable-inlining",
54 cl::desc("Do not run the inliner pass"));
Nick Kledzik77595fc2008-02-26 20:26:43 +000055
56
57const char* LTOCodeGenerator::getVersionString()
58{
59#ifdef LLVM_VERSION_INFO
60 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
61#else
62 return PACKAGE_NAME " version " PACKAGE_VERSION;
63#endif
64}
65
66
Owen Anderson0e7a5462009-07-02 00:31:14 +000067LTOCodeGenerator::LTOCodeGenerator()
68 : _context(getGlobalContext()),
Owen Anderson8b477ed2009-07-01 16:58:40 +000069 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
Nick Kledzik77595fc2008-02-26 20:26:43 +000070 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Nick Kledzikef194ed2008-02-27 22:25:36 +000071 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Nick Lewycky3e4c41a2009-08-03 07:16:42 +000072 _nativeObjectFile(NULL), _assemblerPath(NULL)
Nick Kledzik77595fc2008-02-26 20:26:43 +000073{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +000074 InitializeAllTargets();
75 InitializeAllAsmPrinters();
Nick Kledzik77595fc2008-02-26 20:26:43 +000076}
77
78LTOCodeGenerator::~LTOCodeGenerator()
79{
Nick Kledzikef194ed2008-02-27 22:25:36 +000080 delete _target;
81 delete _nativeObjectFile;
Nick Kledzik77595fc2008-02-26 20:26:43 +000082}
83
84
85
86bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
87{
88 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
89}
90
91
92bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
93{
94 switch (debug) {
95 case LTO_DEBUG_MODEL_NONE:
96 _emitDwarfDebugInfo = false;
97 return false;
98
99 case LTO_DEBUG_MODEL_DWARF:
100 _emitDwarfDebugInfo = true;
101 return false;
102 }
103 errMsg = "unknown debug format";
104 return true;
105}
106
107
108bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
Evan Cheng855a1682009-06-26 06:57:16 +0000109 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000110{
111 switch (model) {
112 case LTO_CODEGEN_PIC_MODEL_STATIC:
113 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
114 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
115 _codeModel = model;
116 return false;
117 }
118 errMsg = "unknown pic model";
119 return true;
120}
121
Nick Kledzikcbad5862009-06-04 00:28:45 +0000122void LTOCodeGenerator::setAssemblerPath(const char* path)
123{
124 if ( _assemblerPath )
125 delete _assemblerPath;
126 _assemblerPath = new sys::Path(path);
127}
128
Nick Kledzik77595fc2008-02-26 20:26:43 +0000129void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
130{
131 _mustPreserveSymbols[sym] = 1;
132}
133
134
Chris Lattnerb515d752009-08-23 07:49:08 +0000135bool LTOCodeGenerator::writeMergedModules(const char *path,
136 std::string &errMsg) {
137 if (determineTarget(errMsg))
138 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000139
Chris Lattnerb515d752009-08-23 07:49:08 +0000140 // mark which symbols can not be internalized
141 applyScopeRestrictions();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000142
Chris Lattnerb515d752009-08-23 07:49:08 +0000143 // create output file
144 std::string ErrInfo;
145 raw_fd_ostream Out(path, ErrInfo,
Dan Gohmanbaa26392009-08-25 15:34:52 +0000146 raw_fd_ostream::F_Binary);
Chris Lattnerb515d752009-08-23 07:49:08 +0000147 if (!ErrInfo.empty()) {
148 errMsg = "could not open bitcode file for writing: ";
149 errMsg += path;
150 return true;
151 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000152
Chris Lattnerb515d752009-08-23 07:49:08 +0000153 // write bitcode to it
154 WriteBitcodeToFile(_linker.getModule(), Out);
Dan Gohman4b7416b2010-05-27 20:19:47 +0000155 Out.close();
156
Chris Lattnerb515d752009-08-23 07:49:08 +0000157 if (Out.has_error()) {
158 errMsg = "could not write bitcode file: ";
159 errMsg += path;
Dan Gohman4b7416b2010-05-27 20:19:47 +0000160 Out.clear_error();
Chris Lattnerb515d752009-08-23 07:49:08 +0000161 return true;
162 }
163
164 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000165}
166
167
Nick Kledzikef194ed2008-02-27 22:25:36 +0000168const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000169{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000170 // make unique temp .s file to put generated assembly code
Nick Kledzik77595fc2008-02-26 20:26:43 +0000171 sys::Path uniqueAsmPath("lto-llvm.s");
172 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
173 return NULL;
174 sys::RemoveFileOnSignal(uniqueAsmPath);
175
176 // generate assembly code
Owen Andersoncb371882008-08-21 00:14:44 +0000177 bool genResult = false;
178 {
Dan Gohmanbaa26392009-08-25 15:34:52 +0000179 raw_fd_ostream asmFD(uniqueAsmPath.c_str(), errMsg);
David Greene71847812009-07-14 20:18:05 +0000180 formatted_raw_ostream asmFile(asmFD);
Dan Gohmaned3e8b42008-08-21 15:33:45 +0000181 if (!errMsg.empty())
182 return NULL;
Owen Andersoncb371882008-08-21 00:14:44 +0000183 genResult = this->generateAssemblyCode(asmFile, errMsg);
184 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000185 if ( genResult ) {
186 if ( uniqueAsmPath.exists() )
187 uniqueAsmPath.eraseFromDisk();
188 return NULL;
189 }
190
Nick Kledzikef194ed2008-02-27 22:25:36 +0000191 // make unique temp .o file to put generated object file
Nick Kledzik77595fc2008-02-26 20:26:43 +0000192 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
193 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
194 if ( uniqueAsmPath.exists() )
195 uniqueAsmPath.eraseFromDisk();
196 return NULL;
197 }
198 sys::RemoveFileOnSignal(uniqueObjPath);
199
200 // assemble the assembly code
Chris Lattner74382b72009-08-23 22:45:37 +0000201 const std::string& uniqueObjStr = uniqueObjPath.str();
202 bool asmResult = this->assemble(uniqueAsmPath.str(), uniqueObjStr, errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000203 if ( !asmResult ) {
Nick Kledzikef194ed2008-02-27 22:25:36 +0000204 // remove old buffer if compile() called twice
205 delete _nativeObjectFile;
206
Nick Kledzik77595fc2008-02-26 20:26:43 +0000207 // read .o file into memory buffer
Chris Lattner038112a2008-04-01 18:04:03 +0000208 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000209 }
Nick Kledzikef194ed2008-02-27 22:25:36 +0000210
211 // remove temp files
Nick Kledzik77595fc2008-02-26 20:26:43 +0000212 uniqueAsmPath.eraseFromDisk();
213 uniqueObjPath.eraseFromDisk();
Nick Kledzikef194ed2008-02-27 22:25:36 +0000214
215 // return buffer, unless error
216 if ( _nativeObjectFile == NULL )
217 return NULL;
218 *length = _nativeObjectFile->getBufferSize();
219 return _nativeObjectFile->getBufferStart();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000220}
221
222
223bool LTOCodeGenerator::assemble(const std::string& asmPath,
224 const std::string& objPath, std::string& errMsg)
225{
Nick Kledzikcbad5862009-06-04 00:28:45 +0000226 sys::Path tool;
227 bool needsCompilerOptions = true;
228 if ( _assemblerPath ) {
229 tool = *_assemblerPath;
230 needsCompilerOptions = false;
Nick Lewycky195bea32009-04-30 15:24:09 +0000231 } else {
232 // find compiler driver
Nick Kledzikcbad5862009-06-04 00:28:45 +0000233 tool = sys::Program::FindProgramByName("gcc");
234 if ( tool.isEmpty() ) {
Nick Lewycky195bea32009-04-30 15:24:09 +0000235 errMsg = "can't locate gcc";
236 return true;
237 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000238 }
239
240 // build argument list
241 std::vector<const char*> args;
Viktor Kutuzov51cdac02009-11-17 18:48:27 +0000242 llvm::Triple targetTriple(_linker.getModule()->getTargetTriple());
243 const char *arch = targetTriple.getArchNameForAssembler();
244
Nick Kledzikcbad5862009-06-04 00:28:45 +0000245 args.push_back(tool.c_str());
Viktor Kutuzov51cdac02009-11-17 18:48:27 +0000246
247 if (targetTriple.getOS() == Triple::Darwin) {
Nick Kledzikd8b47112009-06-04 19:14:08 +0000248 // darwin specific command line options
Viktor Kutuzov51cdac02009-11-17 18:48:27 +0000249 if (arch != NULL) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000250 args.push_back("-arch");
Viktor Kutuzov51cdac02009-11-17 18:48:27 +0000251 args.push_back(arch);
Bob Wilson75d6ffd2009-06-22 18:01:28 +0000252 }
Nick Kledzikd8b47112009-06-04 19:14:08 +0000253 // add -static to assembler command line when code model requires
Chris Lattner5ef31a02010-03-12 18:44:54 +0000254 if ( (_assemblerPath != NULL) &&
255 (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
Nick Kledzikd8b47112009-06-04 19:14:08 +0000256 args.push_back("-static");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000257 }
Nick Kledzikcbad5862009-06-04 00:28:45 +0000258 if ( needsCompilerOptions ) {
259 args.push_back("-c");
260 args.push_back("-x");
261 args.push_back("assembler");
262 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000263 args.push_back("-o");
264 args.push_back(objPath.c_str());
265 args.push_back(asmPath.c_str());
266 args.push_back(0);
267
268 // invoke assembler
Nick Kledzikcbad5862009-06-04 00:28:45 +0000269 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000270 errMsg = "error in assembly";
271 return true;
272 }
273 return false; // success
274}
275
276
277
278bool LTOCodeGenerator::determineTarget(std::string& errMsg)
279{
280 if ( _target == NULL ) {
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000281 std::string Triple = _linker.getModule()->getTargetTriple();
282 if (Triple.empty())
283 Triple = sys::getHostTriple();
284
Nick Kledzik77595fc2008-02-26 20:26:43 +0000285 // create target machine from info for merged modules
Daniel Dunbar4bd03ab2009-08-03 04:20:57 +0000286 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000287 if ( march == NULL )
288 return true;
Bill Wendling604a8182008-06-18 06:35:30 +0000289
Nick Kledzikf5a1c35f12009-06-03 22:52:12 +0000290 // The relocation model is actually a static member of TargetMachine
291 // and needs to be set before the TargetMachine is instantiated.
292 switch( _codeModel ) {
293 case LTO_CODEGEN_PIC_MODEL_STATIC:
294 TargetMachine::setRelocationModel(Reloc::Static);
295 break;
296 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
297 TargetMachine::setRelocationModel(Reloc::PIC_);
298 break;
299 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
300 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
301 break;
302 }
303
Bill Wendling604a8182008-06-18 06:35:30 +0000304 // construct LTModule, hand over ownership of module and target
Bill Wendling81043ee2010-05-11 00:30:02 +0000305 SubtargetFeatures Features;
306 Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
307 std::string FeatureStr = Features.getString();
Viktor Kutuzov308f6632009-11-25 22:44:18 +0000308 _target = march->createTargetMachine(Triple, FeatureStr);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000309 }
310 return false;
311}
312
Chris Lattner5ef31a02010-03-12 18:44:54 +0000313void LTOCodeGenerator::applyScopeRestrictions() {
314 if (_scopeRestrictionsDone) return;
315 Module *mergedModule = _linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000316
Chris Lattner5ef31a02010-03-12 18:44:54 +0000317 // Start off with a verification pass.
318 PassManager passes;
319 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000320
Chris Lattner5ef31a02010-03-12 18:44:54 +0000321 // mark which symbols can not be internalized
322 if (!_mustPreserveSymbols.empty()) {
323 MCContext Context(*_target->getMCAsmInfo());
Chris Lattnerb87c3052010-03-12 20:47:28 +0000324 Mangler mangler(Context, *_target->getTargetData());
Chris Lattner5ef31a02010-03-12 18:44:54 +0000325 std::vector<const char*> mustPreserveList;
326 for (Module::iterator f = mergedModule->begin(),
327 e = mergedModule->end(); f != e; ++f) {
328 if (!f->isDeclaration() &&
329 _mustPreserveSymbols.count(mangler.getNameWithPrefix(f)))
330 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
Nick Kledzik77595fc2008-02-26 20:26:43 +0000331 }
Chris Lattner5ef31a02010-03-12 18:44:54 +0000332 for (Module::global_iterator v = mergedModule->global_begin(),
333 e = mergedModule->global_end(); v != e; ++v) {
Bill Wendlingc3d0e0c2010-04-27 00:55:25 +0000334 if (!v->isDeclaration() &&
Chris Lattner5ef31a02010-03-12 18:44:54 +0000335 _mustPreserveSymbols.count(mangler.getNameWithPrefix(v)))
336 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
337 }
338 passes.add(createInternalizePass(mustPreserveList));
339 }
340
341 // apply scope restrictions
342 passes.run(*mergedModule);
343
344 _scopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000345}
346
Nick Kledzik77595fc2008-02-26 20:26:43 +0000347/// Optimize merged modules using various IPO passes
David Greene71847812009-07-14 20:18:05 +0000348bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
Owen Andersoncb371882008-08-21 00:14:44 +0000349 std::string& errMsg)
Nick Kledzik77595fc2008-02-26 20:26:43 +0000350{
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000351 if ( this->determineTarget(errMsg) )
Nick Kledzik77595fc2008-02-26 20:26:43 +0000352 return true;
353
354 // mark which symbols can not be internalized
355 this->applyScopeRestrictions();
356
357 Module* mergedModule = _linker.getModule();
358
Nick Kledzik920ae982008-07-08 21:14:10 +0000359 // if options were requested, set them
360 if ( !_codegenOptions.empty() )
361 cl::ParseCommandLineOptions(_codegenOptions.size(),
Dan Gohman43bc70e2010-04-17 17:44:03 +0000362 const_cast<char **>(&_codegenOptions[0]));
Devang Patela93ae712008-07-03 22:53:14 +0000363
Nick Kledzik77595fc2008-02-26 20:26:43 +0000364 // Instantiate the pass manager to organize the passes.
365 PassManager passes;
366
367 // Start off with a verification pass.
368 passes.add(createVerifierPass());
369
370 // Add an appropriate TargetData instance for this module...
371 passes.add(new TargetData(*_target->getTargetData()));
372
Daniel Dunbar006a0342009-06-03 21:06:14 +0000373 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
Daniel Dunbar006a0342009-06-03 21:06:14 +0000374 /*VerifyEach=*/ false);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000375
376 // Make sure everything is still good.
377 passes.add(createVerifierPass());
378
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000379 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000380
381 codeGenPasses->add(new TargetData(*_target->getTargetData()));
382
Chris Lattner5669e302010-02-03 05:55:08 +0000383 if (_target->addPassesToEmitFile(*codeGenPasses, out,
384 TargetMachine::CGFT_AssemblyFile,
385 CodeGenOpt::Aggressive)) {
386 errMsg = "target file type not supported";
387 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000388 }
389
Nick Kledzik77595fc2008-02-26 20:26:43 +0000390 // Run our queue of passes all at once now, efficiently.
391 passes.run(*mergedModule);
392
393 // Run the code generator, and write assembly file
394 codeGenPasses->doInitialization();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000395
Bill Wendling604a8182008-06-18 06:35:30 +0000396 for (Module::iterator
397 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
398 if (!it->isDeclaration())
399 codeGenPasses->run(*it);
400
401 codeGenPasses->doFinalization();
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000402
Nick Kledzik77595fc2008-02-26 20:26:43 +0000403 return false; // success
404}
405
406
Nick Kledzik920ae982008-07-08 21:14:10 +0000407/// Optimize merged modules using various IPO passes
408void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
409{
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000410 for (std::pair<StringRef, StringRef> o = getToken(options);
411 !o.first.empty(); o = getToken(o.second)) {
Nick Kledzik920ae982008-07-08 21:14:10 +0000412 // ParseCommandLineOptions() expects argv[0] to be program name.
413 // Lazily add that.
414 if ( _codegenOptions.empty() )
415 _codegenOptions.push_back("libLTO");
Benjamin Kramerd4f19592010-01-11 18:03:24 +0000416 _codegenOptions.push_back(strdup(o.first.str().c_str()));
Nick Kledzik920ae982008-07-08 21:14:10 +0000417 }
418}