LLVM 24.0.0git
FunctionImport.cpp
Go to the documentation of this file.
1//===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
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 Function import based on summaries.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringRef.h"
22#include "llvm/IR/AutoUpgrade.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/GlobalAlias.h"
27#include "llvm/IR/GlobalValue.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Metadata.h"
31#include "llvm/IR/Module.h"
34#include "llvm/Linker/IRMover.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/Errc.h"
40#include "llvm/Support/Error.h"
43#include "llvm/Support/JSON.h"
44#include "llvm/Support/Path.h"
53#include <cassert>
54#include <memory>
55#include <string>
56#include <system_error>
57#include <tuple>
58#include <utility>
59
60using namespace llvm;
61
62#define DEBUG_TYPE "function-import"
63
64STATISTIC(NumImportedFunctionsThinLink,
65 "Number of functions thin link decided to import");
66STATISTIC(NumImportedHotFunctionsThinLink,
67 "Number of hot functions thin link decided to import");
68STATISTIC(NumImportedCriticalFunctionsThinLink,
69 "Number of critical functions thin link decided to import");
70STATISTIC(NumImportedGlobalVarsThinLink,
71 "Number of global variables thin link decided to import");
72STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
73STATISTIC(NumImportedFunctionDecls,
74 "Number of function declarations imported in backend");
75STATISTIC(NumImportedGlobalVars,
76 "Number of global variables imported in backend");
77STATISTIC(NumImportedModules, "Number of modules imported from");
78STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
79STATISTIC(NumLiveSymbols, "Number of live symbols in index");
80
81namespace llvm {
83
85 ForceImportAll("force-import-all", cl::init(false), cl::Hidden,
86 cl::desc("Import functions with noinline attribute"));
87
88/// Limit on instruction count of imported functions.
90 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
91 cl::desc("Only import functions with less than N instructions"));
92
94 "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
95 cl::desc("Only import first N functions if N>=0 (default -1)"));
96
97static cl::opt<float>
98 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
100 cl::desc("As we import functions, multiply the "
101 "`import-instr-limit` threshold by this factor "
102 "before processing newly imported functions"));
103
105 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
106 cl::value_desc("x"),
107 cl::desc("As we import functions called from hot callsite, multiply the "
108 "`import-instr-limit` threshold by this factor "
109 "before processing newly imported functions"));
110
112 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
113 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
114
116 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
117 cl::value_desc("x"),
118 cl::desc(
119 "Multiply the `import-instr-limit` threshold for critical callsites"));
120
121// FIXME: This multiplier was not really tuned up.
123 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
124 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
125
126static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
127 cl::desc("Print imported functions"));
128
130 "print-import-failures", cl::init(false), cl::Hidden,
131 cl::desc("Print information for functions rejected for importing"));
132
133static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
134 cl::desc("Compute dead symbols"));
135
137 "enable-import-metadata", cl::init(false), cl::Hidden,
138 cl::desc("Enable import metadata like 'thinlto_src_module' and "
139 "'thinlto_src_file'"));
140
141/// Summary file to use for function importing when using -function-import from
142/// the command line.
144 SummaryFile("summary-file",
145 cl::desc("The summary file to use for function importing."));
146
147/// Used when testing importing from distributed indexes via opt
148// -function-import.
149static cl::opt<bool>
150 ImportAllIndex("import-all-index",
151 cl::desc("Import all external functions in index."));
152
153/// This is a test-only option.
154/// If this option is enabled, the ThinLTO indexing step will import each
155/// function declaration as a fallback. In a real build this may increase ram
156/// usage of the indexing step unnecessarily.
157/// TODO: Implement selective import (based on combined summary analysis) to
158/// ensure the imported function has a use case in the postlink pipeline.
160 "import-declaration", cl::init(false), cl::Hidden,
161 cl::desc("If true, import function declaration as fallback if the function "
162 "definition is not imported."));
163
164/// Pass a workload description file - an example of workload would be the
165/// functions executed to satisfy a RPC request. A workload is defined by a root
166/// function and the list of functions that are (frequently) needed to satisfy
167/// it. The module that defines the root will have all those functions imported.
168/// The file contains a JSON dictionary. The keys are root functions, the values
169/// are lists of functions to import in the module defining the root. It is
170/// assumed -funique-internal-linkage-names was used, thus ensuring function
171/// names are unique even for local linkage ones.
173 "thinlto-workload-def",
174 cl::desc("Pass a workload definition. This is a file containing a JSON "
175 "dictionary. The keys are root functions, the values are lists of "
176 "functions to import in the module defining the root. It is "
177 "assumed -funique-internal-linkage-names was used, to ensure "
178 "local linkage functions have unique names. For example: \n"
179 "{\n"
180 " \"rootFunction_1\": [\"function_to_import_1\", "
181 "\"function_to_import_2\"], \n"
182 " \"rootFunction_2\": [\"function_to_import_3\", "
183 "\"function_to_import_4\"] \n"
184 "}"),
185 cl::Hidden);
186
188
190 "thinlto-move-ctxprof-trees",
191 cl::desc("Move contextual profiling roots and the graphs under them in "
192 "their own module."),
193 cl::Hidden, cl::init(false));
194
196
198} // end namespace llvm
199
200// Load lazily a module from \p FileName in \p Context.
201static std::unique_ptr<Module> loadFile(const std::string &FileName,
202 LLVMContext &Context) {
203 SMDiagnostic Err;
204 LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
205 // Metadata isn't loaded until functions are imported, to minimize
206 // the memory overhead.
207 std::unique_ptr<Module> Result =
208 getLazyIRFileModule(FileName, Err, Context,
209 /* ShouldLazyLoadMetadata = */ true);
210 if (!Result) {
211 Err.print("function-import", errs());
212 report_fatal_error("Abort");
213 }
214
215 return Result;
216}
217
219 size_t NumDefs,
220 StringRef ImporterModule) {
221 // We can import a local when there is one definition.
222 if (NumDefs == 1)
223 return false;
224 // In other cases, make sure we import the copy in the caller's module if the
225 // referenced value has local linkage. The only time a local variable can
226 // share an entry in the index is if there is a local with the same name in
227 // another module that had the same source file name (in a different
228 // directory), where each was compiled in their own directory so there was not
229 // distinguishing path.
230 return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
231 RefSummary->modulePath() != ImporterModule;
232}
233
234/// Given a list of possible callee implementation for a call site, qualify the
235/// legality of importing each. The return is a range of pairs. Each pair
236/// corresponds to a candidate. The first value is the ImportFailureReason for
237/// that candidate, the second is the candidate.
239 const ModuleSummaryIndex &Index,
240 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
241 StringRef CallerModulePath) {
242 return llvm::map_range(
243 CalleeSummaryList,
244 [&Index, CalleeSummaryList,
245 CallerModulePath](const std::unique_ptr<GlobalValueSummary> &SummaryPtr)
247 const GlobalValueSummary *> {
248 auto *GVSummary = SummaryPtr.get();
249 if (!Index.isGlobalValueLive(GVSummary))
251
252 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
254 GVSummary};
255
256 auto *Summary = dyn_cast<FunctionSummary>(GVSummary->getBaseObject());
257
258 // Ignore any callees that aren't actually functions. This could happen
259 // in the case of GUID hash collisions. It could also happen in theory
260 // for SamplePGO profiles collected on old versions of the code after
261 // renaming, since we synthesize edges to any inlined callees appearing
262 // in the profile.
263 if (!Summary)
265
266 // If this is a local function, make sure we import the copy in the
267 // caller's module. The only time a local function can share an entry in
268 // the index is if there is a local with the same name in another module
269 // that had the same source file name (in a different directory), where
270 // each was compiled in their own directory so there was not
271 // distinguishing path.
272 // If the local function is from another module, it must be a reference
273 // due to indirect call profile data since a function pointer can point
274 // to a local in another module. Do the import from another module if
275 // there is only one entry in the list or when all files in the program
276 // are compiled with full path - in both cases the local function has
277 // unique PGO name and GUID.
278 if (shouldSkipLocalInAnotherModule(Summary, CalleeSummaryList.size(),
279 CallerModulePath))
280 return {
282 GVSummary};
283
284 // Skip if it isn't legal to import (e.g. may reference unpromotable
285 // locals).
286 if (Summary->notEligibleToImport())
288 GVSummary};
289
291 });
292}
293
294/// Given a list of possible callee implementation for a call site, select one
295/// that fits the \p Threshold for function definition import. If none are
296/// found, the Reason will give the last reason for the failure (last, in the
297/// order of CalleeSummaryList entries). While looking for a callee definition,
298/// sets \p TooLargeOrNoInlineSummary to the last seen too-large or noinline
299/// candidate; other modules may want to know the function summary or
300/// declaration even if a definition is not needed.
301///
302/// FIXME: select "best" instead of first that fits. But what is "best"?
303/// - The smallest: more likely to be inlined.
304/// - The one with the least outgoing edges (already well optimized).
305/// - One from a module already being imported from in order to reduce the
306/// number of source modules parsed/linked.
307/// - One that has PGO data attached.
308/// - [insert you fancy metric here]
309static const GlobalValueSummary *
311 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
312 unsigned Threshold, StringRef CallerModulePath,
313 const GlobalValueSummary *&TooLargeOrNoInlineSummary,
315 // Records the last summary with reason noinline or too-large.
316 TooLargeOrNoInlineSummary = nullptr;
317 auto QualifiedCandidates =
318 qualifyCalleeCandidates(Index, CalleeSummaryList, CallerModulePath);
319 for (auto QualifiedValue : QualifiedCandidates) {
320 Reason = QualifiedValue.first;
321 // Skip a summary if its import is not (proved to be) legal.
323 continue;
324 auto *Summary =
325 cast<FunctionSummary>(QualifiedValue.second->getBaseObject());
326
327 // Don't bother importing the definition if the chance of inlining it is
328 // not high enough (except under `--force-import-all`).
329 if ((Summary->instCount() > Threshold) && !Summary->fflags().AlwaysInline &&
331 TooLargeOrNoInlineSummary = Summary;
333 continue;
334 }
335
336 // Don't bother importing the definition if we can't inline it anyway.
337 if (Summary->fflags().NoInline && !ForceImportAll) {
338 TooLargeOrNoInlineSummary = Summary;
340 continue;
341 }
342
343 return Summary;
344 }
345 return nullptr;
346}
347
348namespace {
349
350using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */>;
351
352} // anonymous namespace
353
356 GlobalValue::GUID GUID) {
357 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
358 if (!Imports.insert(Def).second)
359 // Already there.
361
362 // Remove Decl in case it's there. Note that a definition takes precedence
363 // over a declaration for a given GUID.
364 return Imports.erase(Decl) ? AddDefinitionStatus::ChangedToDefinition
366}
367
369 StringRef FromModule, GlobalValue::GUID GUID) {
370 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
371 // Insert Decl only if Def is not present. Note that a definition takes
372 // precedence over a declaration for a given GUID.
373 if (!Imports.contains(Def))
374 Imports.insert(Decl);
375}
376
379 SetVector<StringRef> ModuleSet;
380 for (const auto &[SrcMod, GUID, ImportType] : *this)
381 ModuleSet.insert(SrcMod);
382 SmallVector<StringRef, 0> Modules = ModuleSet.takeVector();
383 llvm::sort(Modules);
384 return Modules;
385}
386
387std::optional<GlobalValueSummary::ImportKind>
389 GlobalValue::GUID GUID) const {
390 if (auto IDPair = IDs.getImportIDs(FromModule, GUID)) {
391 auto [Def, Decl] = *IDPair;
392 if (Imports.contains(Def))
394 if (Imports.contains(Decl))
396 }
397 return std::nullopt;
398}
399
400/// Import globals referenced by a function or other globals that are being
401/// imported, if importing such global is possible.
402class GlobalsImporter final {
403 const ModuleSummaryIndex &Index;
404 const GVSummaryMapTy &DefinedGVSummaries;
406 IsPrevailing;
409
410 bool shouldImportGlobal(const ValueInfo &VI, StringRef ReferencingModule) {
411 const auto &GVS = DefinedGVSummaries.find(VI.getGUID());
412 if (GVS == DefinedGVSummaries.end())
413 return true;
414 // A local definition in the destination module cannot satisfy a reference
415 // from a different module.
416 if (shouldSkipLocalInAnotherModule(GVS->second, VI.getSummaryList().size(),
417 ReferencingModule))
418 return true;
419 // We should not skip import if the module contains a non-prevailing
420 // definition with interposable linkage type. This is required for
421 // correctness in the situation where there is a prevailing def available
422 // for import and marked read-only. In this case, the non-prevailing def
423 // will be converted to a declaration, while the prevailing one becomes
424 // internal, thus no definitions will be available for linking. In order to
425 // prevent undefined symbol link error, the prevailing definition must be
426 // imported.
427 // FIXME: Consider adding a check that the suitable prevailing definition
428 // exists and marked read-only.
429 if (VI.getSummaryList().size() > 1 &&
430 GlobalValue::isInterposableLinkage(GVS->second->linkage()) &&
431 !IsPrevailing(VI.getGUID(), GVS->second))
432 return true;
433
434 return false;
435 }
436
437 void
438 onImportingSummaryImpl(const GlobalValueSummary &Summary,
440 for (const auto &VI : Summary.refs()) {
441 if (!shouldImportGlobal(VI, Summary.modulePath())) {
443 dbgs() << "Ref ignored! Target already in destination module.\n");
444 continue;
445 }
446
447 LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
448
449 for (const auto &RefSummary : VI.getSummaryList()) {
450 const auto *GVS = dyn_cast<GlobalVarSummary>(RefSummary.get());
451 // Stop looking if this is not a global variable, e.g. a function.
452 // Functions could be referenced by global vars - e.g. a vtable; but we
453 // don't currently imagine a reason those would be imported here, rather
454 // than as part of the logic deciding which functions to import (i.e.
455 // based on profile information). Should we decide to handle them here,
456 // we can refactor accordingly at that time.
457 // Note that it is safe to stop looking because the one case where we
458 // might have to import (a read/write-only global variable) cannot occur
459 // if this GUID has a non-variable summary. The only case where we even
460 // might find another summary in the list that is a variable is in the
461 // case of same-named locals in different modules not compiled with
462 // enough path, and during attribute propagation we will mark all
463 // summaries for a GUID (ValueInfo) as non read/write-only if any is not
464 // a global variable.
465 if (!GVS)
466 break;
467 bool CanImportDecl = false;
468 if (shouldSkipLocalInAnotherModule(GVS, VI.getSummaryList().size(),
469 Summary.modulePath()) ||
470 !Index.canImportGlobalVar(GVS, /* AnalyzeRefs */ true,
471 CanImportDecl)) {
472 if (ImportDeclaration && CanImportDecl)
473 ImportList.maybeAddDeclaration(RefSummary->modulePath(),
474 VI.getGUID());
475
476 continue;
477 }
478
479 // If there isn't an entry for GUID, insert <GUID, Definition> pair.
480 // Otherwise, definition should take precedence over declaration.
481 if (ImportList.addDefinition(RefSummary->modulePath(), VI.getGUID()) !=
483 break;
484
485 // Only update stat and exports if we haven't already imported this
486 // variable.
487 NumImportedGlobalVarsThinLink++;
488 // Any references made by this variable will be marked exported
489 // later, in ComputeCrossModuleImport, after import decisions are
490 // complete, which is more efficient than adding them here.
491 if (ExportLists)
492 (*ExportLists)[RefSummary->modulePath()].insert(VI);
493
494 // If variable is not writeonly we attempt to recursively analyze
495 // its references in order to import referenced constants.
496 if (!Index.isWriteOnly(GVS))
497 Worklist.emplace_back(GVS);
498 break;
499 }
500 }
501 }
502
503public:
505 const ModuleSummaryIndex &Index, const GVSummaryMapTy &DefinedGVSummaries,
507 IsPrevailing,
510 : Index(Index), DefinedGVSummaries(DefinedGVSummaries),
511 IsPrevailing(IsPrevailing), ImportList(ImportList),
512 ExportLists(ExportLists) {}
513
516 onImportingSummaryImpl(Summary, Worklist);
517 while (!Worklist.empty())
518 onImportingSummaryImpl(*Worklist.pop_back_val(), Worklist);
519 }
520};
521
523
524/// Determine the list of imports and exports for each module.
526 void computeImportForFunction(
527 const FunctionSummary &Summary, unsigned Threshold,
528 const GVSummaryMapTy &DefinedGVSummaries,
529 SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
531 FunctionImporter::ImportThresholdsTy &ImportThresholds);
532
533protected:
538
545 virtual bool canImport(ValueInfo VI) { return true; }
546
547public:
548 virtual ~ModuleImportsManager() = default;
549
550 /// Given the list of globals defined in a module, compute the list of imports
551 /// as well as the list of "exports", i.e. the list of symbols referenced from
552 /// another module (that may require promotion).
553 virtual void
554 computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
555 StringRef ModName,
557
558 static std::unique_ptr<ModuleImportsManager>
563 nullptr);
564};
565
566/// A ModuleImportsManager that operates based on a workload definition (see
567/// -thinlto-workload-def). For modules that do not define workload roots, it
568/// applies the base ModuleImportsManager import policy.
570 // Keep a module name -> value infos to import association. We use it to
571 // determine if a module's import list should be done by the base
572 // ModuleImportsManager or by us.
574 // Track the roots to avoid importing them due to other callers. We want there
575 // to be only one variant), for which we optimize according to the contextual
576 // profile. "Variants" refers to copies due to importing - we want there to be
577 // just one instance of this function.
579
580 void
581 computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
582 StringRef ModName,
583 FunctionImporter::ImportMapTy &ImportList) override {
584 StringRef Filename = ModName;
586 Filename = sys::path::filename(ModName);
587 // Drop the file extension.
588 Filename = Filename.substr(0, Filename.find_last_of('.'));
589 }
590 auto SetIter = Workloads.find(Filename);
591
592 if (SetIter == Workloads.end()) {
593 LLVM_DEBUG(dbgs() << "[Workload] " << ModName
594 << " does not contain the root of any context.\n");
595 return ModuleImportsManager::computeImportForModule(DefinedGVSummaries,
596 ModName, ImportList);
597 }
598 LLVM_DEBUG(dbgs() << "[Workload] " << ModName
599 << " contains the root(s) of context(s).\n");
600
601 GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
603 auto &ValueInfos = SetIter->second;
604 for (auto &VI : llvm::make_early_inc_range(ValueInfos)) {
605 auto It = DefinedGVSummaries.find(VI.getGUID());
606 if (It != DefinedGVSummaries.end() &&
607 IsPrevailing(VI.getGUID(), It->second)) {
609 dbgs() << "[Workload] " << VI.name()
610 << " has the prevailing variant already in the module "
611 << ModName << ". No need to import\n");
612 continue;
613 }
614 auto Candidates =
615 qualifyCalleeCandidates(Index, VI.getSummaryList(), ModName);
616
617 const GlobalValueSummary *GVS = nullptr;
618 auto PotentialCandidates = llvm::map_range(
620 Candidates,
621 [&](const auto &Candidate) {
622 LLVM_DEBUG(dbgs() << "[Workflow] Candidate for " << VI.name()
623 << " from " << Candidate.second->modulePath()
624 << " ImportFailureReason: "
625 << getFailureName(Candidate.first) << "\n");
626 return Candidate.first ==
628 }),
629 [](const auto &Candidate) { return Candidate.second; });
630 if (PotentialCandidates.empty()) {
631 LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
632 << " because can't find eligible Callee. Guid is: "
633 << VI.getGUID() << "\n");
634 continue;
635 }
636 /// We will prefer importing the prevailing candidate, if not, we'll
637 /// still pick the first available candidate. The reason we want to make
638 /// sure we do import the prevailing candidate is because the goal of
639 /// workload-awareness is to enable optimizations specializing the call
640 /// graph of that workload. Suppose a function is already defined in the
641 /// module, but it's not the prevailing variant. Suppose also we do not
642 /// inline it (in fact, if it were interposable, we can't inline it),
643 /// but we could specialize it to the workload in other ways. However,
644 /// the linker would drop it in the favor of the prevailing copy.
645 /// Instead, by importing the prevailing variant (assuming also the use
646 /// of `-avail-extern-to-local`), we keep the specialization. We could
647 /// alteranatively make the non-prevailing variant local, but the
648 /// prevailing one is also the one for which we would have previously
649 /// collected profiles, making it preferrable.
650 auto PrevailingCandidates = llvm::make_filter_range(
651 PotentialCandidates, [&](const auto *Candidate) {
652 return IsPrevailing(VI.getGUID(), Candidate);
653 });
654 if (PrevailingCandidates.empty()) {
655 GVS = *PotentialCandidates.begin();
656 if (!llvm::hasSingleElement(PotentialCandidates) &&
659 dbgs()
660 << "[Workload] Found multiple non-prevailing candidates for "
661 << VI.name()
662 << ". This is unexpected. Are module paths passed to the "
663 "compiler unique for the modules passed to the linker?");
664 // We could in theory have multiple (interposable) copies of a symbol
665 // when there is no prevailing candidate, if say the prevailing copy was
666 // in a native object being linked in. However, we should in theory be
667 // marking all of these non-prevailing IR copies dead in that case, in
668 // which case they won't be candidates.
669 assert(GVS->isLive());
670 } else {
671 assert(llvm::hasSingleElement(PrevailingCandidates));
672 GVS = *PrevailingCandidates.begin();
673 }
674
675 auto ExportingModule = GVS->modulePath();
676 // We checked that for the prevailing case, but if we happen to have for
677 // example an internal that's defined in this module, it'd have no
678 // PrevailingCandidates.
679 if (ExportingModule == ModName) {
680 LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
681 << " because its defining module is the same as the "
682 "current module\n");
683 continue;
684 }
685 LLVM_DEBUG(dbgs() << "[Workload][Including]" << VI.name() << " from "
686 << ExportingModule << " : " << VI.getGUID() << "\n");
687 ImportList.addDefinition(ExportingModule, VI.getGUID());
688 GVI.onImportingSummary(*GVS);
689 if (ExportLists)
690 (*ExportLists)[ExportingModule].insert(VI);
691 }
692 LLVM_DEBUG(dbgs() << "[Workload] Done\n");
693 }
694
695 void loadFromJson() {
696 // Since the workload def uses names, we need a quick lookup
697 // name->ValueInfo.
698 StringMap<ValueInfo> NameToValueInfo;
699 StringSet<> AmbiguousNames;
700 for (auto &I : Index) {
701 ValueInfo VI = Index.getValueInfo(I);
702 if (!NameToValueInfo.insert(std::make_pair(VI.name(), VI)).second)
703 LLVM_DEBUG(AmbiguousNames.insert(VI.name()));
704 }
705 auto DbgReportIfAmbiguous = [&](StringRef Name) {
706 LLVM_DEBUG(if (AmbiguousNames.count(Name) > 0) {
707 dbgs() << "[Workload] Function name " << Name
708 << " present in the workload definition is ambiguous. Consider "
709 "compiling with -funique-internal-linkage-names.";
710 });
711 };
712 std::error_code EC;
714 if (std::error_code EC = BufferOrErr.getError()) {
715 report_fatal_error("Failed to open context file");
716 return;
717 }
718 auto Buffer = std::move(BufferOrErr.get());
719 std::map<std::string, std::vector<std::string>> WorkloadDefs;
720 json::Path::Root NullRoot;
721 // The JSON is supposed to contain a dictionary matching the type of
722 // WorkloadDefs. For example:
723 // {
724 // "rootFunction_1": ["function_to_import_1", "function_to_import_2"],
725 // "rootFunction_2": ["function_to_import_3", "function_to_import_4"]
726 // }
727 auto Parsed = json::parse(Buffer->getBuffer());
728 if (!Parsed)
729 report_fatal_error(Parsed.takeError());
730 if (!json::fromJSON(*Parsed, WorkloadDefs, NullRoot))
731 report_fatal_error("Invalid thinlto contextual profile format.");
732 for (const auto &Workload : WorkloadDefs) {
733 const auto &Root = Workload.first;
734 DbgReportIfAmbiguous(Root);
735 LLVM_DEBUG(dbgs() << "[Workload] Root: " << Root << "\n");
736 const auto &AllCallees = Workload.second;
737 auto RootIt = NameToValueInfo.find(Root);
738 if (RootIt == NameToValueInfo.end()) {
739 LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
740 << " not found in this linkage unit.\n");
741 continue;
742 }
743 auto RootVI = RootIt->second;
744 if (RootVI.getSummaryList().size() != 1) {
745 LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
746 << " should have exactly one summary, but has "
747 << RootVI.getSummaryList().size() << ". Skipping.\n");
748 continue;
749 }
750 StringRef RootDefiningModule =
751 RootVI.getSummaryList().front()->modulePath();
752 LLVM_DEBUG(dbgs() << "[Workload] Root defining module for " << Root
753 << " is : " << RootDefiningModule << "\n");
754 auto &Set = Workloads[RootDefiningModule];
755 for (const auto &Callee : AllCallees) {
756 LLVM_DEBUG(dbgs() << "[Workload] " << Callee << "\n");
757 DbgReportIfAmbiguous(Callee);
758 auto ElemIt = NameToValueInfo.find(Callee);
759 if (ElemIt == NameToValueInfo.end()) {
760 LLVM_DEBUG(dbgs() << "[Workload] " << Callee << " not found\n");
761 continue;
762 }
763 Set.insert(ElemIt->second);
764 }
765 }
766 }
767
768 void loadFromCtxProf() {
769 std::error_code EC;
771 if (std::error_code EC = BufferOrErr.getError()) {
772 report_fatal_error("Failed to open contextual profile file");
773 return;
774 }
775 auto Buffer = std::move(BufferOrErr.get());
776
777 PGOCtxProfileReader Reader(Buffer->getBuffer());
778 auto Ctx = Reader.loadProfiles();
779 if (!Ctx) {
780 report_fatal_error("Failed to parse contextual profiles");
781 return;
782 }
783 const auto &CtxMap = Ctx->Contexts;
784 SetVector<GlobalValue::GUID> ContainedGUIDs;
785 for (const auto &[RootGuid, Root] : CtxMap) {
786 // Avoid ContainedGUIDs to get in/out of scope. Reuse its memory for
787 // subsequent roots, but clear its contents.
788 ContainedGUIDs.clear();
789
790 auto RootVI = Index.getValueInfo(RootGuid);
791 if (!RootVI) {
792 LLVM_DEBUG(dbgs() << "[Workload] Root " << RootGuid
793 << " not found in this linkage unit.\n");
794 continue;
795 }
796 if (RootVI.getSummaryList().size() != 1) {
797 LLVM_DEBUG(dbgs() << "[Workload] Root " << RootGuid
798 << " should have exactly one summary, but has "
799 << RootVI.getSummaryList().size() << ". Skipping.\n");
800 continue;
801 }
802 std::string RootDefiningModule =
803 RootVI.getSummaryList().front()->modulePath().str();
805 RootDefiningModule = std::to_string(RootGuid);
807 dbgs() << "[Workload] Moving " << RootGuid
808 << " to a module with the filename without extension : "
809 << RootDefiningModule << "\n");
810 } else {
811 LLVM_DEBUG(dbgs() << "[Workload] Root defining module for " << RootGuid
812 << " is : " << RootDefiningModule << "\n");
813 }
814 auto &Set = Workloads[RootDefiningModule];
815 Root.getContainedGuids(ContainedGUIDs);
816 Roots.insert(RootVI);
817 for (auto Guid : ContainedGUIDs)
818 if (auto VI = Index.getValueInfo(Guid))
819 Set.insert(VI);
820 }
821 }
822
823 bool canImport(ValueInfo VI) override { return !Roots.contains(VI); }
824
825public:
832 if (UseCtxProfile.empty() == WorkloadDefinitions.empty()) {
833 report_fatal_error(
834 "Pass only one of: -thinlto-pgo-ctx-prof or -thinlto-workload-def");
835 return;
836 }
837 if (!UseCtxProfile.empty())
838 loadFromCtxProf();
839 else
840 loadFromJson();
841 LLVM_DEBUG({
842 for (const auto &[Root, Set] : Workloads) {
843 dbgs() << "[Workload] Root: " << Root << " we have " << Set.size()
844 << " distinct callees.\n";
845 for (const auto &VI : Set) {
846 dbgs() << "[Workload] Root: " << Root
847 << " Would include: " << VI.getGUID() << "\n";
848 }
849 }
850 });
851 }
852};
853
854std::unique_ptr<ModuleImportsManager> ModuleImportsManager::create(
859 if (WorkloadDefinitions.empty() && UseCtxProfile.empty()) {
860 LLVM_DEBUG(dbgs() << "[Workload] Using the regular imports manager.\n");
861 return std::unique_ptr<ModuleImportsManager>(
863 }
864 LLVM_DEBUG(dbgs() << "[Workload] Using the contextual imports manager.\n");
865 return std::make_unique<WorkloadImportsManager>(IsPrevailing, Index,
867}
868
869static const char *
871 switch (Reason) {
873 return "None";
875 return "GlobalVar";
877 return "NotLive";
879 return "TooLarge";
881 return "InterposableLinkage";
883 return "LocalLinkageNotInModule";
885 return "NotEligible";
887 return "NoInline";
888 }
889 llvm_unreachable("invalid reason");
890}
891
892/// Compute the list of functions to import for a given caller. Mark these
893/// imported functions and the symbols they reference in their source module as
894/// exported from their source module.
895void ModuleImportsManager::computeImportForFunction(
896 const FunctionSummary &Summary, const unsigned Threshold,
897 const GVSummaryMapTy &DefinedGVSummaries,
898 SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
899 FunctionImporter::ImportMapTy &ImportList,
900 FunctionImporter::ImportThresholdsTy &ImportThresholds) {
901 GVImporter.onImportingSummary(Summary);
902 static int ImportCount = 0;
903 for (const auto &Edge : Summary.calls()) {
904 ValueInfo VI = Edge.first;
905 LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
906 << "\n");
907
908 if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
909 LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
910 << " reached.\n");
911 continue;
912 }
913
914 if (DefinedGVSummaries.count(VI.getGUID())) {
915 // FIXME: Consider not skipping import if the module contains
916 // a non-prevailing def with interposable linkage. The prevailing copy
917 // can safely be imported (see shouldImportGlobal()).
918 LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
919 continue;
920 }
921
922 if (!canImport(VI)) {
924 dbgs() << "Skipping over " << VI.getGUID()
925 << " because its import is handled in a different module.");
926 assert(VI.getSummaryList().size() == 1 &&
927 "The root was expected to be an external symbol");
928 continue;
929 }
930
931 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
932 if (Hotness == CalleeInfo::HotnessType::Hot)
933 return ImportHotMultiplier;
934 if (Hotness == CalleeInfo::HotnessType::Cold)
938 return 1.0;
939 };
940
941 const auto NewThreshold =
942 Threshold * GetBonusMultiplier(Edge.second.getHotness());
943
944 auto IT = ImportThresholds.insert(std::make_pair(
945 VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
946 bool PreviouslyVisited = !IT.second;
947 auto &ProcessedThreshold = std::get<0>(IT.first->second);
948 auto &CalleeSummary = std::get<1>(IT.first->second);
949 auto &FailureInfo = std::get<2>(IT.first->second);
950
951 bool IsHotCallsite =
952 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
953 bool IsCriticalCallsite =
954 Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
955
956 const FunctionSummary *ResolvedCalleeSummary = nullptr;
957 if (CalleeSummary) {
958 assert(PreviouslyVisited);
959 // Since the traversal of the call graph is DFS, we can revisit a function
960 // a second time with a higher threshold. In this case, it is added back
961 // to the worklist with the new threshold (so that its own callee chains
962 // can be considered with the higher threshold).
963 if (NewThreshold <= ProcessedThreshold) {
965 dbgs() << "ignored! Target was already imported with Threshold "
966 << ProcessedThreshold << "\n");
967 continue;
968 }
969 // Update with new larger threshold.
970 ProcessedThreshold = NewThreshold;
971 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
972 } else {
973 // If we already rejected importing a callee at the same or higher
974 // threshold, don't waste time calling selectCallee.
975 if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
977 dbgs() << "ignored! Target was already rejected with Threshold "
978 << ProcessedThreshold << "\n");
980 assert(FailureInfo &&
981 "Expected FailureInfo for previously rejected candidate");
982 FailureInfo->Attempts++;
983 }
984 continue;
985 }
986
988
989 // `SummaryForDeclImport` is an summary eligible for declaration import.
990 const GlobalValueSummary *SummaryForDeclImport = nullptr;
991 CalleeSummary =
992 selectCallee(Index, VI.getSummaryList(), NewThreshold,
993 Summary.modulePath(), SummaryForDeclImport, Reason);
994 if (!CalleeSummary) {
995 // There isn't a callee for definition import but one for declaration
996 // import.
997 if (ImportDeclaration && SummaryForDeclImport) {
998 StringRef DeclSourceModule = SummaryForDeclImport->modulePath();
999
1000 // Note `ExportLists` only keeps track of exports due to imported
1001 // definitions.
1002 ImportList.maybeAddDeclaration(DeclSourceModule, VI.getGUID());
1003 }
1004 // Update with new larger threshold if this was a retry (otherwise
1005 // we would have already inserted with NewThreshold above). Also
1006 // update failure info if requested.
1007 if (PreviouslyVisited) {
1008 ProcessedThreshold = NewThreshold;
1009 if (PrintImportFailures) {
1010 assert(FailureInfo &&
1011 "Expected FailureInfo for previously rejected candidate");
1012 FailureInfo->Reason = Reason;
1013 FailureInfo->Attempts++;
1014 FailureInfo->MaxHotness =
1015 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
1016 }
1017 } else if (PrintImportFailures) {
1018 assert(!FailureInfo &&
1019 "Expected no FailureInfo for newly rejected candidate");
1020 FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
1021 VI, Edge.second.getHotness(), Reason, 1);
1022 }
1023 if (ForceImportAll) {
1024 std::string Msg = std::string("Failed to import function ") +
1025 VI.name().str() + " due to " +
1026 getFailureName(Reason);
1029 logAllUnhandledErrors(std::move(Error), errs(),
1030 "Error importing module: ");
1031 break;
1032 } else {
1034 << "ignored! No qualifying callee with summary found.\n");
1035 continue;
1036 }
1037 }
1038
1039 // "Resolve" the summary
1040 CalleeSummary = CalleeSummary->getBaseObject();
1041 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
1042
1043 assert((ResolvedCalleeSummary->fflags().AlwaysInline || ForceImportAll ||
1044 (ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
1045 "selectCallee() didn't honor the threshold");
1046
1047 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
1048
1049 // Try emplace the definition entry, and update stats based on insertion
1050 // status.
1051 if (ImportList.addDefinition(ExportModulePath, VI.getGUID()) !=
1053 NumImportedFunctionsThinLink++;
1054 if (IsHotCallsite)
1055 NumImportedHotFunctionsThinLink++;
1056 if (IsCriticalCallsite)
1057 NumImportedCriticalFunctionsThinLink++;
1058 }
1059
1060 // Any calls/references made by this function will be marked exported
1061 // later, in ComputeCrossModuleImport, after import decisions are
1062 // complete, which is more efficient than adding them here.
1063 if (ExportLists)
1064 (*ExportLists)[ExportModulePath].insert(VI);
1065 }
1066
1067 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
1068 // Adjust the threshold for next level of imported functions.
1069 // The threshold is different for hot callsites because we can then
1070 // inline chains of hot calls.
1071 if (IsHotCallsite)
1072 return Threshold * ImportHotInstrFactor;
1073 return Threshold * ImportInstrFactor;
1074 };
1075
1076 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
1077
1078 ImportCount++;
1079
1080 // Insert the newly imported function to the worklist.
1081 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
1082 }
1083}
1084
1086 const GVSummaryMapTy &DefinedGVSummaries, StringRef ModName,
1087 FunctionImporter::ImportMapTy &ImportList) {
1088 // Worklist contains the list of function imported in this module, for which
1089 // we will analyse the callees and may import further down the callgraph.
1091 GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
1092 ExportLists);
1093 FunctionImporter::ImportThresholdsTy ImportThresholds;
1094
1095 // Populate the worklist with the import for the functions in the current
1096 // module
1097 for (const auto &GVSummary : DefinedGVSummaries) {
1098#ifndef NDEBUG
1099 // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
1100 // so this map look up (and possibly others) can be avoided.
1101 auto VI = Index.getValueInfo(GVSummary.first);
1102#endif
1103 if (!Index.isGlobalValueLive(GVSummary.second)) {
1104 LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
1105 continue;
1106 }
1107 auto *FuncSummary =
1108 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
1109 if (!FuncSummary)
1110 // Skip import for global variables
1111 continue;
1112 LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
1113 computeImportForFunction(*FuncSummary, ImportInstrLimit, DefinedGVSummaries,
1114 Worklist, GVI, ImportList, ImportThresholds);
1115 }
1116
1117 // Process the newly imported functions and add callees to the worklist.
1118 while (!Worklist.empty()) {
1119 auto GVInfo = Worklist.pop_back_val();
1120 auto *Summary = std::get<0>(GVInfo);
1121 auto Threshold = std::get<1>(GVInfo);
1122
1123 computeImportForFunction(*Summary, Threshold, DefinedGVSummaries, Worklist,
1124 GVI, ImportList, ImportThresholds);
1125 }
1126
1127 // Print stats about functions considered but rejected for importing
1128 // when requested.
1129 if (PrintImportFailures) {
1130 dbgs() << "Missed imports into module " << ModName << "\n";
1131 for (auto &I : ImportThresholds) {
1132 auto &ProcessedThreshold = std::get<0>(I.second);
1133 auto &CalleeSummary = std::get<1>(I.second);
1134 auto &FailureInfo = std::get<2>(I.second);
1135 if (CalleeSummary)
1136 continue; // We are going to import.
1137 assert(FailureInfo);
1138 FunctionSummary *FS = nullptr;
1139 if (!FailureInfo->VI.getSummaryList().empty())
1141 FailureInfo->VI.getSummaryList()[0]->getBaseObject());
1142 dbgs() << FailureInfo->VI
1143 << ": Reason = " << getFailureName(FailureInfo->Reason)
1144 << ", Threshold = " << ProcessedThreshold
1145 << ", Size = " << (FS ? (int)FS->instCount() : -1)
1146 << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
1147 << ", Attempts = " << FailureInfo->Attempts << "\n";
1148 }
1149 }
1150}
1151
1152#ifndef NDEBUG
1153static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI) {
1154 auto SL = VI.getSummaryList();
1155 return SL.empty()
1156 ? false
1157 : SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
1158}
1159
1162 if (const auto &VI = Index.getValueInfo(G))
1163 return isGlobalVarSummary(Index, VI);
1164 return false;
1165}
1166
1167// Return the number of global variable summaries in ExportSet.
1168static unsigned
1170 FunctionImporter::ExportSetTy &ExportSet) {
1171 unsigned NumGVS = 0;
1172 for (auto &VI : ExportSet)
1173 if (isGlobalVarSummary(Index, VI.getGUID()))
1174 ++NumGVS;
1175 return NumGVS;
1176}
1177
1179 unsigned NumGVS = 0;
1180 unsigned DefinedFS = 0;
1181 unsigned Count = 0;
1182};
1183
1184// Compute import statistics for each source module in ImportList.
1187 const FunctionImporter::ImportMapTy &ImportList) {
1189
1190 for (const auto &[FromModule, GUID, Type] : ImportList) {
1191 ImportStatistics &Entry = Histogram[FromModule];
1192 ++Entry.Count;
1193 if (isGlobalVarSummary(Index, GUID))
1194 ++Entry.NumGVS;
1196 ++Entry.DefinedFS;
1197 }
1198 return Histogram;
1199}
1200#endif
1201
1202#ifndef NDEBUG
1204 const ModuleSummaryIndex &Index,
1207 DenseSet<GlobalValue::GUID> FlattenedImports;
1208
1209 for (const auto &ImportPerModule : ImportLists)
1210 for (const auto &[FromModule, GUID, ImportType] : ImportPerModule.second)
1211 FlattenedImports.insert(GUID);
1212
1213 // Checks that all GUIDs of read/writeonly vars we see in export lists
1214 // are also in the import lists. Otherwise we my face linker undefs,
1215 // because readonly and writeonly vars are internalized in their
1216 // source modules. The exception would be if it has a linkage type indicating
1217 // that there may have been a copy existing in the importing module (e.g.
1218 // linkonce_odr). In that case we cannot accurately do this checking.
1219 auto IsReadOrWriteOnlyVarNeedingImporting = [&](StringRef ModulePath,
1220 const ValueInfo &VI) {
1222 Index.findSummaryInModule(VI, ModulePath));
1223 return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS)) &&
1224 !(GVS->linkage() == GlobalValue::AvailableExternallyLinkage ||
1225 GVS->linkage() == GlobalValue::WeakODRLinkage ||
1226 GVS->linkage() == GlobalValue::LinkOnceODRLinkage);
1227 };
1228
1229 for (auto &ExportPerModule : ExportLists)
1230 for (auto &VI : ExportPerModule.second)
1231 if (!FlattenedImports.count(VI.getGUID()) &&
1232 IsReadOrWriteOnlyVarNeedingImporting(ExportPerModule.first, VI))
1233 return false;
1234
1235 return true;
1236}
1237#endif
1238
1239/// Compute all the import and export for every module using the Index.
1241 const ModuleSummaryIndex &Index,
1242 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1244 isPrevailing,
1247 auto MIS = ModuleImportsManager::create(isPrevailing, Index, &ExportLists);
1248 // For each module that has function defined, compute the import/export lists.
1249 for (const auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
1250 auto &ImportList = ImportLists[DefinedGVSummaries.first];
1251 LLVM_DEBUG(dbgs() << "Computing import for Module '"
1252 << DefinedGVSummaries.first << "'\n");
1253 MIS->computeImportForModule(DefinedGVSummaries.second,
1254 DefinedGVSummaries.first, ImportList);
1255 }
1256
1257 // When computing imports we only added the variables and functions being
1258 // imported to the export list. We also need to mark any references and calls
1259 // they make as exported as well. We do this here, as it is more efficient
1260 // since we may import the same values multiple times into different modules
1261 // during the import computation.
1262 for (auto &ELI : ExportLists) {
1263 // `NewExports` tracks the VI that gets exported because the full definition
1264 // of its user/referencer gets exported.
1266 const auto &DefinedGVSummaries =
1267 ModuleToDefinedGVSummaries.lookup(ELI.first);
1268 for (auto &EI : ELI.second) {
1269 // Find the copy defined in the exporting module so that we can mark the
1270 // values it references in that specific definition as exported.
1271 // Below we will add all references and called values, without regard to
1272 // whether they are also defined in this module. We subsequently prune the
1273 // list to only include those defined in the exporting module, see comment
1274 // there as to why.
1275 auto DS = DefinedGVSummaries.find(EI.getGUID());
1276 // Anything marked exported during the import computation must have been
1277 // defined in the exporting module.
1278 assert(DS != DefinedGVSummaries.end());
1279 auto *S = DS->getSecond();
1280 S = S->getBaseObject();
1281 if (auto *GVS = dyn_cast<GlobalVarSummary>(S)) {
1282 // Export referenced functions and variables. We don't export/promote
1283 // objects referenced by writeonly variable initializer, because
1284 // we convert such variables initializers to "zeroinitializer".
1285 // See processGlobalForThinLTO.
1286 if (!Index.isWriteOnly(GVS))
1287 NewExports.insert_range(GVS->refs());
1288 } else {
1289 auto *FS = cast<FunctionSummary>(S);
1290 NewExports.insert_range(llvm::make_first_range(FS->calls()));
1291 NewExports.insert_range(FS->refs());
1292 }
1293 }
1294 // Prune list computed above to only include values defined in the
1295 // exporting module. We do this after the above insertion since we may hit
1296 // the same ref/call target multiple times in above loop, and it is more
1297 // efficient to avoid a set lookup each time.
1298 NewExports.remove_if(
1299 [&](ValueInfo VI) { return !DefinedGVSummaries.count(VI.getGUID()); });
1300 ELI.second.insert_range(NewExports);
1301 }
1302
1303 assert(checkVariableImport(Index, ImportLists, ExportLists));
1304#ifndef NDEBUG
1305 LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
1306 << " modules:\n");
1307 for (const auto &ModuleImports : ImportLists) {
1308 auto ModName = ModuleImports.first;
1309 auto &Exports = ExportLists[ModName];
1310 unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
1312 collectImportStatistics(Index, ModuleImports.second);
1313 LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
1314 << Exports.size() - NumGVS << " functions and " << NumGVS
1315 << " vars. Imports from " << Histogram.size()
1316 << " modules.\n");
1317 for (const auto &[SrcModName, Stats] : Histogram) {
1318 LLVM_DEBUG(dbgs() << " - " << Stats.DefinedFS
1319 << " function definitions and "
1320 << Stats.Count - Stats.NumGVS - Stats.DefinedFS
1321 << " function declarations imported from " << SrcModName
1322 << "\n");
1323 LLVM_DEBUG(dbgs() << " - " << Stats.NumGVS
1324 << " global vars imported from " << SrcModName << "\n");
1325 }
1326 }
1327#endif
1328}
1329
1330#ifndef NDEBUG
1332 StringRef ModulePath,
1333 FunctionImporter::ImportMapTy &ImportList) {
1335 collectImportStatistics(Index, ImportList);
1336 LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
1337 << Histogram.size() << " modules.\n");
1338 for (const auto &[SrcModName, Stats] : Histogram) {
1339 LLVM_DEBUG(dbgs() << " - " << Stats.DefinedFS
1340 << " function definitions and "
1341 << Stats.Count - Stats.DefinedFS - Stats.NumGVS
1342 << " function declarations imported from " << SrcModName
1343 << "\n");
1344 LLVM_DEBUG(dbgs() << " - " << Stats.NumGVS << " vars imported from "
1345 << SrcModName << "\n");
1346 }
1347}
1348#endif
1349
1350/// Compute all the imports for the given module using the Index.
1351///
1352/// \p isPrevailing is a callback that will be called with a global value's GUID
1353/// and summary and should return whether the module corresponding to the
1354/// summary contains the linker-prevailing copy of that value.
1355///
1356/// \p ImportList will be populated with a map that can be passed to
1357/// FunctionImporter::importFunctions() above (see description there).
1359 StringRef ModulePath,
1361 isPrevailing,
1362 const ModuleSummaryIndex &Index,
1363 FunctionImporter::ImportMapTy &ImportList) {
1364 // Collect the list of functions this module defines.
1365 // GUID -> Summary
1366 GVSummaryMapTy FunctionSummaryMap;
1367 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
1368
1369 // Compute the import list for this module.
1370 LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
1371 auto MIS = ModuleImportsManager::create(isPrevailing, Index);
1372 MIS->computeImportForModule(FunctionSummaryMap, ModulePath, ImportList);
1373
1374#ifndef NDEBUG
1375 dumpImportListForModule(Index, ModulePath, ImportList);
1376#endif
1377}
1378
1379/// Mark all external summaries in \p Index for import into the given module.
1380/// Used for testing the case of distributed builds using a distributed index.
1381///
1382/// \p ImportList will be populated with a map that can be passed to
1383/// FunctionImporter::importFunctions() above (see description there).
1385 StringRef ModulePath, const ModuleSummaryIndex &Index,
1386 FunctionImporter::ImportMapTy &ImportList) {
1387 for (const auto &GlobalList : Index) {
1388 // Ignore entries for undefined references.
1389 if (GlobalList.second.getSummaryList().empty())
1390 continue;
1391
1392 auto GUID = GlobalList.first;
1393 assert(GlobalList.second.getSummaryList().size() == 1 &&
1394 "Expected individual combined index to have one summary per GUID");
1395 auto &Summary = GlobalList.second.getSummaryList()[0];
1396 // Skip the summaries for the importing module. These are included to
1397 // e.g. record required linkage changes.
1398 if (Summary->modulePath() == ModulePath)
1399 continue;
1400 // Add an entry to provoke importing by thinBackend.
1401 ImportList.addGUID(Summary->modulePath(), GUID, Summary->importType());
1402 }
1403#ifndef NDEBUG
1404 dumpImportListForModule(Index, ModulePath, ImportList);
1405#endif
1406}
1407
1408// For SamplePGO, the indirect call targets for local functions will
1409// have its original name annotated in profile. We try to find the
1410// corresponding PGOFuncName as the GUID, and fix up the edges
1411// accordingly.
1413 FunctionSummary *FS) {
1414 // Returns the ValueInfo that should be used in place of \p CalleeVI, or an
1415 // empty ValueInfo if no update is needed.
1416 auto GetUpdatedCallee = [&](ValueInfo CalleeVI) -> ValueInfo {
1417 if (!CalleeVI || !CalleeVI.getSummaryList().empty())
1418 return ValueInfo();
1419 auto GUID = Index.getGUIDFromOriginalID(CalleeVI.getGUID());
1420 if (GUID == 0)
1421 return ValueInfo();
1422 auto VI = Index.getValueInfo(GUID);
1423 if (llvm::any_of(
1424 VI.getSummaryList(),
1425 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
1426 // The mapping from OriginalId to GUID may return a GUID
1427 // that corresponds to a static variable. Filter it out here.
1428 // This can happen when
1429 // 1) There is a call to a library function which is not defined
1430 // in the index.
1431 // 2) There is a static variable with the OriginalGUID identical
1432 // to the GUID of the library function in 1);
1433 // When this happens the static variable in 2) will be found,
1434 // which needs to be filtered out.
1435 return SummaryPtr->getSummaryKind() ==
1436 GlobalValueSummary::GlobalVarKind;
1437 }))
1438 return ValueInfo();
1439 return VI;
1440 };
1441
1442 for (auto &EI : FS->mutableCalls()) {
1443 // Update the edge to point directly to the correct GUID.
1444 if (auto VI = GetUpdatedCallee(EI.first))
1445 EI.first = VI;
1446 }
1447
1448 // MemProf summarizes indirect callsites by synthesizing a CallsiteInfo
1449 // record for each profiled target, using the same GUIDs found in the VP
1450 // metadata (which, for local targets, may be the original name GUID when
1451 // e.g. synthesized from the MemProf profile or from a SamplePGO profile).
1452 // Update those callees as well so that they are consistent with the call
1453 // edges above, and so that the thin link's MemProf context disambiguation
1454 // can correlate the callsite with the summary for the target function.
1455 if (FS->callsites().empty())
1456 return;
1457 for (auto &CI : FS->mutableCallsites()) {
1458 if (auto VI = GetUpdatedCallee(CI.Callee))
1459 CI.Callee = VI;
1460 }
1461}
1462
1464 for (const auto &Entry : Index) {
1465 for (const auto &S : Entry.second.getSummaryList()) {
1466 if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1468 }
1469 }
1470}
1471
1473 ModuleSummaryIndex &Index,
1474 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
1476 assert(!Index.withGlobalValueDeadStripping());
1477 if (!ComputeDead ||
1478 // Don't do anything when nothing is live, this is friendly with tests.
1479 GUIDPreservedSymbols.empty()) {
1480 // Still need to update indirect calls.
1481 updateIndirectCalls(Index);
1482 return;
1483 }
1484 unsigned LiveSymbols = 0;
1486 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
1487 for (auto GUID : GUIDPreservedSymbols) {
1488 ValueInfo VI = Index.getValueInfo(GUID);
1489 if (!VI)
1490 continue;
1491 for (const auto &S : VI.getSummaryList())
1492 S->setLive(true);
1493 }
1494
1495 // Add values flagged in the index as live roots to the worklist.
1496 for (const auto &Entry : Index) {
1497 auto VI = Index.getValueInfo(Entry);
1498 for (const auto &S : Entry.second.getSummaryList()) {
1499 if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1501 if (S->isLive()) {
1502 LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
1503 Worklist.push_back(VI);
1504 ++LiveSymbols;
1505 break;
1506 }
1507 }
1508 }
1509
1510 // Make value live and add it to the worklist if it was not live before.
1511 auto visit = [&](ValueInfo VI, bool IsAliasee) {
1512 // FIXME: If we knew which edges were created for indirect call profiles,
1513 // we could skip them here. Any that are live should be reached via
1514 // other edges, e.g. reference edges. Otherwise, using a profile collected
1515 // on a slightly different binary might provoke preserving, importing
1516 // and ultimately promoting calls to functions not linked into this
1517 // binary, which increases the binary size unnecessarily. Note that
1518 // if this code changes, the importer needs to change so that edges
1519 // to functions marked dead are skipped.
1520
1521 if (llvm::any_of(VI.getSummaryList(),
1522 [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
1523 return S->isLive();
1524 }))
1525 return;
1526
1527 // We only keep live symbols that are known to be non-prevailing if any are
1528 // available_externally, linkonceodr, weakodr. Those symbols are discarded
1529 // later in the EliminateAvailableExternally pass and setting them to
1530 // not-live could break downstreams users of liveness information (PR36483)
1531 // or limit optimization opportunities.
1532 if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
1533 bool KeepAliveLinkage = false;
1534 bool Interposable = false;
1535 for (const auto &S : VI.getSummaryList()) {
1536 if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
1537 S->linkage() == GlobalValue::WeakODRLinkage ||
1538 S->linkage() == GlobalValue::LinkOnceODRLinkage)
1539 KeepAliveLinkage = true;
1540 else if (GlobalValue::isInterposableLinkage(S->linkage()))
1541 Interposable = true;
1542 }
1543
1544 if (!IsAliasee) {
1545 if (!KeepAliveLinkage)
1546 return;
1547
1548 if (Interposable)
1550 "Interposable and available_externally/linkonce_odr/weak_odr "
1551 "symbol");
1552 }
1553 }
1554
1555 for (const auto &S : VI.getSummaryList())
1556 S->setLive(true);
1557 ++LiveSymbols;
1558 Worklist.push_back(VI);
1559 };
1560
1561 while (!Worklist.empty()) {
1562 auto VI = Worklist.pop_back_val();
1563 for (const auto &Summary : VI.getSummaryList()) {
1564 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
1565 // If this is an alias, visit the aliasee VI to ensure that all copies
1566 // are marked live and it is added to the worklist for further
1567 // processing of its references.
1568 visit(AS->getAliaseeVI(), true);
1569 continue;
1570 }
1571 for (auto Ref : Summary->refs())
1572 visit(Ref, false);
1573 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
1574 for (auto Call : FS->calls())
1575 visit(Call.first, false);
1576 }
1577 }
1578 Index.setWithGlobalValueDeadStripping();
1579
1580 unsigned DeadSymbols = Index.size() - LiveSymbols;
1581 LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
1582 << " symbols Dead \n");
1583 NumDeadSymbols += DeadSymbols;
1584 NumLiveSymbols += LiveSymbols;
1585}
1586
1587// Compute dead symbols and propagate constants in combined index.
1589 ModuleSummaryIndex &Index,
1590 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
1592 bool ImportEnabled) {
1593 llvm::TimeTraceScope timeScope("Drop dead symbols and propagate attributes");
1594 computeDeadSymbolsAndUpdateIndirectCalls(Index, GUIDPreservedSymbols,
1595 isPrevailing);
1596 if (ImportEnabled)
1597 Index.propagateAttributes(GUIDPreservedSymbols);
1598}
1599
1600/// Compute the set of summaries needed for a ThinLTO backend compilation of
1601/// \p ModulePath.
1603 StringRef ModulePath,
1604 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1605 const FunctionImporter::ImportMapTy &ImportList,
1606 ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
1607 GVSummaryPtrSet &DecSummaries) {
1608 // Include all summaries from the importing module.
1609 ModuleToSummariesForIndex[std::string(ModulePath)] =
1610 ModuleToDefinedGVSummaries.lookup(ModulePath);
1611
1612 // Forward port the heterogeneous std::map::operator[]() from C++26, which
1613 // lets us look up the map without allocating an instance of std::string when
1614 // the key-value pair exists in the map.
1615 // TODO: Remove this in favor of the heterogenous std::map::operator[]() from
1616 // C++26 when it becomes available for our codebase.
1617 auto LookupOrCreate = [](ModuleToSummariesForIndexTy &Map,
1619 auto It = Map.find(Key);
1620 if (It == Map.end())
1621 std::tie(It, std::ignore) =
1622 Map.try_emplace(std::string(Key), GVSummaryMapTy());
1623 return It->second;
1624 };
1625
1626 // Include summaries for imports.
1627 for (const auto &[FromModule, GUID, ImportType] : ImportList) {
1628 auto &SummariesForIndex =
1629 LookupOrCreate(ModuleToSummariesForIndex, FromModule);
1630
1631 const auto &DefinedGVSummaries = ModuleToDefinedGVSummaries.at(FromModule);
1632 const auto &DS = DefinedGVSummaries.find(GUID);
1633 assert(DS != DefinedGVSummaries.end() &&
1634 "Expected a defined summary for imported global value");
1635 if (ImportType == GlobalValueSummary::Declaration)
1636 DecSummaries.insert(DS->second);
1637
1638 SummariesForIndex[GUID] = DS->second;
1639 }
1640
1641 // When AlwaysRenamePromotedLocals is false, for each source module we import
1642 // from, also include summaries for local functions that have
1643 // NoRenameOnPromotion set. This is needed for distributed ThinLTO. Otherwise,
1644 // the local function of the source module will keep its origin name, e.g.,
1645 // foo() while the function in destination module will have name
1646 // foo.llvm.<...>() and this will cause a link failure.
1647 //
1648 // Note: this imports a superset of the necessary declarations — all locals
1649 // with NoRenameOnPromotion in each source module, not just those referenced
1650 // by the importing module. Computing the precise set would require walking
1651 // the summary reference graph from each imported function, which is more
1652 // expensive than the simple scan here.
1654 for (auto &[ModPath, SummariesForIndex] : ModuleToSummariesForIndex) {
1655 if (ModPath == ModulePath)
1656 continue;
1657 auto It = ModuleToDefinedGVSummaries.find(ModPath);
1658 if (It == ModuleToDefinedGVSummaries.end())
1659 continue;
1660 for (const auto &[GUID, Summary] : It->second) {
1661 if (Summary->noRenameOnPromotion()) {
1662 DecSummaries.insert(Summary);
1663 SummariesForIndex.try_emplace(GUID, Summary);
1664 }
1665 }
1666 }
1667 }
1668}
1669
1670/// Emit the files \p ModulePath will import from into \p OutputFilename.
1673 const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex) {
1674 std::error_code EC;
1676 if (EC)
1677 return createFileError("cannot open " + OutputFilename,
1678 errorCodeToError(EC));
1679 processImportsFiles(ModulePath, ModuleToSummariesForIndex,
1680 [&](StringRef M) { ImportsOS << M << "\n"; });
1681 return Error::success();
1682}
1683
1684/// Invoke callback \p F on the file paths from which \p ModulePath
1685/// will import.
1687 StringRef ModulePath,
1688 const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
1689 function_ref<void(const std::string &)> F) {
1690 for (const auto &ILI : ModuleToSummariesForIndex)
1691 // The ModuleToSummariesForIndex map includes an entry for the current
1692 // Module (needed for writing out the index files). We don't want to
1693 // include it in the imports file, however, so filter it out.
1694 if (ILI.first != ModulePath)
1695 F(ILI.first);
1696}
1697
1699 LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
1700 << "\n");
1701 MDNode *UniqueID = nullptr;
1702 if (auto *GO = dyn_cast<GlobalObject>(&GV))
1703 UniqueID = GO->getMetadata(LLVMContext::MD_guid);
1704
1705 if (Function *F = dyn_cast<Function>(&GV)) {
1706 F->deleteBody();
1707 F->clearMetadata();
1708 if (UniqueID)
1709 F->setMetadata(LLVMContext::MD_guid, UniqueID);
1710 F->setComdat(nullptr);
1711 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
1712 V->setInitializer(nullptr);
1713 V->setLinkage(GlobalValue::ExternalLinkage);
1714 V->clearMetadata();
1715 if (UniqueID)
1716 V->setMetadata(LLVMContext::MD_guid, UniqueID);
1717 V->setComdat(nullptr);
1718 } else {
1719 GlobalValue *NewGV;
1720 if (GV.getValueType()->isFunctionTy())
1721 NewGV =
1724 "", GV.getParent());
1725 else
1726 NewGV =
1727 new GlobalVariable(*GV.getParent(), GV.getValueType(),
1728 /*isConstant*/ false, GlobalValue::ExternalLinkage,
1729 /*init*/ nullptr, "",
1730 /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
1731 GV.getType()->getAddressSpace());
1732 NewGV->takeName(&GV);
1733 GV.replaceAllUsesWith(NewGV);
1734 return false;
1735 }
1736 if (!GV.isImplicitDSOLocal())
1737 GV.setDSOLocal(false);
1738 return true;
1739}
1740
1742 const GVSummaryMapTy &DefinedGlobals,
1743 bool PropagateAttrs) {
1744 llvm::TimeTraceScope timeScope("ThinLTO finalize in module");
1745 DenseSet<Comdat *> NonPrevailingComdats;
1746 auto FinalizeInModule = [&](GlobalValue &GV, bool Propagate = false) {
1747 // See if the global summary analysis computed a new resolved linkage.
1748 const auto &GS = DefinedGlobals.find(GV.getGUIDOrFallback());
1749 if (GS == DefinedGlobals.end())
1750 return;
1751
1752 if (Propagate)
1753 if (FunctionSummary *FS = dyn_cast<FunctionSummary>(GS->second)) {
1754 if (Function *F = dyn_cast<Function>(&GV)) {
1755 // TODO: propagate ReadNone and ReadOnly.
1756 if (FS->fflags().ReadNone && !F->doesNotAccessMemory())
1757 F->setDoesNotAccessMemory();
1758
1759 if (FS->fflags().ReadOnly && !F->onlyReadsMemory())
1760 F->setOnlyReadsMemory();
1761
1762 if (FS->fflags().NoRecurse && !F->doesNotRecurse())
1763 F->setDoesNotRecurse();
1764
1765 if (FS->fflags().NoUnwind && !F->doesNotThrow())
1766 F->setDoesNotThrow();
1767 }
1768 }
1769
1770 auto NewLinkage = GS->second->linkage();
1772 // Don't internalize anything here, because the code below
1773 // lacks necessary correctness checks. Leave this job to
1774 // LLVM 'internalize' pass.
1775 GlobalValue::isLocalLinkage(NewLinkage) ||
1776 // In case it was dead and already converted to declaration.
1777 GV.isDeclaration())
1778 return;
1779
1780 // Set the potentially more constraining visibility computed from summaries.
1781 // The DefaultVisibility condition is because older GlobalValueSummary does
1782 // not record DefaultVisibility and we don't want to change protected/hidden
1783 // to default.
1784 if (GS->second->getVisibility() != GlobalValue::DefaultVisibility)
1785 GV.setVisibility(GS->second->getVisibility());
1786
1787 if (NewLinkage == GV.getLinkage())
1788 return;
1789
1790 // Check for a non-prevailing def that has interposable linkage
1791 // (e.g. non-odr weak or linkonce). In that case we can't simply
1792 // convert to available_externally, since it would lose the
1793 // interposable property and possibly get inlined. Simply drop
1794 // the definition in that case.
1797 if (!convertToDeclaration(GV))
1798 // FIXME: Change this to collect replaced GVs and later erase
1799 // them from the parent module once thinLTOResolvePrevailingGUID is
1800 // changed to enable this for aliases.
1801 llvm_unreachable("Expected GV to be converted");
1802 } else {
1803 // If all copies of the original symbol had global unnamed addr and
1804 // linkonce_odr linkage, or if all of them had local unnamed addr linkage
1805 // and are constants, then it should be an auto hide symbol. In that case
1806 // the thin link would have marked it as CanAutoHide. Add hidden
1807 // visibility to the symbol to preserve the property.
1808 if (NewLinkage == GlobalValue::WeakODRLinkage &&
1809 GS->second->canAutoHide()) {
1812 }
1813
1814 LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
1815 << "` from " << GV.getLinkage() << " to " << NewLinkage
1816 << "\n");
1817 GV.setLinkage(NewLinkage);
1818 }
1819 // Remove declarations from comdats, including available_externally
1820 // as this is a declaration for the linker, and will be dropped eventually.
1821 // It is illegal for comdats to contain declarations.
1822 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
1823 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
1824 if (GO->getComdat()->getName() == GO->getName())
1825 NonPrevailingComdats.insert(GO->getComdat());
1826 GO->setComdat(nullptr);
1827 }
1828 };
1829
1830 // Process functions and global now
1831 for (auto &GV : TheModule)
1832 FinalizeInModule(GV, PropagateAttrs);
1833 for (auto &GV : TheModule.globals())
1834 FinalizeInModule(GV);
1835 for (auto &GV : TheModule.aliases())
1836 FinalizeInModule(GV);
1837
1838 // For a non-prevailing comdat, all its members must be available_externally.
1839 // FinalizeInModule has handled non-local-linkage GlobalValues. Here we handle
1840 // local linkage GlobalValues.
1841 if (NonPrevailingComdats.empty())
1842 return;
1843 for (auto &GO : TheModule.global_objects()) {
1844 if (auto *C = GO.getComdat(); C && NonPrevailingComdats.count(C)) {
1845 GO.setComdat(nullptr);
1847 }
1848 }
1849 bool Changed;
1850 do {
1851 Changed = false;
1852 // If an alias references a GlobalValue in a non-prevailing comdat, change
1853 // it to available_externally. For simplicity we only handle GlobalValue and
1854 // ConstantExpr with a base object. ConstantExpr without a base object is
1855 // unlikely used in a COMDAT.
1856 for (auto &GA : TheModule.aliases()) {
1857 if (GA.hasAvailableExternallyLinkage())
1858 continue;
1859 GlobalObject *Obj = GA.getAliaseeObject();
1860 assert(Obj && "aliasee without an base object is unimplemented");
1861 if (Obj->hasAvailableExternallyLinkage()) {
1863 Changed = true;
1864 }
1865 }
1866 } while (Changed);
1867}
1868
1869/// Run internalization on \p TheModule based on symmary analysis.
1871 const GVSummaryMapTy &DefinedGlobals) {
1872 llvm::TimeTraceScope timeScope("ThinLTO internalize module");
1873 // Declare a callback for the internalize pass that will ask for every
1874 // candidate GlobalValue if it can be internalized or not.
1875 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
1876 // It may be the case that GV is on a chain of an ifunc, its alias and
1877 // subsequent aliases. In this case, the summary for the value is not
1878 // available.
1879 if (isa<GlobalIFunc>(&GV) ||
1880 (isa<GlobalAlias>(&GV) &&
1881 isa<GlobalIFunc>(cast<GlobalAlias>(&GV)->getAliaseeObject())))
1882 return true;
1883
1884 // Lookup the linkage recorded in the summaries during global analysis.
1885 auto GS = DefinedGlobals.find(GV.getGUIDOrFallback());
1886 if (GS == DefinedGlobals.end()) {
1887 // Must have been promoted (possibly conservatively). Find original
1888 // name so that we can access the correct summary and see if it can
1889 // be internalized again.
1890 // FIXME: Eventually we should control promotion instead of promoting
1891 // and internalizing again.
1892 StringRef OrigName =
1894 std::string OrigId = GlobalValue::getGlobalIdentifier(
1896 TheModule.getSourceFileName());
1897 GS = DefinedGlobals.find(
1899 if (GS == DefinedGlobals.end()) {
1900 // Also check the original non-promoted non-globalized name. In some
1901 // cases a preempted weak value is linked in as a local copy because
1902 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
1903 // In that case, since it was originally not a local value, it was
1904 // recorded in the index using the original name.
1905 // FIXME: This may not be needed once PR27866 is fixed.
1906 GS = DefinedGlobals.find(
1908 assert(GS != DefinedGlobals.end());
1909 }
1910 }
1911 return !GlobalValue::isLocalLinkage(GS->second->linkage());
1912 };
1913
1914 // FIXME: See if we can just internalize directly here via linkage changes
1915 // based on the index, rather than invoking internalizeModule.
1916 internalizeModule(TheModule, MustPreserveGV);
1917}
1918
1919/// Make alias a clone of its aliasee.
1922
1923 ValueToValueMapTy VMap;
1924 Function *NewFn = CloneFunction(Fn, VMap);
1925 // Clone should use the original alias's linkage, visibility and name, and we
1926 // ensure all uses of alias instead use the new clone (casted if necessary).
1927 NewFn->setLinkage(GA->getLinkage());
1928 NewFn->setVisibility(GA->getVisibility());
1929 GA->replaceAllUsesWith(NewFn);
1930 NewFn->takeName(GA);
1931 return NewFn;
1932}
1933
1934// Internalize values that we marked with specific attribute
1935// in processGlobalForThinLTO.
1937 for (auto &GV : M.globals())
1938 // Skip GVs which have been converted to declarations
1939 // by dropDeadSymbols.
1940 if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
1941 GV.setLinkage(GlobalValue::InternalLinkage);
1942 GV.setVisibility(GlobalValue::DefaultVisibility);
1943 }
1944}
1945
1946/// When a function carrying !implicit.ref is imported via ThinLTO, the
1947/// referenced global arrives as available_externally. This string can be dead
1948/// code eliminated since it has no IR uses -- only metadata references. Adding
1949/// it to llvm.compiler.used prevents elimination.
1953 for (Function &F : M) {
1954 if (!F.hasAvailableExternallyLinkage() ||
1955 !F.hasMetadata(LLVMContext::MD_implicit_ref))
1956 continue;
1958 F.getMetadata(LLVMContext::MD_implicit_ref, MDs);
1959 for (MDNode *MD : MDs) {
1960 auto *Op = MD->getOperand(0).get();
1961 if (!Op)
1962 continue;
1963 if (auto *VAM = dyn_cast<ValueAsMetadata>(Op))
1964 if (auto *GV = dyn_cast<GlobalVariable>(VAM->getValue()))
1965 if (GV->hasAvailableExternallyLinkage() && Seen.insert(GV).second)
1966 ToProtect.push_back(GV);
1967 }
1968 }
1969 if (!ToProtect.empty())
1970 appendToCompilerUsed(M, ToProtect);
1971}
1972
1973// Automatically import functions in Module \p DestModule based on the summaries
1974// index.
1976 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
1977 LLVM_DEBUG(dbgs() << "Starting import for Module "
1978 << DestModule.getModuleIdentifier() << "\n");
1979 unsigned ImportedCount = 0, ImportedGVCount = 0;
1980 // Before carrying out any imports, see if this module defines functions in
1981 // MoveSymbolGUID. If it does, delete them here (but leave the declaration).
1982 // The function will be imported elsewhere, as extenal linkage, and the
1983 // destination doesn't yet have its definition.
1984 DenseSet<GlobalValue::GUID> MoveSymbolGUIDSet;
1985 MoveSymbolGUIDSet.insert_range(MoveSymbolGUID);
1986 for (auto &F : DestModule)
1987 if (!F.isDeclaration() && MoveSymbolGUIDSet.contains(F.getGUIDOrFallback()))
1988 F.deleteBody();
1989
1990 IRMover Mover(DestModule);
1991
1992 // Do the actual import of functions now, one Module at a time
1993 for (const auto &ModName : ImportList.getSourceModules()) {
1994 llvm::TimeTraceScope timeScope("Import", ModName);
1995 // Get the module for the import
1996 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(ModName);
1997 if (!SrcModuleOrErr)
1998 return SrcModuleOrErr.takeError();
1999 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
2000 assert(&DestModule.getContext() == &SrcModule->getContext() &&
2001 "Context mismatch");
2002
2003 // If modules were created with lazy metadata loading, materialize it
2004 // now, before linking it (otherwise this will be a noop).
2005 if (Error Err = SrcModule->materializeMetadata())
2006 return std::move(Err);
2007
2008 // Find the globals to import
2009 SetVector<GlobalValue *> GlobalsToImport;
2010 // Functions (or aliases of functions) to import as declarations, along
2011 // with their GUIDs.
2013 {
2014 llvm::TimeTraceScope functionsScope("Functions");
2015 for (Function &F : *SrcModule) {
2016 if (!F.hasName())
2017 continue;
2018 auto GUID = F.getGUIDOrFallback();
2019 auto MaybeImportType = ImportList.getImportType(ModName, GUID);
2020 bool ImportDefinition =
2021 MaybeImportType == GlobalValueSummary::Definition;
2022
2023 LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
2024 << " importing function"
2025 << (ImportDefinition
2026 ? " definition "
2027 : (MaybeImportType ? " declaration " : " "))
2028 << GUID << " " << F.getName() << " from "
2029 << SrcModule->getSourceFileName() << "\n");
2030 if (ImportDefinition) {
2031 if (Error Err = F.materialize())
2032 return std::move(Err);
2033 // MemProf should match function's definition and summary,
2034 // 'thinlto_src_module' is needed.
2036 // Add 'thinlto_src_module' and 'thinlto_src_file' metadata for
2037 // statistics and debugging.
2038 F.setMetadata(
2039 "thinlto_src_module",
2040 MDNode::get(DestModule.getContext(),
2041 {MDString::get(DestModule.getContext(),
2042 SrcModule->getModuleIdentifier())}));
2043 F.setMetadata(
2044 "thinlto_src_file",
2045 MDNode::get(DestModule.getContext(),
2046 {MDString::get(DestModule.getContext(),
2047 SrcModule->getSourceFileName())}));
2048 }
2049 GlobalsToImport.insert(&F);
2050 } else if (MaybeImportType) {
2051 assert(*MaybeImportType == GlobalValueSummary::Declaration);
2052 DeclsToImport.push_back({&F, GUID});
2053 }
2054 }
2055 }
2056 {
2057 llvm::TimeTraceScope globalsScope("Globals");
2058 for (GlobalVariable &GV : SrcModule->globals()) {
2059 if (!GV.hasName())
2060 continue;
2061 auto GUID = GV.getGUIDOrFallback();
2062 auto MaybeImportType = ImportList.getImportType(ModName, GUID);
2063 bool ImportDefinition =
2064 MaybeImportType == GlobalValueSummary::Definition;
2065
2066 LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
2067 << " importing global"
2068 << (ImportDefinition
2069 ? " definition "
2070 : (MaybeImportType ? " declaration " : " "))
2071 << GUID << " " << GV.getName() << " from "
2072 << SrcModule->getSourceFileName() << "\n");
2073 if (ImportDefinition) {
2074 if (Error Err = GV.materialize())
2075 return std::move(Err);
2076 ImportedGVCount += GlobalsToImport.insert(&GV);
2077 }
2078 }
2079 }
2080 {
2081 llvm::TimeTraceScope aliasesScope("Aliases");
2082 for (GlobalAlias &GA : SrcModule->aliases()) {
2083 if (!GA.hasName() || isa<GlobalIFunc>(GA.getAliaseeObject()))
2084 continue;
2085 auto GUID = GA.getGUIDOrFallback();
2086 auto MaybeImportType = ImportList.getImportType(ModName, GUID);
2087 bool ImportDefinition =
2088 MaybeImportType == GlobalValueSummary::Definition;
2089
2090 LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
2091 << " importing alias"
2092 << (ImportDefinition
2093 ? " definition "
2094 : (MaybeImportType ? " declaration " : " "))
2095 << GUID << " " << GA.getName() << " from "
2096 << SrcModule->getSourceFileName() << "\n");
2097 if (ImportDefinition) {
2098 if (Error Err = GA.materialize())
2099 return std::move(Err);
2100 // Import alias as a copy of its aliasee.
2101 GlobalObject *GO = GA.getAliaseeObject();
2102 if (Error Err = GO->materialize())
2103 return std::move(Err);
2104 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
2105 assert(Fn);
2106 (void)Fn;
2108 << "Is importing aliasee fn " << GO->getGUIDOrFallback()
2109 << " " << GO->getName() << " from "
2110 << SrcModule->getSourceFileName() << "\n");
2112 // Add 'thinlto_src_module' and 'thinlto_src_file' metadata for
2113 // statistics and debugging.
2114 Fn->setMetadata(
2115 "thinlto_src_module",
2116 MDNode::get(DestModule.getContext(),
2117 {MDString::get(DestModule.getContext(),
2118 SrcModule->getModuleIdentifier())}));
2119 Fn->setMetadata(
2120 "thinlto_src_file",
2121 MDNode::get(DestModule.getContext(),
2122 {MDString::get(DestModule.getContext(),
2123 SrcModule->getSourceFileName())}));
2124 }
2125 GlobalsToImport.insert(Fn);
2126 } else if (MaybeImportType) {
2127 assert(*MaybeImportType == GlobalValueSummary::Declaration);
2128 if (isa<FunctionType>(GA.getValueType()))
2129 DeclsToImport.push_back({&GA, GUID});
2130 }
2131 }
2132 }
2133
2134 // Upgrade debug info after we're done materializing all the globals and we
2135 // have loaded all the required metadata!
2136 UpgradeDebugInfo(*SrcModule);
2137
2138 // Set the partial sample profile ratio in the profile summary module flag
2139 // of the imported source module, if applicable, so that the profile summary
2140 // module flag will match with that of the destination module when it's
2141 // imported.
2142 SrcModule->setPartialSampleProfileRatio(Index);
2143
2144 // Link in the specified functions.
2145 renameModuleForThinLTO(*SrcModule, Index, ClearDSOLocalOnDeclarations,
2146 &GlobalsToImport);
2147
2148 // Record the information needed to create the declarations to import,
2149 // after any promotion and renaming above, since the source module is
2150 // consumed by the IRMover below.
2151 struct DeclInfo {
2152 std::string Name;
2153 FunctionType *Ty;
2154 unsigned AddrSpace;
2155 CallingConv::ID CC;
2156 AttributeList Attrs;
2158 bool DSOLocal;
2159 GlobalValue::GUID GUID;
2160 };
2161 SmallVector<DeclInfo> DeclInfos;
2162 for (auto [GV, GUID] : DeclsToImport) {
2163 assert(!GV->hasLocalLinkage() &&
2164 "Expected imported declaration to be promoted");
2165 const Function *F = dyn_cast<Function>(GV);
2166 if (!F)
2168 cast<GlobalAlias>(GV)->getAliaseeObject());
2169 if (!F)
2170 continue;
2171 DeclInfos.push_back({GV->getName().str(), F->getFunctionType(),
2172 F->getAddressSpace(), F->getCallingConv(),
2173 F->getAttributes(), GV->getVisibility(),
2174 GV->isDSOLocal(), GUID});
2175 }
2176
2177 if (PrintImports) {
2178 for (const auto *GV : GlobalsToImport)
2179 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
2180 << " from " << SrcModule->getSourceFileName() << "\n";
2181 }
2182
2183 if (Error Err = Mover.move(std::move(SrcModule),
2184 GlobalsToImport.getArrayRef(), nullptr,
2185 /*IsPerformingImport=*/true))
2187 Twine("Function Import: link error: ") +
2188 toString(std::move(Err)));
2189
2190 ImportedCount += GlobalsToImport.size();
2191 NumImportedModules++;
2192
2193 // Now create the declarations to import, if they don't already exist in
2194 // the destination module. Declarations of direct callees will typically
2195 // already exist, either because the call is in the destination module or
2196 // because the IRMover created them when linking an imported definition
2197 // that references them. Callees reached only via indirect calls (e.g.
2198 // from value profile or MemProf call edges in the summary) have no such IR
2199 // reference, so this is mainly where declarations of those are created.
2200 //
2201 // We create these declarations by hand rather than via the IRMover: the
2202 // IRMover only creates declarations as a side effect of mapping references
2203 // from linked IR, it creates attribute-less declarations for aliases, and
2204 // it does not copy metadata from source definitions.
2205 for (auto &DI : DeclInfos) {
2206 if (DestModule.getNamedValue(DI.Name))
2207 continue;
2209 DI.AddrSpace, DI.Name, &DestModule);
2210 F->setCallingConv(DI.CC);
2211 F->setAttributes(DI.Attrs);
2212 // Note that the visibility must be set before dso_local, since
2213 // setDSOLocal(false) is not allowed on an implicitly dso_local value.
2214 F->setVisibility(DI.Visibility);
2215 F->setDSOLocal(DI.DSOLocal);
2216 // Record the GUID of the original value, which may differ from the GUID
2217 // computed from the current name if it was a promoted local. This allows
2218 // the declaration to be located via the GUID, e.g. by MemProf ICP.
2219 F->setMetadata(LLVMContext::MD_guid,
2220 MDNode::get(DestModule.getContext(),
2221 {ConstantAsMetadata::get(ConstantInt::get(
2222 Type::getInt64Ty(DestModule.getContext()),
2223 DI.GUID))}));
2224 NumImportedFunctionDecls++;
2225 }
2226 }
2227
2228 internalizeGVsAfterImport(DestModule);
2229
2230 // Protect !implicit.ref-referenced globals imported as available_externally
2231 // from DCE'd. Only needed when globals were actually imported.
2232 if (ImportedGVCount > 0)
2233 protectImplicitRefGlobals(DestModule);
2234
2235 NumImportedFunctions += (ImportedCount - ImportedGVCount);
2236 NumImportedGlobalVars += ImportedGVCount;
2237
2238 // TODO: Print counters for definitions and declarations in the debugging log.
2239 LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
2240 << " functions for Module "
2241 << DestModule.getModuleIdentifier() << "\n");
2242 LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
2243 << " global variables for Module "
2244 << DestModule.getModuleIdentifier() << "\n");
2245 return ImportedCount;
2246}
2247
2250 isPrevailing) {
2251 if (SummaryFile.empty())
2252 report_fatal_error("error: -function-import requires -summary-file\n");
2255 if (!IndexPtrOrErr) {
2256 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
2257 "Error loading file '" + SummaryFile + "': ");
2258 return false;
2259 }
2260 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
2261
2262 // First step is collecting the import list.
2264 FunctionImporter::ImportMapTy ImportList(ImportIDs);
2265 // If requested, simply import all functions in the index. This is used
2266 // when testing distributed backend handling via the opt tool, when
2267 // we have distributed indexes containing exactly the summaries to import.
2268 if (ImportAllIndex)
2270 *Index, ImportList);
2271 else
2272 ComputeCrossModuleImportForModuleForTest(M.getModuleIdentifier(),
2273 isPrevailing, *Index, ImportList);
2274
2275 // Conservatively mark all internal values as promoted. This interface is
2276 // only used when doing importing via the function importing pass. The pass
2277 // is only enabled when testing importing via the 'opt' tool, which does
2278 // not do the ThinLink that would normally determine what values to promote.
2279 for (auto &I : *Index) {
2280 for (auto &S : I.second.getSummaryList()) {
2281 if (GlobalValue::isLocalLinkage(S->linkage()))
2282 S->setExternalLinkageForTest();
2283 }
2284 }
2285
2286 // Next we need to promote to global scope and rename any local values that
2287 // are potentially exported to other modules.
2288 renameModuleForThinLTO(M, *Index, /*ClearDSOLocalOnDeclarations=*/false,
2289 /*GlobalsToImport=*/nullptr);
2290
2291 // Perform the import now.
2292 auto ModuleLoader = [&M](StringRef Identifier) {
2293 return loadFile(std::string(Identifier), M.getContext());
2294 };
2295 FunctionImporter Importer(*Index, ModuleLoader,
2296 /*ClearDSOLocalOnDeclarations=*/false);
2297 Expected<bool> Result = Importer.importFunctions(M, ImportList);
2298
2299 // FIXME: Probably need to propagate Errors through the pass manager.
2300 if (!Result) {
2301 logAllUnhandledErrors(Result.takeError(), errs(),
2302 "Error importing module: ");
2303 return true;
2304 }
2305
2306 return true;
2307}
2308
2311 // This is only used for testing the function import pass via opt, where we
2312 // don't have prevailing information from the LTO context available, so just
2313 // conservatively assume everything is prevailing (which is fine for the very
2314 // limited use of prevailing checking in this pass).
2315 auto isPrevailing = [](GlobalValue::GUID, const GlobalValueSummary *) {
2316 return true;
2317 };
2318 if (!doImportingForModuleForTest(M, isPrevailing))
2319 return PreservedAnalyses::all();
2320
2321 return PreservedAnalyses::none();
2322}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
static auto qualifyCalleeCandidates(const ModuleSummaryIndex &Index, ArrayRef< std::unique_ptr< GlobalValueSummary > > CalleeSummaryList, StringRef CallerModulePath)
Given a list of possible callee implementation for a call site, qualify the legality of importing eac...
static DenseMap< StringRef, ImportStatistics > collectImportStatistics(const ModuleSummaryIndex &Index, const FunctionImporter::ImportMapTy &ImportList)
static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, FunctionImporter::ExportSetTy &ExportSet)
static bool checkVariableImport(const ModuleSummaryIndex &Index, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
static bool doImportingForModuleForTest(Module &M, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
static const char * getFailureName(FunctionImporter::ImportFailureReason Reason)
static void internalizeGVsAfterImport(Module &M)
void updateValueInfoForIndirectCalls(ModuleSummaryIndex &Index, FunctionSummary *FS)
static std::unique_ptr< Module > loadFile(const std::string &FileName, LLVMContext &Context)
static bool shouldSkipLocalInAnotherModule(const GlobalValueSummary *RefSummary, size_t NumDefs, StringRef ImporterModule)
static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI)
static Function * replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA)
Make alias a clone of its aliasee.
static void protectImplicitRefGlobals(Module &M)
When a function carrying !implicit.ref is imported via ThinLTO, the referenced global arrives as avai...
static void dumpImportListForModule(const ModuleSummaryIndex &Index, StringRef ModulePath, FunctionImporter::ImportMapTy &ImportList)
static void ComputeCrossModuleImportForModuleFromIndexForTest(StringRef ModulePath, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList)
Mark all external summaries in Index for import into the given module.
static const GlobalValueSummary * selectCallee(const ModuleSummaryIndex &Index, ArrayRef< std::unique_ptr< GlobalValueSummary > > CalleeSummaryList, unsigned Threshold, StringRef CallerModulePath, const GlobalValueSummary *&TooLargeOrNoInlineSummary, FunctionImporter::ImportFailureReason &Reason)
Given a list of possible callee implementation for a call site, select one that fits the Threshold fo...
static void ComputeCrossModuleImportForModuleForTest(StringRef ModulePath, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList)
Compute all the imports for the given module using the Index.
Module.h This file contains the declarations for the Module class.
This file supports working with JSON data.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
block placement Basic Block Placement Stats
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
This file contains the declarations for metadata subclasses.
static cl::opt< bool > PropagateAttrs("propagate-attrs", cl::init(true), cl::Hidden, cl::desc("Propagate attributes in index"))
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
static constexpr StringLiteral Filename
Reader for contextual iFDO profile, which comes in bitstream format.
if(PassOpts->AAPipeline)
const char * Msg
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Import globals referenced by a function or other globals that are being imported, if importing such g...
void onImportingSummary(const GlobalValueSummary &Summary)
GlobalsImporter(const ModuleSummaryIndex &Index, const GVSummaryMapTy &DefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, FunctionImporter::ImportMapTy &ImportList, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists)
virtual bool canImport(ValueInfo VI)
DenseMap< StringRef, FunctionImporter::ExportSetTy > *const ExportLists
virtual ~ModuleImportsManager()=default
static std::unique_ptr< ModuleImportsManager > create(function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists=nullptr)
function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing
ModuleImportsManager(function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists=nullptr)
const ModuleSummaryIndex & Index
virtual void computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries, StringRef ModName, FunctionImporter::ImportMapTy &ImportList)
Given the list of globals defined in a module, compute the list of imports as well as the list of "ex...
WorkloadImportsManager(function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:811
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
The map maintains the list of imports.
LLVM_ABI AddDefinitionStatus addDefinition(StringRef FromModule, GlobalValue::GUID GUID)
void addGUID(StringRef FromModule, GlobalValue::GUID GUID, GlobalValueSummary::ImportKind ImportKind)
LLVM_ABI SmallVector< StringRef, 0 > getSourceModules() const
LLVM_ABI std::optional< GlobalValueSummary::ImportKind > getImportType(StringRef FromModule, GlobalValue::GUID GUID) const
LLVM_ABI void maybeAddDeclaration(StringRef FromModule, GlobalValue::GUID GUID)
The function importer is automatically importing function from other modules based on the provided su...
LLVM_ABI Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
DenseMap< GlobalValue::GUID, std::tuple< unsigned, const GlobalValueSummary *, std::unique_ptr< ImportFailureInfo > > > ImportThresholdsTy
Map of callee GUID considered for import into a given module to a pair consisting of the largest thre...
ImportFailureReason
The different reasons selectCallee will chose not to import a candidate.
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function summary information to aid decisions and implementation of importing.
unsigned instCount() const
Get the instruction count recorded for this function.
FFlags fflags() const
Get function summary flags.
Class to represent function types.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:730
Function and variable summary information to aid decisions and implementation of importing.
StringRef modulePath() const
Get the path to the module containing this function.
GlobalValue::LinkageTypes linkage() const
Return linkage type recorded for this global value.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
VisibilityTypes getVisibility() const
bool isImplicitDSOLocal() const
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
Definition Globals.cpp:110
ThreadLocalMode getThreadLocalMode() const
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
void setLinkage(LinkageTypes LT)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:234
void setVisibility(VisibilityTypes V)
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
LLVM_ABI Error materialize()
Make sure this GlobalValue is fully read.
Definition Globals.cpp:52
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition Globals.cpp:546
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue * > ValuesToLink, LazyCallback AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
Definition IRMover.cpp:1693
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted).
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
const std::string & getSourceFileName() const
Get the module's original source file name.
Definition Module.h:310
iterator_range< alias_iterator > aliases()
Definition Module.h:853
iterator_range< global_iterator > globals()
Definition Module.h:802
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:299
iterator_range< global_object_iterator > global_objects()
Definition Module.cpp:461
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition Module.cpp:177
LLVM_ABI Expected< PGOCtxProfile > loadProfiles()
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:307
A vector that has set insertion semantics.
Definition SetVector.h:57
ArrayRef< value_type > getArrayRef() const
Definition SetVector.h:91
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
Vector takeVector()
Clear the SetVector and return the underlying vector.
Definition SetVector.h:94
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition StringMap.h:275
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:311
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
char front() const
Get the first character in the string.
Definition StringRef.h:147
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:39
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:268
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
void insert_range(Range &&R)
Definition DenseSet.h:235
size_type size() const
Definition DenseSet.h:84
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:187
bool remove_if(Predicate Pred)
Remove all elements for which Pred returns true.
Definition DenseSet.h:103
An efficient, type-erasing, non-owning reference to a callable.
The root is the trivial Path to the root value.
Definition JSON.h:700
A raw_ostream that writes to a file descriptor.
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
LLVM_ABI llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
Definition JSON.cpp:681
bool fromJSON(const Value &E, std::string &Out, Path P)
Definition JSON.h:729
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:793
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
static cl::opt< float > ImportHotMultiplier("import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"))
static cl::opt< bool > CtxprofMoveRootsToOwnModule("thinlto-move-ctxprof-trees", cl::desc("Move contextual profiling roots and the graphs under them in " "their own module."), cl::Hidden, cl::init(false))
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
bool internalizeModule(Module &TheModule, std::function< bool(const GlobalValue &)> MustPreserveGV)
Helper function to internalize functions and variables in a Module.
Definition Internalize.h:78
static cl::opt< float > ImportColdMultiplier("import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"))
std::error_code make_error_code(BitcodeError E)
cl::list< GlobalValue::GUID > MoveSymbolGUID
const char * getHotnessName(CalleeInfo::HotnessType HT)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
static cl::opt< std::string > WorkloadDefinitions("thinlto-workload-def", cl::desc("Pass a workload definition. This is a file containing a JSON " "dictionary. The keys are root functions, the values are lists of " "functions to import in the module defining the root. It is " "assumed -funique-internal-linkage-names was used, to ensure " "local linkage functions have unique names. For example: \n" "{\n" " \"rootFunction_1\": [\"function_to_import_1\", " "\"function_to_import_2\"], \n" " \"rootFunction_2\": [\"function_to_import_3\", " "\"function_to_import_4\"] \n" "}"), cl::Hidden)
Pass a workload description file - an example of workload would be the functions executed to satisfy ...
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
static cl::opt< bool > PrintImportFailures("print-import-failures", cl::init(false), cl::Hidden, cl::desc("Print information for functions rejected for importing"))
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
static cl::opt< unsigned > ImportInstrLimit("import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), cl::desc("Only import functions with less than N instructions"))
Limit on instruction count of imported functions.
LLVM_ABI void renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
static cl::opt< float > ImportHotInstrFactor("import-hot-evolution-factor", cl::init(1.0), cl::Hidden, cl::value_desc("x"), cl::desc("As we import functions called from hot callsite, multiply the " "`import-instr-limit` threshold by this factor " "before processing newly imported functions"))
static cl::opt< bool > PrintImports("print-imports", cl::init(false), cl::Hidden, cl::desc("Print imported functions"))
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
@ not_supported
Definition Errc.h:69
@ invalid_argument
Definition Errc.h:56
LLVM_ABI void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static cl::opt< float > ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), cl::Hidden, cl::value_desc("x"), cl::desc("As we import functions, multiply the " "`import-instr-limit` threshold by this factor " "before processing newly imported functions"))
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
cl::opt< bool > AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true), cl::Hidden, cl::desc("Always rename promoted locals."))
Definition LTO.cpp:112
LLVM_ABI void computeDeadSymbolsAndUpdateIndirectCalls(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing)
Compute all the symbols that are "dead": i.e these that can't be reached in the graph from any of the...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:300
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
static cl::opt< bool > ImportAllIndex("import-all-index", cl::desc("Import all external functions in index."))
Used when testing importing from distributed indexes via opt.
static cl::opt< int > ImportCutoff("import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"), cl::desc("Only import first N functions if N>=0 (default -1)"))
static cl::opt< bool > ImportDeclaration("import-declaration", cl::init(false), cl::Hidden, cl::desc("If true, import function declaration as fallback if the function " "definition is not imported."))
This is a test-only option.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI void updateIndirectCalls(ModuleSummaryIndex &Index)
Update call edges for indirect calls to local functions added from SamplePGO when needed.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
LLVM_ABI std::unique_ptr< Module > getLazyIRFileModule(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata=false)
If the given file holds a bitcode image, return a Module for it which does lazy deserialization of fu...
Definition IRReader.cpp:51
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
cl::opt< bool > ForceImportAll
DWARFExpression::Operation Op
LLVM_ABI void gatherImportedSummariesForModule(StringRef ModulePath, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
static cl::opt< std::string > SummaryFile("summary-file", cl::desc("The summary file to use for function importing."))
Summary file to use for function importing when using -function-import from the command line.
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void processImportsFiles(StringRef ModulePath, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, function_ref< void(const std::string &)> F)
Call F passing each of the files module ModulePath will import from.
static cl::opt< float > ImportCriticalMultiplier("import-critical-multiplier", cl::init(100.0), cl::Hidden, cl::value_desc("x"), cl::desc("Multiply the `import-instr-limit` threshold for critical callsites"))
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
PrevailingType
PrevailingType enum used as a return type of callback passed to computeDeadSymbolsAndUpdateIndirectCa...
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
static cl::opt< bool > EnableImportMetadata("enable-import-metadata", cl::init(false), cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module' and " "'thinlto_src_file'"))
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
LLVM_ABI 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.
LLVM_ABI Error EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
static cl::opt< bool > ComputeDead("compute-dead", cl::init(true), cl::Hidden, cl::desc("Compute dead symbols"))
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
Struct that holds a reference to a particular GUID in a global value summary.