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/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/ModuleProvider.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/Passes.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Analysis/Verifier.h"
30 #include "llvm/Bitcode/ReaderWriter.h"
31 #include "llvm/CodeGen/FileWriters.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/StandardPasses.h"
37 #include "llvm/Support/SystemUtils.h"
38 #include "llvm/System/Host.h"
39 #include "llvm/System/Program.h"
40 #include "llvm/System/Signals.h"
41 #include "llvm/Target/SubtargetFeature.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetRegistry.h"
47 #include "llvm/Target/TargetSelect.h"
48 #include "llvm/Transforms/IPO.h"
49 #include "llvm/Transforms/Scalar.h"
50 #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(getGlobalContext()),
74 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
75 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
76 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
77 _nativeObjectFile(NULL), _assemblerPath(NULL)
79 InitializeAllTargets();
80 InitializeAllAsmPrinters();
83 LTOCodeGenerator::~LTOCodeGenerator()
86 delete _nativeObjectFile;
91 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
93 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
97 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
100 case LTO_DEBUG_MODEL_NONE:
101 _emitDwarfDebugInfo = false;
104 case LTO_DEBUG_MODEL_DWARF:
105 _emitDwarfDebugInfo = true;
108 errMsg = "unknown debug format";
113 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
117 case LTO_CODEGEN_PIC_MODEL_STATIC:
118 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
119 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
123 errMsg = "unknown pic model";
127 void LTOCodeGenerator::setAssemblerPath(const char* path)
129 if ( _assemblerPath )
130 delete _assemblerPath;
131 _assemblerPath = new sys::Path(path);
134 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
136 _mustPreserveSymbols[sym] = 1;
140 bool LTOCodeGenerator::writeMergedModules(const char *path,
141 std::string &errMsg) {
142 if (determineTarget(errMsg))
145 // mark which symbols can not be internalized
146 applyScopeRestrictions();
148 // create output file
150 raw_fd_ostream Out(path, ErrInfo,
151 raw_fd_ostream::F_Binary);
152 if (!ErrInfo.empty()) {
153 errMsg = "could not open bitcode file for writing: ";
158 // write bitcode to it
159 WriteBitcodeToFile(_linker.getModule(), Out);
161 if (Out.has_error()) {
162 errMsg = "could not write bitcode file: ";
171 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
173 // make unique temp .s file to put generated assembly code
174 sys::Path uniqueAsmPath("lto-llvm.s");
175 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
177 sys::RemoveFileOnSignal(uniqueAsmPath);
179 // generate assembly code
180 bool genResult = false;
182 raw_fd_ostream asmFD(uniqueAsmPath.c_str(), errMsg);
183 formatted_raw_ostream asmFile(asmFD);
186 genResult = this->generateAssemblyCode(asmFile, errMsg);
189 if ( uniqueAsmPath.exists() )
190 uniqueAsmPath.eraseFromDisk();
194 // make unique temp .o file to put generated object file
195 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
196 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
197 if ( uniqueAsmPath.exists() )
198 uniqueAsmPath.eraseFromDisk();
201 sys::RemoveFileOnSignal(uniqueObjPath);
203 // assemble the assembly code
204 const std::string& uniqueObjStr = uniqueObjPath.str();
205 bool asmResult = this->assemble(uniqueAsmPath.str(), uniqueObjStr, errMsg);
207 // remove old buffer if compile() called twice
208 delete _nativeObjectFile;
210 // read .o file into memory buffer
211 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
215 uniqueAsmPath.eraseFromDisk();
216 uniqueObjPath.eraseFromDisk();
218 // return buffer, unless error
219 if ( _nativeObjectFile == NULL )
221 *length = _nativeObjectFile->getBufferSize();
222 return _nativeObjectFile->getBufferStart();
226 bool LTOCodeGenerator::assemble(const std::string& asmPath,
227 const std::string& objPath, std::string& errMsg)
230 bool needsCompilerOptions = true;
231 if ( _assemblerPath ) {
232 tool = *_assemblerPath;
233 needsCompilerOptions = false;
235 // find compiler driver
236 tool = sys::Program::FindProgramByName("gcc");
237 if ( tool.isEmpty() ) {
238 errMsg = "can't locate gcc";
243 // build argument list
244 std::vector<const char*> args;
245 std::string targetTriple = _linker.getModule()->getTargetTriple();
246 args.push_back(tool.c_str());
247 if ( targetTriple.find("darwin") != std::string::npos ) {
248 // darwin specific command line options
249 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
250 args.push_back("-arch");
251 args.push_back("i386");
253 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
254 args.push_back("-arch");
255 args.push_back("x86_64");
257 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
258 args.push_back("-arch");
259 args.push_back("ppc");
261 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
262 args.push_back("-arch");
263 args.push_back("ppc64");
265 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
266 args.push_back("-arch");
267 args.push_back("arm");
269 else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
270 (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
271 args.push_back("-arch");
272 args.push_back("armv4t");
274 else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
275 (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
276 (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
277 (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
278 args.push_back("-arch");
279 args.push_back("armv5");
281 else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
282 (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
283 args.push_back("-arch");
284 args.push_back("armv6");
286 else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
287 (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
288 args.push_back("-arch");
289 args.push_back("armv7");
291 // add -static to assembler command line when code model requires
292 if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
293 args.push_back("-static");
295 if ( needsCompilerOptions ) {
296 args.push_back("-c");
297 args.push_back("-x");
298 args.push_back("assembler");
300 args.push_back("-o");
301 args.push_back(objPath.c_str());
302 args.push_back(asmPath.c_str());
306 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
307 errMsg = "error in assembly";
310 return false; // success
315 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
317 if ( _target == NULL ) {
318 std::string Triple = _linker.getModule()->getTargetTriple();
320 Triple = sys::getHostTriple();
322 // create target machine from info for merged modules
323 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
327 // The relocation model is actually a static member of TargetMachine
328 // and needs to be set before the TargetMachine is instantiated.
329 switch( _codeModel ) {
330 case LTO_CODEGEN_PIC_MODEL_STATIC:
331 TargetMachine::setRelocationModel(Reloc::Static);
333 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
334 TargetMachine::setRelocationModel(Reloc::PIC_);
336 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
337 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
341 // construct LTModule, hand over ownership of module and target
342 std::string FeatureStr = getFeatureString(Triple.c_str());
343 _target = march->createTargetMachine(Triple, FeatureStr);
348 void LTOCodeGenerator::applyScopeRestrictions()
350 if ( !_scopeRestrictionsDone ) {
351 Module* mergedModule = _linker.getModule();
353 // Start off with a verification pass.
355 passes.add(createVerifierPass());
357 // mark which symbols can not be internalized
358 if ( !_mustPreserveSymbols.empty() ) {
359 Mangler mangler(*mergedModule,
360 _target->getMCAsmInfo()->getGlobalPrefix());
361 std::vector<const char*> mustPreserveList;
362 for (Module::iterator f = mergedModule->begin(),
363 e = mergedModule->end(); f != e; ++f) {
364 if ( !f->isDeclaration()
365 && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
366 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
368 for (Module::global_iterator v = mergedModule->global_begin(),
369 e = mergedModule->global_end(); v != e; ++v) {
370 if ( !v->isDeclaration()
371 && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
372 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
374 passes.add(createInternalizePass(mustPreserveList));
376 // apply scope restrictions
377 passes.run(*mergedModule);
379 _scopeRestrictionsDone = true;
383 /// Optimize merged modules using various IPO passes
384 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
387 if ( this->determineTarget(errMsg) )
390 // mark which symbols can not be internalized
391 this->applyScopeRestrictions();
393 Module* mergedModule = _linker.getModule();
395 // If target supports exception handling then enable it now.
396 switch (_target->getMCAsmInfo()->getExceptionHandlingType()) {
397 case ExceptionHandling::Dwarf:
398 llvm::DwarfExceptionHandling = true;
400 case ExceptionHandling::SjLj:
401 llvm::SjLjExceptionHandling = true;
403 case ExceptionHandling::None:
406 assert (0 && "Unknown exception handling model!");
409 // if options were requested, set them
410 if ( !_codegenOptions.empty() )
411 cl::ParseCommandLineOptions(_codegenOptions.size(),
412 (char**)&_codegenOptions[0]);
414 // Instantiate the pass manager to organize the passes.
417 // Start off with a verification pass.
418 passes.add(createVerifierPass());
420 // Add an appropriate TargetData instance for this module...
421 passes.add(new TargetData(*_target->getTargetData()));
423 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
424 /*VerifyEach=*/ false);
426 // Make sure everything is still good.
427 passes.add(createVerifierPass());
429 FunctionPassManager* codeGenPasses =
430 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
432 codeGenPasses->add(new TargetData(*_target->getTargetData()));
434 ObjectCodeEmitter* oce = NULL;
436 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
437 TargetMachine::AssemblyFile,
438 CodeGenOpt::Aggressive)) {
439 case FileModel::MachOFile:
440 oce = AddMachOWriter(*codeGenPasses, out, *_target);
442 case FileModel::ElfFile:
443 oce = AddELFWriter(*codeGenPasses, out, *_target);
445 case FileModel::AsmFile:
447 case FileModel::Error:
448 case FileModel::None:
449 errMsg = "target file type not supported";
453 if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
454 CodeGenOpt::Aggressive)) {
455 errMsg = "target does not support generation of this file type";
459 // Run our queue of passes all at once now, efficiently.
460 passes.run(*mergedModule);
462 // Run the code generator, and write assembly file
463 codeGenPasses->doInitialization();
465 for (Module::iterator
466 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
467 if (!it->isDeclaration())
468 codeGenPasses->run(*it);
470 codeGenPasses->doFinalization();
472 return false; // success
476 /// Optimize merged modules using various IPO passes
477 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
479 std::string ops(options);
480 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
481 // ParseCommandLineOptions() expects argv[0] to be program name.
483 if ( _codegenOptions.empty() )
484 _codegenOptions.push_back("libLTO");
485 _codegenOptions.push_back(strdup(o.c_str()));