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"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Linker.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.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/Support/CommandLine.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/StandardPasses.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/System/Host.h"
36 #include "llvm/System/Program.h"
37 #include "llvm/System/Signals.h"
38 #include "llvm/Target/Mangler.h"
39 #include "llvm/Target/SubtargetFeature.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/MC/MCAsmInfo.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Target/TargetSelect.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include "llvm/Config/config.h"
56 static cl::opt<bool> DisableInline("disable-inlining",
57 cl::desc("Do not run the inliner pass"));
60 const char* LTOCodeGenerator::getVersionString()
62 #ifdef LLVM_VERSION_INFO
63 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
65 return PACKAGE_NAME " version " PACKAGE_VERSION;
70 LTOCodeGenerator::LTOCodeGenerator()
71 : _context(getGlobalContext()),
72 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
73 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
74 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
75 _nativeObjectFile(NULL), _assemblerPath(NULL)
77 InitializeAllTargets();
78 InitializeAllAsmPrinters();
81 LTOCodeGenerator::~LTOCodeGenerator()
84 delete _nativeObjectFile;
89 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
91 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
95 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
98 case LTO_DEBUG_MODEL_NONE:
99 _emitDwarfDebugInfo = false;
102 case LTO_DEBUG_MODEL_DWARF:
103 _emitDwarfDebugInfo = true;
106 errMsg = "unknown debug format";
111 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
115 case LTO_CODEGEN_PIC_MODEL_STATIC:
116 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
117 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
121 errMsg = "unknown pic model";
125 void LTOCodeGenerator::setAssemblerPath(const char* path)
127 if ( _assemblerPath )
128 delete _assemblerPath;
129 _assemblerPath = new sys::Path(path);
132 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
134 _mustPreserveSymbols[sym] = 1;
138 bool LTOCodeGenerator::writeMergedModules(const char *path,
139 std::string &errMsg) {
140 if (determineTarget(errMsg))
143 // mark which symbols can not be internalized
144 applyScopeRestrictions();
146 // create output file
148 raw_fd_ostream Out(path, ErrInfo,
149 raw_fd_ostream::F_Binary);
150 if (!ErrInfo.empty()) {
151 errMsg = "could not open bitcode file for writing: ";
156 // write bitcode to it
157 WriteBitcodeToFile(_linker.getModule(), Out);
159 if (Out.has_error()) {
160 errMsg = "could not write bitcode file: ";
169 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
171 // make unique temp .s file to put generated assembly code
172 sys::Path uniqueAsmPath("lto-llvm.s");
173 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
175 sys::RemoveFileOnSignal(uniqueAsmPath);
177 // generate assembly code
178 bool genResult = false;
180 raw_fd_ostream asmFD(uniqueAsmPath.c_str(), errMsg);
181 formatted_raw_ostream asmFile(asmFD);
184 genResult = this->generateAssemblyCode(asmFile, errMsg);
187 if ( uniqueAsmPath.exists() )
188 uniqueAsmPath.eraseFromDisk();
192 // make unique temp .o file to put generated object file
193 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
194 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
195 if ( uniqueAsmPath.exists() )
196 uniqueAsmPath.eraseFromDisk();
199 sys::RemoveFileOnSignal(uniqueObjPath);
201 // assemble the assembly code
202 const std::string& uniqueObjStr = uniqueObjPath.str();
203 bool asmResult = this->assemble(uniqueAsmPath.str(), uniqueObjStr, errMsg);
205 // remove old buffer if compile() called twice
206 delete _nativeObjectFile;
208 // read .o file into memory buffer
209 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
213 uniqueAsmPath.eraseFromDisk();
214 uniqueObjPath.eraseFromDisk();
216 // return buffer, unless error
217 if ( _nativeObjectFile == NULL )
219 *length = _nativeObjectFile->getBufferSize();
220 return _nativeObjectFile->getBufferStart();
224 bool LTOCodeGenerator::assemble(const std::string& asmPath,
225 const std::string& objPath, std::string& errMsg)
228 bool needsCompilerOptions = true;
229 if ( _assemblerPath ) {
230 tool = *_assemblerPath;
231 needsCompilerOptions = false;
233 // find compiler driver
234 tool = sys::Program::FindProgramByName("gcc");
235 if ( tool.isEmpty() ) {
236 errMsg = "can't locate gcc";
241 // build argument list
242 std::vector<const char*> args;
243 llvm::Triple targetTriple(_linker.getModule()->getTargetTriple());
244 const char *arch = targetTriple.getArchNameForAssembler();
246 args.push_back(tool.c_str());
248 if (targetTriple.getOS() == Triple::Darwin) {
249 // darwin specific command line options
251 args.push_back("-arch");
252 args.push_back(arch);
254 // add -static to assembler command line when code model requires
255 if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
256 args.push_back("-static");
258 if ( needsCompilerOptions ) {
259 args.push_back("-c");
260 args.push_back("-x");
261 args.push_back("assembler");
263 args.push_back("-o");
264 args.push_back(objPath.c_str());
265 args.push_back(asmPath.c_str());
269 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
270 errMsg = "error in assembly";
273 return false; // success
278 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
280 if ( _target == NULL ) {
281 std::string Triple = _linker.getModule()->getTargetTriple();
283 Triple = sys::getHostTriple();
285 // create target machine from info for merged modules
286 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
290 // The relocation model is actually a static member of TargetMachine
291 // and needs to be set before the TargetMachine is instantiated.
292 switch( _codeModel ) {
293 case LTO_CODEGEN_PIC_MODEL_STATIC:
294 TargetMachine::setRelocationModel(Reloc::Static);
296 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
297 TargetMachine::setRelocationModel(Reloc::PIC_);
299 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
300 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
304 // construct LTModule, hand over ownership of module and target
305 const std::string FeatureStr =
306 SubtargetFeatures::getDefaultSubtargetFeatures(llvm::Triple(Triple));
307 _target = march->createTargetMachine(Triple, FeatureStr);
312 void LTOCodeGenerator::applyScopeRestrictions()
314 if ( !_scopeRestrictionsDone ) {
315 Module* mergedModule = _linker.getModule();
317 // Start off with a verification pass.
319 passes.add(createVerifierPass());
321 // mark which symbols can not be internalized
322 if ( !_mustPreserveSymbols.empty() ) {
323 Mangler mangler(*_target->getMCAsmInfo());
324 std::vector<const char*> mustPreserveList;
325 for (Module::iterator f = mergedModule->begin(),
326 e = mergedModule->end(); f != e; ++f) {
327 if ( !f->isDeclaration()
328 && _mustPreserveSymbols.count(mangler.getNameWithPrefix(f)) )
329 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
331 for (Module::global_iterator v = mergedModule->global_begin(),
332 e = mergedModule->global_end(); v != e; ++v) {
333 if ( !v->isDeclaration()
334 && _mustPreserveSymbols.count(mangler.getNameWithPrefix(v)) )
335 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
337 passes.add(createInternalizePass(mustPreserveList));
339 // apply scope restrictions
340 passes.run(*mergedModule);
342 _scopeRestrictionsDone = true;
346 /// Optimize merged modules using various IPO passes
347 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
350 if ( this->determineTarget(errMsg) )
353 // mark which symbols can not be internalized
354 this->applyScopeRestrictions();
356 Module* mergedModule = _linker.getModule();
358 // If target supports exception handling then enable it now.
359 switch (_target->getMCAsmInfo()->getExceptionHandlingType()) {
360 case ExceptionHandling::Dwarf:
361 llvm::DwarfExceptionHandling = true;
363 case ExceptionHandling::SjLj:
364 llvm::SjLjExceptionHandling = true;
366 case ExceptionHandling::None:
369 assert (0 && "Unknown exception handling model!");
372 // if options were requested, set them
373 if ( !_codegenOptions.empty() )
374 cl::ParseCommandLineOptions(_codegenOptions.size(),
375 (char**)&_codegenOptions[0]);
377 // Instantiate the pass manager to organize the passes.
380 // Start off with a verification pass.
381 passes.add(createVerifierPass());
383 // Add an appropriate TargetData instance for this module...
384 passes.add(new TargetData(*_target->getTargetData()));
386 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
387 /*VerifyEach=*/ false);
389 // Make sure everything is still good.
390 passes.add(createVerifierPass());
392 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
394 codeGenPasses->add(new TargetData(*_target->getTargetData()));
396 if (_target->addPassesToEmitFile(*codeGenPasses, out,
397 TargetMachine::CGFT_AssemblyFile,
398 CodeGenOpt::Aggressive)) {
399 errMsg = "target file type not supported";
403 // Run our queue of passes all at once now, efficiently.
404 passes.run(*mergedModule);
406 // Run the code generator, and write assembly file
407 codeGenPasses->doInitialization();
409 for (Module::iterator
410 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
411 if (!it->isDeclaration())
412 codeGenPasses->run(*it);
414 codeGenPasses->doFinalization();
416 return false; // success
420 /// Optimize merged modules using various IPO passes
421 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
423 for (std::pair<StringRef, StringRef> o = getToken(options);
424 !o.first.empty(); o = getToken(o.second)) {
425 // ParseCommandLineOptions() expects argv[0] to be program name.
427 if ( _codegenOptions.empty() )
428 _codegenOptions.push_back("libLTO");
429 _codegenOptions.push_back(strdup(o.first.str().c_str()));