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/legacy/LTOCodeGenerator.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeWriter.h"
23 #include "llvm/CodeGen/ParallelCG.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/LTO/LTO.h"
39 #include "llvm/LTO/legacy/LTOModule.h"
40 #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
41 #include "llvm/Linker/Linker.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/SubtargetFeature.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/Host.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Signals.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/ToolOutputFile.h"
53 #include "llvm/Support/YAMLTraits.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "llvm/Transforms/IPO.h"
57 #include "llvm/Transforms/IPO/Internalize.h"
58 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
59 #include "llvm/Transforms/ObjCARC.h"
60 #include "llvm/Transforms/Utils/ModuleUtils.h"
61 #include <system_error>
64 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 cl::opt<bool> LTODiscardValueNames(
74 "lto-discard-value-names",
75 cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
84 LTORemarksFilename("lto-pass-remarks-output",
85 cl::desc("Output filename for pass remarks"),
86 cl::value_desc("filename"));
88 cl::opt<bool> LTOPassRemarksWithHotness(
89 "lto-pass-remarks-with-hotness",
90 cl::desc("With PGO, include profile count in optimization remarks"),
94 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
95 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
96 TheLinker(new Linker(*MergedModule)) {
97 Context.setDiscardValueNames(LTODiscardValueNames);
98 Context.enableDebugTypeODRUniquing();
99 initializeLTOPasses();
102 LTOCodeGenerator::~LTOCodeGenerator() {}
104 // Initialize LTO passes. Please keep this function in sync with
105 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
106 // passes are initialized.
107 void LTOCodeGenerator::initializeLTOPasses() {
108 PassRegistry &R = *PassRegistry::getPassRegistry();
110 initializeInternalizeLegacyPassPass(R);
111 initializeIPSCCPLegacyPassPass(R);
112 initializeGlobalOptLegacyPassPass(R);
113 initializeConstantMergeLegacyPassPass(R);
114 initializeDAHPass(R);
115 initializeInstructionCombiningPassPass(R);
116 initializeSimpleInlinerPass(R);
117 initializePruneEHPass(R);
118 initializeGlobalDCELegacyPassPass(R);
119 initializeArgPromotionPass(R);
120 initializeJumpThreadingPass(R);
121 initializeSROALegacyPassPass(R);
122 initializePostOrderFunctionAttrsLegacyPassPass(R);
123 initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
124 initializeGlobalsAAWrapperPassPass(R);
125 initializeLegacyLICMPassPass(R);
126 initializeMergedLoadStoreMotionLegacyPassPass(R);
127 initializeGVNLegacyPassPass(R);
128 initializeMemCpyOptLegacyPassPass(R);
129 initializeDCELegacyPassPass(R);
130 initializeCFGSimplifyPassPass(R);
133 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
134 const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
135 for (int i = 0, e = undefs.size(); i != e; ++i)
136 AsmUndefinedRefs[undefs[i]] = 1;
139 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
140 assert(&Mod->getModule().getContext() == &Context &&
141 "Expected module in same context");
143 bool ret = TheLinker->linkInModule(Mod->takeModule());
144 setAsmUndefinedRefs(Mod);
146 // We've just changed the input, so let's make sure we verify it.
147 HasVerifiedInput = false;
152 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
153 assert(&Mod->getModule().getContext() == &Context &&
154 "Expected module in same context");
156 AsmUndefinedRefs.clear();
158 MergedModule = Mod->takeModule();
159 TheLinker = make_unique<Linker>(*MergedModule);
160 setAsmUndefinedRefs(&*Mod);
162 // We've just changed the input, so let's make sure we verify it.
163 HasVerifiedInput = false;
166 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
167 this->Options = Options;
170 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
172 case LTO_DEBUG_MODEL_NONE:
173 EmitDwarfDebugInfo = false;
176 case LTO_DEBUG_MODEL_DWARF:
177 EmitDwarfDebugInfo = true;
180 llvm_unreachable("Unknown debug format!");
183 void LTOCodeGenerator::setOptLevel(unsigned Level) {
187 CGOptLevel = CodeGenOpt::None;
190 CGOptLevel = CodeGenOpt::Less;
193 CGOptLevel = CodeGenOpt::Default;
196 CGOptLevel = CodeGenOpt::Aggressive;
199 llvm_unreachable("Unknown optimization level!");
202 bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
203 if (!determineTarget())
206 // We always run the verifier once on the merged module.
207 verifyMergedModuleOnce();
209 // mark which symbols can not be internalized
210 applyScopeRestrictions();
212 // create output file
214 ToolOutputFile Out(Path, EC, sys::fs::F_None);
216 std::string ErrMsg = "could not open bitcode file for writing: ";
217 ErrMsg += Path.str() + ": " + EC.message();
222 // write bitcode to it
223 WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
226 if (Out.os().has_error()) {
227 std::string ErrMsg = "could not write bitcode file: ";
228 ErrMsg += Path.str() + ": " + Out.os().error().message();
230 Out.os().clear_error();
238 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
239 // make unique temp output file to put generated code
240 SmallString<128> Filename;
244 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
247 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
249 emitError(EC.message());
253 // generate object file
254 ToolOutputFile objFile(Filename, FD);
256 bool genResult = compileOptimized(&objFile.os());
257 objFile.os().close();
258 if (objFile.os().has_error()) {
259 emitError((Twine("could not write object file: ") + Filename + ": " +
260 objFile.os().error().message())
262 objFile.os().clear_error();
263 sys::fs::remove(Twine(Filename));
269 sys::fs::remove(Twine(Filename));
273 NativeObjectPath = Filename.c_str();
274 *Name = NativeObjectPath.c_str();
278 std::unique_ptr<MemoryBuffer>
279 LTOCodeGenerator::compileOptimized() {
281 if (!compileOptimizedToFile(&name))
284 // read .o file into memory buffer
285 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
286 MemoryBuffer::getFile(name, -1, false);
287 if (std::error_code EC = BufferOrErr.getError()) {
288 emitError(EC.message());
289 sys::fs::remove(NativeObjectPath);
294 sys::fs::remove(NativeObjectPath);
296 return std::move(*BufferOrErr);
299 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
301 bool DisableGVNLoadPRE,
302 bool DisableVectorization) {
303 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
304 DisableVectorization))
307 return compileOptimizedToFile(Name);
310 std::unique_ptr<MemoryBuffer>
311 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
312 bool DisableGVNLoadPRE, bool DisableVectorization) {
313 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
314 DisableVectorization))
317 return compileOptimized();
320 bool LTOCodeGenerator::determineTarget() {
324 TripleStr = MergedModule->getTargetTriple();
325 if (TripleStr.empty()) {
326 TripleStr = sys::getDefaultTargetTriple();
327 MergedModule->setTargetTriple(TripleStr);
329 llvm::Triple Triple(TripleStr);
331 // create target machine from info for merged modules
333 MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
339 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
340 // the default set of features.
341 SubtargetFeatures Features(MAttr);
342 Features.getDefaultSubtargetFeatures(Triple);
343 FeatureStr = Features.getString();
344 // Set a default CPU for Darwin triples.
345 if (MCpu.empty() && Triple.isOSDarwin()) {
346 if (Triple.getArch() == llvm::Triple::x86_64)
348 else if (Triple.getArch() == llvm::Triple::x86)
350 else if (Triple.getArch() == llvm::Triple::aarch64)
354 TargetMach = createTargetMachine();
358 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
359 return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
360 TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
363 // If a linkonce global is present in the MustPreserveSymbols, we need to make
364 // sure we honor this. To force the compiler to not drop it, we add it to the
365 // "llvm.compiler.used" global.
366 void LTOCodeGenerator::preserveDiscardableGVs(
368 llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
369 std::vector<GlobalValue *> Used;
370 auto mayPreserveGlobal = [&](GlobalValue &GV) {
371 if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
374 if (GV.hasAvailableExternallyLinkage())
376 (Twine("Linker asked to preserve available_externally global: '") +
377 GV.getName() + "'").str());
378 if (GV.hasInternalLinkage())
379 return emitWarning((Twine("Linker asked to preserve internal global: '") +
380 GV.getName() + "'").str());
383 for (auto &GV : TheModule)
384 mayPreserveGlobal(GV);
385 for (auto &GV : TheModule.globals())
386 mayPreserveGlobal(GV);
387 for (auto &GV : TheModule.aliases())
388 mayPreserveGlobal(GV);
393 appendToCompilerUsed(TheModule, Used);
396 void LTOCodeGenerator::applyScopeRestrictions() {
397 if (ScopeRestrictionsDone)
400 // Declare a callback for the internalize pass that will ask for every
401 // candidate GlobalValue if it can be internalized or not.
403 SmallString<64> MangledName;
404 auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
405 // Unnamed globals can't be mangled, but they can't be preserved either.
409 // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
410 // with the linker supplied name, which on Darwin includes a leading
413 MangledName.reserve(GV.getName().size() + 1);
414 Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
415 return MustPreserveSymbols.count(MangledName);
418 // Preserve linkonce value on linker request
419 preserveDiscardableGVs(*MergedModule, mustPreserveGV);
421 if (!ShouldInternalize)
424 if (ShouldRestoreGlobalsLinkage) {
425 // Record the linkage type of non-local symbols so they can be restored
427 // to module splitting.
428 auto RecordLinkage = [&](const GlobalValue &GV) {
429 if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
431 ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
433 for (auto &GV : *MergedModule)
435 for (auto &GV : MergedModule->globals())
437 for (auto &GV : MergedModule->aliases())
441 // Update the llvm.compiler_used globals to force preserving libcalls and
442 // symbols referenced from asm
443 updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
445 internalizeModule(*MergedModule, mustPreserveGV);
447 ScopeRestrictionsDone = true;
450 /// Restore original linkage for symbols that may have been internalized
451 void LTOCodeGenerator::restoreLinkageForExternals() {
452 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
455 assert(ScopeRestrictionsDone &&
456 "Cannot externalize without internalization!");
458 if (ExternalSymbols.empty())
461 auto externalize = [this](GlobalValue &GV) {
462 if (!GV.hasLocalLinkage() || !GV.hasName())
465 auto I = ExternalSymbols.find(GV.getName());
466 if (I == ExternalSymbols.end())
469 GV.setLinkage(I->second);
472 llvm::for_each(MergedModule->functions(), externalize);
473 llvm::for_each(MergedModule->globals(), externalize);
474 llvm::for_each(MergedModule->aliases(), externalize);
477 void LTOCodeGenerator::verifyMergedModuleOnce() {
478 // Only run on the first call.
479 if (HasVerifiedInput)
481 HasVerifiedInput = true;
483 bool BrokenDebugInfo = false;
484 if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
485 report_fatal_error("Broken module found, compilation aborted!");
486 if (BrokenDebugInfo) {
487 emitWarning("Invalid debug info found, debug info will be stripped");
488 StripDebugInfo(*MergedModule);
492 void LTOCodeGenerator::finishOptimizationRemarks() {
493 if (DiagnosticOutputFile) {
494 DiagnosticOutputFile->keep();
495 // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
496 DiagnosticOutputFile->os().flush();
500 /// Optimize merged modules using various IPO passes
501 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
502 bool DisableGVNLoadPRE,
503 bool DisableVectorization) {
504 if (!this->determineTarget())
507 auto DiagFileOrErr = lto::setupOptimizationRemarks(
508 Context, LTORemarksFilename, LTOPassRemarksWithHotness);
509 if (!DiagFileOrErr) {
510 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
511 report_fatal_error("Can't get an output file for the remarks");
513 DiagnosticOutputFile = std::move(*DiagFileOrErr);
515 // We always run the verifier once on the merged module, the `DisableVerify`
516 // parameter only applies to subsequent verify.
517 verifyMergedModuleOnce();
519 // Mark which symbols can not be internalized
520 this->applyScopeRestrictions();
522 // Instantiate the pass manager to organize the passes.
523 legacy::PassManager passes;
525 // Add an appropriate DataLayout instance for this module...
526 MergedModule->setDataLayout(TargetMach->createDataLayout());
529 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
531 Triple TargetTriple(TargetMach->getTargetTriple());
532 PassManagerBuilder PMB;
533 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
534 PMB.LoopVectorize = !DisableVectorization;
535 PMB.SLPVectorize = !DisableVectorization;
537 PMB.Inliner = createFunctionInliningPass();
538 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
540 PMB.LibraryInfo->disableAllFunctions();
541 PMB.OptLevel = OptLevel;
542 PMB.VerifyInput = !DisableVerify;
543 PMB.VerifyOutput = !DisableVerify;
545 PMB.populateLTOPassManager(passes);
547 // Run our queue of passes all at once now, efficiently.
548 passes.run(*MergedModule);
553 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
554 if (!this->determineTarget())
557 // We always run the verifier once on the merged module. If it has already
558 // been called in optimize(), this call will return early.
559 verifyMergedModuleOnce();
561 legacy::PassManager preCodeGenPasses;
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 preCodeGenPasses.add(createObjCARCContractPass());
566 preCodeGenPasses.run(*MergedModule);
568 // Re-externalize globals that may have been internalized to increase scope
570 restoreLinkageForExternals();
572 // Do code generation. We need to preserve the module in case the client calls
573 // writeMergedModules() after compilation, but we only need to allow this at
574 // parallelism level 1. This is achieved by having splitCodeGen return the
575 // original module at parallelism level 1 which we then assign back to
577 MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
578 [&]() { return createTargetMachine(); }, FileType,
579 ShouldRestoreGlobalsLinkage);
581 // If statistics were requested, print them out after codegen.
582 if (llvm::AreStatisticsEnabled())
583 llvm::PrintStatistics();
584 reportAndResetTimings();
586 finishOptimizationRemarks();
591 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
593 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
594 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
595 o = getToken(o.second))
596 CodegenOptions.push_back(o.first);
599 void LTOCodeGenerator::parseCodeGenDebugOptions() {
600 // if options were requested, set them
601 if (!CodegenOptions.empty()) {
602 // ParseCommandLineOptions() expects argv[0] to be program name.
603 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
604 for (std::string &Arg : CodegenOptions)
605 CodegenArgv.push_back(Arg.c_str());
606 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
611 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
612 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
613 lto_codegen_diagnostic_severity_t Severity;
614 switch (DI.getSeverity()) {
616 Severity = LTO_DS_ERROR;
619 Severity = LTO_DS_WARNING;
622 Severity = LTO_DS_REMARK;
625 Severity = LTO_DS_NOTE;
628 // Create the string that will be reported to the external diagnostic handler.
629 std::string MsgStorage;
630 raw_string_ostream Stream(MsgStorage);
631 DiagnosticPrinterRawOStream DP(Stream);
635 // If this method has been called it means someone has set up an external
636 // diagnostic handler. Assert on that.
637 assert(DiagHandler && "Invalid diagnostic handler");
638 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
642 struct LTODiagnosticHandler : public DiagnosticHandler {
643 LTOCodeGenerator *CodeGenerator;
644 LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
645 : CodeGenerator(CodeGenPtr) {}
646 bool handleDiagnostics(const DiagnosticInfo &DI) override {
647 CodeGenerator->DiagnosticHandler(DI);
654 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
656 this->DiagHandler = DiagHandler;
657 this->DiagContext = Ctxt;
659 return Context.setDiagnosticHandler(nullptr);
660 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
661 // diagnostic to the external DiagHandler.
662 Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
667 class LTODiagnosticInfo : public DiagnosticInfo {
670 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
671 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
672 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
676 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
678 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
680 Context.diagnose(LTODiagnosticInfo(ErrMsg));
683 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
685 (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
687 Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));