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/RuntimeLibcalls.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/TargetLowering.h"
56 #include "llvm/Target/TargetOptions.h"
57 #include "llvm/Target/TargetRegisterInfo.h"
58 #include "llvm/Target/TargetSubtargetInfo.h"
59 #include "llvm/Transforms/IPO.h"
60 #include "llvm/Transforms/IPO/Internalize.h"
61 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
62 #include "llvm/Transforms/ObjCARC.h"
63 #include "llvm/Transforms/Utils/ModuleUtils.h"
64 #include <system_error>
67 const char* LTOCodeGenerator::getVersionString() {
68 #ifdef LLVM_VERSION_INFO
69 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
71 return PACKAGE_NAME " version " PACKAGE_VERSION;
76 cl::opt<bool> LTODiscardValueNames(
77 "lto-discard-value-names",
78 cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
87 LTORemarksFilename("lto-pass-remarks-output",
88 cl::desc("Output filename for pass remarks"),
89 cl::value_desc("filename"));
91 cl::opt<bool> LTOPassRemarksWithHotness(
92 "lto-pass-remarks-with-hotness",
93 cl::desc("With PGO, include profile count in optimization remarks"),
97 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
98 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
99 TheLinker(new Linker(*MergedModule)) {
100 Context.setDiscardValueNames(LTODiscardValueNames);
101 Context.enableDebugTypeODRUniquing();
102 initializeLTOPasses();
105 LTOCodeGenerator::~LTOCodeGenerator() {}
107 // Initialize LTO passes. Please keep this function in sync with
108 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
109 // passes are initialized.
110 void LTOCodeGenerator::initializeLTOPasses() {
111 PassRegistry &R = *PassRegistry::getPassRegistry();
113 initializeInternalizeLegacyPassPass(R);
114 initializeIPSCCPLegacyPassPass(R);
115 initializeGlobalOptLegacyPassPass(R);
116 initializeConstantMergeLegacyPassPass(R);
117 initializeDAHPass(R);
118 initializeInstructionCombiningPassPass(R);
119 initializeSimpleInlinerPass(R);
120 initializePruneEHPass(R);
121 initializeGlobalDCELegacyPassPass(R);
122 initializeArgPromotionPass(R);
123 initializeJumpThreadingPass(R);
124 initializeSROALegacyPassPass(R);
125 initializePostOrderFunctionAttrsLegacyPassPass(R);
126 initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
127 initializeGlobalsAAWrapperPassPass(R);
128 initializeLegacyLICMPassPass(R);
129 initializeMergedLoadStoreMotionLegacyPassPass(R);
130 initializeGVNLegacyPassPass(R);
131 initializeMemCpyOptLegacyPassPass(R);
132 initializeDCELegacyPassPass(R);
133 initializeCFGSimplifyPassPass(R);
136 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
137 const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
138 for (int i = 0, e = undefs.size(); i != e; ++i)
139 AsmUndefinedRefs[undefs[i]] = 1;
142 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
143 assert(&Mod->getModule().getContext() == &Context &&
144 "Expected module in same context");
146 bool ret = TheLinker->linkInModule(Mod->takeModule());
147 setAsmUndefinedRefs(Mod);
149 // We've just changed the input, so let's make sure we verify it.
150 HasVerifiedInput = false;
155 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
156 assert(&Mod->getModule().getContext() == &Context &&
157 "Expected module in same context");
159 AsmUndefinedRefs.clear();
161 MergedModule = Mod->takeModule();
162 TheLinker = make_unique<Linker>(*MergedModule);
163 setAsmUndefinedRefs(&*Mod);
165 // We've just changed the input, so let's make sure we verify it.
166 HasVerifiedInput = false;
169 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
170 this->Options = Options;
173 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
175 case LTO_DEBUG_MODEL_NONE:
176 EmitDwarfDebugInfo = false;
179 case LTO_DEBUG_MODEL_DWARF:
180 EmitDwarfDebugInfo = true;
183 llvm_unreachable("Unknown debug format!");
186 void LTOCodeGenerator::setOptLevel(unsigned Level) {
190 CGOptLevel = CodeGenOpt::None;
193 CGOptLevel = CodeGenOpt::Less;
196 CGOptLevel = CodeGenOpt::Default;
199 CGOptLevel = CodeGenOpt::Aggressive;
202 llvm_unreachable("Unknown optimization level!");
205 bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
206 if (!determineTarget())
209 // We always run the verifier once on the merged module.
210 verifyMergedModuleOnce();
212 // mark which symbols can not be internalized
213 applyScopeRestrictions();
215 // create output file
217 ToolOutputFile Out(Path, EC, sys::fs::F_None);
219 std::string ErrMsg = "could not open bitcode file for writing: ";
220 ErrMsg += Path.str() + ": " + EC.message();
225 // write bitcode to it
226 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
229 if (Out.os().has_error()) {
230 std::string ErrMsg = "could not write bitcode file: ";
231 ErrMsg += Path.str() + ": " + Out.os().error().message();
233 Out.os().clear_error();
241 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
242 // make unique temp output file to put generated code
243 SmallString<128> Filename;
247 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
250 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
252 emitError(EC.message());
256 // generate object file
257 ToolOutputFile objFile(Filename, FD);
259 bool genResult = compileOptimized(&objFile.os());
260 objFile.os().close();
261 if (objFile.os().has_error()) {
262 emitError((Twine("could not write object file: ") + Filename + ": " +
263 objFile.os().error().message())
265 objFile.os().clear_error();
266 sys::fs::remove(Twine(Filename));
272 sys::fs::remove(Twine(Filename));
276 NativeObjectPath = Filename.c_str();
277 *Name = NativeObjectPath.c_str();
281 std::unique_ptr<MemoryBuffer>
282 LTOCodeGenerator::compileOptimized() {
284 if (!compileOptimizedToFile(&name))
287 // read .o file into memory buffer
288 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
289 MemoryBuffer::getFile(name, -1, false);
290 if (std::error_code EC = BufferOrErr.getError()) {
291 emitError(EC.message());
292 sys::fs::remove(NativeObjectPath);
297 sys::fs::remove(NativeObjectPath);
299 return std::move(*BufferOrErr);
302 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
304 bool DisableGVNLoadPRE,
305 bool DisableVectorization) {
306 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
307 DisableVectorization))
310 return compileOptimizedToFile(Name);
313 std::unique_ptr<MemoryBuffer>
314 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
315 bool DisableGVNLoadPRE, bool DisableVectorization) {
316 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
317 DisableVectorization))
320 return compileOptimized();
323 bool LTOCodeGenerator::determineTarget() {
327 TripleStr = MergedModule->getTargetTriple();
328 if (TripleStr.empty()) {
329 TripleStr = sys::getDefaultTargetTriple();
330 MergedModule->setTargetTriple(TripleStr);
332 llvm::Triple Triple(TripleStr);
334 // create target machine from info for merged modules
336 MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
342 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
343 // the default set of features.
344 SubtargetFeatures Features(MAttr);
345 Features.getDefaultSubtargetFeatures(Triple);
346 FeatureStr = Features.getString();
347 // Set a default CPU for Darwin triples.
348 if (MCpu.empty() && Triple.isOSDarwin()) {
349 if (Triple.getArch() == llvm::Triple::x86_64)
351 else if (Triple.getArch() == llvm::Triple::x86)
353 else if (Triple.getArch() == llvm::Triple::aarch64)
357 TargetMach = createTargetMachine();
361 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
362 return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
363 TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
366 // If a linkonce global is present in the MustPreserveSymbols, we need to make
367 // sure we honor this. To force the compiler to not drop it, we add it to the
368 // "llvm.compiler.used" global.
369 void LTOCodeGenerator::preserveDiscardableGVs(
371 llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
372 std::vector<GlobalValue *> Used;
373 auto mayPreserveGlobal = [&](GlobalValue &GV) {
374 if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
377 if (GV.hasAvailableExternallyLinkage())
379 (Twine("Linker asked to preserve available_externally global: '") +
380 GV.getName() + "'").str());
381 if (GV.hasInternalLinkage())
382 return emitWarning((Twine("Linker asked to preserve internal global: '") +
383 GV.getName() + "'").str());
386 for (auto &GV : TheModule)
387 mayPreserveGlobal(GV);
388 for (auto &GV : TheModule.globals())
389 mayPreserveGlobal(GV);
390 for (auto &GV : TheModule.aliases())
391 mayPreserveGlobal(GV);
396 appendToCompilerUsed(TheModule, Used);
399 void LTOCodeGenerator::applyScopeRestrictions() {
400 if (ScopeRestrictionsDone)
403 // Declare a callback for the internalize pass that will ask for every
404 // candidate GlobalValue if it can be internalized or not.
406 SmallString<64> MangledName;
407 auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
408 // Unnamed globals can't be mangled, but they can't be preserved either.
412 // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
413 // with the linker supplied name, which on Darwin includes a leading
416 MangledName.reserve(GV.getName().size() + 1);
417 Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
418 return MustPreserveSymbols.count(MangledName);
421 // Preserve linkonce value on linker request
422 preserveDiscardableGVs(*MergedModule, mustPreserveGV);
424 if (!ShouldInternalize)
427 if (ShouldRestoreGlobalsLinkage) {
428 // Record the linkage type of non-local symbols so they can be restored
430 // to module splitting.
431 auto RecordLinkage = [&](const GlobalValue &GV) {
432 if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
434 ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
436 for (auto &GV : *MergedModule)
438 for (auto &GV : MergedModule->globals())
440 for (auto &GV : MergedModule->aliases())
444 // Update the llvm.compiler_used globals to force preserving libcalls and
445 // symbols referenced from asm
446 updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
448 internalizeModule(*MergedModule, mustPreserveGV);
450 ScopeRestrictionsDone = true;
453 /// Restore original linkage for symbols that may have been internalized
454 void LTOCodeGenerator::restoreLinkageForExternals() {
455 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
458 assert(ScopeRestrictionsDone &&
459 "Cannot externalize without internalization!");
461 if (ExternalSymbols.empty())
464 auto externalize = [this](GlobalValue &GV) {
465 if (!GV.hasLocalLinkage() || !GV.hasName())
468 auto I = ExternalSymbols.find(GV.getName());
469 if (I == ExternalSymbols.end())
472 GV.setLinkage(I->second);
\r
475 llvm::for_each(MergedModule->functions(), externalize);
\r
476 llvm::for_each(MergedModule->globals(), externalize);
\r
477 llvm::for_each(MergedModule->aliases(), externalize);
\r
480 void LTOCodeGenerator::verifyMergedModuleOnce() {
\r
481 // Only run on the first call.
482 if (HasVerifiedInput)
484 HasVerifiedInput = true;
486 bool BrokenDebugInfo = false;
487 if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
488 report_fatal_error("Broken module found, compilation aborted!");
489 if (BrokenDebugInfo) {
490 emitWarning("Invalid debug info found, debug info will be stripped");
491 StripDebugInfo(*MergedModule);
495 void LTOCodeGenerator::finishOptimizationRemarks() {
496 if (DiagnosticOutputFile) {
497 DiagnosticOutputFile->keep();
498 // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
499 DiagnosticOutputFile->os().flush();
503 /// Optimize merged modules using various IPO passes
504 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
505 bool DisableGVNLoadPRE,
506 bool DisableVectorization) {
507 if (!this->determineTarget())
510 auto DiagFileOrErr = lto::setupOptimizationRemarks(
511 Context, LTORemarksFilename, LTOPassRemarksWithHotness);
512 if (!DiagFileOrErr) {
513 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
514 report_fatal_error("Can't get an output file for the remarks");
516 DiagnosticOutputFile = std::move(*DiagFileOrErr);
518 // We always run the verifier once on the merged module, the `DisableVerify`
519 // parameter only applies to subsequent verify.
520 verifyMergedModuleOnce();
522 // Mark which symbols can not be internalized
523 this->applyScopeRestrictions();
525 // Instantiate the pass manager to organize the passes.
526 legacy::PassManager passes;
528 // Add an appropriate DataLayout instance for this module...
529 MergedModule->setDataLayout(TargetMach->createDataLayout());
532 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
534 Triple TargetTriple(TargetMach->getTargetTriple());
535 PassManagerBuilder PMB;
536 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
537 PMB.LoopVectorize = !DisableVectorization;
538 PMB.SLPVectorize = !DisableVectorization;
540 PMB.Inliner = createFunctionInliningPass();
541 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
543 PMB.LibraryInfo->disableAllFunctions();
544 PMB.OptLevel = OptLevel;
545 PMB.VerifyInput = !DisableVerify;
546 PMB.VerifyOutput = !DisableVerify;
548 PMB.populateLTOPassManager(passes);
550 // Run our queue of passes all at once now, efficiently.
551 passes.run(*MergedModule);
556 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
557 if (!this->determineTarget())
560 // We always run the verifier once on the merged module. If it has already
561 // been called in optimize(), this call will return early.
562 verifyMergedModuleOnce();
564 legacy::PassManager preCodeGenPasses;
566 // If the bitcode files contain ARC code and were compiled with optimization,
567 // the ObjCARCContractPass must be run, so do it unconditionally here.
568 preCodeGenPasses.add(createObjCARCContractPass());
569 preCodeGenPasses.run(*MergedModule);
571 // Re-externalize globals that may have been internalized to increase scope
573 restoreLinkageForExternals();
575 // Do code generation. We need to preserve the module in case the client calls
576 // writeMergedModules() after compilation, but we only need to allow this at
577 // parallelism level 1. This is achieved by having splitCodeGen return the
578 // original module at parallelism level 1 which we then assign back to
580 MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
581 [&]() { return createTargetMachine(); }, FileType,
582 ShouldRestoreGlobalsLinkage);
584 // If statistics were requested, print them out after codegen.
585 if (llvm::AreStatisticsEnabled())
586 llvm::PrintStatistics();
587 reportAndResetTimings();
589 finishOptimizationRemarks();
594 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
596 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
597 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
598 o = getToken(o.second))
599 CodegenOptions.push_back(o.first);
602 void LTOCodeGenerator::parseCodeGenDebugOptions() {
603 // if options were requested, set them
604 if (!CodegenOptions.empty()) {
605 // ParseCommandLineOptions() expects argv[0] to be program name.
606 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
607 for (std::string &Arg : CodegenOptions)
608 CodegenArgv.push_back(Arg.c_str());
609 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
614 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
615 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
616 lto_codegen_diagnostic_severity_t Severity;
617 switch (DI.getSeverity()) {
619 Severity = LTO_DS_ERROR;
622 Severity = LTO_DS_WARNING;
625 Severity = LTO_DS_REMARK;
628 Severity = LTO_DS_NOTE;
631 // Create the string that will be reported to the external diagnostic handler.
632 std::string MsgStorage;
633 raw_string_ostream Stream(MsgStorage);
634 DiagnosticPrinterRawOStream DP(Stream);
638 // If this method has been called it means someone has set up an external
639 // diagnostic handler. Assert on that.
640 assert(DiagHandler && "Invalid diagnostic handler");
641 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
645 struct LTODiagnosticHandler : public DiagnosticHandler {
646 LTOCodeGenerator *CodeGenerator;
647 LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
648 : CodeGenerator(CodeGenPtr) {}
649 bool handleDiagnostics(const DiagnosticInfo &DI) override {
650 CodeGenerator->DiagnosticHandler(DI);
657 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
659 this->DiagHandler = DiagHandler;
660 this->DiagContext = Ctxt;
662 return Context.setDiagnosticHandler(nullptr);
663 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
664 // diagnostic to the external DiagHandler.
665 Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
670 class LTODiagnosticInfo : public DiagnosticInfo {
673 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
674 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
675 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
679 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
681 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
683 Context.diagnose(LTODiagnosticInfo(ErrMsg));
686 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
688 (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
690 Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));