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