1//===- ThinLTOBitcodeWriter.cpp - Bitcode writing pass for ThinLTO --------===//
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#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
10#include "llvm/Analysis/BasicAliasAnalysis.h"
11#include "llvm/Analysis/BlockFrequencyInfo.h"
12#include "llvm/Analysis/ModuleSummaryAnalysis.h"
13#include "llvm/Analysis/ProfileSummaryInfo.h"
14#include "llvm/Bitcode/BitcodeWriter.h"
15#include "llvm/IR/Constants.h"
16#include "llvm/IR/DebugInfo.h"
17#include "llvm/IR/Instructions.h"
18#include "llvm/IR/Intrinsics.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/ModuleSummaryIndex.h"
21#include "llvm/IR/PassManager.h"
22#include "llvm/Support/raw_ostream.h"
23#include "llvm/Transforms/IPO.h"
24#include "llvm/Transforms/IPO/FunctionAttrs.h"
25#include "llvm/Transforms/IPO/FunctionImport.h"
26#include "llvm/Transforms/IPO/LowerTypeTests.h"
27#include "llvm/Transforms/Utils/Cloning.h"
28#include "llvm/Transforms/Utils/ModuleUtils.h"
29using namespace llvm;
30
31namespace {
32
33// Promote each local-linkage entity defined by ExportM and used by ImportM by
34// changing visibility and appending ".llvm." + ModuleId (matching
35// ModuleSummaryIndex::getGlobalNameForLocal so downstream PGO, SamplePGO,
36// MemProf, and linker symbol canonicalization strip the promotion suffix).
37void promoteInternals(Module &ExportM, Module &ImportM, StringRef ModuleId,
38 SetVector<GlobalValue *> *PromoteExtra = nullptr) {
39 DenseMap<const Comdat *, Comdat *> RenamedComdats;
40 for (auto &ExportGV : ExportM.global_values()) {
41 if (!ExportGV.hasLocalLinkage())
42 continue;
43
44 auto Name = ExportGV.getName();
45 GlobalValue *ImportGV = nullptr;
46 const bool MustPromote = PromoteExtra && PromoteExtra->count(key: &ExportGV);
47 if (!MustPromote) {
48 ImportGV = ImportM.getNamedValue(Name);
49 if (!ImportGV)
50 continue;
51 ImportGV->removeDeadConstantUsers();
52 if (ImportGV->use_empty()) {
53 ImportGV->eraseFromParent();
54 continue;
55 }
56 }
57
58 std::string NewName =
59 ModuleSummaryIndex::getGlobalNameForLocal(Name, Suffix: ModuleId);
60
61 if (const auto *C = ExportGV.getComdat())
62 if (C->getName() == Name)
63 RenamedComdats.try_emplace(Key: C, Args: ExportM.getOrInsertComdat(Name: NewName));
64
65 Constant *Aliasee = &ExportGV;
66 while (auto *GA = dyn_cast<GlobalAlias>(Val: Aliasee))
67 Aliasee = GA->getAliasee();
68
69 // We must use the function's value type (FunctionType), not ptr - hence
70 // ExportGV.getValueType() rather than getType(). Otherwise, when an
71 // internal coroutine is imported into another module, IRMover sees a
72 // non-function value type for the unimported alias and materializes it as
73 // an external GlobalVariable rather than a Function declaration. That
74 // violates the verifier requirement that the coroutine argument of
75 // @llvm.coro.id must refer to a function. We could "pierce through" by
76 // stripping pointers, and cases other than coro do that, but this is
77 // cleaner.
78 auto *ExternalAlias = GlobalAlias::create(
79 Ty: ExportGV.getValueType(), AddressSpace: ExportGV.getAddressSpace(),
80 Linkage: GlobalValue::ExternalLinkage, Name: NewName, Aliasee, Parent: &ExportM);
81 ExternalAlias->setVisibility(GlobalValue::HiddenVisibility);
82
83 if (MustPromote) {
84 ExportGV.replaceUsesWithIf(
85 New: ExternalAlias, ShouldReplace: [](Use &U) { return !isa<GlobalAlias>(Val: U.getUser()); });
86 PromoteExtra->remove(X: &ExportGV);
87 PromoteExtra->insert(X: ExternalAlias);
88 }
89
90 if (ImportGV) {
91 ImportGV->setName(NewName);
92 ImportGV->setVisibility(GlobalValue::HiddenVisibility);
93 ImportGV->reassignGUID();
94 }
95 }
96
97 if (!RenamedComdats.empty())
98 for (auto &GO : ExportM.global_objects())
99 if (auto *C = GO.getComdat()) {
100 auto Replacement = RenamedComdats.find(Val: C);
101 if (Replacement != RenamedComdats.end())
102 GO.setComdat(Replacement->second);
103 }
104}
105
106// Promote all internal (i.e. distinct) type ids used by the module by replacing
107// them with external type ids formed using the module id.
108//
109// Note that this needs to be done before we clone the module because each clone
110// will receive its own set of distinct metadata nodes.
111void promoteTypeIds(Module &M, StringRef ModuleId) {
112 DenseMap<Metadata *, Metadata *> LocalToGlobal;
113 auto ExternalizeTypeId = [&](CallInst *CI, unsigned ArgNo) {
114 Metadata *MD =
115 cast<MetadataAsValue>(Val: CI->getArgOperand(i: ArgNo))->getMetadata();
116
117 if (isa<MDNode>(Val: MD) && cast<MDNode>(Val: MD)->isDistinct()) {
118 Metadata *&GlobalMD = LocalToGlobal[MD];
119 if (!GlobalMD) {
120 std::string NewName =
121 (Twine(LocalToGlobal.size()) + "." + ModuleId).str();
122 GlobalMD = MDString::get(Context&: M.getContext(), Str: NewName);
123 }
124
125 CI->setArgOperand(i: ArgNo,
126 v: MetadataAsValue::get(Context&: M.getContext(), MD: GlobalMD));
127 }
128 };
129
130 if (Function *TypeTestFunc =
131 Intrinsic::getDeclarationIfExists(M: &M, id: Intrinsic::type_test)) {
132 for (const Use &U : TypeTestFunc->uses()) {
133 auto CI = cast<CallInst>(Val: U.getUser());
134 ExternalizeTypeId(CI, 1);
135 }
136 }
137
138 if (Function *PublicTypeTestFunc =
139 Intrinsic::getDeclarationIfExists(M: &M, id: Intrinsic::public_type_test)) {
140 for (const Use &U : PublicTypeTestFunc->uses()) {
141 auto CI = cast<CallInst>(Val: U.getUser());
142 ExternalizeTypeId(CI, 1);
143 }
144 }
145
146 if (Function *TypeCheckedLoadFunc =
147 Intrinsic::getDeclarationIfExists(M: &M, id: Intrinsic::type_checked_load)) {
148 for (const Use &U : TypeCheckedLoadFunc->uses()) {
149 auto CI = cast<CallInst>(Val: U.getUser());
150 ExternalizeTypeId(CI, 2);
151 }
152 }
153
154 if (Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
155 M: &M, id: Intrinsic::type_checked_load_relative)) {
156 for (const Use &U : TypeCheckedLoadRelativeFunc->uses()) {
157 auto CI = cast<CallInst>(Val: U.getUser());
158 ExternalizeTypeId(CI, 2);
159 }
160 }
161
162 for (GlobalObject &GO : M.global_objects()) {
163 SmallVector<MDNode *, 1> MDs;
164 GO.getMetadata(KindID: LLVMContext::MD_type, MDs);
165
166 GO.eraseMetadata(KindID: LLVMContext::MD_type);
167 for (auto *MD : MDs) {
168 auto I = LocalToGlobal.find(Val: MD->getOperand(I: 1));
169 if (I == LocalToGlobal.end()) {
170 GO.addMetadata(KindID: LLVMContext::MD_type, MD&: *MD);
171 continue;
172 }
173 GO.addMetadata(
174 KindID: LLVMContext::MD_type,
175 MD&: *MDNode::get(Context&: M.getContext(), MDs: {MD->getOperand(I: 0), I->second}));
176 }
177
178 SmallVector<MDNode *, 1> CGMDs;
179 GO.getMetadata(KindID: LLVMContext::MD_callgraph, MDs&: CGMDs);
180
181 GO.eraseMetadata(KindID: LLVMContext::MD_callgraph);
182 for (auto *MD : CGMDs) {
183 if (MD->getNumOperands() == 1) {
184 auto I = LocalToGlobal.find(Val: MD->getOperand(I: 0));
185 if (I == LocalToGlobal.end()) {
186 GO.addMetadata(KindID: LLVMContext::MD_callgraph, MD&: *MD);
187 continue;
188 }
189 GO.addMetadata(KindID: LLVMContext::MD_callgraph,
190 MD&: *MDNode::get(Context&: M.getContext(), MDs: {I->second}));
191 }
192 }
193 }
194}
195
196// Drop unused globals, and drop type information from function declarations.
197// FIXME: If we made functions typeless then there would be no need to do this.
198void simplifyExternals(Module &M) {
199 FunctionType *EmptyFT =
200 FunctionType::get(Result: Type::getVoidTy(C&: M.getContext()), isVarArg: false);
201
202 for (Function &F : llvm::make_early_inc_range(Range&: M)) {
203 if (F.isDeclaration() && F.use_empty()) {
204 F.eraseFromParent();
205 continue;
206 }
207
208 if (!F.isDeclaration() || F.getFunctionType() == EmptyFT ||
209 // Changing the type of an intrinsic may invalidate the IR.
210 F.getName().starts_with(Prefix: "llvm."))
211 continue;
212
213 Function *NewF = Function::Create(Ty: EmptyFT, Linkage: GlobalValue::ExternalLinkage,
214 AddrSpace: F.getAddressSpace(), N: "", M: &M);
215 NewF->copyAttributesFrom(Src: &F);
216 // Only copy function attribtues.
217 NewF->setAttributes(AttributeList::get(C&: M.getContext(),
218 Index: AttributeList::FunctionIndex,
219 Attrs: F.getAttributes().getFnAttrs()));
220 NewF->takeName(V: &F);
221 NewF->setMetadata(KindID: LLVMContext::MD_guid,
222 Node: F.getMetadata(KindID: LLVMContext::MD_guid));
223 F.replaceAllUsesWith(V: NewF);
224 F.eraseFromParent();
225 }
226
227 for (GlobalIFunc &I : llvm::make_early_inc_range(Range: M.ifuncs())) {
228 if (I.use_empty())
229 I.eraseFromParent();
230 else
231 assert(I.getResolverFunction() && "ifunc misses its resolver function");
232 }
233
234 for (GlobalVariable &GV : llvm::make_early_inc_range(Range: M.globals())) {
235 if (GV.isDeclaration() && GV.use_empty()) {
236 GV.eraseFromParent();
237 continue;
238 }
239 }
240}
241
242static void
243filterModule(Module *M,
244 function_ref<bool(const GlobalValue *)> ShouldKeepDefinition) {
245 std::vector<GlobalValue *> V;
246 for (GlobalValue &GV : M->global_values())
247 if (!ShouldKeepDefinition(&GV))
248 V.push_back(x: &GV);
249
250 for (GlobalValue *GV : V)
251 if (!convertToDeclaration(GV&: *GV))
252 GV->eraseFromParent();
253}
254
255void forEachVirtualFunction(Constant *C, function_ref<void(Function *)> Fn) {
256 if (auto *F = dyn_cast<Function>(Val: C))
257 return Fn(F);
258 if (isa<GlobalValue>(Val: C))
259 return;
260 for (Value *Op : C->operands())
261 forEachVirtualFunction(C: cast<Constant>(Val: Op), Fn);
262}
263
264// Clone any @llvm[.compiler].used over to the new module and append
265// values whose defs were cloned into that module.
266static void cloneUsedGlobalVariables(const Module &SrcM, Module &DestM,
267 bool CompilerUsed) {
268 SmallVector<GlobalValue *, 4> Used, NewUsed;
269 // First collect those in the llvm[.compiler].used set.
270 collectUsedGlobalVariables(M: SrcM, Vec&: Used, CompilerUsed);
271 // Next build a set of the equivalent values defined in DestM.
272 for (auto *V : Used) {
273 auto *GV = DestM.getNamedValue(Name: V->getName());
274 if (GV && !GV->isDeclaration())
275 NewUsed.push_back(Elt: GV);
276 }
277 // Finally, add them to a llvm[.compiler].used variable in DestM.
278 if (CompilerUsed)
279 appendToCompilerUsed(M&: DestM, Values: NewUsed);
280 else
281 appendToUsed(M&: DestM, Values: NewUsed);
282}
283
284#ifndef NDEBUG
285static bool enableUnifiedLTO(Module &M) {
286 bool UnifiedLTO = false;
287 if (auto *MD =
288 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("UnifiedLTO")))
289 UnifiedLTO = MD->getZExtValue();
290 return UnifiedLTO;
291}
292#endif
293
294bool mustEmitToMergedModule(const GlobalValue *GV) {
295 // The __cfi_check definition is filled in by the CrossDSOCFI pass which
296 // runs only in the merged module.
297 return GV->getName() == "__cfi_check";
298}
299
300// If it's possible to split M into regular and thin LTO parts, do so and write
301// a multi-module bitcode file with the two parts to OS. Otherwise, write only a
302// regular LTO bitcode file to OS.
303void splitAndWriteThinLTOBitcode(
304 raw_ostream &OS, raw_ostream *ThinLinkOS,
305 function_ref<AAResults &(Function &)> AARGetter,
306 function_ref<const BlockFrequencyInfo &(Function &)> BFIGetter, Module &M,
307 const bool ShouldPreserveUseListOrder) {
308 std::string ModuleId = getUniqueModuleId(M: &M);
309 if (ModuleId.empty()) {
310 assert(!enableUnifiedLTO(M));
311 // We couldn't generate a module ID for this module, write it out as a
312 // regular LTO module with an index for summary-based dead stripping.
313 ProfileSummaryInfo PSI(M);
314 M.addModuleFlag(Behavior: Module::Error, Key: "ThinLTO", Val: uint32_t(0));
315 ModuleSummaryIndex Index = buildModuleSummaryIndex(M, GetBFICallback: nullptr, PSI: &PSI);
316 WriteBitcodeToFile(M, Out&: OS, ShouldPreserveUseListOrder, Index: &Index,
317 /*UnifiedLTO=*/GenerateHash: false);
318
319 if (ThinLinkOS)
320 // We don't have a ThinLTO part, but still write the module to the
321 // ThinLinkOS if requested so that the expected output file is produced.
322 WriteBitcodeToFile(M, Out&: *ThinLinkOS, ShouldPreserveUseListOrder, Index: &Index,
323 /*UnifiedLTO=*/GenerateHash: false);
324
325 return;
326 }
327
328 promoteTypeIds(M, ModuleId);
329
330 // Collect the set of virtual functions that are eligible for virtual constant
331 // propagation. Each eligible function must not access memory, must return
332 // an integer of width <=64 bits, must take at least one argument, must not
333 // use its first argument (assumed to be "this") and all arguments other than
334 // the first one must be of <=64 bit integer type.
335 //
336 // Note that we test whether this copy of the function is readnone, rather
337 // than testing function attributes, which must hold for any copy of the
338 // function, even a less optimized version substituted at link time. This is
339 // sound because the virtual constant propagation optimizations effectively
340 // inline all implementations of the virtual function into each call site,
341 // rather than using function attributes to perform local optimization.
342 DenseSet<const Function *> EligibleVirtualFns;
343 // If any member of a comdat lives in MergedM, put all members of that
344 // comdat in MergedM to keep the comdat together.
345 DenseSet<const Comdat *> MergedMComdats;
346 for (GlobalVariable &GV : M.globals())
347 if (!GV.isDeclaration() && lowertypetests::hasTypeMetadata(GO: GV)) {
348 if (const auto *C = GV.getComdat())
349 MergedMComdats.insert(V: C);
350 forEachVirtualFunction(C: GV.getInitializer(), Fn: [&](Function *F) {
351 auto *RT = dyn_cast<IntegerType>(Val: F->getReturnType());
352 if (!RT || RT->getBitWidth() > 64 || F->arg_empty() ||
353 !F->arg_begin()->use_empty())
354 return;
355 for (auto &Arg : drop_begin(RangeOrContainer: F->args())) {
356 auto *ArgT = dyn_cast<IntegerType>(Val: Arg.getType());
357 if (!ArgT || ArgT->getBitWidth() > 64)
358 return;
359 }
360 if (!F->isDeclaration() &&
361 computeFunctionBodyMemoryAccess(F&: *F, AAR&: AARGetter(*F))
362 .doesNotAccessMemory())
363 EligibleVirtualFns.insert(V: F);
364 });
365 }
366
367 ValueToValueMapTy VMap;
368 std::unique_ptr<Module> MergedM(
369 CloneModule(M, VMap, ShouldCloneDefinition: [&](const GlobalValue *GV) -> bool {
370 if (const auto *C = GV->getComdat())
371 if (MergedMComdats.count(V: C))
372 return true;
373 if (mustEmitToMergedModule(GV))
374 return true;
375 if (auto *F = dyn_cast<Function>(Val: GV))
376 return EligibleVirtualFns.count(V: F);
377 if (auto *GVar =
378 dyn_cast_or_null<GlobalVariable>(Val: GV->getAliaseeObject()))
379 return lowertypetests::hasTypeMetadata(GO: *GVar);
380 return false;
381 }));
382 StripDebugInfo(M&: *MergedM);
383 MergedM->removeModuleInlineAsm();
384
385 // Clone any llvm.*used globals to ensure the included values are
386 // not deleted.
387 cloneUsedGlobalVariables(SrcM: M, DestM&: *MergedM, /*CompilerUsed*/ false);
388 cloneUsedGlobalVariables(SrcM: M, DestM&: *MergedM, /*CompilerUsed*/ true);
389
390 for (Function &F : *MergedM)
391 if (!F.isDeclaration() && !mustEmitToMergedModule(GV: &F)) {
392 // Reset the linkage of all functions eligible for virtual constant
393 // propagation. The canonical definitions live in the thin LTO module so
394 // that they can be imported.
395 F.setLinkage(GlobalValue::AvailableExternallyLinkage);
396 F.setComdat(nullptr);
397 }
398
399 SetVector<GlobalValue *> CfiFunctions = lowertypetests::findCfiFunctions(M);
400
401 // Remove all globals with type metadata, globals with comdats that live in
402 // MergedM, and aliases pointing to such globals from the thin LTO module.
403 filterModule(M: &M, ShouldKeepDefinition: [&](const GlobalValue *GV) {
404 if (auto *GVar = dyn_cast_or_null<GlobalVariable>(Val: GV->getAliaseeObject()))
405 if (lowertypetests::hasTypeMetadata(GO: *GVar))
406 return false;
407 if (const auto *C = GV->getComdat())
408 if (MergedMComdats.count(V: C))
409 return false;
410 if (mustEmitToMergedModule(GV))
411 return false;
412 return true;
413 });
414
415 // CfiFunctions contains only symbols from M. promoteInternals tries to find
416 // match values from its first argument (the "exporting module") in
417 // CfiFunctions. So we only need CfiFunctions for the second promotion (M ->
418 // MergedM)
419 promoteInternals(ExportM&: *MergedM, ImportM&: M, ModuleId, PromoteExtra: nullptr);
420 promoteInternals(ExportM&: M, ImportM&: *MergedM, ModuleId, PromoteExtra: &CfiFunctions);
421
422 // FIXME: Try to re-use PSI from the original module here.
423 ProfileSummaryInfo PSI(M);
424
425 lowertypetests::createCfiMetadata(DestM&: *MergedM, SrcM: M, CfiFunctions: CfiFunctions.getArrayRef(),
426 PSI, BFIGetter);
427
428 simplifyExternals(M&: *MergedM);
429
430 // FIXME: Try to re-use BSI from the original module here.
431 ModuleSummaryIndex Index = buildModuleSummaryIndex(M, GetBFICallback: nullptr, PSI: &PSI);
432
433 // Mark the merged module as requiring full LTO. We still want an index for
434 // it though, so that it can participate in summary-based dead stripping.
435 MergedM->addModuleFlag(Behavior: Module::Error, Key: "ThinLTO", Val: uint32_t(0));
436 ModuleSummaryIndex MergedMIndex =
437 buildModuleSummaryIndex(M: *MergedM, GetBFICallback: nullptr, PSI: &PSI);
438
439 SmallVector<char, 0> Buffer;
440
441 BitcodeWriter W(Buffer);
442 // Save the module hash produced for the full bitcode, which will
443 // be used in the backends, and use that in the minimized bitcode
444 // produced for the full link.
445 ModuleHash ModHash = {._M_elems: {0}};
446 W.writeModule(M, ShouldPreserveUseListOrder, Index: &Index,
447 /*GenerateHash=*/true, ModHash: &ModHash);
448 W.writeModule(M: *MergedM, ShouldPreserveUseListOrder, Index: &MergedMIndex);
449 W.writeSymtab();
450 W.writeStrtab();
451 OS << Buffer;
452
453 // If a minimized bitcode module was requested for the thin link, only
454 // the information that is needed by thin link will be written in the
455 // given OS (the merged module will be written as usual).
456 if (ThinLinkOS) {
457 Buffer.clear();
458 BitcodeWriter W2(Buffer);
459 StripDebugInfo(M);
460 W2.writeThinLinkBitcode(M, Index, ModHash);
461 W2.writeModule(M: *MergedM, /*ShouldPreserveUseListOrder=*/false,
462 Index: &MergedMIndex);
463 W2.writeSymtab();
464 W2.writeStrtab();
465 *ThinLinkOS << Buffer;
466 }
467}
468
469// Check if the LTO Unit splitting has been enabled.
470bool enableSplitLTOUnit(Module &M) {
471 bool EnableSplitLTOUnit = false;
472 if (auto *MD = mdconst::extract_or_null<ConstantInt>(
473 MD: M.getModuleFlag(Key: "EnableSplitLTOUnit")))
474 EnableSplitLTOUnit = MD->getZExtValue();
475 return EnableSplitLTOUnit;
476}
477
478// Returns whether this module needs to be split (if splitting is enabled).
479bool requiresSplit(Module &M) {
480 for (auto &GO : M.global_objects()) {
481 if (GO.hasMetadata(KindID: LLVMContext::MD_type))
482 return true;
483 if (mustEmitToMergedModule(GV: &GO))
484 return true;
485 }
486 return false;
487}
488
489bool writeThinLTOBitcode(
490 raw_ostream &OS, raw_ostream *ThinLinkOS,
491 function_ref<AAResults &(Function &)> AARGetter,
492 function_ref<const BlockFrequencyInfo &(Function &)> BFIGetter, Module &M,
493 const ModuleSummaryIndex *Index, const bool ShouldPreserveUseListOrder) {
494 std::unique_ptr<ModuleSummaryIndex> NewIndex = nullptr;
495 // See if this module needs to be split. If so, we try to split it
496 // or at least promote type ids to enable WPD.
497 if (requiresSplit(M)) {
498 if (enableSplitLTOUnit(M)) {
499 splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, BFIGetter, M,
500 ShouldPreserveUseListOrder);
501 return true;
502 }
503 // Promote type ids as needed for index-based WPD.
504 std::string ModuleId = getUniqueModuleId(M: &M);
505 if (!ModuleId.empty()) {
506 promoteTypeIds(M, ModuleId);
507 // Need to rebuild the index so that it contains type metadata
508 // for the newly promoted type ids.
509 // FIXME: Probably should not bother building the index at all
510 // in the caller of writeThinLTOBitcode (which does so via the
511 // ModuleSummaryIndexAnalysis pass), since we have to rebuild it
512 // anyway whenever there is type metadata (here or in
513 // splitAndWriteThinLTOBitcode). Just always build it once via the
514 // buildModuleSummaryIndex when Module(s) are ready.
515 ProfileSummaryInfo PSI(M);
516 NewIndex = std::make_unique<ModuleSummaryIndex>(
517 args: buildModuleSummaryIndex(M, GetBFICallback: nullptr, PSI: &PSI));
518 Index = NewIndex.get();
519 }
520 }
521
522 // Write it out as an unsplit ThinLTO module.
523
524 // Save the module hash produced for the full bitcode, which will
525 // be used in the backends, and use that in the minimized bitcode
526 // produced for the full link.
527 ModuleHash ModHash = {._M_elems: {0}};
528 WriteBitcodeToFile(M, Out&: OS, ShouldPreserveUseListOrder, Index,
529 /*GenerateHash=*/true, ModHash: &ModHash);
530 // If a minimized bitcode module was requested for the thin link, only
531 // the information that is needed by thin link will be written in the
532 // given OS.
533 if (ThinLinkOS && Index)
534 writeThinLinkBitcodeToFile(M, Out&: *ThinLinkOS, Index: *Index, ModHash);
535 return false;
536}
537
538} // anonymous namespace
539
540PreservedAnalyses
541llvm::ThinLTOBitcodeWriterPass::run(Module &M, ModuleAnalysisManager &AM) {
542 FunctionAnalysisManager &FAM =
543 AM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
544
545 bool Changed = writeThinLTOBitcode(
546 OS, ThinLinkOS,
547 AARGetter: [&FAM](Function &F) -> AAResults & {
548 return FAM.getResult<AAManager>(IR&: F);
549 },
550 BFIGetter: [&FAM](Function &F) -> const BlockFrequencyInfo & {
551 return FAM.getResult<BlockFrequencyAnalysis>(IR&: F);
552 },
553 M, Index: &AM.getResult<ModuleSummaryIndexAnalysis>(IR&: M),
554 ShouldPreserveUseListOrder);
555
556 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
557}
558