blob: 6f5e6bc77133717f628a04a65a23a7b381da6741 [file] [log] [blame]
Nick Kledzik6d886992008-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 Kledzik79d0a052008-02-27 22:25:36 +000015#include "LTOModule.h"
16#include "LTOCodeGenerator.h"
17
18
Nick Kledzik6d886992008-02-26 20:26:43 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
Nick Lewycky3d1feeb2009-06-17 06:52:10 +000021#include "llvm/Linker.h"
22#include "llvm/Module.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000023#include "llvm/ModuleProvider.h"
Nick Lewycky3d1feeb2009-06-17 06:52:10 +000024#include "llvm/PassManager.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/Analysis/Passes.h"
27#include "llvm/Analysis/LoopPass.h"
28#include "llvm/Analysis/Verifier.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000029#include "llvm/Bitcode/ReaderWriter.h"
Nick Lewycky3d1feeb2009-06-17 06:52:10 +000030#include "llvm/CodeGen/FileWriters.h"
Nick Kledzik4059fb12008-07-08 21:14:10 +000031#include "llvm/Support/CommandLine.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000032#include "llvm/Support/Mangler.h"
33#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar9068de52009-06-03 21:06:14 +000034#include "llvm/Support/StandardPasses.h"
35#include "llvm/Support/SystemUtils.h"
Owen Anderson847b99b2008-08-21 00:14:44 +000036#include "llvm/Support/raw_ostream.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000037#include "llvm/System/Signals.h"
Bill Wendling568e37c2008-06-18 06:35:30 +000038#include "llvm/Target/SubtargetFeature.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000039#include "llvm/Target/TargetOptions.h"
Chris Lattner41788082009-06-17 16:42:19 +000040#include "llvm/Target/TargetAsmInfo.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000041#include "llvm/Target/TargetData.h"
42#include "llvm/Target/TargetMachine.h"
43#include "llvm/Target/TargetMachineRegistry.h"
Chris Lattner41788082009-06-17 16:42:19 +000044#include "llvm/Target/TargetSelect.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000045#include "llvm/Transforms/IPO.h"
46#include "llvm/Transforms/Scalar.h"
Nick Kledzik6d886992008-02-26 20:26:43 +000047#include "llvm/Config/config.h"
48
Nick Kledzik6d886992008-02-26 20:26:43 +000049
Nick Lewycky3d1feeb2009-06-17 06:52:10 +000050#include <cstdlib>
Nick Kledzik6d886992008-02-26 20:26:43 +000051#include <fstream>
52#include <unistd.h>
Nick Kledzik6d886992008-02-26 20:26:43 +000053#include <fcntl.h>
54
55
56using namespace llvm;
57
Nick Kledzik4059fb12008-07-08 21:14:10 +000058static cl::opt<bool> DisableInline("disable-inlining",
59 cl::desc("Do not run the inliner pass"));
Nick Kledzik6d886992008-02-26 20:26:43 +000060
61
62const char* LTOCodeGenerator::getVersionString()
63{
64#ifdef LLVM_VERSION_INFO
65 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
66#else
67 return PACKAGE_NAME " version " PACKAGE_VERSION;
68#endif
69}
70
71
Owen Anderson92adb182009-07-01 23:13:44 +000072LTOCodeGenerator::LTOCodeGenerator(LLVMContext& Context)
Owen Andersona148fdd2009-07-01 21:22:36 +000073 : _context(Context),
Owen Anderson25209b42009-07-01 16:58:40 +000074 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
Nick Kledzik6d886992008-02-26 20:26:43 +000075 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Nick Kledzik79d0a052008-02-27 22:25:36 +000076 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Nick Kledzik39d9b412009-06-04 00:28:45 +000077 _nativeObjectFile(NULL), _gccPath(NULL), _assemblerPath(NULL)
Nick Kledzik6d886992008-02-26 20:26:43 +000078{
Chris Lattner41788082009-06-17 16:42:19 +000079 InitializeAllTargets();
80 InitializeAllAsmPrinters();
Nick Kledzik6d886992008-02-26 20:26:43 +000081
82}
83
84LTOCodeGenerator::~LTOCodeGenerator()
85{
Nick Kledzik79d0a052008-02-27 22:25:36 +000086 delete _target;
87 delete _nativeObjectFile;
Nick Kledzik6d886992008-02-26 20:26:43 +000088}
89
90
91
92bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
93{
94 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
95}
96
97
98bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
99{
100 switch (debug) {
101 case LTO_DEBUG_MODEL_NONE:
102 _emitDwarfDebugInfo = false;
103 return false;
104
105 case LTO_DEBUG_MODEL_DWARF:
106 _emitDwarfDebugInfo = true;
107 return false;
108 }
109 errMsg = "unknown debug format";
110 return true;
111}
112
113
114bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
Evan Cheng521500b2009-06-26 06:57:16 +0000115 std::string& errMsg)
Nick Kledzik6d886992008-02-26 20:26:43 +0000116{
117 switch (model) {
118 case LTO_CODEGEN_PIC_MODEL_STATIC:
119 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
120 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
121 _codeModel = model;
122 return false;
123 }
124 errMsg = "unknown pic model";
125 return true;
126}
127
Nick Lewyckyef973202009-04-30 15:24:09 +0000128void LTOCodeGenerator::setGccPath(const char* path)
129{
130 if ( _gccPath )
131 delete _gccPath;
132 _gccPath = new sys::Path(path);
133}
134
Nick Kledzik39d9b412009-06-04 00:28:45 +0000135void LTOCodeGenerator::setAssemblerPath(const char* path)
136{
137 if ( _assemblerPath )
138 delete _assemblerPath;
139 _assemblerPath = new sys::Path(path);
140}
141
Nick Kledzik6d886992008-02-26 20:26:43 +0000142void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
143{
144 _mustPreserveSymbols[sym] = 1;
145}
146
147
148bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
149{
150 if ( this->determineTarget(errMsg) )
151 return true;
152
153 // mark which symbols can not be internalized
154 this->applyScopeRestrictions();
155
156 // create output file
157 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
158 if ( out.fail() ) {
159 errMsg = "could not open bitcode file for writing: ";
160 errMsg += path;
161 return true;
162 }
163
164 // write bitcode to it
165 WriteBitcodeToFile(_linker.getModule(), out);
166 if ( out.fail() ) {
167 errMsg = "could not write bitcode file: ";
168 errMsg += path;
169 return true;
170 }
171
172 return false;
173}
174
175
Nick Kledzik79d0a052008-02-27 22:25:36 +0000176const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
Nick Kledzik6d886992008-02-26 20:26:43 +0000177{
Nick Kledzik79d0a052008-02-27 22:25:36 +0000178 // make unique temp .s file to put generated assembly code
Nick Kledzik6d886992008-02-26 20:26:43 +0000179 sys::Path uniqueAsmPath("lto-llvm.s");
180 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
181 return NULL;
182 sys::RemoveFileOnSignal(uniqueAsmPath);
183
184 // generate assembly code
Owen Anderson847b99b2008-08-21 00:14:44 +0000185 bool genResult = false;
186 {
Daniel Dunbar8c009a32008-11-13 05:01:07 +0000187 raw_fd_ostream asmFile(uniqueAsmPath.c_str(), false, errMsg);
Dan Gohmande20df82008-08-21 15:33:45 +0000188 if (!errMsg.empty())
189 return NULL;
Owen Anderson847b99b2008-08-21 00:14:44 +0000190 genResult = this->generateAssemblyCode(asmFile, errMsg);
191 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000192 if ( genResult ) {
193 if ( uniqueAsmPath.exists() )
194 uniqueAsmPath.eraseFromDisk();
195 return NULL;
196 }
197
Nick Kledzik79d0a052008-02-27 22:25:36 +0000198 // make unique temp .o file to put generated object file
Nick Kledzik6d886992008-02-26 20:26:43 +0000199 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
200 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
201 if ( uniqueAsmPath.exists() )
202 uniqueAsmPath.eraseFromDisk();
203 return NULL;
204 }
205 sys::RemoveFileOnSignal(uniqueObjPath);
206
207 // assemble the assembly code
Nick Kledzik79d0a052008-02-27 22:25:36 +0000208 const std::string& uniqueObjStr = uniqueObjPath.toString();
Nick Kledzik6d886992008-02-26 20:26:43 +0000209 bool asmResult = this->assemble(uniqueAsmPath.toString(),
Nick Kledzik79d0a052008-02-27 22:25:36 +0000210 uniqueObjStr, errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000211 if ( !asmResult ) {
Nick Kledzik79d0a052008-02-27 22:25:36 +0000212 // remove old buffer if compile() called twice
213 delete _nativeObjectFile;
214
Nick Kledzik6d886992008-02-26 20:26:43 +0000215 // read .o file into memory buffer
Chris Lattnerfc003612008-04-01 18:04:03 +0000216 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
Nick Kledzik6d886992008-02-26 20:26:43 +0000217 }
Nick Kledzik79d0a052008-02-27 22:25:36 +0000218
219 // remove temp files
Nick Kledzik6d886992008-02-26 20:26:43 +0000220 uniqueAsmPath.eraseFromDisk();
221 uniqueObjPath.eraseFromDisk();
Nick Kledzik79d0a052008-02-27 22:25:36 +0000222
223 // return buffer, unless error
224 if ( _nativeObjectFile == NULL )
225 return NULL;
226 *length = _nativeObjectFile->getBufferSize();
227 return _nativeObjectFile->getBufferStart();
Nick Kledzik6d886992008-02-26 20:26:43 +0000228}
229
230
231bool LTOCodeGenerator::assemble(const std::string& asmPath,
232 const std::string& objPath, std::string& errMsg)
233{
Nick Kledzik39d9b412009-06-04 00:28:45 +0000234 sys::Path tool;
235 bool needsCompilerOptions = true;
236 if ( _assemblerPath ) {
237 tool = *_assemblerPath;
238 needsCompilerOptions = false;
239 }
240 else if ( _gccPath ) {
241 tool = *_gccPath;
Nick Lewyckyef973202009-04-30 15:24:09 +0000242 } else {
243 // find compiler driver
Nick Kledzik39d9b412009-06-04 00:28:45 +0000244 tool = sys::Program::FindProgramByName("gcc");
245 if ( tool.isEmpty() ) {
Nick Lewyckyef973202009-04-30 15:24:09 +0000246 errMsg = "can't locate gcc";
247 return true;
248 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000249 }
250
251 // build argument list
252 std::vector<const char*> args;
253 std::string targetTriple = _linker.getModule()->getTargetTriple();
Nick Kledzik39d9b412009-06-04 00:28:45 +0000254 args.push_back(tool.c_str());
Rafael Espindola6c279402009-06-09 21:14:25 +0000255 if ( targetTriple.find("darwin") != std::string::npos ) {
Nick Kledzikfe15a722009-06-04 19:14:08 +0000256 // darwin specific command line options
Devang Patelaa6cd1f2008-11-04 23:13:50 +0000257 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000258 args.push_back("-arch");
259 args.push_back("i386");
260 }
261 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
262 args.push_back("-arch");
263 args.push_back("x86_64");
264 }
265 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
266 args.push_back("-arch");
267 args.push_back("ppc");
268 }
269 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
270 args.push_back("-arch");
271 args.push_back("ppc64");
272 }
Evan Chengdc5b6d62009-04-01 18:54:56 +0000273 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
274 args.push_back("-arch");
275 args.push_back("arm");
276 }
277 else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
278 (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
279 args.push_back("-arch");
280 args.push_back("armv4t");
281 }
282 else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
283 (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
284 (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
285 (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
286 args.push_back("-arch");
287 args.push_back("armv5");
288 }
289 else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
290 (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
291 args.push_back("-arch");
292 args.push_back("armv6");
293 }
Bob Wilson5b50a242009-06-22 18:01:28 +0000294 else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
295 (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
296 args.push_back("-arch");
297 args.push_back("armv7");
298 }
Nick Kledzikfe15a722009-06-04 19:14:08 +0000299 // add -static to assembler command line when code model requires
300 if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
301 args.push_back("-static");
Nick Kledzik6d886992008-02-26 20:26:43 +0000302 }
Nick Kledzik39d9b412009-06-04 00:28:45 +0000303 if ( needsCompilerOptions ) {
304 args.push_back("-c");
305 args.push_back("-x");
306 args.push_back("assembler");
307 }
Nick Kledzik6d886992008-02-26 20:26:43 +0000308 args.push_back("-o");
309 args.push_back(objPath.c_str());
310 args.push_back(asmPath.c_str());
311 args.push_back(0);
312
313 // invoke assembler
Nick Kledzik39d9b412009-06-04 00:28:45 +0000314 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000315 errMsg = "error in assembly";
316 return true;
317 }
318 return false; // success
319}
320
321
322
323bool LTOCodeGenerator::determineTarget(std::string& errMsg)
324{
325 if ( _target == NULL ) {
326 // create target machine from info for merged modules
327 Module* mergedModule = _linker.getModule();
328 const TargetMachineRegistry::entry* march =
329 TargetMachineRegistry::getClosestStaticTargetForModule(
330 *mergedModule, errMsg);
331 if ( march == NULL )
332 return true;
Bill Wendling568e37c2008-06-18 06:35:30 +0000333
Nick Kledzik3e843222009-06-03 22:52:12 +0000334 // The relocation model is actually a static member of TargetMachine
335 // and needs to be set before the TargetMachine is instantiated.
336 switch( _codeModel ) {
337 case LTO_CODEGEN_PIC_MODEL_STATIC:
338 TargetMachine::setRelocationModel(Reloc::Static);
339 break;
340 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
341 TargetMachine::setRelocationModel(Reloc::PIC_);
342 break;
343 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
344 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
345 break;
346 }
347
Bill Wendling568e37c2008-06-18 06:35:30 +0000348 // construct LTModule, hand over ownership of module and target
Bill Wendling0478d1a2008-06-18 21:39:02 +0000349 std::string FeatureStr =
350 getFeatureString(_linker.getModule()->getTargetTriple().c_str());
351 _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
Nick Kledzik6d886992008-02-26 20:26:43 +0000352 }
353 return false;
354}
355
356void LTOCodeGenerator::applyScopeRestrictions()
357{
358 if ( !_scopeRestrictionsDone ) {
359 Module* mergedModule = _linker.getModule();
360
361 // Start off with a verification pass.
362 PassManager passes;
363 passes.add(createVerifierPass());
364
365 // mark which symbols can not be internalized
366 if ( !_mustPreserveSymbols.empty() ) {
367 Mangler mangler(*mergedModule,
368 _target->getTargetAsmInfo()->getGlobalPrefix());
369 std::vector<const char*> mustPreserveList;
370 for (Module::iterator f = mergedModule->begin(),
371 e = mergedModule->end(); f != e; ++f) {
372 if ( !f->isDeclaration()
373 && _mustPreserveSymbols.count(mangler.getValueName(f)) )
374 mustPreserveList.push_back(::strdup(f->getName().c_str()));
375 }
376 for (Module::global_iterator v = mergedModule->global_begin(),
377 e = mergedModule->global_end(); v != e; ++v) {
378 if ( !v->isDeclaration()
379 && _mustPreserveSymbols.count(mangler.getValueName(v)) )
380 mustPreserveList.push_back(::strdup(v->getName().c_str()));
381 }
382 passes.add(createInternalizePass(mustPreserveList));
383 }
384 // apply scope restrictions
385 passes.run(*mergedModule);
386
387 _scopeRestrictionsDone = true;
388 }
389}
390
Nick Kledzik6d886992008-02-26 20:26:43 +0000391/// Optimize merged modules using various IPO passes
Owen Anderson847b99b2008-08-21 00:14:44 +0000392bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
393 std::string& errMsg)
Nick Kledzik6d886992008-02-26 20:26:43 +0000394{
395 if ( this->determineTarget(errMsg) )
396 return true;
397
398 // mark which symbols can not be internalized
399 this->applyScopeRestrictions();
400
401 Module* mergedModule = _linker.getModule();
402
403 // If target supports exception handling then enable it now.
404 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
405 llvm::ExceptionHandling = true;
406
Nick Kledzik4059fb12008-07-08 21:14:10 +0000407 // if options were requested, set them
408 if ( !_codegenOptions.empty() )
409 cl::ParseCommandLineOptions(_codegenOptions.size(),
410 (char**)&_codegenOptions[0]);
Devang Patel6fb60262008-07-03 22:53:14 +0000411
Nick Kledzik6d886992008-02-26 20:26:43 +0000412 // Instantiate the pass manager to organize the passes.
413 PassManager passes;
414
415 // Start off with a verification pass.
416 passes.add(createVerifierPass());
417
418 // Add an appropriate TargetData instance for this module...
419 passes.add(new TargetData(*_target->getTargetData()));
420
Daniel Dunbar9068de52009-06-03 21:06:14 +0000421 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
Daniel Dunbar9068de52009-06-03 21:06:14 +0000422 /*VerifyEach=*/ false);
Nick Kledzik6d886992008-02-26 20:26:43 +0000423
424 // Make sure everything is still good.
425 passes.add(createVerifierPass());
426
427 FunctionPassManager* codeGenPasses =
428 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
429
430 codeGenPasses->add(new TargetData(*_target->getTargetData()));
431
432 MachineCodeEmitter* mce = NULL;
433
434 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
Bill Wendling5ed22ac2009-04-29 23:29:43 +0000435 TargetMachine::AssemblyFile,
Bill Wendling2d1c1162009-04-29 23:40:42 +0000436 CodeGenOpt::Aggressive)) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000437 case FileModel::MachOFile:
438 mce = AddMachOWriter(*codeGenPasses, out, *_target);
439 break;
440 case FileModel::ElfFile:
441 mce = AddELFWriter(*codeGenPasses, out, *_target);
442 break;
443 case FileModel::AsmFile:
444 break;
445 case FileModel::Error:
446 case FileModel::None:
447 errMsg = "target file type not supported";
448 return true;
449 }
450
Bill Wendling5ed22ac2009-04-29 23:29:43 +0000451 if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce,
Bill Wendling2d1c1162009-04-29 23:40:42 +0000452 CodeGenOpt::Aggressive)) {
Nick Kledzik6d886992008-02-26 20:26:43 +0000453 errMsg = "target does not support generation of this file type";
454 return true;
455 }
456
457 // Run our queue of passes all at once now, efficiently.
458 passes.run(*mergedModule);
459
460 // Run the code generator, and write assembly file
461 codeGenPasses->doInitialization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000462
Bill Wendling568e37c2008-06-18 06:35:30 +0000463 for (Module::iterator
464 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
465 if (!it->isDeclaration())
466 codeGenPasses->run(*it);
467
468 codeGenPasses->doFinalization();
Nick Kledzik6d886992008-02-26 20:26:43 +0000469 return false; // success
470}
471
472
Nick Kledzik4059fb12008-07-08 21:14:10 +0000473/// Optimize merged modules using various IPO passes
474void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
475{
476 std::string ops(options);
477 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
478 // ParseCommandLineOptions() expects argv[0] to be program name.
479 // Lazily add that.
480 if ( _codegenOptions.empty() )
481 _codegenOptions.push_back("libLTO");
482 _codegenOptions.push_back(strdup(o.c_str()));
483 }
484}