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 "llvm/LTO/LTOCodeGenerator.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/RuntimeLibcalls.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/LTO/LTOModule.h"
35 #include "llvm/Linker/Linker.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/IPO.h"
54 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 #include "llvm/Transforms/ObjCARC.h"
56 #include <system_error>
59 const char* LTOCodeGenerator::getVersionString() {
60 #ifdef LLVM_VERSION_INFO
61 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
63 return PACKAGE_NAME " version " PACKAGE_VERSION;
67 LTOCodeGenerator::LTOCodeGenerator()
68 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
72 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
73 : OwnedContext(std::move(Context)), Context(*OwnedContext),
74 IRLinker(new Module("ld-temp.o", *OwnedContext)) {
78 void LTOCodeGenerator::initialize() {
80 EmitDwarfDebugInfo = false;
81 ScopeRestrictionsDone = false;
82 CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT;
83 DiagHandler = nullptr;
84 DiagContext = nullptr;
86 initializeLTOPasses();
89 LTOCodeGenerator::~LTOCodeGenerator() {
93 IRLinker.deleteModule();
95 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
96 E = CodegenOptions.end();
101 // Initialize LTO passes. Please keep this funciton in sync with
102 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
103 // passes are initialized.
104 void LTOCodeGenerator::initializeLTOPasses() {
105 PassRegistry &R = *PassRegistry::getPassRegistry();
107 initializeInternalizePassPass(R);
108 initializeIPSCCPPass(R);
109 initializeGlobalOptPass(R);
110 initializeConstantMergePass(R);
111 initializeDAHPass(R);
112 initializeInstructionCombiningPassPass(R);
113 initializeSimpleInlinerPass(R);
114 initializePruneEHPass(R);
115 initializeGlobalDCEPass(R);
116 initializeArgPromotionPass(R);
117 initializeJumpThreadingPass(R);
118 initializeSROAPass(R);
119 initializeSROA_DTPass(R);
120 initializeSROA_SSAUpPass(R);
121 initializeFunctionAttrsPass(R);
122 initializeGlobalsModRefPass(R);
123 initializeLICMPass(R);
124 initializeMergedLoadStoreMotionPass(R);
125 initializeGVNPass(R);
126 initializeMemCpyOptPass(R);
127 initializeDCEPass(R);
128 initializeCFGSimplifyPassPass(R);
131 bool LTOCodeGenerator::addModule(LTOModule *mod) {
132 assert(&mod->getModule().getContext() == &Context &&
133 "Expected module in same context");
135 bool ret = IRLinker.linkInModule(&mod->getModule());
137 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
138 for (int i = 0, e = undefs.size(); i != e; ++i)
139 AsmUndefinedRefs[undefs[i]] = 1;
144 void LTOCodeGenerator::setModule(LTOModule *Mod) {
145 assert(&Mod->getModule().getContext() == &Context &&
146 "Expected module in same context");
148 // Delete the old merged module.
149 if (IRLinker.getModule())
150 IRLinker.deleteModule();
151 AsmUndefinedRefs.clear();
153 IRLinker.setModule(&Mod->getModule());
155 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
156 for (int I = 0, E = Undefs.size(); I != E; ++I)
157 AsmUndefinedRefs[Undefs[I]] = 1;
160 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
164 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
166 case LTO_DEBUG_MODEL_NONE:
167 EmitDwarfDebugInfo = false;
170 case LTO_DEBUG_MODEL_DWARF:
171 EmitDwarfDebugInfo = true;
174 llvm_unreachable("Unknown debug format!");
177 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
179 case LTO_CODEGEN_PIC_MODEL_STATIC:
180 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
181 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
182 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
186 llvm_unreachable("Unknown PIC model!");
189 bool LTOCodeGenerator::writeMergedModules(const char *path,
190 std::string &errMsg) {
191 if (!determineTarget(errMsg))
194 // mark which symbols can not be internalized
195 applyScopeRestrictions();
197 // create output file
199 tool_output_file Out(path, EC, sys::fs::F_None);
201 errMsg = "could not open bitcode file for writing: ";
206 // write bitcode to it
207 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
210 if (Out.os().has_error()) {
211 errMsg = "could not write bitcode file: ";
213 Out.os().clear_error();
221 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
222 std::string &errMsg) {
223 // make unique temp .o file to put generated object file
224 SmallString<128> Filename;
227 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
229 errMsg = EC.message();
233 // generate object file
234 tool_output_file objFile(Filename.c_str(), FD);
236 bool genResult = compileOptimized(objFile.os(), errMsg);
237 objFile.os().close();
238 if (objFile.os().has_error()) {
239 objFile.os().clear_error();
240 sys::fs::remove(Twine(Filename));
246 sys::fs::remove(Twine(Filename));
250 NativeObjectPath = Filename.c_str();
251 *name = NativeObjectPath.c_str();
255 const void *LTOCodeGenerator::compileOptimized(size_t *length,
256 std::string &errMsg) {
258 if (!compileOptimizedToFile(&name, errMsg))
261 // read .o file into memory buffer
262 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
263 MemoryBuffer::getFile(name, -1, false);
264 if (std::error_code EC = BufferOrErr.getError()) {
265 errMsg = EC.message();
266 sys::fs::remove(NativeObjectPath);
269 NativeObjectFile = std::move(*BufferOrErr);
272 sys::fs::remove(NativeObjectPath);
274 // return buffer, unless error
275 if (!NativeObjectFile)
277 *length = NativeObjectFile->getBufferSize();
278 return NativeObjectFile->getBufferStart();
282 bool LTOCodeGenerator::compile_to_file(const char **name,
285 bool disableGVNLoadPRE,
286 bool disableVectorization,
287 std::string &errMsg) {
288 if (!optimize(disableOpt, disableInline, disableGVNLoadPRE,
289 disableVectorization, errMsg))
292 return compileOptimizedToFile(name, errMsg);
295 const void* LTOCodeGenerator::compile(size_t *length,
298 bool disableGVNLoadPRE,
299 bool disableVectorization,
300 std::string &errMsg) {
301 if (!optimize(disableOpt, disableInline, disableGVNLoadPRE,
302 disableVectorization, errMsg))
305 return compileOptimized(length, errMsg);
308 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
312 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
313 if (TripleStr.empty())
314 TripleStr = sys::getDefaultTargetTriple();
315 llvm::Triple Triple(TripleStr);
317 // create target machine from info for merged modules
318 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
322 // The relocation model is actually a static member of TargetMachine and
323 // needs to be set before the TargetMachine is instantiated.
324 Reloc::Model RelocModel = Reloc::Default;
326 case LTO_CODEGEN_PIC_MODEL_STATIC:
327 RelocModel = Reloc::Static;
329 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
330 RelocModel = Reloc::PIC_;
332 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
333 RelocModel = Reloc::DynamicNoPIC;
335 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
336 // RelocModel is already the default, so leave it that way.
340 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
341 // the default set of features.
342 SubtargetFeatures Features(MAttr);
343 Features.getDefaultSubtargetFeatures(Triple);
344 std::string FeatureStr = Features.getString();
345 // Set a default CPU for Darwin triples.
346 if (MCpu.empty() && Triple.isOSDarwin()) {
347 if (Triple.getArch() == llvm::Triple::x86_64)
349 else if (Triple.getArch() == llvm::Triple::x86)
351 else if (Triple.getArch() == llvm::Triple::aarch64)
355 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
356 RelocModel, CodeModel::Default,
357 CodeGenOpt::Aggressive);
361 void LTOCodeGenerator::
362 applyRestriction(GlobalValue &GV,
363 ArrayRef<StringRef> Libcalls,
364 std::vector<const char*> &MustPreserveList,
365 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
367 // There are no restrictions to apply to declarations.
368 if (GV.isDeclaration())
371 // There is nothing more restrictive than private linkage.
372 if (GV.hasPrivateLinkage())
375 SmallString<64> Buffer;
376 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
378 if (MustPreserveSymbols.count(Buffer))
379 MustPreserveList.push_back(GV.getName().data());
380 if (AsmUndefinedRefs.count(Buffer))
383 // Conservatively append user-supplied runtime library functions to
384 // llvm.compiler.used. These could be internalized and deleted by
385 // optimizations like -globalopt, causing problems when later optimizations
386 // add new library calls (e.g., llvm.memset => memset and printf => puts).
387 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
388 if (isa<Function>(GV) &&
389 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
393 static void findUsedValues(GlobalVariable *LLVMUsed,
394 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
395 if (!LLVMUsed) return;
397 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
398 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
399 if (GlobalValue *GV =
400 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
401 UsedValues.insert(GV);
404 // Collect names of runtime library functions. User-defined functions with the
405 // same names are added to llvm.compiler.used to prevent them from being
406 // deleted by optimizations.
407 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
408 const TargetLibraryInfo& TLI,
410 const TargetMachine &TM) {
411 // TargetLibraryInfo has info on C runtime library calls on the current
413 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
415 LibFunc::Func F = static_cast<LibFunc::Func>(I);
417 Libcalls.push_back(TLI.getName(F));
420 SmallPtrSet<const TargetLowering *, 1> TLSet;
422 for (const Function &F : Mod) {
423 const TargetLowering *Lowering =
424 TM.getSubtargetImpl(F)->getTargetLowering();
426 if (Lowering && TLSet.insert(Lowering).second)
427 // TargetLowering has info on library calls that CodeGen expects to be
428 // available, both from the C runtime and compiler-rt.
429 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
431 if (const char *Name =
432 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
433 Libcalls.push_back(Name);
436 array_pod_sort(Libcalls.begin(), Libcalls.end());
437 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
441 void LTOCodeGenerator::applyScopeRestrictions() {
442 if (ScopeRestrictionsDone)
444 Module *mergedModule = IRLinker.getModule();
446 // Start off with a verification pass.
447 legacy::PassManager passes;
448 passes.add(createVerifierPass());
449 passes.add(createDebugInfoVerifierPass());
451 // mark which symbols can not be internalized
452 Mangler Mangler(TargetMach->getDataLayout());
453 std::vector<const char*> MustPreserveList;
454 SmallPtrSet<GlobalValue*, 8> AsmUsed;
455 std::vector<StringRef> Libcalls;
456 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
457 TargetLibraryInfo TLI(TLII);
459 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
461 for (Module::iterator f = mergedModule->begin(),
462 e = mergedModule->end(); f != e; ++f)
463 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
464 for (Module::global_iterator v = mergedModule->global_begin(),
465 e = mergedModule->global_end(); v != e; ++v)
466 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
467 for (Module::alias_iterator a = mergedModule->alias_begin(),
468 e = mergedModule->alias_end(); a != e; ++a)
469 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
471 GlobalVariable *LLVMCompilerUsed =
472 mergedModule->getGlobalVariable("llvm.compiler.used");
473 findUsedValues(LLVMCompilerUsed, AsmUsed);
474 if (LLVMCompilerUsed)
475 LLVMCompilerUsed->eraseFromParent();
477 if (!AsmUsed.empty()) {
478 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
479 std::vector<Constant*> asmUsed2;
480 for (auto *GV : AsmUsed) {
481 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
482 asmUsed2.push_back(c);
485 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
487 new llvm::GlobalVariable(*mergedModule, ATy, false,
488 llvm::GlobalValue::AppendingLinkage,
489 llvm::ConstantArray::get(ATy, asmUsed2),
490 "llvm.compiler.used");
492 LLVMCompilerUsed->setSection("llvm.metadata");
495 passes.add(createInternalizePass(MustPreserveList));
497 // apply scope restrictions
498 passes.run(*mergedModule);
500 ScopeRestrictionsDone = true;
503 /// Optimize merged modules using various IPO passes
504 bool LTOCodeGenerator::optimize(bool DisableOpt,
506 bool DisableGVNLoadPRE,
507 bool DisableVectorization,
508 std::string &errMsg) {
509 if (!this->determineTarget(errMsg))
512 Module *mergedModule = IRLinker.getModule();
514 // Mark which symbols can not be internalized
515 this->applyScopeRestrictions();
517 // Instantiate the pass manager to organize the passes.
518 legacy::PassManager passes;
520 // Add an appropriate DataLayout instance for this module...
521 mergedModule->setDataLayout(TargetMach->getDataLayout());
523 passes.add(new DataLayoutPass());
525 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
527 Triple TargetTriple(TargetMach->getTargetTriple());
528 PassManagerBuilder PMB;
529 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
530 PMB.LoopVectorize = !DisableVectorization;
531 PMB.SLPVectorize = !DisableVectorization;
533 PMB.Inliner = createFunctionInliningPass();
534 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
537 PMB.VerifyInput = true;
538 PMB.VerifyOutput = true;
540 PMB.populateLTOPassManager(passes);
542 // Run our queue of passes all at once now, efficiently.
543 passes.run(*mergedModule);
548 bool LTOCodeGenerator::compileOptimized(raw_ostream &out, std::string &errMsg) {
549 if (!this->determineTarget(errMsg))
552 Module *mergedModule = IRLinker.getModule();
554 // Mark which symbols can not be internalized
555 this->applyScopeRestrictions();
557 legacy::PassManager codeGenPasses;
559 codeGenPasses.add(new DataLayoutPass());
561 formatted_raw_ostream Out(out);
563 // If the bitcode files contain ARC code and were compiled with optimization,
564 // the ObjCARCContractPass must be run, so do it unconditionally here.
565 codeGenPasses.add(createObjCARCContractPass());
567 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
568 TargetMachine::CGFT_ObjectFile)) {
569 errMsg = "target file type not supported";
573 // Run the code generator, and write assembly file
574 codeGenPasses.run(*mergedModule);
579 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
581 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
582 for (std::pair<StringRef, StringRef> o = getToken(options);
583 !o.first.empty(); o = getToken(o.second)) {
584 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
586 if (CodegenOptions.empty())
587 CodegenOptions.push_back(strdup("libLLVMLTO"));
588 CodegenOptions.push_back(strdup(o.first.str().c_str()));
592 void LTOCodeGenerator::parseCodeGenDebugOptions() {
593 // if options were requested, set them
594 if (!CodegenOptions.empty())
595 cl::ParseCommandLineOptions(CodegenOptions.size(),
596 const_cast<char **>(&CodegenOptions[0]));
599 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
601 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
604 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
605 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
606 lto_codegen_diagnostic_severity_t Severity;
607 switch (DI.getSeverity()) {
609 Severity = LTO_DS_ERROR;
612 Severity = LTO_DS_WARNING;
615 Severity = LTO_DS_REMARK;
618 Severity = LTO_DS_NOTE;
621 // Create the string that will be reported to the external diagnostic handler.
622 std::string MsgStorage;
623 raw_string_ostream Stream(MsgStorage);
624 DiagnosticPrinterRawOStream DP(Stream);
628 // If this method has been called it means someone has set up an external
629 // diagnostic handler. Assert on that.
630 assert(DiagHandler && "Invalid diagnostic handler");
631 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
635 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
637 this->DiagHandler = DiagHandler;
638 this->DiagContext = Ctxt;
640 return Context.setDiagnosticHandler(nullptr, nullptr);
641 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
642 // diagnostic to the external DiagHandler.
643 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
644 /* RespectFilters */ true);