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 // Prepare subtarget feature set for the given command line options.
308 SubtargetFeatures features;
310 // Set the rest of features by default.
311 // Note: Please keep this after all explict feature settings to make sure
312 // defaults will not override explicitly set options.
313 features.AddFeatures(
314 SubtargetFeatures::getDefaultSubtargetFeatures(llvm::Triple(Triple)));
316 // construct LTModule, hand over ownership of module and target
317 _target = march->createTargetMachine(Triple, features.getString());
322 void LTOCodeGenerator::applyScopeRestrictions()
324 if ( !_scopeRestrictionsDone ) {
325 Module* mergedModule = _linker.getModule();
327 // Start off with a verification pass.
329 passes.add(createVerifierPass());
331 // mark which symbols can not be internalized
332 if ( !_mustPreserveSymbols.empty() ) {
333 Mangler mangler(*mergedModule,
334 _target->getMCAsmInfo()->getGlobalPrefix());
335 std::vector<const char*> mustPreserveList;
336 for (Module::iterator f = mergedModule->begin(),
337 e = mergedModule->end(); f != e; ++f) {
338 if ( !f->isDeclaration()
339 && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
340 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
342 for (Module::global_iterator v = mergedModule->global_begin(),
343 e = mergedModule->global_end(); v != e; ++v) {
344 if ( !v->isDeclaration()
345 && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
346 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
348 passes.add(createInternalizePass(mustPreserveList));
350 // apply scope restrictions
351 passes.run(*mergedModule);
353 _scopeRestrictionsDone = true;
357 /// Optimize merged modules using various IPO passes
358 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
361 if ( this->determineTarget(errMsg) )
364 // mark which symbols can not be internalized
365 this->applyScopeRestrictions();
367 Module* mergedModule = _linker.getModule();
369 // If target supports exception handling then enable it now.
370 switch (_target->getMCAsmInfo()->getExceptionHandlingType()) {
371 case ExceptionHandling::Dwarf:
372 llvm::DwarfExceptionHandling = true;
374 case ExceptionHandling::SjLj:
375 llvm::SjLjExceptionHandling = true;
377 case ExceptionHandling::None:
380 assert (0 && "Unknown exception handling model!");
383 // if options were requested, set them
384 if ( !_codegenOptions.empty() )
385 cl::ParseCommandLineOptions(_codegenOptions.size(),
386 (char**)&_codegenOptions[0]);
388 // Instantiate the pass manager to organize the passes.
391 // Start off with a verification pass.
392 passes.add(createVerifierPass());
394 // Add an appropriate TargetData instance for this module...
395 passes.add(new TargetData(*_target->getTargetData()));
397 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
398 /*VerifyEach=*/ false);
400 // Make sure everything is still good.
401 passes.add(createVerifierPass());
403 FunctionPassManager* codeGenPasses =
404 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
406 codeGenPasses->add(new TargetData(*_target->getTargetData()));
408 ObjectCodeEmitter* oce = NULL;
410 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
411 TargetMachine::AssemblyFile,
412 CodeGenOpt::Aggressive)) {
413 case FileModel::MachOFile:
414 oce = AddMachOWriter(*codeGenPasses, out, *_target);
416 case FileModel::ElfFile:
417 oce = AddELFWriter(*codeGenPasses, out, *_target);
419 case FileModel::AsmFile:
421 case FileModel::Error:
422 case FileModel::None:
423 errMsg = "target file type not supported";
427 if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
428 CodeGenOpt::Aggressive)) {
429 errMsg = "target does not support generation of this file type";
433 // Run our queue of passes all at once now, efficiently.
434 passes.run(*mergedModule);
436 // Run the code generator, and write assembly file
437 codeGenPasses->doInitialization();
439 for (Module::iterator
440 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
441 if (!it->isDeclaration())
442 codeGenPasses->run(*it);
444 codeGenPasses->doFinalization();
446 return false; // success
450 /// Optimize merged modules using various IPO passes
451 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
453 std::string ops(options);
454 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
455 // ParseCommandLineOptions() expects argv[0] to be program name.
457 if ( _codegenOptions.empty() )
458 _codegenOptions.push_back("libLTO");
459 _codegenOptions.push_back(strdup(o.c_str()));