LLVM  4.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"
40 #include "llvm/Linker/Linker.h"
41 #include "llvm/MC/MCAsmInfo.h"
42 #include "llvm/MC/MCContext.h"
46 #include "llvm/Support/Host.h"
48 #include "llvm/Support/Signals.h"
58 #include "llvm/Transforms/IPO.h"
63 #include <system_error>
64 using namespace llvm;
65 
67 #ifdef LLVM_VERSION_INFO
68  return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
69 #else
70  return PACKAGE_NAME " version " PACKAGE_VERSION;
71 #endif
72 }
73 
74 namespace llvm {
76  "lto-discard-value-names",
77  cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
78 #ifdef NDEBUG
79  cl::init(true),
80 #else
81  cl::init(false),
82 #endif
83  cl::Hidden);
84 
86  "lto-strip-invalid-debug-info",
87  cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
88 #ifdef NDEBUG
89  cl::init(true),
90 #else
91  cl::init(false),
92 #endif
93  cl::Hidden);
94 
96  LTORemarksFilename("lto-pass-remarks-output",
97  cl::desc("Output filename for pass remarks"),
98  cl::value_desc("filename"));
99 
101  "lto-pass-remarks-with-hotness",
102  cl::desc("With PGO, include profile count in optimization remarks"),
103  cl::Hidden);
104 }
105 
107  : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
108  TheLinker(new Linker(*MergedModule)) {
110  Context.enableDebugTypeODRUniquing();
111  initializeLTOPasses();
112 }
113 
115 
116 // Initialize LTO passes. Please keep this function in sync with
117 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
118 // passes are initialized.
119 void LTOCodeGenerator::initializeLTOPasses() {
121 
143 }
144 
146  const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
147  for (int i = 0, e = undefs.size(); i != e; ++i)
148  AsmUndefinedRefs[undefs[i]] = 1;
149 }
150 
152  assert(&Mod->getModule().getContext() == &Context &&
153  "Expected module in same context");
154 
155  bool ret = TheLinker->linkInModule(Mod->takeModule());
156  setAsmUndefinedRefs(Mod);
157 
158  // We've just changed the input, so let's make sure we verify it.
159  HasVerifiedInput = false;
160 
161  return !ret;
162 }
163 
164 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
165  assert(&Mod->getModule().getContext() == &Context &&
166  "Expected module in same context");
167 
168  AsmUndefinedRefs.clear();
169 
170  MergedModule = Mod->takeModule();
171  TheLinker = make_unique<Linker>(*MergedModule);
172  setAsmUndefinedRefs(&*Mod);
173 
174  // We've just changed the input, so let's make sure we verify it.
175  HasVerifiedInput = false;
176 }
177 
179  this->Options = Options;
180 }
181 
183  switch (Debug) {
185  EmitDwarfDebugInfo = false;
186  return;
187 
189  EmitDwarfDebugInfo = true;
190  return;
191  }
192  llvm_unreachable("Unknown debug format!");
193 }
194 
196  OptLevel = Level;
197  switch (OptLevel) {
198  case 0:
199  CGOptLevel = CodeGenOpt::None;
200  return;
201  case 1:
202  CGOptLevel = CodeGenOpt::Less;
203  return;
204  case 2:
205  CGOptLevel = CodeGenOpt::Default;
206  return;
207  case 3:
208  CGOptLevel = CodeGenOpt::Aggressive;
209  return;
210  }
211  llvm_unreachable("Unknown optimization level!");
212 }
213 
215  if (!determineTarget())
216  return false;
217 
218  // We always run the verifier once on the merged module.
219  verifyMergedModuleOnce();
220 
221  // mark which symbols can not be internalized
222  applyScopeRestrictions();
223 
224  // create output file
225  std::error_code EC;
226  tool_output_file Out(Path, EC, sys::fs::F_None);
227  if (EC) {
228  std::string ErrMsg = "could not open bitcode file for writing: ";
229  ErrMsg += Path;
230  emitError(ErrMsg);
231  return false;
232  }
233 
234  // write bitcode to it
235  WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
236  Out.os().close();
237 
238  if (Out.os().has_error()) {
239  std::string ErrMsg = "could not write bitcode file: ";
240  ErrMsg += Path;
241  emitError(ErrMsg);
242  Out.os().clear_error();
243  return false;
244  }
245 
246  Out.keep();
247  return true;
248 }
249 
250 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
251  // make unique temp output file to put generated code
252  SmallString<128> Filename;
253  int FD;
254 
255  StringRef Extension
256  (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
257 
258  std::error_code EC =
259  sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
260  if (EC) {
261  emitError(EC.message());
262  return false;
263  }
264 
265  // generate object file
266  tool_output_file objFile(Filename, FD);
267 
268  bool genResult = compileOptimized(&objFile.os());
269  objFile.os().close();
270  if (objFile.os().has_error()) {
271  emitError((Twine("could not write object file: ") + Filename).str());
272  objFile.os().clear_error();
273  sys::fs::remove(Twine(Filename));
274  return false;
275  }
276 
277  objFile.keep();
278  if (!genResult) {
279  sys::fs::remove(Twine(Filename));
280  return false;
281  }
282 
283  NativeObjectPath = Filename.c_str();
284  *Name = NativeObjectPath.c_str();
285  return true;
286 }
287 
288 std::unique_ptr<MemoryBuffer>
290  const char *name;
291  if (!compileOptimizedToFile(&name))
292  return nullptr;
293 
294  // read .o file into memory buffer
296  MemoryBuffer::getFile(name, -1, false);
297  if (std::error_code EC = BufferOrErr.getError()) {
298  emitError(EC.message());
299  sys::fs::remove(NativeObjectPath);
300  return nullptr;
301  }
302 
303  // remove temp files
304  sys::fs::remove(NativeObjectPath);
305 
306  return std::move(*BufferOrErr);
307 }
308 
309 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
310  bool DisableInline,
311  bool DisableGVNLoadPRE,
312  bool DisableVectorization) {
313  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
314  DisableVectorization))
315  return false;
316 
317  return compileOptimizedToFile(Name);
318 }
319 
320 std::unique_ptr<MemoryBuffer>
321 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
322  bool DisableGVNLoadPRE, bool DisableVectorization) {
323  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
324  DisableVectorization))
325  return nullptr;
326 
327  return compileOptimized();
328 }
329 
330 bool LTOCodeGenerator::determineTarget() {
331  if (TargetMach)
332  return true;
333 
334  TripleStr = MergedModule->getTargetTriple();
335  if (TripleStr.empty()) {
336  TripleStr = sys::getDefaultTargetTriple();
337  MergedModule->setTargetTriple(TripleStr);
338  }
339  llvm::Triple Triple(TripleStr);
340 
341  // create target machine from info for merged modules
342  std::string ErrMsg;
343  MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
344  if (!MArch) {
345  emitError(ErrMsg);
346  return false;
347  }
348 
349  // Construct LTOModule, hand over ownership of module and target. Use MAttr as
350  // the default set of features.
352  Features.getDefaultSubtargetFeatures(Triple);
353  FeatureStr = Features.getString();
354  // Set a default CPU for Darwin triples.
355  if (MCpu.empty() && Triple.isOSDarwin()) {
357  MCpu = "core2";
358  else if (Triple.getArch() == llvm::Triple::x86)
359  MCpu = "yonah";
360  else if (Triple.getArch() == llvm::Triple::aarch64)
361  MCpu = "cyclone";
362  }
363 
364  TargetMach = createTargetMachine();
365  return true;
366 }
367 
368 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
369  return std::unique_ptr<TargetMachine>(
370  MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
371  RelocModel, CodeModel::Default, CGOptLevel));
372 }
373 
374 // If a linkonce global is present in the MustPreserveSymbols, we need to make
375 // sure we honor this. To force the compiler to not drop it, we add it to the
376 // "llvm.compiler.used" global.
377 void LTOCodeGenerator::preserveDiscardableGVs(
378  Module &TheModule,
379  llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
380  std::vector<GlobalValue *> Used;
381  auto mayPreserveGlobal = [&](GlobalValue &GV) {
382  if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
383  !mustPreserveGV(GV))
384  return;
385  if (GV.hasAvailableExternallyLinkage())
386  return emitWarning(
387  (Twine("Linker asked to preserve available_externally global: '") +
388  GV.getName() + "'").str());
389  if (GV.hasInternalLinkage())
390  return emitWarning((Twine("Linker asked to preserve internal global: '") +
391  GV.getName() + "'").str());
392  Used.push_back(&GV);
393  };
394  for (auto &GV : TheModule)
395  mayPreserveGlobal(GV);
396  for (auto &GV : TheModule.globals())
397  mayPreserveGlobal(GV);
398  for (auto &GV : TheModule.aliases())
399  mayPreserveGlobal(GV);
400 
401  if (Used.empty())
402  return;
403 
404  appendToCompilerUsed(TheModule, Used);
405 }
406 
407 void LTOCodeGenerator::applyScopeRestrictions() {
408  if (ScopeRestrictionsDone)
409  return;
410 
411  // Declare a callback for the internalize pass that will ask for every
412  // candidate GlobalValue if it can be internalized or not.
413  Mangler Mang;
414  SmallString<64> MangledName;
415  auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
416  // Unnamed globals can't be mangled, but they can't be preserved either.
417  if (!GV.hasName())
418  return false;
419 
420  // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
421  // with the linker supplied name, which on Darwin includes a leading
422  // underscore.
423  MangledName.clear();
424  MangledName.reserve(GV.getName().size() + 1);
425  Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
426  return MustPreserveSymbols.count(MangledName);
427  };
428 
429  // Preserve linkonce value on linker request
430  preserveDiscardableGVs(*MergedModule, mustPreserveGV);
431 
432  if (!ShouldInternalize)
433  return;
434 
435  if (ShouldRestoreGlobalsLinkage) {
436  // Record the linkage type of non-local symbols so they can be restored
437  // prior
438  // to module splitting.
439  auto RecordLinkage = [&](const GlobalValue &GV) {
440  if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
441  GV.hasName())
442  ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
443  };
444  for (auto &GV : *MergedModule)
445  RecordLinkage(GV);
446  for (auto &GV : MergedModule->globals())
447  RecordLinkage(GV);
448  for (auto &GV : MergedModule->aliases())
449  RecordLinkage(GV);
450  }
451 
452  // Update the llvm.compiler_used globals to force preserving libcalls and
453  // symbols referenced from asm
454  updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
455 
456  internalizeModule(*MergedModule, mustPreserveGV);
457 
458  ScopeRestrictionsDone = true;
459 }
460 
461 /// Restore original linkage for symbols that may have been internalized
462 void LTOCodeGenerator::restoreLinkageForExternals() {
463  if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
464  return;
465 
466  assert(ScopeRestrictionsDone &&
467  "Cannot externalize without internalization!");
468 
469  if (ExternalSymbols.empty())
470  return;
471 
472  auto externalize = [this](GlobalValue &GV) {
473  if (!GV.hasLocalLinkage() || !GV.hasName())
474  return;
475 
476  auto I = ExternalSymbols.find(GV.getName());
477  if (I == ExternalSymbols.end())
478  return;
479 
480  GV.setLinkage(I->second);
481  };
482 
483  std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
484  std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
485  externalize);
486  std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
487  externalize);
488 }
489 
490 void LTOCodeGenerator::verifyMergedModuleOnce() {
491  // Only run on the first call.
492  if (HasVerifiedInput)
493  return;
494  HasVerifiedInput = true;
495 
497  bool BrokenDebugInfo = false;
498  if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
499  report_fatal_error("Broken module found, compilation aborted!");
500  if (BrokenDebugInfo) {
501  emitWarning("Invalid debug info found, debug info will be stripped");
502  StripDebugInfo(*MergedModule);
503  }
504  }
505  if (verifyModule(*MergedModule, &dbgs()))
506  report_fatal_error("Broken module found, compilation aborted!");
507 }
508 
509 bool LTOCodeGenerator::setupOptimizationRemarks() {
510  if (LTORemarksFilename != "") {
511  std::error_code EC;
512  DiagnosticOutputFile = llvm::make_unique<tool_output_file>(
514  if (EC) {
515  emitError(EC.message());
516  return false;
517  }
518  Context.setDiagnosticsOutputFile(
519  llvm::make_unique<yaml::Output>(DiagnosticOutputFile->os()));
520  }
521 
523  Context.setDiagnosticHotnessRequested(true);
524 
525  return true;
526 }
527 
528 void LTOCodeGenerator::finishOptimizationRemarks() {
529  if (DiagnosticOutputFile) {
530  DiagnosticOutputFile->keep();
531  // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
532  DiagnosticOutputFile->os().flush();
533  }
534 }
535 
536 /// Optimize merged modules using various IPO passes
537 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
538  bool DisableGVNLoadPRE,
539  bool DisableVectorization) {
540  if (!this->determineTarget())
541  return false;
542 
543  if (!setupOptimizationRemarks())
544  return false;
545 
546  // We always run the verifier once on the merged module, the `DisableVerify`
547  // parameter only applies to subsequent verify.
548  verifyMergedModuleOnce();
549 
550  // Mark which symbols can not be internalized
551  this->applyScopeRestrictions();
552 
553  // Instantiate the pass manager to organize the passes.
554  legacy::PassManager passes;
555 
556  // Add an appropriate DataLayout instance for this module...
557  MergedModule->setDataLayout(TargetMach->createDataLayout());
558 
559  passes.add(
560  createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
561 
562  Triple TargetTriple(TargetMach->getTargetTriple());
563  PassManagerBuilder PMB;
564  PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
565  PMB.LoopVectorize = !DisableVectorization;
566  PMB.SLPVectorize = !DisableVectorization;
567  if (!DisableInline)
568  PMB.Inliner = createFunctionInliningPass();
569  PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
570  PMB.OptLevel = OptLevel;
571  PMB.VerifyInput = !DisableVerify;
572  PMB.VerifyOutput = !DisableVerify;
573 
574  PMB.populateLTOPassManager(passes);
575 
576  // Run our queue of passes all at once now, efficiently.
577  passes.run(*MergedModule);
578 
579  return true;
580 }
581 
583  if (!this->determineTarget())
584  return false;
585 
586  // We always run the verifier once on the merged module. If it has already
587  // been called in optimize(), this call will return early.
588  verifyMergedModuleOnce();
589 
590  legacy::PassManager preCodeGenPasses;
591 
592  // If the bitcode files contain ARC code and were compiled with optimization,
593  // the ObjCARCContractPass must be run, so do it unconditionally here.
594  preCodeGenPasses.add(createObjCARCContractPass());
595  preCodeGenPasses.run(*MergedModule);
596 
597  // Re-externalize globals that may have been internalized to increase scope
598  // for splitting
599  restoreLinkageForExternals();
600 
601  // Do code generation. We need to preserve the module in case the client calls
602  // writeMergedModules() after compilation, but we only need to allow this at
603  // parallelism level 1. This is achieved by having splitCodeGen return the
604  // original module at parallelism level 1 which we then assign back to
605  // MergedModule.
606  MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
607  [&]() { return createTargetMachine(); }, FileType,
608  ShouldRestoreGlobalsLinkage);
609 
610  // If statistics were requested, print them out after codegen.
613 
614  finishOptimizationRemarks();
615 
616  return true;
617 }
618 
619 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
620 /// LTO problems.
622  for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
623  o = getToken(o.second))
624  CodegenOptions.push_back(o.first);
625 }
626 
628  // if options were requested, set them
629  if (!CodegenOptions.empty()) {
630  // ParseCommandLineOptions() expects argv[0] to be program name.
631  std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
632  for (std::string &Arg : CodegenOptions)
633  CodegenArgv.push_back(Arg.c_str());
634  cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
635  }
636 }
637 
638 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
639  void *Context) {
640  ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
641 }
642 
643 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
644  // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
646  switch (DI.getSeverity()) {
647  case DS_Error:
648  Severity = LTO_DS_ERROR;
649  break;
650  case DS_Warning:
651  Severity = LTO_DS_WARNING;
652  break;
653  case DS_Remark:
654  Severity = LTO_DS_REMARK;
655  break;
656  case DS_Note:
657  Severity = LTO_DS_NOTE;
658  break;
659  }
660  // Create the string that will be reported to the external diagnostic handler.
661  std::string MsgStorage;
662  raw_string_ostream Stream(MsgStorage);
663  DiagnosticPrinterRawOStream DP(Stream);
664  DI.print(DP);
665  Stream.flush();
666 
667  // If this method has been called it means someone has set up an external
668  // diagnostic handler. Assert on that.
669  assert(DiagHandler && "Invalid diagnostic handler");
670  (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
671 }
672 
673 void
675  void *Ctxt) {
676  this->DiagHandler = DiagHandler;
677  this->DiagContext = Ctxt;
678  if (!DiagHandler)
679  return Context.setDiagnosticHandler(nullptr, nullptr);
680  // Register the LTOCodeGenerator stub in the LLVMContext to forward the
681  // diagnostic to the external DiagHandler.
682  Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
683  /* RespectFilters */ true);
684 }
685 
686 namespace {
687 class LTODiagnosticInfo : public DiagnosticInfo {
688  const Twine &Msg;
689 public:
690  LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
691  : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
692  void print(DiagnosticPrinter &DP) const override { DP << Msg; }
693 };
694 }
695 
696 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
697  if (DiagHandler)
698  (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
699  else
700  Context.diagnose(LTODiagnosticInfo(ErrMsg));
701 }
702 
703 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
704  if (DiagHandler)
705  (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
706  else
707  Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
708 }
void initializeDCELegacyPassPass(PassRegistry &)
std::error_code getError() const
Definition: ErrorOr.h:169
void initializeGlobalOptLegacyPassPass(PassRegistry &)
Represents either an error or a value T.
Definition: ErrorOr.h:68
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.
size_t i
void setDiagnosticsOutputFile(std::unique_ptr< yaml::Output > F)
Set the diagnostics output file used for optimization diagnostics.
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:52
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:83
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
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 &)
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 setDiagnosticHotnessRequested(bool Requested)
Set if a code hotness metric should be included in optimization diagnostics.
void initializeArgPromotionPass(PassRegistry &)
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:341
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:266
This class provides the core functionality of linking in LLVM.
Definition: Linker/Linker.h:24
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:270
DiagnosticSeverity getSeverity() const
bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", bool IgnoreErrors=false)
lto_debug_model
Definition: lto.h:77
void initializeGVNLegacyPassPass(PassRegistry &)
PassManager manages ModulePassManagers.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
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:48
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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:455
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...
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
SubtargetFeatures - 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:4441
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 WriteBitcodeToFile(const Module *M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false)
Write the specified module to the specified raw output stream.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatileSize=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
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:108
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:794
void initializePostOrderFunctionAttrsLegacyPassPass(PassRegistry &)
void initializeIPSCCPLegacyPassPass(PassRegistry &)
const char * c_str()
Definition: SmallString.h:270
#define I(x, y, z)
Definition: MD5.cpp:54
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...
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:47
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
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)
void setDiagnosticHandler(lto_diagnostic_handler_t, void *)
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:222
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)