1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "LTOModule.h"
16 #include "LTOCodeGenerator.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Linker.h"
22 #include "llvm/Module.h"
23 #include "llvm/ModuleProvider.h"
24 #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"
29 #include "llvm/Bitcode/ReaderWriter.h"
30 #include "llvm/CodeGen/FileWriters.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/StandardPasses.h"
35 #include "llvm/Support/SystemUtils.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/System/Signals.h"
38 #include "llvm/Target/SubtargetFeature.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetAsmInfo.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetMachineRegistry.h"
44 #include "llvm/Target/TargetSelect.h"
45 #include "llvm/Transforms/IPO.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Config/config.h"
58 static cl::opt<bool> DisableInline("disable-inlining",
59 cl::desc("Do not run the inliner pass"));
62 const char* LTOCodeGenerator::getVersionString()
64 #ifdef LLVM_VERSION_INFO
65 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 return PACKAGE_NAME " version " PACKAGE_VERSION;
72 LTOCodeGenerator::LTOCodeGenerator()
73 : _context(new LLVMContext()),
74 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
75 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
76 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
77 _nativeObjectFile(NULL), _gccPath(NULL), _assemblerPath(NULL)
79 InitializeAllTargets();
80 InitializeAllAsmPrinters();
84 LTOCodeGenerator::~LTOCodeGenerator()
87 delete _nativeObjectFile;
92 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
94 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
98 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
101 case LTO_DEBUG_MODEL_NONE:
102 _emitDwarfDebugInfo = false;
105 case LTO_DEBUG_MODEL_DWARF:
106 _emitDwarfDebugInfo = true;
109 errMsg = "unknown debug format";
114 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
118 case LTO_CODEGEN_PIC_MODEL_STATIC:
119 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
120 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
124 errMsg = "unknown pic model";
128 void LTOCodeGenerator::setGccPath(const char* path)
132 _gccPath = new sys::Path(path);
135 void LTOCodeGenerator::setAssemblerPath(const char* path)
137 if ( _assemblerPath )
138 delete _assemblerPath;
139 _assemblerPath = new sys::Path(path);
142 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
144 _mustPreserveSymbols[sym] = 1;
148 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
150 if ( this->determineTarget(errMsg) )
153 // mark which symbols can not be internalized
154 this->applyScopeRestrictions();
156 // create output file
157 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
159 errMsg = "could not open bitcode file for writing: ";
164 // write bitcode to it
165 WriteBitcodeToFile(_linker.getModule(), out);
167 errMsg = "could not write bitcode file: ";
176 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
178 // make unique temp .s file to put generated assembly code
179 sys::Path uniqueAsmPath("lto-llvm.s");
180 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
182 sys::RemoveFileOnSignal(uniqueAsmPath);
184 // generate assembly code
185 bool genResult = false;
187 raw_fd_ostream asmFile(uniqueAsmPath.c_str(), false, errMsg);
190 genResult = this->generateAssemblyCode(asmFile, errMsg);
193 if ( uniqueAsmPath.exists() )
194 uniqueAsmPath.eraseFromDisk();
198 // make unique temp .o file to put generated object file
199 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
200 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
201 if ( uniqueAsmPath.exists() )
202 uniqueAsmPath.eraseFromDisk();
205 sys::RemoveFileOnSignal(uniqueObjPath);
207 // assemble the assembly code
208 const std::string& uniqueObjStr = uniqueObjPath.toString();
209 bool asmResult = this->assemble(uniqueAsmPath.toString(),
210 uniqueObjStr, errMsg);
212 // remove old buffer if compile() called twice
213 delete _nativeObjectFile;
215 // read .o file into memory buffer
216 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
220 uniqueAsmPath.eraseFromDisk();
221 uniqueObjPath.eraseFromDisk();
223 // return buffer, unless error
224 if ( _nativeObjectFile == NULL )
226 *length = _nativeObjectFile->getBufferSize();
227 return _nativeObjectFile->getBufferStart();
231 bool LTOCodeGenerator::assemble(const std::string& asmPath,
232 const std::string& objPath, std::string& errMsg)
235 bool needsCompilerOptions = true;
236 if ( _assemblerPath ) {
237 tool = *_assemblerPath;
238 needsCompilerOptions = false;
240 else if ( _gccPath ) {
243 // find compiler driver
244 tool = sys::Program::FindProgramByName("gcc");
245 if ( tool.isEmpty() ) {
246 errMsg = "can't locate gcc";
251 // build argument list
252 std::vector<const char*> args;
253 std::string targetTriple = _linker.getModule()->getTargetTriple();
254 args.push_back(tool.c_str());
255 if ( targetTriple.find("darwin") != std::string::npos ) {
256 // darwin specific command line options
257 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
258 args.push_back("-arch");
259 args.push_back("i386");
261 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
262 args.push_back("-arch");
263 args.push_back("x86_64");
265 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
266 args.push_back("-arch");
267 args.push_back("ppc");
269 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
270 args.push_back("-arch");
271 args.push_back("ppc64");
273 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
274 args.push_back("-arch");
275 args.push_back("arm");
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");
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");
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");
294 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");
299 // 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");
303 if ( needsCompilerOptions ) {
304 args.push_back("-c");
305 args.push_back("-x");
306 args.push_back("assembler");
308 args.push_back("-o");
309 args.push_back(objPath.c_str());
310 args.push_back(asmPath.c_str());
314 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
315 errMsg = "error in assembly";
318 return false; // success
323 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
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);
334 // 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);
340 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
341 TargetMachine::setRelocationModel(Reloc::PIC_);
343 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
344 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
348 // construct LTModule, hand over ownership of module and target
349 std::string FeatureStr =
350 getFeatureString(_linker.getModule()->getTargetTriple().c_str());
351 _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
356 void LTOCodeGenerator::applyScopeRestrictions()
358 if ( !_scopeRestrictionsDone ) {
359 Module* mergedModule = _linker.getModule();
361 // Start off with a verification pass.
363 passes.add(createVerifierPass());
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()));
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()));
382 passes.add(createInternalizePass(mustPreserveList));
384 // apply scope restrictions
385 passes.run(*mergedModule);
387 _scopeRestrictionsDone = true;
391 /// Optimize merged modules using various IPO passes
392 bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
395 if ( this->determineTarget(errMsg) )
398 // mark which symbols can not be internalized
399 this->applyScopeRestrictions();
401 Module* mergedModule = _linker.getModule();
403 // If target supports exception handling then enable it now.
404 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
405 llvm::ExceptionHandling = true;
407 // if options were requested, set them
408 if ( !_codegenOptions.empty() )
409 cl::ParseCommandLineOptions(_codegenOptions.size(),
410 (char**)&_codegenOptions[0]);
412 // Instantiate the pass manager to organize the passes.
415 // Start off with a verification pass.
416 passes.add(createVerifierPass());
418 // Add an appropriate TargetData instance for this module...
419 passes.add(new TargetData(*_target->getTargetData()));
421 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
422 /*VerifyEach=*/ false);
424 // Make sure everything is still good.
425 passes.add(createVerifierPass());
427 FunctionPassManager* codeGenPasses =
428 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
430 codeGenPasses->add(new TargetData(*_target->getTargetData()));
432 MachineCodeEmitter* mce = NULL;
434 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
435 TargetMachine::AssemblyFile,
436 CodeGenOpt::Aggressive)) {
437 case FileModel::MachOFile:
438 mce = AddMachOWriter(*codeGenPasses, out, *_target);
440 case FileModel::ElfFile:
441 mce = AddELFWriter(*codeGenPasses, out, *_target);
443 case FileModel::AsmFile:
445 case FileModel::Error:
446 case FileModel::None:
447 errMsg = "target file type not supported";
451 if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce,
452 CodeGenOpt::Aggressive)) {
453 errMsg = "target does not support generation of this file type";
457 // Run our queue of passes all at once now, efficiently.
458 passes.run(*mergedModule);
460 // Run the code generator, and write assembly file
461 codeGenPasses->doInitialization();
463 for (Module::iterator
464 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
465 if (!it->isDeclaration())
466 codeGenPasses->run(*it);
468 codeGenPasses->doFinalization();
469 return false; // success
473 /// Optimize merged modules using various IPO passes
474 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
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.
480 if ( _codegenOptions.empty() )
481 _codegenOptions.push_back("libLTO");
482 _codegenOptions.push_back(strdup(o.c_str()));