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.
354d4ee93dSEvgeniy Stepanov void promoteInternals(Module &ExportM, Module &ImportM, StringRef ModuleId,
364d4ee93dSEvgeniy Stepanov                       SetVector<GlobalValue *> &PromoteExtra) {
374075ccc7SBob Haarman   DenseMap<const Comdat *, Comdat *> RenamedComdats;
386b193966SPeter Collingbourne   for (auto &ExportGV : ExportM.global_values()) {
391398a32eSPeter Collingbourne     if (!ExportGV.hasLocalLinkage())
406b193966SPeter Collingbourne       continue;
411398a32eSPeter Collingbourne 
424075ccc7SBob Haarman     auto Name = ExportGV.getName();
434075ccc7SBob Haarman     GlobalValue *ImportGV = ImportM.getNamedValue(Name);
444d4ee93dSEvgeniy Stepanov     if ((!ImportGV || ImportGV->use_empty()) && !PromoteExtra.count(&ExportGV))
456b193966SPeter Collingbourne       continue;
461398a32eSPeter Collingbourne 
474075ccc7SBob Haarman     std::string NewName = (Name + ModuleId).str();
484075ccc7SBob Haarman 
494075ccc7SBob Haarman     if (const auto *C = ExportGV.getComdat())
504075ccc7SBob Haarman       if (C->getName() == Name)
514075ccc7SBob Haarman         RenamedComdats.try_emplace(C, ExportM.getOrInsertComdat(NewName));
521398a32eSPeter Collingbourne 
531398a32eSPeter Collingbourne     ExportGV.setName(NewName);
541398a32eSPeter Collingbourne     ExportGV.setLinkage(GlobalValue::ExternalLinkage);
551398a32eSPeter Collingbourne     ExportGV.setVisibility(GlobalValue::HiddenVisibility);
561398a32eSPeter Collingbourne 
574d4ee93dSEvgeniy Stepanov     if (ImportGV) {
581398a32eSPeter Collingbourne       ImportGV->setName(NewName);
591398a32eSPeter Collingbourne       ImportGV->setVisibility(GlobalValue::HiddenVisibility);
606b193966SPeter Collingbourne     }
614d4ee93dSEvgeniy Stepanov   }
624075ccc7SBob Haarman 
634075ccc7SBob Haarman   if (!RenamedComdats.empty())
644075ccc7SBob Haarman     for (auto &GO : ExportM.global_objects())
654075ccc7SBob Haarman       if (auto *C = GO.getComdat()) {
664075ccc7SBob Haarman         auto Replacement = RenamedComdats.find(C);
674075ccc7SBob Haarman         if (Replacement != RenamedComdats.end())
684075ccc7SBob Haarman           GO.setComdat(Replacement->second);
694075ccc7SBob Haarman       }
701398a32eSPeter Collingbourne }
711398a32eSPeter Collingbourne 
721398a32eSPeter Collingbourne // Promote all internal (i.e. distinct) type ids used by the module by replacing
731398a32eSPeter Collingbourne // them with external type ids formed using the module id.
741398a32eSPeter Collingbourne //
751398a32eSPeter Collingbourne // Note that this needs to be done before we clone the module because each clone
761398a32eSPeter Collingbourne // will receive its own set of distinct metadata nodes.
771398a32eSPeter Collingbourne void promoteTypeIds(Module &M, StringRef ModuleId) {
781398a32eSPeter Collingbourne   DenseMap<Metadata *, Metadata *> LocalToGlobal;
791398a32eSPeter Collingbourne   auto ExternalizeTypeId = [&](CallInst *CI, unsigned ArgNo) {
801398a32eSPeter Collingbourne     Metadata *MD =
811398a32eSPeter Collingbourne         cast<MetadataAsValue>(CI->getArgOperand(ArgNo))->getMetadata();
821398a32eSPeter Collingbourne 
831398a32eSPeter Collingbourne     if (isa<MDNode>(MD) && cast<MDNode>(MD)->isDistinct()) {
841398a32eSPeter Collingbourne       Metadata *&GlobalMD = LocalToGlobal[MD];
851398a32eSPeter Collingbourne       if (!GlobalMD) {
861398a32eSPeter Collingbourne         std::string NewName =
871398a32eSPeter Collingbourne             (to_string(LocalToGlobal.size()) + ModuleId).str();
881398a32eSPeter Collingbourne         GlobalMD = MDString::get(M.getContext(), NewName);
891398a32eSPeter Collingbourne       }
901398a32eSPeter Collingbourne 
911398a32eSPeter Collingbourne       CI->setArgOperand(ArgNo,
921398a32eSPeter Collingbourne                         MetadataAsValue::get(M.getContext(), GlobalMD));
931398a32eSPeter Collingbourne     }
941398a32eSPeter Collingbourne   };
951398a32eSPeter Collingbourne 
961398a32eSPeter Collingbourne   if (Function *TypeTestFunc =
971398a32eSPeter Collingbourne           M.getFunction(Intrinsic::getName(Intrinsic::type_test))) {
981398a32eSPeter Collingbourne     for (const Use &U : TypeTestFunc->uses()) {
991398a32eSPeter Collingbourne       auto CI = cast<CallInst>(U.getUser());
1001398a32eSPeter Collingbourne       ExternalizeTypeId(CI, 1);
1011398a32eSPeter Collingbourne     }
1021398a32eSPeter Collingbourne   }
1031398a32eSPeter Collingbourne 
1041398a32eSPeter Collingbourne   if (Function *TypeCheckedLoadFunc =
1051398a32eSPeter Collingbourne           M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load))) {
1061398a32eSPeter Collingbourne     for (const Use &U : TypeCheckedLoadFunc->uses()) {
1071398a32eSPeter Collingbourne       auto CI = cast<CallInst>(U.getUser());
1081398a32eSPeter Collingbourne       ExternalizeTypeId(CI, 2);
1091398a32eSPeter Collingbourne     }
1101398a32eSPeter Collingbourne   }
1111398a32eSPeter Collingbourne 
1121398a32eSPeter Collingbourne   for (GlobalObject &GO : M.global_objects()) {
1131398a32eSPeter Collingbourne     SmallVector<MDNode *, 1> MDs;
1141398a32eSPeter Collingbourne     GO.getMetadata(LLVMContext::MD_type, MDs);
1151398a32eSPeter Collingbourne 
1161398a32eSPeter Collingbourne     GO.eraseMetadata(LLVMContext::MD_type);
1171398a32eSPeter Collingbourne     for (auto MD : MDs) {
1181398a32eSPeter Collingbourne       auto I = LocalToGlobal.find(MD->getOperand(1));
1191398a32eSPeter Collingbourne       if (I == LocalToGlobal.end()) {
1201398a32eSPeter Collingbourne         GO.addMetadata(LLVMContext::MD_type, *MD);
1211398a32eSPeter Collingbourne         continue;
1221398a32eSPeter Collingbourne       }
1231398a32eSPeter Collingbourne       GO.addMetadata(
1241398a32eSPeter Collingbourne           LLVMContext::MD_type,
1251398a32eSPeter Collingbourne           *MDNode::get(M.getContext(),
1261398a32eSPeter Collingbourne                        ArrayRef<Metadata *>{MD->getOperand(0), I->second}));
1271398a32eSPeter Collingbourne     }
1281398a32eSPeter Collingbourne   }
1291398a32eSPeter Collingbourne }
1301398a32eSPeter Collingbourne 
1311398a32eSPeter Collingbourne // Drop unused globals, and drop type information from function declarations.
1321398a32eSPeter Collingbourne // FIXME: If we made functions typeless then there would be no need to do this.
1331398a32eSPeter Collingbourne void simplifyExternals(Module &M) {
1341398a32eSPeter Collingbourne   FunctionType *EmptyFT =
1351398a32eSPeter Collingbourne       FunctionType::get(Type::getVoidTy(M.getContext()), false);
1361398a32eSPeter Collingbourne 
1371398a32eSPeter Collingbourne   for (auto I = M.begin(), E = M.end(); I != E;) {
1381398a32eSPeter Collingbourne     Function &F = *I++;
1391398a32eSPeter Collingbourne     if (F.isDeclaration() && F.use_empty()) {
1401398a32eSPeter Collingbourne       F.eraseFromParent();
1411398a32eSPeter Collingbourne       continue;
1421398a32eSPeter Collingbourne     }
1431398a32eSPeter Collingbourne 
1441398a32eSPeter Collingbourne     if (!F.isDeclaration() || F.getFunctionType() == EmptyFT)
1451398a32eSPeter Collingbourne       continue;
1461398a32eSPeter Collingbourne 
1471398a32eSPeter Collingbourne     Function *NewF =
1481398a32eSPeter Collingbourne         Function::Create(EmptyFT, GlobalValue::ExternalLinkage, "", &M);
1491398a32eSPeter Collingbourne     NewF->setVisibility(F.getVisibility());
1501398a32eSPeter Collingbourne     NewF->takeName(&F);
1511398a32eSPeter Collingbourne     F.replaceAllUsesWith(ConstantExpr::getBitCast(NewF, F.getType()));
1521398a32eSPeter Collingbourne     F.eraseFromParent();
1531398a32eSPeter Collingbourne   }
1541398a32eSPeter Collingbourne 
1551398a32eSPeter Collingbourne   for (auto I = M.global_begin(), E = M.global_end(); I != E;) {
1561398a32eSPeter Collingbourne     GlobalVariable &GV = *I++;
1571398a32eSPeter Collingbourne     if (GV.isDeclaration() && GV.use_empty()) {
1581398a32eSPeter Collingbourne       GV.eraseFromParent();
1591398a32eSPeter Collingbourne       continue;
1601398a32eSPeter Collingbourne     }
1611398a32eSPeter Collingbourne   }
1621398a32eSPeter Collingbourne }
1631398a32eSPeter Collingbourne 
1641398a32eSPeter Collingbourne void filterModule(
165061f4a5fSBenjamin Kramer     Module *M, function_ref<bool(const GlobalValue *)> ShouldKeepDefinition) {
1666de81347SBob Haarman   for (Module::alias_iterator I = M->alias_begin(), E = M->alias_end();
1676de81347SBob Haarman        I != E;) {
1686de81347SBob Haarman     GlobalAlias *GA = &*I++;
1696de81347SBob Haarman     if (ShouldKeepDefinition(GA))
1706de81347SBob Haarman       continue;
1716de81347SBob Haarman 
1726de81347SBob Haarman     GlobalObject *GO;
1736de81347SBob Haarman     if (GA->getValueType()->isFunctionTy())
1746de81347SBob Haarman       GO = Function::Create(cast<FunctionType>(GA->getValueType()),
1756de81347SBob Haarman                             GlobalValue::ExternalLinkage, "", M);
1766de81347SBob Haarman     else
1776de81347SBob Haarman       GO = new GlobalVariable(
1786de81347SBob Haarman           *M, GA->getValueType(), false, GlobalValue::ExternalLinkage,
179f4dc59baSSerge Guelton           nullptr, "", nullptr,
1806de81347SBob Haarman           GA->getThreadLocalMode(), GA->getType()->getAddressSpace());
1816de81347SBob Haarman     GO->takeName(GA);
1826de81347SBob Haarman     GA->replaceAllUsesWith(GO);
1836de81347SBob Haarman     GA->eraseFromParent();
1846de81347SBob Haarman   }
1856de81347SBob Haarman 
1861398a32eSPeter Collingbourne   for (Function &F : *M) {
1871398a32eSPeter Collingbourne     if (ShouldKeepDefinition(&F))
1881398a32eSPeter Collingbourne       continue;
1891398a32eSPeter Collingbourne 
1901398a32eSPeter Collingbourne     F.deleteBody();
19120a00933SPeter Collingbourne     F.setComdat(nullptr);
1921398a32eSPeter Collingbourne     F.clearMetadata();
1931398a32eSPeter Collingbourne   }
1941398a32eSPeter Collingbourne 
1951398a32eSPeter Collingbourne   for (GlobalVariable &GV : M->globals()) {
1961398a32eSPeter Collingbourne     if (ShouldKeepDefinition(&GV))
1971398a32eSPeter Collingbourne       continue;
1981398a32eSPeter Collingbourne 
1991398a32eSPeter Collingbourne     GV.setInitializer(nullptr);
2001398a32eSPeter Collingbourne     GV.setLinkage(GlobalValue::ExternalLinkage);
20120a00933SPeter Collingbourne     GV.setComdat(nullptr);
2021398a32eSPeter Collingbourne     GV.clearMetadata();
2031398a32eSPeter Collingbourne   }
2041398a32eSPeter Collingbourne }
2051398a32eSPeter Collingbourne 
206002c2d53SPeter Collingbourne void forEachVirtualFunction(Constant *C, function_ref<void(Function *)> Fn) {
207002c2d53SPeter Collingbourne   if (auto *F = dyn_cast<Function>(C))
208002c2d53SPeter Collingbourne     return Fn(F);
2093baa72afSPeter Collingbourne   if (isa<GlobalValue>(C))
2103baa72afSPeter Collingbourne     return;
211002c2d53SPeter Collingbourne   for (Value *Op : C->operands())
212002c2d53SPeter Collingbourne     forEachVirtualFunction(cast<Constant>(Op), Fn);
213002c2d53SPeter Collingbourne }
214002c2d53SPeter Collingbourne 
2151398a32eSPeter Collingbourne // If it's possible to split M into regular and thin LTO parts, do so and write
2161398a32eSPeter Collingbourne // a multi-module bitcode file with the two parts to OS. Otherwise, write only a
2171398a32eSPeter Collingbourne // regular LTO bitcode file to OS.
218002c2d53SPeter Collingbourne void splitAndWriteThinLTOBitcode(
2190c6a4ff8STeresa Johnson     raw_ostream &OS, raw_ostream *ThinLinkOS,
2200c6a4ff8STeresa Johnson     function_ref<AAResults &(Function &)> AARGetter, Module &M) {
221964f4663SEvgeniy Stepanov   std::string ModuleId = getUniqueModuleId(&M);
2221398a32eSPeter Collingbourne   if (ModuleId.empty()) {
2231398a32eSPeter Collingbourne     // We couldn't generate a module ID for this module, just write it out as a
2241398a32eSPeter Collingbourne     // regular LTO module.
2251398a32eSPeter Collingbourne     WriteBitcodeToFile(&M, OS);
2260c6a4ff8STeresa Johnson     if (ThinLinkOS)
2270c6a4ff8STeresa Johnson       // We don't have a ThinLTO part, but still write the module to the
2280c6a4ff8STeresa Johnson       // ThinLinkOS if requested so that the expected output file is produced.
2290c6a4ff8STeresa Johnson       WriteBitcodeToFile(&M, *ThinLinkOS);
2301398a32eSPeter Collingbourne     return;
2311398a32eSPeter Collingbourne   }
2321398a32eSPeter Collingbourne 
2331398a32eSPeter Collingbourne   promoteTypeIds(M, ModuleId);
2341398a32eSPeter Collingbourne 
235002c2d53SPeter Collingbourne   // Returns whether a global has attached type metadata. Such globals may
236002c2d53SPeter Collingbourne   // participate in CFI or whole-program devirtualization, so they need to
237002c2d53SPeter Collingbourne   // appear in the merged module instead of the thin LTO module.
238002c2d53SPeter Collingbourne   auto HasTypeMetadata = [&](const GlobalObject *GO) {
2391398a32eSPeter Collingbourne     SmallVector<MDNode *, 1> MDs;
240002c2d53SPeter Collingbourne     GO->getMetadata(LLVMContext::MD_type, MDs);
2411398a32eSPeter Collingbourne     return !MDs.empty();
2421398a32eSPeter Collingbourne   };
2431398a32eSPeter Collingbourne 
244002c2d53SPeter Collingbourne   // Collect the set of virtual functions that are eligible for virtual constant
245002c2d53SPeter Collingbourne   // propagation. Each eligible function must not access memory, must return
246002c2d53SPeter Collingbourne   // an integer of width <=64 bits, must take at least one argument, must not
247002c2d53SPeter Collingbourne   // use its first argument (assumed to be "this") and all arguments other than
248002c2d53SPeter Collingbourne   // the first one must be of <=64 bit integer type.
249002c2d53SPeter Collingbourne   //
250002c2d53SPeter Collingbourne   // Note that we test whether this copy of the function is readnone, rather
251002c2d53SPeter Collingbourne   // than testing function attributes, which must hold for any copy of the
252002c2d53SPeter Collingbourne   // function, even a less optimized version substituted at link time. This is
253002c2d53SPeter Collingbourne   // sound because the virtual constant propagation optimizations effectively
254002c2d53SPeter Collingbourne   // inline all implementations of the virtual function into each call site,
255002c2d53SPeter Collingbourne   // rather than using function attributes to perform local optimization.
256002c2d53SPeter Collingbourne   std::set<const Function *> EligibleVirtualFns;
2574075ccc7SBob Haarman   // If any member of a comdat lives in MergedM, put all members of that
2584075ccc7SBob Haarman   // comdat in MergedM to keep the comdat together.
2594075ccc7SBob Haarman   DenseSet<const Comdat *> MergedMComdats;
260002c2d53SPeter Collingbourne   for (GlobalVariable &GV : M.globals())
2614075ccc7SBob Haarman     if (HasTypeMetadata(&GV)) {
2624075ccc7SBob Haarman       if (const auto *C = GV.getComdat())
2634075ccc7SBob Haarman         MergedMComdats.insert(C);
264002c2d53SPeter Collingbourne       forEachVirtualFunction(GV.getInitializer(), [&](Function *F) {
265002c2d53SPeter Collingbourne         auto *RT = dyn_cast<IntegerType>(F->getReturnType());
266002c2d53SPeter Collingbourne         if (!RT || RT->getBitWidth() > 64 || F->arg_empty() ||
267002c2d53SPeter Collingbourne             !F->arg_begin()->use_empty())
268002c2d53SPeter Collingbourne           return;
269002c2d53SPeter Collingbourne         for (auto &Arg : make_range(std::next(F->arg_begin()), F->arg_end())) {
270002c2d53SPeter Collingbourne           auto *ArgT = dyn_cast<IntegerType>(Arg.getType());
271002c2d53SPeter Collingbourne           if (!ArgT || ArgT->getBitWidth() > 64)
272002c2d53SPeter Collingbourne             return;
273002c2d53SPeter Collingbourne         }
274*01f0c8a8SChandler Carruth         if (!F->isDeclaration() &&
275*01f0c8a8SChandler Carruth             computeFunctionBodyMemoryAccess(*F, AARGetter(*F)) == MAK_ReadNone)
276002c2d53SPeter Collingbourne           EligibleVirtualFns.insert(F);
277002c2d53SPeter Collingbourne       });
2784075ccc7SBob Haarman     }
279002c2d53SPeter Collingbourne 
2801398a32eSPeter Collingbourne   ValueToValueMapTy VMap;
281002c2d53SPeter Collingbourne   std::unique_ptr<Module> MergedM(
282002c2d53SPeter Collingbourne       CloneModule(&M, VMap, [&](const GlobalValue *GV) -> bool {
2834075ccc7SBob Haarman         if (const auto *C = GV->getComdat())
2844075ccc7SBob Haarman           if (MergedMComdats.count(C))
2854075ccc7SBob Haarman             return true;
286002c2d53SPeter Collingbourne         if (auto *F = dyn_cast<Function>(GV))
287002c2d53SPeter Collingbourne           return EligibleVirtualFns.count(F);
288002c2d53SPeter Collingbourne         if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
289002c2d53SPeter Collingbourne           return HasTypeMetadata(GVar);
290002c2d53SPeter Collingbourne         return false;
291002c2d53SPeter Collingbourne       }));
29228ffd326SPeter Collingbourne   StripDebugInfo(*MergedM);
2931398a32eSPeter Collingbourne 
294002c2d53SPeter Collingbourne   for (Function &F : *MergedM)
295002c2d53SPeter Collingbourne     if (!F.isDeclaration()) {
296002c2d53SPeter Collingbourne       // Reset the linkage of all functions eligible for virtual constant
297002c2d53SPeter Collingbourne       // propagation. The canonical definitions live in the thin LTO module so
298002c2d53SPeter Collingbourne       // that they can be imported.
299002c2d53SPeter Collingbourne       F.setLinkage(GlobalValue::AvailableExternallyLinkage);
300002c2d53SPeter Collingbourne       F.setComdat(nullptr);
301002c2d53SPeter Collingbourne     }
302002c2d53SPeter Collingbourne 
3034d4ee93dSEvgeniy Stepanov   SetVector<GlobalValue *> CfiFunctions;
3044d4ee93dSEvgeniy Stepanov   for (auto &F : M)
3054d4ee93dSEvgeniy Stepanov     if ((!F.hasLocalLinkage() || F.hasAddressTaken()) && HasTypeMetadata(&F))
3064d4ee93dSEvgeniy Stepanov       CfiFunctions.insert(&F);
3074d4ee93dSEvgeniy Stepanov 
3084075ccc7SBob Haarman   // Remove all globals with type metadata, globals with comdats that live in
3094075ccc7SBob Haarman   // MergedM, and aliases pointing to such globals from the thin LTO module.
310002c2d53SPeter Collingbourne   filterModule(&M, [&](const GlobalValue *GV) {
311002c2d53SPeter Collingbourne     if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
3124075ccc7SBob Haarman       if (HasTypeMetadata(GVar))
3134075ccc7SBob Haarman         return false;
3144075ccc7SBob Haarman     if (const auto *C = GV->getComdat())
3154075ccc7SBob Haarman       if (MergedMComdats.count(C))
3164075ccc7SBob Haarman         return false;
317002c2d53SPeter Collingbourne     return true;
318002c2d53SPeter Collingbourne   });
3191398a32eSPeter Collingbourne 
3204d4ee93dSEvgeniy Stepanov   promoteInternals(*MergedM, M, ModuleId, CfiFunctions);
3214d4ee93dSEvgeniy Stepanov   promoteInternals(M, *MergedM, ModuleId, CfiFunctions);
3224d4ee93dSEvgeniy Stepanov 
3234d4ee93dSEvgeniy Stepanov   SmallVector<MDNode *, 8> CfiFunctionMDs;
3244d4ee93dSEvgeniy Stepanov   for (auto V : CfiFunctions) {
3254d4ee93dSEvgeniy Stepanov     Function &F = *cast<Function>(V);
3264d4ee93dSEvgeniy Stepanov     SmallVector<MDNode *, 2> Types;
3274d4ee93dSEvgeniy Stepanov     F.getMetadata(LLVMContext::MD_type, Types);
3284d4ee93dSEvgeniy Stepanov 
3294d4ee93dSEvgeniy Stepanov     auto &Ctx = MergedM->getContext();
3304d4ee93dSEvgeniy Stepanov     SmallVector<Metadata *, 4> Elts;
3314d4ee93dSEvgeniy Stepanov     Elts.push_back(MDString::get(Ctx, F.getName()));
3324d4ee93dSEvgeniy Stepanov     CfiFunctionLinkage Linkage;
3334d4ee93dSEvgeniy Stepanov     if (!F.isDeclarationForLinker())
3344d4ee93dSEvgeniy Stepanov       Linkage = CFL_Definition;
3354d4ee93dSEvgeniy Stepanov     else if (F.isWeakForLinker())
3364d4ee93dSEvgeniy Stepanov       Linkage = CFL_WeakDeclaration;
3374d4ee93dSEvgeniy Stepanov     else
3384d4ee93dSEvgeniy Stepanov       Linkage = CFL_Declaration;
3394d4ee93dSEvgeniy Stepanov     Elts.push_back(ConstantAsMetadata::get(
3404d4ee93dSEvgeniy Stepanov         llvm::ConstantInt::get(Type::getInt8Ty(Ctx), Linkage)));
3414d4ee93dSEvgeniy Stepanov     for (auto Type : Types)
3424d4ee93dSEvgeniy Stepanov       Elts.push_back(Type);
3434d4ee93dSEvgeniy Stepanov     CfiFunctionMDs.push_back(MDTuple::get(Ctx, Elts));
3444d4ee93dSEvgeniy Stepanov   }
3454d4ee93dSEvgeniy Stepanov 
3464d4ee93dSEvgeniy Stepanov   if(!CfiFunctionMDs.empty()) {
3474d4ee93dSEvgeniy Stepanov     NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("cfi.functions");
3484d4ee93dSEvgeniy Stepanov     for (auto MD : CfiFunctionMDs)
3494d4ee93dSEvgeniy Stepanov       NMD->addOperand(MD);
3504d4ee93dSEvgeniy Stepanov   }
3511398a32eSPeter Collingbourne 
3521398a32eSPeter Collingbourne   simplifyExternals(*MergedM);
3531398a32eSPeter Collingbourne 
3541398a32eSPeter Collingbourne   // FIXME: Try to re-use BSI and PFI from the original module here.
35594624acaSTeresa Johnson   ProfileSummaryInfo PSI(M);
35694624acaSTeresa Johnson   ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
3570c6a4ff8STeresa Johnson 
358e357fbd2SPeter Collingbourne   // Mark the merged module as requiring full LTO. We still want an index for
359e357fbd2SPeter Collingbourne   // it though, so that it can participate in summary-based dead stripping.
360e357fbd2SPeter Collingbourne   MergedM->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
361e357fbd2SPeter Collingbourne   ModuleSummaryIndex MergedMIndex =
362e357fbd2SPeter Collingbourne       buildModuleSummaryIndex(*MergedM, nullptr, &PSI);
363e357fbd2SPeter Collingbourne 
3640c6a4ff8STeresa Johnson   SmallVector<char, 0> Buffer;
3650c6a4ff8STeresa Johnson 
3660c6a4ff8STeresa Johnson   BitcodeWriter W(Buffer);
3670c6a4ff8STeresa Johnson   // Save the module hash produced for the full bitcode, which will
3680c6a4ff8STeresa Johnson   // be used in the backends, and use that in the minimized bitcode
3690c6a4ff8STeresa Johnson   // produced for the full link.
3700c6a4ff8STeresa Johnson   ModuleHash ModHash = {{0}};
3711398a32eSPeter Collingbourne   W.writeModule(&M, /*ShouldPreserveUseListOrder=*/false, &Index,
3720c6a4ff8STeresa Johnson                 /*GenerateHash=*/true, &ModHash);
373e357fbd2SPeter Collingbourne   W.writeModule(MergedM.get(), /*ShouldPreserveUseListOrder=*/false,
374e357fbd2SPeter Collingbourne                 &MergedMIndex);
37592648c25SPeter Collingbourne   W.writeSymtab();
376a0f371a1SPeter Collingbourne   W.writeStrtab();
3771398a32eSPeter Collingbourne   OS << Buffer;
3780c6a4ff8STeresa Johnson 
3790c6a4ff8STeresa Johnson   // If a minimized bitcode module was requested for the thin link,
3800c6a4ff8STeresa Johnson   // strip the debug info (the merged module was already stripped above)
3810c6a4ff8STeresa Johnson   // and write it to the given OS.
3820c6a4ff8STeresa Johnson   if (ThinLinkOS) {
3830c6a4ff8STeresa Johnson     Buffer.clear();
3840c6a4ff8STeresa Johnson     BitcodeWriter W2(Buffer);
3850c6a4ff8STeresa Johnson     StripDebugInfo(M);
3860c6a4ff8STeresa Johnson     W2.writeModule(&M, /*ShouldPreserveUseListOrder=*/false, &Index,
3870c6a4ff8STeresa Johnson                    /*GenerateHash=*/false, &ModHash);
388e357fbd2SPeter Collingbourne     W2.writeModule(MergedM.get(), /*ShouldPreserveUseListOrder=*/false,
389e357fbd2SPeter Collingbourne                    &MergedMIndex);
39092648c25SPeter Collingbourne     W2.writeSymtab();
391a0f371a1SPeter Collingbourne     W2.writeStrtab();
3920c6a4ff8STeresa Johnson     *ThinLinkOS << Buffer;
3930c6a4ff8STeresa Johnson   }
3941398a32eSPeter Collingbourne }
3951398a32eSPeter Collingbourne 
3961398a32eSPeter Collingbourne // Returns whether this module needs to be split because it uses type metadata.
3971398a32eSPeter Collingbourne bool requiresSplit(Module &M) {
3981398a32eSPeter Collingbourne   SmallVector<MDNode *, 1> MDs;
3991398a32eSPeter Collingbourne   for (auto &GO : M.global_objects()) {
4001398a32eSPeter Collingbourne     GO.getMetadata(LLVMContext::MD_type, MDs);
4011398a32eSPeter Collingbourne     if (!MDs.empty())
4021398a32eSPeter Collingbourne       return true;
4031398a32eSPeter Collingbourne   }
4041398a32eSPeter Collingbourne 
4051398a32eSPeter Collingbourne   return false;
4061398a32eSPeter Collingbourne }
4071398a32eSPeter Collingbourne 
4080c6a4ff8STeresa Johnson void writeThinLTOBitcode(raw_ostream &OS, raw_ostream *ThinLinkOS,
409002c2d53SPeter Collingbourne                          function_ref<AAResults &(Function &)> AARGetter,
410002c2d53SPeter Collingbourne                          Module &M, const ModuleSummaryIndex *Index) {
4111398a32eSPeter Collingbourne   // See if this module has any type metadata. If so, we need to split it.
4121398a32eSPeter Collingbourne   if (requiresSplit(M))
4130c6a4ff8STeresa Johnson     return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M);
4141398a32eSPeter Collingbourne 
4151398a32eSPeter Collingbourne   // Otherwise we can just write it out as a regular module.
4160c6a4ff8STeresa Johnson 
4170c6a4ff8STeresa Johnson   // Save the module hash produced for the full bitcode, which will
4180c6a4ff8STeresa Johnson   // be used in the backends, and use that in the minimized bitcode
4190c6a4ff8STeresa Johnson   // produced for the full link.
4200c6a4ff8STeresa Johnson   ModuleHash ModHash = {{0}};
4211398a32eSPeter Collingbourne   WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false, Index,
4220c6a4ff8STeresa Johnson                      /*GenerateHash=*/true, &ModHash);
4230c6a4ff8STeresa Johnson   // If a minimized bitcode module was requested for the thin link,
4240c6a4ff8STeresa Johnson   // strip the debug info and write it to the given OS.
4250c6a4ff8STeresa Johnson   if (ThinLinkOS) {
4260c6a4ff8STeresa Johnson     StripDebugInfo(M);
4270c6a4ff8STeresa Johnson     WriteBitcodeToFile(&M, *ThinLinkOS, /*ShouldPreserveUseListOrder=*/false,
4280c6a4ff8STeresa Johnson                        Index,
4290c6a4ff8STeresa Johnson                        /*GenerateHash=*/false, &ModHash);
4300c6a4ff8STeresa Johnson   }
4311398a32eSPeter Collingbourne }
4321398a32eSPeter Collingbourne 
4331398a32eSPeter Collingbourne class WriteThinLTOBitcode : public ModulePass {
4341398a32eSPeter Collingbourne   raw_ostream &OS; // raw_ostream to print on
4350c6a4ff8STeresa Johnson   // The output stream on which to emit a minimized module for use
4360c6a4ff8STeresa Johnson   // just in the thin link, if requested.
4370c6a4ff8STeresa Johnson   raw_ostream *ThinLinkOS;
4381398a32eSPeter Collingbourne 
4391398a32eSPeter Collingbourne public:
4401398a32eSPeter Collingbourne   static char ID; // Pass identification, replacement for typeid
4410c6a4ff8STeresa Johnson   WriteThinLTOBitcode() : ModulePass(ID), OS(dbgs()), ThinLinkOS(nullptr) {
4421398a32eSPeter Collingbourne     initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
4431398a32eSPeter Collingbourne   }
4441398a32eSPeter Collingbourne 
4450c6a4ff8STeresa Johnson   explicit WriteThinLTOBitcode(raw_ostream &o, raw_ostream *ThinLinkOS)
4460c6a4ff8STeresa Johnson       : ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS) {
4471398a32eSPeter Collingbourne     initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
4481398a32eSPeter Collingbourne   }
4491398a32eSPeter Collingbourne 
4501398a32eSPeter Collingbourne   StringRef getPassName() const override { return "ThinLTO Bitcode Writer"; }
4511398a32eSPeter Collingbourne 
4521398a32eSPeter Collingbourne   bool runOnModule(Module &M) override {
4531398a32eSPeter Collingbourne     const ModuleSummaryIndex *Index =
4541398a32eSPeter Collingbourne         &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex());
4550c6a4ff8STeresa Johnson     writeThinLTOBitcode(OS, ThinLinkOS, LegacyAARGetter(*this), M, Index);
4561398a32eSPeter Collingbourne     return true;
4571398a32eSPeter Collingbourne   }
4581398a32eSPeter Collingbourne   void getAnalysisUsage(AnalysisUsage &AU) const override {
4591398a32eSPeter Collingbourne     AU.setPreservesAll();
460002c2d53SPeter Collingbourne     AU.addRequired<AssumptionCacheTracker>();
4611398a32eSPeter Collingbourne     AU.addRequired<ModuleSummaryIndexWrapperPass>();
462002c2d53SPeter Collingbourne     AU.addRequired<TargetLibraryInfoWrapperPass>();
4631398a32eSPeter Collingbourne   }
4641398a32eSPeter Collingbourne };
4651398a32eSPeter Collingbourne } // anonymous namespace
4661398a32eSPeter Collingbourne 
4671398a32eSPeter Collingbourne char WriteThinLTOBitcode::ID = 0;
4681398a32eSPeter Collingbourne INITIALIZE_PASS_BEGIN(WriteThinLTOBitcode, "write-thinlto-bitcode",
4691398a32eSPeter Collingbourne                       "Write ThinLTO Bitcode", false, true)
470002c2d53SPeter Collingbourne INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4711398a32eSPeter Collingbourne INITIALIZE_PASS_DEPENDENCY(ModuleSummaryIndexWrapperPass)
472002c2d53SPeter Collingbourne INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
4731398a32eSPeter Collingbourne INITIALIZE_PASS_END(WriteThinLTOBitcode, "write-thinlto-bitcode",
4741398a32eSPeter Collingbourne                     "Write ThinLTO Bitcode", false, true)
4751398a32eSPeter Collingbourne 
4760c6a4ff8STeresa Johnson ModulePass *llvm::createWriteThinLTOBitcodePass(raw_ostream &Str,
4770c6a4ff8STeresa Johnson                                                 raw_ostream *ThinLinkOS) {
4780c6a4ff8STeresa Johnson   return new WriteThinLTOBitcode(Str, ThinLinkOS);
4791398a32eSPeter Collingbourne }
4806b411418STim Shen 
4816b411418STim Shen PreservedAnalyses
4826b411418STim Shen llvm::ThinLTOBitcodeWriterPass::run(Module &M, ModuleAnalysisManager &AM) {
4836b411418STim Shen   FunctionAnalysisManager &FAM =
4846b411418STim Shen       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
4856b411418STim Shen   writeThinLTOBitcode(OS, ThinLinkOS,
4866b411418STim Shen                       [&FAM](Function &F) -> AAResults & {
4876b411418STim Shen                         return FAM.getResult<AAManager>(F);
4886b411418STim Shen                       },
4896b411418STim Shen                       M, &AM.getResult<ModuleSummaryIndexAnalysis>(M));
4906b411418STim Shen   return PreservedAnalyses::all();
4916b411418STim Shen }
492