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/Module.h"
20 #include "llvm/PassManager.h"
21 #include "llvm/Linker.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/ModuleProvider.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/StandardPasses.h"
30 #include "llvm/Support/SystemUtils.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/System/Signals.h"
33 #include "llvm/Analysis/Passes.h"
34 #include "llvm/Analysis/LoopPass.h"
35 #include "llvm/Analysis/Verifier.h"
36 #include "llvm/CodeGen/FileWriters.h"
37 #include "llvm/Target/SubtargetFeature.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetMachineRegistry.h"
42 #include "llvm/Target/TargetAsmInfo.h"
43 #include "llvm/Transforms/IPO.h"
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/Config/config.h"
57 static cl::opt<bool> DisableInline("disable-inlining",
58 cl::desc("Do not run the inliner pass"));
61 const char* LTOCodeGenerator::getVersionString()
63 #ifdef LLVM_VERSION_INFO
64 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
66 return PACKAGE_NAME " version " PACKAGE_VERSION;
71 LTOCodeGenerator::LTOCodeGenerator()
72 : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
73 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
74 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
75 _nativeObjectFile(NULL), _gccPath(NULL), _assemblerPath(NULL)
80 LTOCodeGenerator::~LTOCodeGenerator()
83 delete _nativeObjectFile;
88 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
90 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
94 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
97 case LTO_DEBUG_MODEL_NONE:
98 _emitDwarfDebugInfo = false;
101 case LTO_DEBUG_MODEL_DWARF:
102 _emitDwarfDebugInfo = true;
105 errMsg = "unknown debug format";
110 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
114 case LTO_CODEGEN_PIC_MODEL_STATIC:
115 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
116 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
120 errMsg = "unknown pic model";
124 void LTOCodeGenerator::setGccPath(const char* path)
128 _gccPath = new sys::Path(path);
131 void LTOCodeGenerator::setAssemblerPath(const char* path)
133 if ( _assemblerPath )
134 delete _assemblerPath;
135 _assemblerPath = new sys::Path(path);
138 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
140 _mustPreserveSymbols[sym] = 1;
144 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
146 if ( this->determineTarget(errMsg) )
149 // mark which symbols can not be internalized
150 this->applyScopeRestrictions();
152 // create output file
153 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
155 errMsg = "could not open bitcode file for writing: ";
160 // write bitcode to it
161 WriteBitcodeToFile(_linker.getModule(), out);
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 asmFile(uniqueAsmPath.c_str(), false, errMsg);
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.toString();
205 bool asmResult = this->assemble(uniqueAsmPath.toString(),
206 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 else if ( _gccPath ) {
239 // find compiler driver
240 tool = sys::Program::FindProgramByName("gcc");
241 if ( tool.isEmpty() ) {
242 errMsg = "can't locate gcc";
247 // build argument list
248 std::vector<const char*> args;
249 std::string targetTriple = _linker.getModule()->getTargetTriple();
250 args.push_back(tool.c_str());
251 if ( targetTriple.find("darwin") != targetTriple.size() ) {
252 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
253 args.push_back("-arch");
254 args.push_back("i386");
256 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
257 args.push_back("-arch");
258 args.push_back("x86_64");
260 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
261 args.push_back("-arch");
262 args.push_back("ppc");
264 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
265 args.push_back("-arch");
266 args.push_back("ppc64");
268 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
269 args.push_back("-arch");
270 args.push_back("arm");
272 else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
273 (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
274 args.push_back("-arch");
275 args.push_back("armv4t");
277 else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
278 (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
279 (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
280 (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
281 args.push_back("-arch");
282 args.push_back("armv5");
284 else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
285 (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
286 args.push_back("-arch");
287 args.push_back("armv6");
290 if ( needsCompilerOptions ) {
291 args.push_back("-c");
292 args.push_back("-x");
293 args.push_back("assembler");
295 args.push_back("-o");
296 args.push_back(objPath.c_str());
297 args.push_back(asmPath.c_str());
301 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
302 errMsg = "error in assembly";
305 return false; // success
310 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
312 if ( _target == NULL ) {
313 // create target machine from info for merged modules
314 Module* mergedModule = _linker.getModule();
315 const TargetMachineRegistry::entry* march =
316 TargetMachineRegistry::getClosestStaticTargetForModule(
317 *mergedModule, errMsg);
321 // The relocation model is actually a static member of TargetMachine
322 // and needs to be set before the TargetMachine is instantiated.
323 switch( _codeModel ) {
324 case LTO_CODEGEN_PIC_MODEL_STATIC:
325 TargetMachine::setRelocationModel(Reloc::Static);
327 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
328 TargetMachine::setRelocationModel(Reloc::PIC_);
330 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
331 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
335 // construct LTModule, hand over ownership of module and target
336 std::string FeatureStr =
337 getFeatureString(_linker.getModule()->getTargetTriple().c_str());
338 _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
343 void LTOCodeGenerator::applyScopeRestrictions()
345 if ( !_scopeRestrictionsDone ) {
346 Module* mergedModule = _linker.getModule();
348 // Start off with a verification pass.
350 passes.add(createVerifierPass());
352 // mark which symbols can not be internalized
353 if ( !_mustPreserveSymbols.empty() ) {
354 Mangler mangler(*mergedModule,
355 _target->getTargetAsmInfo()->getGlobalPrefix());
356 std::vector<const char*> mustPreserveList;
357 for (Module::iterator f = mergedModule->begin(),
358 e = mergedModule->end(); f != e; ++f) {
359 if ( !f->isDeclaration()
360 && _mustPreserveSymbols.count(mangler.getValueName(f)) )
361 mustPreserveList.push_back(::strdup(f->getName().c_str()));
363 for (Module::global_iterator v = mergedModule->global_begin(),
364 e = mergedModule->global_end(); v != e; ++v) {
365 if ( !v->isDeclaration()
366 && _mustPreserveSymbols.count(mangler.getValueName(v)) )
367 mustPreserveList.push_back(::strdup(v->getName().c_str()));
369 passes.add(createInternalizePass(mustPreserveList));
371 // apply scope restrictions
372 passes.run(*mergedModule);
374 _scopeRestrictionsDone = true;
378 /// Optimize merged modules using various IPO passes
379 bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
382 if ( this->determineTarget(errMsg) )
385 // mark which symbols can not be internalized
386 this->applyScopeRestrictions();
388 Module* mergedModule = _linker.getModule();
390 // If target supports exception handling then enable it now.
391 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
392 llvm::ExceptionHandling = true;
394 // if options were requested, set them
395 if ( !_codegenOptions.empty() )
396 cl::ParseCommandLineOptions(_codegenOptions.size(),
397 (char**)&_codegenOptions[0]);
399 // Instantiate the pass manager to organize the passes.
402 // Start off with a verification pass.
403 passes.add(createVerifierPass());
405 // Add an appropriate TargetData instance for this module...
406 passes.add(new TargetData(*_target->getTargetData()));
408 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
409 /*VerifyEach=*/ false);
411 // Make sure everything is still good.
412 passes.add(createVerifierPass());
414 FunctionPassManager* codeGenPasses =
415 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
417 codeGenPasses->add(new TargetData(*_target->getTargetData()));
419 MachineCodeEmitter* mce = NULL;
421 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
422 TargetMachine::AssemblyFile,
423 CodeGenOpt::Aggressive)) {
424 case FileModel::MachOFile:
425 mce = AddMachOWriter(*codeGenPasses, out, *_target);
427 case FileModel::ElfFile:
428 mce = AddELFWriter(*codeGenPasses, out, *_target);
430 case FileModel::AsmFile:
432 case FileModel::Error:
433 case FileModel::None:
434 errMsg = "target file type not supported";
438 if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce,
439 CodeGenOpt::Aggressive)) {
440 errMsg = "target does not support generation of this file type";
444 // Run our queue of passes all at once now, efficiently.
445 passes.run(*mergedModule);
447 // Run the code generator, and write assembly file
448 codeGenPasses->doInitialization();
450 for (Module::iterator
451 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
452 if (!it->isDeclaration())
453 codeGenPasses->run(*it);
455 codeGenPasses->doFinalization();
456 return false; // success
460 /// Optimize merged modules using various IPO passes
461 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
463 std::string ops(options);
464 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
465 // ParseCommandLineOptions() expects argv[0] to be program name.
467 if ( _codegenOptions.empty() )
468 _codegenOptions.push_back("libLTO");
469 _codegenOptions.push_back(strdup(o.c_str()));