LLVM  6.0.0svn
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"
28 #include "llvm/Config/config.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Mangler.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Verifier.h"
40 #include "llvm/InitializePasses.h"
41 #include "llvm/LTO/LTO.h"
44 #include "llvm/Linker/Linker.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
50 #include "llvm/Support/Host.h"
52 #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  LTORemarksFilename("lto-pass-remarks-output",
88  cl::desc("Output filename for pass remarks"),
89  cl::value_desc("filename"));
90 
92  "lto-pass-remarks-with-hotness",
93  cl::desc("With PGO, include profile count in optimization remarks"),
94  cl::Hidden);
95 }
96 
98  : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
99  TheLinker(new Linker(*MergedModule)) {
101  Context.enableDebugTypeODRUniquing();
102  initializeLTOPasses();
103 }
104 
106 
107 // Initialize LTO passes. Please keep this function in sync with
108 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
109 // passes are initialized.
110 void LTOCodeGenerator::initializeLTOPasses() {
112 
134 }
135 
137  const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
138  for (int i = 0, e = undefs.size(); i != e; ++i)
139  AsmUndefinedRefs[undefs[i]] = 1;
140 }
141 
143  assert(&Mod->getModule().getContext() == &Context &&
144  "Expected module in same context");
145 
146  bool ret = TheLinker->linkInModule(Mod->takeModule());
147  setAsmUndefinedRefs(Mod);
148 
149  // We've just changed the input, so let's make sure we verify it.
150  HasVerifiedInput = false;
151 
152  return !ret;
153 }
154 
155 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
156  assert(&Mod->getModule().getContext() == &Context &&
157  "Expected module in same context");
158 
159  AsmUndefinedRefs.clear();
160 
161  MergedModule = Mod->takeModule();
162  TheLinker = make_unique<Linker>(*MergedModule);
163  setAsmUndefinedRefs(&*Mod);
164 
165  // We've just changed the input, so let's make sure we verify it.
166  HasVerifiedInput = false;
167 }
168 
170  this->Options = Options;
171 }
172 
174  switch (Debug) {
176  EmitDwarfDebugInfo = false;
177  return;
178 
180  EmitDwarfDebugInfo = true;
181  return;
182  }
183  llvm_unreachable("Unknown debug format!");
184 }
185 
187  OptLevel = Level;
188  switch (OptLevel) {
189  case 0:
190  CGOptLevel = CodeGenOpt::None;
191  return;
192  case 1:
193  CGOptLevel = CodeGenOpt::Less;
194  return;
195  case 2:
196  CGOptLevel = CodeGenOpt::Default;
197  return;
198  case 3:
199  CGOptLevel = CodeGenOpt::Aggressive;
200  return;
201  }
202  llvm_unreachable("Unknown optimization level!");
203 }
204 
206  if (!determineTarget())
207  return false;
208 
209  // We always run the verifier once on the merged module.
210  verifyMergedModuleOnce();
211 
212  // mark which symbols can not be internalized
213  applyScopeRestrictions();
214 
215  // create output file
216  std::error_code EC;
217  ToolOutputFile Out(Path, EC, sys::fs::F_None);
218  if (EC) {
219  std::string ErrMsg = "could not open bitcode file for writing: ";
220  ErrMsg += Path.str() + ": " + EC.message();
221  emitError(ErrMsg);
222  return false;
223  }
224 
225  // write bitcode to it
226  WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
227  Out.os().close();
228 
229  if (Out.os().has_error()) {
230  std::string ErrMsg = "could not write bitcode file: ";
231  ErrMsg += Path.str() + ": " + Out.os().error().message();
232  emitError(ErrMsg);
233  Out.os().clear_error();
234  return false;
235  }
236 
237  Out.keep();
238  return true;
239 }
240 
241 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
242  // make unique temp output file to put generated code
243  SmallString<128> Filename;
244  int FD;
245 
246  StringRef Extension
247  (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
248 
249  std::error_code EC =
250  sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
251  if (EC) {
252  emitError(EC.message());
253  return false;
254  }
255 
256  // generate object file
257  ToolOutputFile objFile(Filename, FD);
258 
259  bool genResult = compileOptimized(&objFile.os());
260  objFile.os().close();
261  if (objFile.os().has_error()) {
262  emitError((Twine("could not write object file: ") + Filename + ": " +
263  objFile.os().error().message())
264  .str());
265  objFile.os().clear_error();
266  sys::fs::remove(Twine(Filename));
267  return false;
268  }
269 
270  objFile.keep();
271  if (!genResult) {
272  sys::fs::remove(Twine(Filename));
273  return false;
274  }
275 
276  NativeObjectPath = Filename.c_str();
277  *Name = NativeObjectPath.c_str();
278  return true;
279 }
280 
281 std::unique_ptr<MemoryBuffer>
283  const char *name;
284  if (!compileOptimizedToFile(&name))
285  return nullptr;
286 
287  // read .o file into memory buffer
289  MemoryBuffer::getFile(name, -1, false);
290  if (std::error_code EC = BufferOrErr.getError()) {
291  emitError(EC.message());
292  sys::fs::remove(NativeObjectPath);
293  return nullptr;
294  }
295 
296  // remove temp files
297  sys::fs::remove(NativeObjectPath);
298 
299  return std::move(*BufferOrErr);
300 }
301 
302 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
303  bool DisableInline,
304  bool DisableGVNLoadPRE,
305  bool DisableVectorization) {
306  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
307  DisableVectorization))
308  return false;
309 
310  return compileOptimizedToFile(Name);
311 }
312 
313 std::unique_ptr<MemoryBuffer>
314 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
315  bool DisableGVNLoadPRE, bool DisableVectorization) {
316  if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
317  DisableVectorization))
318  return nullptr;
319 
320  return compileOptimized();
321 }
322 
323 bool LTOCodeGenerator::determineTarget() {
324  if (TargetMach)
325  return true;
326 
327  TripleStr = MergedModule->getTargetTriple();
328  if (TripleStr.empty()) {
329  TripleStr = sys::getDefaultTargetTriple();
330  MergedModule->setTargetTriple(TripleStr);
331  }
332  llvm::Triple Triple(TripleStr);
333 
334  // create target machine from info for merged modules
335  std::string ErrMsg;
336  MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
337  if (!MArch) {
338  emitError(ErrMsg);
339  return false;
340  }
341 
342  // Construct LTOModule, hand over ownership of module and target. Use MAttr as
343  // the default set of features.
345  Features.getDefaultSubtargetFeatures(Triple);
346  FeatureStr = Features.getString();
347  // Set a default CPU for Darwin triples.
348  if (MCpu.empty() && Triple.isOSDarwin()) {
349  if (Triple.getArch() == llvm::Triple::x86_64)
350  MCpu = "core2";
351  else if (Triple.getArch() == llvm::Triple::x86)
352  MCpu = "yonah";
353  else if (Triple.getArch() == llvm::Triple::aarch64)
354  MCpu = "cyclone";
355  }
356 
357  TargetMach = createTargetMachine();
358  return true;
359 }
360 
361 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
362  return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
363  TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
364 }
365 
366 // If a linkonce global is present in the MustPreserveSymbols, we need to make
367 // sure we honor this. To force the compiler to not drop it, we add it to the
368 // "llvm.compiler.used" global.
369 void LTOCodeGenerator::preserveDiscardableGVs(
370  Module &TheModule,
372  std::vector<GlobalValue *> Used;
373  auto mayPreserveGlobal = [&](GlobalValue &GV) {
374  if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
375  !mustPreserveGV(GV))
376  return;
377  if (GV.hasAvailableExternallyLinkage())
378  return emitWarning(
379  (Twine("Linker asked to preserve available_externally global: '") +
380  GV.getName() + "'").str());
381  if (GV.hasInternalLinkage())
382  return emitWarning((Twine("Linker asked to preserve internal global: '") +
383  GV.getName() + "'").str());
384  Used.push_back(&GV);
385  };
386  for (auto &GV : TheModule)
387  mayPreserveGlobal(GV);
388  for (auto &GV : TheModule.globals())
389  mayPreserveGlobal(GV);
390  for (auto &GV : TheModule.aliases())
391  mayPreserveGlobal(GV);
392 
393  if (Used.empty())
394  return;
395 
396  appendToCompilerUsed(TheModule, Used);
397 }
398 
399 void LTOCodeGenerator::applyScopeRestrictions() {
400  if (ScopeRestrictionsDone)
401  return;
402 
403  // Declare a callback for the internalize pass that will ask for every
404  // candidate GlobalValue if it can be internalized or not.
405  Mangler Mang;
406  SmallString<64> MangledName;
407  auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
408  // Unnamed globals can't be mangled, but they can't be preserved either.
409  if (!GV.hasName())
410  return false;
411 
412  // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
413  // with the linker supplied name, which on Darwin includes a leading
414  // underscore.
415  MangledName.clear();
416  MangledName.reserve(GV.getName().size() + 1);
417  Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
418  return MustPreserveSymbols.count(MangledName);
419  };
420 
421  // Preserve linkonce value on linker request
422  preserveDiscardableGVs(*MergedModule, mustPreserveGV);
423 
424  if (!ShouldInternalize)
425  return;
426 
427  if (ShouldRestoreGlobalsLinkage) {
428  // Record the linkage type of non-local symbols so they can be restored
429  // prior
430  // to module splitting.
431  auto RecordLinkage = [&](const GlobalValue &GV) {
432  if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
433  GV.hasName())
434  ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
435  };
436  for (auto &GV : *MergedModule)
437  RecordLinkage(GV);
438  for (auto &GV : MergedModule->globals())
439  RecordLinkage(GV);
440  for (auto &GV : MergedModule->aliases())
441  RecordLinkage(GV);
442  }
443 
444  // Update the llvm.compiler_used globals to force preserving libcalls and
445  // symbols referenced from asm
446  updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
447 
448  internalizeModule(*MergedModule, mustPreserveGV);
449 
450  ScopeRestrictionsDone = true;
451 }
452 
453 /// Restore original linkage for symbols that may have been internalized
454 void LTOCodeGenerator::restoreLinkageForExternals() {
455  if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
456  return;
457 
458  assert(ScopeRestrictionsDone &&
459  "Cannot externalize without internalization!");
460 
461  if (ExternalSymbols.empty())
462  return;
463 
464  auto externalize = [this](GlobalValue &GV) {
465  if (!GV.hasLocalLinkage() || !GV.hasName())
466  return;
467 
468  auto I = ExternalSymbols.find(GV.getName());
469  if (I == ExternalSymbols.end())
470  return;
471 
472  GV.setLinkage(I->second);
473  };
474 
475  llvm::for_each(MergedModule->functions(), externalize);
476  llvm::for_each(MergedModule->globals(), externalize);
477  llvm::for_each(MergedModule->aliases(), externalize);
478 }
479 
480 void LTOCodeGenerator::verifyMergedModuleOnce() {
481  // Only run on the first call.
482  if (HasVerifiedInput)
483  return;
484  HasVerifiedInput = true;
485 
486  bool BrokenDebugInfo = false;
487  if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
488  report_fatal_error("Broken module found, compilation aborted!");
489  if (BrokenDebugInfo) {
490  emitWarning("Invalid debug info found, debug info will be stripped");
491  StripDebugInfo(*MergedModule);
492  }
493 }
494 
495 void LTOCodeGenerator::finishOptimizationRemarks() {
496  if (DiagnosticOutputFile) {
497  DiagnosticOutputFile->keep();
498  // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
499  DiagnosticOutputFile->os().flush();
500  }
501 }
502 
503 /// Optimize merged modules using various IPO passes
504 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
505  bool DisableGVNLoadPRE,
506  bool DisableVectorization) {
507  if (!this->determineTarget())
508  return false;
509 
510  auto DiagFileOrErr = lto::setupOptimizationRemarks(
512  if (!DiagFileOrErr) {
513  errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
514  report_fatal_error("Can't get an output file for the remarks");
515  }
516  DiagnosticOutputFile = std::move(*DiagFileOrErr);
517 
518  // We always run the verifier once on the merged module, the `DisableVerify`
519  // parameter only applies to subsequent verify.
520  verifyMergedModuleOnce();
521 
522  // Mark which symbols can not be internalized
523  this->applyScopeRestrictions();
524 
525  // Instantiate the pass manager to organize the passes.
526  legacy::PassManager passes;
527 
528  // Add an appropriate DataLayout instance for this module...
529  MergedModule->setDataLayout(TargetMach->createDataLayout());
530 
531  passes.add(
532  createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
533 
534  Triple TargetTriple(TargetMach->getTargetTriple());
535  PassManagerBuilder PMB;
536  PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
537  PMB.LoopVectorize = !DisableVectorization;
538  PMB.SLPVectorize = !DisableVectorization;
539  if (!DisableInline)
540  PMB.Inliner = createFunctionInliningPass();
541  PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
542  if (Freestanding)
543  PMB.LibraryInfo->disableAllFunctions();
544  PMB.OptLevel = OptLevel;
545  PMB.VerifyInput = !DisableVerify;
546  PMB.VerifyOutput = !DisableVerify;
547 
548  PMB.populateLTOPassManager(passes);
549 
550  // Run our queue of passes all at once now, efficiently.
551  passes.run(*MergedModule);
552 
553  return true;
554 }
555 
557  if (!this->determineTarget())
558  return false;
559 
560  // We always run the verifier once on the merged module. If it has already
561  // been called in optimize(), this call will return early.
562  verifyMergedModuleOnce();
563 
564  legacy::PassManager preCodeGenPasses;
565 
566  // If the bitcode files contain ARC code and were compiled with optimization,
567  // the ObjCARCContractPass must be run, so do it unconditionally here.
568  preCodeGenPasses.add(createObjCARCContractPass());
569  preCodeGenPasses.run(*MergedModule);
570 
571  // Re-externalize globals that may have been internalized to increase scope
572  // for splitting
573  restoreLinkageForExternals();
574 
575  // Do code generation. We need to preserve the module in case the client calls
576  // writeMergedModules() after compilation, but we only need to allow this at
577  // parallelism level 1. This is achieved by having splitCodeGen return the
578  // original module at parallelism level 1 which we then assign back to
579  // MergedModule.
580  MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
581  [&]() { return createTargetMachine(); }, FileType,
582  ShouldRestoreGlobalsLinkage);
583 
584  // If statistics were requested, print them out after codegen.
588 
589  finishOptimizationRemarks();
590 
591  return true;
592 }
593 
594 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
595 /// LTO problems.
597  for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
598  o = getToken(o.second))
599  CodegenOptions.push_back(o.first);
600 }
601 
603  // if options were requested, set them
604  if (!CodegenOptions.empty()) {
605  // ParseCommandLineOptions() expects argv[0] to be program name.
606  std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
607  for (std::string &Arg : CodegenOptions)
608  CodegenArgv.push_back(Arg.c_str());
609  cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
610  }
611 }
612 
613 
615  // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
617  switch (DI.getSeverity()) {
618  case DS_Error:
619  Severity = LTO_DS_ERROR;
620  break;
621  case DS_Warning:
622  Severity = LTO_DS_WARNING;
623  break;
624  case DS_Remark:
625  Severity = LTO_DS_REMARK;
626  break;
627  case DS_Note:
628  Severity = LTO_DS_NOTE;
629  break;
630  }
631  // Create the string that will be reported to the external diagnostic handler.
632  std::string MsgStorage;
633  raw_string_ostream Stream(MsgStorage);
634  DiagnosticPrinterRawOStream DP(Stream);
635  DI.print(DP);
636  Stream.flush();
637 
638  // If this method has been called it means someone has set up an external
639  // diagnostic handler. Assert on that.
640  assert(DiagHandler && "Invalid diagnostic handler");
641  (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
642 }
643 
644 namespace {
645 struct LTODiagnosticHandler : public DiagnosticHandler {
646  LTOCodeGenerator *CodeGenerator;
647  LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
648  : CodeGenerator(CodeGenPtr) {}
649  bool handleDiagnostics(const DiagnosticInfo &DI) override {
650  CodeGenerator->DiagnosticHandler(DI);
651  return true;
652  }
653 };
654 }
655 
656 void
658  void *Ctxt) {
659  this->DiagHandler = DiagHandler;
660  this->DiagContext = Ctxt;
661  if (!DiagHandler)
662  return Context.setDiagnosticHandler(nullptr);
663  // Register the LTOCodeGenerator stub in the LLVMContext to forward the
664  // diagnostic to the external DiagHandler.
665  Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
666  true);
667 }
668 
669 namespace {
670 class LTODiagnosticInfo : public DiagnosticInfo {
671  const Twine &Msg;
672 public:
673  LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
674  : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
675  void print(DiagnosticPrinter &DP) const override { DP << Msg; }
676 };
677 }
678 
679 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
680  if (DiagHandler)
681  (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
682  else
683  Context.diagnose(LTODiagnosticInfo(ErrMsg));
684 }
685 
686 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
687  if (DiagHandler)
688  (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
689  else
690  Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
691 }
void setDiagnosticHandler(std::unique_ptr< DiagnosticHandler > &&DH, bool RespectFilters=false)
setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler to provide custom d...
void initializeDCELegacyPassPass(PassRegistry &)
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
Definition: Triple.h:470
This is the base class for diagnostic handling in LLVM.
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.
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1184
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:228
LLVMContext & Context
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
void initializeInternalizeLegacyPassPass(PassRegistry &)
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:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
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
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...
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.
std::string getString() const
Returns features as a string.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:89
void initializeGlobalDCELegacyPassPass(PassRegistry &)
iterator find(StringRef Key)
Definition: StringMap.h:337
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:380
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
std::error_code error() const
Definition: raw_ostream.h:425
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:947
void add(Pass *P) override
Add a pass to the queue of passes to run.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237
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...
Interface for custom diagnostic printing.
bool writeMergedModules(StringRef Path)
Write the merged module to the file specified by the given path.
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \\\)
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
cl::opt< bool > LTOPassRemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:285
Pass * createObjCARCContractPass()
static const char * getVersionString()
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:332
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
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:406
This is the base abstract class for diagnostic reporting in the backend.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:363
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::error_code getError() const
Definition: ErrorOr.h:172
void initializeSROALegacyPassPass(PassRegistry &)
void setOptLevel(unsigned OptLevel)
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
void setTargetOptions(const TargetOptions &Options)
const Module & getModule() const
Definition: LTOModule.h:115
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
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:431
C++ class which implements the opaque lto_code_gen_t type.
void initializeGlobalsAAWrapperPassPass(PassRegistry &)
void(* lto_diagnostic_handler_t)(lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt)
Diagnostic handler type.
Definition: lto.h:321
const std::vector< StringRef > & getAsmUndefinedRefs()
Definition: LTOModule.h:157
Module.h This file contains the declarations for the Module class.
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:370
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:4638
amdgpu Simplify well known AMD library false Value Value * Arg
Basic diagnostic printer that uses an underlying raw_ostream.
void DiagnosticHandler(const DiagnosticInfo &DI)
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
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:860
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...
DiagnosticSeverity getSeverity() const
static bool mustPreserveGV(const GlobalValue &GV)
Predicate for Internalize pass.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
void initializeInstructionCombiningPassPass(PassRegistry &)
void keep()
Indicate that the tool&#39;s job wrt this output file has been successful and the file should not be dele...
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
bool empty() const
Definition: StringMap.h:111
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:462
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))
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
const FeatureBitset Features
void initializeLegacyLICMPassPass(PassRegistry &)
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:109
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:39
This pass exposes codegen information to IR-level passes.
void parseCodeGenDebugOptions()
Parse the options set in setCodeGenDebugOptions.
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:806
void setModule(std::unique_ptr< LTOModule > M)
Set the destination module.
void initializeMergedLoadStoreMotionLegacyPassPass(PassRegistry &)
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
iterator end()
Definition: StringMap.h:322
raw_fd_ostream & os()
Return the contained raw_fd_ostream.
void setDiagnosticHandler(lto_diagnostic_handler_t, void *)
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:442
void setDebugInfo(lto_debug_model)