1//===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements functions and classes used to support LTO.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/LTO/LTO.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/ScopeExit.h"
16#include "llvm/ADT/SmallSet.h"
17#include "llvm/ADT/StableHashing.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/Analysis/OptimizationRemarkEmitter.h"
21#include "llvm/Analysis/StackSafetyAnalysis.h"
22#include "llvm/Analysis/TargetTransformInfo.h"
23#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
25#include "llvm/CGData/CodeGenData.h"
26#include "llvm/CodeGen/Analysis.h"
27#include "llvm/Config/llvm-config.h"
28#include "llvm/IR/AutoUpgrade.h"
29#include "llvm/IR/DiagnosticPrinter.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMRemarkStreamer.h"
32#include "llvm/IR/LegacyPassManager.h"
33#include "llvm/IR/Mangler.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/RuntimeLibcalls.h"
36#include "llvm/LTO/LTOBackend.h"
37#include "llvm/Linker/IRMover.h"
38#include "llvm/MC/TargetRegistry.h"
39#include "llvm/Object/IRObjectFile.h"
40#include "llvm/Support/Caching.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/Compiler.h"
43#include "llvm/Support/Error.h"
44#include "llvm/Support/FileSystem.h"
45#include "llvm/Support/JSON.h"
46#include "llvm/Support/MemoryBuffer.h"
47#include "llvm/Support/Path.h"
48#include "llvm/Support/Process.h"
49#include "llvm/Support/SHA1.h"
50#include "llvm/Support/Signals.h"
51#include "llvm/Support/SourceMgr.h"
52#include "llvm/Support/ThreadPool.h"
53#include "llvm/Support/Threading.h"
54#include "llvm/Support/TimeProfiler.h"
55#include "llvm/Support/ToolOutputFile.h"
56#include "llvm/Support/VCSRevision.h"
57#include "llvm/Support/raw_ostream.h"
58#include "llvm/Target/TargetOptions.h"
59#include "llvm/Transforms/IPO.h"
60#include "llvm/Transforms/IPO/MemProfContextDisambiguation.h"
61#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
62#include "llvm/Transforms/Utils/FunctionImportUtils.h"
63#include "llvm/Transforms/Utils/SplitModule.h"
64
65#include <optional>
66#include <set>
67
68using namespace llvm;
69using namespace lto;
70using namespace object;
71
72#define DEBUG_TYPE "lto"
73
74Error LTO::setupOptimizationRemarks() {
75 // Setup the remark streamer according to the provided configuration.
76 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
77 Context&: RegularLTO.Ctx, RemarksFilename: Conf.RemarksFilename, RemarksPasses: Conf.RemarksPasses,
78 RemarksFormat: Conf.RemarksFormat, RemarksWithHotness: Conf.RemarksWithHotness,
79 RemarksHotnessThreshold: Conf.RemarksHotnessThreshold);
80 if (!DiagFileOrErr)
81 return DiagFileOrErr.takeError();
82
83 DiagnosticOutputFile = std::move(*DiagFileOrErr);
84
85 // Create a dummy function to serve as a context for LTO-link remarks.
86 // This is required because OptimizationRemark requires a valid Function,
87 // and in ThinLTO we may not have any IR functions available during the
88 // thin link. Host it in a private module to avoid interfering with the LTO
89 // process.
90 if (!LinkerRemarkFunction) {
91 DummyModule = std::make_unique<Module>(args: "remark_dummy", args&: RegularLTO.Ctx);
92 LinkerRemarkFunction = Function::Create(
93 Ty: FunctionType::get(Result: Type::getVoidTy(C&: RegularLTO.Ctx), isVarArg: false),
94 Linkage: GlobalValue::ExternalLinkage, N: "thinlto_remark_dummy",
95 M: DummyModule.get());
96 }
97
98 return Error::success();
99}
100
101void LTO::emitRemark(OptimizationRemark &Remark) {
102 const Function &F = Remark.getFunction();
103 OptimizationRemarkEmitter ORE(const_cast<Function *>(&F));
104 ORE.emit(OptDiag&: Remark);
105}
106
107static cl::opt<bool>
108 DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(Val: false), cl::Hidden,
109 cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
110namespace llvm {
111extern cl::opt<bool> CodeGenDataThinLTOTwoRounds;
112extern cl::opt<bool> ForceImportAll;
113extern cl::opt<bool> AlwaysRenamePromotedLocals;
114} // end namespace llvm
115
116namespace llvm {
117/// Enable global value internalization in LTO.
118cl::opt<bool> EnableLTOInternalization(
119 "enable-lto-internalization", cl::init(Val: true), cl::Hidden,
120 cl::desc("Enable global value internalization in LTO"));
121
122static cl::opt<bool>
123 LTOKeepSymbolCopies("lto-keep-symbol-copies", cl::init(Val: false), cl::Hidden,
124 cl::desc("Keep copies of symbols in LTO indexing"));
125
126/// Indicate we are linking with an allocator that supports hot/cold operator
127/// new interfaces.
128extern cl::opt<bool> SupportsHotColdNew;
129
130/// Enable MemProf context disambiguation for thin link.
131extern cl::opt<bool> EnableMemProfContextDisambiguation;
132} // namespace llvm
133
134// Computes a unique hash for the Module considering the current list of
135// export/import and other global analysis results.
136// Returns the hash in its hexadecimal representation.
137std::string llvm::computeLTOCacheKey(
138 const Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID,
139 const FunctionImporter::ImportMapTy &ImportList,
140 const FunctionImporter::ExportSetTy &ExportList,
141 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
142 const GVSummaryMapTy &DefinedGlobals,
143 const DenseSet<GlobalValue::GUID> &CfiFunctionDefs,
144 const DenseSet<GlobalValue::GUID> &CfiFunctionDecls) {
145 // Compute the unique hash for this entry.
146 // This is based on the current compiler version, the module itself, the
147 // export list, the hash for every single module in the import list, the
148 // list of ResolvedODR for the module, and the list of preserved symbols.
149 SHA1 Hasher;
150
151 // Start with the compiler revision
152 Hasher.update(LLVM_VERSION_STRING);
153#ifdef LLVM_REVISION
154 Hasher.update(LLVM_REVISION);
155#endif
156
157 // Include the parts of the LTO configuration that affect code generation.
158 auto AddString = [&](StringRef Str) {
159 Hasher.update(Str);
160 Hasher.update(Data: ArrayRef<uint8_t>{0});
161 };
162 auto AddUnsigned = [&](unsigned I) {
163 uint8_t Data[4];
164 support::endian::write32le(P: Data, V: I);
165 Hasher.update(Data);
166 };
167 auto AddUint64 = [&](uint64_t I) {
168 uint8_t Data[8];
169 support::endian::write64le(P: Data, V: I);
170 Hasher.update(Data);
171 };
172 auto AddUint8 = [&](const uint8_t I) {
173 Hasher.update(Data: ArrayRef<uint8_t>(&I, 1));
174 };
175 AddString(Conf.CPU);
176 // FIXME: Hash more of Options. For now all clients initialize Options from
177 // command-line flags (which is unsupported in production), but may set
178 // X86RelaxRelocations. The clang driver can also pass FunctionSections,
179 // DataSections and DebuggerTuning via command line flags.
180 AddUnsigned(Conf.Options.MCOptions.X86RelaxRelocations);
181 AddUnsigned(Conf.Options.FunctionSections);
182 AddUnsigned(Conf.Options.DataSections);
183 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
184 for (auto &A : Conf.MAttrs)
185 AddString(A);
186 if (Conf.RelocModel)
187 AddUnsigned(*Conf.RelocModel);
188 else
189 AddUnsigned(-1);
190 if (Conf.CodeModel)
191 AddUnsigned(*Conf.CodeModel);
192 else
193 AddUnsigned(-1);
194 for (const auto &S : Conf.MllvmArgs)
195 AddString(S);
196 AddUnsigned(static_cast<int>(Conf.CGOptLevel));
197 AddUnsigned(static_cast<int>(Conf.CGFileType));
198 AddUnsigned(Conf.OptLevel);
199 AddUnsigned(Conf.Freestanding);
200 AddString(Conf.OptPipeline);
201 AddString(Conf.AAPipeline);
202 AddString(Conf.OverrideTriple);
203 AddString(Conf.DefaultTriple);
204 AddString(Conf.DwoDir);
205 AddUint8(Conf.Dtlto);
206
207 // Include the hash for the current module
208 auto ModHash = Index.getModuleHash(ModPath: ModuleID);
209 Hasher.update(Data: ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
210
211 // TODO: `ExportList` is determined by `ImportList`. Since `ImportList` is
212 // used to compute cache key, we could omit hashing `ExportList` here.
213 std::vector<uint64_t> ExportsGUID;
214 ExportsGUID.reserve(n: ExportList.size());
215 for (const auto &VI : ExportList)
216 ExportsGUID.push_back(x: VI.getGUID());
217
218 // Sort the export list elements GUIDs.
219 llvm::sort(C&: ExportsGUID);
220 for (auto GUID : ExportsGUID)
221 Hasher.update(Data: ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
222
223 // Order using module hash, to be both independent of module name and
224 // module order.
225 auto Comp = [&](const std::pair<StringRef, GlobalValue::GUID> &L,
226 const std::pair<StringRef, GlobalValue::GUID> &R) {
227 return std::make_pair(x: Index.getModule(ModPath: L.first)->second, y: L.second) <
228 std::make_pair(x: Index.getModule(ModPath: R.first)->second, y: R.second);
229 };
230 FunctionImporter::SortedImportList SortedImportList(ImportList, Comp);
231
232 // Count the number of imports for each source module.
233 DenseMap<StringRef, unsigned> ModuleToNumImports;
234 for (const auto &[FromModule, GUID, Type] : SortedImportList)
235 ++ModuleToNumImports[FromModule];
236
237 std::optional<StringRef> LastModule;
238 for (const auto &[FromModule, GUID, Type] : SortedImportList) {
239 if (LastModule != FromModule) {
240 // Include the hash for every module we import functions from. The set of
241 // imported symbols for each module may affect code generation and is
242 // sensitive to link order, so include that as well.
243 LastModule = FromModule;
244 auto ModHash = Index.getModule(ModPath: FromModule)->second;
245 Hasher.update(Data: ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
246 AddUint64(ModuleToNumImports[FromModule]);
247 }
248 AddUint64(GUID);
249 AddUint8(Type);
250 }
251
252 // Include the hash for the resolved ODR.
253 for (auto &Entry : ResolvedODR) {
254 Hasher.update(Data: ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
255 sizeof(GlobalValue::GUID)));
256 Hasher.update(Data: ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
257 sizeof(GlobalValue::LinkageTypes)));
258 }
259
260 // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
261 // defined in this module.
262 std::set<GlobalValue::GUID> UsedCfiDefs;
263 std::set<GlobalValue::GUID> UsedCfiDecls;
264
265 // Typeids used in this module.
266 std::set<GlobalValue::GUID> UsedTypeIds;
267
268 auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
269 if (CfiFunctionDefs.contains(V: ValueGUID))
270 UsedCfiDefs.insert(x: ValueGUID);
271 if (CfiFunctionDecls.contains(V: ValueGUID))
272 UsedCfiDecls.insert(x: ValueGUID);
273 };
274
275 auto AddUsedThings = [&](GlobalValueSummary *GS) {
276 if (!GS) return;
277 AddUnsigned(GS->getVisibility());
278 AddUnsigned(GS->isLive());
279 AddUnsigned(GS->canAutoHide());
280 for (const ValueInfo &VI : GS->refs()) {
281 AddUnsigned(VI.isDSOLocal(WithDSOLocalPropagation: Index.withDSOLocalPropagation()));
282 AddUsedCfiGlobal(VI.getGUID());
283 }
284 if (auto *GVS = dyn_cast<GlobalVarSummary>(Val: GS)) {
285 AddUnsigned(GVS->maybeReadOnly());
286 AddUnsigned(GVS->maybeWriteOnly());
287 }
288 if (auto *FS = dyn_cast<FunctionSummary>(Val: GS)) {
289 for (auto &TT : FS->type_tests())
290 UsedTypeIds.insert(x: TT);
291 for (auto &TT : FS->type_test_assume_vcalls())
292 UsedTypeIds.insert(x: TT.GUID);
293 for (auto &TT : FS->type_checked_load_vcalls())
294 UsedTypeIds.insert(x: TT.GUID);
295 for (auto &TT : FS->type_test_assume_const_vcalls())
296 UsedTypeIds.insert(x: TT.VFunc.GUID);
297 for (auto &TT : FS->type_checked_load_const_vcalls())
298 UsedTypeIds.insert(x: TT.VFunc.GUID);
299 for (auto &ET : FS->calls()) {
300 AddUnsigned(ET.first.isDSOLocal(WithDSOLocalPropagation: Index.withDSOLocalPropagation()));
301 AddUsedCfiGlobal(ET.first.getGUID());
302 }
303 }
304 };
305
306 // Include the hash for the linkage type to reflect internalization and weak
307 // resolution, and collect any used type identifier resolutions.
308 for (auto &GS : DefinedGlobals) {
309 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
310 Hasher.update(
311 Data: ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
312 AddUsedCfiGlobal(GS.first);
313 AddUsedThings(GS.second);
314 }
315
316 // Imported functions may introduce new uses of type identifier resolutions,
317 // so we need to collect their used resolutions as well.
318 for (const auto &[FromModule, GUID, Type] : SortedImportList) {
319 GlobalValueSummary *S = Index.findSummaryInModule(ValueGUID: GUID, ModuleId: FromModule);
320 AddUsedThings(S);
321 // If this is an alias, we also care about any types/etc. that the aliasee
322 // may reference.
323 if (auto *AS = dyn_cast_or_null<AliasSummary>(Val: S))
324 AddUsedThings(AS->getBaseObject());
325 }
326
327 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
328 AddString(TId);
329
330 AddUnsigned(S.TTRes.TheKind);
331 AddUnsigned(S.TTRes.SizeM1BitWidth);
332
333 AddUint64(S.TTRes.AlignLog2);
334 AddUint64(S.TTRes.SizeM1);
335 AddUint64(S.TTRes.BitMask);
336 AddUint64(S.TTRes.InlineBits);
337
338 AddUint64(S.WPDRes.size());
339 for (auto &WPD : S.WPDRes) {
340 AddUnsigned(WPD.first);
341 AddUnsigned(WPD.second.TheKind);
342 AddString(WPD.second.SingleImplName);
343
344 AddUint64(WPD.second.ResByArg.size());
345 for (auto &ByArg : WPD.second.ResByArg) {
346 AddUint64(ByArg.first.size());
347 for (uint64_t Arg : ByArg.first)
348 AddUint64(Arg);
349 AddUnsigned(ByArg.second.TheKind);
350 AddUint64(ByArg.second.Info);
351 AddUnsigned(ByArg.second.Byte);
352 AddUnsigned(ByArg.second.Bit);
353 }
354 }
355 };
356
357 // Include the hash for all type identifiers used by this module.
358 for (GlobalValue::GUID TId : UsedTypeIds) {
359 auto TidIter = Index.typeIds().equal_range(x: TId);
360 for (const auto &I : make_range(p: TidIter))
361 AddTypeIdSummary(I.second.first, I.second.second);
362 }
363
364 AddUnsigned(UsedCfiDefs.size());
365 for (auto &V : UsedCfiDefs)
366 AddUint64(V);
367
368 AddUnsigned(UsedCfiDecls.size());
369 for (auto &V : UsedCfiDecls)
370 AddUint64(V);
371
372 if (!Conf.SampleProfile.empty()) {
373 auto FileOrErr = MemoryBuffer::getFile(Filename: Conf.SampleProfile);
374 if (FileOrErr) {
375 Hasher.update(Str: FileOrErr.get()->getBuffer());
376
377 if (!Conf.ProfileRemapping.empty()) {
378 FileOrErr = MemoryBuffer::getFile(Filename: Conf.ProfileRemapping);
379 if (FileOrErr)
380 Hasher.update(Str: FileOrErr.get()->getBuffer());
381 }
382 }
383 }
384
385 return toHex(Input: Hasher.result());
386}
387
388std::string llvm::recomputeLTOCacheKey(const std::string &Key,
389 StringRef ExtraID) {
390 SHA1 Hasher;
391
392 auto AddString = [&](StringRef Str) {
393 Hasher.update(Str);
394 Hasher.update(Data: ArrayRef<uint8_t>{0});
395 };
396 AddString(Key);
397 AddString(ExtraID);
398
399 return toHex(Input: Hasher.result());
400}
401
402static void thinLTOResolvePrevailingGUID(
403 const Config &C, ValueInfo VI,
404 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
405 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
406 isPrevailing,
407 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
408 recordNewLinkage,
409 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
410 GlobalValue::VisibilityTypes Visibility =
411 C.VisibilityScheme == Config::ELF ? VI.getELFVisibility()
412 : GlobalValue::DefaultVisibility;
413 for (auto &S : VI.getSummaryList()) {
414 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
415 // Ignore local and appending linkage values since the linker
416 // doesn't resolve them.
417 if (GlobalValue::isLocalLinkage(Linkage: OriginalLinkage) ||
418 GlobalValue::isAppendingLinkage(Linkage: S->linkage()))
419 continue;
420 // We need to emit only one of these. The prevailing module will keep it,
421 // but turned into a weak, while the others will drop it when possible.
422 // This is both a compile-time optimization and a correctness
423 // transformation. This is necessary for correctness when we have exported
424 // a reference - we need to convert the linkonce to weak to
425 // ensure a copy is kept to satisfy the exported reference.
426 // FIXME: We may want to split the compile time and correctness
427 // aspects into separate routines.
428 if (isPrevailing(VI.getGUID(), S.get())) {
429 assert(!S->wasPromoted() &&
430 "promoted symbols used to be internal linkage and shouldn't have "
431 "a prevailing variant");
432 if (GlobalValue::isLinkOnceLinkage(Linkage: OriginalLinkage)) {
433 S->setLinkage(GlobalValue::getWeakLinkage(
434 ODR: GlobalValue::isLinkOnceODRLinkage(Linkage: OriginalLinkage)));
435 // The kept copy is eligible for auto-hiding (hidden visibility) if all
436 // copies were (i.e. they were all linkonce_odr global unnamed addr).
437 // If any copy is not (e.g. it was originally weak_odr), then the symbol
438 // must remain externally available (e.g. a weak_odr from an explicitly
439 // instantiated template). Additionally, if it is in the
440 // GUIDPreservedSymbols set, that means that it is visibile outside
441 // the summary (e.g. in a native object or a bitcode file without
442 // summary), and in that case we cannot hide it as it isn't possible to
443 // check all copies.
444 S->setCanAutoHide(VI.canAutoHide() &&
445 !GUIDPreservedSymbols.count(V: VI.getGUID()));
446 }
447 if (C.VisibilityScheme == Config::FromPrevailing)
448 Visibility = S->getVisibility();
449 }
450 // Alias and aliasee can't be turned into available_externally.
451 // When force-import-all is used, it indicates that object linking is not
452 // supported by the target. In this case, we can't change the linkage as
453 // well in case the global is converted to declaration.
454 // Also, if the symbol was promoted, it wouldn't have a prevailing variant,
455 // but also its linkage is set correctly (to External) already.
456 else if (!isa<AliasSummary>(Val: S.get()) &&
457 !GlobalInvolvedWithAlias.count(V: S.get()) && !ForceImportAll &&
458 !S->wasPromoted())
459 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
460
461 // For ELF, set visibility to the computed visibility from summaries. We
462 // don't track visibility from declarations so this may be more relaxed than
463 // the most constraining one.
464 if (C.VisibilityScheme == Config::ELF)
465 S->setVisibility(Visibility);
466
467 if (S->linkage() != OriginalLinkage)
468 recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
469 }
470
471 if (C.VisibilityScheme == Config::FromPrevailing) {
472 for (auto &S : VI.getSummaryList()) {
473 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
474 if (GlobalValue::isLocalLinkage(Linkage: OriginalLinkage) ||
475 GlobalValue::isAppendingLinkage(Linkage: S->linkage()))
476 continue;
477 S->setVisibility(Visibility);
478 }
479 }
480}
481
482/// Resolve linkage for prevailing symbols in the \p Index.
483//
484// We'd like to drop these functions if they are no longer referenced in the
485// current module. However there is a chance that another module is still
486// referencing them because of the import. We make sure we always emit at least
487// one copy.
488void llvm::thinLTOResolvePrevailingInIndex(
489 const Config &C, ModuleSummaryIndex &Index,
490 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
491 isPrevailing,
492 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
493 recordNewLinkage,
494 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
495 // We won't optimize the globals that are referenced by an alias for now
496 // Ideally we should turn the alias into a global and duplicate the definition
497 // when needed.
498 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
499 for (auto &I : Index)
500 for (auto &S : I.second.getSummaryList())
501 if (auto AS = dyn_cast<AliasSummary>(Val: S.get()))
502 GlobalInvolvedWithAlias.insert(V: &AS->getAliasee());
503
504 for (auto &I : Index)
505 thinLTOResolvePrevailingGUID(C, VI: Index.getValueInfo(R: I),
506 GlobalInvolvedWithAlias, isPrevailing,
507 recordNewLinkage, GUIDPreservedSymbols);
508}
509
510static void thinLTOInternalizeAndPromoteGUID(
511 ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
512 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
513 isPrevailing,
514 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr) {
515 // Before performing index-based internalization and promotion for this GUID,
516 // the local flag should be consistent with the summary list linkage types.
517 VI.verifyLocal();
518
519 const bool SingleExternallyVisibleCopy =
520 VI.getSummaryList().size() == 1 &&
521 !GlobalValue::isLocalLinkage(Linkage: VI.getSummaryList().front()->linkage());
522
523 bool NameRecorded = false;
524 for (auto &S : VI.getSummaryList()) {
525 // First see if we need to promote an internal value because it is not
526 // exported.
527 if (isExported(S->modulePath(), VI)) {
528 if (GlobalValue::isLocalLinkage(Linkage: S->linkage())) {
529 // Only the first local GlobalValue in a list of summaries does not
530 // need renaming. In rare cases if there exist more than one summaries
531 // in the list, the rest of them must have renaming (through promotion)
532 // to avoid conflict.
533 if (ExternallyVisibleSymbolNamesPtr && !NameRecorded) {
534 NameRecorded = true;
535 if (ExternallyVisibleSymbolNamesPtr->insert(V: VI.name()).second)
536 S->setNoRenameOnPromotion(true);
537 }
538
539 S->promote();
540 }
541 continue;
542 }
543
544 // Otherwise, see if we can internalize.
545 if (!EnableLTOInternalization)
546 continue;
547
548 // Non-exported values with external linkage can be internalized.
549 if (GlobalValue::isExternalLinkage(Linkage: S->linkage())) {
550 S->setLinkage(GlobalValue::InternalLinkage);
551 continue;
552 }
553
554 // Non-exported function and variable definitions with a weak-for-linker
555 // linkage can be internalized in certain cases. The minimum legality
556 // requirements would be that they are not address taken to ensure that we
557 // don't break pointer equality checks, and that variables are either read-
558 // or write-only. For functions, this is the case if either all copies are
559 // [local_]unnamed_addr, or we can propagate reference edge attributes
560 // (which is how this is guaranteed for variables, when analyzing whether
561 // they are read or write-only).
562 //
563 // However, we only get to this code for weak-for-linkage values in one of
564 // two cases:
565 // 1) The prevailing copy is not in IR (it is in native code).
566 // 2) The prevailing copy in IR is not exported from its module.
567 // Additionally, at least for the new LTO API, case 2 will only happen if
568 // there is exactly one definition of the value (i.e. in exactly one
569 // module), as duplicate defs are result in the value being marked exported.
570 // Likely, users of the legacy LTO API are similar, however, currently there
571 // are llvm-lto based tests of the legacy LTO API that do not mark
572 // duplicate linkonce_odr copies as exported via the tool, so we need
573 // to handle that case below by checking the number of copies.
574 //
575 // Generally, we only want to internalize a weak-for-linker value in case
576 // 2, because in case 1 we cannot see how the value is used to know if it
577 // is read or write-only. We also don't want to bloat the binary with
578 // multiple internalized copies of non-prevailing linkonce/weak functions.
579 // Note if we don't internalize, we will convert non-prevailing copies to
580 // available_externally anyway, so that we drop them after inlining. The
581 // only reason to internalize such a function is if we indeed have a single
582 // copy, because internalizing it won't increase binary size, and enables
583 // use of inliner heuristics that are more aggressive in the face of a
584 // single call to a static (local). For variables, internalizing a read or
585 // write only variable can enable more aggressive optimization. However, we
586 // already perform this elsewhere in the ThinLTO backend handling for
587 // read or write-only variables (processGlobalForThinLTO).
588 //
589 // Therefore, only internalize linkonce/weak if there is a single copy, that
590 // is prevailing in this IR module. We can do so aggressively, without
591 // requiring the address to be insignificant, or that a variable be read or
592 // write-only.
593 if (!GlobalValue::isWeakForLinker(Linkage: S->linkage()) ||
594 GlobalValue::isExternalWeakLinkage(Linkage: S->linkage()))
595 continue;
596
597 // We may have a single summary copy that is externally visible but not
598 // prevailing if the prevailing copy is in a native object.
599 if (SingleExternallyVisibleCopy && isPrevailing(VI.getGUID(), S.get()))
600 S->setLinkage(GlobalValue::InternalLinkage);
601 }
602}
603
604// Update the linkages in the given \p Index to mark exported values
605// as external and non-exported values as internal.
606void llvm::thinLTOInternalizeAndPromoteInIndex(
607 ModuleSummaryIndex &Index,
608 function_ref<bool(StringRef, ValueInfo)> isExported,
609 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
610 isPrevailing,
611 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr) {
612 assert(!Index.withInternalizeAndPromote());
613
614 for (auto &I : Index)
615 thinLTOInternalizeAndPromoteGUID(VI: Index.getValueInfo(R: I), isExported,
616 isPrevailing,
617 ExternallyVisibleSymbolNamesPtr);
618 Index.setWithInternalizeAndPromote();
619}
620
621// Requires a destructor for std::vector<InputModule>.
622InputFile::~InputFile() = default;
623
624Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
625 std::unique_ptr<InputFile> File(new InputFile);
626
627 Expected<IRSymtabFile> FOrErr = readIRSymtab(MBRef: Object);
628 if (!FOrErr)
629 return FOrErr.takeError();
630
631 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
632 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
633 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
634 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
635 File->ComdatTable = FOrErr->TheReader.getComdatTable();
636 File->MbRef =
637 Object; // Save a memory buffer reference to an input file object.
638
639 for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
640 size_t Begin = File->Symbols.size();
641 for (const irsymtab::Reader::SymbolRef &Sym :
642 FOrErr->TheReader.module_symbols(I))
643 // Skip symbols that are irrelevant to LTO. Note that this condition needs
644 // to match the one in Skip() in LTO::addRegularLTO().
645 if (Sym.isGlobal() && !Sym.isFormatSpecific())
646 File->Symbols.push_back(x: Sym);
647 File->ModuleSymIndices.push_back(x: {Begin, File->Symbols.size()});
648 }
649
650 File->Mods = FOrErr->Mods;
651 File->Strtab = std::move(FOrErr->Strtab);
652 return std::move(File);
653}
654
655bool InputFile::Symbol::isLibcall(
656 const TargetLibraryInfo &TLI,
657 const RTLIB::RuntimeLibcallsInfo &Libcalls) const {
658 LibFunc F;
659 if (TLI.getLibFunc(funcName: IRName, F) && TLI.has(F))
660 return true;
661 return Libcalls.getSupportedLibcallImpl(FuncName: IRName) != RTLIB::Unsupported;
662}
663
664StringRef InputFile::getName() const {
665 return Mods[0].getModuleIdentifier();
666}
667
668BitcodeModule &InputFile::getSingleBitcodeModule() {
669 assert(Mods.size() == 1 && "Expect only one bitcode module");
670 return Mods[0];
671}
672
673BitcodeModule &InputFile::getPrimaryBitcodeModule() { return Mods[0]; }
674
675LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
676 const Config &Conf)
677 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
678 Ctx(Conf), CombinedModule(std::make_unique<Module>(args: "ld-temp.o", args&: Ctx)),
679 Mover(std::make_unique<IRMover>(args&: *CombinedModule)) {}
680
681LTO::ThinLTOState::ThinLTOState(ThinBackend BackendParam)
682 : Backend(std::move(BackendParam)), CombinedIndex(/*HaveGVs*/ false) {
683 if (!Backend.isValid())
684 Backend =
685 createInProcessThinBackend(Parallelism: llvm::heavyweight_hardware_concurrency());
686}
687
688LTO::LTO(Config Conf, ThinBackend Backend,
689 unsigned ParallelCodeGenParallelismLevel, LTOKind LTOMode)
690 : Conf(std::move(Conf)),
691 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
692 ThinLTO(std::move(Backend)),
693 GlobalResolutions(
694 std::make_unique<DenseMap<StringRef, GlobalResolution>>()),
695 LTOMode(LTOMode) {
696 if (Conf.KeepSymbolNameCopies || LTOKeepSymbolCopies) {
697 Alloc = std::make_unique<BumpPtrAllocator>();
698 GlobalResolutionSymbolSaver = std::make_unique<llvm::StringSaver>(args&: *Alloc);
699 }
700}
701
702// Requires a destructor for MapVector<BitcodeModule>.
703LTO::~LTO() = default;
704
705void LTO::cleanup() {
706 DummyModule.reset();
707 LinkerRemarkFunction = nullptr;
708 consumeError(Err: finalizeOptimizationRemarks(DiagOutputFile: std::move(DiagnosticOutputFile)));
709}
710
711// Add the symbols in the given module to the GlobalResolutions map, and resolve
712// their partitions.
713void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
714 ArrayRef<SymbolResolution> Res,
715 unsigned Partition, bool InSummary,
716 const Triple &TT) {
717 llvm::TimeTraceScope timeScope("LTO add module to global resolution");
718 auto *ResI = Res.begin();
719 auto *ResE = Res.end();
720 (void)ResE;
721 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
722 TargetLibraryInfoImpl TLII(TT);
723 TargetLibraryInfo TLI(TLII);
724 for (const InputFile::Symbol &Sym : Syms) {
725 assert(ResI != ResE);
726 SymbolResolution Res = *ResI++;
727
728 StringRef SymbolName = Sym.getName();
729 // Keep copies of symbols if the client of LTO says so.
730 if (GlobalResolutionSymbolSaver && !GlobalResolutions->contains(Val: SymbolName))
731 SymbolName = GlobalResolutionSymbolSaver->save(S: SymbolName);
732
733 auto &GlobalRes = (*GlobalResolutions)[SymbolName];
734 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
735 if (Res.Prevailing) {
736 assert(!GlobalRes.Prevailing &&
737 "Multiple prevailing defs are not allowed");
738 GlobalRes.Prevailing = true;
739 GlobalRes.IRName = std::string(Sym.getIRName());
740 } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
741 // Sometimes it can be two copies of symbol in a module and prevailing
742 // symbol can have no IR name. That might happen if symbol is defined in
743 // module level inline asm block. In case we have multiple modules with
744 // the same symbol we want to use IR name of the prevailing symbol.
745 // Otherwise, if we haven't seen a prevailing symbol, set the name so that
746 // we can later use it to check if there is any prevailing copy in IR.
747 GlobalRes.IRName = std::string(Sym.getIRName());
748 }
749
750 // In rare occasion, the symbol used to initialize GlobalRes has a different
751 // IRName from the inspected Symbol. This can happen on macOS + iOS, when a
752 // symbol is referenced through its mangled name, say @"\01_symbol" while
753 // the IRName is @symbol (the prefix underscore comes from MachO mangling).
754 // In that case, we have the same actual Symbol that can get two different
755 // GUID, leading to some invalid internalization. Workaround this by marking
756 // the GlobalRes external.
757
758 // FIXME: instead of this check, it would be desirable to compute GUIDs
759 // based on mangled name, but this requires an access to the Target Triple
760 // and would be relatively invasive on the codebase.
761 if (GlobalRes.IRName != Sym.getIRName()) {
762 GlobalRes.Partition = GlobalResolution::External;
763 GlobalRes.VisibleOutsideSummary = true;
764 }
765
766 bool IsLibcall = Sym.isLibcall(TLI, Libcalls);
767
768 // Set the partition to external if we know it is re-defined by the linker
769 // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
770 // regular object, is referenced from llvm.compiler.used/llvm.used, or was
771 // already recorded as being referenced from a different partition.
772 if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
773 IsLibcall ||
774 (GlobalRes.Partition != GlobalResolution::Unknown &&
775 GlobalRes.Partition != Partition)) {
776 GlobalRes.Partition = GlobalResolution::External;
777 } else
778 // First recorded reference, save the current partition.
779 GlobalRes.Partition = Partition;
780
781 // Flag as visible outside of summary if visible from a regular object or
782 // from a module that does not have a summary.
783 GlobalRes.VisibleOutsideSummary |=
784 (Res.VisibleToRegularObj || Sym.isUsed() || IsLibcall || !InSummary);
785
786 GlobalRes.ExportDynamic |= Res.ExportDynamic;
787 }
788}
789
790void LTO::releaseGlobalResolutionsMemory() {
791 // Release GlobalResolutions dense-map itself.
792 GlobalResolutions.reset();
793 // Release the string saver memory.
794 GlobalResolutionSymbolSaver.reset();
795 Alloc.reset();
796}
797
798static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
799 ArrayRef<SymbolResolution> Res) {
800 StringRef Path = Input->getName();
801 OS << Path << '\n';
802 auto ResI = Res.begin();
803 for (const InputFile::Symbol &Sym : Input->symbols()) {
804 assert(ResI != Res.end());
805 SymbolResolution Res = *ResI++;
806
807 OS << "-r=" << Path << ',' << Sym.getName() << ',';
808 if (Res.Prevailing)
809 OS << 'p';
810 if (Res.FinalDefinitionInLinkageUnit)
811 OS << 'l';
812 if (Res.VisibleToRegularObj)
813 OS << 'x';
814 if (Res.LinkerRedefined)
815 OS << 'r';
816 OS << '\n';
817 }
818 OS.flush();
819 assert(ResI == Res.end());
820}
821
822Error LTO::add(std::unique_ptr<InputFile> InputPtr,
823 ArrayRef<SymbolResolution> Res) {
824 llvm::TimeTraceScope timeScope("LTO add input", InputPtr->getName());
825 assert(!CalledGetMaxTasks);
826
827 Expected<std::shared_ptr<InputFile>> InputOrErr =
828 addInput(InputPtr: std::move(InputPtr));
829 if (!InputOrErr)
830 return InputOrErr.takeError();
831 InputFile *Input = (*InputOrErr).get();
832
833 if (Conf.ResolutionFile)
834 writeToResolutionFile(OS&: *Conf.ResolutionFile, Input, Res);
835
836 if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
837 Triple InputTriple(Input->getTargetTriple());
838 RegularLTO.CombinedModule->setTargetTriple(InputTriple);
839 if (InputTriple.isOSBinFormatELF())
840 Conf.VisibilityScheme = Config::ELF;
841 }
842
843 ArrayRef<SymbolResolution> InputRes = Res;
844 for (unsigned I = 0; I != Input->Mods.size(); ++I) {
845 if (auto Err = addModule(Input&: *Input, InputRes, ModI: I, Res).moveInto(Value&: Res))
846 return Err;
847 }
848
849 assert(Res.empty());
850 return Error::success();
851}
852
853void LTO::setBitcodeLibFuncs(ArrayRef<StringRef> BitcodeLibFuncs) {
854 assert(this->BitcodeLibFuncs.empty() &&
855 "bitcode libfuncs were set twice; maybe accidentally clobbered?");
856 this->BitcodeLibFuncs.append(in_start: BitcodeLibFuncs.begin(), in_end: BitcodeLibFuncs.end());
857}
858
859Expected<ArrayRef<SymbolResolution>>
860LTO::addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
861 unsigned ModI, ArrayRef<SymbolResolution> Res) {
862 llvm::TimeTraceScope timeScope("LTO add module", Input.getName());
863 Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
864 if (!LTOInfo)
865 return LTOInfo.takeError();
866
867 if (EnableSplitLTOUnit) {
868 // If only some modules were split, flag this in the index so that
869 // we can skip or error on optimizations that need consistently split
870 // modules (whole program devirt and lower type tests).
871 if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
872 ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
873 } else
874 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
875
876 BitcodeModule BM = Input.Mods[ModI];
877
878 if ((LTOMode == LTOK_UnifiedRegular || LTOMode == LTOK_UnifiedThin) &&
879 !LTOInfo->UnifiedLTO)
880 return make_error<StringError>(
881 Args: "unified LTO compilation must use "
882 "compatible bitcode modules (use -funified-lto)",
883 Args: inconvertibleErrorCode());
884
885 if (LTOInfo->UnifiedLTO && LTOMode == LTOK_Default)
886 LTOMode = LTOK_UnifiedThin;
887
888 bool IsThinLTO = LTOInfo->IsThinLTO && (LTOMode != LTOK_UnifiedRegular);
889 // If any of the modules inside of a input bitcode file was compiled with
890 // ThinLTO, we assume that the whole input file also was compiled with
891 // ThinLTO.
892 Input.IsThinLTO |= IsThinLTO;
893
894 auto ModSyms = Input.module_symbols(I: ModI);
895 addModuleToGlobalRes(Syms: ModSyms, Res,
896 Partition: IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
897 InSummary: LTOInfo->HasSummary, TT: Triple(Input.getTargetTriple()));
898
899 if (IsThinLTO)
900 return addThinLTO(BM, Syms: ModSyms, Res);
901
902 RegularLTO.EmptyCombinedModule = false;
903 auto ModOrErr = addRegularLTO(Input, InputRes, BM, Syms: ModSyms, Res);
904 if (!ModOrErr)
905 return ModOrErr.takeError();
906 Res = ModOrErr->second;
907
908 if (!LTOInfo->HasSummary) {
909 if (Error Err = linkRegularLTO(Mod: std::move(ModOrErr->first),
910 /*LivenessFromIndex=*/false))
911 return Err;
912 return Res;
913 }
914
915 // Regular LTO module summaries are added to a dummy module that represents
916 // the combined regular LTO module.
917 if (Error Err = BM.readSummary(CombinedIndex&: ThinLTO.CombinedIndex, ModulePath: ""))
918 return Err;
919 RegularLTO.ModsWithSummaries.push_back(x: std::move(ModOrErr->first));
920 return Res;
921}
922
923// Checks whether the given global value is in a non-prevailing comdat
924// (comdat containing values the linker indicated were not prevailing,
925// which we then dropped to available_externally), and if so, removes
926// it from the comdat. This is called for all global values to ensure the
927// comdat is empty rather than leaving an incomplete comdat. It is needed for
928// regular LTO modules, in case we are in a mixed-LTO mode (both regular
929// and thin LTO modules) compilation. Since the regular LTO module will be
930// linked first in the final native link, we want to make sure the linker
931// doesn't select any of these incomplete comdats that would be left
932// in the regular LTO module without this cleanup.
933static void
934handleNonPrevailingComdat(GlobalValue &GV,
935 std::set<const Comdat *> &NonPrevailingComdats) {
936 Comdat *C = GV.getComdat();
937 if (!C)
938 return;
939
940 if (!NonPrevailingComdats.count(x: C))
941 return;
942
943 // Additionally need to drop all global values from the comdat to
944 // available_externally, to satisfy the COMDAT requirement that all members
945 // are discarded as a unit. The non-local linkage global values avoid
946 // duplicate definition linker errors.
947 GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
948
949 if (auto GO = dyn_cast<GlobalObject>(Val: &GV))
950 GO->setComdat(nullptr);
951}
952
953// Add a regular LTO object to the link.
954// The resulting module needs to be linked into the combined LTO module with
955// linkRegularLTO.
956Expected<
957 std::pair<LTO::RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
958LTO::addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
959 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
960 ArrayRef<SymbolResolution> Res) {
961 llvm::TimeTraceScope timeScope("LTO add regular LTO");
962 RegularLTOState::AddedModule Mod;
963 Expected<std::unique_ptr<Module>> MOrErr =
964 BM.getLazyModule(Context&: RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
965 /*IsImporting*/ false);
966 if (!MOrErr)
967 return MOrErr.takeError();
968 Module &M = **MOrErr;
969 Mod.M = std::move(*MOrErr);
970
971 if (Error Err = M.materializeMetadata())
972 return std::move(Err);
973
974 if (LTOMode == LTOK_UnifiedRegular) {
975 // cfi.functions metadata is intended to be used with ThinLTO and may
976 // trigger invalid IR transformations if they are present when doing regular
977 // LTO, so delete it.
978 if (NamedMDNode *CfiFunctionsMD = M.getNamedMetadata(Name: "cfi.functions"))
979 M.eraseNamedMetadata(NMD: CfiFunctionsMD);
980 } else if (NamedMDNode *AliasesMD = M.getNamedMetadata(Name: "aliases")) {
981 // Delete aliases entries for non-prevailing symbols on the ThinLTO side of
982 // this input file.
983 DenseSet<StringRef> Prevailing;
984 for (auto [I, R] : zip(t: Input.symbols(), u&: InputRes))
985 if (R.Prevailing && !I.getIRName().empty())
986 Prevailing.insert(V: I.getIRName());
987 std::vector<MDNode *> AliasGroups;
988 for (MDNode *AliasGroup : AliasesMD->operands()) {
989 std::vector<Metadata *> Aliases;
990 for (Metadata *Alias : AliasGroup->operands()) {
991 if (isa<MDString>(Val: Alias) &&
992 Prevailing.count(V: cast<MDString>(Val: Alias)->getString()))
993 Aliases.push_back(x: Alias);
994 }
995 if (Aliases.size() > 1)
996 AliasGroups.push_back(x: MDTuple::get(Context&: RegularLTO.Ctx, MDs: Aliases));
997 }
998 AliasesMD->clearOperands();
999 for (MDNode *G : AliasGroups)
1000 AliasesMD->addOperand(M: G);
1001 }
1002
1003 UpgradeDebugInfo(M);
1004
1005 ModuleSymbolTable SymTab;
1006 SymTab.addModule(M: &M);
1007
1008 for (GlobalVariable &GV : M.globals())
1009 if (GV.hasAppendingLinkage())
1010 Mod.Keep.push_back(x: &GV);
1011
1012 DenseSet<GlobalObject *> AliasedGlobals;
1013 for (auto &GA : M.aliases())
1014 if (GlobalObject *GO = GA.getAliaseeObject())
1015 AliasedGlobals.insert(V: GO);
1016
1017 // In this function we need IR GlobalValues matching the symbols in Syms
1018 // (which is not backed by a module), so we need to enumerate them in the same
1019 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
1020 // matches the order of an irsymtab, but when we read the irsymtab in
1021 // InputFile::create we omit some symbols that are irrelevant to LTO. The
1022 // Skip() function skips the same symbols from the module as InputFile does
1023 // from the symbol table.
1024 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
1025 auto Skip = [&]() {
1026 while (MsymI != MsymE) {
1027 auto Flags = SymTab.getSymbolFlags(S: *MsymI);
1028 if ((Flags & object::BasicSymbolRef::SF_Global) &&
1029 !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
1030 return;
1031 ++MsymI;
1032 }
1033 };
1034 Skip();
1035
1036 std::set<const Comdat *> NonPrevailingComdats;
1037 SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
1038 for (const InputFile::Symbol &Sym : Syms) {
1039 assert(!Res.empty());
1040 const SymbolResolution &R = Res.consume_front();
1041
1042 assert(MsymI != MsymE);
1043 ModuleSymbolTable::Symbol Msym = *MsymI++;
1044 Skip();
1045
1046 if (GlobalValue *GV = dyn_cast_if_present<GlobalValue *>(Val&: Msym)) {
1047 if (R.Prevailing) {
1048 if (Sym.isUndefined())
1049 continue;
1050 Mod.Keep.push_back(x: GV);
1051 // For symbols re-defined with linker -wrap and -defsym options,
1052 // set the linkage to weak to inhibit IPO. The linkage will be
1053 // restored by the linker.
1054 if (R.LinkerRedefined)
1055 GV->setLinkage(GlobalValue::WeakAnyLinkage);
1056
1057 GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
1058 if (GlobalValue::isLinkOnceLinkage(Linkage: OriginalLinkage))
1059 GV->setLinkage(GlobalValue::getWeakLinkage(
1060 ODR: GlobalValue::isLinkOnceODRLinkage(Linkage: OriginalLinkage)));
1061 } else if (isa<GlobalObject>(Val: GV) &&
1062 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
1063 GV->hasAvailableExternallyLinkage()) &&
1064 !AliasedGlobals.count(V: cast<GlobalObject>(Val: GV))) {
1065 // Any of the above three types of linkage indicates that the
1066 // chosen prevailing symbol will have the same semantics as this copy of
1067 // the symbol, so we may be able to link it with available_externally
1068 // linkage. We will decide later whether to do that when we link this
1069 // module (in linkRegularLTO), based on whether it is undefined.
1070 Mod.Keep.push_back(x: GV);
1071 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
1072 if (GV->hasComdat())
1073 NonPrevailingComdats.insert(x: GV->getComdat());
1074 cast<GlobalObject>(Val: GV)->setComdat(nullptr);
1075 }
1076
1077 // Set the 'local' flag based on the linker resolution for this symbol.
1078 if (R.FinalDefinitionInLinkageUnit) {
1079 GV->setDSOLocal(true);
1080 if (GV->hasDLLImportStorageClass())
1081 GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
1082 DefaultStorageClass);
1083 }
1084 } else if (auto *AS =
1085 dyn_cast_if_present<ModuleSymbolTable::AsmSymbol *>(Val&: Msym)) {
1086 // Collect non-prevailing symbols.
1087 if (!R.Prevailing)
1088 NonPrevailingAsmSymbols.insert(V: AS->first);
1089 } else {
1090 llvm_unreachable("unknown symbol type");
1091 }
1092
1093 // Common resolution: collect the maximum size/alignment over all commons.
1094 // We also record if we see an instance of a common as prevailing, so that
1095 // if none is prevailing we can ignore it later.
1096 if (Sym.isCommon()) {
1097 // FIXME: We should figure out what to do about commons defined by asm.
1098 // For now they aren't reported correctly by ModuleSymbolTable.
1099 auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
1100 CommonRes.Size = std::max(a: CommonRes.Size, b: Sym.getCommonSize());
1101 if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
1102 CommonRes.Alignment =
1103 std::max(a: Align(SymAlignValue), b: CommonRes.Alignment);
1104 }
1105 CommonRes.Prevailing |= R.Prevailing;
1106 }
1107 }
1108
1109 if (!M.getComdatSymbolTable().empty())
1110 for (GlobalValue &GV : M.global_values())
1111 handleNonPrevailingComdat(GV, NonPrevailingComdats);
1112
1113 // Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
1114 // block.
1115 if (!M.getModuleInlineAsm().empty()) {
1116 std::string NewIA = ".lto_discard";
1117 if (!NonPrevailingAsmSymbols.empty()) {
1118 // Don't dicard a symbol if there is a live .symver for it.
1119 ModuleSymbolTable::CollectAsmSymvers(
1120 M, AsmSymver: [&](StringRef Name, StringRef Alias) {
1121 if (!NonPrevailingAsmSymbols.count(V: Alias))
1122 NonPrevailingAsmSymbols.erase(V: Name);
1123 });
1124 NewIA += " " + llvm::join(R&: NonPrevailingAsmSymbols, Separator: ", ");
1125 }
1126 NewIA += "\n";
1127 M.setModuleInlineAsm(NewIA + M.getModuleInlineAsm());
1128 }
1129
1130 assert(MsymI == MsymE);
1131 return std::make_pair(x: std::move(Mod), y&: Res);
1132}
1133
1134Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
1135 bool LivenessFromIndex) {
1136 llvm::TimeTraceScope timeScope("LTO link regular LTO");
1137 std::vector<GlobalValue *> Keep;
1138 for (GlobalValue *GV : Mod.Keep) {
1139 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GUID: GV->getGUID())) {
1140 if (Function *F = dyn_cast<Function>(Val: GV)) {
1141 if (DiagnosticOutputFile) {
1142 if (Error Err = F->materialize())
1143 return Err;
1144 auto R = OptimizationRemark(DEBUG_TYPE, "deadfunction", F);
1145 R << ore::NV("Function", F) << " not added to the combined module ";
1146 emitRemark(Remark&: R);
1147 }
1148 }
1149 continue;
1150 }
1151
1152 if (!GV->hasAvailableExternallyLinkage()) {
1153 Keep.push_back(x: GV);
1154 continue;
1155 }
1156
1157 // Only link available_externally definitions if we don't already have a
1158 // definition.
1159 GlobalValue *CombinedGV =
1160 RegularLTO.CombinedModule->getNamedValue(Name: GV->getName());
1161 if (CombinedGV && !CombinedGV->isDeclaration())
1162 continue;
1163
1164 Keep.push_back(x: GV);
1165 }
1166
1167 return RegularLTO.Mover->move(Src: std::move(Mod.M), ValuesToLink: Keep, AddLazyFor: nullptr,
1168 /* IsPerformingImport */ false);
1169}
1170
1171// Add a ThinLTO module to the link.
1172Expected<ArrayRef<SymbolResolution>>
1173LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
1174 ArrayRef<SymbolResolution> Res) {
1175 llvm::TimeTraceScope timeScope("LTO add thin LTO");
1176 const auto BMID = BM.getModuleIdentifier();
1177 ArrayRef<SymbolResolution> ResTmp = Res;
1178 for (const InputFile::Symbol &Sym : Syms) {
1179 assert(!ResTmp.empty());
1180 const SymbolResolution &R = ResTmp.consume_front();
1181
1182 if (!Sym.getIRName().empty() && R.Prevailing) {
1183 auto GUID = GlobalValue::getGUIDAssumingExternalLinkage(
1184 GlobalName: GlobalValue::getGlobalIdentifier(Name: Sym.getIRName(),
1185 Linkage: GlobalValue::ExternalLinkage, FileName: ""));
1186 ThinLTO.setPrevailingModuleForGUID(GUID, Module: BMID);
1187 }
1188 }
1189
1190 if (Error Err = BM.readSummary(
1191 CombinedIndex&: ThinLTO.CombinedIndex, ModulePath: BMID, IsPrevailing: [&](GlobalValue::GUID GUID) {
1192 return ThinLTO.isPrevailingModuleForGUID(GUID, Module: BMID);
1193 }))
1194 return Err;
1195 LLVM_DEBUG(dbgs() << "Module " << BMID << "\n");
1196
1197 for (const InputFile::Symbol &Sym : Syms) {
1198 assert(!Res.empty());
1199 const SymbolResolution &R = Res.consume_front();
1200
1201 if (!Sym.getIRName().empty() &&
1202 (R.Prevailing || R.FinalDefinitionInLinkageUnit)) {
1203 auto GUID = GlobalValue::getGUIDAssumingExternalLinkage(
1204 GlobalName: GlobalValue::getGlobalIdentifier(Name: Sym.getIRName(),
1205 Linkage: GlobalValue::ExternalLinkage, FileName: ""));
1206 if (R.Prevailing) {
1207 assert(ThinLTO.isPrevailingModuleForGUID(GUID, BMID));
1208
1209 // For linker redefined symbols (via --wrap or --defsym) we want to
1210 // switch the linkage to `weak` to prevent IPOs from happening.
1211 // Find the summary in the module for this very GV and record the new
1212 // linkage so that we can switch it when we import the GV.
1213 if (R.LinkerRedefined)
1214 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(ValueGUID: GUID, ModuleId: BMID))
1215 S->setLinkage(GlobalValue::WeakAnyLinkage);
1216 }
1217
1218 // If the linker resolved the symbol to a local definition then mark it
1219 // as local in the summary for the module we are adding.
1220 if (R.FinalDefinitionInLinkageUnit) {
1221 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(ValueGUID: GUID, ModuleId: BMID)) {
1222 S->setDSOLocal(true);
1223 }
1224 }
1225 }
1226 }
1227
1228 if (!ThinLTO.ModuleMap.insert(KV: {BMID, BM}).second)
1229 return make_error<StringError>(
1230 Args: "Expected at most one ThinLTO module per bitcode file",
1231 Args: inconvertibleErrorCode());
1232
1233 if (!Conf.ThinLTOModulesToCompile.empty()) {
1234 if (!ThinLTO.ModulesToCompile)
1235 ThinLTO.ModulesToCompile = ModuleMapType();
1236 // This is a fuzzy name matching where only modules with name containing the
1237 // specified switch values are going to be compiled.
1238 for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
1239 if (BMID.contains(Other: Name)) {
1240 ThinLTO.ModulesToCompile->insert(KV: {BMID, BM});
1241 LLVM_DEBUG(dbgs() << "[ThinLTO] Selecting " << BMID << " to compile\n");
1242 break;
1243 }
1244 }
1245 }
1246
1247 return Res;
1248}
1249
1250unsigned LTO::getMaxTasks() const {
1251 CalledGetMaxTasks = true;
1252 auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
1253 : ThinLTO.ModuleMap.size();
1254 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1255}
1256
1257// If only some of the modules were split, we cannot correctly handle
1258// code that contains type tests or type checked loads.
1259Error LTO::checkPartiallySplit() {
1260 if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
1261 return Error::success();
1262
1263 const Module *Combined = RegularLTO.CombinedModule.get();
1264 Function *TypeTestFunc =
1265 Intrinsic::getDeclarationIfExists(M: Combined, id: Intrinsic::type_test);
1266 Function *TypeCheckedLoadFunc =
1267 Intrinsic::getDeclarationIfExists(M: Combined, id: Intrinsic::type_checked_load);
1268 Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
1269 M: Combined, id: Intrinsic::type_checked_load_relative);
1270
1271 // First check if there are type tests / type checked loads in the
1272 // merged regular LTO module IR.
1273 if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
1274 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()) ||
1275 (TypeCheckedLoadRelativeFunc &&
1276 !TypeCheckedLoadRelativeFunc->use_empty()))
1277 return make_error<StringError>(
1278 Args: "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1279 Args: inconvertibleErrorCode());
1280
1281 // Otherwise check if there are any recorded in the combined summary from the
1282 // ThinLTO modules.
1283 for (auto &P : ThinLTO.CombinedIndex) {
1284 for (auto &S : P.second.getSummaryList()) {
1285 auto *FS = dyn_cast<FunctionSummary>(Val: S.get());
1286 if (!FS)
1287 continue;
1288 if (!FS->type_test_assume_vcalls().empty() ||
1289 !FS->type_checked_load_vcalls().empty() ||
1290 !FS->type_test_assume_const_vcalls().empty() ||
1291 !FS->type_checked_load_const_vcalls().empty() ||
1292 !FS->type_tests().empty())
1293 return make_error<StringError>(
1294 Args: "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1295 Args: inconvertibleErrorCode());
1296 }
1297 }
1298 return Error::success();
1299}
1300
1301Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
1302 // Call the base class cleanup() explicitly since run() may be invoked on a
1303 // derived LTO object.
1304 llvm::scope_exit CleanUp([this]() { LTO::cleanup(); });
1305
1306 // Compute "dead" symbols, we don't want to import/export these!
1307 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1308 DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
1309 for (auto &Res : *GlobalResolutions) {
1310 // Normally resolution have IR name of symbol. We can do nothing here
1311 // otherwise. See comments in GlobalResolution struct for more details.
1312 if (Res.second.IRName.empty())
1313 continue;
1314
1315 GlobalValue::GUID GUID = GlobalValue::getGUIDAssumingExternalLinkage(
1316 GlobalName: GlobalValue::dropLLVMManglingEscape(Name: Res.second.IRName));
1317
1318 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1319 GUIDPreservedSymbols.insert(V: GUID);
1320
1321 if (Res.second.ExportDynamic)
1322 DynamicExportSymbols.insert(V: GUID);
1323
1324 GUIDPrevailingResolutions[GUID] =
1325 Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
1326 }
1327
1328 auto isPrevailing = [&](GlobalValue::GUID G) {
1329 auto It = GUIDPrevailingResolutions.find(Val: G);
1330 if (It == GUIDPrevailingResolutions.end())
1331 return PrevailingType::Unknown;
1332 return It->second;
1333 };
1334 computeDeadSymbolsWithConstProp(Index&: ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1335 isPrevailing, ImportEnabled: Conf.OptLevel > 0);
1336
1337 // Setup output file to emit statistics.
1338 auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
1339 if (!StatsFileOrErr)
1340 return StatsFileOrErr.takeError();
1341 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1342
1343 if (Error Err = setupOptimizationRemarks())
1344 return Err;
1345
1346 // TODO: Ideally this would be controlled automatically by detecting that we
1347 // are linking with an allocator that supports these interfaces, rather than
1348 // an internal option (which would still be needed for tests, however). For
1349 // example, if the library exported a symbol like __malloc_hot_cold the linker
1350 // could recognize that and set a flag in the lto::Config.
1351 if (SupportsHotColdNew)
1352 ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1353
1354 Error Result = runRegularLTO(AddStream);
1355 if (!Result)
1356 // This will reset the GlobalResolutions optional once done with it to
1357 // reduce peak memory before importing.
1358 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1359
1360 if (StatsFile)
1361 PrintStatisticsJSON(OS&: StatsFile->os());
1362
1363 return Result;
1364}
1365
1366Error LTO::runRegularLTO(AddStreamFn AddStream) {
1367 llvm::TimeTraceScope timeScope("Run regular LTO");
1368 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
1369
1370 // Finalize linking of regular LTO modules containing summaries now that
1371 // we have computed liveness information.
1372 {
1373 llvm::TimeTraceScope timeScope("Link regular LTO");
1374 for (auto &M : RegularLTO.ModsWithSummaries)
1375 if (Error Err = linkRegularLTO(Mod: std::move(M), /*LivenessFromIndex=*/true))
1376 return Err;
1377 }
1378
1379 // Ensure we don't have inconsistently split LTO units with type tests.
1380 // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
1381 // this path both cases but eventually this should be split into two and
1382 // do the ThinLTO checks in `runThinLTO`.
1383 if (Error Err = checkPartiallySplit())
1384 return Err;
1385
1386 // Make sure commons have the right size/alignment: we kept the largest from
1387 // all the prevailing when adding the inputs, and we apply it here.
1388 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
1389 for (auto &I : RegularLTO.Commons) {
1390 if (!I.second.Prevailing)
1391 // Don't do anything if no instance of this common was prevailing.
1392 continue;
1393 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(Name: I.first);
1394 if (OldGV && OldGV->getGlobalSize(DL) == I.second.Size) {
1395 // Don't create a new global if the type is already correct, just make
1396 // sure the alignment is correct.
1397 OldGV->setAlignment(I.second.Alignment);
1398 continue;
1399 }
1400 ArrayType *Ty =
1401 ArrayType::get(ElementType: Type::getInt8Ty(C&: RegularLTO.Ctx), NumElements: I.second.Size);
1402 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
1403 GlobalValue::CommonLinkage,
1404 ConstantAggregateZero::get(Ty), "");
1405 GV->setAlignment(I.second.Alignment);
1406 if (OldGV) {
1407 OldGV->replaceAllUsesWith(V: GV);
1408 GV->takeName(V: OldGV);
1409 OldGV->eraseFromParent();
1410 } else {
1411 GV->setName(I.first);
1412 }
1413 }
1414
1415 bool WholeProgramVisibilityEnabledInLTO =
1416 Conf.HasWholeProgramVisibility &&
1417 // If validation is enabled, upgrade visibility only when all vtables
1418 // have typeinfos.
1419 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1420
1421 // This returns true when the name is local or not defined. Locals are
1422 // expected to be handled separately.
1423 auto IsVisibleToRegularObj = [&](StringRef name) {
1424 auto It = GlobalResolutions->find(Val: name);
1425 return (It == GlobalResolutions->end() ||
1426 It->second.VisibleOutsideSummary || !It->second.Prevailing);
1427 };
1428
1429 // If allowed, upgrade public vcall visibility metadata to linkage unit
1430 // visibility before whole program devirtualization in the optimizer.
1431 updateVCallVisibilityInModule(
1432 M&: *RegularLTO.CombinedModule, WholeProgramVisibilityEnabledInLTO,
1433 DynamicExportSymbols, ValidateAllVtablesHaveTypeInfos: Conf.ValidateAllVtablesHaveTypeInfos,
1434 IsVisibleToRegularObj);
1435 updatePublicTypeTestCalls(M&: *RegularLTO.CombinedModule,
1436 WholeProgramVisibilityEnabledInLTO);
1437
1438 if (Conf.PreOptModuleHook &&
1439 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1440 return Error::success();
1441
1442 if (!Conf.CodeGenOnly) {
1443 for (const auto &R : *GlobalResolutions) {
1444 GlobalValue *GV =
1445 RegularLTO.CombinedModule->getNamedValue(Name: R.second.IRName);
1446 if (!R.second.isPrevailingIRSymbol())
1447 continue;
1448 if (R.second.Partition != 0 &&
1449 R.second.Partition != GlobalResolution::External)
1450 continue;
1451
1452 // Ignore symbols defined in other partitions.
1453 // Also skip declarations, which are not allowed to have internal linkage.
1454 if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1455 continue;
1456
1457 // Symbols that are marked DLLImport or DLLExport should not be
1458 // internalized, as they are either externally visible or referencing
1459 // external symbols. Symbols that have AvailableExternally or Appending
1460 // linkage might be used by future passes and should be kept as is.
1461 // These linkages are seen in Unified regular LTO, because the process
1462 // of creating split LTO units introduces symbols with that linkage into
1463 // one of the created modules. Normally, only the ThinLTO backend would
1464 // compile this module, but Unified Regular LTO processes both
1465 // modules created by the splitting process as regular LTO modules.
1466 if ((LTOMode == LTOKind::LTOK_UnifiedRegular) &&
1467 ((GV->getDLLStorageClass() != GlobalValue::DefaultStorageClass) ||
1468 GV->hasAvailableExternallyLinkage() || GV->hasAppendingLinkage()))
1469 continue;
1470
1471 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1472 : GlobalValue::UnnamedAddr::None);
1473 if (EnableLTOInternalization && R.second.Partition == 0)
1474 GV->setLinkage(GlobalValue::InternalLinkage);
1475 }
1476
1477 if (Conf.PostInternalizeModuleHook &&
1478 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1479 return Error::success();
1480 }
1481
1482 if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1483 if (Error Err = backend(
1484 C: Conf, AddStream, ParallelCodeGenParallelismLevel: RegularLTO.ParallelCodeGenParallelismLevel,
1485 M&: *RegularLTO.CombinedModule, CombinedIndex&: ThinLTO.CombinedIndex, BitcodeLibFuncs))
1486 return Err;
1487 }
1488
1489 return Error::success();
1490}
1491
1492SmallVector<const char *> LTO::getRuntimeLibcallSymbols(const Triple &TT) {
1493 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
1494 SmallVector<const char *> LibcallSymbols;
1495 LibcallSymbols.reserve(N: Libcalls.getNumAvailableLibcallImpls());
1496
1497 for (RTLIB::LibcallImpl Impl : RTLIB::libcall_impls()) {
1498 if (Libcalls.isAvailable(Impl))
1499 LibcallSymbols.push_back(Elt: Libcalls.getLibcallImplName(CallImpl: Impl).data());
1500 }
1501
1502 return LibcallSymbols;
1503}
1504
1505SmallVector<StringRef> LTO::getLibFuncSymbols(const Triple &TT,
1506 StringSaver &Saver) {
1507 auto TLII = std::make_unique<TargetLibraryInfoImpl>(args: TT);
1508 TargetLibraryInfo TLI(*TLII);
1509 SmallVector<StringRef> LibFuncSymbols;
1510 LibFuncSymbols.reserve(N: LibFunc::NumLibFuncs);
1511 for (unsigned I = LibFunc::Begin_LibFunc; I != LibFunc::End_LibFunc; ++I) {
1512 LibFunc F = static_cast<LibFunc>(I);
1513 if (TLI.has(F))
1514 LibFuncSymbols.push_back(Elt: Saver.save(S: TLI.getName(F)).data());
1515 }
1516 return LibFuncSymbols;
1517}
1518
1519Error ThinBackendProc::emitFiles(
1520 const FunctionImporter::ImportMapTy &ImportList, unsigned Task,
1521 llvm::StringRef ModulePath, const std::string &NewModulePath) const {
1522 return emitFiles(ImportList, Task, ModulePath, NewModulePath,
1523 SummaryPath: NewModulePath + ".thinlto.bc");
1524}
1525
1526Error ThinBackendProc::emitFiles(
1527 const FunctionImporter::ImportMapTy &ImportList, unsigned Task,
1528 llvm::StringRef ModulePath, const std::string &NewModulePath,
1529 StringRef SummaryPath) const {
1530 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
1531 GVSummaryPtrSet DeclarationSummaries;
1532
1533 std::error_code EC;
1534 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
1535 ImportList, ModuleToSummariesForIndex,
1536 DecSummaries&: DeclarationSummaries);
1537 // Resolve the output stream (either file-backed or callback-provided) for the
1538 // index file.
1539 std::unique_ptr<raw_pwrite_stream> OS;
1540 if (Conf.GetSummaryIndexOutputStream) {
1541 OS = Conf.GetSummaryIndexOutputStream(Task);
1542 assert(OS && "GetSummaryIndexOutputStream returned null");
1543 } else {
1544 auto FileOS = std::make_unique<raw_fd_ostream>(args&: SummaryPath, args&: EC,
1545 args: sys::fs::OpenFlags::OF_None);
1546 if (EC)
1547 return createFileError(F: "cannot open " + Twine(SummaryPath), EC);
1548 OS = std::move(FileOS);
1549 }
1550
1551 writeIndexToFile(Index: CombinedIndex, Out&: *OS, ModuleToSummariesForIndex: &ModuleToSummariesForIndex,
1552 DecSummaries: &DeclarationSummaries);
1553
1554 // Emit imports files if requested, using callback if provided.
1555 if (Conf.GetImportsListOutputArray) {
1556 std::vector<std::string> &ImportsListRef =
1557 Conf.GetImportsListOutputArray(Task);
1558 processImportsFiles(
1559 ModulePath, ModuleToSummariesForIndex,
1560 F: [&](StringRef M) { ImportsListRef.push_back(x: M.str()); });
1561 } else if (ShouldEmitImportsFiles) {
1562 if (Error E = EmitImportsFiles(ModulePath, OutputFilename: NewModulePath + ".imports",
1563 ModuleToSummariesForIndex))
1564 return E;
1565 }
1566 return Error::success();
1567}
1568
1569namespace {
1570/// Base class for ThinLTO backends that perform code generation and insert the
1571/// generated files back into the link.
1572class CGThinBackend : public ThinBackendProc {
1573protected:
1574 DenseSet<GlobalValue::GUID> CfiFunctionDefs;
1575 DenseSet<GlobalValue::GUID> CfiFunctionDecls;
1576 bool ShouldEmitIndexFiles;
1577
1578public:
1579 CGThinBackend(
1580 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1581 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1582 lto::IndexWriteCallback OnWrite, bool ShouldEmitIndexFiles,
1583 bool ShouldEmitImportsFiles, ThreadPoolStrategy ThinLTOParallelism)
1584 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1585 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1586 ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1587 auto &Defs = CombinedIndex.cfiFunctionDefs();
1588 CfiFunctionDefs.insert_range(R: Defs.getExportedThinLTOGUIDs());
1589 auto &Decls = CombinedIndex.cfiFunctionDecls();
1590 CfiFunctionDecls.insert_range(R: Decls.getExportedThinLTOGUIDs());
1591 }
1592};
1593
1594/// This backend performs code generation by scheduling a job to run on
1595/// an in-process thread when invoked for each task.
1596class InProcessThinBackend : public CGThinBackend {
1597protected:
1598 // Callback used to add generated native object files to the link by code
1599 // generating directly into the returned output stream.
1600 AddStreamFn AddStream;
1601 FileCache Cache;
1602 ArrayRef<StringRef> BitcodeLibFuncs;
1603
1604public:
1605 InProcessThinBackend(
1606 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1607 ThreadPoolStrategy ThinLTOParallelism,
1608 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1609 AddStreamFn AddStream, FileCache Cache, lto::IndexWriteCallback OnWrite,
1610 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
1611 ArrayRef<StringRef> BitcodeLibFuncs)
1612 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries, OnWrite,
1613 ShouldEmitIndexFiles, ShouldEmitImportsFiles,
1614 ThinLTOParallelism),
1615 AddStream(std::move(AddStream)), Cache(std::move(Cache)),
1616 BitcodeLibFuncs(BitcodeLibFuncs) {}
1617
1618 virtual Error runThinLTOBackendThread(
1619 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1620 ModuleSummaryIndex &CombinedIndex,
1621 const FunctionImporter::ImportMapTy &ImportList,
1622 const FunctionImporter::ExportSetTy &ExportList,
1623 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1624 const GVSummaryMapTy &DefinedGlobals,
1625 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1626 auto ModuleID = BM.getModuleIdentifier();
1627 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (in-process)",
1628 ModuleID);
1629 auto RunThinBackend = [&](AddStreamFn AddStream) {
1630 LTOLLVMContext BackendContext(Conf);
1631 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(Context&: BackendContext);
1632 if (!MOrErr)
1633 return MOrErr.takeError();
1634
1635 return thinBackend(C: Conf, Task, AddStream, M&: **MOrErr, CombinedIndex,
1636 ImportList, DefinedGlobals, ModuleMap: &ModuleMap,
1637 CodeGenOnly: Conf.CodeGenOnly, BitcodeLibFuncs);
1638 };
1639 if (ShouldEmitIndexFiles) {
1640 if (auto E = emitFiles(ImportList, Task, ModulePath: ModuleID, NewModulePath: ModuleID.str()))
1641 return E;
1642 }
1643
1644 if (!Cache.isValid() || !CombinedIndex.modulePaths().count(Key: ModuleID) ||
1645 all_of(Range: CombinedIndex.getModuleHash(ModPath: ModuleID),
1646 P: [](uint32_t V) { return V == 0; }))
1647 // Cache disabled or no entry for this module in the combined index or
1648 // no module hash.
1649 return RunThinBackend(AddStream);
1650
1651 // The module may be cached, this helps handling it.
1652 std::string Key = computeLTOCacheKey(
1653 Conf, Index: CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1654 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1655 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1656 if (Error Err = CacheAddStreamOrErr.takeError())
1657 return Err;
1658 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1659 if (CacheAddStream)
1660 return RunThinBackend(CacheAddStream);
1661
1662 return Error::success();
1663 }
1664
1665 Error start(
1666 unsigned Task, BitcodeModule BM,
1667 const FunctionImporter::ImportMapTy &ImportList,
1668 const FunctionImporter::ExportSetTy &ExportList,
1669 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1670 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1671 StringRef ModulePath = BM.getModuleIdentifier();
1672 assert(ModuleToDefinedGVSummaries.count(ModulePath));
1673 const GVSummaryMapTy &DefinedGlobals =
1674 ModuleToDefinedGVSummaries.find(Val: ModulePath)->second;
1675 BackendThreadPool.async(
1676 F: [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1677 const FunctionImporter::ImportMapTy &ImportList,
1678 const FunctionImporter::ExportSetTy &ExportList,
1679 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1680 &ResolvedODR,
1681 const GVSummaryMapTy &DefinedGlobals,
1682 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1683 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1684 timeTraceProfilerInitialize(TimeTraceGranularity: Conf.TimeTraceGranularity,
1685 ProcName: "thin backend");
1686 Error E = runThinLTOBackendThread(
1687 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1688 ResolvedODR, DefinedGlobals, ModuleMap);
1689 if (E) {
1690 std::unique_lock<std::mutex> L(ErrMu);
1691 if (Err)
1692 Err = joinErrors(E1: std::move(*Err), E2: std::move(E));
1693 else
1694 Err = std::move(E);
1695 }
1696 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1697 timeTraceProfilerFinishThread();
1698 },
1699 ArgList&: BM, ArgList: std::ref(t&: CombinedIndex), ArgList: std::ref(t: ImportList), ArgList: std::ref(t: ExportList),
1700 ArgList: std::ref(t: ResolvedODR), ArgList: std::ref(t: DefinedGlobals), ArgList: std::ref(t&: ModuleMap));
1701
1702 if (OnWrite)
1703 OnWrite(std::string(ModulePath));
1704 return Error::success();
1705 }
1706};
1707
1708/// This backend is utilized in the first round of a two-codegen round process.
1709/// It first saves optimized bitcode files to disk before the codegen process
1710/// begins. After codegen, it stores the resulting object files in a scratch
1711/// buffer. Note the codegen data stored in the scratch buffer will be extracted
1712/// and merged in the subsequent step.
1713class FirstRoundThinBackend : public InProcessThinBackend {
1714 AddStreamFn IRAddStream;
1715 FileCache IRCache;
1716
1717public:
1718 FirstRoundThinBackend(
1719 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1720 ThreadPoolStrategy ThinLTOParallelism,
1721 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1722 AddStreamFn CGAddStream, FileCache CGCache,
1723 ArrayRef<StringRef> BitcodeLibFuncs, AddStreamFn IRAddStream,
1724 FileCache IRCache)
1725 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1726 ModuleToDefinedGVSummaries, std::move(CGAddStream),
1727 std::move(CGCache), /*OnWrite=*/nullptr,
1728 /*ShouldEmitIndexFiles=*/false,
1729 /*ShouldEmitImportsFiles=*/false, BitcodeLibFuncs),
1730 IRAddStream(std::move(IRAddStream)), IRCache(std::move(IRCache)) {}
1731
1732 Error runThinLTOBackendThread(
1733 AddStreamFn CGAddStream, FileCache CGCache, unsigned Task,
1734 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1735 const FunctionImporter::ImportMapTy &ImportList,
1736 const FunctionImporter::ExportSetTy &ExportList,
1737 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1738 const GVSummaryMapTy &DefinedGlobals,
1739 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1740 auto ModuleID = BM.getModuleIdentifier();
1741 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (first round)",
1742 ModuleID);
1743 auto RunThinBackend = [&](AddStreamFn CGAddStream,
1744 AddStreamFn IRAddStream) {
1745 LTOLLVMContext BackendContext(Conf);
1746 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(Context&: BackendContext);
1747 if (!MOrErr)
1748 return MOrErr.takeError();
1749
1750 return thinBackend(C: Conf, Task, AddStream: CGAddStream, M&: **MOrErr, CombinedIndex,
1751 ImportList, DefinedGlobals, ModuleMap: &ModuleMap,
1752 CodeGenOnly: Conf.CodeGenOnly, BitcodeLibFuncs, IRAddStream);
1753 };
1754 // Like InProcessThinBackend, we produce index files as needed for
1755 // FirstRoundThinBackend. However, these files are not generated for
1756 // SecondRoundThinBackend.
1757 if (ShouldEmitIndexFiles) {
1758 if (auto E = emitFiles(ImportList, Task, ModulePath: ModuleID, NewModulePath: ModuleID.str()))
1759 return E;
1760 }
1761
1762 assert((CGCache.isValid() == IRCache.isValid()) &&
1763 "Both caches for CG and IR should have matching availability");
1764 if (!CGCache.isValid() || !CombinedIndex.modulePaths().count(Key: ModuleID) ||
1765 all_of(Range: CombinedIndex.getModuleHash(ModPath: ModuleID),
1766 P: [](uint32_t V) { return V == 0; }))
1767 // Cache disabled or no entry for this module in the combined index or
1768 // no module hash.
1769 return RunThinBackend(CGAddStream, IRAddStream);
1770
1771 // Get CGKey for caching object in CGCache.
1772 std::string CGKey = computeLTOCacheKey(
1773 Conf, Index: CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1774 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1775 Expected<AddStreamFn> CacheCGAddStreamOrErr =
1776 CGCache(Task, CGKey, ModuleID);
1777 if (Error Err = CacheCGAddStreamOrErr.takeError())
1778 return Err;
1779 AddStreamFn &CacheCGAddStream = *CacheCGAddStreamOrErr;
1780
1781 // Get IRKey for caching (optimized) IR in IRCache with an extra ID.
1782 std::string IRKey = recomputeLTOCacheKey(Key: CGKey, /*ExtraID=*/"IR");
1783 Expected<AddStreamFn> CacheIRAddStreamOrErr =
1784 IRCache(Task, IRKey, ModuleID);
1785 if (Error Err = CacheIRAddStreamOrErr.takeError())
1786 return Err;
1787 AddStreamFn &CacheIRAddStream = *CacheIRAddStreamOrErr;
1788
1789 // Ideally, both CG and IR caching should be synchronized. However, in
1790 // practice, their availability may differ due to different expiration
1791 // times. Therefore, if either cache is missing, the backend process is
1792 // triggered.
1793 if (CacheCGAddStream || CacheIRAddStream) {
1794 LLVM_DEBUG(dbgs() << "[FirstRound] Cache Miss for "
1795 << BM.getModuleIdentifier() << "\n");
1796 return RunThinBackend(CacheCGAddStream ? CacheCGAddStream : CGAddStream,
1797 CacheIRAddStream ? CacheIRAddStream : IRAddStream);
1798 }
1799
1800 return Error::success();
1801 }
1802};
1803
1804/// This backend operates in the second round of a two-codegen round process.
1805/// It starts by reading the optimized bitcode files that were saved during the
1806/// first round. The backend then executes the codegen only to further optimize
1807/// the code, utilizing the codegen data merged from the first round. Finally,
1808/// it writes the resulting object files as usual.
1809class SecondRoundThinBackend : public InProcessThinBackend {
1810 std::unique_ptr<SmallVector<StringRef>> IRFiles;
1811 stable_hash CombinedCGDataHash;
1812
1813public:
1814 SecondRoundThinBackend(
1815 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1816 ThreadPoolStrategy ThinLTOParallelism,
1817 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1818 AddStreamFn AddStream, FileCache Cache,
1819 ArrayRef<StringRef> BitcodeLibFuncs,
1820 std::unique_ptr<SmallVector<StringRef>> IRFiles,
1821 stable_hash CombinedCGDataHash)
1822 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1823 ModuleToDefinedGVSummaries, std::move(AddStream),
1824 std::move(Cache),
1825 /*OnWrite=*/nullptr,
1826 /*ShouldEmitIndexFiles=*/false,
1827 /*ShouldEmitImportsFiles=*/false, BitcodeLibFuncs),
1828 IRFiles(std::move(IRFiles)), CombinedCGDataHash(CombinedCGDataHash) {}
1829
1830 Error runThinLTOBackendThread(
1831 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1832 ModuleSummaryIndex &CombinedIndex,
1833 const FunctionImporter::ImportMapTy &ImportList,
1834 const FunctionImporter::ExportSetTy &ExportList,
1835 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1836 const GVSummaryMapTy &DefinedGlobals,
1837 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1838 auto ModuleID = BM.getModuleIdentifier();
1839 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (second round)",
1840 ModuleID);
1841 auto RunThinBackend = [&](AddStreamFn AddStream) {
1842 LTOLLVMContext BackendContext(Conf);
1843 std::unique_ptr<Module> LoadedModule =
1844 cgdata::loadModuleForTwoRounds(OrigModule&: BM, Task, Context&: BackendContext, IRFiles: *IRFiles);
1845
1846 return thinBackend(C: Conf, Task, AddStream, M&: *LoadedModule, CombinedIndex,
1847 ImportList, DefinedGlobals, ModuleMap: &ModuleMap,
1848 /*CodeGenOnly=*/true, BitcodeLibFuncs);
1849 };
1850 if (!Cache.isValid() || !CombinedIndex.modulePaths().count(Key: ModuleID) ||
1851 all_of(Range: CombinedIndex.getModuleHash(ModPath: ModuleID),
1852 P: [](uint32_t V) { return V == 0; }))
1853 // Cache disabled or no entry for this module in the combined index or
1854 // no module hash.
1855 return RunThinBackend(AddStream);
1856
1857 // Get Key for caching the final object file in Cache with the combined
1858 // CGData hash.
1859 std::string Key = computeLTOCacheKey(
1860 Conf, Index: CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1861 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1862 Key = recomputeLTOCacheKey(Key,
1863 /*ExtraID=*/std::to_string(val: CombinedCGDataHash));
1864 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1865 if (Error Err = CacheAddStreamOrErr.takeError())
1866 return Err;
1867 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1868
1869 if (CacheAddStream) {
1870 LLVM_DEBUG(dbgs() << "[SecondRound] Cache Miss for "
1871 << BM.getModuleIdentifier() << "\n");
1872 return RunThinBackend(CacheAddStream);
1873 }
1874
1875 return Error::success();
1876 }
1877};
1878} // end anonymous namespace
1879
1880ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism,
1881 lto::IndexWriteCallback OnWrite,
1882 bool ShouldEmitIndexFiles,
1883 bool ShouldEmitImportsFiles) {
1884 auto Func =
1885 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1886 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1887 AddStreamFn AddStream, FileCache Cache,
1888 ArrayRef<StringRef> BitcodeLibFuncs) {
1889 return std::make_unique<InProcessThinBackend>(
1890 args: Conf, args&: CombinedIndex, args: Parallelism, args: ModuleToDefinedGVSummaries,
1891 args&: AddStream, args&: Cache, args: OnWrite, args: ShouldEmitIndexFiles,
1892 args: ShouldEmitImportsFiles, args&: BitcodeLibFuncs);
1893 };
1894 return ThinBackend(Func, Parallelism);
1895}
1896
1897StringLiteral lto::getThinLTODefaultCPU(const Triple &TheTriple) {
1898 if (!TheTriple.isOSDarwin())
1899 return "";
1900 if (TheTriple.getArch() == Triple::x86_64)
1901 return "core2";
1902 if (TheTriple.getArch() == Triple::x86)
1903 return "yonah";
1904 if (TheTriple.isArm64e())
1905 return "apple-a12";
1906 if (TheTriple.getArch() == Triple::aarch64 ||
1907 TheTriple.getArch() == Triple::aarch64_32)
1908 return "cyclone";
1909 return "";
1910}
1911
1912// Given the original \p Path to an output file, replace any path
1913// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1914// resulting directory if it does not yet exist.
1915std::string lto::getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
1916 StringRef NewPrefix) {
1917 if (OldPrefix.empty() && NewPrefix.empty())
1918 return std::string(Path);
1919 SmallString<128> NewPath(Path);
1920 llvm::sys::path::replace_path_prefix(Path&: NewPath, OldPrefix, NewPrefix);
1921 StringRef ParentPath = llvm::sys::path::parent_path(path: NewPath.str());
1922 if (!ParentPath.empty()) {
1923 // Make sure the new directory exists, creating it if necessary.
1924 if (std::error_code EC = llvm::sys::fs::create_directories(path: ParentPath))
1925 llvm::errs() << "warning: could not create directory '" << ParentPath
1926 << "': " << EC.message() << '\n';
1927 }
1928 return std::string(NewPath);
1929}
1930
1931namespace {
1932class WriteIndexesThinBackend : public ThinBackendProc {
1933 std::string OldPrefix, NewPrefix, NativeObjectPrefix;
1934 raw_fd_ostream *LinkedObjectsFile;
1935 DenseSet<GlobalValue::GUID> CfiFunctionDefs;
1936 DenseSet<GlobalValue::GUID> CfiFunctionDecls;
1937
1938public:
1939 WriteIndexesThinBackend(
1940 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1941 ThreadPoolStrategy ThinLTOParallelism,
1942 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1943 std::string OldPrefix, std::string NewPrefix,
1944 std::string NativeObjectPrefix, bool ShouldEmitImportsFiles,
1945 raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1946 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1947 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1948 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1949 NativeObjectPrefix(NativeObjectPrefix),
1950 LinkedObjectsFile(LinkedObjectsFile) {
1951 auto Defs = CombinedIndex.cfiFunctionDefs().getExportedThinLTOGUIDs();
1952 CfiFunctionDefs.insert(I: Defs.begin(), E: Defs.end());
1953 auto Decls = CombinedIndex.cfiFunctionDecls().getExportedThinLTOGUIDs();
1954 CfiFunctionDecls.insert(I: Decls.begin(), E: Decls.end());
1955 }
1956
1957 Error start(
1958 unsigned Task, BitcodeModule BM,
1959 const FunctionImporter::ImportMapTy &ImportList,
1960 const FunctionImporter::ExportSetTy &ExportList,
1961 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1962 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1963 StringRef ModulePath = BM.getModuleIdentifier();
1964
1965 // The contents of this file may be used as input to a native link, and must
1966 // therefore contain the processed modules in a determinstic order that
1967 // match the order they are provided on the command line. For that reason,
1968 // we cannot include this in the asynchronously executed lambda below.
1969 if (LinkedObjectsFile) {
1970 std::string ObjectPrefix =
1971 NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
1972 std::string LinkedObjectsFilePath =
1973 getThinLTOOutputFile(Path: ModulePath, OldPrefix, NewPrefix: ObjectPrefix);
1974 *LinkedObjectsFile << LinkedObjectsFilePath << '\n';
1975 }
1976
1977 BackendThreadPool.async(
1978 F: [this](unsigned Task, const StringRef ModulePath,
1979 const FunctionImporter::ImportMapTy &ImportList,
1980 const FunctionImporter::ExportSetTy &ExportList,
1981 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1982 &ResolvedODR,
1983 const std::string &OldPrefix, const std::string &NewPrefix) {
1984 std::string NewModulePath =
1985 getThinLTOOutputFile(Path: ModulePath, OldPrefix, NewPrefix);
1986 auto E = emitFiles(ImportList, Task, ModulePath, NewModulePath);
1987 if (E) {
1988 std::unique_lock<std::mutex> L(ErrMu);
1989 if (Err)
1990 Err = joinErrors(E1: std::move(*Err), E2: std::move(E));
1991 else
1992 Err = std::move(E);
1993 }
1994 assert(ModuleToDefinedGVSummaries.count(ModulePath));
1995 const GVSummaryMapTy &DefinedGlobals =
1996 ModuleToDefinedGVSummaries.find(Val: ModulePath)->second;
1997
1998 // DTLTO needs the per-module LTO cache key to probe the cache.
1999 if (Conf.GetCacheKeyOutputString) {
2000 std::string &CacheKey = Conf.GetCacheKeyOutputString(Task);
2001 CacheKey = computeLTOCacheKey(
2002 Conf, Index: CombinedIndex, ModuleID: ModulePath, ImportList, ExportList,
2003 ResolvedODR, DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
2004 }
2005 },
2006 ArgList&: Task, ArgList&: ModulePath, ArgList: ImportList, ArgList: ExportList, ArgList: ResolvedODR, ArgList&: OldPrefix,
2007 ArgList&: NewPrefix);
2008
2009 if (OnWrite)
2010 OnWrite(std::string(ModulePath));
2011 return Error::success();
2012 }
2013
2014 bool isSensitiveToInputOrder() override {
2015 // The order which modules are written to LinkedObjectsFile should be
2016 // deterministic and match the order they are passed on the command line.
2017 return true;
2018 }
2019};
2020} // end anonymous namespace
2021
2022ThinBackend lto::createWriteIndexesThinBackend(
2023 ThreadPoolStrategy Parallelism, std::string OldPrefix,
2024 std::string NewPrefix, std::string NativeObjectPrefix,
2025 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
2026 IndexWriteCallback OnWrite) {
2027 auto Func =
2028 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
2029 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
2030 AddStreamFn AddStream, FileCache Cache,
2031 ArrayRef<StringRef> BitcodeLibFuncs) {
2032 return std::make_unique<WriteIndexesThinBackend>(
2033 args: Conf, args&: CombinedIndex, args: Parallelism, args: ModuleToDefinedGVSummaries,
2034 args: OldPrefix, args: NewPrefix, args: NativeObjectPrefix, args: ShouldEmitImportsFiles,
2035 args: LinkedObjectsFile, args: OnWrite);
2036 };
2037 return ThinBackend(Func, Parallelism);
2038}
2039
2040Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
2041 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
2042 llvm::TimeTraceScope timeScope("Run ThinLTO");
2043 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
2044 ThinLTO.CombinedIndex.releaseTemporaryMemory();
2045 timeTraceProfilerBegin(Name: "ThinLink", Detail: StringRef(""));
2046 llvm::scope_exit TimeTraceScopeExit([]() {
2047 if (llvm::timeTraceProfilerEnabled())
2048 llvm::timeTraceProfilerEnd();
2049 });
2050 if (ThinLTO.ModuleMap.empty())
2051 return Error::success();
2052
2053 if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
2054 llvm::errs() << "warning: [ThinLTO] No module compiled\n";
2055 return Error::success();
2056 }
2057
2058 if (Conf.CombinedIndexHook &&
2059 !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
2060 return Error::success();
2061
2062 // Collect for each module the list of function it defines (GUID ->
2063 // Summary).
2064 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(
2065 ThinLTO.ModuleMap.size());
2066 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
2067 ModuleToDefinedGVSummaries);
2068 // Create entries for any modules that didn't have any GV summaries
2069 // (either they didn't have any GVs to start with, or we suppressed
2070 // generation of the summaries because they e.g. had inline assembly
2071 // uses that couldn't be promoted/renamed on export). This is so
2072 // InProcessThinBackend::start can still launch a backend thread, which
2073 // is passed the map of summaries for the module, without any special
2074 // handling for this case.
2075 for (auto &Mod : ThinLTO.ModuleMap)
2076 if (!ModuleToDefinedGVSummaries.count(Val: Mod.first))
2077 ModuleToDefinedGVSummaries.try_emplace(Key: Mod.first);
2078
2079 FunctionImporter::ImportListsTy ImportLists(ThinLTO.ModuleMap.size());
2080 DenseMap<StringRef, FunctionImporter::ExportSetTy> ExportLists(
2081 ThinLTO.ModuleMap.size());
2082 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
2083
2084 if (DumpThinCGSCCs)
2085 ThinLTO.CombinedIndex.dumpSCCs(OS&: outs());
2086
2087 std::set<GlobalValue::GUID> ExportedGUIDs;
2088
2089 bool WholeProgramVisibilityEnabledInLTO =
2090 Conf.HasWholeProgramVisibility &&
2091 // If validation is enabled, upgrade visibility only when all vtables
2092 // have typeinfos.
2093 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
2094 if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
2095 ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
2096
2097 // If we're validating, get the vtable symbols that should not be
2098 // upgraded because they correspond to typeIDs outside of index-based
2099 // WPD info.
2100 DenseSet<GlobalValue::GUID> VisibleToRegularObjSymbols;
2101 if (WholeProgramVisibilityEnabledInLTO &&
2102 Conf.ValidateAllVtablesHaveTypeInfos) {
2103 // This returns true when the name is local or not defined. Locals are
2104 // expected to be handled separately.
2105 auto IsVisibleToRegularObj = [&](StringRef name) {
2106 auto It = GlobalResolutions->find(Val: name);
2107 return (It == GlobalResolutions->end() ||
2108 It->second.VisibleOutsideSummary || !It->second.Prevailing);
2109 };
2110
2111 getVisibleToRegularObjVtableGUIDs(Index&: ThinLTO.CombinedIndex,
2112 VisibleToRegularObjSymbols,
2113 IsVisibleToRegularObj);
2114 }
2115
2116 // If allowed, upgrade public vcall visibility to linkage unit visibility in
2117 // the summaries before whole program devirtualization below.
2118 updateVCallVisibilityInIndex(
2119 Index&: ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO,
2120 DynamicExportSymbols, VisibleToRegularObjSymbols);
2121
2122 // Perform index-based WPD. This will return immediately if there are
2123 // no index entries in the typeIdMetadata map (e.g. if we are instead
2124 // performing IR-based WPD in hybrid regular/thin LTO mode).
2125 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
2126 DenseSet<StringRef> ExternallyVisibleSymbolNames;
2127
2128 // Used by the promotion-time renaming logic. When non-null, this set
2129 // identifies symbols that should not be renamed during promotion.
2130 // It is non-null only when whole-program visibility is enabled and
2131 // renaming is not forced. Otherwise, the default renaming behavior applies.
2132 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr =
2133 (WholeProgramVisibilityEnabledInLTO && !AlwaysRenamePromotedLocals)
2134 ? &ExternallyVisibleSymbolNames
2135 : nullptr;
2136 runWholeProgramDevirtOnIndex(Summary&: ThinLTO.CombinedIndex, ExportedGUIDs,
2137 LocalWPDTargetsMap,
2138 ExternallyVisibleSymbolNamesPtr);
2139
2140 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
2141 return ThinLTO.isPrevailingModuleForGUID(GUID, Module: S->modulePath());
2142 };
2143 if (EnableMemProfContextDisambiguation) {
2144 MemProfContextDisambiguation ContextDisambiguation;
2145 ContextDisambiguation.run(
2146 Index&: ThinLTO.CombinedIndex, isPrevailing, Ctx&: RegularLTO.Ctx,
2147 EmitRemark: [&](StringRef PassName, StringRef RemarkName, const Twine &Msg) {
2148 auto R = OptimizationRemark(PassName.data(), RemarkName,
2149 LinkerRemarkFunction);
2150 R << Msg.str();
2151 emitRemark(Remark&: R);
2152 });
2153 }
2154
2155 // Figure out which symbols need to be internalized. This also needs to happen
2156 // at -O0 because summary-based DCE is implemented using internalization, and
2157 // we must apply DCE consistently with the full LTO module in order to avoid
2158 // undefined references during the final link.
2159 for (auto &Res : *GlobalResolutions) {
2160 // If the symbol does not have external references or it is not prevailing,
2161 // then not need to mark it as exported from a ThinLTO partition.
2162 if (Res.second.Partition != GlobalResolution::External ||
2163 !Res.second.isPrevailingIRSymbol())
2164 continue;
2165 auto GUID = GlobalValue::getGUIDAssumingExternalLinkage(
2166 GlobalName: GlobalValue::dropLLVMManglingEscape(Name: Res.second.IRName));
2167 // Mark exported unless index-based analysis determined it to be dead.
2168 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
2169 ExportedGUIDs.insert(x: GUID);
2170 }
2171
2172 // Reset the GlobalResolutions to deallocate the associated memory, as there
2173 // are no further accesses. We specifically want to do this before computing
2174 // cross module importing, which adds to peak memory via the computed import
2175 // and export lists.
2176 releaseGlobalResolutionsMemory();
2177
2178 if (Conf.OptLevel > 0)
2179 ComputeCrossModuleImport(Index: ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2180 isPrevailing, ImportLists, ExportLists);
2181
2182 // Any functions referenced by the jump table in the regular LTO object must
2183 // be exported.
2184 auto Defs = ThinLTO.CombinedIndex.cfiFunctionDefs().getExportedThinLTOGUIDs();
2185 ExportedGUIDs.insert(first: Defs.begin(), last: Defs.end());
2186 auto Decls =
2187 ThinLTO.CombinedIndex.cfiFunctionDecls().getExportedThinLTOGUIDs();
2188 ExportedGUIDs.insert(first: Decls.begin(), last: Decls.end());
2189
2190 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
2191 const auto &ExportList = ExportLists.find(Val: ModuleIdentifier);
2192 return (ExportList != ExportLists.end() && ExportList->second.count(V: VI)) ||
2193 ExportedGUIDs.count(x: VI.getGUID());
2194 };
2195
2196 // Update local devirtualized targets that were exported by cross-module
2197 // importing or by other devirtualizations marked in the ExportedGUIDs set.
2198 updateIndexWPDForExports(Summary&: ThinLTO.CombinedIndex, isExported,
2199 LocalWPDTargetsMap, ExternallyVisibleSymbolNamesPtr);
2200
2201 if (ExternallyVisibleSymbolNamesPtr) {
2202 // Add to ExternallyVisibleSymbolNames the set of unique names used by all
2203 // externally visible symbols in the index.
2204 for (auto &I : ThinLTO.CombinedIndex) {
2205 ValueInfo VI = ThinLTO.CombinedIndex.getValueInfo(R: I);
2206 for (const auto &Summary : VI.getSummaryList()) {
2207 const GlobalValueSummary *Base = Summary->getBaseObject();
2208 if (GlobalValue::isLocalLinkage(Linkage: Base->linkage()))
2209 continue;
2210
2211 ExternallyVisibleSymbolNamesPtr->insert(V: VI.name());
2212 break;
2213 }
2214 }
2215 }
2216
2217 thinLTOInternalizeAndPromoteInIndex(Index&: ThinLTO.CombinedIndex, isExported,
2218 isPrevailing,
2219 ExternallyVisibleSymbolNamesPtr);
2220
2221 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
2222 GlobalValue::GUID GUID,
2223 GlobalValue::LinkageTypes NewLinkage) {
2224 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
2225 };
2226 thinLTOResolvePrevailingInIndex(C: Conf, Index&: ThinLTO.CombinedIndex, isPrevailing,
2227 recordNewLinkage, GUIDPreservedSymbols);
2228
2229 thinLTOPropagateFunctionAttrs(Index&: ThinLTO.CombinedIndex, isPrevailing);
2230
2231 generateParamAccessSummary(Index&: ThinLTO.CombinedIndex);
2232
2233 if (llvm::timeTraceProfilerEnabled())
2234 llvm::timeTraceProfilerEnd();
2235
2236 TimeTraceScopeExit.release();
2237
2238 auto &ModuleMap =
2239 ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
2240
2241 auto RunBackends = [&](ThinBackendProc *BackendProcess) -> Error {
2242 auto ProcessOneModule = [&](int I) -> Error {
2243 auto &Mod = *(ModuleMap.begin() + I);
2244 // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
2245 // combined module and parallel code generation partitions.
2246 return BackendProcess->start(
2247 Task: RegularLTO.ParallelCodeGenParallelismLevel + I, BM: Mod.second,
2248 ImportList: ImportLists[Mod.first], ExportList: ExportLists[Mod.first],
2249 ResolvedODR: ResolvedODR[Mod.first], ModuleMap&: ThinLTO.ModuleMap);
2250 };
2251
2252 BackendProcess->setup(ThinLTONumTasks: ModuleMap.size(),
2253 ThinLTOTaskOffset: RegularLTO.ParallelCodeGenParallelismLevel,
2254 Triple: RegularLTO.CombinedModule->getTargetTriple());
2255
2256 if (BackendProcess->getThreadCount() == 1 ||
2257 BackendProcess->isSensitiveToInputOrder()) {
2258 // Process the modules in the order they were provided on the
2259 // command-line. It is important for this codepath to be used for
2260 // WriteIndexesThinBackend, to ensure the emitted LinkedObjectsFile lists
2261 // ThinLTO objects in the same order as the inputs, which otherwise would
2262 // affect the final link order.
2263 for (int I = 0, E = ModuleMap.size(); I != E; ++I)
2264 if (Error E = ProcessOneModule(I))
2265 return E;
2266 } else {
2267 // When executing in parallel, process largest bitsize modules first to
2268 // improve parallelism, and avoid starving the thread pool near the end.
2269 // This saves about 15 sec on a 36-core machine while link `clang.exe`
2270 // (out of 100 sec).
2271 std::vector<BitcodeModule *> ModulesVec;
2272 ModulesVec.reserve(n: ModuleMap.size());
2273 for (auto &Mod : ModuleMap)
2274 ModulesVec.push_back(x: &Mod.second);
2275 for (int I : generateModulesOrdering(R: ModulesVec))
2276 if (Error E = ProcessOneModule(I))
2277 return E;
2278 }
2279 return BackendProcess->wait();
2280 };
2281
2282 if (!CodeGenDataThinLTOTwoRounds) {
2283 std::unique_ptr<ThinBackendProc> BackendProc =
2284 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2285 AddStream, Cache, BitcodeLibFuncs);
2286 return RunBackends(BackendProc.get());
2287 }
2288
2289 // Perform two rounds of code generation for ThinLTO:
2290 // 1. First round: Perform optimization and code generation, outputting to
2291 // temporary scratch objects.
2292 // 2. Merge code generation data extracted from the temporary scratch objects.
2293 // 3. Second round: Execute code generation again using the merged data.
2294 LLVM_DEBUG(dbgs() << "[TwoRounds] Initializing ThinLTO two-codegen rounds\n");
2295
2296 unsigned MaxTasks = getMaxTasks();
2297 auto Parallelism = ThinLTO.Backend.getParallelism();
2298 // Set up two additional streams and caches for storing temporary scratch
2299 // objects and optimized IRs, using the same cache directory as the original.
2300 cgdata::StreamCacheData CG(MaxTasks, Cache, "CG"), IR(MaxTasks, Cache, "IR");
2301
2302 // First round: Execute optimization and code generation, outputting to
2303 // temporary scratch objects. Serialize the optimized IRs before initiating
2304 // code generation.
2305 LLVM_DEBUG(dbgs() << "[TwoRounds] Running the first round of codegen\n");
2306 auto FirstRoundLTO = std::make_unique<FirstRoundThinBackend>(
2307 args&: Conf, args&: ThinLTO.CombinedIndex, args&: Parallelism, args&: ModuleToDefinedGVSummaries,
2308 args&: CG.AddStream, args&: CG.Cache, args&: BitcodeLibFuncs, args&: IR.AddStream, args&: IR.Cache);
2309 if (Error E = RunBackends(FirstRoundLTO.get()))
2310 return E;
2311
2312 LLVM_DEBUG(dbgs() << "[TwoRounds] Merging codegen data\n");
2313 auto CombinedHashOrErr = cgdata::mergeCodeGenData(ObjectFiles: *CG.getResult());
2314 if (Error E = CombinedHashOrErr.takeError())
2315 return E;
2316 auto CombinedHash = *CombinedHashOrErr;
2317 LLVM_DEBUG(dbgs() << "[TwoRounds] CGData hash: " << CombinedHash << "\n");
2318
2319 // Second round: Read the optimized IRs and execute code generation using the
2320 // merged data.
2321 LLVM_DEBUG(dbgs() << "[TwoRounds] Running the second round of codegen\n");
2322 auto SecondRoundLTO = std::make_unique<SecondRoundThinBackend>(
2323 args&: Conf, args&: ThinLTO.CombinedIndex, args&: Parallelism, args&: ModuleToDefinedGVSummaries,
2324 args&: AddStream, args&: Cache, args&: BitcodeLibFuncs, args: IR.getResult(), args&: CombinedHash);
2325 return RunBackends(SecondRoundLTO.get());
2326}
2327
2328Expected<LLVMRemarkFileHandle> lto::setupLLVMOptimizationRemarks(
2329 LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
2330 StringRef RemarksFormat, bool RemarksWithHotness,
2331 std::optional<uint64_t> RemarksHotnessThreshold, int Count) {
2332 std::string Filename = std::string(RemarksFilename);
2333 // For ThinLTO, file.opt.<format> becomes
2334 // file.opt.<format>.thin.<num>.<format>.
2335 if (!Filename.empty() && Count != -1)
2336 Filename =
2337 (Twine(Filename) + ".thin." + llvm::utostr(X: Count) + "." + RemarksFormat)
2338 .str();
2339
2340 auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
2341 Context, RemarksFilename: Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
2342 RemarksHotnessThreshold);
2343 if (Error E = ResultOrErr.takeError())
2344 return std::move(E);
2345
2346 if (*ResultOrErr)
2347 (*ResultOrErr)->keep();
2348
2349 return ResultOrErr;
2350}
2351
2352Expected<std::unique_ptr<ToolOutputFile>>
2353lto::setupStatsFile(StringRef StatsFilename) {
2354 // Setup output file to emit statistics.
2355 if (StatsFilename.empty())
2356 return nullptr;
2357
2358 llvm::EnableStatistics(DoPrintOnExit: false);
2359 std::error_code EC;
2360 auto StatsFile =
2361 std::make_unique<ToolOutputFile>(args&: StatsFilename, args&: EC, args: sys::fs::OF_None);
2362 if (EC)
2363 return errorCodeToError(EC);
2364
2365 StatsFile->keep();
2366 return std::move(StatsFile);
2367}
2368
2369// Compute the ordering we will process the inputs: the rough heuristic here
2370// is to sort them per size so that the largest module get schedule as soon as
2371// possible. This is purely a compile-time optimization.
2372std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) {
2373 auto Seq = llvm::seq<int>(Begin: 0, End: R.size());
2374 std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
2375 llvm::sort(C&: ModulesOrdering, Comp: [&](int LeftIndex, int RightIndex) {
2376 auto LSize = R[LeftIndex]->getBuffer().size();
2377 auto RSize = R[RightIndex]->getBuffer().size();
2378 return LSize > RSize;
2379 });
2380 return ModulesOrdering;
2381}
2382