LLVM  3.7.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 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/LTO/LTOModule.h"
35 #include "llvm/Linker/Linker.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
41 #include "llvm/Support/Host.h"
43 #include "llvm/Support/Signals.h"
52 #include "llvm/Transforms/IPO.h"
55 #include <system_error>
56 using namespace llvm;
57 
59 #ifdef LLVM_VERSION_INFO
60  return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
61 #else
62  return PACKAGE_NAME " version " PACKAGE_VERSION;
63 #endif
64 }
65 
67  : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
68  initializeLTOPasses();
69 }
70 
71 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
72  : OwnedContext(std::move(Context)), Context(*OwnedContext),
73  IRLinker(new Module("ld-temp.o", *OwnedContext)) {
74  initializeLTOPasses();
75 }
76 
77 void LTOCodeGenerator::destroyMergedModule() {
78  if (OwnedModule) {
79  assert(IRLinker.getModule() == &OwnedModule->getModule() &&
80  "The linker's module should be the same as the owned module");
81  delete OwnedModule;
82  OwnedModule = nullptr;
83  } else if (IRLinker.getModule())
84  IRLinker.deleteModule();
85 }
86 
88  destroyMergedModule();
89 
90  delete TargetMach;
91  TargetMach = nullptr;
92 
93  for (std::vector<char *>::iterator I = CodegenOptions.begin(),
94  E = CodegenOptions.end();
95  I != E; ++I)
96  free(*I);
97 }
98 
99 // Initialize LTO passes. Please keep this funciton in sync with
100 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
101 // passes are initialized.
102 void LTOCodeGenerator::initializeLTOPasses() {
104 
127 }
128 
130  assert(&mod->getModule().getContext() == &Context &&
131  "Expected module in same context");
132 
133  bool ret = IRLinker.linkInModule(&mod->getModule());
134 
135  const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
136  for (int i = 0, e = undefs.size(); i != e; ++i)
137  AsmUndefinedRefs[undefs[i]] = 1;
138 
139  return !ret;
140 }
141 
143  assert(&Mod->getModule().getContext() == &Context &&
144  "Expected module in same context");
145 
146  // Delete the old merged module.
147  destroyMergedModule();
148  AsmUndefinedRefs.clear();
149 
150  OwnedModule = Mod;
151  IRLinker.setModule(&Mod->getModule());
152 
153  const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
154  for (int I = 0, E = Undefs.size(); I != E; ++I)
155  AsmUndefinedRefs[Undefs[I]] = 1;
156 }
157 
159  Options = options;
160 }
161 
163  switch (debug) {
165  EmitDwarfDebugInfo = false;
166  return;
167 
169  EmitDwarfDebugInfo = true;
170  return;
171  }
172  llvm_unreachable("Unknown debug format!");
173 }
174 
176  switch (model) {
181  CodeModel = model;
182  return;
183  }
184  llvm_unreachable("Unknown PIC model!");
185 }
186 
188  std::string &errMsg) {
189  if (!determineTarget(errMsg))
190  return false;
191 
192  // mark which symbols can not be internalized
193  applyScopeRestrictions();
194 
195  // create output file
196  std::error_code EC;
197  tool_output_file Out(path, EC, sys::fs::F_None);
198  if (EC) {
199  errMsg = "could not open bitcode file for writing: ";
200  errMsg += path;
201  return false;
202  }
203 
204  // write bitcode to it
205  WriteBitcodeToFile(IRLinker.getModule(), Out.os(), ShouldEmbedUselists);
206  Out.os().close();
207 
208  if (Out.os().has_error()) {
209  errMsg = "could not write bitcode file: ";
210  errMsg += path;
211  Out.os().clear_error();
212  return false;
213  }
214 
215  Out.keep();
216  return true;
217 }
218 
219 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
220  std::string &errMsg) {
221  // make unique temp .o file to put generated object file
222  SmallString<128> Filename;
223  int FD;
224  std::error_code EC =
225  sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
226  if (EC) {
227  errMsg = EC.message();
228  return false;
229  }
230 
231  // generate object file
232  tool_output_file objFile(Filename.c_str(), FD);
233 
234  bool genResult = compileOptimized(objFile.os(), errMsg);
235  objFile.os().close();
236  if (objFile.os().has_error()) {
237  objFile.os().clear_error();
238  sys::fs::remove(Twine(Filename));
239  return false;
240  }
241 
242  objFile.keep();
243  if (!genResult) {
244  sys::fs::remove(Twine(Filename));
245  return false;
246  }
247 
248  NativeObjectPath = Filename.c_str();
249  *name = NativeObjectPath.c_str();
250  return true;
251 }
252 
253 std::unique_ptr<MemoryBuffer>
255  const char *name;
256  if (!compileOptimizedToFile(&name, errMsg))
257  return nullptr;
258 
259  // read .o file into memory buffer
261  MemoryBuffer::getFile(name, -1, false);
262  if (std::error_code EC = BufferOrErr.getError()) {
263  errMsg = EC.message();
264  sys::fs::remove(NativeObjectPath);
265  return nullptr;
266  }
267 
268  // remove temp files
269  sys::fs::remove(NativeObjectPath);
270 
271  return std::move(*BufferOrErr);
272 }
273 
274 
275 bool LTOCodeGenerator::compile_to_file(const char **name,
276  bool disableInline,
277  bool disableGVNLoadPRE,
278  bool disableVectorization,
279  std::string &errMsg) {
280  if (!optimize(disableInline, disableGVNLoadPRE,
281  disableVectorization, errMsg))
282  return false;
283 
284  return compileOptimizedToFile(name, errMsg);
285 }
286 
287 std::unique_ptr<MemoryBuffer>
288 LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
289  bool disableVectorization, std::string &errMsg) {
290  if (!optimize(disableInline, disableGVNLoadPRE,
291  disableVectorization, errMsg))
292  return nullptr;
293 
294  return compileOptimized(errMsg);
295 }
296 
297 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
298  if (TargetMach)
299  return true;
300 
301  std::string TripleStr = IRLinker.getModule()->getTargetTriple();
302  if (TripleStr.empty())
303  TripleStr = sys::getDefaultTargetTriple();
304  llvm::Triple Triple(TripleStr);
305 
306  // create target machine from info for merged modules
307  const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
308  if (!march)
309  return false;
310 
311  // The relocation model is actually a static member of TargetMachine and
312  // needs to be set before the TargetMachine is instantiated.
314  switch (CodeModel) {
316  RelocModel = Reloc::Static;
317  break;
319  RelocModel = Reloc::PIC_;
320  break;
322  RelocModel = Reloc::DynamicNoPIC;
323  break;
325  // RelocModel is already the default, so leave it that way.
326  break;
327  }
328 
329  // Construct LTOModule, hand over ownership of module and target. Use MAttr as
330  // the default set of features.
332  Features.getDefaultSubtargetFeatures(Triple);
333  std::string FeatureStr = Features.getString();
334  // Set a default CPU for Darwin triples.
335  if (MCpu.empty() && Triple.isOSDarwin()) {
337  MCpu = "core2";
338  else if (Triple.getArch() == llvm::Triple::x86)
339  MCpu = "yonah";
340  else if (Triple.getArch() == llvm::Triple::aarch64)
341  MCpu = "cyclone";
342  }
343 
344  CodeGenOpt::Level CGOptLevel;
345  switch (OptLevel) {
346  case 0:
347  CGOptLevel = CodeGenOpt::None;
348  break;
349  case 1:
350  CGOptLevel = CodeGenOpt::Less;
351  break;
352  case 2:
353  CGOptLevel = CodeGenOpt::Default;
354  break;
355  case 3:
356  CGOptLevel = CodeGenOpt::Aggressive;
357  break;
358  }
359 
360  TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
361  RelocModel, CodeModel::Default,
362  CGOptLevel);
363  return true;
364 }
365 
366 void LTOCodeGenerator::
367 applyRestriction(GlobalValue &GV,
368  ArrayRef<StringRef> Libcalls,
369  std::vector<const char*> &MustPreserveList,
371  Mangler &Mangler) {
372  // There are no restrictions to apply to declarations.
373  if (GV.isDeclaration())
374  return;
375 
376  // There is nothing more restrictive than private linkage.
377  if (GV.hasPrivateLinkage())
378  return;
379 
380  SmallString<64> Buffer;
381  TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
382 
383  if (MustPreserveSymbols.count(Buffer))
384  MustPreserveList.push_back(GV.getName().data());
385  if (AsmUndefinedRefs.count(Buffer))
386  AsmUsed.insert(&GV);
387 
388  // Conservatively append user-supplied runtime library functions to
389  // llvm.compiler.used. These could be internalized and deleted by
390  // optimizations like -globalopt, causing problems when later optimizations
391  // add new library calls (e.g., llvm.memset => memset and printf => puts).
392  // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
393  if (isa<Function>(GV) &&
394  std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
395  AsmUsed.insert(&GV);
396 }
397 
398 static void findUsedValues(GlobalVariable *LLVMUsed,
399  SmallPtrSetImpl<GlobalValue*> &UsedValues) {
400  if (!LLVMUsed) return;
401 
402  ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
403  for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
404  if (GlobalValue *GV =
405  dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
406  UsedValues.insert(GV);
407 }
408 
409 // Collect names of runtime library functions. User-defined functions with the
410 // same names are added to llvm.compiler.used to prevent them from being
411 // deleted by optimizations.
412 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
413  const TargetLibraryInfo& TLI,
414  const Module &Mod,
415  const TargetMachine &TM) {
416  // TargetLibraryInfo has info on C runtime library calls on the current
417  // target.
418  for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
419  I != E; ++I) {
420  LibFunc::Func F = static_cast<LibFunc::Func>(I);
421  if (TLI.has(F))
422  Libcalls.push_back(TLI.getName(F));
423  }
424 
426 
427  for (const Function &F : Mod) {
428  const TargetLowering *Lowering =
430 
431  if (Lowering && TLSet.insert(Lowering).second)
432  // TargetLowering has info on library calls that CodeGen expects to be
433  // available, both from the C runtime and compiler-rt.
434  for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
435  I != E; ++I)
436  if (const char *Name =
437  Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
438  Libcalls.push_back(Name);
439  }
440 
441  array_pod_sort(Libcalls.begin(), Libcalls.end());
442  Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
443  Libcalls.end());
444 }
445 
446 void LTOCodeGenerator::applyScopeRestrictions() {
447  if (ScopeRestrictionsDone || !ShouldInternalize)
448  return;
449  Module *mergedModule = IRLinker.getModule();
450 
451  // Start off with a verification pass.
452  legacy::PassManager passes;
453  passes.add(createVerifierPass());
454 
455  // mark which symbols can not be internalized
456  Mangler Mangler;
457  std::vector<const char*> MustPreserveList;
459  std::vector<StringRef> Libcalls;
460  TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
461  TargetLibraryInfo TLI(TLII);
462 
463  accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
464 
465  for (Module::iterator f = mergedModule->begin(),
466  e = mergedModule->end(); f != e; ++f)
467  applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
468  for (Module::global_iterator v = mergedModule->global_begin(),
469  e = mergedModule->global_end(); v != e; ++v)
470  applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
471  for (Module::alias_iterator a = mergedModule->alias_begin(),
472  e = mergedModule->alias_end(); a != e; ++a)
473  applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
474 
475  GlobalVariable *LLVMCompilerUsed =
476  mergedModule->getGlobalVariable("llvm.compiler.used");
477  findUsedValues(LLVMCompilerUsed, AsmUsed);
478  if (LLVMCompilerUsed)
479  LLVMCompilerUsed->eraseFromParent();
480 
481  if (!AsmUsed.empty()) {
482  llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
483  std::vector<Constant*> asmUsed2;
484  for (auto *GV : AsmUsed) {
485  Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
486  asmUsed2.push_back(c);
487  }
488 
489  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
490  LLVMCompilerUsed =
491  new llvm::GlobalVariable(*mergedModule, ATy, false,
493  llvm::ConstantArray::get(ATy, asmUsed2),
494  "llvm.compiler.used");
495 
496  LLVMCompilerUsed->setSection("llvm.metadata");
497  }
498 
499  passes.add(createInternalizePass(MustPreserveList));
500 
501  // apply scope restrictions
502  passes.run(*mergedModule);
503 
504  ScopeRestrictionsDone = true;
505 }
506 
507 /// Optimize merged modules using various IPO passes
508 bool LTOCodeGenerator::optimize(bool DisableInline,
509  bool DisableGVNLoadPRE,
510  bool DisableVectorization,
511  std::string &errMsg) {
512  if (!this->determineTarget(errMsg))
513  return false;
514 
515  Module *mergedModule = IRLinker.getModule();
516 
517  // Mark which symbols can not be internalized
518  this->applyScopeRestrictions();
519 
520  // Instantiate the pass manager to organize the passes.
521  legacy::PassManager passes;
522 
523  // Add an appropriate DataLayout instance for this module...
524  mergedModule->setDataLayout(*TargetMach->getDataLayout());
525 
526  passes.add(
528 
529  Triple TargetTriple(TargetMach->getTargetTriple());
530  PassManagerBuilder PMB;
531  PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
532  PMB.LoopVectorize = !DisableVectorization;
533  PMB.SLPVectorize = !DisableVectorization;
534  if (!DisableInline)
535  PMB.Inliner = createFunctionInliningPass();
536  PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
537  PMB.OptLevel = OptLevel;
538  PMB.VerifyInput = true;
539  PMB.VerifyOutput = true;
540 
541  PMB.populateLTOPassManager(passes);
542 
543  // Run our queue of passes all at once now, efficiently.
544  passes.run(*mergedModule);
545 
546  return true;
547 }
548 
550  std::string &errMsg) {
551  if (!this->determineTarget(errMsg))
552  return false;
553 
554  Module *mergedModule = IRLinker.getModule();
555 
556  legacy::PassManager codeGenPasses;
557 
558  // If the bitcode files contain ARC code and were compiled with optimization,
559  // the ObjCARCContractPass must be run, so do it unconditionally here.
560  codeGenPasses.add(createObjCARCContractPass());
561 
562  if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
564  errMsg = "target file type not supported";
565  return false;
566  }
567 
568  // Run the code generator, and write assembly file
569  codeGenPasses.run(*mergedModule);
570 
571  return true;
572 }
573 
574 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
575 /// LTO problems.
576 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
577  for (std::pair<StringRef, StringRef> o = getToken(options);
578  !o.first.empty(); o = getToken(o.second)) {
579  // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
580  // that.
581  if (CodegenOptions.empty())
582  CodegenOptions.push_back(strdup("libLLVMLTO"));
583  CodegenOptions.push_back(strdup(o.first.str().c_str()));
584  }
585 }
586 
588  // if options were requested, set them
589  if (!CodegenOptions.empty())
590  cl::ParseCommandLineOptions(CodegenOptions.size(),
591  const_cast<char **>(&CodegenOptions[0]));
592 }
593 
594 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
595  void *Context) {
596  ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
597 }
598 
599 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
600  // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
602  switch (DI.getSeverity()) {
603  case DS_Error:
604  Severity = LTO_DS_ERROR;
605  break;
606  case DS_Warning:
607  Severity = LTO_DS_WARNING;
608  break;
609  case DS_Remark:
610  Severity = LTO_DS_REMARK;
611  break;
612  case DS_Note:
613  Severity = LTO_DS_NOTE;
614  break;
615  }
616  // Create the string that will be reported to the external diagnostic handler.
617  std::string MsgStorage;
618  raw_string_ostream Stream(MsgStorage);
619  DiagnosticPrinterRawOStream DP(Stream);
620  DI.print(DP);
621  Stream.flush();
622 
623  // If this method has been called it means someone has set up an external
624  // diagnostic handler. Assert on that.
625  assert(DiagHandler && "Invalid diagnostic handler");
626  (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
627 }
628 
629 void
631  void *Ctxt) {
632  this->DiagHandler = DiagHandler;
633  this->DiagContext = Ctxt;
634  if (!DiagHandler)
635  return Context.setDiagnosticHandler(nullptr, nullptr);
636  // Register the LTOCodeGenerator stub in the LLVMContext to forward the
637  // diagnostic to the external DiagHandler.
638  Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
639  /* RespectFilters */ true);
640 }
void initializeFunctionAttrsPass(PassRegistry &)
std::error_code getError() const
Definition: ErrorOr.h:178
Represents either an error or a value T.
Definition: ErrorOr.h:82
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:46
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallPtrSet.h:78
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
bool compile_to_file(const char **name, bool disableInline, bool disableGVNLoadPRE, bool disableVectorization, std::string &errMsg)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
void deleteModule()
void initializeSimpleInlinerPass(PassRegistry &)
void initializeJumpThreadingPass(PassRegistry &)
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
unsigned getNumOperands() const
Definition: User.h:138
bool optimize(bool disableInline, bool disableGVNLoadPRE, bool disableVectorization, std::string &errMsg)
Optimize merged modules using various IPO passes.
iterator end() const
Definition: ArrayRef.h:123
lto_codegen_diagnostic_severity_t
Diagnostic severity.
Definition: lto.h:300
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
void initializeInternalizePassPass(PassRegistry &)
FunctionPass * createVerifierPass(bool FatalErrors=true)
Create a verifier pass.
Definition: Verifier.cpp:3703
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
const FeatureBitset Features
raw_fd_ostream & os()
Return the contained raw_fd_ostream.
bool addModule(struct LTOModule *)
void setDataLayout(StringRef Desc)
Set the data layout.
Definition: Module.cpp:366
Implementation of the target library information.
F(f)
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:261
void initializeSROA_DTPass(PassRegistry &)
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:242
const Triple & getTargetTriple() const
void initializePruneEHPass(PassRegistry &)
void add(Pass *P) override
Add a pass to the queue of passes to run.
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:430
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:79
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 ...
bool has(LibFunc::Func F) const
Tests whether a library function is available.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
void initializeMergedLoadStoreMotionPass(PassRegistry &)
void initializeArgPromotionPass(PassRegistry &)
void initializeGlobalOptPass(PassRegistry &)
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:291
const Module & getModule() const
Definition: LTOModule.h:109
void eraseFromParent() override
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Definition: Globals.cpp:194
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
bool hasPrivateLinkage() const
Definition: GlobalValue.h:279
void setTargetOptions(TargetOptions options)
global_iterator global_begin()
Definition: Module.h:552
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:107
Pass * createObjCARCContractPass()
ArrayType - Class to represent array types.
Definition: DerivedTypes.h:336
static const char * getVersionString()
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Reloc::Model RM=Reloc::Default, CodeModel::Model CM=CodeModel::Default, CodeGenOpt::Level OL=CodeGenOpt::Default) const
createTargetMachine - Create a target specific machine implementation for the specified Triple...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:242
DiagnosticSeverity getSeverity() const
void initializeGlobalsModRefPass(PassRegistry &)
bool linkInModule(Module *Src, bool OverrideSymbols=false)
Link Src into the composite.
lto_debug_model
Definition: lto.h:73
PassManager manages ModulePassManagers.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1835
bool writeMergedModules(const char *path, std::string &errMsg)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition: STLExtras.h:287
This is the base abstract class for diagnostic reporting in the backend.
cl::opt< Reloc::Model > RelocModel("relocation-model", cl::desc("Choose relocation model"), cl::init(Reloc::Default), cl::values(clEnumValN(Reloc::Default,"default","Target default relocation model"), clEnumValN(Reloc::Static,"static","Non-relocatable code"), clEnumValN(Reloc::PIC_,"pic","Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC,"dynamic-no-pic","Relocatable external references, non-relocatable code"), clEnumValEnd))
void setCodeGenDebugOptions(const char *opts)
setCodeGenDebugOptions - Set codegen debugging options to aid in debugging LTO problems.
alias_iterator alias_end()
Definition: Module.h:593
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important base class in LLVM.
Definition: Constant.h:41
void WriteBitcodeToFile(const Module *M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false)
Write the specified module to the specified raw output stream.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
virtual TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:873
void setModule(struct LTOModule *)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:264
iterator begin() const
Definition: ArrayRef.h:122
Value * getOperand(unsigned i) const
Definition: User.h:118
void initializeIPSCCPPass(PassRegistry &)
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
void initializeLICMPass(PassRegistry &)
C++ class which implements the opaque lto_module_t type.
Definition: LTOModule.h:39
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:283
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
void setModule(Module *Dst)
Set the composite to the passed-in module.
static void accumulateAndSortLibcalls(std::vector< StringRef > &Libcalls, const TargetLibraryInfo &TLI, const Module &Mod, const TargetMachine &TM)
void(* lto_diagnostic_handler_t)(lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt)
Diagnostic handler type.
Definition: lto.h:316
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
C++ class which implements the opaque lto_code_gen_t type.
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X or iOS).
Definition: Triple.h:404
global_iterator global_end()
Definition: Module.h:554
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
std::unique_ptr< MemoryBuffer > compileOptimized(std::string &errMsg)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
const char * getLibcallName(RTLIB::Libcall Call) const
Get the libcall routine name for the specified libcall.
shadow stack gc Shadow Stack GC Lowering
const DataLayout * getDataLayout() const
Deprecated in 3.7, will be removed in 3.8.
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
virtual const TargetLowering * getTargetLowering() const
void initializeSROA_SSAUpPass(PassRegistry &)
alias_iterator alias_begin()
Definition: Module.h:591
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:458
lto_codegen_model
Definition: lto.h:81
#define debug(s)
Target - Wrapper for Target specific information.
ConstantArray - Constant Array Declarations.
Definition: Constants.h:356
SubtargetFeatures - Manages the enabling and disabling of subtarget specific features.
void ParseCommandLineOptions(int argc, const char *const *argv, const char *Overview=nullptr)
void initializeDCEPass(PassRegistry &)
void initializeDAHPass(PassRegistry &)
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, CodeGenFileType, bool=true, AnalysisID=nullptr, AnalysisID=nullptr, AnalysisID=nullptr, MachineFunctionInitializer *=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
void initializeSROAPass(PassRegistry &)
void initializeGlobalDCEPass(PassRegistry &)
Basic diagnostic printer that uses an underlying raw_ostream.
iterator end()
Definition: Module.h:571
void keep()
Indicate that the tool's job wrt this output file has been successful and the file should not be dele...
StringRef getName(LibFunc::Func F) const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:128
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.
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:713
static void findUsedValues(GlobalVariable *LLVMUsed, SmallPtrSetImpl< GlobalValue * > &UsedValues)
const char * c_str()
Definition: SmallString.h:270
#define I(x, y, z)
Definition: MD5.cpp:54
iterator begin()
Definition: Module.h:569
static ArrayType * get(Type *ElementType, uint64_t NumElements)
ArrayType::get - This static method is the primary way to construct an ArrayType. ...
Definition: Type.cpp:686
const std::vector< const char * > & getAsmUndefinedRefs()
Definition: LTOModule.h:155
ModulePass * createInternalizePass(ArrayRef< const char * > ExportList)
createInternalizePass - This pass loops over all of the functions in the input module, internalizing all globals (functions and variables) it can.
void initializeConstantMergePass(PassRegistry &)
void initializeInstructionCombiningPassPass(PassRegistry &)
void close()
Manually flush the stream and close the file.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:321
void initializeCFGSimplifyPassPass(PassRegistry &)
void initializeMemCpyOptPass(PassRegistry &)
Module * getModule() const
Definition: Linker/Linker.h:67
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:465
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
static const char * name
void setCodePICModel(lto_codegen_model)
Primary interface to the complete machine description for the target machine.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:41
This pass exposes codegen information to IR-level passes.
std::unique_ptr< MemoryBuffer > compile(bool disableInline, bool disableGVNLoadPRE, bool disableVectorization, std::string &errMsg)
LLVMContext & getGlobalContext()
getGlobalContext - Returns a global context.
Definition: LLVMContext.cpp:30
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:381
void setDiagnosticHandler(lto_diagnostic_handler_t, void *)
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:265
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:443
void setDebugInfo(lto_debug_model)
void initializeGVNPass(PassRegistry &)