LLVM  10.0.0
LTO.cpp
Go to the documentation of this file.
1 //===-LTO.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 functions and classes used to support LTO.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/LTO/LTO.h"
14 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/Config/llvm-config.h"
21 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Metadata.h"
27 #include "llvm/IR/RemarkStreamer.h"
28 #include "llvm/LTO/LTOBackend.h"
30 #include "llvm/Linker/IRMover.h"
33 #include "llvm/Support/Error.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/SHA1.h"
38 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/Threading.h"
42 #include "llvm/Support/VCSRevision.h"
46 #include "llvm/Transforms/IPO.h"
51 
52 #include <set>
53 
54 using namespace llvm;
55 using namespace lto;
56 using namespace object;
57 
58 #define DEBUG_TYPE "lto"
59 
60 static cl::opt<bool>
61  DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
62  cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
63 
64 /// Enable global value internalization in LTO.
66  "enable-lto-internalization", cl::init(true), cl::Hidden,
67  cl::desc("Enable global value internalization in LTO"));
68 
69 // Computes a unique hash for the Module considering the current list of
70 // export/import and other global analysis results.
71 // The hash is produced in \p Key.
73  SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
74  StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
75  const FunctionImporter::ExportSetTy &ExportList,
76  const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
77  const GVSummaryMapTy &DefinedGlobals,
78  const std::set<GlobalValue::GUID> &CfiFunctionDefs,
79  const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
80  // Compute the unique hash for this entry.
81  // This is based on the current compiler version, the module itself, the
82  // export list, the hash for every single module in the import list, the
83  // list of ResolvedODR for the module, and the list of preserved symbols.
84  SHA1 Hasher;
85 
86  // Start with the compiler revision
87  Hasher.update(LLVM_VERSION_STRING);
88 #ifdef LLVM_REVISION
89  Hasher.update(LLVM_REVISION);
90 #endif
91 
92  // Include the parts of the LTO configuration that affect code generation.
93  auto AddString = [&](StringRef Str) {
94  Hasher.update(Str);
95  Hasher.update(ArrayRef<uint8_t>{0});
96  };
97  auto AddUnsigned = [&](unsigned I) {
98  uint8_t Data[4];
99  Data[0] = I;
100  Data[1] = I >> 8;
101  Data[2] = I >> 16;
102  Data[3] = I >> 24;
103  Hasher.update(ArrayRef<uint8_t>{Data, 4});
104  };
105  auto AddUint64 = [&](uint64_t I) {
106  uint8_t Data[8];
107  Data[0] = I;
108  Data[1] = I >> 8;
109  Data[2] = I >> 16;
110  Data[3] = I >> 24;
111  Data[4] = I >> 32;
112  Data[5] = I >> 40;
113  Data[6] = I >> 48;
114  Data[7] = I >> 56;
115  Hasher.update(ArrayRef<uint8_t>{Data, 8});
116  };
117  AddString(Conf.CPU);
118  // FIXME: Hash more of Options. For now all clients initialize Options from
119  // command-line flags (which is unsupported in production), but may set
120  // RelaxELFRelocations. The clang driver can also pass FunctionSections,
121  // DataSections and DebuggerTuning via command line flags.
122  AddUnsigned(Conf.Options.RelaxELFRelocations);
123  AddUnsigned(Conf.Options.FunctionSections);
124  AddUnsigned(Conf.Options.DataSections);
125  AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
126  for (auto &A : Conf.MAttrs)
127  AddString(A);
128  if (Conf.RelocModel)
129  AddUnsigned(*Conf.RelocModel);
130  else
131  AddUnsigned(-1);
132  if (Conf.CodeModel)
133  AddUnsigned(*Conf.CodeModel);
134  else
135  AddUnsigned(-1);
136  AddUnsigned(Conf.CGOptLevel);
137  AddUnsigned(Conf.CGFileType);
138  AddUnsigned(Conf.OptLevel);
139  AddUnsigned(Conf.UseNewPM);
140  AddUnsigned(Conf.Freestanding);
141  AddString(Conf.OptPipeline);
142  AddString(Conf.AAPipeline);
143  AddString(Conf.OverrideTriple);
144  AddString(Conf.DefaultTriple);
145  AddString(Conf.DwoDir);
146 
147  // Include the hash for the current module
148  auto ModHash = Index.getModuleHash(ModuleID);
149  Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
150  for (const auto &VI : ExportList) {
151  auto GUID = VI.getGUID();
152  // The export list can impact the internalization, be conservative here
153  Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
154  }
155 
156  // Include the hash for every module we import functions from. The set of
157  // imported symbols for each module may affect code generation and is
158  // sensitive to link order, so include that as well.
159  for (auto &Entry : ImportList) {
160  auto ModHash = Index.getModuleHash(Entry.first());
161  Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
162 
163  AddUint64(Entry.second.size());
164  for (auto &Fn : Entry.second)
165  AddUint64(Fn);
166  }
167 
168  // Include the hash for the resolved ODR.
169  for (auto &Entry : ResolvedODR) {
170  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
171  sizeof(GlobalValue::GUID)));
172  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
173  sizeof(GlobalValue::LinkageTypes)));
174  }
175 
176  // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
177  // defined in this module.
178  std::set<GlobalValue::GUID> UsedCfiDefs;
179  std::set<GlobalValue::GUID> UsedCfiDecls;
180 
181  // Typeids used in this module.
182  std::set<GlobalValue::GUID> UsedTypeIds;
183 
184  auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
185  if (CfiFunctionDefs.count(ValueGUID))
186  UsedCfiDefs.insert(ValueGUID);
187  if (CfiFunctionDecls.count(ValueGUID))
188  UsedCfiDecls.insert(ValueGUID);
189  };
190 
191  auto AddUsedThings = [&](GlobalValueSummary *GS) {
192  if (!GS) return;
193  AddUnsigned(GS->isLive());
194  AddUnsigned(GS->canAutoHide());
195  for (const ValueInfo &VI : GS->refs()) {
196  AddUnsigned(VI.isDSOLocal());
197  AddUsedCfiGlobal(VI.getGUID());
198  }
199  if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
200  AddUnsigned(GVS->maybeReadOnly());
201  AddUnsigned(GVS->maybeWriteOnly());
202  }
203  if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
204  for (auto &TT : FS->type_tests())
205  UsedTypeIds.insert(TT);
206  for (auto &TT : FS->type_test_assume_vcalls())
207  UsedTypeIds.insert(TT.GUID);
208  for (auto &TT : FS->type_checked_load_vcalls())
209  UsedTypeIds.insert(TT.GUID);
210  for (auto &TT : FS->type_test_assume_const_vcalls())
211  UsedTypeIds.insert(TT.VFunc.GUID);
212  for (auto &TT : FS->type_checked_load_const_vcalls())
213  UsedTypeIds.insert(TT.VFunc.GUID);
214  for (auto &ET : FS->calls()) {
215  AddUnsigned(ET.first.isDSOLocal());
216  AddUsedCfiGlobal(ET.first.getGUID());
217  }
218  }
219  };
220 
221  // Include the hash for the linkage type to reflect internalization and weak
222  // resolution, and collect any used type identifier resolutions.
223  for (auto &GS : DefinedGlobals) {
224  GlobalValue::LinkageTypes Linkage = GS.second->linkage();
225  Hasher.update(
226  ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
227  AddUsedCfiGlobal(GS.first);
228  AddUsedThings(GS.second);
229  }
230 
231  // Imported functions may introduce new uses of type identifier resolutions,
232  // so we need to collect their used resolutions as well.
233  for (auto &ImpM : ImportList)
234  for (auto &ImpF : ImpM.second) {
235  GlobalValueSummary *S = Index.findSummaryInModule(ImpF, ImpM.first());
236  AddUsedThings(S);
237  // If this is an alias, we also care about any types/etc. that the aliasee
238  // may reference.
239  if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
240  AddUsedThings(AS->getBaseObject());
241  }
242 
243  auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
244  AddString(TId);
245 
246  AddUnsigned(S.TTRes.TheKind);
247  AddUnsigned(S.TTRes.SizeM1BitWidth);
248 
249  AddUint64(S.TTRes.AlignLog2);
250  AddUint64(S.TTRes.SizeM1);
251  AddUint64(S.TTRes.BitMask);
252  AddUint64(S.TTRes.InlineBits);
253 
254  AddUint64(S.WPDRes.size());
255  for (auto &WPD : S.WPDRes) {
256  AddUnsigned(WPD.first);
257  AddUnsigned(WPD.second.TheKind);
258  AddString(WPD.second.SingleImplName);
259 
260  AddUint64(WPD.second.ResByArg.size());
261  for (auto &ByArg : WPD.second.ResByArg) {
262  AddUint64(ByArg.first.size());
263  for (uint64_t Arg : ByArg.first)
264  AddUint64(Arg);
265  AddUnsigned(ByArg.second.TheKind);
266  AddUint64(ByArg.second.Info);
267  AddUnsigned(ByArg.second.Byte);
268  AddUnsigned(ByArg.second.Bit);
269  }
270  }
271  };
272 
273  // Include the hash for all type identifiers used by this module.
274  for (GlobalValue::GUID TId : UsedTypeIds) {
275  auto TidIter = Index.typeIds().equal_range(TId);
276  for (auto It = TidIter.first; It != TidIter.second; ++It)
277  AddTypeIdSummary(It->second.first, It->second.second);
278  }
279 
280  AddUnsigned(UsedCfiDefs.size());
281  for (auto &V : UsedCfiDefs)
282  AddUint64(V);
283 
284  AddUnsigned(UsedCfiDecls.size());
285  for (auto &V : UsedCfiDecls)
286  AddUint64(V);
287 
288  if (!Conf.SampleProfile.empty()) {
289  auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
290  if (FileOrErr) {
291  Hasher.update(FileOrErr.get()->getBuffer());
292 
293  if (!Conf.ProfileRemapping.empty()) {
294  FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
295  if (FileOrErr)
296  Hasher.update(FileOrErr.get()->getBuffer());
297  }
298  }
299  }
300 
301  Key = toHex(Hasher.result());
302 }
303 
305  ValueInfo VI, DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
307  isPrevailing,
309  recordNewLinkage,
310  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
311  for (auto &S : VI.getSummaryList()) {
312  GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
313  // Ignore local and appending linkage values since the linker
314  // doesn't resolve them.
315  if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
316  GlobalValue::isAppendingLinkage(S->linkage()))
317  continue;
318  // We need to emit only one of these. The prevailing module will keep it,
319  // but turned into a weak, while the others will drop it when possible.
320  // This is both a compile-time optimization and a correctness
321  // transformation. This is necessary for correctness when we have exported
322  // a reference - we need to convert the linkonce to weak to
323  // ensure a copy is kept to satisfy the exported reference.
324  // FIXME: We may want to split the compile time and correctness
325  // aspects into separate routines.
326  if (isPrevailing(VI.getGUID(), S.get())) {
327  if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
328  S->setLinkage(GlobalValue::getWeakLinkage(
329  GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
330  // The kept copy is eligible for auto-hiding (hidden visibility) if all
331  // copies were (i.e. they were all linkonce_odr global unnamed addr).
332  // If any copy is not (e.g. it was originally weak_odr), then the symbol
333  // must remain externally available (e.g. a weak_odr from an explicitly
334  // instantiated template). Additionally, if it is in the
335  // GUIDPreservedSymbols set, that means that it is visibile outside
336  // the summary (e.g. in a native object or a bitcode file without
337  // summary), and in that case we cannot hide it as it isn't possible to
338  // check all copies.
339  S->setCanAutoHide(VI.canAutoHide() &&
340  !GUIDPreservedSymbols.count(VI.getGUID()));
341  }
342  }
343  // Alias and aliasee can't be turned into available_externally.
344  else if (!isa<AliasSummary>(S.get()) &&
345  !GlobalInvolvedWithAlias.count(S.get()))
347  if (S->linkage() != OriginalLinkage)
348  recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
349  }
350 }
351 
352 /// Resolve linkage for prevailing symbols in the \p Index.
353 //
354 // We'd like to drop these functions if they are no longer referenced in the
355 // current module. However there is a chance that another module is still
356 // referencing them because of the import. We make sure we always emit at least
357 // one copy.
361  isPrevailing,
363  recordNewLinkage,
364  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
365  // We won't optimize the globals that are referenced by an alias for now
366  // Ideally we should turn the alias into a global and duplicate the definition
367  // when needed.
368  DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
369  for (auto &I : Index)
370  for (auto &S : I.second.SummaryList)
371  if (auto AS = dyn_cast<AliasSummary>(S.get()))
372  GlobalInvolvedWithAlias.insert(&AS->getAliasee());
373 
374  for (auto &I : Index)
375  thinLTOResolvePrevailingGUID(Index.getValueInfo(I), GlobalInvolvedWithAlias,
376  isPrevailing, recordNewLinkage,
377  GUIDPreservedSymbols);
378 }
379 
381  if (auto *VarSummary = dyn_cast<GlobalVarSummary>(GVS->getBaseObject()))
382  return !VarSummary->maybeReadOnly() && !VarSummary->maybeWriteOnly() &&
383  (VarSummary->linkage() == GlobalValue::WeakODRLinkage ||
384  VarSummary->linkage() == GlobalValue::LinkOnceODRLinkage);
385  return false;
386 }
387 
389  ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
391  isPrevailing) {
392  for (auto &S : VI.getSummaryList()) {
393  if (isExported(S->modulePath(), VI)) {
394  if (GlobalValue::isLocalLinkage(S->linkage()))
395  S->setLinkage(GlobalValue::ExternalLinkage);
396  } else if (EnableLTOInternalization &&
397  // Ignore local and appending linkage values since the linker
398  // doesn't resolve them.
399  !GlobalValue::isLocalLinkage(S->linkage()) &&
400  (!GlobalValue::isInterposableLinkage(S->linkage()) ||
401  isPrevailing(VI.getGUID(), S.get())) &&
402  S->linkage() != GlobalValue::AppendingLinkage &&
403  // We can't internalize available_externally globals because this
404  // can break function pointer equality.
405  S->linkage() != GlobalValue::AvailableExternallyLinkage &&
406  // Functions and read-only variables with linkonce_odr and
407  // weak_odr linkage can be internalized. We can't internalize
408  // linkonce_odr and weak_odr variables which are both modified
409  // and read somewhere in the program because reads and writes
410  // will become inconsistent.
411  !isWeakObjectWithRWAccess(S.get()))
412  S->setLinkage(GlobalValue::InternalLinkage);
413  }
414 }
415 
416 // Update the linkages in the given \p Index to mark exported values
417 // as external and non-exported values as internal.
419  ModuleSummaryIndex &Index,
420  function_ref<bool(StringRef, ValueInfo)> isExported,
422  isPrevailing) {
423  for (auto &I : Index)
424  thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
425  isPrevailing);
426 }
427 
428 // Requires a destructor for std::vector<InputModule>.
429 InputFile::~InputFile() = default;
430 
432  std::unique_ptr<InputFile> File(new InputFile);
433 
434  Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
435  if (!FOrErr)
436  return FOrErr.takeError();
437 
438  File->TargetTriple = FOrErr->TheReader.getTargetTriple();
439  File->SourceFileName = FOrErr->TheReader.getSourceFileName();
440  File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
441  File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
442  File->ComdatTable = FOrErr->TheReader.getComdatTable();
443 
444  for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
445  size_t Begin = File->Symbols.size();
446  for (const irsymtab::Reader::SymbolRef &Sym :
447  FOrErr->TheReader.module_symbols(I))
448  // Skip symbols that are irrelevant to LTO. Note that this condition needs
449  // to match the one in Skip() in LTO::addRegularLTO().
450  if (Sym.isGlobal() && !Sym.isFormatSpecific())
451  File->Symbols.push_back(Sym);
452  File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
453  }
454 
455  File->Mods = FOrErr->Mods;
456  File->Strtab = std::move(FOrErr->Strtab);
457  return std::move(File);
458 }
459 
461  return Mods[0].getModuleIdentifier();
462 }
463 
465  assert(Mods.size() == 1 && "Expect only one bitcode module");
466  return Mods[0];
467 }
468 
469 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
470  const Config &Conf)
471  : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
472  Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
473  Mover(std::make_unique<IRMover>(*CombinedModule)) {}
474 
475 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend)
476  : Backend(Backend), CombinedIndex(/*HaveGVs*/ false) {
477  if (!Backend)
478  this->Backend =
480 }
481 
483  unsigned ParallelCodeGenParallelismLevel)
484  : Conf(std::move(Conf)),
485  RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
486  ThinLTO(std::move(Backend)) {}
487 
488 // Requires a destructor for MapVector<BitcodeModule>.
489 LTO::~LTO() = default;
490 
491 // Add the symbols in the given module to the GlobalResolutions map, and resolve
492 // their partitions.
493 void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
495  unsigned Partition, bool InSummary) {
496  auto *ResI = Res.begin();
497  auto *ResE = Res.end();
498  (void)ResE;
499  for (const InputFile::Symbol &Sym : Syms) {
500  assert(ResI != ResE);
501  SymbolResolution Res = *ResI++;
502 
503  StringRef Name = Sym.getName();
504  Triple TT(RegularLTO.CombinedModule->getTargetTriple());
505  // Strip the __imp_ prefix from COFF dllimport symbols (similar to the
506  // way they are handled by lld), otherwise we can end up with two
507  // global resolutions (one with and one for a copy of the symbol without).
508  if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_"))
509  Name = Name.substr(strlen("__imp_"));
510  auto &GlobalRes = GlobalResolutions[Name];
511  GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
512  if (Res.Prevailing) {
513  assert(!GlobalRes.Prevailing &&
514  "Multiple prevailing defs are not allowed");
515  GlobalRes.Prevailing = true;
516  GlobalRes.IRName = Sym.getIRName();
517  } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
518  // Sometimes it can be two copies of symbol in a module and prevailing
519  // symbol can have no IR name. That might happen if symbol is defined in
520  // module level inline asm block. In case we have multiple modules with
521  // the same symbol we want to use IR name of the prevailing symbol.
522  // Otherwise, if we haven't seen a prevailing symbol, set the name so that
523  // we can later use it to check if there is any prevailing copy in IR.
524  GlobalRes.IRName = Sym.getIRName();
525  }
526 
527  // Set the partition to external if we know it is re-defined by the linker
528  // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
529  // regular object, is referenced from llvm.compiler_used, or was already
530  // recorded as being referenced from a different partition.
531  if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
532  (GlobalRes.Partition != GlobalResolution::Unknown &&
533  GlobalRes.Partition != Partition)) {
534  GlobalRes.Partition = GlobalResolution::External;
535  } else
536  // First recorded reference, save the current partition.
537  GlobalRes.Partition = Partition;
538 
539  // Flag as visible outside of summary if visible from a regular object or
540  // from a module that does not have a summary.
541  GlobalRes.VisibleOutsideSummary |=
542  (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
543  }
544 }
545 
548  StringRef Path = Input->getName();
549  OS << Path << '\n';
550  auto ResI = Res.begin();
551  for (const InputFile::Symbol &Sym : Input->symbols()) {
552  assert(ResI != Res.end());
553  SymbolResolution Res = *ResI++;
554 
555  OS << "-r=" << Path << ',' << Sym.getName() << ',';
556  if (Res.Prevailing)
557  OS << 'p';
558  if (Res.FinalDefinitionInLinkageUnit)
559  OS << 'l';
560  if (Res.VisibleToRegularObj)
561  OS << 'x';
562  if (Res.LinkerRedefined)
563  OS << 'r';
564  OS << '\n';
565  }
566  OS.flush();
567  assert(ResI == Res.end());
568 }
569 
570 Error LTO::add(std::unique_ptr<InputFile> Input,
572  assert(!CalledGetMaxTasks);
573 
574  if (Conf.ResolutionFile)
575  writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
576 
577  if (RegularLTO.CombinedModule->getTargetTriple().empty())
578  RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
579 
580  const SymbolResolution *ResI = Res.begin();
581  for (unsigned I = 0; I != Input->Mods.size(); ++I)
582  if (Error Err = addModule(*Input, I, ResI, Res.end()))
583  return Err;
584 
585  assert(ResI == Res.end());
586  return Error::success();
587 }
588 
589 Error LTO::addModule(InputFile &Input, unsigned ModI,
590  const SymbolResolution *&ResI,
591  const SymbolResolution *ResE) {
592  Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
593  if (!LTOInfo)
594  return LTOInfo.takeError();
595 
596  if (EnableSplitLTOUnit.hasValue()) {
597  // If only some modules were split, flag this in the index so that
598  // we can skip or error on optimizations that need consistently split
599  // modules (whole program devirt and lower type tests).
600  if (EnableSplitLTOUnit.getValue() != LTOInfo->EnableSplitLTOUnit)
601  ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
602  } else
603  EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
604 
605  BitcodeModule BM = Input.Mods[ModI];
606  auto ModSyms = Input.module_symbols(ModI);
607  addModuleToGlobalRes(ModSyms, {ResI, ResE},
608  LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
609  LTOInfo->HasSummary);
610 
611  if (LTOInfo->IsThinLTO)
612  return addThinLTO(BM, ModSyms, ResI, ResE);
613 
615  addRegularLTO(BM, ModSyms, ResI, ResE);
616  if (!ModOrErr)
617  return ModOrErr.takeError();
618 
619  if (!LTOInfo->HasSummary)
620  return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
621 
622  // Regular LTO module summaries are added to a dummy module that represents
623  // the combined regular LTO module.
624  if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, "", -1ull))
625  return Err;
626  RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
627  return Error::success();
628 }
629 
630 // Checks whether the given global value is in a non-prevailing comdat
631 // (comdat containing values the linker indicated were not prevailing,
632 // which we then dropped to available_externally), and if so, removes
633 // it from the comdat. This is called for all global values to ensure the
634 // comdat is empty rather than leaving an incomplete comdat. It is needed for
635 // regular LTO modules, in case we are in a mixed-LTO mode (both regular
636 // and thin LTO modules) compilation. Since the regular LTO module will be
637 // linked first in the final native link, we want to make sure the linker
638 // doesn't select any of these incomplete comdats that would be left
639 // in the regular LTO module without this cleanup.
640 static void
642  std::set<const Comdat *> &NonPrevailingComdats) {
643  Comdat *C = GV.getComdat();
644  if (!C)
645  return;
646 
647  if (!NonPrevailingComdats.count(C))
648  return;
649 
650  // Additionally need to drop externally visible global values from the comdat
651  // to available_externally, so that there aren't multiply defined linker
652  // errors.
653  if (!GV.hasLocalLinkage())
655 
656  if (auto GO = dyn_cast<GlobalObject>(&GV))
657  GO->setComdat(nullptr);
658 }
659 
660 // Add a regular LTO object to the link.
661 // The resulting module needs to be linked into the combined LTO module with
662 // linkRegularLTO.
664 LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
665  const SymbolResolution *&ResI,
666  const SymbolResolution *ResE) {
667  RegularLTOState::AddedModule Mod;
669  BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
670  /*IsImporting*/ false);
671  if (!MOrErr)
672  return MOrErr.takeError();
673  Module &M = **MOrErr;
674  Mod.M = std::move(*MOrErr);
675 
676  if (Error Err = M.materializeMetadata())
677  return std::move(Err);
678  UpgradeDebugInfo(M);
679 
680  ModuleSymbolTable SymTab;
681  SymTab.addModule(&M);
682 
683  for (GlobalVariable &GV : M.globals())
684  if (GV.hasAppendingLinkage())
685  Mod.Keep.push_back(&GV);
686 
687  DenseSet<GlobalObject *> AliasedGlobals;
688  for (auto &GA : M.aliases())
689  if (GlobalObject *GO = GA.getBaseObject())
690  AliasedGlobals.insert(GO);
691 
692  // In this function we need IR GlobalValues matching the symbols in Syms
693  // (which is not backed by a module), so we need to enumerate them in the same
694  // order. The symbol enumeration order of a ModuleSymbolTable intentionally
695  // matches the order of an irsymtab, but when we read the irsymtab in
696  // InputFile::create we omit some symbols that are irrelevant to LTO. The
697  // Skip() function skips the same symbols from the module as InputFile does
698  // from the symbol table.
699  auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
700  auto Skip = [&]() {
701  while (MsymI != MsymE) {
702  auto Flags = SymTab.getSymbolFlags(*MsymI);
703  if ((Flags & object::BasicSymbolRef::SF_Global) &&
705  return;
706  ++MsymI;
707  }
708  };
709  Skip();
710 
711  std::set<const Comdat *> NonPrevailingComdats;
712  for (const InputFile::Symbol &Sym : Syms) {
713  assert(ResI != ResE);
714  SymbolResolution Res = *ResI++;
715 
716  assert(MsymI != MsymE);
717  ModuleSymbolTable::Symbol Msym = *MsymI++;
718  Skip();
719 
720  if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
721  if (Res.Prevailing) {
722  if (Sym.isUndefined())
723  continue;
724  Mod.Keep.push_back(GV);
725  // For symbols re-defined with linker -wrap and -defsym options,
726  // set the linkage to weak to inhibit IPO. The linkage will be
727  // restored by the linker.
728  if (Res.LinkerRedefined)
729  GV->setLinkage(GlobalValue::WeakAnyLinkage);
730 
731  GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
732  if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
733  GV->setLinkage(GlobalValue::getWeakLinkage(
734  GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
735  } else if (isa<GlobalObject>(GV) &&
736  (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
737  GV->hasAvailableExternallyLinkage()) &&
738  !AliasedGlobals.count(cast<GlobalObject>(GV))) {
739  // Any of the above three types of linkage indicates that the
740  // chosen prevailing symbol will have the same semantics as this copy of
741  // the symbol, so we may be able to link it with available_externally
742  // linkage. We will decide later whether to do that when we link this
743  // module (in linkRegularLTO), based on whether it is undefined.
744  Mod.Keep.push_back(GV);
746  if (GV->hasComdat())
747  NonPrevailingComdats.insert(GV->getComdat());
748  cast<GlobalObject>(GV)->setComdat(nullptr);
749  }
750 
751  // Set the 'local' flag based on the linker resolution for this symbol.
753  GV->setDSOLocal(true);
754  if (GV->hasDLLImportStorageClass())
755  GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
756  DefaultStorageClass);
757  }
758  }
759  // Common resolution: collect the maximum size/alignment over all commons.
760  // We also record if we see an instance of a common as prevailing, so that
761  // if none is prevailing we can ignore it later.
762  if (Sym.isCommon()) {
763  // FIXME: We should figure out what to do about commons defined by asm.
764  // For now they aren't reported correctly by ModuleSymbolTable.
765  auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
766  CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
767  CommonRes.Align =
768  std::max(CommonRes.Align, MaybeAlign(Sym.getCommonAlignment()));
769  CommonRes.Prevailing |= Res.Prevailing;
770  }
771 
772  }
773  if (!M.getComdatSymbolTable().empty())
774  for (GlobalValue &GV : M.global_values())
775  handleNonPrevailingComdat(GV, NonPrevailingComdats);
776  assert(MsymI == MsymE);
777  return std::move(Mod);
778 }
779 
780 Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
781  bool LivenessFromIndex) {
782  std::vector<GlobalValue *> Keep;
783  for (GlobalValue *GV : Mod.Keep) {
784  if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID()))
785  continue;
786 
787  if (!GV->hasAvailableExternallyLinkage()) {
788  Keep.push_back(GV);
789  continue;
790  }
791 
792  // Only link available_externally definitions if we don't already have a
793  // definition.
794  GlobalValue *CombinedGV =
795  RegularLTO.CombinedModule->getNamedValue(GV->getName());
796  if (CombinedGV && !CombinedGV->isDeclaration())
797  continue;
798 
799  Keep.push_back(GV);
800  }
801 
802  return RegularLTO.Mover->move(std::move(Mod.M), Keep,
804  /* IsPerformingImport */ false);
805 }
806 
807 // Add a ThinLTO module to the link.
808 Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
809  const SymbolResolution *&ResI,
810  const SymbolResolution *ResE) {
811  if (Error Err =
812  BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
813  ThinLTO.ModuleMap.size()))
814  return Err;
815 
816  for (const InputFile::Symbol &Sym : Syms) {
817  assert(ResI != ResE);
818  SymbolResolution Res = *ResI++;
819 
820  if (!Sym.getIRName().empty()) {
822  Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
823  if (Res.Prevailing) {
824  ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
825 
826  // For linker redefined symbols (via --wrap or --defsym) we want to
827  // switch the linkage to `weak` to prevent IPOs from happening.
828  // Find the summary in the module for this very GV and record the new
829  // linkage so that we can switch it when we import the GV.
830  if (Res.LinkerRedefined)
831  if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
832  GUID, BM.getModuleIdentifier()))
833  S->setLinkage(GlobalValue::WeakAnyLinkage);
834  }
835 
836  // If the linker resolved the symbol to a local definition then mark it
837  // as local in the summary for the module we are adding.
839  if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
840  GUID, BM.getModuleIdentifier())) {
841  S->setDSOLocal(true);
842  }
843  }
844  }
845  }
846 
847  if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
848  return make_error<StringError>(
849  "Expected at most one ThinLTO module per bitcode file",
851 
852  return Error::success();
853 }
854 
855 unsigned LTO::getMaxTasks() const {
856  CalledGetMaxTasks = true;
857  return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
858 }
859 
860 // If only some of the modules were split, we cannot correctly handle
861 // code that contains type tests or type checked loads.
862 Error LTO::checkPartiallySplit() {
863  if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
864  return Error::success();
865 
866  Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
867  Intrinsic::getName(Intrinsic::type_test));
868  Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
869  Intrinsic::getName(Intrinsic::type_checked_load));
870 
871  // First check if there are type tests / type checked loads in the
872  // merged regular LTO module IR.
873  if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
874  (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
875  return make_error<StringError>(
876  "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
878 
879  // Otherwise check if there are any recorded in the combined summary from the
880  // ThinLTO modules.
881  for (auto &P : ThinLTO.CombinedIndex) {
882  for (auto &S : P.second.SummaryList) {
883  auto *FS = dyn_cast<FunctionSummary>(S.get());
884  if (!FS)
885  continue;
886  if (!FS->type_test_assume_vcalls().empty() ||
887  !FS->type_checked_load_vcalls().empty() ||
888  !FS->type_test_assume_const_vcalls().empty() ||
889  !FS->type_checked_load_const_vcalls().empty() ||
890  !FS->type_tests().empty())
891  return make_error<StringError>(
892  "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
894  }
895  }
896  return Error::success();
897 }
898 
900  // Compute "dead" symbols, we don't want to import/export these!
901  DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
902  DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
903  for (auto &Res : GlobalResolutions) {
904  // Normally resolution have IR name of symbol. We can do nothing here
905  // otherwise. See comments in GlobalResolution struct for more details.
906  if (Res.second.IRName.empty())
907  continue;
908 
910  GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
911 
912  if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
913  GUIDPreservedSymbols.insert(GUID);
914 
915  GUIDPrevailingResolutions[GUID] =
916  Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
917  }
918 
919  auto isPrevailing = [&](GlobalValue::GUID G) {
920  auto It = GUIDPrevailingResolutions.find(G);
921  if (It == GUIDPrevailingResolutions.end())
923  return It->second;
924  };
925  computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
926  isPrevailing, Conf.OptLevel > 0);
927 
928  // Setup output file to emit statistics.
929  auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
930  if (!StatsFileOrErr)
931  return StatsFileOrErr.takeError();
932  std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
933 
934  // Finalize linking of regular LTO modules containing summaries now that
935  // we have computed liveness information.
936  for (auto &M : RegularLTO.ModsWithSummaries)
937  if (Error Err = linkRegularLTO(std::move(M),
938  /*LivenessFromIndex=*/true))
939  return Err;
940 
941  // Ensure we don't have inconsistently split LTO units with type tests.
942  if (Error Err = checkPartiallySplit())
943  return Err;
944 
945  Error Result = runRegularLTO(AddStream);
946  if (!Result)
947  Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
948 
949  if (StatsFile)
950  PrintStatisticsJSON(StatsFile->os());
951 
952  return Result;
953 }
954 
955 Error LTO::runRegularLTO(AddStreamFn AddStream) {
956  // Make sure commons have the right size/alignment: we kept the largest from
957  // all the prevailing when adding the inputs, and we apply it here.
958  const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
959  for (auto &I : RegularLTO.Commons) {
960  if (!I.second.Prevailing)
961  // Don't do anything if no instance of this common was prevailing.
962  continue;
963  GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
964  if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
965  // Don't create a new global if the type is already correct, just make
966  // sure the alignment is correct.
967  OldGV->setAlignment(I.second.Align);
968  continue;
969  }
970  ArrayType *Ty =
971  ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
972  auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
975  GV->setAlignment(I.second.Align);
976  if (OldGV) {
978  GV->takeName(OldGV);
979  OldGV->eraseFromParent();
980  } else {
981  GV->setName(I.first);
982  }
983  }
984 
985  if (Conf.PreOptModuleHook &&
986  !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
987  return Error::success();
988 
989  if (!Conf.CodeGenOnly) {
990  for (const auto &R : GlobalResolutions) {
991  if (!R.second.isPrevailingIRSymbol())
992  continue;
993  if (R.second.Partition != 0 &&
994  R.second.Partition != GlobalResolution::External)
995  continue;
996 
997  GlobalValue *GV =
998  RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
999  // Ignore symbols defined in other partitions.
1000  // Also skip declarations, which are not allowed to have internal linkage.
1001  if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1002  continue;
1003  GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1005  if (EnableLTOInternalization && R.second.Partition == 0)
1007  }
1008 
1009  RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
1010 
1011  if (Conf.PostInternalizeModuleHook &&
1012  !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1013  return Error::success();
1014  }
1015  return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1016  std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
1017 }
1018 
1019 static const char *libcallRoutineNames[] = {
1020 #define HANDLE_LIBCALL(code, name) name,
1021 #include "llvm/IR/RuntimeLibcalls.def"
1022 #undef HANDLE_LIBCALL
1023 };
1024 
1026  return makeArrayRef(libcallRoutineNames);
1027 }
1028 
1029 /// This class defines the interface to the ThinLTO backend.
1031 protected:
1032  const Config &Conf;
1035 
1036 public:
1037  ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1038  const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
1039  : Conf(Conf), CombinedIndex(CombinedIndex),
1040  ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
1041 
1042  virtual ~ThinBackendProc() {}
1043  virtual Error start(
1044  unsigned Task, BitcodeModule BM,
1045  const FunctionImporter::ImportMapTy &ImportList,
1046  const FunctionImporter::ExportSetTy &ExportList,
1047  const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1048  MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
1049  virtual Error wait() = 0;
1050 };
1051 
1052 namespace {
1053 class InProcessThinBackend : public ThinBackendProc {
1054  ThreadPool BackendThreadPool;
1055  AddStreamFn AddStream;
1056  NativeObjectCache Cache;
1057  std::set<GlobalValue::GUID> CfiFunctionDefs;
1058  std::set<GlobalValue::GUID> CfiFunctionDecls;
1059 
1060  Optional<Error> Err;
1061  std::mutex ErrMu;
1062 
1063 public:
1064  InProcessThinBackend(
1065  const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1066  unsigned ThinLTOParallelismLevel,
1067  const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1068  AddStreamFn AddStream, NativeObjectCache Cache)
1069  : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
1070  BackendThreadPool(ThinLTOParallelismLevel),
1071  AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
1072  for (auto &Name : CombinedIndex.cfiFunctionDefs())
1073  CfiFunctionDefs.insert(
1075  for (auto &Name : CombinedIndex.cfiFunctionDecls())
1076  CfiFunctionDecls.insert(
1078  }
1079 
1080  Error runThinLTOBackendThread(
1081  AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
1082  BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1083  const FunctionImporter::ImportMapTy &ImportList,
1084  const FunctionImporter::ExportSetTy &ExportList,
1085  const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1086  const GVSummaryMapTy &DefinedGlobals,
1088  auto RunThinBackend = [&](AddStreamFn AddStream) {
1089  LTOLLVMContext BackendContext(Conf);
1090  Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1091  if (!MOrErr)
1092  return MOrErr.takeError();
1093 
1094  return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1095  ImportList, DefinedGlobals, ModuleMap);
1096  };
1097 
1098  auto ModuleID = BM.getModuleIdentifier();
1099 
1100  if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
1101  all_of(CombinedIndex.getModuleHash(ModuleID),
1102  [](uint32_t V) { return V == 0; }))
1103  // Cache disabled or no entry for this module in the combined index or
1104  // no module hash.
1105  return RunThinBackend(AddStream);
1106 
1108  // The module may be cached, this helps handling it.
1109  computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList,
1110  ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
1111  CfiFunctionDecls);
1112  if (AddStreamFn CacheAddStream = Cache(Task, Key))
1113  return RunThinBackend(CacheAddStream);
1114 
1115  return Error::success();
1116  }
1117 
1118  Error start(
1119  unsigned Task, BitcodeModule BM,
1120  const FunctionImporter::ImportMapTy &ImportList,
1121  const FunctionImporter::ExportSetTy &ExportList,
1122  const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1123  MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1124  StringRef ModulePath = BM.getModuleIdentifier();
1125  assert(ModuleToDefinedGVSummaries.count(ModulePath));
1126  const GVSummaryMapTy &DefinedGlobals =
1127  ModuleToDefinedGVSummaries.find(ModulePath)->second;
1128  BackendThreadPool.async(
1129  [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1130  const FunctionImporter::ImportMapTy &ImportList,
1131  const FunctionImporter::ExportSetTy &ExportList,
1132  const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1133  &ResolvedODR,
1134  const GVSummaryMapTy &DefinedGlobals,
1136  Error E = runThinLTOBackendThread(
1137  AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1138  ResolvedODR, DefinedGlobals, ModuleMap);
1139  if (E) {
1140  std::unique_lock<std::mutex> L(ErrMu);
1141  if (Err)
1142  Err = joinErrors(std::move(*Err), std::move(E));
1143  else
1144  Err = std::move(E);
1145  }
1146  },
1147  BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1148  std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1149  return Error::success();
1150  }
1151 
1152  Error wait() override {
1153  BackendThreadPool.wait();
1154  if (Err)
1155  return std::move(*Err);
1156  else
1157  return Error::success();
1158  }
1159 };
1160 } // end anonymous namespace
1161 
1162 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
1163  return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1164  const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1165  AddStreamFn AddStream, NativeObjectCache Cache) {
1166  return std::make_unique<InProcessThinBackend>(
1167  Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
1168  AddStream, Cache);
1169  };
1170 }
1171 
1172 // Given the original \p Path to an output file, replace any path
1173 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1174 // resulting directory if it does not yet exist.
1175 std::string lto::getThinLTOOutputFile(const std::string &Path,
1176  const std::string &OldPrefix,
1177  const std::string &NewPrefix) {
1178  if (OldPrefix.empty() && NewPrefix.empty())
1179  return Path;
1180  SmallString<128> NewPath(Path);
1181  llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1182  StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1183  if (!ParentPath.empty()) {
1184  // Make sure the new directory exists, creating it if necessary.
1185  if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1186  llvm::errs() << "warning: could not create directory '" << ParentPath
1187  << "': " << EC.message() << '\n';
1188  }
1189  return NewPath.str();
1190 }
1191 
1192 namespace {
1193 class WriteIndexesThinBackend : public ThinBackendProc {
1194  std::string OldPrefix, NewPrefix;
1195  bool ShouldEmitImportsFiles;
1196  raw_fd_ostream *LinkedObjectsFile;
1197  lto::IndexWriteCallback OnWrite;
1198 
1199 public:
1200  WriteIndexesThinBackend(
1201  const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1202  const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1203  std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1204  raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1205  : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
1206  OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1207  ShouldEmitImportsFiles(ShouldEmitImportsFiles),
1208  LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {}
1209 
1210  Error start(
1211  unsigned Task, BitcodeModule BM,
1212  const FunctionImporter::ImportMapTy &ImportList,
1213  const FunctionImporter::ExportSetTy &ExportList,
1214  const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1215  MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1216  StringRef ModulePath = BM.getModuleIdentifier();
1217  std::string NewModulePath =
1218  getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
1219 
1220  if (LinkedObjectsFile)
1221  *LinkedObjectsFile << NewModulePath << '\n';
1222 
1223  std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1224  gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
1225  ImportList, ModuleToSummariesForIndex);
1226 
1227  std::error_code EC;
1228  raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
1230  if (EC)
1231  return errorCodeToError(EC);
1232  WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
1233 
1234  if (ShouldEmitImportsFiles) {
1235  EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
1236  ModuleToSummariesForIndex);
1237  if (EC)
1238  return errorCodeToError(EC);
1239  }
1240 
1241  if (OnWrite)
1242  OnWrite(ModulePath);
1243  return Error::success();
1244  }
1245 
1246  Error wait() override { return Error::success(); }
1247 };
1248 } // end anonymous namespace
1249 
1251  std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1252  raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) {
1253  return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1254  const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1255  AddStreamFn AddStream, NativeObjectCache Cache) {
1256  return std::make_unique<WriteIndexesThinBackend>(
1257  Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
1258  ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
1259  };
1260 }
1261 
1262 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
1263  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
1264  if (ThinLTO.ModuleMap.empty())
1265  return Error::success();
1266 
1267  if (Conf.CombinedIndexHook &&
1268  !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
1269  return Error::success();
1270 
1271  // Collect for each module the list of function it defines (GUID ->
1272  // Summary).
1274  ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
1275  ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1276  ModuleToDefinedGVSummaries);
1277  // Create entries for any modules that didn't have any GV summaries
1278  // (either they didn't have any GVs to start with, or we suppressed
1279  // generation of the summaries because they e.g. had inline assembly
1280  // uses that couldn't be promoted/renamed on export). This is so
1281  // InProcessThinBackend::start can still launch a backend thread, which
1282  // is passed the map of summaries for the module, without any special
1283  // handling for this case.
1284  for (auto &Mod : ThinLTO.ModuleMap)
1285  if (!ModuleToDefinedGVSummaries.count(Mod.first))
1286  ModuleToDefinedGVSummaries.try_emplace(Mod.first);
1287 
1288  // Synthesize entry counts for functions in the CombinedIndex.
1289  computeSyntheticCounts(ThinLTO.CombinedIndex);
1290 
1292  ThinLTO.ModuleMap.size());
1294  ThinLTO.ModuleMap.size());
1296 
1297  if (DumpThinCGSCCs)
1298  ThinLTO.CombinedIndex.dumpSCCs(outs());
1299 
1300  std::set<GlobalValue::GUID> ExportedGUIDs;
1301 
1302  // Perform index-based WPD. This will return immediately if there are
1303  // no index entries in the typeIdMetadata map (e.g. if we are instead
1304  // performing IR-based WPD in hybrid regular/thin LTO mode).
1305  std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1306  runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
1307  LocalWPDTargetsMap);
1308 
1309  if (Conf.OptLevel > 0)
1310  ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1311  ImportLists, ExportLists);
1312 
1313  // Figure out which symbols need to be internalized. This also needs to happen
1314  // at -O0 because summary-based DCE is implemented using internalization, and
1315  // we must apply DCE consistently with the full LTO module in order to avoid
1316  // undefined references during the final link.
1317  for (auto &Res : GlobalResolutions) {
1318  // If the symbol does not have external references or it is not prevailing,
1319  // then not need to mark it as exported from a ThinLTO partition.
1320  if (Res.second.Partition != GlobalResolution::External ||
1321  !Res.second.isPrevailingIRSymbol())
1322  continue;
1323  auto GUID = GlobalValue::getGUID(
1324  GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1325  // Mark exported unless index-based analysis determined it to be dead.
1326  if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1327  ExportedGUIDs.insert(GUID);
1328  }
1329 
1330  // Any functions referenced by the jump table in the regular LTO object must
1331  // be exported.
1332  for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1333  ExportedGUIDs.insert(
1335 
1336  auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
1337  const auto &ExportList = ExportLists.find(ModuleIdentifier);
1338  return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
1339  ExportedGUIDs.count(VI.getGUID());
1340  };
1341 
1342  // Update local devirtualized targets that were exported by cross-module
1343  // importing or by other devirtualizations marked in the ExportedGUIDs set.
1344  updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
1345  LocalWPDTargetsMap);
1346 
1347  auto isPrevailing = [&](GlobalValue::GUID GUID,
1348  const GlobalValueSummary *S) {
1349  return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1350  };
1351  thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
1352  isPrevailing);
1353 
1354  auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1355  GlobalValue::GUID GUID,
1356  GlobalValue::LinkageTypes NewLinkage) {
1357  ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1358  };
1359  thinLTOResolvePrevailingInIndex(ThinLTO.CombinedIndex, isPrevailing,
1360  recordNewLinkage, GUIDPreservedSymbols);
1361 
1362  std::unique_ptr<ThinBackendProc> BackendProc =
1363  ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1364  AddStream, Cache);
1365 
1366  // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for combined
1367  // module and parallel code generation partitions.
1368  unsigned Task = RegularLTO.ParallelCodeGenParallelismLevel;
1369  for (auto &Mod : ThinLTO.ModuleMap) {
1370  if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1371  ExportLists[Mod.first],
1372  ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1373  return E;
1374  ++Task;
1375  }
1376 
1377  return BackendProc->wait();
1378 }
1379 
1383  bool RemarksWithHotness, int Count) {
1384  std::string Filename = RemarksFilename;
1385  // For ThinLTO, file.opt.<format> becomes
1386  // file.opt.<format>.thin.<num>.<format>.
1387  if (!Filename.empty() && Count != -1)
1388  Filename =
1389  (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
1390  .str();
1391 
1392  auto ResultOrErr = llvm::setupOptimizationRemarks(
1393  Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness);
1394  if (Error E = ResultOrErr.takeError())
1395  return std::move(E);
1396 
1397  if (*ResultOrErr)
1398  (*ResultOrErr)->keep();
1399 
1400  return ResultOrErr;
1401 }
1402 
1405  // Setup output file to emit statistics.
1406  if (StatsFilename.empty())
1407  return nullptr;
1408 
1409  llvm::EnableStatistics(false);
1410  std::error_code EC;
1411  auto StatsFile =
1412  std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
1413  if (EC)
1414  return errorCodeToError(EC);
1415 
1416  StatsFile->keep();
1417  return std::move(StatsFile);
1418 }
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time...
Definition: GlobalValue.h:346
uint64_t CallInst * C
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:938
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
ArrayRef< Symbol > symbols() const
A range over the symbols in this InputFile.
Definition: LTO.h:157
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
This class defines the interface to the ThinLTO backend.
Definition: LTO.cpp:1030
bool hasLocalLinkage() const
Definition: GlobalValue.h:445
std::string CPU
Definition: Config.h:41
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:54
std::string AAPipeline
Definition: Config.h:72
uint32_t getSymbolFlags(Symbol S) const
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition: LTO.cpp:418
LLVMContext & Context
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition: LTO.h:440
CodeGenOpt::Level CGOptLevel
Definition: Config.h:46
BitcodeModule & getSingleBitcodeModule()
Definition: LTO.cpp:464
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:502
This class represents lattice values for constants.
Definition: AllocatorList.h:23
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
Definition: Threading.cpp:82
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
iterator begin() const
Definition: ArrayRef.h:146
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:53
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
The purpose of this class is to only expose the symbol information that an LTO client should need in ...
Definition: LTO.h:132
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:277
Implements a dense probed hash-table based set.
Definition: DenseSet.h:249
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Definition: Config.h:76
Available for inspection, not emission.
Definition: GlobalValue.h:49
unsigned DataSections
Emit data into separate sections.
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1414
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.
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Definition: Config.h:59
Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, uint64_t ModuleId)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:432
This file contains the declarations for metadata subclasses.
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition: LTO.h:451
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
Definition: Config.h:130
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:99
iterator find(StringRef Key)
Definition: StringMap.h:355
const StringMap< std::pair< uint64_t, ModuleHash > > & modulePaths() const
Table of modules, containing module hash and id.
Externally visible function.
Definition: GlobalValue.h:48
The resolution for a symbol.
Definition: LTO.h:434
This class implements a map that also provides access to all stored values in a deterministic order...
Definition: MapVector.h:37
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:1182
const StringMap< GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition: LTO.cpp:1034
A class that wrap the SHA1 algorithm.
Definition: SHA1.h:28
static Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition: LTO.cpp:431
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
static void thinLTOResolvePrevailingGUID(ValueInfo VI, DenseSet< GlobalValueSummary *> &GlobalInvolvedWithAlias, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Definition: LTO.cpp:304
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
Definition: Globals.cpp:160
std::function< void(const std::string &)> IndexWriteCallback
This ThinBackend writes individual module indexes to files, instead of running the individual backend...
Definition: LTO.h:245
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:54
StringRef getModuleIdentifier() const
Definition: BitcodeReader.h:92
Tentative definitions.
Definition: GlobalValue.h:58
ThinBackend createWriteIndexesThinBackend(std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite)
Definition: LTO.cpp:1250
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:330
static bool isLinkOnceLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:309
CombinedIndexHookFn CombinedIndexHook
Definition: Config.h:195
StringRef getName() const
Returns the path to the InputFile.
Definition: LTO.cpp:460
static void thinLTOInternalizeAndPromoteGUID(ValueInfo VI, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Definition: LTO.cpp:388
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
Definition: PointerUnion.h:201
GlobalValue::GUID getGUID() const
Definition: BitVector.h:937
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:659
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
Represents a module in a bitcode file.
Definition: BitcodeReader.h:57
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:460
std::string DwoDir
The directory to store .dwo files.
Definition: Config.h:92
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module&#39;s symbol table for COMDATs (constant).
Definition: Module.h:574
std::vector< std::string > MAttrs
Definition: Config.h:43
void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary >> &LocalWPDTargetsMap)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
std::string ProfileRemapping
Name remapping file for profile data.
Definition: Config.h:89
ModuleSummaryIndex & CombinedIndex
Definition: LTO.cpp:1033
const TypeIdSummaryMapTy & typeIds() const
ArrayRef< Symbol > symbols() const
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:600
StringRef result()
Return a reference to the current raw 160-bits SHA1 for the digested data since the last call to init...
Definition: SHA1.cpp:284
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:306
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:266
Key
PAL metadata keys.
Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
Definition: LTOBackend.cpp:448
constexpr Align()=default
Default is byte-aligned.
const T & getValue() const LLVM_LVALUE_FUNCTION
Definition: Optional.h:255
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries)
Definition: LTO.cpp:1037
Class to represent array types.
Definition: DerivedTypes.h:408
std::string SampleProfile
Sample PGO profile path.
Definition: Config.h:86
bool canAutoHide() const
Checks if all copies are eligible for auto-hiding (have flag set).
TargetOptions Options
Definition: Config.h:42
unsigned FunctionSections
Emit functions into separate sections.
Optional< CodeModel::Model > CodeModel
Definition: Config.h:45
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:25
An input file.
Definition: LTO.h:104
A ThreadPool for asynchronous parallel execution on a defined number of threads.
Definition: ThreadPool.h:36
static bool isAppendingLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:321
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:430
static ArrayRef< const char * > getRuntimeLibcallSymbols()
Static method that returns a list of libcall symbols that can be generated by LTO but might not be vi...
Definition: LTO.cpp:1025
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&... Args)
Emplace a new element for the specified key into the map if the key isn&#39;t already in the map...
Definition: StringMap.h:432
Class to hold module path string table and global value map, and encapsulate methods for operating on...
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition: LTO.cpp:1404
void update(ArrayRef< uint8_t > Data)
Digest more data.
Definition: SHA1.cpp:213
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1872
Ephemeral symbols produced by Reader::symbols() and Reader::module_symbols().
Definition: IRSymtab.h:306
Error add(std::unique_ptr< InputFile > Obj, ArrayRef< SymbolResolution > Res)
Add an input file to the LTO link, using the provided symbol resolutions.
Definition: LTO.cpp:570
std::function< std::unique_ptr< ThinBackendProc >(const Config &C, ModuleSummaryIndex &CombinedIndex, StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, NativeObjectCache Cache)> ThinBackend
A ThinBackend defines what happens after the thin-link phase during ThinLTO.
Definition: LTO.h:227
DebuggerKind DebuggerTuning
Which debugger to tune for.
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
#define P(N)
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:51
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
Definition: Config.h:163
Emits an error if two values disagree, otherwise the resulting value is that of the operands...
Definition: Module.h:117
static cl::opt< bool > DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden, cl::desc("Dump the SCCs in the ThinLTO index's callgraph"))
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.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:381
void runWholeProgramDevirtOnIndex(ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary >> &LocalWPDTargetsMap)
Perform index-based whole program devirtualization on the Summary index.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:63
Instrumentation for Order File
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:486
bool UseNewPM
Use the new pass manager.
Definition: Config.h:52
Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > &ModuleMap)
Runs a ThinLTO backend.
Definition: LTOBackend.cpp:502
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
unsigned OptLevel
Definition: Config.h:48
std::function< AddStreamFn(unsigned Task, StringRef Key)> NativeObjectCache
This is the type of a native object cache.
Definition: LTO.h:219
void eraseFromParent()
eraseFromParent - This method unlinks &#39;this&#39; from the containing module and deletes it...
Definition: Globals.cpp:384
const Config & Conf
Definition: LTO.cpp:1032
LTO configuration.
Definition: Config.h:38
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
Definition: Config.h:80
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition: GlobalValue.h:69
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
void thinLTOResolvePrevailingInIndex(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Resolve linkage for prevailing symbols in the Index.
Definition: LTO.cpp:358
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:466
bool replace_path_prefix(SmallVectorImpl< char > &Path, const StringRef &OldPrefix, const StringRef &NewPrefix, Style style=Style::native, bool strict=false)
Replace matching path prefix with another path.
Definition: Path.cpp:499
Function and variable summary information to aid decisions and implementation of importing.
static GUID getGUID(StringRef GlobalName)
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:506
std::string StatsFile
Statistics output file path.
Definition: Config.h:121
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition: Config.h:170
static bool isWeakObjectWithRWAccess(GlobalValueSummary *GVS)
Definition: LTO.cpp:380
std::function< std::unique_ptr< NativeObjectStream >(unsigned Task)> AddStreamFn
This type defines the callback to add a native object that is generated on the fly.
Definition: LTO.h:204
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
static LinkageTypes getWeakLinkage(bool ODR)
Definition: GlobalValue.h:296
Struct that holds a reference to a particular GUID in a global value summary.
static void writeToResolutionFile(raw_ostream &OS, InputFile *Input, ArrayRef< SymbolResolution > Res)
Definition: LTO.cpp:546
void computeSyntheticCounts(ModuleSummaryIndex &Index)
Compute synthetic function entry counts.
void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
Definition: Statistic.cpp:200
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
GlobalValueSummary * getBaseObject()
If this is an alias summary, returns the summary of the aliased object (a global variable or function...
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
Definition: LTO.cpp:855
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
Definition: Alignment.h:117
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:72
iterator end() const
Definition: ArrayRef.h:147
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
virtual ~ThinBackendProc()
Definition: LTO.cpp:1042
Optional< Reloc::Model > RelocModel
Definition: Config.h:44
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:454
The access may modify the value stored in memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:242
const Comdat * getComdat() const
Definition: Globals.cpp:175
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character &#39;\1&#39;, drop it.
Definition: GlobalValue.h:481
CodeGenFileType CGFileType
Definition: Config.h:47
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
Definition: Config.h:67
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 ...
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:510
unsigned RelaxELFRelocations
ThinBackend createInProcessThinBackend(unsigned ParallelismLevel)
This ThinBackend runs the individual backend jobs in-process.
Definition: LTO.cpp:1162
static const char * libcallRoutineNames[]
Definition: LTO.cpp:1019
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, unsigned RemarksHotnessThreshold=0)
Setup optimization remarks that output to a file.
std::set< std::string > & cfiFunctionDefs()
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.
bool hasValue() const
Definition: Optional.h:259
void setAlignment(MaybeAlign Align)
Definition: Globals.cpp:116
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:397
LTO(Config Conf, ThinBackend Backend=nullptr, unsigned ParallelCodeGenParallelismLevel=1)
Create an LTO object.
Definition: LTO.cpp:482
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:219
static void handleNonPrevailingComdat(GlobalValue &GV, std::set< const Comdat *> &NonPrevailingComdats)
Definition: LTO.cpp:641
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:423
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
#define I(x, y, z)
Definition: MD5.cpp:58
Error run(AddStreamFn AddStream, NativeObjectCache Cache=nullptr)
Runs the LTO pipeline.
Definition: LTO.cpp:899
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:587
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Type * getValueType() const
Definition: GlobalValue.h:279
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
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
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
Function summary information to aid decisions and implementation of importing.
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition: LTO.h:447
cl::opt< bool > EnableLTOInternalization("enable-lto-internalization", cl::init(true), cl::Hidden, cl::desc("Enable global value internalization in LTO"))
Enable global value internalization in LTO.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
const GlobalObject * getBaseObject() const
Definition: Globals.cpp:286
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 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.
bool empty() const
Definition: StringMap.h:110
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::set< std::string > & cfiFunctionDecls()
std::function< void(GlobalValue &)> ValueAdder
Definition: IRMover.h:64
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1381
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
void EnableStatistics(bool DoPrintOnExit=true)
Enable the collection and printing of statistics.
Definition: Statistic.cpp:126
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting)
Read the bitcode module and prepare for lazy deserialization of function bodies.
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context)
Read the entire bitcode module and return it.
iterator_range< global_iterator > globals()
Definition: Module.h:588
A derived class of LLVMContext that initializes itself according to a given Config object...
Definition: Config.h:230
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target...
Definition: Config.h:56
This pass exposes codegen information to IR-level passes.
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit...
Definition: LTO.h:444
Expected< IRSymtabFile > readIRSymtab(MemoryBufferRef MBRef)
Reads a bitcode file, creating its irsymtab if necessary.
std::string toHex(StringRef Input, bool LowerCase=false)
Convert buffer Input to its hexadecimal representation.
Definition: StringExtras.h:141
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
Definition: ThreadPool.cpp:71
llvm::Error materializeMetadata()
Definition: Module.cpp:424
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:178
bool use_empty() const
Definition: Value.h:343
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:277
std::string getThinLTOOutputFile(const std::string &Path, const std::string &OldPrefix, const std::string &NewPrefix)
Given the original Path to an output file, replace any path prefix matching OldPrefix with NewPrefix...
Definition: LTO.cpp:1175
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:153
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition: PointerUnion.h:156
iterator_range< alias_iterator > aliases()
Definition: Module.h:628
iterator_range< global_value_iterator > global_values()
Definition: Module.cpp:392