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