LLVM  8.0.1
LTOBackend.cpp
Go to the documentation of this file.
1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the "backend" phase of LTO, i.e. it performs
11 // optimization and code generation on a loaded module. It is generally used
12 // internally by the LTO class but can also be used independently, for example
13 // to implement a standalone ThinLTO backend.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/LTO/LTOBackend.h"
25 #include "llvm/IR/PassManager.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"
45 
46 using namespace llvm;
47 using namespace lto;
48 
50  errs() << "failed to open " << Path << ": " << Msg << '\n';
51  errs().flush();
52  exit(1);
53 }
54 
55 Error Config::addSaveTemps(std::string OutputFileName,
56  bool UseInputModulePath) {
58 
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);
64 
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;
73 
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  };
95 
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);
102 
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);
112 
113  Path = OutputFileName + "index.dot";
115  if (EC)
116  reportOpenError(Path, EC.message());
117  Index.exportToDot(OSDot);
118  return true;
119  };
120 
121  return Error::success();
122 }
123 
124 namespace {
125 
126 std::unique_ptr<TargetMachine>
127 createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
128  StringRef TheTriple = M.getTargetTriple();
130  Features.getDefaultSubtargetFeatures(Triple(TheTriple));
131  for (const std::string &A : Conf.MAttrs)
132  Features.AddFeature(A);
133 
135  if (Conf.RelocModel)
136  RelocModel = *Conf.RelocModel;
137  else
138  RelocModel =
140 
142  if (Conf.CodeModel)
143  CodeModel = *Conf.CodeModel;
144  else
145  CodeModel = M.getCodeModel();
146 
147  return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
148  TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
149  CodeModel, Conf.CGOptLevel));
150 }
151 
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,
159  false, true);
160 
161  PassBuilder PB(TM, PGOOpt);
162  AAManager AA;
163 
164  // Parse a custom AA pipeline if asked to.
165  if (auto Err = PB.parseAAPipeline(AA, "default"))
166  report_fatal_error("Error parsing default AA pipeline");
167 
172 
173  // Register the AA manager first so that our version is the one used.
174  FAM.registerPass([&] { return std::move(AA); });
175 
176  // Register all the basic analyses with the managers.
177  PB.registerModuleAnalyses(MAM);
178  PB.registerCGSCCAnalyses(CGAM);
179  PB.registerFunctionAnalyses(FAM);
180  PB.registerLoopAnalyses(LAM);
181  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
182 
184  // FIXME (davide): verify the input.
185 
187 
188  switch (OptLevel) {
189  default:
190  llvm_unreachable("Invalid optimization level");
191  case 0:
192  OL = PassBuilder::O0;
193  break;
194  case 1:
195  OL = PassBuilder::O1;
196  break;
197  case 2:
198  OL = PassBuilder::O2;
199  break;
200  case 3:
201  OL = PassBuilder::O3;
202  break;
203  }
204 
205  if (IsThinLTO)
207  ImportSummary);
208  else
209  MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
210  MPM.run(Mod, MAM);
211 
212  // FIXME (davide): verify the output.
213 }
214 
215 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
216  std::string PipelineDesc,
217  std::string AAPipelineDesc,
218  bool DisableVerify) {
219  PassBuilder PB(TM);
220  AAManager AA;
221 
222  // Parse a custom AA pipeline if asked to.
223  if (!AAPipelineDesc.empty())
224  if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
225  report_fatal_error("unable to parse AA pipeline description '" +
226  AAPipelineDesc + "': " + toString(std::move(Err)));
227 
232 
233  // Register the AA manager first so that our version is the one used.
234  FAM.registerPass([&] { return std::move(AA); });
235 
236  // Register all the basic analyses with the managers.
237  PB.registerModuleAnalyses(MAM);
238  PB.registerCGSCCAnalyses(CGAM);
239  PB.registerFunctionAnalyses(FAM);
240  PB.registerLoopAnalyses(LAM);
241  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
242 
243  ModulePassManager MPM;
244 
245  // Always verify the input.
246  MPM.addPass(VerifierPass());
247 
248  // Now, add all the passes we've been requested to.
249  if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
250  report_fatal_error("unable to parse pass pipeline description '" +
251  PipelineDesc + "': " + toString(std::move(Err)));
252 
253  if (!DisableVerify)
254  MPM.addPass(VerifierPass());
255  MPM.run(Mod, MAM);
256 }
257 
258 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
259  bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
260  const ModuleSummaryIndex *ImportSummary) {
261  legacy::PassManager passes;
263 
264  PassManagerBuilder PMB;
267  PMB.ExportSummary = ExportSummary;
268  PMB.ImportSummary = ImportSummary;
269  // Unconditionally verify input since it is not verified before this
270  // point and has unknown origin.
271  PMB.VerifyInput = true;
272  PMB.VerifyOutput = !Conf.DisableVerify;
273  PMB.LoopVectorize = true;
274  PMB.SLPVectorize = true;
275  PMB.OptLevel = Conf.OptLevel;
276  PMB.PGOSampleUse = Conf.SampleProfile;
277  if (IsThinLTO)
278  PMB.populateThinLTOPassManager(passes);
279  else
280  PMB.populateLTOPassManager(passes);
281  passes.run(Mod);
282 }
283 
284 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
285  bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
286  const ModuleSummaryIndex *ImportSummary) {
287  // FIXME: Plumb the combined index into the new pass manager.
288  if (!Conf.OptPipeline.empty())
289  runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
290  Conf.DisableVerify);
291  else if (Conf.UseNewPM)
292  runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
293  ImportSummary);
294  else
295  runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
296  return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
297 }
298 
299 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
300  unsigned Task, Module &Mod) {
301  if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
302  return;
303 
304  std::unique_ptr<ToolOutputFile> DwoOut;
305  SmallString<1024> DwoFile(Conf.DwoPath);
306  if (!Conf.DwoDir.empty()) {
307  std::error_code EC;
308  if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
309  report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
310  EC.message());
311 
312  DwoFile = Conf.DwoDir;
313  sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
314  }
315 
316  if (!DwoFile.empty()) {
317  std::error_code EC;
318  TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
319  DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::F_None);
320  if (EC)
321  report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
322  }
323 
324  auto Stream = AddStream(Task);
325  legacy::PassManager CodeGenPasses;
326  if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
327  DwoOut ? &DwoOut->os() : nullptr,
328  Conf.CGFileType))
329  report_fatal_error("Failed to setup codegen");
330  CodeGenPasses.run(Mod);
331 
332  if (DwoOut)
333  DwoOut->keep();
334 }
335 
336 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
337  unsigned ParallelCodeGenParallelismLevel,
338  std::unique_ptr<Module> Mod) {
339  ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
340  unsigned ThreadCount = 0;
341  const Target *T = &TM->getTarget();
342 
343  SplitModule(
344  std::move(Mod), ParallelCodeGenParallelismLevel,
345  [&](std::unique_ptr<Module> MPart) {
346  // We want to clone the module in a new context to multi-thread the
347  // codegen. We do it by serializing partition modules to bitcode
348  // (while still on the main thread, in order to avoid data races) and
349  // spinning up new threads which deserialize the partitions into
350  // separate contexts.
351  // FIXME: Provide a more direct way to do this in LLVM.
352  SmallString<0> BC;
353  raw_svector_ostream BCOS(BC);
354  WriteBitcodeToFile(*MPart, BCOS);
355 
356  // Enqueue the task
357  CodegenThreadPool.async(
358  [&](const SmallString<0> &BC, unsigned ThreadId) {
359  LTOLLVMContext Ctx(C);
361  MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
362  Ctx);
363  if (!MOrErr)
364  report_fatal_error("Failed to read bitcode");
365  std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
366 
367  std::unique_ptr<TargetMachine> TM =
368  createTargetMachine(C, T, *MPartInCtx);
369 
370  codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
371  },
372  // Pass BC using std::move to ensure that it get moved rather than
373  // copied into the thread's context.
374  std::move(BC), ThreadCount++);
375  },
376  false);
377 
378  // Because the inner lambda (which runs in a worker thread) captures our local
379  // variables, we need to wait for the worker threads to terminate before we
380  // can leave the function scope.
381  CodegenThreadPool.wait();
382 }
383 
384 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
385  if (!C.OverrideTriple.empty())
387  else if (Mod.getTargetTriple().empty())
389 
390  std::string Msg;
392  if (!T)
393  return make_error<StringError>(Msg, inconvertibleErrorCode());
394  return T;
395 }
396 
397 }
398 
399 static Error
400 finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
401  // Make sure we flush the diagnostic remarks file in case the linker doesn't
402  // call the global destructors before exiting.
403  if (!DiagOutputFile)
404  return Error::success();
405  DiagOutputFile->keep();
406  DiagOutputFile->os().flush();
407  return Error::success();
408 }
409 
411  unsigned ParallelCodeGenParallelismLevel,
412  std::unique_ptr<Module> Mod,
413  ModuleSummaryIndex &CombinedIndex) {
414  Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
415  if (!TOrErr)
416  return TOrErr.takeError();
417 
418  std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
419 
420  // Setup optimization remarks.
421  auto DiagFileOrErr = lto::setupOptimizationRemarks(
422  Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
423  if (!DiagFileOrErr)
424  return DiagFileOrErr.takeError();
425  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
426 
427  if (!C.CodeGenOnly) {
428  if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
429  /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
430  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
431  }
432 
433  if (ParallelCodeGenParallelismLevel == 1) {
434  codegen(C, TM.get(), AddStream, 0, *Mod);
435  } else {
436  splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
437  std::move(Mod));
438  }
439  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
440 }
441 
442 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
443  const ModuleSummaryIndex &Index) {
444  std::vector<GlobalValue*> DeadGVs;
445  for (auto &GV : Mod.global_values())
446  if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
447  if (!Index.isGlobalValueLive(GVS)) {
448  DeadGVs.push_back(&GV);
450  }
451 
452  // Now that all dead bodies have been dropped, delete the actual objects
453  // themselves when possible.
454  for (GlobalValue *GV : DeadGVs) {
455  GV->removeDeadConstantUsers();
456  // Might reference something defined in native object (i.e. dropped a
457  // non-prevailing IR def, but we need to keep the declaration).
458  if (GV->use_empty())
459  GV->eraseFromParent();
460  }
461 }
462 
463 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
464  Module &Mod, const ModuleSummaryIndex &CombinedIndex,
465  const FunctionImporter::ImportMapTy &ImportList,
466  const GVSummaryMapTy &DefinedGlobals,
468  Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
469  if (!TOrErr)
470  return TOrErr.takeError();
471 
472  std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
473 
474  // Setup optimization remarks.
475  auto DiagFileOrErr = lto::setupOptimizationRemarks(
476  Mod.getContext(), Conf.RemarksFilename, Conf.RemarksWithHotness, Task);
477  if (!DiagFileOrErr)
478  return DiagFileOrErr.takeError();
479  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
480 
481  if (Conf.CodeGenOnly) {
482  codegen(Conf, TM.get(), AddStream, Task, Mod);
483  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
484  }
485 
486  if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
487  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
488 
489  renameModuleForThinLTO(Mod, CombinedIndex);
490 
491  dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
492 
493  thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
494 
495  if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
496  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
497 
498  if (!DefinedGlobals.empty())
499  thinLTOInternalizeModule(Mod, DefinedGlobals);
500 
501  if (Conf.PostInternalizeModuleHook &&
502  !Conf.PostInternalizeModuleHook(Task, Mod))
503  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
504 
505  auto ModuleLoader = [&](StringRef Identifier) {
507  "ODR Type uniquing should be enabled on the context");
508  auto I = ModuleMap.find(Identifier);
509  assert(I != ModuleMap.end());
510  return I->second.getLazyModule(Mod.getContext(),
511  /*ShouldLazyLoadMetadata=*/true,
512  /*IsImporting*/ true);
513  };
514 
515  FunctionImporter Importer(CombinedIndex, ModuleLoader);
516  if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
517  return Err;
518 
519  if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
520  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
521 
522  if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
523  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
524  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
525 
526  codegen(Conf, TM.get(), AddStream, Task, Mod);
527  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
528 }
static void codegen(Module *M, llvm::raw_pwrite_stream &OS, function_ref< std::unique_ptr< TargetMachine >()> TMFactory, TargetMachine::CodeGenFileType FileType)
Definition: ParallelCG.cpp:28
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:914
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.
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1267
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:39
std::string AAPipeline
Definition: Config.h:67
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:228
CodeGenOpt::Level CGOptLevel
Definition: Config.h:44
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:140
This class represents lattice values for constants.
Definition: AllocatorList.h:24
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
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:103
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Definition: Config.h:71
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
std::string SplitDwarfFile
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Definition: Config.h:57
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:110
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 FeatureBitset Features
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:510
Optional< CodeModel::Model > getCodeModel() const
Returns the code model (tiny, small, kernel, medium or large model)
Definition: Module.cpp:518
OptimizationLevel
LLVM-provided high-level optimization levels.
Definition: PassBuilder.h:98
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:38
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition: Config.h:98
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:38
std::string PGOSampleUse
Path of the sample Profile data file.
Error takeError()
Take ownership of the stored error.
Definition: Error.h:553
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:482
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:55
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition: Config.h:158
Pass * Inliner
Inliner - Specifies the inliner to use.
CombinedIndexHookFn CombinedIndexHook
Definition: Config.h:171
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.
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:187
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:480
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:967
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:95
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::string DwoDir
The directory to store .dwo files.
Definition: Config.h:84
std::vector< std::string > MAttrs
Definition: Config.h:41
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:244
std::string ProfileRemapping
Name remapping file for profile data.
Definition: Config.h:81
void populateLTOPassManager(legacy::PassManagerBase &PM)
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:822
This class provides access to building LLVM&#39;s passes.
Definition: PassBuilder.h:63
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:136
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
void registerLoopAnalyses(LoopAnalysisManager &LAM)
Registers all available loop analysis passes.
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:267
bool DisableVerify
Definition: Config.h:47
#define T
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:78
TargetOptions Options
Definition: Config.h:40
Optional< CodeModel::Model > CodeModel
Definition: Config.h:43
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
A ThreadPool for asynchronous parallel execution on a defined number of threads.
Definition: ThreadPool.h:37
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:148
PassManager manages ModulePassManagers.
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
Definition: LTOBackend.cpp:442
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
Definition: Config.h:140
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:88
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Disable as many optimizations as possible.
Definition: PassBuilder.h:102
A manager for alias analyses.
TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
bool UseNewPM
Use the new pass manager.
Definition: Config.h:50
unsigned OptLevel
Definition: Config.h:46
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:36
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
Definition: Config.h:75
Optimize for fast execution as much as possible.
Definition: PassBuilder.h:156
const Triple & getTargetTriple() const
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:147
size_t size() const
Definition: SmallVector.h:53
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
Create a verifier pass.
Definition: Verifier.h:137
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:45
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
std::string RemarksFilename
Optimization remarks file path.
Definition: Config.h:92
static ErrorSuccess success()
Create a success value.
Definition: Error.h:327
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
Definition: PassBuilder.h:140
Error parsePassPipeline(ModulePassManager &MPM, StringRef PipelineText, bool VerifyEachPass=true, bool DebugLogging=false)
Parse a textual pass pipeline description into a ModulePassManager.
Optional< Reloc::Model > RelocModel
Definition: Config.h:42
reference get()
Returns a reference to the stored T value.
Definition: Error.h:533
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:224
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:220
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:62
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:400
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
#define LLVM_ATTRIBUTE_NORETURN
Definition: Compiler.h:222
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:463
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:366
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:149
Manages a sequence of passes over a particular unit of IR.
Definition: PassManager.h:458
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
A struct capturing PGO tunables.
Definition: PassBuilder.h:34
TargetOptions Options
Definition: TargetMachine.h:97
#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 DwoPath
The path to write a .dwo file to.
Definition: Config.h:89
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:123
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:62
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:150
Error backend(Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
Definition: LTOBackend.cpp:410
iterator end()
Definition: MapVector.h:72
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Optimize quickly without destroying debuggability.
Definition: PassBuilder.h:122
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:158
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition: Config.h:153
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:59
PICLevel::Level getPICLevel() const
Returns the PIC level (small or large model)
Definition: Module.cpp:490
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:206
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
hexagon cext opt
A container for analyses that lazily runs them and caches their results.
void addPass(PassT Pass)
Definition: PassManager.h:542
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:144
iterator_range< global_value_iterator > global_values()
Definition: Module.h:685
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
Definition: ThreadPool.cpp:72
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:78