LLVM  9.0.0svn
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 //===----------------------------------------------------------------------===//
16 #include "llvm/LTO/LTOBackend.h"
24 #include "llvm/IR/PassManager.h"
25 #include "llvm/IR/RemarkStreamer.h"
26 #include "llvm/IR/Verifier.h"
27 #include "llvm/LTO/LTO.h"
31 #include "llvm/Support/Error.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/Program.h"
40 #include "llvm/Transforms/IPO.h"
46 using namespace llvm;
47 using namespace lto;
50  errs() << "failed to open " << Path << ": " << Msg << '\n';
51  errs().flush();
52  exit(1);
53 }
55 Error Config::addSaveTemps(std::string OutputFileName,
56  bool UseInputModulePath) {
59  std::error_code EC;
60  ResolutionFile = llvm::make_unique<raw_fd_ostream>(
61  OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
62  if (EC)
63  return errorCodeToError(EC);
65  auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
66  // Keep track of the hook provided by the linker, which also needs to run.
67  ModuleHookFn LinkerHook = Hook;
68  Hook = [=](unsigned Task, const Module &M) {
69  // If the linker's hook returned false, we need to pass that result
70  // through.
71  if (LinkerHook && !LinkerHook(Task, M))
72  return false;
74  std::string PathPrefix;
75  // If this is the combined module (not a ThinLTO backend compile) or the
76  // user hasn't requested using the input module's path, emit to a file
77  // named from the provided OutputFileName with the Task ID appended.
78  if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
79  PathPrefix = OutputFileName;
80  if (Task != (unsigned)-1)
81  PathPrefix += utostr(Task) + ".";
82  } else
83  PathPrefix = M.getModuleIdentifier() + ".";
84  std::string Path = PathPrefix + PathSuffix + ".bc";
85  std::error_code EC;
87  // Because -save-temps is a debugging feature, we report the error
88  // directly and exit.
89  if (EC)
90  reportOpenError(Path, EC.message());
91  WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
92  return true;
93  };
94  };
96  setHook("0.preopt", PreOptModuleHook);
97  setHook("1.promote", PostPromoteModuleHook);
98  setHook("2.internalize", PostInternalizeModuleHook);
99  setHook("3.import", PostImportModuleHook);
100  setHook("4.opt", PostOptModuleHook);
101  setHook("5.precodegen", PreCodeGenModuleHook);
104  std::string Path = OutputFileName + "index.bc";
105  std::error_code EC;
107  // Because -save-temps is a debugging feature, we report the error
108  // directly and exit.
109  if (EC)
110  reportOpenError(Path, EC.message());
111  WriteIndexToFile(Index, OS);
113  Path = OutputFileName + "index.dot";
115  if (EC)
116  reportOpenError(Path, EC.message());
117  Index.exportToDot(OSDot);
118  return true;
119  };
121  return Error::success();
122 }
124 namespace {
126 std::unique_ptr<TargetMachine>
127 createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
128  StringRef TheTriple = M.getTargetTriple();
129  SubtargetFeatures Features;
130  Features.getDefaultSubtargetFeatures(Triple(TheTriple));
131  for (const std::string &A : Conf.MAttrs)
132  Features.AddFeature(A);
135  if (Conf.RelocModel)
136  RelocModel = *Conf.RelocModel;
137  else
138  RelocModel =
142  if (Conf.CodeModel)
143  CodeModel = *Conf.CodeModel;
144  else
145  CodeModel = M.getCodeModel();
147  return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
148  TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
149  CodeModel, Conf.CGOptLevel));
150 }
152 static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
153  unsigned OptLevel, bool IsThinLTO,
154  ModuleSummaryIndex *ExportSummary,
155  const ModuleSummaryIndex *ImportSummary) {
156  Optional<PGOOptions> PGOOpt;
157  if (!Conf.SampleProfile.empty())
158  PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
160  else if (Conf.RunCSIRInstr) {
161  PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
163  } else if (!Conf.CSIRProfile.empty()) {
164  PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
166  }
168  PassBuilder PB(TM, PipelineTuningOptions(), PGOOpt);
169  AAManager AA;
171  // Parse a custom AA pipeline if asked to.
172  if (auto Err = PB.parseAAPipeline(AA, "default"))
173  report_fatal_error("Error parsing default AA pipeline");
180  // Register the AA manager first so that our version is the one used.
181  FAM.registerPass([&] { return std::move(AA); });
183  // Register all the basic analyses with the managers.
184  PB.registerModuleAnalyses(MAM);
185  PB.registerCGSCCAnalyses(CGAM);
186  PB.registerFunctionAnalyses(FAM);
187  PB.registerLoopAnalyses(LAM);
188  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
191  // FIXME (davide): verify the input.
195  switch (OptLevel) {
196  default:
197  llvm_unreachable("Invalid optimization level");
198  case 0:
199  OL = PassBuilder::O0;
200  break;
201  case 1:
202  OL = PassBuilder::O1;
203  break;
204  case 2:
205  OL = PassBuilder::O2;
206  break;
207  case 3:
208  OL = PassBuilder::O3;
209  break;
210  }
212  if (IsThinLTO)
214  ImportSummary);
215  else
216  MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
217  MPM.run(Mod, MAM);
219  // FIXME (davide): verify the output.
220 }
222 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
223  std::string PipelineDesc,
224  std::string AAPipelineDesc,
225  bool DisableVerify) {
226  PassBuilder PB(TM);
227  AAManager AA;
229  // Parse a custom AA pipeline if asked to.
230  if (!AAPipelineDesc.empty())
231  if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
232  report_fatal_error("unable to parse AA pipeline description '" +
233  AAPipelineDesc + "': " + toString(std::move(Err)));
240  // Register the AA manager first so that our version is the one used.
241  FAM.registerPass([&] { return std::move(AA); });
243  // Register all the basic analyses with the managers.
244  PB.registerModuleAnalyses(MAM);
245  PB.registerCGSCCAnalyses(CGAM);
246  PB.registerFunctionAnalyses(FAM);
247  PB.registerLoopAnalyses(LAM);
248  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
250  ModulePassManager MPM;
252  // Always verify the input.
253  MPM.addPass(VerifierPass());
255  // Now, add all the passes we've been requested to.
256  if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
257  report_fatal_error("unable to parse pass pipeline description '" +
258  PipelineDesc + "': " + toString(std::move(Err)));
260  if (!DisableVerify)
261  MPM.addPass(VerifierPass());
262  MPM.run(Mod, MAM);
263 }
265 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
266  bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
267  const ModuleSummaryIndex *ImportSummary) {
268  legacy::PassManager passes;
271  PassManagerBuilder PMB;
274  PMB.ExportSummary = ExportSummary;
275  PMB.ImportSummary = ImportSummary;
276  // Unconditionally verify input since it is not verified before this
277  // point and has unknown origin.
278  PMB.VerifyInput = true;
279  PMB.VerifyOutput = !Conf.DisableVerify;
280  PMB.LoopVectorize = true;
281  PMB.SLPVectorize = true;
282  PMB.OptLevel = Conf.OptLevel;
283  PMB.PGOSampleUse = Conf.SampleProfile;
285  if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
286  PMB.EnablePGOCSInstrUse = true;
287  PMB.PGOInstrUse = Conf.CSIRProfile;
288  }
289  if (IsThinLTO)
290  PMB.populateThinLTOPassManager(passes);
291  else
292  PMB.populateLTOPassManager(passes);
293  passes.run(Mod);
294 }
296 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
297  bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
298  const ModuleSummaryIndex *ImportSummary) {
299  // FIXME: Plumb the combined index into the new pass manager.
300  if (!Conf.OptPipeline.empty())
301  runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
302  Conf.DisableVerify);
303  else if (Conf.UseNewPM)
304  runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
305  ImportSummary);
306  else
307  runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
308  return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
309 }
311 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
312  unsigned Task, Module &Mod) {
313  if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
314  return;
316  std::unique_ptr<ToolOutputFile> DwoOut;
317  SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
318  if (!Conf.DwoDir.empty()) {
319  std::error_code EC;
320  if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
321  report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
322  EC.message());
324  DwoFile = Conf.DwoDir;
325  sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
326  TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
327  } else
330  if (!DwoFile.empty()) {
331  std::error_code EC;
332  DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::F_None);
333  if (EC)
334  report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
335  }
337  auto Stream = AddStream(Task);
338  legacy::PassManager CodeGenPasses;
339  if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
340  DwoOut ? &DwoOut->os() : nullptr,
341  Conf.CGFileType))
342  report_fatal_error("Failed to setup codegen");
343  CodeGenPasses.run(Mod);
345  if (DwoOut)
346  DwoOut->keep();
347 }
349 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
350  unsigned ParallelCodeGenParallelismLevel,
351  std::unique_ptr<Module> Mod) {
352  ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
353  unsigned ThreadCount = 0;
354  const Target *T = &TM->getTarget();
356  SplitModule(
357  std::move(Mod), ParallelCodeGenParallelismLevel,
358  [&](std::unique_ptr<Module> MPart) {
359  // We want to clone the module in a new context to multi-thread the
360  // codegen. We do it by serializing partition modules to bitcode
361  // (while still on the main thread, in order to avoid data races) and
362  // spinning up new threads which deserialize the partitions into
363  // separate contexts.
364  // FIXME: Provide a more direct way to do this in LLVM.
365  SmallString<0> BC;
366  raw_svector_ostream BCOS(BC);
367  WriteBitcodeToFile(*MPart, BCOS);
369  // Enqueue the task
370  CodegenThreadPool.async(
371  [&](const SmallString<0> &BC, unsigned ThreadId) {
372  LTOLLVMContext Ctx(C);
374  MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
375  Ctx);
376  if (!MOrErr)
377  report_fatal_error("Failed to read bitcode");
378  std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
380  std::unique_ptr<TargetMachine> TM =
381  createTargetMachine(C, T, *MPartInCtx);
383  codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
384  },
385  // Pass BC using std::move to ensure that it get moved rather than
386  // copied into the thread's context.
387  std::move(BC), ThreadCount++);
388  },
389  false);
391  // Because the inner lambda (which runs in a worker thread) captures our local
392  // variables, we need to wait for the worker threads to terminate before we
393  // can leave the function scope.
394  CodegenThreadPool.wait();
395 }
397 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
398  if (!C.OverrideTriple.empty())
400  else if (Mod.getTargetTriple().empty())
403  std::string Msg;
405  if (!T)
406  return make_error<StringError>(Msg, inconvertibleErrorCode());
407  return T;
408 }
410 }
412 static Error
413 finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
414  // Make sure we flush the diagnostic remarks file in case the linker doesn't
415  // call the global destructors before exiting.
416  if (!DiagOutputFile)
417  return Error::success();
418  DiagOutputFile->keep();
419  DiagOutputFile->os().flush();
420  return Error::success();
421 }
424  unsigned ParallelCodeGenParallelismLevel,
425  std::unique_ptr<Module> Mod,
426  ModuleSummaryIndex &CombinedIndex) {
427  Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
428  if (!TOrErr)
429  return TOrErr.takeError();
431  std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
433  // Setup optimization remarks.
434  auto DiagFileOrErr = lto::setupOptimizationRemarks(
435  Mod->getContext(), C.RemarksFilename, C.RemarksPasses, C.RemarksFormat,
437  if (!DiagFileOrErr)
438  return DiagFileOrErr.takeError();
439  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
441  if (!C.CodeGenOnly) {
442  if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
443  /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
444  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
445  }
447  if (ParallelCodeGenParallelismLevel == 1) {
448  codegen(C, TM.get(), AddStream, 0, *Mod);
449  } else {
450  splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
451  std::move(Mod));
452  }
453  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
454 }
456 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
457  const ModuleSummaryIndex &Index) {
458  std::vector<GlobalValue*> DeadGVs;
459  for (auto &GV : Mod.global_values())
460  if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
461  if (!Index.isGlobalValueLive(GVS)) {
462  DeadGVs.push_back(&GV);
464  }
466  // Now that all dead bodies have been dropped, delete the actual objects
467  // themselves when possible.
468  for (GlobalValue *GV : DeadGVs) {
469  GV->removeDeadConstantUsers();
470  // Might reference something defined in native object (i.e. dropped a
471  // non-prevailing IR def, but we need to keep the declaration).
472  if (GV->use_empty())
473  GV->eraseFromParent();
474  }
475 }
477 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
478  Module &Mod, const ModuleSummaryIndex &CombinedIndex,
479  const FunctionImporter::ImportMapTy &ImportList,
480  const GVSummaryMapTy &DefinedGlobals,
482  Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
483  if (!TOrErr)
484  return TOrErr.takeError();
486  std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
488  // Setup optimization remarks.
489  auto DiagFileOrErr = lto::setupOptimizationRemarks(
490  Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
491  Conf.RemarksFormat, Conf.RemarksWithHotness, Task);
492  if (!DiagFileOrErr)
493  return DiagFileOrErr.takeError();
494  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
496  if (Conf.CodeGenOnly) {
497  codegen(Conf, TM.get(), AddStream, Task, Mod);
498  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
499  }
501  if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
502  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
504  renameModuleForThinLTO(Mod, CombinedIndex);
506  dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
508  thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
510  if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
511  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
513  if (!DefinedGlobals.empty())
514  thinLTOInternalizeModule(Mod, DefinedGlobals);
516  if (Conf.PostInternalizeModuleHook &&
517  !Conf.PostInternalizeModuleHook(Task, Mod))
518  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
520  auto ModuleLoader = [&](StringRef Identifier) {
522  "ODR Type uniquing should be enabled on the context");
523  auto I = ModuleMap.find(Identifier);
524  assert(I != ModuleMap.end());
525  return I->second.getLazyModule(Mod.getContext(),
526  /*ShouldLazyLoadMetadata=*/true,
527  /*IsImporting*/ true);
528  };
530  FunctionImporter Importer(CombinedIndex, ModuleLoader);
531  if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
532  return Err;
534  if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
535  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
537  if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
538  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
539  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
541  codegen(Conf, TM.get(), AddStream, Task, Mod);
542  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
543 }
static void codegen(Module *M, llvm::raw_pwrite_stream &OS, function_ref< std::unique_ptr< TargetMachine >()> TMFactory, TargetMachine::CodeGenFileType FileType)
Definition: ParallelCG.cpp:27
uint64_t CallInst * C
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:915
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:240
Interfaces for registering analysis passes, producing common pass manager configurations, and parsing of pass pipelines.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void thinLTOResolvePrevailingInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Resolve prevailing symbol linkages in TheModule based on the information recorded in the summaries du...
std::string CPU
Definition: Config.h:38
std::string AAPipeline
Definition: Config.h:69
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:218
CodeGenOpt::Level CGOptLevel
Definition: Config.h:43
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
MCTargetOptions MCOptions
Machine level options.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
bool EnablePGOCSInstrUse
Enable profile context sensitive profile use pass.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
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...
Error parseAAPipeline(AAManager &AA, StringRef PipelineText)
Parse a textual alias analysis pipeline into the provided AA manager.
bool ShouldDiscardValueNames
Definition: Config.h:120
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Definition: Config.h:73
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
std::string SplitDwarfFile
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Definition: Config.h:56
void registerModuleAnalyses(ModuleAnalysisManager &MAM)
Registers all available module analysis passes.
void SplitModule(std::unique_ptr< Module > M, unsigned N, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback, bool PreserveLocals=false)
Splits the module M into N linkable partitions.
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:127
bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
ModuleSummaryIndex * ExportSummary
The module summary index to use for exporting information from the regular LTO phase, for example for the CFI and devirtualization type tests.
std::string getString() const
Returns features as a string.
const ModuleSummaryIndex * ImportSummary
The module summary index to use for importing information to the thin LTO backends, for example for the CFI and devirtualization type tests.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:509
Optional< CodeModel::Model > getCodeModel() const
Returns the code model (tiny, small, kernel, medium or large model)
Definition: Module.cpp:516
LLVM-provided high-level optimization levels.
Definition: PassBuilder.h:146
Implementation of the target library information.
This class implements a map that also provides access to all stored values in a deterministic order...
Definition: MapVector.h:37
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition: Config.h:115
std::unique_ptr< Module > splitCodeGen(std::unique_ptr< Module > M, ArrayRef< raw_pwrite_stream *> OSs, ArrayRef< llvm::raw_pwrite_stream *> BCOSs, const std::function< std::unique_ptr< TargetMachine >()> &TMFactory, TargetMachine::CodeGenFileType FileType=TargetMachine::CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
Definition: ParallelCG.cpp:37
std::string PGOSampleUse
Path of the sample Profile data file.
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
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:488
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:54
Tunable parameters for passes in the default pipelines.
Definition: PassBuilder.h:70
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition: Config.h:175
Pass * Inliner
Inliner - Specifies the inliner to use.
CombinedIndexHookFn CombinedIndexHook
Definition: Config.h:188
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfo *MMI=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:455
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:966
void add(Pass *P) override
Add a pass to the queue of passes to run.
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition: Config.h:109
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
std::string DwoDir
The directory to store .dwo files.
Definition: Config.h:89
std::vector< std::string > MAttrs
Definition: Config.h:40
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:244
std::string ProfileRemapping
Name remapping file for profile data.
Definition: Config.h:86
void populateLTOPassManager(legacy::PassManagerBase &PM)
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:828
This class provides access to building LLVM&#39;s passes.
Definition: PassBuilder.h:110
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
bool EnablePGOCSInstrGen
Enable profile context sensitive instrumentation pass.
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
void registerLoopAnalyses(LoopAnalysisManager &LAM)
Registers all available loop analysis passes.
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:95
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:266
bool DisableVerify
Definition: Config.h:46
unsigned OptLevel
The Optimization Level - Specify the basic optimization level.
void crossRegisterProxies(LoopAnalysisManager &LAM, FunctionAnalysisManager &FAM, CGSCCAnalysisManager &CGAM, ModuleAnalysisManager &MAM)
Cross register the analysis managers through their proxies.
std::string SampleProfile
Sample PGO profile path.
Definition: Config.h:83
TargetOptions Options
Definition: Config.h:39
Optional< CodeModel::Model > CodeModel
Definition: Config.h:42
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:25
A ThreadPool for asynchronous parallel execution on a defined number of threads.
Definition: ThreadPool.h:36
Class to hold module path string table and global value map, and encapsulate methods for operating on...
iterator find(const KeyT &Key)
Definition: MapVector.h:147
std::string PGOInstrUse
Path of the profile data file.
PassManager manages ModulePassManagers.
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
Definition: LTOBackend.cpp:456
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
Definition: Config.h:157
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:153
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, SetVector< GlobalValue *> *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Disable as many optimizations as possible.
Definition: PassBuilder.h:150
A manager for alias analyses.
TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
bool UseNewPM
Use the new pass manager.
Definition: Config.h:49
unsigned OptLevel
Definition: Config.h:45
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.
bool isODRUniquingDebugTypes() const
Whether there is a string map for uniquing debug info identifiers across the context.
void registerFunctionAnalyses(FunctionAnalysisManager &FAM)
Registers all available function analysis passes.
LTO configuration.
Definition: Config.h:35
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
Definition: Config.h:77
Optimize for fast execution as much as possible.
Definition: PassBuilder.h:204
const Triple & getTargetTriple() const
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition: Config.h:80
Function and variable summary information to aid decisions and implementation of importing.
const Target & getTarget() const
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition: Config.h:164
size_t size() const
Definition: SmallVector.h:52
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
Create a verifier pass.
Definition: Verifier.h:136
ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, const ModuleSummaryIndex *ImportSummary)
Build an ThinLTO default optimization pipeline to a pass manager.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
TargetMachine::CodeGenFileType CGFileType
Definition: Config.h:44
std::function< std::unique_ptr< NativeObjectStream >(unsigned Task)> AddStreamFn
This type defines the callback to add a native object that is generated on the fly.
Definition: LTO.h:202
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
std::string RemarksFilename
Optimization remarks file path.
Definition: Config.h:103
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition: Config.h:59
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
Definition: PassBuilder.h:188
Error parsePassPipeline(ModulePassManager &MPM, StringRef PipelineText, bool VerifyEachPass=true, bool DebugLogging=false)
Parse a textual pass pipeline description into a ModulePassManager.
Definition: Compiler.h:221
Optional< Reloc::Model > RelocModel
Definition: Config.h:41
reference get()
Returns a reference to the stored T value.
Definition: Error.h:532
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
The access may modify the value stored in memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:219
Target - Wrapper for Target specific information.
Manages the enabling and disabling of subtarget specific features.
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:64
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 ...
static Error finalizeOptimizationRemarks(std::unique_ptr< ToolOutputFile > DiagOutputFile)
Definition: LTOBackend.cpp:413
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition: Config.h:112
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
Error thinBackend(Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > &ModuleMap)
Runs a ThinLTO backend.
Definition: LTOBackend.cpp:477
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:365
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:144
Manages a sequence of passes over a particular unit of IR.
Definition: PassManager.h:464
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
A struct capturing PGO tunables.
Definition: PassBuilder.h:33
TargetOptions Options
#define I(x, y, z)
Definition: MD5.cpp:58
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
void setTargetTriple(StringRef T)
Set the target triple.
Definition: Module.h:283
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition: Config.h:100
std::string RemarksPasses
Optimization remarks pass filter.
Definition: Config.h:106
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:122
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:211
This header provides classes for managing passes over SCCs of the call graph.
const std::string to_string(const T &Value)
Definition: ScopedPrinter.h:61
void registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM)
Registers all available CGSCC analysis passes.
ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition: Config.h:167
Error backend(Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
Definition: LTOBackend.cpp:423
iterator end()
Definition: MapVector.h:71
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Optimize quickly without destroying debuggability.
Definition: PassBuilder.h:170
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1344
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
The function importer is automatically importing function from other modules based on the provided su...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition: Config.h:170
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
PICLevel::Level getPICLevel() const
Returns the PIC level (small or large model)
Definition: Module.cpp:488
Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false)
This is a convenience function that configures this Config object to write temporary files named afte...
Definition: LTOBackend.cpp:55
A derived class of LLVMContext that initializes itself according to a given Config object...
Definition: Config.h:223
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
hexagon cext opt
A container for analyses that lazily runs them and caches their results.
void addPass(PassT Pass)
Definition: PassManager.h:548
static LLVM_ATTRIBUTE_NORETURN void reportOpenError(StringRef Path, Twine Msg)
Definition: LTOBackend.cpp:49
This pass exposes codegen information to IR-level passes.
This header defines various interfaces for pass management in LLVM.
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
Definition: Config.h:161
iterator_range< global_value_iterator > global_values()
Definition: Module.h:688
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
Definition: ThreadPool.cpp:71
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77