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 "IPOOptions.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SetVector.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/StringRef.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/GlobalAlias.h"
28#include "llvm/IR/GlobalValue.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/IR/Module.h"
35#include "llvm/Linker/IRMover.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/Errc.h"
41#include "llvm/Support/Error.h"
44#include "llvm/Support/JSON.h"
45#include "llvm/Support/Path.h"
54#include <cassert>
55#include <memory>
56#include <string>
57#include <system_error>
58#include <tuple>
59#include <utility>
60
61using namespace llvm;
62
63#define DEBUG_TYPE "function-import"
64
65STATISTIC(NumImportedFunctionsThinLink,
66 "Number of functions thin link decided to import");
67STATISTIC(NumImportedHotFunctionsThinLink,
68 "Number of hot functions thin link decided to import");
69STATISTIC(NumImportedCriticalFunctionsThinLink,
70 "Number of critical functions thin link decided to import");
71STATISTIC(NumImportedGlobalVarsThinLink,
72 "Number of global variables thin link decided to import");
73STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
74STATISTIC(NumRequiredDeclsThinLink,
75 "Number of function declarations thin link decided to import because "
76 "the callee is required in the caller's module (e.g. for MemProf "
77 "ICP)");
78STATISTIC(NumImportedFunctionDecls,
79 "Number of function declarations imported in backend");
80STATISTIC(NumImportedGlobalVars,
81 "Number of global variables imported in backend");
82STATISTIC(NumImportedModules, "Number of modules imported from");
83STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
84STATISTIC(NumLiveSymbols, "Number of live symbols in index");
85
86namespace llvm {
88
90 ForceImportAll("force-import-all", cl::init(false), cl::Hidden,
91 cl::desc("Import functions with noinline attribute"));
92
93/// Limit on instruction count of imported functions.
95 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
96 cl::desc("Only import functions with less than N instructions"));
97
99 "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
100 cl::desc("Only import first N functions if N>=0 (default -1)"));
101
102static cl::opt<float>
103 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
105 cl::desc("As we import functions, multiply the "
106 "`import-instr-limit` threshold by this factor "
107 "before processing newly imported functions"));
108
110 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
111 cl::value_desc("x"),
112 cl::desc("As we import functions called from hot callsite, multiply the "
113 "`import-instr-limit` threshold by this factor "
114 "before processing newly imported functions"));
115
117 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
118 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
119
121 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
122 cl::value_desc("x"),
123 cl::desc(
124 "Multiply the `import-instr-limit` threshold for critical callsites"));
125
126// FIXME: This multiplier was not really tuned up.
128 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
129 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
130
132 "print-import-failures", cl::init(false), cl::Hidden,
133 cl::desc("Print information for functions rejected for importing"));
134
135static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
136 cl::desc("Compute dead symbols"));
137
138/// This is a test-only option.
139/// If this option is enabled, the ThinLTO indexing step will import each
140/// function declaration as a fallback. In a real build this may increase ram
141/// usage of the indexing step unnecessarily.
142/// TODO: Implement selective import (based on combined summary analysis) to
143/// ensure the imported function has a use case in the postlink pipeline.
145 "import-declaration", cl::init(false), cl::Hidden,
146 cl::desc("If true, import function declaration as fallback if the function "
147 "definition is not imported."));
148
149/// Pass a workload description file - an example of workload would be the
150/// functions executed to satisfy a RPC request. A workload is defined by a root
151/// function and the list of functions that are (frequently) needed to satisfy
152/// it. The module that defines the root will have all those functions imported.
153/// The file contains a JSON dictionary. The keys are root functions, the values
154/// are lists of functions to import in the module defining the root. It is
155/// assumed -funique-internal-linkage-names was used, thus ensuring function
156/// names are unique even for local linkage ones.
158 "thinlto-workload-def",
159 cl::desc("Pass a workload definition. This is a file containing a JSON "
160 "dictionary. The keys are root functions, the values are lists of "
161 "functions to import in the module defining the root. It is "
162 "assumed -funique-internal-linkage-names was used, to ensure "
163 "local linkage functions have unique names. For example: \n"
164 "{\n"
165 " \"rootFunction_1\": [\"function_to_import_1\", "
166 "\"function_to_import_2\"], \n"
167 " \"rootFunction_2\": [\"function_to_import_3\", "
168 "\"function_to_import_4\"] \n"
169 "}"),
170 cl::Hidden);
171
173
175 "thinlto-move-ctxprof-trees",
176 cl::desc("Move contextual profiling roots and the graphs under them in "
177 "their own module."),
178 cl::Hidden, cl::init(false));
179
181
183} // end namespace llvm
184
185// Load lazily a module from \p FileName in \p Context.
186static std::unique_ptr<Module> loadFile(const std::string &FileName,
187 LLVMContext &Context) {
188 SMDiagnostic Err;
189 LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
190 // Metadata isn't loaded until functions are imported, to minimize
191 // the memory overhead.
192 std::unique_ptr<Module> Result =
193 getLazyIRFileModule(FileName, Err, Context,
194 /* ShouldLazyLoadMetadata = */ true);
195 if (!Result) {
196 Err.print("function-import", errs());
197 report_fatal_error("Abort");
198 }
199
200 return Result;
201}
202
204 size_t NumDefs,
205 StringRef ImporterModule) {
206 // We can import a local when there is one definition.
207 if (NumDefs == 1)
208 return false;
209 // In other cases, make sure we import the copy in the caller's module if the
210 // referenced value has local linkage. The only time a local variable can
211 // share an entry in the index is if there is a local with the same name in
212 // another module that had the same source file name (in a different
213 // directory), where each was compiled in their own directory so there was not
214 // distinguishing path.
215 return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
216 RefSummary->modulePath() != ImporterModule;
217}
218
219/// Given a list of possible callee implementation for a call site, qualify the
220/// legality of importing each. The return is a range of pairs. Each pair
221/// corresponds to a candidate. The first value is the ImportFailureReason for
222/// that candidate, the second is the candidate.
224 const ModuleSummaryIndex &Index,
225 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
226 StringRef CallerModulePath) {
227 return llvm::map_range(
228 CalleeSummaryList,
229 [&Index, CalleeSummaryList,
230 CallerModulePath](const std::unique_ptr<GlobalValueSummary> &SummaryPtr)
232 const GlobalValueSummary *> {
233 auto *GVSummary = SummaryPtr.get();
234 if (!Index.isGlobalValueLive(GVSummary))
236
237 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
239 GVSummary};
240
241 auto *Summary = dyn_cast<FunctionSummary>(GVSummary->getBaseObject());
242
243 // Ignore any callees that aren't actually functions. This could happen
244 // in the case of GUID hash collisions. It could also happen in theory
245 // for SamplePGO profiles collected on old versions of the code after
246 // renaming, since we synthesize edges to any inlined callees appearing
247 // in the profile.
248 if (!Summary)
250
251 // If this is a local function, make sure we import the copy in the
252 // caller's module. The only time a local function can share an entry in
253 // the index is if there is a local with the same name in another module
254 // that had the same source file name (in a different directory), where
255 // each was compiled in their own directory so there was not
256 // distinguishing path.
257 // If the local function is from another module, it must be a reference
258 // due to indirect call profile data since a function pointer can point
259 // to a local in another module. Do the import from another module if
260 // there is only one entry in the list or when all files in the program
261 // are compiled with full path - in both cases the local function has
262 // unique PGO name and GUID.
263 if (shouldSkipLocalInAnotherModule(Summary, CalleeSummaryList.size(),
264 CallerModulePath))
265 return {
267 GVSummary};
268
269 // Skip if it isn't legal to import (e.g. may reference unpromotable
270 // locals).
271 if (Summary->notEligibleToImport())
273 GVSummary};
274
276 });
277}
278
279/// Given a list of possible callee implementation for a call site, select one
280/// that fits the \p Threshold for function definition import. If none are
281/// found, the Reason will give the last reason for the failure (last, in the
282/// order of CalleeSummaryList entries). While looking for a callee definition,
283/// sets \p TooLargeOrNoInlineSummary to the last seen too-large or noinline
284/// candidate; other modules may want to know the function summary or
285/// declaration even if a definition is not needed.
286///
287/// FIXME: select "best" instead of first that fits. But what is "best"?
288/// - The smallest: more likely to be inlined.
289/// - The one with the least outgoing edges (already well optimized).
290/// - One from a module already being imported from in order to reduce the
291/// number of source modules parsed/linked.
292/// - One that has PGO data attached.
293/// - [insert you fancy metric here]
294static const GlobalValueSummary *
296 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
297 unsigned Threshold, StringRef CallerModulePath,
298 const GlobalValueSummary *&TooLargeOrNoInlineSummary,
300 // Records the last summary with reason noinline or too-large.
301 TooLargeOrNoInlineSummary = nullptr;
302 auto QualifiedCandidates =
303 qualifyCalleeCandidates(Index, CalleeSummaryList, CallerModulePath);
304 for (auto QualifiedValue : QualifiedCandidates) {
305 Reason = QualifiedValue.first;
306 // Skip a summary if its import is not (proved to be) legal.
308 continue;
309 auto *Summary =
310 cast<FunctionSummary>(QualifiedValue.second->getBaseObject());
311
312 // Don't bother importing the definition if the chance of inlining it is
313 // not high enough (except under `--force-import-all`).
314 if ((Summary->instCount() > Threshold) && !Summary->fflags().AlwaysInline &&
316 TooLargeOrNoInlineSummary = Summary;
318 continue;
319 }
320
321 // Don't bother importing the definition if we can't inline it anyway.
322 if (Summary->fflags().NoInline && !ForceImportAll) {
323 TooLargeOrNoInlineSummary = Summary;
325 continue;
326 }
327
328 return Summary;
329 }
330 return nullptr;
331}
332
333namespace {
334
335using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */>;
336
337} // anonymous namespace
338
341 GlobalValue::GUID GUID) {
342 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
343 if (!Imports.insert(Def).second)
344 // Already there.
346
347 // Remove Decl in case it's there. Note that a definition takes precedence
348 // over a declaration for a given GUID.
349 return Imports.erase(Decl) ? AddDefinitionStatus::ChangedToDefinition
351}
352
354 StringRef FromModule, GlobalValue::GUID GUID) {
355 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
356 // Insert Decl only if Def is not present. Note that a definition takes
357 // precedence over a declaration for a given GUID.
358 if (!Imports.contains(Def))
359 Imports.insert(Decl);
360}
361
364 SetVector<StringRef> ModuleSet;
365 for (const auto &[SrcMod, GUID, ImportType] : *this)
366 ModuleSet.insert(SrcMod);
367 SmallVector<StringRef, 0> Modules = ModuleSet.takeVector();
368 llvm::sort(Modules);
369 return Modules;
370}
371
372std::optional<GlobalValueSummary::ImportKind>
374 GlobalValue::GUID GUID) const {
375 if (auto IDPair = IDs.getImportIDs(FromModule, GUID)) {
376 auto [Def, Decl] = *IDPair;
377 if (Imports.contains(Def))
379 if (Imports.contains(Decl))
381 }
382 return std::nullopt;
383}
384
385/// Import globals referenced by a function or other globals that are being
386/// imported, if importing such global is possible.
387class GlobalsImporter final {
388 const ModuleSummaryIndex &Index;
389 const GVSummaryMapTy &DefinedGVSummaries;
391 IsPrevailing;
394
395 bool shouldImportGlobal(const ValueInfo &VI, StringRef ReferencingModule) {
396 const auto &GVS = DefinedGVSummaries.find(VI.getGUID());
397 if (GVS == DefinedGVSummaries.end())
398 return true;
399 // A local definition in the destination module cannot satisfy a reference
400 // from a different module.
401 if (shouldSkipLocalInAnotherModule(GVS->second, VI.getSummaryList().size(),
402 ReferencingModule))
403 return true;
404 // We should not skip import if the module contains a non-prevailing
405 // definition with interposable linkage type. This is required for
406 // correctness in the situation where there is a prevailing def available
407 // for import and marked read-only. In this case, the non-prevailing def
408 // will be converted to a declaration, while the prevailing one becomes
409 // internal, thus no definitions will be available for linking. In order to
410 // prevent undefined symbol link error, the prevailing definition must be
411 // imported.
412 // FIXME: Consider adding a check that the suitable prevailing definition
413 // exists and marked read-only.
414 if (VI.getSummaryList().size() > 1 &&
415 GlobalValue::isInterposableLinkage(GVS->second->linkage()) &&
416 !IsPrevailing(VI.getGUID(), GVS->second))
417 return true;
418
419 return false;
420 }
421
422 void
423 onImportingSummaryImpl(const GlobalValueSummary &Summary,
425 for (const auto &VI : Summary.refs()) {
426 if (!shouldImportGlobal(VI, Summary.modulePath())) {
428 dbgs() << "Ref ignored! Target already in destination module.\n");
429 continue;
430 }
431
432 LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
433
434 for (const auto &RefSummary : VI.getSummaryList()) {
435 const auto *GVS = dyn_cast<GlobalVarSummary>(RefSummary.get());
436 // Stop looking if this is not a global variable, e.g. a function.
437 // Functions could be referenced by global vars - e.g. a vtable; but we
438 // don't currently imagine a reason those would be imported here, rather
439 // than as part of the logic deciding which functions to import (i.e.
440 // based on profile information). Should we decide to handle them here,
441 // we can refactor accordingly at that time.
442 // Note that it is safe to stop looking because the one case where we
443 // might have to import (a read/write-only global variable) cannot occur
444 // if this GUID has a non-variable summary. The only case where we even
445 // might find another summary in the list that is a variable is in the
446 // case of same-named locals in different modules not compiled with
447 // enough path, and during attribute propagation we will mark all
448 // summaries for a GUID (ValueInfo) as non read/write-only if any is not
449 // a global variable.
450 if (!GVS)
451 break;
452 bool CanImportDecl = false;
453 if (shouldSkipLocalInAnotherModule(GVS, VI.getSummaryList().size(),
454 Summary.modulePath()) ||
455 !Index.canImportGlobalVar(GVS, /* AnalyzeRefs */ true,
456 CanImportDecl)) {
457 if (ImportDeclaration && CanImportDecl)
458 ImportList.maybeAddDeclaration(RefSummary->modulePath(),
459 VI.getGUID());
460
461 continue;
462 }
463
464 // If there isn't an entry for GUID, insert <GUID, Definition> pair.
465 // Otherwise, definition should take precedence over declaration.
466 if (ImportList.addDefinition(RefSummary->modulePath(), VI.getGUID()) !=
468 break;
469
470 // Only update stat and exports if we haven't already imported this
471 // variable.
472 NumImportedGlobalVarsThinLink++;
473 // Any references made by this variable will be marked exported
474 // later, in ComputeCrossModuleImport, after import decisions are
475 // complete, which is more efficient than adding them here.
476 if (ExportLists)
477 (*ExportLists)[RefSummary->modulePath()].insert(VI);
478
479 // If variable is not writeonly we attempt to recursively analyze
480 // its references in order to import referenced constants.
481 if (!Index.isWriteOnly(GVS))
482 Worklist.emplace_back(GVS);
483 break;
484 }
485 }
486 }
487
488public:
490 const ModuleSummaryIndex &Index, const GVSummaryMapTy &DefinedGVSummaries,
492 IsPrevailing,
495 : Index(Index), DefinedGVSummaries(DefinedGVSummaries),
496 IsPrevailing(IsPrevailing), ImportList(ImportList),
497 ExportLists(ExportLists) {}
498
501 onImportingSummaryImpl(Summary, Worklist);
502 while (!Worklist.empty())
503 onImportingSummaryImpl(*Worklist.pop_back_val(), Worklist);
504 }
505};
506
508
509/// Determine the list of imports and exports for each module.
511 void computeImportForFunction(
512 const FunctionSummary &Summary, unsigned Threshold,
513 const GVSummaryMapTy &DefinedGVSummaries,
514 SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
516 FunctionImporter::ImportThresholdsTy &ImportThresholds);
517
518protected:
523 // Values exported because a declaration of them is required in an importing
524 // module (see RequiresDeclImport in computeImportForFunction). These are
525 // tracked separately from ExportLists, as unlike values exported because of
526 // an imported definition, their own references and calls should not be
527 // exported.
529
536 virtual bool canImport(ValueInfo VI) { return true; }
537
538 /// Import a declaration of the callee \p VI of a call edge requiring a
539 /// declaration import (see RequiresDeclImport in computeImportForFunction),
540 /// from a function in \p CallerModulePath that is defined in or being
541 /// imported into the current module, and isn't already defined in the
542 /// current module. This is called when the callee definition is not being
543 /// imported via that edge, and the callee summaries have not already been
544 /// qualified by selectCallee (see addRequiredDeclaration). If the
545 /// definition is (or is subsequently) imported via another edge, it takes
546 /// precedence over the declaration.
547 void importRequiredDeclaration(ValueInfo VI, StringRef CallerModulePath,
549
550 /// Import a declaration of the callee \p VI from the module containing
551 /// \p DeclSummary, which must be a candidate that is legal to import (i.e.
552 /// for which qualifyCalleeCandidates returned ImportFailureReason::None, as
553 /// is the case for the SummaryForDeclImport returned by selectCallee), and
554 /// mark it exported from that module. Does nothing if the callee definition
555 /// was already imported.
556 void addRequiredDeclaration(ValueInfo VI,
557 const GlobalValueSummary *DeclSummary,
559
560public:
561 virtual ~ModuleImportsManager() = default;
562
563 /// Values that must be exported from their defining modules because
564 /// declarations of them are required in importing modules.
568
569 /// Given the list of globals defined in a module, compute the list of imports
570 /// as well as the list of "exports", i.e. the list of symbols referenced from
571 /// another module (that may require promotion).
572 virtual void
573 computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
574 StringRef ModName,
576
577 static std::unique_ptr<ModuleImportsManager>
579 IsPrevailing,
580 const ModuleSummaryIndex &Index,
582 nullptr);
583};
584
585/// A ModuleImportsManager that operates based on a workload definition (see
586/// -thinlto-workload-def). For modules that do not define workload roots, it
587/// applies the base ModuleImportsManager import policy.
589 // Keep a module name -> value infos to import association. We use it to
590 // determine if a module's import list should be done by the base
591 // ModuleImportsManager or by us.
593 // Track the roots to avoid importing them due to other callers. We want there
594 // to be only one variant), for which we optimize according to the contextual
595 // profile. "Variants" refers to copies due to importing - we want there to be
596 // just one instance of this function.
598
599 void
600 computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
601 StringRef ModName,
602 FunctionImporter::ImportMapTy &ImportList) override {
603 StringRef Filename = ModName;
605 Filename = sys::path::filename(ModName);
606 // Drop the file extension.
607 Filename = Filename.substr(0, Filename.find_last_of('.'));
608 }
609 auto SetIter = Workloads.find(Filename);
610
611 if (SetIter == Workloads.end()) {
612 LLVM_DEBUG(dbgs() << "[Workload] " << ModName
613 << " does not contain the root of any context.\n");
614 return ModuleImportsManager::computeImportForModule(DefinedGVSummaries,
615 ModName, ImportList);
616 }
617 LLVM_DEBUG(dbgs() << "[Workload] " << ModName
618 << " contains the root(s) of context(s).\n");
619
620 GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
622 auto &ValueInfos = SetIter->second;
623 for (auto &VI : llvm::make_early_inc_range(ValueInfos)) {
624 auto It = DefinedGVSummaries.find(VI.getGUID());
625 if (It != DefinedGVSummaries.end() &&
626 IsPrevailing(VI.getGUID(), It->second)) {
628 dbgs() << "[Workload] " << VI.name()
629 << " has the prevailing variant already in the module "
630 << ModName << ". No need to import\n");
631 continue;
632 }
633 auto Candidates =
634 qualifyCalleeCandidates(Index, VI.getSummaryList(), ModName);
635
636 const GlobalValueSummary *GVS = nullptr;
637 auto PotentialCandidates = llvm::map_range(
639 Candidates,
640 [&](const auto &Candidate) {
641 LLVM_DEBUG(dbgs() << "[Workflow] Candidate for " << VI.name()
642 << " from " << Candidate.second->modulePath()
643 << " ImportFailureReason: "
644 << getFailureName(Candidate.first) << "\n");
645 return Candidate.first ==
647 }),
648 [](const auto &Candidate) { return Candidate.second; });
649 if (PotentialCandidates.empty()) {
650 LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
651 << " because can't find eligible Callee. Guid is: "
652 << VI.getGUID() << "\n");
653 continue;
654 }
655 /// We will prefer importing the prevailing candidate, if not, we'll
656 /// still pick the first available candidate. The reason we want to make
657 /// sure we do import the prevailing candidate is because the goal of
658 /// workload-awareness is to enable optimizations specializing the call
659 /// graph of that workload. Suppose a function is already defined in the
660 /// module, but it's not the prevailing variant. Suppose also we do not
661 /// inline it (in fact, if it were interposable, we can't inline it),
662 /// but we could specialize it to the workload in other ways. However,
663 /// the linker would drop it in the favor of the prevailing copy.
664 /// Instead, by importing the prevailing variant (assuming also the use
665 /// of `-avail-extern-to-local`), we keep the specialization. We could
666 /// alteranatively make the non-prevailing variant local, but the
667 /// prevailing one is also the one for which we would have previously
668 /// collected profiles, making it preferrable.
669 auto PrevailingCandidates = llvm::make_filter_range(
670 PotentialCandidates, [&](const auto *Candidate) {
671 return IsPrevailing(VI.getGUID(), Candidate);
672 });
673 if (PrevailingCandidates.empty()) {
674 GVS = *PotentialCandidates.begin();
675 if (!llvm::hasSingleElement(PotentialCandidates) &&
678 dbgs()
679 << "[Workload] Found multiple non-prevailing candidates for "
680 << VI.name()
681 << ". This is unexpected. Are module paths passed to the "
682 "compiler unique for the modules passed to the linker?");
683 // We could in theory have multiple (interposable) copies of a symbol
684 // when there is no prevailing candidate, if say the prevailing copy was
685 // in a native object being linked in. However, we should in theory be
686 // marking all of these non-prevailing IR copies dead in that case, in
687 // which case they won't be candidates.
688 assert(GVS->isLive());
689 } else {
690 assert(llvm::hasSingleElement(PrevailingCandidates));
691 GVS = *PrevailingCandidates.begin();
692 }
693
694 auto ExportingModule = GVS->modulePath();
695 // We checked that for the prevailing case, but if we happen to have for
696 // example an internal that's defined in this module, it'd have no
697 // PrevailingCandidates.
698 if (ExportingModule == ModName) {
699 LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
700 << " because its defining module is the same as the "
701 "current module\n");
702 continue;
703 }
704 LLVM_DEBUG(dbgs() << "[Workload][Including]" << VI.name() << " from "
705 << ExportingModule << " : " << VI.getGUID() << "\n");
706 ImportList.addDefinition(ExportingModule, VI.getGUID());
707 GVI.onImportingSummary(*GVS);
708 if (ExportLists)
709 (*ExportLists)[ExportingModule].insert(VI);
710 }
711 LLVM_DEBUG(dbgs() << "[Workload] Done\n");
712 }
713
714 void loadFromJson() {
715 // Since the workload def uses names, we need a quick lookup
716 // name->ValueInfo.
717 StringMap<ValueInfo> NameToValueInfo;
718 [[maybe_unused]] StringSet<> AmbiguousNames;
719 for (auto &I : Index) {
720 ValueInfo VI = Index.getValueInfo(I);
721 if (!NameToValueInfo.insert(std::make_pair(VI.name(), VI)).second)
722 LLVM_DEBUG(AmbiguousNames.insert(VI.name()));
723 }
724 auto DbgReportIfAmbiguous = [&](StringRef Name) {
725 LLVM_DEBUG(if (AmbiguousNames.count(Name) > 0) {
726 dbgs() << "[Workload] Function name " << Name
727 << " present in the workload definition is ambiguous. Consider "
728 "compiling with -funique-internal-linkage-names.";
729 });
730 };
731 std::error_code EC;
733 if (std::error_code EC = BufferOrErr.getError()) {
734 report_fatal_error("Failed to open context file");
735 return;
736 }
737 auto Buffer = std::move(BufferOrErr.get());
738 std::map<std::string, std::vector<std::string>> WorkloadDefs;
739 json::Path::Root NullRoot;
740 // The JSON is supposed to contain a dictionary matching the type of
741 // WorkloadDefs. For example:
742 // {
743 // "rootFunction_1": ["function_to_import_1", "function_to_import_2"],
744 // "rootFunction_2": ["function_to_import_3", "function_to_import_4"]
745 // }
746 auto Parsed = json::parse(Buffer->getBuffer());
747 if (!Parsed)
748 report_fatal_error(Parsed.takeError());
749 if (!json::fromJSON(*Parsed, WorkloadDefs, NullRoot))
750 report_fatal_error("Invalid thinlto contextual profile format.");
751 for (const auto &Workload : WorkloadDefs) {
752 const auto &Root = Workload.first;
753 DbgReportIfAmbiguous(Root);
754 LLVM_DEBUG(dbgs() << "[Workload] Root: " << Root << "\n");
755 const auto &AllCallees = Workload.second;
756 auto RootIt = NameToValueInfo.find(Root);
757 if (RootIt == NameToValueInfo.end()) {
758 LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
759 << " not found in this linkage unit.\n");
760 continue;
761 }
762 auto RootVI = RootIt->second;
763 if (RootVI.getSummaryList().size() != 1) {
764 LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
765 << " should have exactly one summary, but has "
766 << RootVI.getSummaryList().size() << ". Skipping.\n");
767 continue;
768 }
769 StringRef RootDefiningModule =
770 RootVI.getSummaryList().front()->modulePath();
771 LLVM_DEBUG(dbgs() << "[Workload] Root defining module for " << Root
772 << " is : " << RootDefiningModule << "\n");
773 auto &Set = Workloads[RootDefiningModule];
774 for (const auto &Callee : AllCallees) {
775 LLVM_DEBUG(dbgs() << "[Workload] " << Callee << "\n");
776 DbgReportIfAmbiguous(Callee);
777 auto ElemIt = NameToValueInfo.find(Callee);
778 if (ElemIt == NameToValueInfo.end()) {
779 LLVM_DEBUG(dbgs() << "[Workload] " << Callee << " not found\n");
780 continue;
781 }
782 Set.insert(ElemIt->second);
783 }
784 }
785 }
786
787 void loadFromCtxProf() {
788 std::error_code EC;
790 if (std::error_code EC = BufferOrErr.getError()) {
791 report_fatal_error("Failed to open contextual profile file");
792 return;
793 }
794 auto Buffer = std::move(BufferOrErr.get());
795
796 PGOCtxProfileReader Reader(Buffer->getBuffer());
797 auto Ctx = Reader.loadProfiles();
798 if (!Ctx) {
799 report_fatal_error("Failed to parse contextual profiles");
800 return;
801 }
802 const auto &CtxMap = Ctx->Contexts;
803 SetVector<GlobalValue::GUID> ContainedGUIDs;
804 for (const auto &[RootGuid, Root] : CtxMap) {
805 // Avoid ContainedGUIDs to get in/out of scope. Reuse its memory for
806 // subsequent roots, but clear its contents.
807 ContainedGUIDs.clear();
808
809 auto RootVI = Index.getValueInfo(RootGuid);
810 if (!RootVI) {
811 LLVM_DEBUG(dbgs() << "[Workload] Root " << RootGuid
812 << " not found in this linkage unit.\n");
813 continue;
814 }
815 if (RootVI.getSummaryList().size() != 1) {
816 LLVM_DEBUG(dbgs() << "[Workload] Root " << RootGuid
817 << " should have exactly one summary, but has "
818 << RootVI.getSummaryList().size() << ". Skipping.\n");
819 continue;
820 }
821 std::string RootDefiningModule =
822 RootVI.getSummaryList().front()->modulePath().str();
824 RootDefiningModule = std::to_string(RootGuid);
826 dbgs() << "[Workload] Moving " << RootGuid
827 << " to a module with the filename without extension : "
828 << RootDefiningModule << "\n");
829 } else {
830 LLVM_DEBUG(dbgs() << "[Workload] Root defining module for " << RootGuid
831 << " is : " << RootDefiningModule << "\n");
832 }
833 auto &Set = Workloads[RootDefiningModule];
834 Root.getContainedGuids(ContainedGUIDs);
835 Roots.insert(RootVI);
836 for (auto Guid : ContainedGUIDs)
837 if (auto VI = Index.getValueInfo(Guid))
838 Set.insert(VI);
839 }
840 }
841
842 bool canImport(ValueInfo VI) override { return !Roots.contains(VI); }
843
844public:
851 if (UseCtxProfile.empty() == WorkloadDefinitions.empty()) {
852 report_fatal_error(
853 "Pass only one of: -thinlto-pgo-ctx-prof or -thinlto-workload-def");
854 return;
855 }
856 if (!UseCtxProfile.empty())
857 loadFromCtxProf();
858 else
859 loadFromJson();
860 LLVM_DEBUG({
861 for (const auto &[Root, Set] : Workloads) {
862 dbgs() << "[Workload] Root: " << Root << " we have " << Set.size()
863 << " distinct callees.\n";
864 for (const auto &VI : Set) {
865 dbgs() << "[Workload] Root: " << Root
866 << " Would include: " << VI.getGUID() << "\n";
867 }
868 }
869 });
870 }
871};
872
873std::unique_ptr<ModuleImportsManager> ModuleImportsManager::create(
878 if (WorkloadDefinitions.empty() && UseCtxProfile.empty()) {
879 LLVM_DEBUG(dbgs() << "[Workload] Using the regular imports manager.\n");
880 return std::unique_ptr<ModuleImportsManager>(
882 }
883 LLVM_DEBUG(dbgs() << "[Workload] Using the contextual imports manager.\n");
884 return std::make_unique<WorkloadImportsManager>(IsPrevailing, Index,
886}
887
888static const char *
890 switch (Reason) {
892 return "None";
894 return "GlobalVar";
896 return "NotLive";
898 return "TooLarge";
900 return "InterposableLinkage";
902 return "LocalLinkageNotInModule";
904 return "NotEligible";
906 return "NoInline";
907 }
908 llvm_unreachable("invalid reason");
909}
910
911/// Compute the list of functions to import for a given caller. Mark these
912/// imported functions and the symbols they reference in their source module as
913/// exported from their source module.
914void ModuleImportsManager::computeImportForFunction(
915 const FunctionSummary &Summary, const unsigned Threshold,
916 const GVSummaryMapTy &DefinedGVSummaries,
917 SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
918 FunctionImporter::ImportMapTy &ImportList,
919 FunctionImporter::ImportThresholdsTy &ImportThresholds) {
920 GVImporter.onImportingSummary(Summary);
921 static int ImportCount = 0;
922 for (const auto &Edge : Summary.calls()) {
923 ValueInfo VI = Edge.first;
924 LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
925 << "\n");
926
927 // Whether at least a declaration of the callee must be imported (and the
928 // callee exported from its defining module) if its definition is not
929 // imported. This is the case when the edge was marked as requiring a
930 // declaration import (e.g. for MemProf ICP), or when declaration imports
931 // are enabled via -import-declaration for an indirect call edge, since the
932 // backend may then promote the indirect call to the imported declaration
933 // (e.g. regular ICP under -icp-allow-decls), which requires that the
934 // callee not be internalized. Callees of direct calls don't need to be
935 // exported here, since they are either referenced directly from the
936 // destination module, in which case they are already treated as visible
937 // outside their defining module, or from an imported definition, in which
938 // case they are marked exported in ComputeCrossModuleImport.
939 const bool RequiresDeclImport =
940 Edge.second.requiresDeclImport() ||
941 (ImportDeclaration && Edge.second.hasIndirectCall());
942
943 if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
944 LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
945 << " reached.\n");
946 // Still import a declaration if one is required, as that doesn't
947 // affect the import cutoff count.
948 if (RequiresDeclImport && !DefinedGVSummaries.count(VI.getGUID()))
949 importRequiredDeclaration(VI, Summary.modulePath(), ImportList);
950 continue;
951 }
952
953 if (DefinedGVSummaries.count(VI.getGUID())) {
954 // FIXME: Consider not skipping import if the module contains
955 // a non-prevailing def with interposable linkage. The prevailing copy
956 // can safely be imported (see shouldImportGlobal()).
957 LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
958 continue;
959 }
960
961 if (!canImport(VI)) {
963 dbgs() << "Skipping over " << VI.getGUID()
964 << " because its import is handled in a different module.");
965 assert(VI.getSummaryList().size() == 1 &&
966 "The root was expected to be an external symbol");
967 continue;
968 }
969
970 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
971 if (Hotness == CalleeInfo::HotnessType::Hot)
972 return ImportHotMultiplier;
973 if (Hotness == CalleeInfo::HotnessType::Cold)
977 return 1.0;
978 };
979
980 const auto NewThreshold =
981 Threshold * GetBonusMultiplier(Edge.second.getHotness());
982
983 auto IT = ImportThresholds.insert(std::make_pair(
984 VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
985 bool PreviouslyVisited = !IT.second;
986 auto &ProcessedThreshold = std::get<0>(IT.first->second);
987 auto &CalleeSummary = std::get<1>(IT.first->second);
988 auto &FailureInfo = std::get<2>(IT.first->second);
989
990 bool IsHotCallsite =
991 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
992 bool IsCriticalCallsite =
993 Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
994
995 const FunctionSummary *ResolvedCalleeSummary = nullptr;
996 if (CalleeSummary) {
997 assert(PreviouslyVisited);
998 // Since the traversal of the call graph is DFS, we can revisit a function
999 // a second time with a higher threshold. In this case, it is added back
1000 // to the worklist with the new threshold (so that its own callee chains
1001 // can be considered with the higher threshold).
1002 if (NewThreshold <= ProcessedThreshold) {
1003 LLVM_DEBUG(
1004 dbgs() << "ignored! Target was already imported with Threshold "
1005 << ProcessedThreshold << "\n");
1006 continue;
1007 }
1008 // Update with new larger threshold.
1009 ProcessedThreshold = NewThreshold;
1010 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
1011 } else {
1012 // If we already rejected importing a callee at the same or higher
1013 // threshold, don't waste time calling selectCallee.
1014 if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
1015 LLVM_DEBUG(
1016 dbgs() << "ignored! Target was already rejected with Threshold "
1017 << ProcessedThreshold << "\n");
1018 if (PrintImportFailures) {
1019 assert(FailureInfo &&
1020 "Expected FailureInfo for previously rejected candidate");
1021 FailureInfo->Attempts++;
1022 }
1023 // The callee definition was rejected when reached via a different
1024 // edge, but this edge may require that a declaration be imported and
1025 // exported.
1026 if (RequiresDeclImport)
1027 importRequiredDeclaration(VI, Summary.modulePath(), ImportList);
1028 continue;
1029 }
1030
1032
1033 // `SummaryForDeclImport` is an summary eligible for declaration import.
1034 const GlobalValueSummary *SummaryForDeclImport = nullptr;
1035 CalleeSummary =
1036 selectCallee(Index, VI.getSummaryList(), NewThreshold,
1037 Summary.modulePath(), SummaryForDeclImport, Reason);
1038 if (!CalleeSummary) {
1039 // There isn't a callee for definition import but one for declaration
1040 // import.
1041 if (SummaryForDeclImport) {
1042 if (RequiresDeclImport)
1043 // This also marks the callee exported.
1044 addRequiredDeclaration(VI, SummaryForDeclImport, ImportList);
1045 else if (ImportDeclaration)
1046 // Not exported, see the comments where RequiresDeclImport is set.
1047 ImportList.maybeAddDeclaration(SummaryForDeclImport->modulePath(),
1048 VI.getGUID());
1049 }
1050 // Update with new larger threshold if this was a retry (otherwise
1051 // we would have already inserted with NewThreshold above). Also
1052 // update failure info if requested.
1053 if (PreviouslyVisited) {
1054 ProcessedThreshold = NewThreshold;
1055 if (PrintImportFailures) {
1056 assert(FailureInfo &&
1057 "Expected FailureInfo for previously rejected candidate");
1058 FailureInfo->Reason = Reason;
1059 FailureInfo->Attempts++;
1060 FailureInfo->MaxHotness =
1061 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
1062 }
1063 } else if (PrintImportFailures) {
1064 assert(!FailureInfo &&
1065 "Expected no FailureInfo for newly rejected candidate");
1066 FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
1067 VI, Edge.second.getHotness(), Reason, 1);
1068 }
1069 if (ForceImportAll) {
1070 std::string Msg = std::string("Failed to import function ") +
1071 VI.name().str() + " due to " +
1072 getFailureName(Reason);
1075 logAllUnhandledErrors(std::move(Error), errs(),
1076 "Error importing module: ");
1077 break;
1078 } else {
1080 << "ignored! No qualifying callee with summary found.\n");
1081 continue;
1082 }
1083 }
1084
1085 // "Resolve" the summary
1086 CalleeSummary = CalleeSummary->getBaseObject();
1087 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
1088
1089 assert((ResolvedCalleeSummary->fflags().AlwaysInline || ForceImportAll ||
1090 (ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
1091 "selectCallee() didn't honor the threshold");
1092
1093 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
1094
1095 // Try emplace the definition entry, and update stats based on insertion
1096 // status.
1097 if (ImportList.addDefinition(ExportModulePath, VI.getGUID()) !=
1099 NumImportedFunctionsThinLink++;
1100 if (IsHotCallsite)
1101 NumImportedHotFunctionsThinLink++;
1102 if (IsCriticalCallsite)
1103 NumImportedCriticalFunctionsThinLink++;
1104 }
1105
1106 // Any calls/references made by this function will be marked exported
1107 // later, in ComputeCrossModuleImport, after import decisions are
1108 // complete, which is more efficient than adding them here.
1109 if (ExportLists)
1110 (*ExportLists)[ExportModulePath].insert(VI);
1111 }
1112
1113 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
1114 // Adjust the threshold for next level of imported functions.
1115 // The threshold is different for hot callsites because we can then
1116 // inline chains of hot calls.
1117 if (IsHotCallsite)
1118 return Threshold * ImportHotInstrFactor;
1119 return Threshold * ImportInstrFactor;
1120 };
1121
1122 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
1123
1124 ImportCount++;
1125
1126 // Insert the newly imported function to the worklist.
1127 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
1128 }
1129}
1130
1132 const GVSummaryMapTy &DefinedGVSummaries, StringRef ModName,
1133 FunctionImporter::ImportMapTy &ImportList) {
1134 // Worklist contains the list of function imported in this module, for which
1135 // we will analyse the callees and may import further down the callgraph.
1137 GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
1138 ExportLists);
1139 FunctionImporter::ImportThresholdsTy ImportThresholds;
1140
1141 // Populate the worklist with the import for the functions in the current
1142 // module
1143 for (const auto &GVSummary : DefinedGVSummaries) {
1144#ifndef NDEBUG
1145 // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
1146 // so this map look up (and possibly others) can be avoided.
1147 auto VI = Index.getValueInfo(GVSummary.first);
1148#endif
1149 if (!Index.isGlobalValueLive(GVSummary.second)) {
1150 LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
1151 continue;
1152 }
1153 auto *FuncSummary =
1154 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
1155 if (!FuncSummary)
1156 // Skip import for global variables
1157 continue;
1158 LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
1159 computeImportForFunction(*FuncSummary, ImportInstrLimit, DefinedGVSummaries,
1160 Worklist, GVI, ImportList, ImportThresholds);
1161 }
1162
1163 // Process the newly imported functions and add callees to the worklist.
1164 while (!Worklist.empty()) {
1165 auto GVInfo = Worklist.pop_back_val();
1166 auto *Summary = std::get<0>(GVInfo);
1167 auto Threshold = std::get<1>(GVInfo);
1168
1169 computeImportForFunction(*Summary, Threshold, DefinedGVSummaries, Worklist,
1170 GVI, ImportList, ImportThresholds);
1171 }
1172
1173 // Print stats about functions considered but rejected for importing
1174 // when requested.
1175 if (PrintImportFailures) {
1176 dbgs() << "Missed imports into module " << ModName << "\n";
1177 for (auto &I : ImportThresholds) {
1178 auto &ProcessedThreshold = std::get<0>(I.second);
1179 auto &CalleeSummary = std::get<1>(I.second);
1180 auto &FailureInfo = std::get<2>(I.second);
1181 if (CalleeSummary)
1182 continue; // We are going to import.
1183 assert(FailureInfo);
1184 FunctionSummary *FS = nullptr;
1185 if (!FailureInfo->VI.getSummaryList().empty())
1187 FailureInfo->VI.getSummaryList()[0]->getBaseObject());
1188 dbgs() << FailureInfo->VI
1189 << ": Reason = " << getFailureName(FailureInfo->Reason)
1190 << ", Threshold = " << ProcessedThreshold
1191 << ", Size = " << (FS ? (int)FS->instCount() : -1)
1192 << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
1193 << ", Attempts = " << FailureInfo->Attempts << "\n";
1194 }
1195 }
1196}
1197
1199 ValueInfo VI, StringRef CallerModulePath,
1200 FunctionImporter::ImportMapTy &ImportList) {
1201 // Find a callee summary that we can legally import a declaration of. Note
1202 // that qualifyCalleeCandidates only checks the legality of importing each
1203 // candidate (returning ImportFailureReason::None if legal). The additional
1204 // size and noinline checks that determine whether it is worth importing a
1205 // definition (TooLarge/NoInline) are applied separately by selectCallee, and
1206 // are not relevant for a declaration import.
1207 for (auto [Reason, CandidateSummary] :
1208 qualifyCalleeCandidates(Index, VI.getSummaryList(), CallerModulePath)) {
1211 "Expected only legality checks in qualifyCalleeCandidates");
1213 addRequiredDeclaration(VI, CandidateSummary, ImportList);
1214 return;
1215 }
1216 }
1217}
1218
1220 ValueInfo VI, const GlobalValueSummary *DeclSummary,
1221 FunctionImporter::ImportMapTy &ImportList) {
1222 StringRef SrcModule = DeclSummary->modulePath();
1223 auto ExistingImportType = ImportList.getImportType(SrcModule, VI.getGUID());
1224 // Nothing to do if we already decided to import the definition, which is
1225 // also exported.
1226 if (ExistingImportType == GlobalValueSummary::Definition)
1227 return;
1228 if (!ExistingImportType) {
1229 ImportList.maybeAddDeclaration(SrcModule, VI.getGUID());
1230 NumRequiredDeclsThinLink++;
1231 }
1232 // The declaration needs to be exported so that the callee is not
1233 // internalized, and so that locals are promoted. Note this is needed even if
1234 // we already decided to import the declaration for another reason (i.e.
1235 // -import-declaration for a direct call edge), as those declaration imports
1236 // are not exported.
1237 if (ExportLists)
1238 RequiredDeclExports[SrcModule].insert(VI);
1239}
1240
1241#ifndef NDEBUG
1242static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI) {
1243 auto SL = VI.getSummaryList();
1244 return SL.empty()
1245 ? false
1246 : SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
1247}
1248
1251 if (const auto &VI = Index.getValueInfo(G))
1252 return isGlobalVarSummary(Index, VI);
1253 return false;
1254}
1255
1256// Return the number of global variable summaries in ExportSet.
1257static unsigned
1259 FunctionImporter::ExportSetTy &ExportSet) {
1260 unsigned NumGVS = 0;
1261 for (auto &VI : ExportSet)
1262 if (isGlobalVarSummary(Index, VI.getGUID()))
1263 ++NumGVS;
1264 return NumGVS;
1265}
1266
1268 unsigned NumGVS = 0;
1269 unsigned DefinedFS = 0;
1270 unsigned Count = 0;
1271};
1272
1273// Compute import statistics for each source module in ImportList.
1276 const FunctionImporter::ImportMapTy &ImportList) {
1278
1279 for (const auto &[FromModule, GUID, Type] : ImportList) {
1280 ImportStatistics &Entry = Histogram[FromModule];
1281 ++Entry.Count;
1282 if (isGlobalVarSummary(Index, GUID))
1283 ++Entry.NumGVS;
1285 ++Entry.DefinedFS;
1286 }
1287 return Histogram;
1288}
1289#endif
1290
1291#ifndef NDEBUG
1293 const ModuleSummaryIndex &Index,
1296 DenseSet<GlobalValue::GUID> FlattenedImports;
1297
1298 for (const auto &ImportPerModule : ImportLists)
1299 for (const auto &[FromModule, GUID, ImportType] : ImportPerModule.second)
1300 FlattenedImports.insert(GUID);
1301
1302 // Checks that all GUIDs of read/writeonly vars we see in export lists
1303 // are also in the import lists. Otherwise we my face linker undefs,
1304 // because readonly and writeonly vars are internalized in their
1305 // source modules. The exception would be if it has a linkage type indicating
1306 // that there may have been a copy existing in the importing module (e.g.
1307 // linkonce_odr). In that case we cannot accurately do this checking.
1308 auto IsReadOrWriteOnlyVarNeedingImporting = [&](StringRef ModulePath,
1309 const ValueInfo &VI) {
1311 Index.findSummaryInModule(VI, ModulePath));
1312 return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS)) &&
1313 !(GVS->linkage() == GlobalValue::AvailableExternallyLinkage ||
1314 GVS->linkage() == GlobalValue::WeakODRLinkage ||
1315 GVS->linkage() == GlobalValue::LinkOnceODRLinkage);
1316 };
1317
1318 for (auto &ExportPerModule : ExportLists)
1319 for (auto &VI : ExportPerModule.second)
1320 if (!FlattenedImports.count(VI.getGUID()) &&
1321 IsReadOrWriteOnlyVarNeedingImporting(ExportPerModule.first, VI))
1322 return false;
1323
1324 return true;
1325}
1326#endif
1327
1328/// Compute all the import and export for every module using the Index.
1330 const ModuleSummaryIndex &Index,
1331 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1333 isPrevailing,
1336 auto MIS = ModuleImportsManager::create(isPrevailing, Index, &ExportLists);
1337 // For each module that has function defined, compute the import/export lists.
1338 for (const auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
1339 auto &ImportList = ImportLists[DefinedGVSummaries.first];
1340 LLVM_DEBUG(dbgs() << "Computing import for Module '"
1341 << DefinedGVSummaries.first << "'\n");
1342 MIS->computeImportForModule(DefinedGVSummaries.second,
1343 DefinedGVSummaries.first, ImportList);
1344 }
1345
1346 // When computing imports we only added the variables and functions being
1347 // imported to the export list. We also need to mark any references and calls
1348 // they make as exported as well. We do this here, as it is more efficient
1349 // since we may import the same values multiple times into different modules
1350 // during the import computation.
1351 for (auto &ELI : ExportLists) {
1352 // `NewExports` tracks the VI that gets exported because the full definition
1353 // of its user/referencer gets exported.
1355 const auto &DefinedGVSummaries =
1356 ModuleToDefinedGVSummaries.lookup(ELI.first);
1357 for (auto &EI : ELI.second) {
1358 // Find the copy defined in the exporting module so that we can mark the
1359 // values it references in that specific definition as exported.
1360 // Below we will add all references and called values, without regard to
1361 // whether they are also defined in this module. We subsequently prune the
1362 // list to only include those defined in the exporting module, see comment
1363 // there as to why.
1364 auto DS = DefinedGVSummaries.find(EI.getGUID());
1365 // Anything marked exported during the import computation must have been
1366 // defined in the exporting module.
1367 assert(DS != DefinedGVSummaries.end());
1368 auto *S = DS->getSecond();
1369 S = S->getBaseObject();
1370 if (auto *GVS = dyn_cast<GlobalVarSummary>(S)) {
1371 // Export referenced functions and variables. We don't export/promote
1372 // objects referenced by writeonly variable initializer, because
1373 // we convert such variables initializers to "zeroinitializer".
1374 // See processGlobalForThinLTO.
1375 if (!Index.isWriteOnly(GVS))
1376 NewExports.insert_range(GVS->refs());
1377 } else {
1378 auto *FS = cast<FunctionSummary>(S);
1379 NewExports.insert_range(llvm::make_first_range(FS->calls()));
1380 NewExports.insert_range(FS->refs());
1381 }
1382 }
1383 // Prune list computed above to only include values defined in the
1384 // exporting module. We do this after the above insertion since we may hit
1385 // the same ref/call target multiple times in above loop, and it is more
1386 // efficient to avoid a set lookup each time.
1387 NewExports.remove_if(
1388 [&](ValueInfo VI) { return !DefinedGVSummaries.count(VI.getGUID()); });
1389 ELI.second.insert_range(NewExports);
1390 }
1391
1392 // Now add the values exported because declarations of them are required in
1393 // importing modules. We do this after the above loop since their own
1394 // references and calls should not be exported.
1395 for (auto &[ModPath, RequiredExports] : MIS->requiredDeclExports())
1396 ExportLists[ModPath].insert_range(RequiredExports);
1397
1398 assert(checkVariableImport(Index, ImportLists, ExportLists));
1399#ifndef NDEBUG
1400 LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
1401 << " modules:\n");
1402 for (const auto &ModuleImports : ImportLists) {
1403 auto ModName = ModuleImports.first;
1404 auto &Exports = ExportLists[ModName];
1405 unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
1407 collectImportStatistics(Index, ModuleImports.second);
1408 LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
1409 << Exports.size() - NumGVS << " functions and " << NumGVS
1410 << " vars. Imports from " << Histogram.size()
1411 << " modules.\n");
1412 for (const auto &[SrcModName, Stats] : Histogram) {
1413 LLVM_DEBUG(dbgs() << " - " << Stats.DefinedFS
1414 << " function definitions and "
1415 << Stats.Count - Stats.NumGVS - Stats.DefinedFS
1416 << " function declarations imported from " << SrcModName
1417 << "\n");
1418 LLVM_DEBUG(dbgs() << " - " << Stats.NumGVS
1419 << " global vars imported from " << SrcModName << "\n");
1420 }
1421 }
1422#endif
1423}
1424
1425#ifndef NDEBUG
1427 StringRef ModulePath,
1428 FunctionImporter::ImportMapTy &ImportList) {
1430 collectImportStatistics(Index, ImportList);
1431 LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
1432 << Histogram.size() << " modules.\n");
1433 for (const auto &[SrcModName, Stats] : Histogram) {
1434 LLVM_DEBUG(dbgs() << " - " << Stats.DefinedFS
1435 << " function definitions and "
1436 << Stats.Count - Stats.DefinedFS - Stats.NumGVS
1437 << " function declarations imported from " << SrcModName
1438 << "\n");
1439 LLVM_DEBUG(dbgs() << " - " << Stats.NumGVS << " vars imported from "
1440 << SrcModName << "\n");
1441 }
1442}
1443#endif
1444
1445/// Compute all the imports for the given module using the Index.
1446///
1447/// \p isPrevailing is a callback that will be called with a global value's GUID
1448/// and summary and should return whether the module corresponding to the
1449/// summary contains the linker-prevailing copy of that value.
1450///
1451/// \p ImportList will be populated with a map that can be passed to
1452/// FunctionImporter::importFunctions() above (see description there).
1454 StringRef ModulePath,
1456 isPrevailing,
1457 const ModuleSummaryIndex &Index,
1458 FunctionImporter::ImportMapTy &ImportList) {
1459 // Collect the list of functions this module defines.
1460 // GUID -> Summary
1461 GVSummaryMapTy FunctionSummaryMap;
1462 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
1463
1464 // Compute the import list for this module.
1465 LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
1466 auto MIS = ModuleImportsManager::create(isPrevailing, Index);
1467 MIS->computeImportForModule(FunctionSummaryMap, ModulePath, ImportList);
1468
1469#ifndef NDEBUG
1470 dumpImportListForModule(Index, ModulePath, ImportList);
1471#endif
1472}
1473
1474/// Mark all external summaries in \p Index for import into the given module.
1475/// Used for testing the case of distributed builds using a distributed index.
1476///
1477/// \p ImportList will be populated with a map that can be passed to
1478/// FunctionImporter::importFunctions() above (see description there).
1480 StringRef ModulePath, const ModuleSummaryIndex &Index,
1481 FunctionImporter::ImportMapTy &ImportList) {
1482 for (const auto &GlobalList : Index) {
1483 // Ignore entries for undefined references.
1484 if (GlobalList.second.getSummaryList().empty())
1485 continue;
1486
1487 auto GUID = GlobalList.first;
1488 assert(GlobalList.second.getSummaryList().size() == 1 &&
1489 "Expected individual combined index to have one summary per GUID");
1490 auto &Summary = GlobalList.second.getSummaryList()[0];
1491 // Skip the summaries for the importing module. These are included to
1492 // e.g. record required linkage changes.
1493 if (Summary->modulePath() == ModulePath)
1494 continue;
1495 // Add an entry to provoke importing by thinBackend.
1496 ImportList.addGUID(Summary->modulePath(), GUID, Summary->importType());
1497 }
1498#ifndef NDEBUG
1499 dumpImportListForModule(Index, ModulePath, ImportList);
1500#endif
1501}
1502
1503// For SamplePGO, the indirect call targets for local functions will
1504// have its original name annotated in profile. We try to find the
1505// corresponding PGOFuncName as the GUID, and fix up the edges
1506// accordingly.
1508 FunctionSummary *FS) {
1509 // Returns the ValueInfo that should be used in place of \p CalleeVI, or an
1510 // empty ValueInfo if no update is needed.
1511 auto GetUpdatedCallee = [&](ValueInfo CalleeVI) -> ValueInfo {
1512 if (!CalleeVI || !CalleeVI.getSummaryList().empty())
1513 return ValueInfo();
1514 auto GUID = Index.getGUIDFromOriginalID(CalleeVI.getGUID());
1515 if (GUID == 0)
1516 return ValueInfo();
1517 auto VI = Index.getValueInfo(GUID);
1518 if (llvm::any_of(
1519 VI.getSummaryList(),
1520 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
1521 // The mapping from OriginalId to GUID may return a GUID
1522 // that corresponds to a static variable. Filter it out here.
1523 // This can happen when
1524 // 1) There is a call to a library function which is not defined
1525 // in the index.
1526 // 2) There is a static variable with the OriginalGUID identical
1527 // to the GUID of the library function in 1);
1528 // When this happens the static variable in 2) will be found,
1529 // which needs to be filtered out.
1530 return SummaryPtr->getSummaryKind() ==
1531 GlobalValueSummary::GlobalVarKind;
1532 }))
1533 return ValueInfo();
1534 return VI;
1535 };
1536
1537 for (auto &EI : FS->mutableCalls()) {
1538 // Update the edge to point directly to the correct GUID.
1539 if (auto VI = GetUpdatedCallee(EI.first))
1540 EI.first = VI;
1541 }
1542
1543 // MemProf summarizes indirect callsites by synthesizing a CallsiteInfo
1544 // record for each profiled target, using the same GUIDs found in the VP
1545 // metadata (which, for local targets, may be the original name GUID when
1546 // e.g. synthesized from the MemProf profile or from a SamplePGO profile).
1547 // Update those callees as well so that they are consistent with the call
1548 // edges above, and so that the thin link's MemProf context disambiguation
1549 // can correlate the callsite with the summary for the target function.
1550 if (FS->callsites().empty())
1551 return;
1552 for (auto &CI : FS->mutableCallsites()) {
1553 if (auto VI = GetUpdatedCallee(CI.Callee))
1554 CI.Callee = VI;
1555 }
1556}
1557
1559 for (const auto &Entry : Index) {
1560 for (const auto &S : Entry.second.getSummaryList()) {
1561 if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1563 }
1564 }
1565}
1566
1568 ModuleSummaryIndex &Index,
1569 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
1571 assert(!Index.withGlobalValueDeadStripping());
1572 if (!ComputeDead ||
1573 // Don't do anything when nothing is live, this is friendly with tests.
1574 GUIDPreservedSymbols.empty()) {
1575 // Still need to update indirect calls.
1576 updateIndirectCalls(Index);
1577 return;
1578 }
1579 unsigned LiveSymbols = 0;
1581 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
1582 for (auto GUID : GUIDPreservedSymbols) {
1583 ValueInfo VI = Index.getValueInfo(GUID);
1584 if (!VI)
1585 continue;
1586 for (const auto &S : VI.getSummaryList())
1587 S->setLive(true);
1588 }
1589
1590 // Add values flagged in the index as live roots to the worklist.
1591 for (const auto &Entry : Index) {
1592 auto VI = Index.getValueInfo(Entry);
1593 for (const auto &S : Entry.second.getSummaryList()) {
1594 if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1596 if (S->isLive()) {
1597 LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
1598 Worklist.push_back(VI);
1599 ++LiveSymbols;
1600 break;
1601 }
1602 }
1603 }
1604
1605 // Make value live and add it to the worklist if it was not live before.
1606 auto visit = [&](ValueInfo VI, bool IsAliasee) {
1607 // FIXME: If we knew which edges were created for indirect call profiles,
1608 // we could skip them here. Any that are live should be reached via
1609 // other edges, e.g. reference edges. Otherwise, using a profile collected
1610 // on a slightly different binary might provoke preserving, importing
1611 // and ultimately promoting calls to functions not linked into this
1612 // binary, which increases the binary size unnecessarily. Note that
1613 // if this code changes, the importer needs to change so that edges
1614 // to functions marked dead are skipped.
1615
1616 if (llvm::any_of(VI.getSummaryList(),
1617 [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
1618 return S->isLive();
1619 }))
1620 return;
1621
1622 // We only keep live symbols that are known to be non-prevailing if any are
1623 // available_externally, linkonceodr, weakodr. Those symbols are discarded
1624 // later in the EliminateAvailableExternally pass and setting them to
1625 // not-live could break downstreams users of liveness information (PR36483)
1626 // or limit optimization opportunities.
1627 if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
1628 bool KeepAliveLinkage = false;
1629 bool Interposable = false;
1630 for (const auto &S : VI.getSummaryList()) {
1631 if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
1632 S->linkage() == GlobalValue::WeakODRLinkage ||
1633 S->linkage() == GlobalValue::LinkOnceODRLinkage)
1634 KeepAliveLinkage = true;
1635 else if (GlobalValue::isInterposableLinkage(S->linkage()))
1636 Interposable = true;
1637 }
1638
1639 if (!IsAliasee) {
1640 if (!KeepAliveLinkage)
1641 return;
1642
1643 if (Interposable)
1645 "Interposable and available_externally/linkonce_odr/weak_odr "
1646 "symbol");
1647 }
1648 }
1649
1650 for (const auto &S : VI.getSummaryList())
1651 S->setLive(true);
1652 ++LiveSymbols;
1653 Worklist.push_back(VI);
1654 };
1655
1656 while (!Worklist.empty()) {
1657 auto VI = Worklist.pop_back_val();
1658 for (const auto &Summary : VI.getSummaryList()) {
1659 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
1660 // If this is an alias, visit the aliasee VI to ensure that all copies
1661 // are marked live and it is added to the worklist for further
1662 // processing of its references.
1663 visit(AS->getAliaseeVI(), true);
1664 continue;
1665 }
1666 for (auto Ref : Summary->refs())
1667 visit(Ref, false);
1668 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
1669 for (auto Call : FS->calls())
1670 visit(Call.first, false);
1671 }
1672 }
1673 Index.setWithGlobalValueDeadStripping();
1674
1675 unsigned DeadSymbols = Index.size() - LiveSymbols;
1676 LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
1677 << " symbols Dead \n");
1678 NumDeadSymbols += DeadSymbols;
1679 NumLiveSymbols += LiveSymbols;
1680}
1681
1682// Compute dead symbols and propagate constants in combined index.
1684 ModuleSummaryIndex &Index,
1685 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
1687 bool ImportEnabled) {
1688 llvm::TimeTraceScope timeScope("Drop dead symbols and propagate attributes");
1689 computeDeadSymbolsAndUpdateIndirectCalls(Index, GUIDPreservedSymbols,
1690 isPrevailing);
1691 if (ImportEnabled)
1692 Index.propagateAttributes(GUIDPreservedSymbols);
1693}
1694
1695/// Compute the set of summaries needed for a ThinLTO backend compilation of
1696/// \p ModulePath.
1698 StringRef ModulePath,
1699 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1700 const FunctionImporter::ImportMapTy &ImportList,
1701 ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
1702 GVSummaryPtrSet &DecSummaries) {
1703 // Include all summaries from the importing module.
1704 ModuleToSummariesForIndex[std::string(ModulePath)] =
1705 ModuleToDefinedGVSummaries.lookup(ModulePath);
1706
1707 // Forward port the heterogeneous std::map::operator[]() from C++26, which
1708 // lets us look up the map without allocating an instance of std::string when
1709 // the key-value pair exists in the map.
1710 // TODO: Remove this in favor of the heterogenous std::map::operator[]() from
1711 // C++26 when it becomes available for our codebase.
1712 auto LookupOrCreate = [](ModuleToSummariesForIndexTy &Map,
1714 auto It = Map.find(Key);
1715 if (It == Map.end())
1716 std::tie(It, std::ignore) =
1717 Map.try_emplace(std::string(Key), GVSummaryMapTy());
1718 return It->second;
1719 };
1720
1721 // Include summaries for imports.
1722 for (const auto &[FromModule, GUID, ImportType] : ImportList) {
1723 auto &SummariesForIndex =
1724 LookupOrCreate(ModuleToSummariesForIndex, FromModule);
1725
1726 const auto &DefinedGVSummaries = ModuleToDefinedGVSummaries.at(FromModule);
1727 const auto &DS = DefinedGVSummaries.find(GUID);
1728 assert(DS != DefinedGVSummaries.end() &&
1729 "Expected a defined summary for imported global value");
1730 if (ImportType == GlobalValueSummary::Declaration)
1731 DecSummaries.insert(DS->second);
1732
1733 SummariesForIndex[GUID] = DS->second;
1734 }
1735
1736 // When AlwaysRenamePromotedLocals is false, for each source module we import
1737 // from, also include summaries for local functions that have
1738 // NoRenameOnPromotion set. This is needed for distributed ThinLTO. Otherwise,
1739 // the local function of the source module will keep its origin name, e.g.,
1740 // foo() while the function in destination module will have name
1741 // foo.llvm.<...>() and this will cause a link failure.
1742 //
1743 // Note: this imports a superset of the necessary declarations — all locals
1744 // with NoRenameOnPromotion in each source module, not just those referenced
1745 // by the importing module. Computing the precise set would require walking
1746 // the summary reference graph from each imported function, which is more
1747 // expensive than the simple scan here.
1749 for (auto &[ModPath, SummariesForIndex] : ModuleToSummariesForIndex) {
1750 if (ModPath == ModulePath)
1751 continue;
1752 auto It = ModuleToDefinedGVSummaries.find(ModPath);
1753 if (It == ModuleToDefinedGVSummaries.end())
1754 continue;
1755 for (const auto &[GUID, Summary] : It->second) {
1756 if (Summary->noRenameOnPromotion()) {
1757 DecSummaries.insert(Summary);
1758 SummariesForIndex.try_emplace(GUID, Summary);
1759 }
1760 }
1761 }
1762 }
1763}
1764
1765/// Emit the files \p ModulePath will import from into \p OutputFilename.
1768 const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex) {
1769 std::error_code EC;
1771 if (EC)
1772 return createFileError("cannot open " + OutputFilename,
1773 errorCodeToError(EC));
1774 processImportsFiles(ModulePath, ModuleToSummariesForIndex,
1775 [&](StringRef M) { ImportsOS << M << "\n"; });
1776 return Error::success();
1777}
1778
1779/// Invoke callback \p F on the file paths from which \p ModulePath
1780/// will import.
1782 StringRef ModulePath,
1783 const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
1784 function_ref<void(const std::string &)> F) {
1785 for (const auto &ILI : ModuleToSummariesForIndex)
1786 // The ModuleToSummariesForIndex map includes an entry for the current
1787 // Module (needed for writing out the index files). We don't want to
1788 // include it in the imports file, however, so filter it out.
1789 if (ILI.first != ModulePath)
1790 F(ILI.first);
1791}
1792
1794 LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
1795 << "\n");
1796 MDNode *UniqueID = nullptr;
1797 if (auto *GO = dyn_cast<GlobalObject>(&GV))
1798 UniqueID = GO->getMetadata(LLVMContext::MD_guid);
1799
1800 if (Function *F = dyn_cast<Function>(&GV)) {
1801 F->deleteBody();
1802 F->clearMetadata();
1803 if (UniqueID)
1804 F->setMetadata(LLVMContext::MD_guid, UniqueID);
1805 F->setComdat(nullptr);
1806 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
1807 V->setInitializer(nullptr);
1808 V->setLinkage(GlobalValue::ExternalLinkage);
1809 V->clearMetadata();
1810 if (UniqueID)
1811 V->setMetadata(LLVMContext::MD_guid, UniqueID);
1812 V->setComdat(nullptr);
1813 } else {
1814 GlobalValue *NewGV;
1815 if (GV.getValueType()->isFunctionTy())
1816 NewGV =
1819 "", GV.getParent());
1820 else
1821 NewGV =
1822 new GlobalVariable(*GV.getParent(), GV.getValueType(),
1823 /*isConstant*/ false, GlobalValue::ExternalLinkage,
1824 /*init*/ nullptr, "",
1825 /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
1826 GV.getType()->getAddressSpace());
1827 NewGV->takeName(&GV);
1828 GV.replaceAllUsesWith(NewGV);
1829 return false;
1830 }
1831 if (!GV.isImplicitDSOLocal())
1832 GV.setDSOLocal(false);
1833 return true;
1834}
1835
1837 const GVSummaryMapTy &DefinedGlobals,
1838 bool PropagateAttrs) {
1839 llvm::TimeTraceScope timeScope("ThinLTO finalize in module");
1840 DenseSet<Comdat *> NonPrevailingComdats;
1841 auto FinalizeInModule = [&](GlobalValue &GV, bool Propagate = false) {
1842 // See if the global summary analysis computed a new resolved linkage.
1843 const auto &GS = DefinedGlobals.find(GV.getGUIDOrFallback());
1844 if (GS == DefinedGlobals.end())
1845 return;
1846
1847 if (Propagate)
1848 if (FunctionSummary *FS = dyn_cast<FunctionSummary>(GS->second)) {
1849 if (Function *F = dyn_cast<Function>(&GV)) {
1850 // TODO: propagate ReadNone and ReadOnly.
1851 if (FS->fflags().ReadNone && !F->doesNotAccessMemory())
1852 F->setDoesNotAccessMemory();
1853
1854 if (FS->fflags().ReadOnly && !F->onlyReadsMemory())
1855 F->setOnlyReadsMemory();
1856
1857 if (FS->fflags().NoRecurse && !F->doesNotRecurse())
1858 F->setDoesNotRecurse();
1859
1860 if (FS->fflags().NoUnwind && !F->doesNotThrow())
1861 F->setDoesNotThrow();
1862 }
1863 }
1864
1865 auto NewLinkage = GS->second->linkage();
1867 // Don't internalize anything here, because the code below
1868 // lacks necessary correctness checks. Leave this job to
1869 // LLVM 'internalize' pass.
1870 GlobalValue::isLocalLinkage(NewLinkage) ||
1871 // In case it was dead and already converted to declaration.
1872 GV.isDeclaration())
1873 return;
1874
1875 // Set the potentially more constraining visibility computed from summaries.
1876 // The DefaultVisibility condition is because older GlobalValueSummary does
1877 // not record DefaultVisibility and we don't want to change protected/hidden
1878 // to default.
1879 if (GS->second->getVisibility() != GlobalValue::DefaultVisibility)
1880 GV.setVisibility(GS->second->getVisibility());
1881
1882 if (NewLinkage == GV.getLinkage())
1883 return;
1884
1885 // Check for a non-prevailing def that has interposable linkage
1886 // (e.g. non-odr weak or linkonce). In that case we can't simply
1887 // convert to available_externally, since it would lose the
1888 // interposable property and possibly get inlined. Simply drop
1889 // the definition in that case.
1892 if (!convertToDeclaration(GV))
1893 // FIXME: Change this to collect replaced GVs and later erase
1894 // them from the parent module once thinLTOResolvePrevailingGUID is
1895 // changed to enable this for aliases.
1896 llvm_unreachable("Expected GV to be converted");
1897 } else {
1898 // If all copies of the original symbol had global unnamed addr and
1899 // linkonce_odr linkage, or if all of them had local unnamed addr linkage
1900 // and are constants, then it should be an auto hide symbol. In that case
1901 // the thin link would have marked it as CanAutoHide. Add hidden
1902 // visibility to the symbol to preserve the property.
1903 if (NewLinkage == GlobalValue::WeakODRLinkage &&
1904 GS->second->canAutoHide()) {
1907 }
1908
1909 LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
1910 << "` from " << GV.getLinkage() << " to " << NewLinkage
1911 << "\n");
1912 GV.setLinkage(NewLinkage);
1913 }
1914 // Remove declarations from comdats, including available_externally
1915 // as this is a declaration for the linker, and will be dropped eventually.
1916 // It is illegal for comdats to contain declarations.
1917 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
1918 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
1919 if (GO->getComdat()->getName() == GO->getName())
1920 NonPrevailingComdats.insert(GO->getComdat());
1921 GO->setComdat(nullptr);
1922 }
1923 };
1924
1925 // Process functions and global now
1926 for (auto &GV : TheModule)
1927 FinalizeInModule(GV, PropagateAttrs);
1928 for (auto &GV : TheModule.globals())
1929 FinalizeInModule(GV);
1930 for (auto &GV : TheModule.aliases())
1931 FinalizeInModule(GV);
1932
1933 // For a non-prevailing comdat, all its members must be available_externally.
1934 // FinalizeInModule has handled non-local-linkage GlobalValues. Here we handle
1935 // local linkage GlobalValues.
1936 if (NonPrevailingComdats.empty())
1937 return;
1938 for (auto &GO : TheModule.global_objects()) {
1939 if (auto *C = GO.getComdat(); C && NonPrevailingComdats.count(C)) {
1940 GO.setComdat(nullptr);
1942 }
1943 }
1944 bool Changed;
1945 do {
1946 Changed = false;
1947 // If an alias references a GlobalValue in a non-prevailing comdat, change
1948 // it to available_externally. For simplicity we only handle GlobalValue and
1949 // ConstantExpr with a base object. ConstantExpr without a base object is
1950 // unlikely used in a COMDAT.
1951 for (auto &GA : TheModule.aliases()) {
1952 if (GA.hasAvailableExternallyLinkage())
1953 continue;
1954 GlobalObject *Obj = GA.getAliaseeObject();
1955 assert(Obj && "aliasee without an base object is unimplemented");
1956 if (Obj->hasAvailableExternallyLinkage()) {
1958 Changed = true;
1959 }
1960 }
1961 } while (Changed);
1962}
1963
1964/// Run internalization on \p TheModule based on symmary analysis.
1966 const GVSummaryMapTy &DefinedGlobals) {
1967 llvm::TimeTraceScope timeScope("ThinLTO internalize module");
1968 // Declare a callback for the internalize pass that will ask for every
1969 // candidate GlobalValue if it can be internalized or not.
1970 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
1971 // It may be the case that GV is on a chain of an ifunc, its alias and
1972 // subsequent aliases. In this case, the summary for the value is not
1973 // available.
1974 if (isa<GlobalIFunc>(&GV) ||
1975 (isa<GlobalAlias>(&GV) &&
1976 isa<GlobalIFunc>(cast<GlobalAlias>(&GV)->getAliaseeObject())))
1977 return true;
1978
1979 // Lookup the linkage recorded in the summaries during global analysis.
1980 auto GS = DefinedGlobals.find(GV.getGUIDOrFallback());
1981 if (GS == DefinedGlobals.end()) {
1982 // Must have been promoted (possibly conservatively). Find original
1983 // name so that we can access the correct summary and see if it can
1984 // be internalized again.
1985 // FIXME: Eventually we should control promotion instead of promoting
1986 // and internalizing again.
1987 StringRef OrigName =
1989 std::string OrigId = GlobalValue::getGlobalIdentifier(
1991 TheModule.getSourceFileName());
1992 GS = DefinedGlobals.find(
1994 if (GS == DefinedGlobals.end()) {
1995 // Also check the original non-promoted non-globalized name. In some
1996 // cases a preempted weak value is linked in as a local copy because
1997 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
1998 // In that case, since it was originally not a local value, it was
1999 // recorded in the index using the original name.
2000 // FIXME: This may not be needed once PR27866 is fixed.
2001 GS = DefinedGlobals.find(
2003 assert(GS != DefinedGlobals.end());
2004 }
2005 }
2006 return !GlobalValue::isLocalLinkage(GS->second->linkage());
2007 };
2008
2009 // FIXME: See if we can just internalize directly here via linkage changes
2010 // based on the index, rather than invoking internalizeModule.
2011 internalizeModule(TheModule, MustPreserveGV);
2012}
2013
2014/// Make alias a clone of its aliasee.
2017
2018 ValueToValueMapTy VMap;
2019 Function *NewFn = CloneFunction(Fn, VMap);
2020 // Clone should use the original alias's linkage, visibility and name, and we
2021 // ensure all uses of alias instead use the new clone (casted if necessary).
2022 NewFn->setLinkage(GA->getLinkage());
2023 NewFn->setVisibility(GA->getVisibility());
2024 GA->replaceAllUsesWith(NewFn);
2025 NewFn->takeName(GA);
2026 return NewFn;
2027}
2028
2029// Internalize values that we marked with specific attribute
2030// in processGlobalForThinLTO.
2032 for (auto &GV : M.globals())
2033 // Skip GVs which have been converted to declarations
2034 // by dropDeadSymbols.
2035 if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
2036 GV.setLinkage(GlobalValue::InternalLinkage);
2037 GV.setVisibility(GlobalValue::DefaultVisibility);
2038 }
2039}
2040
2041/// When a function carrying !implicit.ref is imported via ThinLTO, the
2042/// referenced global arrives as available_externally. This string can be dead
2043/// code eliminated since it has no IR uses -- only metadata references. Adding
2044/// it to llvm.compiler.used prevents elimination.
2048 for (Function &F : M) {
2049 if (!F.hasAvailableExternallyLinkage() ||
2050 !F.hasMetadata(LLVMContext::MD_implicit_ref))
2051 continue;
2053 F.getMetadata(LLVMContext::MD_implicit_ref, MDs);
2054 for (MDNode *MD : MDs) {
2055 auto *Op = MD->getOperand(0).get();
2056 if (!Op)
2057 continue;
2058 if (auto *VAM = dyn_cast<ValueAsMetadata>(Op))
2059 if (auto *GV = dyn_cast<GlobalVariable>(VAM->getValue()))
2060 if (GV->hasAvailableExternallyLinkage() && Seen.insert(GV).second)
2061 ToProtect.push_back(GV);
2062 }
2063 }
2064 if (!ToProtect.empty())
2065 appendToCompilerUsed(M, ToProtect);
2066}
2067
2068// Automatically import functions in Module \p DestModule based on the summaries
2069// index.
2071 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
2072 const IPOOptions &Opts = getIPOOptions(DestModule);
2073 LLVM_DEBUG(dbgs() << "Starting import for Module "
2074 << DestModule.getModuleIdentifier() << "\n");
2075 unsigned ImportedCount = 0, ImportedGVCount = 0;
2076 // Before carrying out any imports, see if this module defines functions in
2077 // MoveSymbolGUID. If it does, delete them here (but leave the declaration).
2078 // The function will be imported elsewhere, as extenal linkage, and the
2079 // destination doesn't yet have its definition.
2080 DenseSet<GlobalValue::GUID> MoveSymbolGUIDSet;
2081 MoveSymbolGUIDSet.insert_range(MoveSymbolGUID);
2082 for (auto &F : DestModule)
2083 if (!F.isDeclaration() && MoveSymbolGUIDSet.contains(F.getGUIDOrFallback()))
2084 F.deleteBody();
2085
2086 IRMover Mover(DestModule);
2087
2088 // Do the actual import of functions now, one Module at a time
2089 for (const auto &ModName : ImportList.getSourceModules()) {
2090 llvm::TimeTraceScope timeScope("Import", ModName);
2091 // Get the module for the import
2092 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(ModName);
2093 if (!SrcModuleOrErr)
2094 return SrcModuleOrErr.takeError();
2095 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
2096 assert(&DestModule.getContext() == &SrcModule->getContext() &&
2097 "Context mismatch");
2098
2099 // If modules were created with lazy metadata loading, materialize it
2100 // now, before linking it (otherwise this will be a noop).
2101 if (Error Err = SrcModule->materializeMetadata())
2102 return std::move(Err);
2103
2104 // Find the globals to import
2105 SetVector<GlobalValue *> GlobalsToImport;
2106 // Functions (or aliases of functions) to import as declarations, along
2107 // with their GUIDs.
2109 {
2110 llvm::TimeTraceScope functionsScope("Functions");
2111 for (Function &F : *SrcModule) {
2112 if (!F.hasName())
2113 continue;
2114 auto GUID = F.getGUIDOrFallback();
2115 auto MaybeImportType = ImportList.getImportType(ModName, GUID);
2116 bool ImportDefinition =
2117 MaybeImportType == GlobalValueSummary::Definition;
2118
2119 LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
2120 << " importing function"
2121 << (ImportDefinition
2122 ? " definition "
2123 : (MaybeImportType ? " declaration " : " "))
2124 << GUID << " " << F.getName() << " from "
2125 << SrcModule->getSourceFileName() << "\n");
2126 if (ImportDefinition) {
2127 if (Error Err = F.materialize())
2128 return std::move(Err);
2129 // MemProf should match function's definition and summary,
2130 // 'thinlto_src_module' is needed.
2131 if (Opts.enable_import_metadata ||
2133 // Add 'thinlto_src_module' and 'thinlto_src_file' metadata for
2134 // statistics and debugging.
2135 F.setMetadata(
2136 "thinlto_src_module",
2137 MDNode::get(DestModule.getContext(),
2138 {MDString::get(DestModule.getContext(),
2139 SrcModule->getModuleIdentifier())}));
2140 F.setMetadata(
2141 "thinlto_src_file",
2142 MDNode::get(DestModule.getContext(),
2143 {MDString::get(DestModule.getContext(),
2144 SrcModule->getSourceFileName())}));
2145 }
2146 GlobalsToImport.insert(&F);
2147 } else if (MaybeImportType) {
2148 assert(*MaybeImportType == GlobalValueSummary::Declaration);
2149 DeclsToImport.push_back({&F, GUID});
2150 }
2151 }
2152 }
2153 {
2154 llvm::TimeTraceScope globalsScope("Globals");
2155 for (GlobalVariable &GV : SrcModule->globals()) {
2156 if (!GV.hasName())
2157 continue;
2158 auto GUID = GV.getGUIDOrFallback();
2159 auto MaybeImportType = ImportList.getImportType(ModName, GUID);
2160 bool ImportDefinition =
2161 MaybeImportType == GlobalValueSummary::Definition;
2162
2163 LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
2164 << " importing global"
2165 << (ImportDefinition
2166 ? " definition "
2167 : (MaybeImportType ? " declaration " : " "))
2168 << GUID << " " << GV.getName() << " from "
2169 << SrcModule->getSourceFileName() << "\n");
2170 if (ImportDefinition) {
2171 if (Error Err = GV.materialize())
2172 return std::move(Err);
2173 ImportedGVCount += GlobalsToImport.insert(&GV);
2174 }
2175 }
2176 }
2177 {
2178 llvm::TimeTraceScope aliasesScope("Aliases");
2179 for (GlobalAlias &GA : SrcModule->aliases()) {
2180 if (!GA.hasName() || isa<GlobalIFunc>(GA.getAliaseeObject()))
2181 continue;
2182 auto GUID = GA.getGUIDOrFallback();
2183 auto MaybeImportType = ImportList.getImportType(ModName, GUID);
2184 bool ImportDefinition =
2185 MaybeImportType == GlobalValueSummary::Definition;
2186
2187 LLVM_DEBUG(dbgs() << (MaybeImportType ? "Is" : "Not")
2188 << " importing alias"
2189 << (ImportDefinition
2190 ? " definition "
2191 : (MaybeImportType ? " declaration " : " "))
2192 << GUID << " " << GA.getName() << " from "
2193 << SrcModule->getSourceFileName() << "\n");
2194 if (ImportDefinition) {
2195 if (Error Err = GA.materialize())
2196 return std::move(Err);
2197 // Import alias as a copy of its aliasee.
2198 GlobalObject *GO = GA.getAliaseeObject();
2199 if (Error Err = GO->materialize())
2200 return std::move(Err);
2201 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
2202 assert(Fn);
2203 (void)Fn;
2205 << "Is importing aliasee fn " << GO->getGUIDOrFallback()
2206 << " " << GO->getName() << " from "
2207 << SrcModule->getSourceFileName() << "\n");
2208 if (Opts.enable_import_metadata ||
2210 // Add 'thinlto_src_module', 'thinlto_src_file', and
2211 // 'thinlto_alias_guid' metadata for statistics, debugging, and
2212 // summary lookup (since Fn retains the aliasee's !guid metadata).
2213 LLVMContext &Ctx = DestModule.getContext();
2214 Fn->setMetadata(
2215 "thinlto_src_module",
2217 Ctx, SrcModule->getModuleIdentifier())}));
2218 Fn->setMetadata(
2219 "thinlto_src_file",
2221 Ctx, {MDString::get(Ctx, SrcModule->getSourceFileName())}));
2222 Fn->setMetadata(
2223 "thinlto_alias_guid",
2224 MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(
2225 Type::getInt64Ty(Ctx), GUID))}));
2226 }
2227 GlobalsToImport.insert(Fn);
2228 } else if (MaybeImportType) {
2229 assert(*MaybeImportType == GlobalValueSummary::Declaration);
2230 if (isa<FunctionType>(GA.getValueType()))
2231 DeclsToImport.push_back({&GA, GUID});
2232 }
2233 }
2234 }
2235
2236 // Upgrade debug info after we're done materializing all the globals and we
2237 // have loaded all the required metadata!
2238 UpgradeDebugInfo(*SrcModule);
2239
2240 // Set the partial sample profile ratio in the profile summary module flag
2241 // of the imported source module, if applicable, so that the profile summary
2242 // module flag will match with that of the destination module when it's
2243 // imported.
2244 SrcModule->setPartialSampleProfileRatio(Index);
2245
2246 // Link in the specified functions.
2247 renameModuleForThinLTO(*SrcModule, Index, ClearDSOLocalOnDeclarations,
2248 &GlobalsToImport);
2249
2250 // Record the information needed to create the declarations to import,
2251 // after any promotion and renaming above, since the source module is
2252 // consumed by the IRMover below.
2253 struct DeclInfo {
2254 std::string Name;
2255 FunctionType *Ty;
2256 unsigned AddrSpace;
2258 AttributeList Attrs;
2260 bool DSOLocal;
2261 GlobalValue::GUID GUID;
2262 };
2263 SmallVector<DeclInfo> DeclInfos;
2264 for (auto [GV, GUID] : DeclsToImport) {
2265 assert(!GV->hasLocalLinkage() &&
2266 "Expected imported declaration to be promoted");
2267 const Function *F = dyn_cast<Function>(GV);
2268 if (!F)
2270 cast<GlobalAlias>(GV)->getAliaseeObject());
2271 if (!F)
2272 continue;
2273 DeclInfos.push_back({GV->getName().str(), F->getFunctionType(),
2274 F->getAddressSpace(), F->getCallingConv(),
2275 F->getAttributes(), GV->getVisibility(),
2276 GV->isDSOLocal(), GUID});
2277 }
2278
2279 if (Opts.print_imports) {
2280 for (const auto *GV : GlobalsToImport)
2281 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
2282 << " from " << SrcModule->getSourceFileName() << "\n";
2283 }
2284
2285 if (Error Err = Mover.move(std::move(SrcModule),
2286 GlobalsToImport.getArrayRef(), nullptr,
2287 /*IsPerformingImport=*/true))
2289 Twine("Function Import: link error: ") +
2290 toString(std::move(Err)));
2291
2292 ImportedCount += GlobalsToImport.size();
2293 NumImportedModules++;
2294
2295 // Now create the declarations to import, if they don't already exist in
2296 // the destination module. Declarations of direct callees will typically
2297 // already exist, either because the call is in the destination module or
2298 // because the IRMover created them when linking an imported definition
2299 // that references them. Callees reached only via indirect calls (e.g.
2300 // from value profile or MemProf call edges in the summary) have no such IR
2301 // reference, so this is mainly where declarations of those are created.
2302 //
2303 // We create these declarations by hand rather than via the IRMover: the
2304 // IRMover only creates declarations as a side effect of mapping references
2305 // from linked IR, it creates attribute-less declarations for aliases, and
2306 // it does not copy metadata from source definitions.
2307 for (auto &DI : DeclInfos) {
2308 if (DestModule.getNamedValue(DI.Name))
2309 continue;
2311 DI.AddrSpace, DI.Name, &DestModule);
2312 F->setCallingConv(DI.CC);
2313 F->setAttributes(DI.Attrs);
2314 // Note that the visibility must be set before dso_local, since
2315 // setDSOLocal(false) is not allowed on an implicitly dso_local value.
2316 F->setVisibility(DI.Visibility);
2317 F->setDSOLocal(DI.DSOLocal);
2318 // Record the GUID of the original value, which may differ from the GUID
2319 // computed from the current name if it was a promoted local. This allows
2320 // the declaration to be located via the GUID, e.g. by MemProf ICP.
2321 F->setMetadata(LLVMContext::MD_guid,
2322 MDNode::get(DestModule.getContext(),
2323 {ConstantAsMetadata::get(ConstantInt::get(
2324 Type::getInt64Ty(DestModule.getContext()),
2325 DI.GUID))}));
2326 NumImportedFunctionDecls++;
2327 }
2328 }
2329
2330 internalizeGVsAfterImport(DestModule);
2331
2332 // Protect !implicit.ref-referenced globals imported as available_externally
2333 // from DCE'd. Only needed when globals were actually imported.
2334 if (ImportedGVCount > 0)
2335 protectImplicitRefGlobals(DestModule);
2336
2337 NumImportedFunctions += (ImportedCount - ImportedGVCount);
2338 NumImportedGlobalVars += ImportedGVCount;
2339
2340 // TODO: Print counters for definitions and declarations in the debugging log.
2341 LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
2342 << " functions for Module "
2343 << DestModule.getModuleIdentifier() << "\n");
2344 LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
2345 << " global variables for Module "
2346 << DestModule.getModuleIdentifier() << "\n");
2347 return ImportedCount;
2348}
2349
2352 isPrevailing) {
2353 const IPOOptions &Opts = getIPOOptions(M);
2354 if (Opts.summary_file.empty())
2355 report_fatal_error("error: -function-import requires -summary-file\n");
2357 getModuleSummaryIndexForFile(Opts.summary_file);
2358 if (!IndexPtrOrErr) {
2359 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
2360 "Error loading file '" + Opts.summary_file + "': ");
2361 return false;
2362 }
2363 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
2364
2365 // First step is collecting the import list.
2367 FunctionImporter::ImportMapTy ImportList(ImportIDs);
2368 // If requested, simply import all functions in the index. This is used
2369 // when testing distributed backend handling via the opt tool, when
2370 // we have distributed indexes containing exactly the summaries to import.
2371 if (Opts.import_all_index)
2373 *Index, ImportList);
2374 else
2375 ComputeCrossModuleImportForModuleForTest(M.getModuleIdentifier(),
2376 isPrevailing, *Index, ImportList);
2377
2378 // Conservatively mark all internal values as promoted. This interface is
2379 // only used when doing importing via the function importing pass. The pass
2380 // is only enabled when testing importing via the 'opt' tool, which does
2381 // not do the ThinLink that would normally determine what values to promote.
2382 for (auto &I : *Index) {
2383 for (auto &S : I.second.getSummaryList()) {
2384 if (GlobalValue::isLocalLinkage(S->linkage()))
2385 S->setExternalLinkageForTest();
2386 }
2387 }
2388
2389 // Next we need to promote to global scope and rename any local values that
2390 // are potentially exported to other modules.
2391 renameModuleForThinLTO(M, *Index, /*ClearDSOLocalOnDeclarations=*/false,
2392 /*GlobalsToImport=*/nullptr);
2393
2394 // Perform the import now.
2395 auto ModuleLoader = [&M](StringRef Identifier) {
2396 return loadFile(std::string(Identifier), M.getContext());
2397 };
2398 FunctionImporter Importer(*Index, ModuleLoader,
2399 /*ClearDSOLocalOnDeclarations=*/false);
2400 Expected<bool> Result = Importer.importFunctions(M, ImportList);
2401
2402 // FIXME: Probably need to propagate Errors through the pass manager.
2403 if (!Result) {
2404 logAllUnhandledErrors(Result.takeError(), errs(),
2405 "Error importing module: ");
2406 return true;
2407 }
2408
2409 return true;
2410}
2411
2414 // This is only used for testing the function import pass via opt, where we
2415 // don't have prevailing information from the LTO context available, so just
2416 // conservatively assume everything is prevailing (which is fine for the very
2417 // limited use of prevailing checking in this pass).
2418 auto isPrevailing = [](GlobalValue::GUID, const GlobalValueSummary *) {
2419 return true;
2420 };
2421 if (!doImportingForModuleForTest(M, isPrevailing))
2422 return PreservedAnalyses::all();
2423
2424 return PreservedAnalyses::none();
2425}
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)
RISCVCC::CondCode CC
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)
void importRequiredDeclaration(ValueInfo VI, StringRef CallerModulePath, FunctionImporter::ImportMapTy &ImportList)
Import a declaration of the callee VI of a call edge requiring a declaration import (see RequiresDecl...
DenseMap< StringRef, FunctionImporter::ExportSetTy > *const ExportLists
void addRequiredDeclaration(ValueInfo VI, const GlobalValueSummary *DeclSummary, FunctionImporter::ImportMapTy &ImportList)
Import a declaration of the callee VI from the module containing DeclSummary, which must be a candida...
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
DenseMap< StringRef, FunctionImporter::ExportSetTy > RequiredDeclExports
DenseMap< StringRef, FunctionImporter::ExportSetTy > & requiredDeclExports()
Values that must be exported from their defining modules because declarations of them are required in...
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
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
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
void insert_range(Range &&R)
Inserts a range of 'std::pair<KeyT, ValueT>' values into the map.
Definition DenseMap.h:894
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:283
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:1683
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 LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
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:27
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:41
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
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
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:548
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
void insert_range(Range &&R)
Definition DenseSet.h:236
size_type size() const
Definition DenseSet.h:85
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:188
bool remove_if(Predicate Pred)
Remove all elements for which Pred returns true.
Definition DenseSet.h:104
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
#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"))
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
const IPOOptions & getIPOOptions(const LLVMContext &C)
Definition IPOOptions.h:33
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< 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.
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.
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.