LLVM  5.0.0
LTOCodeGenerator.cpp
Go to the documentation of this file.
1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
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 Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/Passes.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/LTO/LTO.h"
41 #include "llvm/Linker/Linker.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
47 #include "llvm/Support/Host.h"
49 #include "llvm/Support/Signals.h"
59 #include "llvm/Transforms/IPO.h"
64 #include <system_error>
65 using namespace llvm;
66 
68 #ifdef LLVM_VERSION_INFO
69  return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
70 #else
71  return PACKAGE_NAME " version " PACKAGE_VERSION;
72 #endif
73 }
74 
75 namespace llvm {
77  "lto-discard-value-names",
78  cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
79 #ifdef NDEBUG
80  cl::init(true),
81 #else
82  cl::init(false),
83 #endif
84  cl::Hidden);
85 
87  "lto-strip-invalid-debug-info",
88  cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
89 #ifdef NDEBUG
90  cl::init(true),
91 #else
92  cl::init(false),
93 #endif
94  cl::Hidden);
95 
97  LTORemarksFilename("lto-pass-remarks-output",
98  cl::desc("Output filename for pass remarks"),
99  cl::value_desc("filename"));
100 
102  "lto-pass-remarks-with-hotness",
103  cl::desc("With PGO, include profile count in optimization remarks"),
104  cl::Hidden);
105 }
106 
108  : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
109  TheLinker(new Linker(*MergedModule)) {
111  Context.enableDebugTypeODRUniquing();
112  initializeLTOPasses();
113 }
114 
116 
117 // Initialize LTO passes. Please keep this function in sync with
118 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
119 // passes are initialized.
120 void LTOCodeGenerator::initializeLTOPasses() {
122 
145 }
146 
148  const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
149  for (int i = 0, e = undefs.size(); i != e; ++i)
150  AsmUndefinedRefs[undefs[i]] = 1;
151 }
152 
154  assert(&Mod->getModule().getContext() == &Context &&
155  "Expected module in same context");
156 
157  bool ret = TheLinker->linkInModule(Mod->takeModule());
158  setAsmUndefinedRefs(Mod);
159 
160  // We've just changed the input, so let's make sure we verify it.
161  HasVerifiedInput = false;
162 
163  return !ret;
164 }
165 
166 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
167  assert(&Mod->getModule().getContext() == &Context &&
168  "Expected module in same context");
169 
170  AsmUndefinedRefs.clear();
171 
172  MergedModule = Mod->takeModule();
173  TheLinker = make_unique<Linker>(*MergedModule);
174  setAsmUndefinedRefs(&*Mod);
175 
176  // We've just changed the input, so let's make sure we verify it.
177  HasVerifiedInput = false;
178 }
179 
181  this->Options = Options;
182 }
183 
185  switch (Debug) {
187  EmitDwarfDebugInfo = false;
188  return;
189 
191  EmitDwarfDebugInfo = true;
192  return;
193  }
194  llvm_unreachable("Unknown debug format!");
195 }
196 
198  OptLevel = Level;
199  switch (OptLevel) {
200  case 0:
201  CGOptLevel = CodeGenOpt::None;
202  return;
203  case 1:
204  CGOptLevel = CodeGenOpt::Less;
205  return;
206  case 2:
207  CGOptLevel = CodeGenOpt::Default;
208  return;
209  case 3:
210  CGOptLevel = CodeGenOpt::Aggressive;
211  return;
212  }
213  llvm_unreachable("Unknown optimization level!");
214 }
215 
217  if (!determineTarget())
218  return false;
219 
220  // We always run the verifier once on the merged module.
221  verifyMergedModuleOnce();
222 
223  // mark which symbols can not be internalized
224  applyScopeRestrictions();
225 
226  // create output file
227  std::error_code EC;
228  tool_output_file Out(Path, EC, sys::fs::F_None);
229  if (EC) {
230  std::string ErrMsg = "could not open bitcode file for writing: ";
231  ErrMsg += Path;
232  emitError(ErrMsg);
233  return false;
234  }
235 
236  // write bitcode to it
237  WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
238  Out.os().close();
239 
240  if (Out.os().has_error()) {
241  std::string ErrMsg = "could not write bitcode file: ";
242  ErrMsg += Path;
243  emitError(ErrMsg);
244  Out.os().clear_error();
245  return false;
246  }
247 
248  Out.keep();
249  return true;
250 }
251 
252 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
253  // make unique temp output file to put generated code
254  SmallString<128> Filename;
255  int FD;
256 
257  StringRef Extension
258  (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
259 
260  std::error_code EC =
261  sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
262  if (EC) {
263  emitError(EC.message());
264  return false;
265  }
266 
267  // generate object file
268  tool_output_file objFile(Filename, FD);
269 
270  bool genResult = compileOptimized(&objFile.os());
271  objFile.os().close();
272  if (objFile.os().has_error()) {
273  emitError((Twine("could not write object file: ") + Filename).str());
274  objFile.os().clear_error();
275  sys::fs::remove(Twine(Filename));
276  return false;
277  }
278 
279  objFile.keep();
280  if (!genResult) {
281  sys::fs::remove(Twine(Filename));
282  return false;
283  }
284 
285  NativeObjectPath = Filename.c_str();
286  *Name = NativeObjectPath.c_str();
287  return true;
288 }
289 
290 std::unique_ptr<MemoryBuffer>
292  const char *name;
293  if (!compileOptimizedToFile(&name))
294  return nullptr;
295 
296  // read .o file into memory buffer
298  MemoryBuffer::getFile(name, -1, false);
299  if (std::error_code EC = BufferOrErr.getError()) {
300  emitError(EC.message());
301  sys::fs::remove(NativeObjectPath);
302  return nullptr;
303  }
304 
305  // remove temp files
306  sys::fs::remove(NativeObjectPath);
307 
308  return std::move(*BufferOrErr);
309 }
310 
311 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
312  bool DisableInline,
313  bool DisableGVNLoadPRE,
314  bool DisableVectorization) {
315  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
316  DisableVectorization))
317  return false;
318 
319  return compileOptimizedToFile(Name);
320 }
321 
322 std::unique_ptr<MemoryBuffer>
323 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
324  bool DisableGVNLoadPRE, bool DisableVectorization) {
325  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
326  DisableVectorization))
327  return nullptr;
328 
329  return compileOptimized();
330 }
331 
332 bool LTOCodeGenerator::determineTarget() {
333  if (TargetMach)
334  return true;
335 
336  TripleStr = MergedModule->getTargetTriple();
337  if (TripleStr.empty()) {
338  TripleStr = sys::getDefaultTargetTriple();
339  MergedModule->setTargetTriple(TripleStr);
340  }
341  llvm::Triple Triple(TripleStr);
342 
343  // create target machine from info for merged modules
344  std::string ErrMsg;
345  MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
346  if (!MArch) {
347  emitError(ErrMsg);
348  return false;
349  }
350 
351  // Construct LTOModule, hand over ownership of module and target. Use MAttr as
352  // the default set of features.
354  Features.getDefaultSubtargetFeatures(Triple);
355  FeatureStr = Features.getString();
356  // Set a default CPU for Darwin triples.
357  if (MCpu.empty() && Triple.isOSDarwin()) {
359  MCpu = "core2";
360  else if (Triple.getArch() == llvm::Triple::x86)
361  MCpu = "yonah";
362  else if (Triple.getArch() == llvm::Triple::aarch64)
363  MCpu = "cyclone";
364  }
365 
366  TargetMach = createTargetMachine();
367  return true;
368 }
369 
370 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
371  return std::unique_ptr<TargetMachine>(
372  MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
373  RelocModel, CodeModel::Default, CGOptLevel));
374 }
375 
376 // If a linkonce global is present in the MustPreserveSymbols, we need to make
377 // sure we honor this. To force the compiler to not drop it, we add it to the
378 // "llvm.compiler.used" global.
379 void LTOCodeGenerator::preserveDiscardableGVs(
380  Module &TheModule,
381  llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
382  std::vector<GlobalValue *> Used;
383  auto mayPreserveGlobal = [&](GlobalValue &GV) {
384  if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
385  !mustPreserveGV(GV))
386  return;
387  if (GV.hasAvailableExternallyLinkage())
388  return emitWarning(
389  (Twine("Linker asked to preserve available_externally global: '") +
390  GV.getName() + "'").str());
391  if (GV.hasInternalLinkage())
392  return emitWarning((Twine("Linker asked to preserve internal global: '") +
393  GV.getName() + "'").str());
394  Used.push_back(&GV);
395  };
396  for (auto &GV : TheModule)
397  mayPreserveGlobal(GV);
398  for (auto &GV : TheModule.globals())
399  mayPreserveGlobal(GV);
400  for (auto &GV : TheModule.aliases())
401  mayPreserveGlobal(GV);
402 
403  if (Used.empty())
404  return;
405 
406  appendToCompilerUsed(TheModule, Used);
407 }
408 
409 void LTOCodeGenerator::applyScopeRestrictions() {
410  if (ScopeRestrictionsDone)
411  return;
412 
413  // Declare a callback for the internalize pass that will ask for every
414  // candidate GlobalValue if it can be internalized or not.
415  Mangler Mang;
416  SmallString<64> MangledName;
417  auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
418  // Unnamed globals can't be mangled, but they can't be preserved either.
419  if (!GV.hasName())
420  return false;
421 
422  // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
423  // with the linker supplied name, which on Darwin includes a leading
424  // underscore.
425  MangledName.clear();
426  MangledName.reserve(GV.getName().size() + 1);
427  Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
428  return MustPreserveSymbols.count(MangledName);
429  };
430 
431  // Preserve linkonce value on linker request
432  preserveDiscardableGVs(*MergedModule, mustPreserveGV);
433 
434  if (!ShouldInternalize)
435  return;
436 
437  if (ShouldRestoreGlobalsLinkage) {
438  // Record the linkage type of non-local symbols so they can be restored
439  // prior
440  // to module splitting.
441  auto RecordLinkage = [&](const GlobalValue &GV) {
442  if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
443  GV.hasName())
444  ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
445  };
446  for (auto &GV : *MergedModule)
447  RecordLinkage(GV);
448  for (auto &GV : MergedModule->globals())
449  RecordLinkage(GV);
450  for (auto &GV : MergedModule->aliases())
451  RecordLinkage(GV);
452  }
453 
454  // Update the llvm.compiler_used globals to force preserving libcalls and
455  // symbols referenced from asm
456  updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
457 
458  internalizeModule(*MergedModule, mustPreserveGV);
459 
460  ScopeRestrictionsDone = true;
461 }
462 
463 /// Restore original linkage for symbols that may have been internalized
464 void LTOCodeGenerator::restoreLinkageForExternals() {
465  if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
466  return;
467 
468  assert(ScopeRestrictionsDone &&
469  "Cannot externalize without internalization!");
470 
471  if (ExternalSymbols.empty())
472  return;
473 
474  auto externalize = [this](GlobalValue &GV) {
475  if (!GV.hasLocalLinkage() || !GV.hasName())
476  return;
477 
478  auto I = ExternalSymbols.find(GV.getName());
479  if (I == ExternalSymbols.end())
480  return;
481 
482  GV.setLinkage(I->second);
483  };
484 
485  std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
486  std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
487  externalize);
488  std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
489  externalize);
490 }
491 
492 void LTOCodeGenerator::verifyMergedModuleOnce() {
493  // Only run on the first call.
494  if (HasVerifiedInput)
495  return;
496  HasVerifiedInput = true;
497 
498  bool BrokenDebugInfo = false;
499  if (verifyModule(*MergedModule, &dbgs(),
500  LTOStripInvalidDebugInfo ? &BrokenDebugInfo : nullptr))
501  report_fatal_error("Broken module found, compilation aborted!");
502  if (BrokenDebugInfo) {
503  emitWarning("Invalid debug info found, debug info will be stripped");
504  StripDebugInfo(*MergedModule);
505  }
506 }
507 
508 void LTOCodeGenerator::finishOptimizationRemarks() {
509  if (DiagnosticOutputFile) {
510  DiagnosticOutputFile->keep();
511  // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
512  DiagnosticOutputFile->os().flush();
513  }
514 }
515 
516 /// Optimize merged modules using various IPO passes
517 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
518  bool DisableGVNLoadPRE,
519  bool DisableVectorization) {
520  if (!this->determineTarget())
521  return false;
522 
523  auto DiagFileOrErr = lto::setupOptimizationRemarks(
525  if (!DiagFileOrErr) {
526  errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
527  report_fatal_error("Can't get an output file for the remarks");
528  }
529  DiagnosticOutputFile = std::move(*DiagFileOrErr);
530 
531  // We always run the verifier once on the merged module, the `DisableVerify`
532  // parameter only applies to subsequent verify.
533  verifyMergedModuleOnce();
534 
535  // Mark which symbols can not be internalized
536  this->applyScopeRestrictions();
537 
538  // Instantiate the pass manager to organize the passes.
539  legacy::PassManager passes;
540 
541  // Add an appropriate DataLayout instance for this module...
542  MergedModule->setDataLayout(TargetMach->createDataLayout());
543 
544  passes.add(
545  createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
546 
547  Triple TargetTriple(TargetMach->getTargetTriple());
548  PassManagerBuilder PMB;
549  PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
550  PMB.LoopVectorize = !DisableVectorization;
551  PMB.SLPVectorize = !DisableVectorization;
552  if (!DisableInline)
553  PMB.Inliner = createFunctionInliningPass();
554  PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
555  if (Freestanding)
556  PMB.LibraryInfo->disableAllFunctions();
557  PMB.OptLevel = OptLevel;
558  PMB.VerifyInput = !DisableVerify;
559  PMB.VerifyOutput = !DisableVerify;
560 
561  PMB.populateLTOPassManager(passes);
562 
563  // Run our queue of passes all at once now, efficiently.
564  passes.run(*MergedModule);
565 
566  return true;
567 }
568 
570  if (!this->determineTarget())
571  return false;
572 
573  // We always run the verifier once on the merged module. If it has already
574  // been called in optimize(), this call will return early.
575  verifyMergedModuleOnce();
576 
577  legacy::PassManager preCodeGenPasses;
578 
579  // If the bitcode files contain ARC code and were compiled with optimization,
580  // the ObjCARCContractPass must be run, so do it unconditionally here.
581  preCodeGenPasses.add(createObjCARCContractPass());
582  preCodeGenPasses.run(*MergedModule);
583 
584  // Re-externalize globals that may have been internalized to increase scope
585  // for splitting
586  restoreLinkageForExternals();
587 
588  // Do code generation. We need to preserve the module in case the client calls
589  // writeMergedModules() after compilation, but we only need to allow this at
590  // parallelism level 1. This is achieved by having splitCodeGen return the
591  // original module at parallelism level 1 which we then assign back to
592  // MergedModule.
593  MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
594  [&]() { return createTargetMachine(); }, FileType,
595  ShouldRestoreGlobalsLinkage);
596 
597  // If statistics were requested, print them out after codegen.
601 
602  finishOptimizationRemarks();
603 
604  return true;
605 }
606 
607 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
608 /// LTO problems.
610  for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
611  o = getToken(o.second))
612  CodegenOptions.push_back(o.first);
613 }
614 
616  // if options were requested, set them
617  if (!CodegenOptions.empty()) {
618  // ParseCommandLineOptions() expects argv[0] to be program name.
619  std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
620  for (std::string &Arg : CodegenOptions)
621  CodegenArgv.push_back(Arg.c_str());
622  cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
623  }
624 }
625 
626 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
627  void *Context) {
628  ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
629 }
630 
631 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
632  // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
634  switch (DI.getSeverity()) {
635  case DS_Error:
636  Severity = LTO_DS_ERROR;
637  break;
638  case DS_Warning:
639  Severity = LTO_DS_WARNING;
640  break;
641  case DS_Remark:
642  Severity = LTO_DS_REMARK;
643  break;
644  case DS_Note:
645  Severity = LTO_DS_NOTE;
646  break;
647  }
648  // Create the string that will be reported to the external diagnostic handler.
649  std::string MsgStorage;
650  raw_string_ostream Stream(MsgStorage);
651  DiagnosticPrinterRawOStream DP(Stream);
652  DI.print(DP);
653  Stream.flush();
654 
655  // If this method has been called it means someone has set up an external
656  // diagnostic handler. Assert on that.
657  assert(DiagHandler && "Invalid diagnostic handler");
658  (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
659 }
660 
661 void
663  void *Ctxt) {
664  this->DiagHandler = DiagHandler;
665  this->DiagContext = Ctxt;
666  if (!DiagHandler)
667  return Context.setDiagnosticHandler(nullptr, nullptr);
668  // Register the LTOCodeGenerator stub in the LLVMContext to forward the
669  // diagnostic to the external DiagHandler.
670  Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
671  /* RespectFilters */ true);
672 }
673 
674 namespace {
675 class LTODiagnosticInfo : public DiagnosticInfo {
676  const Twine &Msg;
677 public:
678  LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
679  : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
680  void print(DiagnosticPrinter &DP) const override { DP << Msg; }
681 };
682 }
683 
684 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
685  if (DiagHandler)
686  (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
687  else
688  Context.diagnose(LTODiagnosticInfo(ErrMsg));
689 }
690 
691 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
692  if (DiagHandler)
693  (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
694  else
695  Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
696 }
void initializeDCELegacyPassPass(PassRegistry &)
std::error_code getError() const
Definition: ErrorOr.h:172
void initializeGlobalOptLegacyPassPass(PassRegistry &)
Represents either an error or a value T.
Definition: ErrorOr.h:69
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & Context
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
void initializeInternalizeLegacyPassPass(PassRegistry &)
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
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:103
cl::opt< std::string > LTORemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
std::unique_ptr< MemoryBuffer > compileOptimized()
Compiles the merged optimized module into a single output file.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
void initializeSimpleInlinerPass(PassRegistry &)
void initializeJumpThreadingPass(PassRegistry &)
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
lto_codegen_diagnostic_severity_t
Diagnostic severity.
Definition: lto.h:305
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
void enableDebugTypeODRUniquing()
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:89
void initializeGlobalDCELegacyPassPass(PassRegistry &)
raw_fd_ostream & os()
Return the contained raw_fd_ostream.
bool addModule(struct LTOModule *)
Merge given module.
Implementation of the target library information.
bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
Optimizes the merged module.
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
void reserve(size_type N)
Definition: SmallVector.h:377
void reportAndResetTimings()
If -time-passes has been specified, report the timings immediately and then reset the timers to zero...
std::unique_ptr< Module > takeModule()
Definition: LTOModule.h:118
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
void initializeReversePostOrderFunctionAttrsLegacyPassPass(PassRegistry &)
static void externalize(GlobalValue *GV)
void initializePruneEHPass(PassRegistry &)
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:578
void add(Pass *P) override
Add a pass to the queue of passes to run.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
Definition: raw_ostream.h:428
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
void initializeArgPromotionPass(PassRegistry &)
cl::opt< bool > LTOStripInvalidDebugInfo("lto-strip-invalid-debug-info", cl::desc("Strip invalid debug info metadata during LTO instead of aborting."), cl::init(false), cl::Hidden)
std::unique_ptr< MemoryBuffer > compile(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
As with compile_to_file(), this function compiles the merged module into single output file...
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:359
Interface for custom diagnostic printing.
const Module & getModule() const
Definition: LTOModule.h:115
bool writeMergedModules(StringRef Path)
Write the merged module to the file specified by the given path.
cl::opt< bool > LTOPassRemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
Pass * createObjCARCContractPass()
static const char * getVersionString()
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:325
This class provides the core functionality of linking in LLVM.
Definition: Linker.h:25
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:281
DiagnosticSeverity getSeverity() const
const char * Name
lto_debug_model
Definition: lto.h:77
void initializeGVNLegacyPassPass(PassRegistry &)
PassManager manages ModulePassManagers.
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.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
std::string ErrMsg
This is the base abstract class for diagnostic reporting in the backend.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
void initializeLateCFGSimplifyPassPass(PassRegistry &)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Expected< std::unique_ptr< tool_output_file > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1117
void initializeSROALegacyPassPass(PassRegistry &)
void setOptLevel(unsigned OptLevel)
void setTargetOptions(const TargetOptions &Options)
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
C++ class which implements the opaque lto_module_t type.
Definition: LTOModule.h:38
bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr)
void setCodeGenDebugOptions(StringRef Opts)
Pass options to the driver and optimization passes.
void initializeMemCpyOptLegacyPassPass(PassRegistry &)
void initializeConstantMergeLegacyPassPass(PassRegistry &)
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
void(* lto_diagnostic_handler_t)(lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt)
Diagnostic handler type.
Definition: lto.h:321
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
C++ class which implements the opaque lto_code_gen_t type.
void initializeGlobalsAAWrapperPassPass(PassRegistry &)
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
Definition: Triple.h:466
const std::vector< StringRef > & getAsmUndefinedRefs()
Definition: LTOModule.h:157
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Optional< Reloc::Model > RM, CodeModel::Model CM=CodeModel::Default, CodeGenOpt::Level OL=CodeGenOpt::Default) const
createTargetMachine - Create a target specific machine implementation for the specified Triple...
void for_each(Policy policy, IterTy Begin, IterTy End, FuncTy Fn)
Definition: Parallel.h:209
Module.h This file contains the declarations for the Module class.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Manages the enabling and disabling of subtarget specific features.
void initializeDAHPass(PassRegistry &)
#define NDEBUG
Definition: regutils.h:48
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
Definition: Verifier.cpp:4624
llvm_unreachable("Unknown RegBank!")
Basic diagnostic printer that uses an underlying raw_ostream.
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
void keep()
Indicate that the tool's job wrt this output file has been successful and the file should not be dele...
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:109
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath)
Create a file in the system temporary directory.
Definition: Path.cpp:783
void initializePostOrderFunctionAttrsLegacyPassPass(PassRegistry &)
void initializeIPSCCPLegacyPassPass(PassRegistry &)
const char * c_str()
Definition: SmallString.h:270
#define I(x, y, z)
Definition: MD5.cpp:58
bool compile_to_file(const char **Name, bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization)
Compile the merged module into a single output file; the path to output file is returned to the calle...
void initializeInstructionCombiningPassPass(PassRegistry &)
void close()
Manually flush the stream and close the file.
void updateCompilerUsed(Module &TheModule, const TargetMachine &TM, const StringSet<> &AsmUndefinedRefs)
Find all globals in TheModule that are referenced in AsmUndefinedRefs, as well as the user-supplied f...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
void setAsmUndefinedRefs(struct LTOModule *)
void initializeCFGSimplifyPassPass(PassRegistry &)
void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
Definition: Statistic.cpp:183
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:463
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
static const char * name
LTOCodeGenerator(LLVMContext &Context)
static cl::opt< bool, true > Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag))
const FeatureBitset Features
void initializeLegacyLICMPassPass(PassRegistry &)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:40
This pass exposes codegen information to IR-level passes.
void parseCodeGenDebugOptions()
Parse the options set in setCodeGenDebugOptions.
void setModule(std::unique_ptr< LTOModule > M)
Set the destination module.
void initializeMergedLoadStoreMotionLegacyPassPass(PassRegistry &)
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 FT=TargetMachine::CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
Definition: ParallelCG.cpp:39
bool internalizeModule(Module &TheModule, std::function< bool(const GlobalValue &)> MustPreserveGV, CallGraph *CG=nullptr)
Helper function to internalize functions and variables in a Module.
Definition: Internalize.h:71
bool AreStatisticsEnabled()
Check if statistics are enabled.
Definition: Statistic.cpp:112
void setDiagnosticHandler(lto_diagnostic_handler_t, void *)
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237
This file describes how to lower LLVM code to machine code.
void clear_error()
Set the flag read by has_error() to false.
Definition: raw_ostream.h:441
void setDebugInfo(lto_debug_model)