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 "LTOCodeGenerator.h"
16 #include "LTOModule.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/Verifier.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Linker.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/PassManager.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/system_error.h"
42 #include "llvm/Target/Mangler.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
48 #include "llvm/Transforms/ObjCARC.h"
52 DisableOpt("disable-opt", cl::init(false),
53 cl::desc("Do not run any optimization passes"));
56 DisableInline("disable-inlining", cl::init(false),
57 cl::desc("Do not run the inliner pass"));
60 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
61 cl::desc("Do not run the GVN load PRE pass"));
63 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;
71 LTOCodeGenerator::LTOCodeGenerator()
72 : _context(getGlobalContext()),
73 _linker(new Module("ld-temp.o", _context)), _target(NULL),
74 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
75 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
76 _nativeObjectFile(NULL) {
77 InitializeAllTargets();
78 InitializeAllTargetMCs();
79 InitializeAllAsmPrinters();
82 LTOCodeGenerator::~LTOCodeGenerator() {
84 delete _nativeObjectFile;
85 delete _linker.getModule();
87 for (std::vector<char*>::iterator I = _codegenOptions.begin(),
88 E = _codegenOptions.end(); I != E; ++I)
92 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
93 bool ret = _linker.linkInModule(mod->getLLVVMModule(), &errMsg);
95 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
96 for (int i = 0, e = undefs.size(); i != e; ++i)
97 _asmUndefinedRefs[undefs[i]] = 1;
102 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
103 std::string& errMsg) {
105 case LTO_DEBUG_MODEL_NONE:
106 _emitDwarfDebugInfo = false;
109 case LTO_DEBUG_MODEL_DWARF:
110 _emitDwarfDebugInfo = true;
113 llvm_unreachable("Unknown debug format!");
116 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
117 std::string& errMsg) {
119 case LTO_CODEGEN_PIC_MODEL_STATIC:
120 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
121 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
125 llvm_unreachable("Unknown PIC model!");
128 bool LTOCodeGenerator::writeMergedModules(const char *path,
129 std::string &errMsg) {
130 if (determineTarget(errMsg))
133 // mark which symbols can not be internalized
134 applyScopeRestrictions();
136 // create output file
138 tool_output_file Out(path, ErrInfo,
139 raw_fd_ostream::F_Binary);
140 if (!ErrInfo.empty()) {
141 errMsg = "could not open bitcode file for writing: ";
146 // write bitcode to it
147 WriteBitcodeToFile(_linker.getModule(), Out.os());
150 if (Out.os().has_error()) {
151 errMsg = "could not write bitcode file: ";
153 Out.os().clear_error();
161 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
162 // make unique temp .o file to put generated object file
163 SmallString<128> Filename;
165 error_code EC = sys::fs::unique_file("lto-llvm-%%%%%%%.o",
168 errMsg = EC.message();
172 // generate object file
173 tool_output_file objFile(Filename.c_str(), FD);
175 bool genResult = generateObjectFile(objFile.os(), errMsg);
176 objFile.os().close();
177 if (objFile.os().has_error()) {
178 objFile.os().clear_error();
179 sys::fs::remove(Twine(Filename));
185 sys::fs::remove(Twine(Filename));
189 _nativeObjectPath = Filename.c_str();
190 *name = _nativeObjectPath.c_str();
194 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
196 if (compile_to_file(&name, errMsg))
199 // remove old buffer if compile() called twice
200 delete _nativeObjectFile;
202 // read .o file into memory buffer
203 OwningPtr<MemoryBuffer> BuffPtr;
204 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
205 errMsg = ec.message();
206 sys::fs::remove(_nativeObjectPath);
209 _nativeObjectFile = BuffPtr.take();
212 sys::fs::remove(_nativeObjectPath);
214 // return buffer, unless error
215 if (_nativeObjectFile == NULL)
217 *length = _nativeObjectFile->getBufferSize();
218 return _nativeObjectFile->getBufferStart();
221 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
225 // if options were requested, set them
226 if (!_codegenOptions.empty())
227 cl::ParseCommandLineOptions(_codegenOptions.size(),
228 const_cast<char **>(&_codegenOptions[0]));
230 std::string TripleStr = _linker.getModule()->getTargetTriple();
231 if (TripleStr.empty())
232 TripleStr = sys::getDefaultTargetTriple();
233 llvm::Triple Triple(TripleStr);
235 // create target machine from info for merged modules
236 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
240 // The relocation model is actually a static member of TargetMachine and
241 // needs to be set before the TargetMachine is instantiated.
242 Reloc::Model RelocModel = Reloc::Default;
243 switch (_codeModel) {
244 case LTO_CODEGEN_PIC_MODEL_STATIC:
245 RelocModel = Reloc::Static;
247 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
248 RelocModel = Reloc::PIC_;
250 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
251 RelocModel = Reloc::DynamicNoPIC;
255 // construct LTOModule, hand over ownership of module and target
256 SubtargetFeatures Features;
257 Features.getDefaultSubtargetFeatures(Triple);
258 std::string FeatureStr = Features.getString();
259 // Set a default CPU for Darwin triples.
260 if (_mCpu.empty() && Triple.isOSDarwin()) {
261 if (Triple.getArch() == llvm::Triple::x86_64)
263 else if (Triple.getArch() == llvm::Triple::x86)
266 TargetOptions Options;
267 LTOModule::getTargetOptions(Options);
268 _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
269 RelocModel, CodeModel::Default,
270 CodeGenOpt::Aggressive);
274 void LTOCodeGenerator::
275 applyRestriction(GlobalValue &GV,
276 std::vector<const char*> &mustPreserveList,
277 SmallPtrSet<GlobalValue*, 8> &asmUsed,
279 SmallString<64> Buffer;
280 mangler.getNameWithPrefix(Buffer, &GV, false);
282 if (GV.isDeclaration())
284 if (_mustPreserveSymbols.count(Buffer))
285 mustPreserveList.push_back(GV.getName().data());
286 if (_asmUndefinedRefs.count(Buffer))
290 static void findUsedValues(GlobalVariable *LLVMUsed,
291 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
292 if (LLVMUsed == 0) return;
294 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
295 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
296 if (GlobalValue *GV =
297 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
298 UsedValues.insert(GV);
301 void LTOCodeGenerator::applyScopeRestrictions() {
302 if (_scopeRestrictionsDone) return;
303 Module *mergedModule = _linker.getModule();
305 // Start off with a verification pass.
307 passes.add(createVerifierPass());
309 // mark which symbols can not be internalized
310 MCContext Context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL);
311 Mangler mangler(Context, _target);
312 std::vector<const char*> mustPreserveList;
313 SmallPtrSet<GlobalValue*, 8> asmUsed;
315 for (Module::iterator f = mergedModule->begin(),
316 e = mergedModule->end(); f != e; ++f)
317 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
318 for (Module::global_iterator v = mergedModule->global_begin(),
319 e = mergedModule->global_end(); v != e; ++v)
320 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
321 for (Module::alias_iterator a = mergedModule->alias_begin(),
322 e = mergedModule->alias_end(); a != e; ++a)
323 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
325 GlobalVariable *LLVMCompilerUsed =
326 mergedModule->getGlobalVariable("llvm.compiler.used");
327 findUsedValues(LLVMCompilerUsed, asmUsed);
328 if (LLVMCompilerUsed)
329 LLVMCompilerUsed->eraseFromParent();
331 if (!asmUsed.empty()) {
332 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
333 std::vector<Constant*> asmUsed2;
334 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
335 e = asmUsed.end(); i !=e; ++i) {
336 GlobalValue *GV = *i;
337 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
338 asmUsed2.push_back(c);
341 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
343 new llvm::GlobalVariable(*mergedModule, ATy, false,
344 llvm::GlobalValue::AppendingLinkage,
345 llvm::ConstantArray::get(ATy, asmUsed2),
346 "llvm.compiler.used");
348 LLVMCompilerUsed->setSection("llvm.metadata");
351 passes.add(createInternalizePass(mustPreserveList));
353 // apply scope restrictions
354 passes.run(*mergedModule);
356 _scopeRestrictionsDone = true;
359 /// Optimize merged modules using various IPO passes
360 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
361 std::string &errMsg) {
362 if (this->determineTarget(errMsg))
365 Module* mergedModule = _linker.getModule();
367 // Mark which symbols can not be internalized
368 this->applyScopeRestrictions();
370 // Instantiate the pass manager to organize the passes.
373 // Start off with a verification pass.
374 passes.add(createVerifierPass());
376 // Add an appropriate DataLayout instance for this module...
377 passes.add(new DataLayout(*_target->getDataLayout()));
378 _target->addAnalysisPasses(passes);
380 // Enabling internalize here would use its AllButMain variant. It
381 // keeps only main if it exists and does nothing for libraries. Instead
382 // we create the pass ourselves with the symbol list provided by the linker.
384 PassManagerBuilder().populateLTOPassManager(passes,
385 /*Internalize=*/false,
389 // Make sure everything is still good.
390 passes.add(createVerifierPass());
392 PassManager codeGenPasses;
394 codeGenPasses.add(new DataLayout(*_target->getDataLayout()));
395 _target->addAnalysisPasses(codeGenPasses);
397 formatted_raw_ostream Out(out);
399 // If the bitcode files contain ARC code and were compiled with optimization,
400 // the ObjCARCContractPass must be run, so do it unconditionally here.
401 codeGenPasses.add(createObjCARCContractPass());
403 if (_target->addPassesToEmitFile(codeGenPasses, Out,
404 TargetMachine::CGFT_ObjectFile)) {
405 errMsg = "target file type not supported";
409 // Run our queue of passes all at once now, efficiently.
410 passes.run(*mergedModule);
412 // Run the code generator, and write assembly file
413 codeGenPasses.run(*mergedModule);
415 return false; // success
418 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
420 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
421 for (std::pair<StringRef, StringRef> o = getToken(options);
422 !o.first.empty(); o = getToken(o.second)) {
423 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
425 if (_codegenOptions.empty())
426 _codegenOptions.push_back(strdup("libLTO"));
427 _codegenOptions.push_back(strdup(o.first.str().c_str()));