11398a32eSPeter Collingbourne //===- ThinLTOBitcodeWriter.cpp - Bitcode writing pass for ThinLTO --------===//
21398a32eSPeter Collingbourne //
31398a32eSPeter Collingbourne //                     The LLVM Compiler Infrastructure
41398a32eSPeter Collingbourne //
51398a32eSPeter Collingbourne // This file is distributed under the University of Illinois Open Source
61398a32eSPeter Collingbourne // License. See LICENSE.TXT for details.
71398a32eSPeter Collingbourne //
81398a32eSPeter Collingbourne //===----------------------------------------------------------------------===//
91398a32eSPeter Collingbourne 
106b411418STim Shen #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
11002c2d53SPeter Collingbourne #include "llvm/Analysis/BasicAliasAnalysis.h"
121398a32eSPeter Collingbourne #include "llvm/Analysis/ModuleSummaryAnalysis.h"
1394624acaSTeresa Johnson #include "llvm/Analysis/ProfileSummaryInfo.h"
141398a32eSPeter Collingbourne #include "llvm/Analysis/TypeMetadataUtils.h"
151398a32eSPeter Collingbourne #include "llvm/Bitcode/BitcodeWriter.h"
161398a32eSPeter Collingbourne #include "llvm/IR/Constants.h"
1728ffd326SPeter Collingbourne #include "llvm/IR/DebugInfo.h"
181398a32eSPeter Collingbourne #include "llvm/IR/Intrinsics.h"
191398a32eSPeter Collingbourne #include "llvm/IR/Module.h"
201398a32eSPeter Collingbourne #include "llvm/IR/PassManager.h"
211398a32eSPeter Collingbourne #include "llvm/Pass.h"
220c6a4ff8STeresa Johnson #include "llvm/Support/FileSystem.h"
231398a32eSPeter Collingbourne #include "llvm/Support/ScopedPrinter.h"
240c6a4ff8STeresa Johnson #include "llvm/Support/raw_ostream.h"
250c6a4ff8STeresa Johnson #include "llvm/Transforms/IPO.h"
26002c2d53SPeter Collingbourne #include "llvm/Transforms/IPO/FunctionAttrs.h"
271398a32eSPeter Collingbourne #include "llvm/Transforms/Utils/Cloning.h"
28964f4663SEvgeniy Stepanov #include "llvm/Transforms/Utils/ModuleUtils.h"
291398a32eSPeter Collingbourne using namespace llvm;
301398a32eSPeter Collingbourne 
311398a32eSPeter Collingbourne namespace {
321398a32eSPeter Collingbourne 
331398a32eSPeter Collingbourne // Promote each local-linkage entity defined by ExportM and used by ImportM by
341398a32eSPeter Collingbourne // changing visibility and appending the given ModuleId.
351398a32eSPeter Collingbourne void promoteInternals(Module &ExportM, Module &ImportM, StringRef ModuleId) {
364075ccc7SBob Haarman   DenseMap<const Comdat *, Comdat *> RenamedComdats;
376b193966SPeter Collingbourne   for (auto &ExportGV : ExportM.global_values()) {
381398a32eSPeter Collingbourne     if (!ExportGV.hasLocalLinkage())
396b193966SPeter Collingbourne       continue;
401398a32eSPeter Collingbourne 
414075ccc7SBob Haarman     auto Name = ExportGV.getName();
424075ccc7SBob Haarman     GlobalValue *ImportGV = ImportM.getNamedValue(Name);
431398a32eSPeter Collingbourne     if (!ImportGV || ImportGV->use_empty())
446b193966SPeter Collingbourne       continue;
451398a32eSPeter Collingbourne 
464075ccc7SBob Haarman     std::string NewName = (Name + ModuleId).str();
474075ccc7SBob Haarman 
484075ccc7SBob Haarman     if (const auto *C = ExportGV.getComdat())
494075ccc7SBob Haarman       if (C->getName() == Name)
504075ccc7SBob Haarman         RenamedComdats.try_emplace(C, ExportM.getOrInsertComdat(NewName));
511398a32eSPeter Collingbourne 
521398a32eSPeter Collingbourne     ExportGV.setName(NewName);
531398a32eSPeter Collingbourne     ExportGV.setLinkage(GlobalValue::ExternalLinkage);
541398a32eSPeter Collingbourne     ExportGV.setVisibility(GlobalValue::HiddenVisibility);
551398a32eSPeter Collingbourne 
561398a32eSPeter Collingbourne     ImportGV->setName(NewName);
571398a32eSPeter Collingbourne     ImportGV->setVisibility(GlobalValue::HiddenVisibility);
586b193966SPeter Collingbourne   }
594075ccc7SBob Haarman 
604075ccc7SBob Haarman   if (!RenamedComdats.empty())
614075ccc7SBob Haarman     for (auto &GO : ExportM.global_objects())
624075ccc7SBob Haarman       if (auto *C = GO.getComdat()) {
634075ccc7SBob Haarman         auto Replacement = RenamedComdats.find(C);
644075ccc7SBob Haarman         if (Replacement != RenamedComdats.end())
654075ccc7SBob Haarman           GO.setComdat(Replacement->second);
664075ccc7SBob Haarman       }
671398a32eSPeter Collingbourne }
681398a32eSPeter Collingbourne 
691398a32eSPeter Collingbourne // Promote all internal (i.e. distinct) type ids used by the module by replacing
701398a32eSPeter Collingbourne // them with external type ids formed using the module id.
711398a32eSPeter Collingbourne //
721398a32eSPeter Collingbourne // Note that this needs to be done before we clone the module because each clone
731398a32eSPeter Collingbourne // will receive its own set of distinct metadata nodes.
741398a32eSPeter Collingbourne void promoteTypeIds(Module &M, StringRef ModuleId) {
751398a32eSPeter Collingbourne   DenseMap<Metadata *, Metadata *> LocalToGlobal;
761398a32eSPeter Collingbourne   auto ExternalizeTypeId = [&](CallInst *CI, unsigned ArgNo) {
771398a32eSPeter Collingbourne     Metadata *MD =
781398a32eSPeter Collingbourne         cast<MetadataAsValue>(CI->getArgOperand(ArgNo))->getMetadata();
791398a32eSPeter Collingbourne 
801398a32eSPeter Collingbourne     if (isa<MDNode>(MD) && cast<MDNode>(MD)->isDistinct()) {
811398a32eSPeter Collingbourne       Metadata *&GlobalMD = LocalToGlobal[MD];
821398a32eSPeter Collingbourne       if (!GlobalMD) {
831398a32eSPeter Collingbourne         std::string NewName =
841398a32eSPeter Collingbourne             (to_string(LocalToGlobal.size()) + ModuleId).str();
851398a32eSPeter Collingbourne         GlobalMD = MDString::get(M.getContext(), NewName);
861398a32eSPeter Collingbourne       }
871398a32eSPeter Collingbourne 
881398a32eSPeter Collingbourne       CI->setArgOperand(ArgNo,
891398a32eSPeter Collingbourne                         MetadataAsValue::get(M.getContext(), GlobalMD));
901398a32eSPeter Collingbourne     }
911398a32eSPeter Collingbourne   };
921398a32eSPeter Collingbourne 
931398a32eSPeter Collingbourne   if (Function *TypeTestFunc =
941398a32eSPeter Collingbourne           M.getFunction(Intrinsic::getName(Intrinsic::type_test))) {
951398a32eSPeter Collingbourne     for (const Use &U : TypeTestFunc->uses()) {
961398a32eSPeter Collingbourne       auto CI = cast<CallInst>(U.getUser());
971398a32eSPeter Collingbourne       ExternalizeTypeId(CI, 1);
981398a32eSPeter Collingbourne     }
991398a32eSPeter Collingbourne   }
1001398a32eSPeter Collingbourne 
1011398a32eSPeter Collingbourne   if (Function *TypeCheckedLoadFunc =
1021398a32eSPeter Collingbourne           M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load))) {
1031398a32eSPeter Collingbourne     for (const Use &U : TypeCheckedLoadFunc->uses()) {
1041398a32eSPeter Collingbourne       auto CI = cast<CallInst>(U.getUser());
1051398a32eSPeter Collingbourne       ExternalizeTypeId(CI, 2);
1061398a32eSPeter Collingbourne     }
1071398a32eSPeter Collingbourne   }
1081398a32eSPeter Collingbourne 
1091398a32eSPeter Collingbourne   for (GlobalObject &GO : M.global_objects()) {
1101398a32eSPeter Collingbourne     SmallVector<MDNode *, 1> MDs;
1111398a32eSPeter Collingbourne     GO.getMetadata(LLVMContext::MD_type, MDs);
1121398a32eSPeter Collingbourne 
1131398a32eSPeter Collingbourne     GO.eraseMetadata(LLVMContext::MD_type);
1141398a32eSPeter Collingbourne     for (auto MD : MDs) {
1151398a32eSPeter Collingbourne       auto I = LocalToGlobal.find(MD->getOperand(1));
1161398a32eSPeter Collingbourne       if (I == LocalToGlobal.end()) {
1171398a32eSPeter Collingbourne         GO.addMetadata(LLVMContext::MD_type, *MD);
1181398a32eSPeter Collingbourne         continue;
1191398a32eSPeter Collingbourne       }
1201398a32eSPeter Collingbourne       GO.addMetadata(
1211398a32eSPeter Collingbourne           LLVMContext::MD_type,
1221398a32eSPeter Collingbourne           *MDNode::get(M.getContext(),
1231398a32eSPeter Collingbourne                        ArrayRef<Metadata *>{MD->getOperand(0), I->second}));
1241398a32eSPeter Collingbourne     }
1251398a32eSPeter Collingbourne   }
1261398a32eSPeter Collingbourne }
1271398a32eSPeter Collingbourne 
1281398a32eSPeter Collingbourne // Drop unused globals, and drop type information from function declarations.
1291398a32eSPeter Collingbourne // FIXME: If we made functions typeless then there would be no need to do this.
1301398a32eSPeter Collingbourne void simplifyExternals(Module &M) {
1311398a32eSPeter Collingbourne   FunctionType *EmptyFT =
1321398a32eSPeter Collingbourne       FunctionType::get(Type::getVoidTy(M.getContext()), false);
1331398a32eSPeter Collingbourne 
1341398a32eSPeter Collingbourne   for (auto I = M.begin(), E = M.end(); I != E;) {
1351398a32eSPeter Collingbourne     Function &F = *I++;
1361398a32eSPeter Collingbourne     if (F.isDeclaration() && F.use_empty()) {
1371398a32eSPeter Collingbourne       F.eraseFromParent();
1381398a32eSPeter Collingbourne       continue;
1391398a32eSPeter Collingbourne     }
1401398a32eSPeter Collingbourne 
1411398a32eSPeter Collingbourne     if (!F.isDeclaration() || F.getFunctionType() == EmptyFT)
1421398a32eSPeter Collingbourne       continue;
1431398a32eSPeter Collingbourne 
1441398a32eSPeter Collingbourne     Function *NewF =
1451398a32eSPeter Collingbourne         Function::Create(EmptyFT, GlobalValue::ExternalLinkage, "", &M);
1461398a32eSPeter Collingbourne     NewF->setVisibility(F.getVisibility());
1471398a32eSPeter Collingbourne     NewF->takeName(&F);
1481398a32eSPeter Collingbourne     F.replaceAllUsesWith(ConstantExpr::getBitCast(NewF, F.getType()));
1491398a32eSPeter Collingbourne     F.eraseFromParent();
1501398a32eSPeter Collingbourne   }
1511398a32eSPeter Collingbourne 
1521398a32eSPeter Collingbourne   for (auto I = M.global_begin(), E = M.global_end(); I != E;) {
1531398a32eSPeter Collingbourne     GlobalVariable &GV = *I++;
1541398a32eSPeter Collingbourne     if (GV.isDeclaration() && GV.use_empty()) {
1551398a32eSPeter Collingbourne       GV.eraseFromParent();
1561398a32eSPeter Collingbourne       continue;
1571398a32eSPeter Collingbourne     }
1581398a32eSPeter Collingbourne   }
1591398a32eSPeter Collingbourne }
1601398a32eSPeter Collingbourne 
1611398a32eSPeter Collingbourne void filterModule(
162061f4a5fSBenjamin Kramer     Module *M, function_ref<bool(const GlobalValue *)> ShouldKeepDefinition) {
1636de81347SBob Haarman   for (Module::alias_iterator I = M->alias_begin(), E = M->alias_end();
1646de81347SBob Haarman        I != E;) {
1656de81347SBob Haarman     GlobalAlias *GA = &*I++;
1666de81347SBob Haarman     if (ShouldKeepDefinition(GA))
1676de81347SBob Haarman       continue;
1686de81347SBob Haarman 
1696de81347SBob Haarman     GlobalObject *GO;
1706de81347SBob Haarman     if (GA->getValueType()->isFunctionTy())
1716de81347SBob Haarman       GO = Function::Create(cast<FunctionType>(GA->getValueType()),
1726de81347SBob Haarman                             GlobalValue::ExternalLinkage, "", M);
1736de81347SBob Haarman     else
1746de81347SBob Haarman       GO = new GlobalVariable(
1756de81347SBob Haarman           *M, GA->getValueType(), false, GlobalValue::ExternalLinkage,
176f4dc59baSSerge Guelton           nullptr, "", nullptr,
1776de81347SBob Haarman           GA->getThreadLocalMode(), GA->getType()->getAddressSpace());
1786de81347SBob Haarman     GO->takeName(GA);
1796de81347SBob Haarman     GA->replaceAllUsesWith(GO);
1806de81347SBob Haarman     GA->eraseFromParent();
1816de81347SBob Haarman   }
1826de81347SBob Haarman 
1831398a32eSPeter Collingbourne   for (Function &F : *M) {
1841398a32eSPeter Collingbourne     if (ShouldKeepDefinition(&F))
1851398a32eSPeter Collingbourne       continue;
1861398a32eSPeter Collingbourne 
1871398a32eSPeter Collingbourne     F.deleteBody();
18820a00933SPeter Collingbourne     F.setComdat(nullptr);
1891398a32eSPeter Collingbourne     F.clearMetadata();
1901398a32eSPeter Collingbourne   }
1911398a32eSPeter Collingbourne 
1921398a32eSPeter Collingbourne   for (GlobalVariable &GV : M->globals()) {
1931398a32eSPeter Collingbourne     if (ShouldKeepDefinition(&GV))
1941398a32eSPeter Collingbourne       continue;
1951398a32eSPeter Collingbourne 
1961398a32eSPeter Collingbourne     GV.setInitializer(nullptr);
1971398a32eSPeter Collingbourne     GV.setLinkage(GlobalValue::ExternalLinkage);
19820a00933SPeter Collingbourne     GV.setComdat(nullptr);
1991398a32eSPeter Collingbourne     GV.clearMetadata();
2001398a32eSPeter Collingbourne   }
2011398a32eSPeter Collingbourne }
2021398a32eSPeter Collingbourne 
203002c2d53SPeter Collingbourne void forEachVirtualFunction(Constant *C, function_ref<void(Function *)> Fn) {
204002c2d53SPeter Collingbourne   if (auto *F = dyn_cast<Function>(C))
205002c2d53SPeter Collingbourne     return Fn(F);
2063baa72afSPeter Collingbourne   if (isa<GlobalValue>(C))
2073baa72afSPeter Collingbourne     return;
208002c2d53SPeter Collingbourne   for (Value *Op : C->operands())
209002c2d53SPeter Collingbourne     forEachVirtualFunction(cast<Constant>(Op), Fn);
210002c2d53SPeter Collingbourne }
211002c2d53SPeter Collingbourne 
2121398a32eSPeter Collingbourne // If it's possible to split M into regular and thin LTO parts, do so and write
2131398a32eSPeter Collingbourne // a multi-module bitcode file with the two parts to OS. Otherwise, write only a
2141398a32eSPeter Collingbourne // regular LTO bitcode file to OS.
215002c2d53SPeter Collingbourne void splitAndWriteThinLTOBitcode(
2160c6a4ff8STeresa Johnson     raw_ostream &OS, raw_ostream *ThinLinkOS,
2170c6a4ff8STeresa Johnson     function_ref<AAResults &(Function &)> AARGetter, Module &M) {
218964f4663SEvgeniy Stepanov   std::string ModuleId = getUniqueModuleId(&M);
2191398a32eSPeter Collingbourne   if (ModuleId.empty()) {
2201398a32eSPeter Collingbourne     // We couldn't generate a module ID for this module, just write it out as a
2211398a32eSPeter Collingbourne     // regular LTO module.
2221398a32eSPeter Collingbourne     WriteBitcodeToFile(&M, OS);
2230c6a4ff8STeresa Johnson     if (ThinLinkOS)
2240c6a4ff8STeresa Johnson       // We don't have a ThinLTO part, but still write the module to the
2250c6a4ff8STeresa Johnson       // ThinLinkOS if requested so that the expected output file is produced.
2260c6a4ff8STeresa Johnson       WriteBitcodeToFile(&M, *ThinLinkOS);
2271398a32eSPeter Collingbourne     return;
2281398a32eSPeter Collingbourne   }
2291398a32eSPeter Collingbourne 
2301398a32eSPeter Collingbourne   promoteTypeIds(M, ModuleId);
2311398a32eSPeter Collingbourne 
232002c2d53SPeter Collingbourne   // Returns whether a global has attached type metadata. Such globals may
233002c2d53SPeter Collingbourne   // participate in CFI or whole-program devirtualization, so they need to
234002c2d53SPeter Collingbourne   // appear in the merged module instead of the thin LTO module.
235002c2d53SPeter Collingbourne   auto HasTypeMetadata = [&](const GlobalObject *GO) {
2361398a32eSPeter Collingbourne     SmallVector<MDNode *, 1> MDs;
237002c2d53SPeter Collingbourne     GO->getMetadata(LLVMContext::MD_type, MDs);
2381398a32eSPeter Collingbourne     return !MDs.empty();
2391398a32eSPeter Collingbourne   };
2401398a32eSPeter Collingbourne 
241002c2d53SPeter Collingbourne   // Collect the set of virtual functions that are eligible for virtual constant
242002c2d53SPeter Collingbourne   // propagation. Each eligible function must not access memory, must return
243002c2d53SPeter Collingbourne   // an integer of width <=64 bits, must take at least one argument, must not
244002c2d53SPeter Collingbourne   // use its first argument (assumed to be "this") and all arguments other than
245002c2d53SPeter Collingbourne   // the first one must be of <=64 bit integer type.
246002c2d53SPeter Collingbourne   //
247002c2d53SPeter Collingbourne   // Note that we test whether this copy of the function is readnone, rather
248002c2d53SPeter Collingbourne   // than testing function attributes, which must hold for any copy of the
249002c2d53SPeter Collingbourne   // function, even a less optimized version substituted at link time. This is
250002c2d53SPeter Collingbourne   // sound because the virtual constant propagation optimizations effectively
251002c2d53SPeter Collingbourne   // inline all implementations of the virtual function into each call site,
252002c2d53SPeter Collingbourne   // rather than using function attributes to perform local optimization.
253002c2d53SPeter Collingbourne   std::set<const Function *> EligibleVirtualFns;
2544075ccc7SBob Haarman   // If any member of a comdat lives in MergedM, put all members of that
2554075ccc7SBob Haarman   // comdat in MergedM to keep the comdat together.
2564075ccc7SBob Haarman   DenseSet<const Comdat *> MergedMComdats;
257002c2d53SPeter Collingbourne   for (GlobalVariable &GV : M.globals())
2584075ccc7SBob Haarman     if (HasTypeMetadata(&GV)) {
2594075ccc7SBob Haarman       if (const auto *C = GV.getComdat())
2604075ccc7SBob Haarman         MergedMComdats.insert(C);
261002c2d53SPeter Collingbourne       forEachVirtualFunction(GV.getInitializer(), [&](Function *F) {
262002c2d53SPeter Collingbourne         auto *RT = dyn_cast<IntegerType>(F->getReturnType());
263002c2d53SPeter Collingbourne         if (!RT || RT->getBitWidth() > 64 || F->arg_empty() ||
264002c2d53SPeter Collingbourne             !F->arg_begin()->use_empty())
265002c2d53SPeter Collingbourne           return;
266002c2d53SPeter Collingbourne         for (auto &Arg : make_range(std::next(F->arg_begin()), F->arg_end())) {
267002c2d53SPeter Collingbourne           auto *ArgT = dyn_cast<IntegerType>(Arg.getType());
268002c2d53SPeter Collingbourne           if (!ArgT || ArgT->getBitWidth() > 64)
269002c2d53SPeter Collingbourne             return;
270002c2d53SPeter Collingbourne         }
271002c2d53SPeter Collingbourne         if (computeFunctionBodyMemoryAccess(*F, AARGetter(*F)) == MAK_ReadNone)
272002c2d53SPeter Collingbourne           EligibleVirtualFns.insert(F);
273002c2d53SPeter Collingbourne       });
2744075ccc7SBob Haarman     }
275002c2d53SPeter Collingbourne 
2761398a32eSPeter Collingbourne   ValueToValueMapTy VMap;
277002c2d53SPeter Collingbourne   std::unique_ptr<Module> MergedM(
278002c2d53SPeter Collingbourne       CloneModule(&M, VMap, [&](const GlobalValue *GV) -> bool {
2794075ccc7SBob Haarman         if (const auto *C = GV->getComdat())
2804075ccc7SBob Haarman           if (MergedMComdats.count(C))
2814075ccc7SBob Haarman             return true;
282002c2d53SPeter Collingbourne         if (auto *F = dyn_cast<Function>(GV))
283002c2d53SPeter Collingbourne           return EligibleVirtualFns.count(F);
284002c2d53SPeter Collingbourne         if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
285002c2d53SPeter Collingbourne           return HasTypeMetadata(GVar);
286002c2d53SPeter Collingbourne         return false;
287002c2d53SPeter Collingbourne       }));
28828ffd326SPeter Collingbourne   StripDebugInfo(*MergedM);
2891398a32eSPeter Collingbourne 
290002c2d53SPeter Collingbourne   for (Function &F : *MergedM)
291002c2d53SPeter Collingbourne     if (!F.isDeclaration()) {
292002c2d53SPeter Collingbourne       // Reset the linkage of all functions eligible for virtual constant
293002c2d53SPeter Collingbourne       // propagation. The canonical definitions live in the thin LTO module so
294002c2d53SPeter Collingbourne       // that they can be imported.
295002c2d53SPeter Collingbourne       F.setLinkage(GlobalValue::AvailableExternallyLinkage);
296002c2d53SPeter Collingbourne       F.setComdat(nullptr);
297002c2d53SPeter Collingbourne     }
298002c2d53SPeter Collingbourne 
2994075ccc7SBob Haarman   // Remove all globals with type metadata, globals with comdats that live in
3004075ccc7SBob Haarman   // MergedM, and aliases pointing to such globals from the thin LTO module.
301002c2d53SPeter Collingbourne   filterModule(&M, [&](const GlobalValue *GV) {
302002c2d53SPeter Collingbourne     if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
3034075ccc7SBob Haarman       if (HasTypeMetadata(GVar))
3044075ccc7SBob Haarman         return false;
3054075ccc7SBob Haarman     if (const auto *C = GV->getComdat())
3064075ccc7SBob Haarman       if (MergedMComdats.count(C))
3074075ccc7SBob Haarman         return false;
308002c2d53SPeter Collingbourne     return true;
309002c2d53SPeter Collingbourne   });
3101398a32eSPeter Collingbourne 
3111398a32eSPeter Collingbourne   promoteInternals(*MergedM, M, ModuleId);
3121398a32eSPeter Collingbourne   promoteInternals(M, *MergedM, ModuleId);
3131398a32eSPeter Collingbourne 
3141398a32eSPeter Collingbourne   simplifyExternals(*MergedM);
3151398a32eSPeter Collingbourne 
3161398a32eSPeter Collingbourne 
3171398a32eSPeter Collingbourne   // FIXME: Try to re-use BSI and PFI from the original module here.
31894624acaSTeresa Johnson   ProfileSummaryInfo PSI(M);
31994624acaSTeresa Johnson   ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
3200c6a4ff8STeresa Johnson 
321*e357fbd2SPeter Collingbourne   // Mark the merged module as requiring full LTO. We still want an index for
322*e357fbd2SPeter Collingbourne   // it though, so that it can participate in summary-based dead stripping.
323*e357fbd2SPeter Collingbourne   MergedM->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
324*e357fbd2SPeter Collingbourne   ModuleSummaryIndex MergedMIndex =
325*e357fbd2SPeter Collingbourne       buildModuleSummaryIndex(*MergedM, nullptr, &PSI);
326*e357fbd2SPeter Collingbourne 
3270c6a4ff8STeresa Johnson   SmallVector<char, 0> Buffer;
3280c6a4ff8STeresa Johnson 
3290c6a4ff8STeresa Johnson   BitcodeWriter W(Buffer);
3300c6a4ff8STeresa Johnson   // Save the module hash produced for the full bitcode, which will
3310c6a4ff8STeresa Johnson   // be used in the backends, and use that in the minimized bitcode
3320c6a4ff8STeresa Johnson   // produced for the full link.
3330c6a4ff8STeresa Johnson   ModuleHash ModHash = {{0}};
3341398a32eSPeter Collingbourne   W.writeModule(&M, /*ShouldPreserveUseListOrder=*/false, &Index,
3350c6a4ff8STeresa Johnson                 /*GenerateHash=*/true, &ModHash);
336*e357fbd2SPeter Collingbourne   W.writeModule(MergedM.get(), /*ShouldPreserveUseListOrder=*/false,
337*e357fbd2SPeter Collingbourne                 &MergedMIndex);
338a0f371a1SPeter Collingbourne   W.writeStrtab();
3391398a32eSPeter Collingbourne   OS << Buffer;
3400c6a4ff8STeresa Johnson 
3410c6a4ff8STeresa Johnson   // If a minimized bitcode module was requested for the thin link,
3420c6a4ff8STeresa Johnson   // strip the debug info (the merged module was already stripped above)
3430c6a4ff8STeresa Johnson   // and write it to the given OS.
3440c6a4ff8STeresa Johnson   if (ThinLinkOS) {
3450c6a4ff8STeresa Johnson     Buffer.clear();
3460c6a4ff8STeresa Johnson     BitcodeWriter W2(Buffer);
3470c6a4ff8STeresa Johnson     StripDebugInfo(M);
3480c6a4ff8STeresa Johnson     W2.writeModule(&M, /*ShouldPreserveUseListOrder=*/false, &Index,
3490c6a4ff8STeresa Johnson                    /*GenerateHash=*/false, &ModHash);
350*e357fbd2SPeter Collingbourne     W2.writeModule(MergedM.get(), /*ShouldPreserveUseListOrder=*/false,
351*e357fbd2SPeter Collingbourne                    &MergedMIndex);
352a0f371a1SPeter Collingbourne     W2.writeStrtab();
3530c6a4ff8STeresa Johnson     *ThinLinkOS << Buffer;
3540c6a4ff8STeresa Johnson   }
3551398a32eSPeter Collingbourne }
3561398a32eSPeter Collingbourne 
3571398a32eSPeter Collingbourne // Returns whether this module needs to be split because it uses type metadata.
3581398a32eSPeter Collingbourne bool requiresSplit(Module &M) {
3591398a32eSPeter Collingbourne   SmallVector<MDNode *, 1> MDs;
3601398a32eSPeter Collingbourne   for (auto &GO : M.global_objects()) {
3611398a32eSPeter Collingbourne     GO.getMetadata(LLVMContext::MD_type, MDs);
3621398a32eSPeter Collingbourne     if (!MDs.empty())
3631398a32eSPeter Collingbourne       return true;
3641398a32eSPeter Collingbourne   }
3651398a32eSPeter Collingbourne 
3661398a32eSPeter Collingbourne   return false;
3671398a32eSPeter Collingbourne }
3681398a32eSPeter Collingbourne 
3690c6a4ff8STeresa Johnson void writeThinLTOBitcode(raw_ostream &OS, raw_ostream *ThinLinkOS,
370002c2d53SPeter Collingbourne                          function_ref<AAResults &(Function &)> AARGetter,
371002c2d53SPeter Collingbourne                          Module &M, const ModuleSummaryIndex *Index) {
3721398a32eSPeter Collingbourne   // See if this module has any type metadata. If so, we need to split it.
3731398a32eSPeter Collingbourne   if (requiresSplit(M))
3740c6a4ff8STeresa Johnson     return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M);
3751398a32eSPeter Collingbourne 
3761398a32eSPeter Collingbourne   // Otherwise we can just write it out as a regular module.
3770c6a4ff8STeresa Johnson 
3780c6a4ff8STeresa Johnson   // Save the module hash produced for the full bitcode, which will
3790c6a4ff8STeresa Johnson   // be used in the backends, and use that in the minimized bitcode
3800c6a4ff8STeresa Johnson   // produced for the full link.
3810c6a4ff8STeresa Johnson   ModuleHash ModHash = {{0}};
3821398a32eSPeter Collingbourne   WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false, Index,
3830c6a4ff8STeresa Johnson                      /*GenerateHash=*/true, &ModHash);
3840c6a4ff8STeresa Johnson   // If a minimized bitcode module was requested for the thin link,
3850c6a4ff8STeresa Johnson   // strip the debug info and write it to the given OS.
3860c6a4ff8STeresa Johnson   if (ThinLinkOS) {
3870c6a4ff8STeresa Johnson     StripDebugInfo(M);
3880c6a4ff8STeresa Johnson     WriteBitcodeToFile(&M, *ThinLinkOS, /*ShouldPreserveUseListOrder=*/false,
3890c6a4ff8STeresa Johnson                        Index,
3900c6a4ff8STeresa Johnson                        /*GenerateHash=*/false, &ModHash);
3910c6a4ff8STeresa Johnson   }
3921398a32eSPeter Collingbourne }
3931398a32eSPeter Collingbourne 
3941398a32eSPeter Collingbourne class WriteThinLTOBitcode : public ModulePass {
3951398a32eSPeter Collingbourne   raw_ostream &OS; // raw_ostream to print on
3960c6a4ff8STeresa Johnson   // The output stream on which to emit a minimized module for use
3970c6a4ff8STeresa Johnson   // just in the thin link, if requested.
3980c6a4ff8STeresa Johnson   raw_ostream *ThinLinkOS;
3991398a32eSPeter Collingbourne 
4001398a32eSPeter Collingbourne public:
4011398a32eSPeter Collingbourne   static char ID; // Pass identification, replacement for typeid
4020c6a4ff8STeresa Johnson   WriteThinLTOBitcode() : ModulePass(ID), OS(dbgs()), ThinLinkOS(nullptr) {
4031398a32eSPeter Collingbourne     initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
4041398a32eSPeter Collingbourne   }
4051398a32eSPeter Collingbourne 
4060c6a4ff8STeresa Johnson   explicit WriteThinLTOBitcode(raw_ostream &o, raw_ostream *ThinLinkOS)
4070c6a4ff8STeresa Johnson       : ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS) {
4081398a32eSPeter Collingbourne     initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
4091398a32eSPeter Collingbourne   }
4101398a32eSPeter Collingbourne 
4111398a32eSPeter Collingbourne   StringRef getPassName() const override { return "ThinLTO Bitcode Writer"; }
4121398a32eSPeter Collingbourne 
4131398a32eSPeter Collingbourne   bool runOnModule(Module &M) override {
4141398a32eSPeter Collingbourne     const ModuleSummaryIndex *Index =
4151398a32eSPeter Collingbourne         &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex());
4160c6a4ff8STeresa Johnson     writeThinLTOBitcode(OS, ThinLinkOS, LegacyAARGetter(*this), M, Index);
4171398a32eSPeter Collingbourne     return true;
4181398a32eSPeter Collingbourne   }
4191398a32eSPeter Collingbourne   void getAnalysisUsage(AnalysisUsage &AU) const override {
4201398a32eSPeter Collingbourne     AU.setPreservesAll();
421002c2d53SPeter Collingbourne     AU.addRequired<AssumptionCacheTracker>();
4221398a32eSPeter Collingbourne     AU.addRequired<ModuleSummaryIndexWrapperPass>();
423002c2d53SPeter Collingbourne     AU.addRequired<TargetLibraryInfoWrapperPass>();
4241398a32eSPeter Collingbourne   }
4251398a32eSPeter Collingbourne };
4261398a32eSPeter Collingbourne } // anonymous namespace
4271398a32eSPeter Collingbourne 
4281398a32eSPeter Collingbourne char WriteThinLTOBitcode::ID = 0;
4291398a32eSPeter Collingbourne INITIALIZE_PASS_BEGIN(WriteThinLTOBitcode, "write-thinlto-bitcode",
4301398a32eSPeter Collingbourne                       "Write ThinLTO Bitcode", false, true)
431002c2d53SPeter Collingbourne INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4321398a32eSPeter Collingbourne INITIALIZE_PASS_DEPENDENCY(ModuleSummaryIndexWrapperPass)
433002c2d53SPeter Collingbourne INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
4341398a32eSPeter Collingbourne INITIALIZE_PASS_END(WriteThinLTOBitcode, "write-thinlto-bitcode",
4351398a32eSPeter Collingbourne                     "Write ThinLTO Bitcode", false, true)
4361398a32eSPeter Collingbourne 
4370c6a4ff8STeresa Johnson ModulePass *llvm::createWriteThinLTOBitcodePass(raw_ostream &Str,
4380c6a4ff8STeresa Johnson                                                 raw_ostream *ThinLinkOS) {
4390c6a4ff8STeresa Johnson   return new WriteThinLTOBitcode(Str, ThinLinkOS);
4401398a32eSPeter Collingbourne }
4416b411418STim Shen 
4426b411418STim Shen PreservedAnalyses
4436b411418STim Shen llvm::ThinLTOBitcodeWriterPass::run(Module &M, ModuleAnalysisManager &AM) {
4446b411418STim Shen   FunctionAnalysisManager &FAM =
4456b411418STim Shen       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
4466b411418STim Shen   writeThinLTOBitcode(OS, ThinLinkOS,
4476b411418STim Shen                       [&FAM](Function &F) -> AAResults & {
4486b411418STim Shen                         return FAM.getResult<AAManager>(F);
4496b411418STim Shen                       },
4506b411418STim Shen                       M, &AM.getResult<ModuleSummaryIndexAnalysis>(M));
4516b411418STim Shen   return PreservedAnalyses::all();
4526b411418STim Shen }
453