LLVM  9.0.0svn
ThinLTOCodeGenerator.cpp
Go to the documentation of this file.
1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Thin Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/PassTimingInfo.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/LTO/LTO.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Error.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/SHA1.h"
46 #include "llvm/Support/Threading.h"
48 #include "llvm/Support/VCSRevision.h"
50 #include "llvm/Transforms/IPO.h"
56 
57 #include <numeric>
58 
59 #if !defined(_MSC_VER) && !defined(__MINGW32__)
60 #include <unistd.h>
61 #else
62 #include <io.h>
63 #endif
64 
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "thinlto"
68 
69 namespace llvm {
70 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
74 }
75 
76 namespace {
77 
78 static cl::opt<int>
79  ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
80 
81 // Simple helper to save temporary files for debug.
82 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
83  unsigned count, StringRef Suffix) {
84  if (TempDir.empty())
85  return;
86  // User asked to save temps, let dump the bitcode file after import.
87  std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
88  std::error_code EC;
89  raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
90  if (EC)
91  report_fatal_error(Twine("Failed to open ") + SaveTempPath +
92  " to save optimized bitcode\n");
93  WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
94 }
95 
96 static const GlobalValueSummary *
97 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
98  // If there is any strong definition anywhere, get it.
99  auto StrongDefForLinker = llvm::find_if(
100  GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
101  auto Linkage = Summary->linkage();
104  });
105  if (StrongDefForLinker != GVSummaryList.end())
106  return StrongDefForLinker->get();
107  // Get the first *linker visible* definition for this global in the summary
108  // list.
109  auto FirstDefForLinker = llvm::find_if(
110  GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
111  auto Linkage = Summary->linkage();
113  });
114  // Extern templates can be emitted as available_externally.
115  if (FirstDefForLinker == GVSummaryList.end())
116  return nullptr;
117  return FirstDefForLinker->get();
118 }
119 
120 // Populate map of GUID to the prevailing copy for any multiply defined
121 // symbols. Currently assume first copy is prevailing, or any strong
122 // definition. Can be refined with Linker information in the future.
123 static void computePrevailingCopies(
124  const ModuleSummaryIndex &Index,
126  auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
127  return GVSummaryList.size() > 1;
128  };
129 
130  for (auto &I : Index) {
131  if (HasMultipleCopies(I.second.SummaryList))
132  PrevailingCopy[I.first] =
133  getFirstDefinitionForLinker(I.second.SummaryList);
134  }
135 }
136 
138 generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
139  StringMap<MemoryBufferRef> ModuleMap;
140  for (auto &ModuleBuffer : Modules) {
141  assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
142  ModuleMap.end() &&
143  "Expect unique Buffer Identifier");
144  ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
145  }
146  return ModuleMap;
147 }
148 
149 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
150  if (renameModuleForThinLTO(TheModule, Index))
151  report_fatal_error("renameModuleForThinLTO failed");
152 }
153 
154 namespace {
155 class ThinLTODiagnosticInfo : public DiagnosticInfo {
156  const Twine &Msg;
157 public:
158  ThinLTODiagnosticInfo(const Twine &DiagMsg,
159  DiagnosticSeverity Severity = DS_Error)
160  : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
161  void print(DiagnosticPrinter &DP) const override { DP << Msg; }
162 };
163 }
164 
165 /// Verify the module and strip broken debug info.
166 static void verifyLoadedModule(Module &TheModule) {
167  bool BrokenDebugInfo = false;
168  if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
169  report_fatal_error("Broken module found, compilation aborted!");
170  if (BrokenDebugInfo) {
171  TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
172  "Invalid debug info found, debug info will be stripped", DS_Warning));
173  StripDebugInfo(TheModule);
174  }
175 }
176 
177 static std::unique_ptr<Module>
178 loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
179  bool Lazy, bool IsImporting) {
180  SMDiagnostic Err;
181  Expected<std::unique_ptr<Module>> ModuleOrErr =
182  Lazy
183  ? getLazyBitcodeModule(Buffer, Context,
184  /* ShouldLazyLoadMetadata */ true, IsImporting)
185  : parseBitcodeFile(Buffer, Context);
186  if (!ModuleOrErr) {
187  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
189  SourceMgr::DK_Error, EIB.message());
190  Err.print("ThinLTO", errs());
191  });
192  report_fatal_error("Can't load module, abort.");
193  }
194  if (!Lazy)
195  verifyLoadedModule(*ModuleOrErr.get());
196  return std::move(ModuleOrErr.get());
197 }
198 
199 static void
200 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
201  StringMap<MemoryBufferRef> &ModuleMap,
202  const FunctionImporter::ImportMapTy &ImportList) {
203  auto Loader = [&](StringRef Identifier) {
204  return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
205  /*Lazy=*/true, /*IsImporting*/ true);
206  };
207 
208  FunctionImporter Importer(Index, Loader);
209  Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
210  if (!Result) {
211  handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
213  SourceMgr::DK_Error, EIB.message());
214  Err.print("ThinLTO", errs());
215  });
216  report_fatal_error("importFunctions failed");
217  }
218  // Verify again after cross-importing.
219  verifyLoadedModule(TheModule);
220 }
221 
222 static void optimizeModule(Module &TheModule, TargetMachine &TM,
223  unsigned OptLevel, bool Freestanding) {
224  // Populate the PassManager
225  PassManagerBuilder PMB;
227  if (Freestanding)
230  // FIXME: should get it from the bitcode?
231  PMB.OptLevel = OptLevel;
232  PMB.LoopVectorize = true;
233  PMB.SLPVectorize = true;
234  // Already did this in verifyLoadedModule().
235  PMB.VerifyInput = false;
236  PMB.VerifyOutput = false;
237 
239 
240  // Add the TTI (required to inform the vectorizer about register size for
241  // instance)
243 
244  // Add optimizations
246 
247  PM.run(TheModule);
248 }
249 
250 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
252 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
253  const Triple &TheTriple) {
254  DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
255  for (auto &Entry : PreservedSymbols) {
256  StringRef Name = Entry.first();
257  if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
258  Name = Name.drop_front();
259  GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
260  }
261  return GUIDPreservedSymbols;
262 }
263 
264 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
265  TargetMachine &TM) {
266  SmallVector<char, 128> OutputBuffer;
267 
268  // CodeGen
269  {
270  raw_svector_ostream OS(OutputBuffer);
272 
273  // If the bitcode files contain ARC code and were compiled with optimization,
274  // the ObjCARCContractPass must be run, so do it unconditionally here.
276 
277  // Setup the codegen now.
278  if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile,
279  /* DisableVerify */ true))
280  report_fatal_error("Failed to setup codegen");
281 
282  // Run codegen now. resulting binary is in OutputBuffer.
283  PM.run(TheModule);
284  }
285  return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
286 }
287 
288 /// Manage caching for a single Module.
289 class ModuleCacheEntry {
290  SmallString<128> EntryPath;
291 
292 public:
293  // Create a cache entry. This compute a unique hash for the Module considering
294  // the current list of export/import, and offer an interface to query to
295  // access the content in the cache.
296  ModuleCacheEntry(
297  StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
298  const FunctionImporter::ImportMapTy &ImportList,
299  const FunctionImporter::ExportSetTy &ExportList,
300  const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
301  const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
302  bool Freestanding, const TargetMachineBuilder &TMBuilder) {
303  if (CachePath.empty())
304  return;
305 
306  if (!Index.modulePaths().count(ModuleID))
307  // The module does not have an entry, it can't have a hash at all
308  return;
309 
310  if (all_of(Index.getModuleHash(ModuleID),
311  [](uint32_t V) { return V == 0; }))
312  // No hash entry, no caching!
313  return;
314 
315  llvm::lto::Config Conf;
316  Conf.OptLevel = OptLevel;
317  Conf.Options = TMBuilder.Options;
318  Conf.CPU = TMBuilder.MCpu;
319  Conf.MAttrs.push_back(TMBuilder.MAttr);
320  Conf.RelocModel = TMBuilder.RelocModel;
321  Conf.CGOptLevel = TMBuilder.CGOptLevel;
322  Conf.Freestanding = Freestanding;
324  computeLTOCacheKey(Key, Conf, Index, ModuleID, ImportList, ExportList,
325  ResolvedODR, DefinedGVSummaries);
326 
327  // This choice of file name allows the cache to be pruned (see pruneCache()
328  // in include/llvm/Support/CachePruning.h).
329  sys::path::append(EntryPath, CachePath, "llvmcache-" + Key);
330  }
331 
332  // Access the path to this entry in the cache.
333  StringRef getEntryPath() { return EntryPath; }
334 
335  // Try loading the buffer for this cache entry.
336  ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
337  if (EntryPath.empty())
338  return std::error_code();
339  int FD;
340  SmallString<64> ResultPath;
341  std::error_code EC = sys::fs::openFileForRead(
342  Twine(EntryPath), FD, sys::fs::OF_UpdateAtime, &ResultPath);
343  if (EC)
344  return EC;
346  MemoryBuffer::getOpenFile(FD, EntryPath,
347  /*FileSize*/ -1,
348  /*RequiresNullTerminator*/ false);
349  close(FD);
350  return MBOrErr;
351  }
352 
353  // Cache the Produced object file
354  void write(const MemoryBuffer &OutputBuffer) {
355  if (EntryPath.empty())
356  return;
357 
358  // Write to a temporary to avoid race condition
359  SmallString<128> TempFilename;
360  SmallString<128> CachePath(EntryPath);
361  int TempFD;
363  sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
364  std::error_code EC =
365  sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename);
366  if (EC) {
367  errs() << "Error: " << EC.message() << "\n";
368  report_fatal_error("ThinLTO: Can't get a temporary file");
369  }
370  {
371  raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
372  OS << OutputBuffer.getBuffer();
373  }
374  // Rename temp file to final destination; rename is atomic
375  EC = sys::fs::rename(TempFilename, EntryPath);
376  if (EC)
377  sys::fs::remove(TempFilename);
378  }
379 };
380 
381 static std::unique_ptr<MemoryBuffer>
382 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
384  const FunctionImporter::ImportMapTy &ImportList,
385  const FunctionImporter::ExportSetTy &ExportList,
386  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
387  const GVSummaryMapTy &DefinedGlobals,
388  const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
389  bool DisableCodeGen, StringRef SaveTempsDir,
390  bool Freestanding, unsigned OptLevel, unsigned count) {
391 
392  // "Benchmark"-like optimization: single-source case
393  bool SingleModule = (ModuleMap.size() == 1);
394 
395  if (!SingleModule) {
396  promoteModule(TheModule, Index);
397 
398  // Apply summary-based prevailing-symbol resolution decisions.
399  thinLTOResolvePrevailingInModule(TheModule, DefinedGlobals);
400 
401  // Save temps: after promotion.
402  saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
403  }
404 
405  // Be friendly and don't nuke totally the module when the client didn't
406  // supply anything to preserve.
407  if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
408  // Apply summary-based internalization decisions.
409  thinLTOInternalizeModule(TheModule, DefinedGlobals);
410  }
411 
412  // Save internalized bitcode
413  saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
414 
415  if (!SingleModule) {
416  crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
417 
418  // Save temps: after cross-module import.
419  saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
420  }
421 
422  optimizeModule(TheModule, TM, OptLevel, Freestanding);
423 
424  saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
425 
426  if (DisableCodeGen) {
427  // Configured to stop before CodeGen, serialize the bitcode and return.
428  SmallVector<char, 128> OutputBuffer;
429  {
430  raw_svector_ostream OS(OutputBuffer);
431  ProfileSummaryInfo PSI(TheModule);
432  auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
433  WriteBitcodeToFile(TheModule, OS, true, &Index);
434  }
435  return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
436  }
437 
438  return codegenModule(TheModule, TM);
439 }
440 
441 /// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
442 /// for caching, and in the \p Index for application during the ThinLTO
443 /// backends. This is needed for correctness for exported symbols (ensure
444 /// at least one copy kept) and a compile-time optimization (to drop duplicate
445 /// copies when possible).
446 static void resolvePrevailingInIndex(
447  ModuleSummaryIndex &Index,
448  StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
449  &ResolvedODR) {
450 
452  computePrevailingCopies(Index, PrevailingCopy);
453 
454  auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
455  const auto &Prevailing = PrevailingCopy.find(GUID);
456  // Not in map means that there was only one copy, which must be prevailing.
457  if (Prevailing == PrevailingCopy.end())
458  return true;
459  return Prevailing->second == S;
460  };
461 
462  auto recordNewLinkage = [&](StringRef ModuleIdentifier,
463  GlobalValue::GUID GUID,
464  GlobalValue::LinkageTypes NewLinkage) {
465  ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
466  };
467 
468  thinLTOResolvePrevailingInIndex(Index, isPrevailing, recordNewLinkage);
469 }
470 
471 // Initialize the TargetMachine builder for a given Triple
472 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
473  const Triple &TheTriple) {
474  // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
475  // FIXME this looks pretty terrible...
476  if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
477  if (TheTriple.getArch() == llvm::Triple::x86_64)
478  TMBuilder.MCpu = "core2";
479  else if (TheTriple.getArch() == llvm::Triple::x86)
480  TMBuilder.MCpu = "yonah";
481  else if (TheTriple.getArch() == llvm::Triple::aarch64)
482  TMBuilder.MCpu = "cyclone";
483  }
484  TMBuilder.TheTriple = std::move(TheTriple);
485 }
486 
487 } // end anonymous namespace
488 
490  ThinLTOBuffer Buffer(Data, Identifier);
492  StringRef TripleStr;
494  Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
495 
496  if (TripleOrErr)
497  TripleStr = *TripleOrErr;
498 
499  Triple TheTriple(TripleStr);
500 
501  if (Modules.empty())
502  initTMBuilder(TMBuilder, Triple(TheTriple));
503  else if (TMBuilder.TheTriple != TheTriple) {
504  if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
505  report_fatal_error("ThinLTO modules with incompatible triples not "
506  "supported");
507  initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
508  }
509 
510  Modules.push_back(Buffer);
511 }
512 
514  PreservedSymbols.insert(Name);
515 }
516 
518  // FIXME: At the moment, we don't take advantage of this extra information,
519  // we're conservatively considering cross-references as preserved.
520  // CrossReferencedSymbols.insert(Name);
521  PreservedSymbols.insert(Name);
522 }
523 
524 // TargetMachine factory
525 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
526  std::string ErrMsg;
527  const Target *TheTarget =
528  TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
529  if (!TheTarget) {
530  report_fatal_error("Can't load target for this Triple: " + ErrMsg);
531  }
532 
533  // Use MAttr as the default set of features.
535  Features.getDefaultSubtargetFeatures(TheTriple);
536  std::string FeatureStr = Features.getString();
537 
538  return std::unique_ptr<TargetMachine>(
539  TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
540  RelocModel, None, CGOptLevel));
541 }
542 
543 /**
544  * Produce the combined summary index from all the bitcode files:
545  * "thin-link".
546  */
547 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
548  std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
549  llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
550  uint64_t NextModuleId = 0;
551  for (auto &ModuleBuffer : Modules) {
552  if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
553  *CombinedIndex, NextModuleId++)) {
554  // FIXME diagnose
556  std::move(Err), errs(),
557  "error: can't create module summary index for buffer: ");
558  return nullptr;
559  }
560  }
561  return CombinedIndex;
562 }
563 
565  const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
566  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
568  auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
569  const auto &ExportList = ExportLists.find(ModuleIdentifier);
570  return (ExportList != ExportLists.end() &&
571  ExportList->second.count(GUID)) ||
572  GUIDPreservedSymbols.count(GUID);
573  };
574 
575  thinLTOInternalizeAndPromoteInIndex(Index, isExported);
576 }
577 
580  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
581  // We have no symbols resolution available. And can't do any better now in the
582  // case where the prevailing symbol is in a native object. It can be refined
583  // with linker information in the future.
584  auto isPrevailing = [&](GlobalValue::GUID G) {
586  };
587  computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
588  /* ImportEnabled = */ true);
589 }
590 
591 /**
592  * Perform promotion and renaming of exported internal functions.
593  * Index is updated to reflect linkage changes from weak resolution.
594  */
597  auto ModuleCount = Index.modulePaths().size();
598  auto ModuleIdentifier = TheModule.getModuleIdentifier();
599 
600  // Collect for each module the list of function it defines (GUID -> Summary).
601  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
602  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
603 
604  // Convert the preserved symbols set from string to GUID
605  auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
606  PreservedSymbols, Triple(TheModule.getTargetTriple()));
607 
608  // Compute "dead" symbols, we don't want to import/export these!
609  computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
610 
611  // Generate import/export list
612  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
613  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
614  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
615  ExportLists);
616 
617  // Resolve prevailing symbols
619  resolvePrevailingInIndex(Index, ResolvedODR);
620 
622  TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
623 
624  // Promote the exported values in the index, so that they are promoted
625  // in the module.
626  internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
627 
628  promoteModule(TheModule, Index);
629 }
630 
631 /**
632  * Perform cross-module importing for the module identified by ModuleIdentifier.
633  */
636  auto ModuleMap = generateModuleMap(Modules);
637  auto ModuleCount = Index.modulePaths().size();
638 
639  // Collect for each module the list of function it defines (GUID -> Summary).
640  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
641  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
642 
643  // Convert the preserved symbols set from string to GUID
644  auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
645  PreservedSymbols, Triple(TheModule.getTargetTriple()));
646 
647  // Compute "dead" symbols, we don't want to import/export these!
648  computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
649 
650  // Generate import/export list
651  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
652  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
653  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
654  ExportLists);
655  auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
656 
657  crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
658 }
659 
660 /**
661  * Compute the list of summaries needed for importing into module.
662  */
664  Module &TheModule, ModuleSummaryIndex &Index,
665  std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
666  auto ModuleCount = Index.modulePaths().size();
667  auto ModuleIdentifier = TheModule.getModuleIdentifier();
668 
669  // Collect for each module the list of function it defines (GUID -> Summary).
670  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
671  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
672 
673  // Convert the preserved symbols set from string to GUID
674  auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
675  PreservedSymbols, Triple(TheModule.getTargetTriple()));
676 
677  // Compute "dead" symbols, we don't want to import/export these!
678  computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
679 
680  // Generate import/export list
681  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
682  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
683  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
684  ExportLists);
685 
687  ModuleIdentifier, ModuleToDefinedGVSummaries,
688  ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
689 }
690 
691 /**
692  * Emit the list of files needed for importing into module.
693  */
696  auto ModuleCount = Index.modulePaths().size();
697  auto ModuleIdentifier = TheModule.getModuleIdentifier();
698 
699  // Collect for each module the list of function it defines (GUID -> Summary).
700  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
701  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
702 
703  // Convert the preserved symbols set from string to GUID
704  auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
705  PreservedSymbols, Triple(TheModule.getTargetTriple()));
706 
707  // Compute "dead" symbols, we don't want to import/export these!
708  computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
709 
710  // Generate import/export list
711  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
712  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
713  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
714  ExportLists);
715 
716  std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
718  ModuleIdentifier, ModuleToDefinedGVSummaries,
719  ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
720 
721  std::error_code EC;
722  if ((EC = EmitImportsFiles(ModuleIdentifier, OutputName,
723  ModuleToSummariesForIndex)))
724  report_fatal_error(Twine("Failed to open ") + OutputName +
725  " to save imports lists\n");
726 }
727 
728 /**
729  * Perform internalization. Index is updated to reflect linkage changes.
730  */
733  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
734  auto ModuleCount = Index.modulePaths().size();
735  auto ModuleIdentifier = TheModule.getModuleIdentifier();
736 
737  // Convert the preserved symbols set from string to GUID
738  auto GUIDPreservedSymbols =
739  computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
740 
741  // Collect for each module the list of function it defines (GUID -> Summary).
742  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
743  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
744 
745  // Compute "dead" symbols, we don't want to import/export these!
746  computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
747 
748  // Generate import/export list
749  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
750  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
751  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
752  ExportLists);
753  auto &ExportList = ExportLists[ModuleIdentifier];
754 
755  // Be friendly and don't nuke totally the module when the client didn't
756  // supply anything to preserve.
757  if (ExportList.empty() && GUIDPreservedSymbols.empty())
758  return;
759 
760  // Internalization
761  internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
762  thinLTOInternalizeModule(TheModule,
763  ModuleToDefinedGVSummaries[ModuleIdentifier]);
764 }
765 
766 /**
767  * Perform post-importing ThinLTO optimizations.
768  */
770  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
771 
772  // Optimize now
773  optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
774 }
775 
776 /// Write out the generated object file, either from CacheEntryPath or from
777 /// OutputBuffer, preferring hard-link when possible.
778 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
779 static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
780  StringRef SavedObjectsDirectoryPath,
781  const MemoryBuffer &OutputBuffer) {
782  SmallString<128> OutputPath(SavedObjectsDirectoryPath);
783  llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
784  OutputPath.c_str(); // Ensure the string is null terminated.
785  if (sys::fs::exists(OutputPath))
786  sys::fs::remove(OutputPath);
787 
788  // We don't return a memory buffer to the linker, just a list of files.
789  if (!CacheEntryPath.empty()) {
790  // Cache is enabled, hard-link the entry (or copy if hard-link fails).
791  auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
792  if (!Err)
793  return OutputPath.str();
794  // Hard linking failed, try to copy.
795  Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
796  if (!Err)
797  return OutputPath.str();
798  // Copy failed (could be because the CacheEntry was removed from the cache
799  // in the meantime by another process), fall back and try to write down the
800  // buffer to the output.
801  errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
802  << "' to '" << OutputPath << "'\n";
803  }
804  // No cache entry, just write out the buffer.
805  std::error_code Err;
806  raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
807  if (Err)
808  report_fatal_error("Can't open output '" + OutputPath + "'\n");
809  OS << OutputBuffer.getBuffer();
810  return OutputPath.str();
811 }
812 
813 // Main entry point for the ThinLTO processing
815  // Prepare the resulting object vector
816  assert(ProducedBinaries.empty() && "The generator should not be reused");
817  if (SavedObjectsDirectoryPath.empty())
818  ProducedBinaries.resize(Modules.size());
819  else {
820  sys::fs::create_directories(SavedObjectsDirectoryPath);
821  bool IsDir;
822  sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
823  if (!IsDir)
824  report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
825  ProducedBinaryFiles.resize(Modules.size());
826  }
827 
828  if (CodeGenOnly) {
829  // Perform only parallel codegen and return.
830  ThreadPool Pool;
831  int count = 0;
832  for (auto &ModuleBuffer : Modules) {
833  Pool.async([&](int count) {
836 
837  // Parse module now
838  auto TheModule =
839  loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
840  /*IsImporting*/ false);
841 
842  // CodeGen
843  auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
844  if (SavedObjectsDirectoryPath.empty())
845  ProducedBinaries[count] = std::move(OutputBuffer);
846  else
847  ProducedBinaryFiles[count] = writeGeneratedObject(
848  count, "", SavedObjectsDirectoryPath, *OutputBuffer);
849  }, count++);
850  }
851 
852  return;
853  }
854 
855  // Sequential linking phase
856  auto Index = linkCombinedIndex();
857 
858  // Save temps: index.
859  if (!SaveTempsDir.empty()) {
860  auto SaveTempPath = SaveTempsDir + "index.bc";
861  std::error_code EC;
862  raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
863  if (EC)
864  report_fatal_error(Twine("Failed to open ") + SaveTempPath +
865  " to save optimized bitcode\n");
866  WriteIndexToFile(*Index, OS);
867  }
868 
869 
870  // Prepare the module map.
871  auto ModuleMap = generateModuleMap(Modules);
872  auto ModuleCount = Modules.size();
873 
874  // Collect for each module the list of function it defines (GUID -> Summary).
875  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
876  Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
877 
878  // Convert the preserved symbols set from string to GUID, this is needed for
879  // computing the caching hash and the internalization.
880  auto GUIDPreservedSymbols =
881  computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
882 
883  // Compute "dead" symbols, we don't want to import/export these!
884  computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
885 
886  // Synthesize entry counts for functions in the combined index.
888 
889  // Collect the import/export lists for all modules from the call-graph in the
890  // combined index.
891  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
892  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
893  ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
894  ExportLists);
895 
896  // We use a std::map here to be able to have a defined ordering when
897  // producing a hash for the cache entry.
898  // FIXME: we should be able to compute the caching hash for the entry based
899  // on the index, and nuke this map.
901 
902  // Resolve prevailing symbols, this has to be computed early because it
903  // impacts the caching.
904  resolvePrevailingInIndex(*Index, ResolvedODR);
905 
906  // Use global summary-based analysis to identify symbols that can be
907  // internalized (because they aren't exported or preserved as per callback).
908  // Changes are made in the index, consumed in the ThinLTO backends.
909  internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
910 
911  // Make sure that every module has an entry in the ExportLists, ImportList,
912  // GVSummary and ResolvedODR maps to enable threaded access to these maps
913  // below.
914  for (auto &Module : Modules) {
915  auto ModuleIdentifier = Module.getBufferIdentifier();
916  ExportLists[ModuleIdentifier];
917  ImportLists[ModuleIdentifier];
918  ResolvedODR[ModuleIdentifier];
919  ModuleToDefinedGVSummaries[ModuleIdentifier];
920  }
921 
922  // Compute the ordering we will process the inputs: the rough heuristic here
923  // is to sort them per size so that the largest module get schedule as soon as
924  // possible. This is purely a compile-time optimization.
925  std::vector<int> ModulesOrdering;
926  ModulesOrdering.resize(Modules.size());
927  std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
928  llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
929  auto LSize = Modules[LeftIndex].getBuffer().size();
930  auto RSize = Modules[RightIndex].getBuffer().size();
931  return LSize > RSize;
932  });
933 
934  // Parallel optimizer + codegen
935  {
936  ThreadPool Pool(ThreadCount);
937  for (auto IndexCount : ModulesOrdering) {
938  auto &ModuleBuffer = Modules[IndexCount];
939  Pool.async([&](int count) {
940  auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
941  auto &ExportList = ExportLists[ModuleIdentifier];
942 
943  auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
944 
945  // The module may be cached, this helps handling it.
946  ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
947  ImportLists[ModuleIdentifier], ExportList,
948  ResolvedODR[ModuleIdentifier],
949  DefinedGVSummaries, OptLevel, Freestanding,
950  TMBuilder);
951  auto CacheEntryPath = CacheEntry.getEntryPath();
952 
953  {
954  auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
955  LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
956  << " '" << CacheEntryPath << "' for buffer "
957  << count << " " << ModuleIdentifier << "\n");
958 
959  if (ErrOrBuffer) {
960  // Cache Hit!
961  if (SavedObjectsDirectoryPath.empty())
962  ProducedBinaries[count] = std::move(ErrOrBuffer.get());
963  else
964  ProducedBinaryFiles[count] = writeGeneratedObject(
965  count, CacheEntryPath, SavedObjectsDirectoryPath,
966  *ErrOrBuffer.get());
967  return;
968  }
969  }
970 
973  Context.enableDebugTypeODRUniquing();
974  auto DiagFileOrErr = lto::setupOptimizationRemarks(
976  if (!DiagFileOrErr) {
977  errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
978  report_fatal_error("ThinLTO: Can't get an output file for the "
979  "remarks");
980  }
981 
982  // Parse module now
983  auto TheModule =
984  loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
985  /*IsImporting*/ false);
986 
987  // Save temps: original file.
988  saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
989 
990  auto &ImportList = ImportLists[ModuleIdentifier];
991  // Run the main process now, and generates a binary
992  auto OutputBuffer = ProcessThinLTOModule(
993  *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
994  ExportList, GUIDPreservedSymbols,
995  ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
996  DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
997 
998  // Commit to the cache (if enabled)
999  CacheEntry.write(*OutputBuffer);
1000 
1001  if (SavedObjectsDirectoryPath.empty()) {
1002  // We need to generated a memory buffer for the linker.
1003  if (!CacheEntryPath.empty()) {
1004  // When cache is enabled, reload from the cache if possible.
1005  // Releasing the buffer from the heap and reloading it from the
1006  // cache file with mmap helps us to lower memory pressure.
1007  // The freed memory can be used for the next input file.
1008  // The final binary link will read from the VFS cache (hopefully!)
1009  // or from disk (if the memory pressure was too high).
1010  auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1011  if (auto EC = ReloadedBufferOrErr.getError()) {
1012  // On error, keep the preexisting buffer and print a diagnostic.
1013  errs() << "error: can't reload cached file '" << CacheEntryPath
1014  << "': " << EC.message() << "\n";
1015  } else {
1016  OutputBuffer = std::move(*ReloadedBufferOrErr);
1017  }
1018  }
1019  ProducedBinaries[count] = std::move(OutputBuffer);
1020  return;
1021  }
1022  ProducedBinaryFiles[count] = writeGeneratedObject(
1023  count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
1024  }, IndexCount);
1025  }
1026  }
1027 
1028  pruneCache(CacheOptions.Path, CacheOptions.Policy);
1029 
1030  // If statistics were requested, print them out now.
1034 }
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
Definition: Triple.h:474
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition: Path.cpp:913
void collectDefinedGVSummariesPerModule(StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries) const
Collect for each module the list of Summaries it defines (GUID -> Summary).
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:239
Represents either an error or a value T.
Definition: ErrorOr.h:56
void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition: Path.cpp:498
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:1312
void thinLTOResolvePrevailingInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Resolve prevailing symbol linkages in TheModule based on the information recorded in the summaries du...
std::string CPU
Definition: Config.h:38
LLVMContext & Context
CodeGenOpt::Level CGOptLevel
Definition: Config.h:43
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
StringRef getBuffer() const
Definition: MemoryBuffer.h:63
std::vector< std::unique_ptr< GlobalValueSummary > > GlobalValueSummaryList
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:492
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:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
Definition: SourceMgr.cpp:373
void promote(Module &Module, ModuleSummaryIndex &Index)
Perform promotion and renaming of exported internal functions, and additionally resolve weak and link...
cl::opt< std::string > LTORemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
Definition: Threading.cpp:62
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
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...
std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, unsigned Mode=all_read|all_write)
Create a uniquely named file.
Definition: Path.cpp:765
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
This is the interface to build a ModuleSummaryIndex for a module.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This file provides a bitcode writing pass.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:249
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
Analysis providing profile information.
void enableDebugTypeODRUniquing()
void disableAllFunctions()
Disables all builtins.
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
std::string getString() const
Returns features as a string.
const FeatureBitset Features
iterator find(StringRef Key)
Definition: StringMap.h:332
const StringMap< std::pair< uint64_t, ModuleHash > > & modulePaths() const
Table of modules, containing module hash and id.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:509
bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition: Path.cpp:1036
Implementation of the target library information.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1185
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
void addModule(StringRef Identifier, StringRef Data)
Add given module to the code generator.
Base class for error info classes.
Definition: Error.h:48
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:54
void reportAndResetTimings()
If -time-passes has been specified, report the timings immediately and then reset the timers to zero...
Pass * Inliner
Inliner - Specifies the inliner to use.
void gatherImportedSummariesForModule(Module &Module, ModuleSummaryIndex &Index, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the list of summaries needed for importing into module.
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI)
Direct function to compute a ModuleSummaryIndex from a given module.
Wrapper around MemoryBufferRef, owning the identifier.
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfo *MMI=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:479
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:966
void add(Pass *P) override
Add a pass to the queue of passes to run.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
unsigned size() const
Definition: StringMap.h:111
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the first N elements dropped.
Definition: StringRef.h:620
std::vector< std::string > MAttrs
Definition: Config.h:40
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:243
std::unordered_set< GlobalValue::GUID > ExportSetTy
The set contains an entry for every global value the module exports.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
Interface for custom diagnostic printing.
This header defines classes/functions to handle pass execution timing information with interfaces for...
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:266
void run()
Process all the modules that were added to the code generator in parallel.
Key
PAL metadata keys.
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:289
Pass * createObjCARCContractPass()
unsigned OptLevel
The Optimization Level - Specify the basic optimization level.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:350
TargetOptions Options
Definition: Config.h:39
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
A ThreadPool for asynchronous parallel execution on a defined number of threads.
Definition: ThreadPool.h:36
Class to hold module path string table and global value map, and encapsulate methods for operating on...
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1251
PassManager manages ModulePassManagers.
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition: Path.cpp:961
void crossReferenceSymbol(StringRef Name)
Adds to a list of all global symbols that are cross-referenced between ThinLTO files.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
This is the base abstract class for diagnostic reporting in the backend.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, SetVector< GlobalValue *> *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
void gatherImportedSummariesForModule(StringRef ModulePath, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
void optimize(Module &Module)
Perform post-importing ThinLTO optimizations.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:358
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Helper to gather options relevant to the target machine creation.
TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
unsigned OptLevel
Definition: Config.h:45
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.
void thinLTOResolvePrevailingInIndex(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage)
Resolve linkage for prevailing symbols in the Index.
Definition: LTO.cpp:338
bool isWeakForLinker() const
Definition: GlobalValue.h:456
LTO configuration.
Definition: Config.h:35
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
const Triple & getTargetTriple() const
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex, uint64_t ModuleId)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1213
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:612
Function and variable summary information to aid decisions and implementation of importing.
static void internalizeAndPromoteInIndex(const StringMap< FunctionImporter::ExportSetTy > &ExportLists, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, ModuleSummaryIndex &Index)
static void write(bool isBE, void *P, T V)
bool pruneCache(StringRef Path, CachePruningPolicy Policy)
Peform pruning using the supplied policy, returns true if pruning occurred, i.e.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition: Error.cpp:61
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:209
Force files Atime to be updated on access. Only makes a difference on windows.
Definition: FileSystem.h:764
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1115
static std::string writeGeneratedObject(int count, StringRef CacheEntryPath, StringRef SavedObjectsDirectoryPath, const MemoryBuffer &OutputBuffer)
Write out the generated object file, either from CacheEntryPath or from OutputBuffer, preferring hard-link when possible.
void computeSyntheticCounts(ModuleSummaryIndex &Index)
Compute synthetic function entry counts.
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:904
void computeLTOCacheKey(SmallString< 40 > &Key, const lto::Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, const GVSummaryMapTy &DefinedGlobals, const std::set< GlobalValue::GUID > &CfiFunctionDefs={}, const std::set< GlobalValue::GUID > &CfiFunctionDecls={})
Computes a unique hash for the Module considering the current list of export/import and other global ...
Definition: LTO.cpp:69
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
const DataFlowGraph & G
Definition: RDFGraph.cpp:210
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:293
Optional< Reloc::Model > RelocModel
Definition: Config.h:41
reference get()
Returns a reference to the stored T value.
Definition: Error.h:532
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:41
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:219
Target - Wrapper for Target specific information.
Manages the enabling and disabling of subtarget specific features.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
void WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
StringRef getBufferIdentifier() const
Definition: MemoryBuffer.h:274
std::unique_ptr< ModuleSummaryIndex > linkCombinedIndex()
Produce the combined summary index from all the bitcode files: "thin-link".
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:500
static void computeDeadSymbolsInIndex(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
Definition: Verifier.cpp:4861
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
std::unique_ptr< TargetMachine > create() const
void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, StringMap< FunctionImporter::ImportMapTy > &ImportLists, StringMap< FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
Definition: BitcodeReader.h:41
MemoryBufferRef getMemBuffer() const
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:365
const char * c_str()
Definition: SmallString.h:269
size_t size() const
Definition: Module.h:605
#define I(x, y, z)
Definition: MD5.cpp:58
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:91
void preserveSymbol(StringRef Name)
Adds to a list of all global symbols that must exist in the final generated code. ...
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
void crossModuleImport(Module &Module, ModuleSummaryIndex &Index)
Perform cross-module importing for the module identified by ModuleIdentifier.
void computeDeadSymbolsWithConstProp(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing, bool ImportEnabled)
Compute dead symbols and run constant propagation in combined index after that.
void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
Definition: Statistic.cpp:228
Optional< Reloc::Model > RelocModel
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
void internalize(Module &Module, ModuleSummaryIndex &Index)
Perform internalization.
The function importer is automatically importing function from other modules based on the provided su...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:27
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:58
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target...
Definition: Config.h:53
void emitImports(Module &Module, StringRef OutputName, ModuleSummaryIndex &Index)
Compute and emit the imported files for module at ModulePath.
This pass exposes codegen information to IR-level passes.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(int FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1021
bool AreStatisticsEnabled()
Check if statistics are enabled.
Definition: Statistic.cpp:133
iterator end()
Definition: StringMap.h:317
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, GlobalValue::GUID)> isExported)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition: LTO.cpp:380
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:259