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