LLVM  16.0.0git
LTOBackend.cpp
Go to the documentation of this file.
1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the "backend" phase of LTO, i.e. it performs
10 // optimization and code generation on a loaded module. It is generally used
11 // internally by the LTO class but can also be used independently, for example
12 // to implement a standalone ThinLTO backend.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/LTO/LTOBackend.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/IR/Verifier.h"
27 #include "llvm/LTO/LTO.h"
29 #include "llvm/MC/TargetRegistry.h"
32 #include "llvm/Passes/PassPlugin.h"
34 #include "llvm/Support/Error.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Program.h"
47 
48 using namespace llvm;
49 using namespace lto;
50 
51 #define DEBUG_TYPE "lto-backend"
52 
53 enum class LTOBitcodeEmbedding {
54  DoNotEmbed = 0,
55  EmbedOptimized = 1,
57 };
58 
60  "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed),
62  "Do not embed"),
64  "Embed after all optimization passes"),
66  "post-merge-pre-opt",
67  "Embed post merge, but before optimizations")),
68  cl::desc("Embed LLVM bitcode in object files produced by LTO"));
69 
71  "thinlto-assume-merged", cl::init(false),
72  cl::desc("Assume the input has already undergone ThinLTO function "
73  "importing and the other pre-optimization pipeline changes."));
74 
75 namespace llvm {
77 }
78 
79 [[noreturn]] static void reportOpenError(StringRef Path, Twine Msg) {
80  errs() << "failed to open " << Path << ": " << Msg << '\n';
81  errs().flush();
82  exit(1);
83 }
84 
85 Error Config::addSaveTemps(std::string OutputFileName, bool UseInputModulePath,
86  const DenseSet<StringRef> &SaveTempsArgs) {
88 
89  std::error_code EC;
90  if (SaveTempsArgs.empty() || SaveTempsArgs.contains("resolution")) {
92  std::make_unique<raw_fd_ostream>(OutputFileName + "resolution.txt", EC,
94  if (EC) {
95  ResolutionFile.reset();
96  return errorCodeToError(EC);
97  }
98  }
99 
100  auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
101  // Keep track of the hook provided by the linker, which also needs to run.
102  ModuleHookFn LinkerHook = Hook;
103  Hook = [=](unsigned Task, const Module &M) {
104  // If the linker's hook returned false, we need to pass that result
105  // through.
106  if (LinkerHook && !LinkerHook(Task, M))
107  return false;
108 
109  std::string PathPrefix;
110  // If this is the combined module (not a ThinLTO backend compile) or the
111  // user hasn't requested using the input module's path, emit to a file
112  // named from the provided OutputFileName with the Task ID appended.
113  if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
114  PathPrefix = OutputFileName;
115  if (Task != (unsigned)-1)
116  PathPrefix += utostr(Task) + ".";
117  } else
118  PathPrefix = M.getModuleIdentifier() + ".";
119  std::string Path = PathPrefix + PathSuffix + ".bc";
120  std::error_code EC;
122  // Because -save-temps is a debugging feature, we report the error
123  // directly and exit.
124  if (EC)
125  reportOpenError(Path, EC.message());
126  WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
127  return true;
128  };
129  };
130 
131  auto SaveCombinedIndex =
132  [=](const ModuleSummaryIndex &Index,
133  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
134  std::string Path = OutputFileName + "index.bc";
135  std::error_code EC;
137  // Because -save-temps is a debugging feature, we report the error
138  // directly and exit.
139  if (EC)
140  reportOpenError(Path, EC.message());
141  writeIndexToFile(Index, OS);
142 
143  Path = OutputFileName + "index.dot";
145  if (EC)
146  reportOpenError(Path, EC.message());
147  Index.exportToDot(OSDot, GUIDPreservedSymbols);
148  return true;
149  };
150 
151  if (SaveTempsArgs.empty()) {
152  setHook("0.preopt", PreOptModuleHook);
153  setHook("1.promote", PostPromoteModuleHook);
154  setHook("2.internalize", PostInternalizeModuleHook);
155  setHook("3.import", PostImportModuleHook);
156  setHook("4.opt", PostOptModuleHook);
157  setHook("5.precodegen", PreCodeGenModuleHook);
158  CombinedIndexHook = SaveCombinedIndex;
159  } else {
160  if (SaveTempsArgs.contains("preopt"))
161  setHook("0.preopt", PreOptModuleHook);
162  if (SaveTempsArgs.contains("promote"))
163  setHook("1.promote", PostPromoteModuleHook);
164  if (SaveTempsArgs.contains("internalize"))
165  setHook("2.internalize", PostInternalizeModuleHook);
166  if (SaveTempsArgs.contains("import"))
167  setHook("3.import", PostImportModuleHook);
168  if (SaveTempsArgs.contains("opt"))
169  setHook("4.opt", PostOptModuleHook);
170  if (SaveTempsArgs.contains("precodegen"))
171  setHook("5.precodegen", PreCodeGenModuleHook);
172  if (SaveTempsArgs.contains("combinedindex"))
173  CombinedIndexHook = SaveCombinedIndex;
174  }
175 
176  return Error::success();
177 }
178 
179 #define HANDLE_EXTENSION(Ext) \
180  llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
181 #include "llvm/Support/Extension.def"
182 
184  PassBuilder &PB) {
185 #define HANDLE_EXTENSION(Ext) \
186  get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
187 #include "llvm/Support/Extension.def"
188 
189  // Load requested pass plugins and let them register pass builder callbacks
190  for (auto &PluginFN : PassPlugins) {
191  auto PassPlugin = PassPlugin::Load(PluginFN);
192  if (!PassPlugin) {
193  errs() << "Failed to load passes from '" << PluginFN
194  << "'. Request ignored.\n";
195  continue;
196  }
197 
199  }
200 }
201 
202 static std::unique_ptr<TargetMachine>
203 createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
204  StringRef TheTriple = M.getTargetTriple();
205  SubtargetFeatures Features;
206  Features.getDefaultSubtargetFeatures(Triple(TheTriple));
207  for (const std::string &A : Conf.MAttrs)
208  Features.AddFeature(A);
209 
210  Optional<Reloc::Model> RelocModel;
211  if (Conf.RelocModel)
212  RelocModel = *Conf.RelocModel;
213  else if (M.getModuleFlag("PIC Level"))
214  RelocModel =
215  M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
216 
218  if (Conf.CodeModel)
219  CodeModel = *Conf.CodeModel;
220  else
221  CodeModel = M.getCodeModel();
222 
223  std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
224  TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
225  CodeModel, Conf.CGOptLevel));
226  assert(TM && "Failed to create target machine");
227  return TM;
228 }
229 
230 static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
231  unsigned OptLevel, bool IsThinLTO,
232  ModuleSummaryIndex *ExportSummary,
233  const ModuleSummaryIndex *ImportSummary) {
234  Optional<PGOOptions> PGOOpt;
235  if (!Conf.SampleProfile.empty())
236  PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
238  else if (Conf.RunCSIRInstr) {
239  PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
241  Conf.AddFSDiscriminator);
242  } else if (!Conf.CSIRProfile.empty()) {
243  PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
245  Conf.AddFSDiscriminator);
247  } else if (Conf.AddFSDiscriminator) {
248  PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
249  PGOOptions::NoCSAction, true);
250  }
251  TM->setPGOOption(PGOOpt);
252 
257 
260  SI.registerCallbacks(PIC, &FAM);
261  PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
262 
264 
265  std::unique_ptr<TargetLibraryInfoImpl> TLII(
266  new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
267  if (Conf.Freestanding)
268  TLII->disableAllFunctions();
269  FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
270 
271  // Parse a custom AA pipeline if asked to.
272  if (!Conf.AAPipeline.empty()) {
273  AAManager AA;
274  if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
275  report_fatal_error(Twine("unable to parse AA pipeline description '") +
276  Conf.AAPipeline + "': " + toString(std::move(Err)));
277  }
278  // Register the AA manager first so that our version is the one used.
279  FAM.registerPass([&] { return std::move(AA); });
280  }
281 
282  // Register all the basic analyses with the managers.
288 
290 
291  if (!Conf.DisableVerify)
293 
295 
296  switch (OptLevel) {
297  default:
298  llvm_unreachable("Invalid optimization level");
299  case 0:
301  break;
302  case 1:
304  break;
305  case 2:
307  break;
308  case 3:
310  break;
311  }
312 
313  // Parse a custom pipeline if asked to.
314  if (!Conf.OptPipeline.empty()) {
315  if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
316  report_fatal_error(Twine("unable to parse pass pipeline description '") +
317  Conf.OptPipeline + "': " + toString(std::move(Err)));
318  }
319  } else if (Conf.UseDefaultPipeline) {
321  } else if (IsThinLTO) {
322  MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
323  } else {
324  MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
325  }
326 
327  if (!Conf.DisableVerify)
329 
330  MPM.run(Mod, MAM);
331 }
332 
333 bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
334  bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
335  const ModuleSummaryIndex *ImportSummary,
336  const std::vector<uint8_t> &CmdArgs) {
338  // FIXME: the motivation for capturing post-merge bitcode and command line
339  // is replicating the compilation environment from bitcode, without needing
340  // to understand the dependencies (the functions to be imported). This
341  // assumes a clang - based invocation, case in which we have the command
342  // line.
343  // It's not very clear how the above motivation would map in the
344  // linker-based case, so we currently don't plumb the command line args in
345  // that case.
346  if (CmdArgs.empty())
347  LLVM_DEBUG(
348  dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
349  "command line arguments are not available");
351  /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
352  /*Cmdline*/ CmdArgs);
353  }
354  // FIXME: Plumb the combined index into the new pass manager.
355  runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
356  ImportSummary);
357  return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
358 }
359 
360 static void codegen(const Config &Conf, TargetMachine *TM,
361  AddStreamFn AddStream, unsigned Task, Module &Mod,
362  const ModuleSummaryIndex &CombinedIndex) {
363  if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
364  return;
365 
368  /*EmbedBitcode*/ true,
369  /*EmbedCmdline*/ false,
370  /*CmdArgs*/ std::vector<uint8_t>());
371 
372  std::unique_ptr<ToolOutputFile> DwoOut;
373  SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
374  if (!Conf.DwoDir.empty()) {
375  std::error_code EC;
376  if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
377  report_fatal_error(Twine("Failed to create directory ") + Conf.DwoDir +
378  ": " + EC.message());
379 
380  DwoFile = Conf.DwoDir;
381  sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
382  TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
383  } else
384  TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
385 
386  if (!DwoFile.empty()) {
387  std::error_code EC;
388  DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
389  if (EC)
390  report_fatal_error(Twine("Failed to open ") + DwoFile + ": " +
391  EC.message());
392  }
393 
395  AddStream(Task, Mod.getModuleIdentifier());
396  if (Error Err = StreamOrErr.takeError())
398  std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
399  TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
400 
401  legacy::PassManager CodeGenPasses;
403  CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
404  CodeGenPasses.add(
406  if (Conf.PreCodeGenPassesHook)
407  Conf.PreCodeGenPassesHook(CodeGenPasses);
408  if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
409  DwoOut ? &DwoOut->os() : nullptr,
410  Conf.CGFileType))
411  report_fatal_error("Failed to setup codegen");
412  CodeGenPasses.run(Mod);
413 
414  if (DwoOut)
415  DwoOut->keep();
416 }
417 
418 static void splitCodeGen(const Config &C, TargetMachine *TM,
419  AddStreamFn AddStream,
420  unsigned ParallelCodeGenParallelismLevel, Module &Mod,
421  const ModuleSummaryIndex &CombinedIndex) {
422  ThreadPool CodegenThreadPool(
423  heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
424  unsigned ThreadCount = 0;
425  const Target *T = &TM->getTarget();
426 
427  SplitModule(
428  Mod, ParallelCodeGenParallelismLevel,
429  [&](std::unique_ptr<Module> MPart) {
430  // We want to clone the module in a new context to multi-thread the
431  // codegen. We do it by serializing partition modules to bitcode
432  // (while still on the main thread, in order to avoid data races) and
433  // spinning up new threads which deserialize the partitions into
434  // separate contexts.
435  // FIXME: Provide a more direct way to do this in LLVM.
436  SmallString<0> BC;
437  raw_svector_ostream BCOS(BC);
438  WriteBitcodeToFile(*MPart, BCOS);
439 
440  // Enqueue the task
441  CodegenThreadPool.async(
442  [&](const SmallString<0> &BC, unsigned ThreadId) {
443  LTOLLVMContext Ctx(C);
445  MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
446  Ctx);
447  if (!MOrErr)
448  report_fatal_error("Failed to read bitcode");
449  std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
450 
451  std::unique_ptr<TargetMachine> TM =
452  createTargetMachine(C, T, *MPartInCtx);
453 
454  codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
455  CombinedIndex);
456  },
457  // Pass BC using std::move to ensure that it get moved rather than
458  // copied into the thread's context.
459  std::move(BC), ThreadCount++);
460  },
461  false);
462 
463  // Because the inner lambda (which runs in a worker thread) captures our local
464  // variables, we need to wait for the worker threads to terminate before we
465  // can leave the function scope.
466  CodegenThreadPool.wait();
467 }
468 
470  Module &Mod) {
471  if (!C.OverrideTriple.empty())
472  Mod.setTargetTriple(C.OverrideTriple);
473  else if (Mod.getTargetTriple().empty())
474  Mod.setTargetTriple(C.DefaultTriple);
475 
476  std::string Msg;
478  if (!T)
479  return make_error<StringError>(Msg, inconvertibleErrorCode());
480  return T;
481 }
482 
484  std::unique_ptr<ToolOutputFile> DiagOutputFile) {
485  // Make sure we flush the diagnostic remarks file in case the linker doesn't
486  // call the global destructors before exiting.
487  if (!DiagOutputFile)
488  return Error::success();
489  DiagOutputFile->keep();
490  DiagOutputFile->os().flush();
491  return Error::success();
492 }
493 
495  unsigned ParallelCodeGenParallelismLevel, Module &Mod,
496  ModuleSummaryIndex &CombinedIndex) {
498  if (!TOrErr)
499  return TOrErr.takeError();
500 
501  std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
502 
503  if (!C.CodeGenOnly) {
504  if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
505  /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
506  /*CmdArgs*/ std::vector<uint8_t>()))
507  return Error::success();
508  }
509 
510  if (ParallelCodeGenParallelismLevel == 1) {
511  codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
512  } else {
513  splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
514  CombinedIndex);
515  }
516  return Error::success();
517 }
518 
519 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
520  const ModuleSummaryIndex &Index) {
521  std::vector<GlobalValue*> DeadGVs;
522  for (auto &GV : Mod.global_values())
523  if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
524  if (!Index.isGlobalValueLive(GVS)) {
525  DeadGVs.push_back(&GV);
527  }
528 
529  // Now that all dead bodies have been dropped, delete the actual objects
530  // themselves when possible.
531  for (GlobalValue *GV : DeadGVs) {
532  GV->removeDeadConstantUsers();
533  // Might reference something defined in native object (i.e. dropped a
534  // non-prevailing IR def, but we need to keep the declaration).
535  if (GV->use_empty())
536  GV->eraseFromParent();
537  }
538 }
539 
540 Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
541  Module &Mod, const ModuleSummaryIndex &CombinedIndex,
542  const FunctionImporter::ImportMapTy &ImportList,
543  const GVSummaryMapTy &DefinedGlobals,
545  const std::vector<uint8_t> &CmdArgs) {
547  if (!TOrErr)
548  return TOrErr.takeError();
549 
550  std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
551 
552  // Setup optimization remarks.
553  auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
556  Task);
557  if (!DiagFileOrErr)
558  return DiagFileOrErr.takeError();
559  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
560 
561  // Set the partial sample profile ratio in the profile summary module flag of
562  // the module, if applicable.
563  Mod.setPartialSampleProfileRatio(CombinedIndex);
564 
566 
567  if (Conf.CodeGenOnly) {
568  codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
569  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
570  }
571 
572  if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
573  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
574 
575  auto OptimizeAndCodegen =
576  [&](Module &Mod, TargetMachine *TM,
577  std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) {
578  if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
579  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
580  CmdArgs))
581  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
582 
583  codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
584  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
585  };
586 
588  return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
589 
590  // When linking an ELF shared object, dso_local should be dropped. We
591  // conservatively do this for -fpic.
592  bool ClearDSOLocalOnDeclarations =
593  TM->getTargetTriple().isOSBinFormatELF() &&
594  TM->getRelocationModel() != Reloc::Static &&
596  renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
597 
598  dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
599 
600  thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true);
601 
602  if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
603  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
604 
605  if (!DefinedGlobals.empty())
606  thinLTOInternalizeModule(Mod, DefinedGlobals);
607 
608  if (Conf.PostInternalizeModuleHook &&
609  !Conf.PostInternalizeModuleHook(Task, Mod))
610  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
611 
612  auto ModuleLoader = [&](StringRef Identifier) {
614  "ODR Type uniquing should be enabled on the context");
615  if (ModuleMap) {
616  auto I = ModuleMap->find(Identifier);
617  assert(I != ModuleMap->end());
618  return I->second.getLazyModule(Mod.getContext(),
619  /*ShouldLazyLoadMetadata=*/true,
620  /*IsImporting*/ true);
621  }
622 
624  llvm::MemoryBuffer::getFile(Identifier);
625  if (!MBOrErr)
626  return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
627  Twine("Error loading imported file ") + Identifier + " : ",
628  MBOrErr.getError()));
629 
630  Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
631  if (!BMOrErr)
632  return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
633  Twine("Error loading imported file ") + Identifier + " : " +
634  toString(BMOrErr.takeError()),
636 
638  BMOrErr->getLazyModule(Mod.getContext(),
639  /*ShouldLazyLoadMetadata=*/true,
640  /*IsImporting*/ true);
641  if (MOrErr)
642  (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));
643  return MOrErr;
644  };
645 
646  FunctionImporter Importer(CombinedIndex, ModuleLoader,
647  ClearDSOLocalOnDeclarations);
648  if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
649  return Err;
650 
651  if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
652  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
653 
654  return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
655 }
656 
658  if (ThinLTOAssumeMerged && BMs.size() == 1)
659  return BMs.begin();
660 
661  for (BitcodeModule &BM : BMs) {
662  Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
663  if (LTOInfo && LTOInfo->IsThinLTO)
664  return &BM;
665  }
666  return nullptr;
667 }
668 
671  if (!BMsOrErr)
672  return BMsOrErr.takeError();
673 
674  // The bitcode file may contain multiple modules, we want the one that is
675  // marked as being the ThinLTO module.
676  if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
677  return *Bm;
678 
679  return make_error<StringError>("Could not find module summary",
681 }
682 
684  const ModuleSummaryIndex &CombinedIndex,
685  FunctionImporter::ImportMapTy &ImportList) {
687  return true;
688  // We can simply import the values mentioned in the combined index, since
689  // we should only invoke this using the individual indexes written out
690  // via a WriteIndexesThinBackend.
691  for (const auto &GlobalList : CombinedIndex) {
692  // Ignore entries for undefined references.
693  if (GlobalList.second.SummaryList.empty())
694  continue;
695 
696  auto GUID = GlobalList.first;
697  for (const auto &Summary : GlobalList.second.SummaryList) {
698  // Skip the summaries for the importing module. These are included to
699  // e.g. record required linkage changes.
700  if (Summary->modulePath() == M.getModuleIdentifier())
701  continue;
702  // Add an entry to provoke importing by thinBackend.
703  ImportList[Summary->modulePath()].insert(GUID);
704  }
705  }
706  return true;
707 }
llvm::Module::global_values
iterator_range< global_value_iterator > global_values()
Definition: Module.cpp:421
MemoryBuffer.h
llvm::AAManager
A manager for alias analyses.
Definition: AliasAnalysis.h:876
FunctionImportUtils.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::lto::Config::UseDefaultPipeline
bool UseDefaultPipeline
Use the standard optimization pipeline.
Definition: Config.h:62
PassBuilder.h
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::lto::initImportList
bool initImportList(const Module &M, const ModuleSummaryIndex &CombinedIndex, FunctionImporter::ImportMapTy &ImportList)
Distributed ThinLTO: collect the referenced modules based on module summary and initialize ImportList...
Definition: LTOBackend.cpp:683
llvm::OptimizationLevel::O1
static const OptimizationLevel O1
Optimize quickly without destroying debuggability.
Definition: OptimizationLevel.h:57
llvm::thinLTOInternalizeModule
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
Definition: FunctionImport.cpp:1179
FileSystem.h
llvm::sys::fs::OF_None
@ OF_None
Definition: FileSystem.h:757
LTOBitcodeEmbedding::EmbedOptimized
@ EmbedOptimized
LTOBitcodeEmbedding
LTOBitcodeEmbedding
Definition: LTOBackend.cpp:53
llvm::lto::Config::DisableVerify
bool DisableVerify
Definition: Config.h:59
llvm::lto::finalizeOptimizationRemarks
Error finalizeOptimizationRemarks(std::unique_ptr< ToolOutputFile > DiagOutputFile)
Definition: LTOBackend.cpp:483
llvm::ThreadPool
A ThreadPool for asynchronous parallel execution on a defined number of threads.
Definition: ThreadPool.h:52
llvm::lto::Config::CGOptLevel
CodeGenOpt::Level CGOptLevel
Definition: Config.h:56
llvm::DenseMapBase::lookup
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:197
llvm::PassManager::addPass
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same< PassT, PassManager >::value > addPass(PassT &&Pass)
Definition: PassManager.h:544
llvm::renameModuleForThinLTO
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
Definition: FunctionImportUtils.cpp:355
llvm::OptimizationLevel::O2
static const OptimizationLevel O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
Definition: OptimizationLevel.h:74
llvm::PassPlugin
A loaded pass plugin.
Definition: PassPlugin.h:60
llvm::lto::Config::RemarksFormat
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition: Config.h:158
llvm::lto::Config::CodeModel
Optional< CodeModel::Model > CodeModel
Definition: Config.h:55
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:149
RegisterPassPlugins
static void RegisterPassPlugins(ArrayRef< std::string > PassPlugins, PassBuilder &PB)
Definition: LTOBackend.cpp:183
llvm::SubtargetFeatures::AddFeature
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
Definition: SubtargetFeature.cpp:37
llvm::lto::Config::RemarksWithHotness
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition: Config.h:140
Path.h
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:329
Error.h
llvm::VerifierPass
Create a verifier pass.
Definition: Verifier.h:137
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
FAM
FunctionAnalysisManager FAM
Definition: PassBuilderBindings.cpp:59
llvm::heavyweight_hardware_concurrency
ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)
Returns a thread strategy for tasks requiring significant memory or other resources.
Definition: Threading.h:161
PIC
PassInstrumentationCallbacks PIC
Definition: PassBuilderBindings.cpp:55
llvm::createImmutableModuleSummaryIndexWrapperPass
ImmutablePass * createImmutableModuleSummaryIndexWrapperPass(const ModuleSummaryIndex *Index)
Definition: ModuleSummaryAnalysis.cpp:1029
llvm::lto::Config
LTO configuration.
Definition: Config.h:40
llvm::Optional< Reloc::Model >
llvm::lto::Config::Freestanding
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition: Config.h:66
T
#define T
Definition: Mips16ISelLowering.cpp:341
llvm::TargetLibraryInfoImpl
Implementation of the target library information.
Definition: TargetLibraryInfo.h:49
llvm::MapVector< StringRef, BitcodeModule >
llvm::errs
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Definition: raw_ostream.cpp:891
llvm::FunctionImporter
The function importer is automatically importing function from other modules based on the provided su...
Definition: FunctionImport.h:33
llvm::lto::setupLLVMOptimizationRemarks
Expected< std::unique_ptr< ToolOutputFile > > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, Optional< uint64_t > RemarksHotnessThreshold=0, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1646
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
llvm::lto::Config::ShouldDiscardValueNames
bool ShouldDiscardValueNames
Definition: Config.h:175
ModuleSummaryAnalysis.h
llvm::lto::Config::PostImportModuleHook
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition: Config.h:232
llvm::lto::Config::CodeGenOnly
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Definition: Config.h:69
llvm::PGOOptions::SampleUse
@ SampleUse
Definition: PGOOptions.h:23
llvm::OptimizationLevel::O0
static const OptimizationLevel O0
Disable as many optimizations as possible.
Definition: OptimizationLevel.h:41
llvm::TargetRegistry::lookupTarget
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Definition: TargetRegistry.cpp:62
LegacyPassManager.h
runNewPMPasses
static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM, unsigned OptLevel, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)
Definition: LTOBackend.cpp:230
llvm::lto::findThinLTOModule
BitcodeModule * findThinLTOModule(MutableArrayRef< BitcodeModule > BMs)
Returns the BitcodeModule that is ThinLTO.
Definition: LTOBackend.cpp:657
llvm::MemoryBufferRef
Definition: MemoryBufferRef.h:22
llvm::lto::Config::CombinedIndexHook
CombinedIndexHookFn CombinedIndexHook
Definition: Config.h:254
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
llvm::MemoryBuffer::getFile
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, Optional< Align > Alignment=None)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: MemoryBuffer.cpp:244
initAndLookupTarget
static Expected< const Target * > initAndLookupTarget(const Config &C, Module &Mod)
Definition: LTOBackend.cpp:469
AliasAnalysis.h
llvm::sys::path::append
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:456
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::PassBuilder::parsePassPipeline
Error parsePassPipeline(ModulePassManager &MPM, StringRef PipelineText)
Parse a textual pass pipeline description into a ModulePassManager.
Definition: PassBuilder.cpp:1650
llvm::lto::Config::SplitDwarfFile
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
Definition: Config.h:126
llvm::FunctionImporter::importFunctions
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
Definition: FunctionImport.cpp:1254
llvm::PassPlugin::Load
static Expected< PassPlugin > Load(const std::string &Filename)
Attempts to load a pass plugin from a given file.
Definition: PassPlugin.cpp:16
llvm::lto::Config::RunCSIRInstr
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition: Config.h:72
llvm::GlobalValueSummary
Function and variable summary information to aid decisions and implementation of importing.
Definition: ModuleSummaryIndex.h:363
llvm::lto::Config::PostPromoteModuleHook
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
Definition: Config.h:226
SubtargetFeature.h
llvm::MSP430Attrs::CodeModel
CodeModel
Definition: MSP430Attributes.h:37
TargetMachine.h
llvm::MutableArrayRef
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:28
llvm::lto::opt
bool opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary, const std::vector< uint8_t > &CmdArgs)
Runs middle-end LTO optimizations on Mod.
Definition: LTOBackend.cpp:333
llvm::lto::Config::SampleProfile
std::string SampleProfile
Sample PGO profile path.
Definition: Config.h:114
BitcodeWriter.h
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::StringMap::insert
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:275
llvm::errorCodeToError
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:92
MAM
ModuleAnalysisManager MAM
Definition: PassBuilderBindings.cpp:61
llvm::lto::Config::Options
TargetOptions Options
Definition: Config.h:48
llvm::PassBuilder
This class provides access to building LLVM's passes.
Definition: PassBuilder.h:97
SI
@ SI
Definition: SIInstrInfo.cpp:7882
llvm::lto::Config::PreCodeGenPassesHook
std::function< void(legacy::PassManager &)> PreCodeGenPassesHook
For adding passes that run right before codegen.
Definition: Config.h:53
llvm::SubtargetFeatures
Manages the enabling and disabling of subtarget specific features.
Definition: SubtargetFeature.h:180
llvm::PGOOptions::IRUse
@ IRUse
Definition: PGOOptions.h:23
TargetLibraryInfo.h
SplitModule.h
llvm::ErrorOr::getError
std::error_code getError() const
Definition: ErrorOr.h:153
llvm::dwarf::Index
Index
Definition: Dwarf.h:472
llvm::LLVMContext::isODRUniquingDebugTypes
bool isODRUniquingDebugTypes() const
Whether there is a string map for uniquing debug info identifiers across the context.
Definition: LLVMContext.cpp:340
llvm::sys::fs::create_directories
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition: Path.cpp:967
llvm::lto::Config::ResolutionFile
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
Definition: Config.h:189
llvm::thinLTOFinalizeInModule
void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
Definition: FunctionImport.cpp:1051
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:145
LTOBitcodeEmbedding::DoNotEmbed
@ DoNotEmbed
llvm::raw_ostream::flush
void flush()
Definition: raw_ostream.h:185
llvm::PGOOptions::CSIRInstr
@ CSIRInstr
Definition: PGOOptions.h:24
llvm::lto::Config::ModuleHookFn
std::function< bool(unsigned Task, const Module &)> ModuleHookFn
The following callbacks deal with tasks, which normally represent the entire optimization and code ge...
Definition: Config.h:218
llvm::lto::Config::DebugPassManager
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition: Config.h:161
llvm::SubtargetFeatures::getDefaultSubtargetFeatures
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
Definition: SubtargetFeature.cpp:66
llvm::Module::setTargetTriple
void setTargetTriple(StringRef T)
Set the target triple.
Definition: Module.h:301
llvm::lto::Config::PostInternalizeModuleHook
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition: Config.h:229
llvm::StringMap
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:110
llvm::SmallString
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
llvm::sys::fs::OF_TextWithCRLF
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition: FileSystem.h:770
LTOBackend.h
llvm::lto::Config::PreCodeGenModuleHook
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition: Config.h:240
llvm::lto::Config::OptLevel
unsigned OptLevel
Definition: Config.h:58
llvm::convertToDeclaration
bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
Definition: FunctionImport.cpp:1016
llvm::PGOOptions::NoCSAction
@ NoCSAction
Definition: PGOOptions.h:24
PB
PassBuilder PB(Machine, PassOpts->PTO, None, &PIC)
llvm::PassPlugin::registerPassBuilderCallbacks
void registerPassBuilderCallbacks(PassBuilder &PB) const
Invoke the PassBuilder callback registration.
Definition: PassPlugin.h:82
llvm::SubtargetFeatures::getString
std::string getString() const
Returns features as a string.
Definition: SubtargetFeature.cpp:50
llvm::DenseSet
Implements a dense probed hash-table based set.
Definition: DenseSet.h:268
ThreadPool.h
llvm::lto::Config::RemarksFilename
std::string RemarksFilename
Optimization remarks file path.
Definition: Config.h:134
llvm::cl::opt
Definition: CommandLine.h:1412
llvm::lto::backend
Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
Definition: LTOBackend.cpp:494
llvm::GlobalValue
Definition: GlobalValue.h:44
llvm::PassBuilder::registerFunctionAnalyses
void registerFunctionAnalyses(FunctionAnalysisManager &FAM)
Registers all available function analysis passes.
Definition: PassBuilder.cpp:451
llvm::cl::values
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:705
llvm::StandardInstrumentations
This class provides an interface to register all the standard pass instrumentations and manages their...
Definition: StandardInstrumentations.h:526
llvm::MapVector::find
iterator find(const KeyT &Key)
Definition: MapVector.h:148
Index
uint32_t Index
Definition: ELFObjHandler.cpp:82
llvm::TargetLibraryInfoWrapperPass
Definition: TargetLibraryInfo.h:474
llvm::parseBitcodeFile
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, DataLayoutCallbackTy DataLayoutCallback=[](StringRef) { return None;})
Read the specified bitcode file, returning the module.
Definition: BitcodeReader.cpp:8090
llvm::lto::Config::DwoDir
std::string DwoDir
The directory to store .dwo files.
Definition: Config.h:120
llvm::lto::Config::AddFSDiscriminator
bool AddFSDiscriminator
Add FSAFDO discriminators.
Definition: Config.h:179
llvm::PassBuilder::registerModuleAnalyses
void registerModuleAnalyses(ModuleAnalysisManager &MAM)
Registers all available module analysis passes.
Definition: PassBuilder.cpp:433
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::DenseMap
Definition: DenseMap.h:714
CGSCCPassManager.h
llvm::PassBuilder::buildLTODefaultPipeline
ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
Definition: PassBuilderPipelines.cpp:1564
llvm::lto::LTOLLVMContext
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition: Config.h:293
I
#define I(x, y, z)
Definition: MD5.cpp:58
llvm::PICLevel::NotPIC
@ NotPIC
Definition: CodeGen.h:33
llvm::detail::DenseSetImpl< ValueT, DenseMap< ValueT, detail::DenseSetEmpty, DenseMapInfo< ValueT >, detail::DenseSetPair< ValueT > >, DenseMapInfo< ValueT > >::empty
bool empty() const
Definition: DenseSet.h:80
llvm::PassBuilder::buildThinLTODefaultPipeline
ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary)
Build an ThinLTO default optimization pipeline to a pass manager.
Definition: PassBuilderPipelines.cpp:1498
createTargetMachine
static std::unique_ptr< TargetMachine > createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M)
Definition: LTOBackend.cpp:203
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:447
ToolOutputFile.h
llvm::AddStreamFn
std::function< Expected< std::unique_ptr< CachedFileStream > >(unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition: Caching.h:42
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::TargetMachine
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
llvm::lto::Config::SplitDwarfOutput
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition: Config.h:131
llvm::Module::getModuleIdentifier
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:228
llvm::lto::Config::MAttrs
std::vector< std::string > MAttrs
Definition: Config.h:49
llvm::MutableArrayRef::begin
iterator begin() const
Definition: ArrayRef.h:355
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
llvm::DenseMapBase::empty
bool empty() const
Definition: DenseMap.h:98
LoopPassManager.h
llvm::lto::Config::ProfileRemapping
std::string ProfileRemapping
Name remapping file for profile data.
Definition: Config.h:117
llvm::PGOOptions::NoAction
@ NoAction
Definition: PGOOptions.h:23
llvm::WriteBitcodeToFile
void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
Definition: BitcodeWriter.cpp:4865
ModuleSymbolTable.h
llvm::lto::Config::RelocModel
Optional< Reloc::Model > RelocModel
Definition: Config.h:54
llvm::ArrayRef< std::string >
llvm::lto::Config::PostOptModuleHook
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition: Config.h:235
llvm::lto::Config::RemarksHotnessThreshold
llvm::Optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
Definition: Config.h:155
llvm::Reloc::PIC_
@ PIC_
Definition: CodeGen.h:22
llvm::lto::thinBackend
Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > *ModuleMap, const std::vector< uint8_t > &CmdArgs=std::vector< uint8_t >())
Runs a ThinLTO backend.
Definition: LTOBackend.cpp:540
llvm::PIELevel::Default
@ Default
Definition: CodeGen.h:37
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
LTOBitcodeEmbedding::EmbedPostMergePreOptimized
@ EmbedPostMergePreOptimized
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:143
llvm::ThreadPool::async
auto async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:66
llvm::Reloc::Static
@ Static
Definition: CodeGen.h:22
llvm::Expected::get
reference get()
Returns a reference to the stored T value.
Definition: Error.h:566
llvm::detail::DenseSetImpl< ValueT, DenseMap< ValueT, detail::DenseSetEmpty, DenseMapInfo< ValueT >, detail::DenseSetPair< ValueT > >, DenseMapInfo< ValueT > >::contains
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
PassPlugin.h
llvm::PGOOptions
A struct capturing PGO tunables.
Definition: PGOOptions.h:22
llvm::OptimizationLevel::O3
static const OptimizationLevel O3
Optimize for fast execution as much as possible.
Definition: OptimizationLevel.h:89
clEnumValN
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:680
llvm::lto::Config::OptPipeline
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
Definition: Config.h:95
ThinLTOAssumeMerged
static cl::opt< bool > ThinLTOAssumeMerged("thinlto-assume-merged", cl::init(false), cl::desc("Assume the input has already undergone ThinLTO function " "importing and the other pre-optimization pipeline changes."))
llvm::NoPGOWarnMismatch
cl::opt< bool > NoPGOWarnMismatch
llvm::raw_fd_ostream
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:440
LAM
LoopAnalysisManager LAM
Definition: PassBuilderBindings.cpp:58
llvm::PassBuilder::parseAAPipeline
Error parseAAPipeline(AAManager &AA, StringRef PipelineText)
Parse a textual alias analysis pipeline into the provided AA manager.
Definition: PassBuilder.cpp:1757
llvm::MapVector::end
iterator end()
Definition: MapVector.h:72
llvm::AMDGPU::SendMsg::Msg
const CustomOperand< const MCSubtargetInfo & > Msg[]
Definition: AMDGPUAsmUtils.cpp:39
llvm::PassManager< Module >
EmbedBitcode
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
llvm::PassBuilder::registerLoopAnalyses
void registerLoopAnalyses(LoopAnalysisManager &LAM)
Registers all available loop analysis passes.
Definition: PassBuilder.cpp:465
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
Verifier.h
llvm::writeIndexToFile
void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
Definition: BitcodeWriter.cpp:4910
llvm::inconvertibleErrorCode
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:79
LLVMRemarkStreamer.h
llvm::toString
const char * toString(DWARFSectionKind Kind)
Definition: DWARFUnitIndex.h:67
llvm::PassBuilder::buildPerModuleDefaultPipeline
ModulePassManager buildPerModuleDefaultPipeline(OptimizationLevel Level, bool LTOPreLink=false)
Build a per-module default optimization pipeline.
Definition: PassBuilderPipelines.cpp:1397
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:155
llvm::legacy::PassManager
PassManager manages ModulePassManagers.
Definition: LegacyPassManager.h:52
llvm::Module::getContext
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:262
dropDeadSymbols
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
Definition: LTOBackend.cpp:519
llvm::PassBuilder::registerCGSCCAnalyses
void registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM)
Registers all available CGSCC analysis passes.
Definition: PassBuilder.cpp:442
llvm::OptimizationLevel
Definition: OptimizationLevel.h:22
llvm::lto::Config::AAPipeline
std::string AAPipeline
Definition: Config.h:100
PassManager.h
llvm::lto::Config::PreOptModuleHook
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module,...
Definition: Config.h:222
llvm::PGOOptions::CSIRUse
@ CSIRUse
Definition: PGOOptions.h:24
llvm::lto::Config::PTO
PipelineTuningOptions PTO
Tunable parameters for passes in the default pipelines.
Definition: Config.h:192
llvm::legacy::PassManager::add
void add(Pass *P) override
Add a pass to the queue of passes to run.
Definition: LegacyPassManager.cpp:1665
llvm::lto::Config::CSIRProfile
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition: Config.h:111
reportOpenError
static void reportOpenError(StringRef Path, Twine Msg)
Definition: LTOBackend.cpp:79
llvm::embedBitcodeInModule
void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
Definition: BitcodeWriter.cpp:5134
llvm::AnalysisManager::registerPass
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:836
llvm::Module::getPIELevel
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition: Module.cpp:604
WholeProgramDevirt.h
llvm::PassManager::run
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
Definition: PassManager.h:498
llvm::Module::setPartialSampleProfileRatio
void setPartialSampleProfileRatio(const ModuleSummaryIndex &Index)
Set the partial sample profile ratio in the profile summary module flag, if applicable.
Definition: Module.cpp:815
llvm::Expected::takeError
Error takeError()
Take ownership of the stored error.
Definition: Error.h:596
llvm::ThreadPool::wait
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
Definition: ThreadPool.cpp:143
codegen
static void codegen(const Config &Conf, TargetMachine *TM, AddStreamFn AddStream, unsigned Task, Module &Mod, const ModuleSummaryIndex &CombinedIndex)
Definition: LTOBackend.cpp:360
llvm::lto::Config::CGFileType
CodeGenFileType CGFileType
Definition: Config.h:57
llvm::updatePublicTypeTestCalls
void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
Definition: WholeProgramDevirt.cpp:805
LTO.h
llvm::ModuleSummaryIndex
Class to hold module path string table and global value map, and encapsulate methods for operating on...
Definition: ModuleSummaryIndex.h:1198
llvm::PassInstrumentationCallbacks
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
Definition: PassInstrumentation.h:66
exit
declare void exit(i32) noreturn nounwind This compiles into
Definition: README.txt:1072
llvm::Module::getTargetTriple
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:258
llvm::PassBuilder::crossRegisterProxies
void crossRegisterProxies(LoopAnalysisManager &LAM, FunctionAnalysisManager &FAM, CGSCCAnalysisManager &CGAM, ModuleAnalysisManager &MAM)
Cross register the analysis managers through their proxies.
Definition: PassBuilder.cpp:1625
Program.h
llvm::ErrorOr
Represents either an error or a value T.
Definition: ErrorOr.h:56
llvm::lto::Config::addSaveTemps
Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false, const DenseSet< StringRef > &SaveTempsArgs={})
This is a convenience function that configures this Config object to write temporary files named afte...
Definition: LTOBackend.cpp:85
llvm::to_string
std::string to_string(const T &Value)
Definition: ScopedPrinter.h:85
llvm::raw_svector_ostream
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:658
llvm::legacy::PassManager::run
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
Definition: LegacyPassManager.cpp:1671
llvm::AnalysisManager
A container for analyses that lazily runs them and caches their results.
Definition: InstructionSimplify.h:42
TM
const char LLVMTargetMachineRef TM
Definition: PassBuilderBindings.cpp:47
llvm::lto::Config::PassPlugins
std::vector< std::string > PassPlugins
Definition: Config.h:51
llvm::lto::Config::CPU
std::string CPU
Definition: Config.h:47
llvm::getBitcodeModuleList
Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
Definition: BitcodeReader.cpp:7748
llvm::BitcodeModule
Represents a module in a bitcode file.
Definition: BitcodeReader.h:62
llvm::cl::desc
Definition: CommandLine.h:413
Mod
Module * Mod
Definition: PassBuilderBindings.cpp:54
BitcodeReader.h
raw_ostream.h
llvm::ModuleSummaryIndex::withWholeProgramVisibility
bool withWholeProgramVisibility() const
Definition: ModuleSummaryIndex.h:1432
TargetRegistry.h
llvm::SplitModule
void SplitModule(Module &M, unsigned N, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback, bool PreserveLocals=false)
Splits the module M into N linkable partitions.
Definition: SplitModule.cpp:251
MPM
ModulePassManager MPM
Definition: PassBuilderBindings.cpp:70
CGAM
CGSCCAnalysisManager CGAM
Definition: PassBuilderBindings.cpp:60
llvm::TargetLibraryAnalysis
Analysis pass providing the TargetLibraryInfo.
Definition: TargetLibraryInfo.h:449
llvm::splitCodeGen
void splitCodeGen(Module &M, ArrayRef< raw_pwrite_stream * > OSs, ArrayRef< llvm::raw_pwrite_stream * > BCOSs, const std::function< std::unique_ptr< TargetMachine >()> &TMFactory, CodeGenFileType FileType=CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
Definition: ParallelCG.cpp:38
llvm::lto::Config::RemarksPasses
std::string RemarksPasses
Optimization remarks pass filter.
Definition: Config.h:137
llvm::lto::Config::PGOWarnMismatch
bool PGOWarnMismatch
Turn on/off the warning about a hash mismatch in the PGO profile data.
Definition: Config.h:75
StandardInstrumentations.h
llvm::Target::createTargetMachine
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Optional< Reloc::Model > RM, Optional< CodeModel::Model > CM=None, CodeGenOpt::Level OL=CodeGenOpt::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
Definition: TargetRegistry.h:481