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/ADT/Triple.h"
28 #include "llvm/Analysis/Passes.h"
29 #include "llvm/Analysis/LoopPass.h"
30 #include "llvm/Analysis/Verifier.h"
31 #include "llvm/Bitcode/ReaderWriter.h"
32 #include "llvm/CodeGen/FileWriters.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/StandardPasses.h"
38 #include "llvm/Support/SystemUtils.h"
39 #include "llvm/System/Host.h"
40 #include "llvm/System/Program.h"
41 #include "llvm/System/Signals.h"
42 #include "llvm/Target/SubtargetFeature.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetRegistry.h"
48 #include "llvm/Target/TargetSelect.h"
49 #include "llvm/Transforms/IPO.h"
50 #include "llvm/Transforms/Scalar.h"
51 #include "llvm/Config/config.h"
59 static cl::opt<bool> DisableInline("disable-inlining",
60 cl::desc("Do not run the inliner pass"));
63 const char* LTOCodeGenerator::getVersionString()
65 #ifdef LLVM_VERSION_INFO
66 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
68 return PACKAGE_NAME " version " PACKAGE_VERSION;
73 LTOCodeGenerator::LTOCodeGenerator()
74 : _context(getGlobalContext()),
75 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
76 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
77 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
78 _nativeObjectFile(NULL), _assemblerPath(NULL)
80 InitializeAllTargets();
81 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::setAssemblerPath(const char* path)
130 if ( _assemblerPath )
131 delete _assemblerPath;
132 _assemblerPath = new sys::Path(path);
135 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
137 _mustPreserveSymbols[sym] = 1;
141 bool LTOCodeGenerator::writeMergedModules(const char *path,
142 std::string &errMsg) {
143 if (determineTarget(errMsg))
146 // mark which symbols can not be internalized
147 applyScopeRestrictions();
149 // create output file
151 raw_fd_ostream Out(path, ErrInfo,
152 raw_fd_ostream::F_Binary);
153 if (!ErrInfo.empty()) {
154 errMsg = "could not open bitcode file for writing: ";
159 // write bitcode to it
160 WriteBitcodeToFile(_linker.getModule(), Out);
162 if (Out.has_error()) {
163 errMsg = "could not write bitcode file: ";
172 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
174 // make unique temp .s file to put generated assembly code
175 sys::Path uniqueAsmPath("lto-llvm.s");
176 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
178 sys::RemoveFileOnSignal(uniqueAsmPath);
180 // generate assembly code
181 bool genResult = false;
183 raw_fd_ostream asmFD(uniqueAsmPath.c_str(), errMsg);
184 formatted_raw_ostream asmFile(asmFD);
187 genResult = this->generateAssemblyCode(asmFile, errMsg);
190 if ( uniqueAsmPath.exists() )
191 uniqueAsmPath.eraseFromDisk();
195 // make unique temp .o file to put generated object file
196 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
197 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
198 if ( uniqueAsmPath.exists() )
199 uniqueAsmPath.eraseFromDisk();
202 sys::RemoveFileOnSignal(uniqueObjPath);
204 // assemble the assembly code
205 const std::string& uniqueObjStr = uniqueObjPath.str();
206 bool asmResult = this->assemble(uniqueAsmPath.str(), uniqueObjStr, errMsg);
208 // remove old buffer if compile() called twice
209 delete _nativeObjectFile;
211 // read .o file into memory buffer
212 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
216 uniqueAsmPath.eraseFromDisk();
217 uniqueObjPath.eraseFromDisk();
219 // return buffer, unless error
220 if ( _nativeObjectFile == NULL )
222 *length = _nativeObjectFile->getBufferSize();
223 return _nativeObjectFile->getBufferStart();
227 bool LTOCodeGenerator::assemble(const std::string& asmPath,
228 const std::string& objPath, std::string& errMsg)
231 bool needsCompilerOptions = true;
232 if ( _assemblerPath ) {
233 tool = *_assemblerPath;
234 needsCompilerOptions = false;
236 // find compiler driver
237 tool = sys::Program::FindProgramByName("gcc");
238 if ( tool.isEmpty() ) {
239 errMsg = "can't locate gcc";
244 // build argument list
245 std::vector<const char*> args;
246 llvm::Triple targetTriple(_linker.getModule()->getTargetTriple());
247 const char *arch = targetTriple.getArchNameForAssembler();
249 args.push_back(tool.c_str());
251 if (targetTriple.getOS() == Triple::Darwin) {
252 // darwin specific command line options
254 args.push_back("-arch");
255 args.push_back(arch);
257 // add -static to assembler command line when code model requires
258 if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
259 args.push_back("-static");
261 if ( needsCompilerOptions ) {
262 args.push_back("-c");
263 args.push_back("-x");
264 args.push_back("assembler");
266 args.push_back("-o");
267 args.push_back(objPath.c_str());
268 args.push_back(asmPath.c_str());
272 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
273 errMsg = "error in assembly";
276 return false; // success
281 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
283 if ( _target == NULL ) {
284 std::string Triple = _linker.getModule()->getTargetTriple();
286 Triple = sys::getHostTriple();
288 // create target machine from info for merged modules
289 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
293 // The relocation model is actually a static member of TargetMachine
294 // and needs to be set before the TargetMachine is instantiated.
295 switch( _codeModel ) {
296 case LTO_CODEGEN_PIC_MODEL_STATIC:
297 TargetMachine::setRelocationModel(Reloc::Static);
299 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
300 TargetMachine::setRelocationModel(Reloc::PIC_);
302 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
303 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
307 // construct LTModule, hand over ownership of module and target
308 const std::string FeatureStr =
309 SubtargetFeatures::getDefaultSubtargetFeatures(llvm::Triple(Triple));
310 _target = march->createTargetMachine(Triple, FeatureStr);
315 void LTOCodeGenerator::applyScopeRestrictions()
317 if ( !_scopeRestrictionsDone ) {
318 Module* mergedModule = _linker.getModule();
320 // Start off with a verification pass.
322 passes.add(createVerifierPass());
324 // mark which symbols can not be internalized
325 if ( !_mustPreserveSymbols.empty() ) {
326 Mangler mangler(*mergedModule,
327 _target->getMCAsmInfo()->getGlobalPrefix());
328 std::vector<const char*> mustPreserveList;
329 for (Module::iterator f = mergedModule->begin(),
330 e = mergedModule->end(); f != e; ++f) {
331 if ( !f->isDeclaration()
332 && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
333 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
335 for (Module::global_iterator v = mergedModule->global_begin(),
336 e = mergedModule->global_end(); v != e; ++v) {
337 if ( !v->isDeclaration()
338 && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
339 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
341 passes.add(createInternalizePass(mustPreserveList));
343 // apply scope restrictions
344 passes.run(*mergedModule);
346 _scopeRestrictionsDone = true;
350 /// Optimize merged modules using various IPO passes
351 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
354 if ( this->determineTarget(errMsg) )
357 // mark which symbols can not be internalized
358 this->applyScopeRestrictions();
360 Module* mergedModule = _linker.getModule();
362 // If target supports exception handling then enable it now.
363 switch (_target->getMCAsmInfo()->getExceptionHandlingType()) {
364 case ExceptionHandling::Dwarf:
365 llvm::DwarfExceptionHandling = true;
367 case ExceptionHandling::SjLj:
368 llvm::SjLjExceptionHandling = true;
370 case ExceptionHandling::None:
373 assert (0 && "Unknown exception handling model!");
376 // if options were requested, set them
377 if ( !_codegenOptions.empty() )
378 cl::ParseCommandLineOptions(_codegenOptions.size(),
379 (char**)&_codegenOptions[0]);
381 // Instantiate the pass manager to organize the passes.
384 // Start off with a verification pass.
385 passes.add(createVerifierPass());
387 // Add an appropriate TargetData instance for this module...
388 passes.add(new TargetData(*_target->getTargetData()));
390 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
391 /*VerifyEach=*/ false);
393 // Make sure everything is still good.
394 passes.add(createVerifierPass());
396 FunctionPassManager* codeGenPasses =
397 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
399 codeGenPasses->add(new TargetData(*_target->getTargetData()));
401 ObjectCodeEmitter* oce = NULL;
403 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
404 TargetMachine::AssemblyFile,
405 CodeGenOpt::Aggressive)) {
406 case FileModel::MachOFile:
407 oce = AddMachOWriter(*codeGenPasses, out, *_target);
409 case FileModel::ElfFile:
410 oce = AddELFWriter(*codeGenPasses, out, *_target);
412 case FileModel::AsmFile:
414 case FileModel::Error:
415 case FileModel::None:
416 errMsg = "target file type not supported";
420 if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
421 CodeGenOpt::Aggressive)) {
422 errMsg = "target does not support generation of this file type";
426 // Run our queue of passes all at once now, efficiently.
427 passes.run(*mergedModule);
429 // Run the code generator, and write assembly file
430 codeGenPasses->doInitialization();
432 for (Module::iterator
433 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
434 if (!it->isDeclaration())
435 codeGenPasses->run(*it);
437 codeGenPasses->doFinalization();
439 return false; // success
443 /// Optimize merged modules using various IPO passes
444 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
446 std::string ops(options);
447 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
448 // ParseCommandLineOptions() expects argv[0] to be program name.
450 if ( _codegenOptions.empty() )
451 _codegenOptions.push_back("libLTO");
452 _codegenOptions.push_back(strdup(o.c_str()));