blob: 690b5e8bf49ee688a547efafca563f1c151b79ba [file] [log] [blame]
Peter Collingbourne1398a322016-12-16 00:26:30 +00001//===- ThinLTOBitcodeWriter.cpp - Bitcode writing pass for ThinLTO --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Peter Collingbourne1398a322016-12-16 00:26:30 +00006//
7//===----------------------------------------------------------------------===//
Peter Collingbourne1398a322016-12-16 00:26:30 +00008
Tim Shen6b4114182017-06-01 01:02:12 +00009#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
Peter Collingbourne002c2d52017-02-14 03:42:38 +000010#include "llvm/Analysis/BasicAliasAnalysis.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000011#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Teresa Johnson94624ac2017-05-10 18:52:16 +000012#include "llvm/Analysis/ProfileSummaryInfo.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000013#include "llvm/Analysis/TypeMetadataUtils.h"
14#include "llvm/Bitcode/BitcodeWriter.h"
15#include "llvm/IR/Constants.h"
Peter Collingbourne28ffd322017-02-08 20:44:00 +000016#include "llvm/IR/DebugInfo.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000017#include "llvm/IR/Intrinsics.h"
18#include "llvm/IR/Module.h"
19#include "llvm/IR/PassManager.h"
Vlad Tsyrklevich230b2562018-04-20 01:36:48 +000020#include "llvm/Object/ModuleSymbolTable.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000021#include "llvm/Pass.h"
22#include "llvm/Support/ScopedPrinter.h"
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +000023#include "llvm/Support/raw_ostream.h"
24#include "llvm/Transforms/IPO.h"
Peter Collingbourne002c2d52017-02-14 03:42:38 +000025#include "llvm/Transforms/IPO/FunctionAttrs.h"
George Rimard3704f62018-02-08 07:23:24 +000026#include "llvm/Transforms/IPO/FunctionImport.h"
Peter Collingbourne0e497d12019-08-09 22:31:59 +000027#include "llvm/Transforms/IPO/LowerTypeTests.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000028#include "llvm/Transforms/Utils/Cloning.h"
Evgeniy Stepanov964f4662017-04-27 20:27:27 +000029#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000030using namespace llvm;
31
32namespace {
33
Peter Collingbourne1398a322016-12-16 00:26:30 +000034// Promote each local-linkage entity defined by ExportM and used by ImportM by
35// changing visibility and appending the given ModuleId.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +000036void promoteInternals(Module &ExportM, Module &ImportM, StringRef ModuleId,
37 SetVector<GlobalValue *> &PromoteExtra) {
Bob Haarman4075ccc2017-04-12 01:43:07 +000038 DenseMap<const Comdat *, Comdat *> RenamedComdats;
Peter Collingbourne6b193962017-03-30 23:43:08 +000039 for (auto &ExportGV : ExportM.global_values()) {
Peter Collingbourne1398a322016-12-16 00:26:30 +000040 if (!ExportGV.hasLocalLinkage())
Peter Collingbourne6b193962017-03-30 23:43:08 +000041 continue;
Peter Collingbourne1398a322016-12-16 00:26:30 +000042
Bob Haarman4075ccc2017-04-12 01:43:07 +000043 auto Name = ExportGV.getName();
Peter Collingbourne1f034222017-11-30 23:05:52 +000044 GlobalValue *ImportGV = nullptr;
45 if (!PromoteExtra.count(&ExportGV)) {
46 ImportGV = ImportM.getNamedValue(Name);
47 if (!ImportGV)
48 continue;
49 ImportGV->removeDeadConstantUsers();
50 if (ImportGV->use_empty()) {
51 ImportGV->eraseFromParent();
52 continue;
53 }
54 }
Peter Collingbourne1398a322016-12-16 00:26:30 +000055
Bob Haarman4075ccc2017-04-12 01:43:07 +000056 std::string NewName = (Name + ModuleId).str();
57
58 if (const auto *C = ExportGV.getComdat())
59 if (C->getName() == Name)
60 RenamedComdats.try_emplace(C, ExportM.getOrInsertComdat(NewName));
Peter Collingbourne1398a322016-12-16 00:26:30 +000061
62 ExportGV.setName(NewName);
63 ExportGV.setLinkage(GlobalValue::ExternalLinkage);
64 ExportGV.setVisibility(GlobalValue::HiddenVisibility);
65
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +000066 if (ImportGV) {
67 ImportGV->setName(NewName);
68 ImportGV->setVisibility(GlobalValue::HiddenVisibility);
69 }
Peter Collingbourne6b193962017-03-30 23:43:08 +000070 }
Bob Haarman4075ccc2017-04-12 01:43:07 +000071
72 if (!RenamedComdats.empty())
73 for (auto &GO : ExportM.global_objects())
74 if (auto *C = GO.getComdat()) {
75 auto Replacement = RenamedComdats.find(C);
76 if (Replacement != RenamedComdats.end())
77 GO.setComdat(Replacement->second);
78 }
Peter Collingbourne1398a322016-12-16 00:26:30 +000079}
80
81// Promote all internal (i.e. distinct) type ids used by the module by replacing
82// them with external type ids formed using the module id.
83//
84// Note that this needs to be done before we clone the module because each clone
85// will receive its own set of distinct metadata nodes.
86void promoteTypeIds(Module &M, StringRef ModuleId) {
87 DenseMap<Metadata *, Metadata *> LocalToGlobal;
88 auto ExternalizeTypeId = [&](CallInst *CI, unsigned ArgNo) {
89 Metadata *MD =
90 cast<MetadataAsValue>(CI->getArgOperand(ArgNo))->getMetadata();
91
92 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isDistinct()) {
93 Metadata *&GlobalMD = LocalToGlobal[MD];
94 if (!GlobalMD) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +000095 std::string NewName = (Twine(LocalToGlobal.size()) + ModuleId).str();
Peter Collingbourne1398a322016-12-16 00:26:30 +000096 GlobalMD = MDString::get(M.getContext(), NewName);
97 }
98
99 CI->setArgOperand(ArgNo,
100 MetadataAsValue::get(M.getContext(), GlobalMD));
101 }
102 };
103
104 if (Function *TypeTestFunc =
105 M.getFunction(Intrinsic::getName(Intrinsic::type_test))) {
106 for (const Use &U : TypeTestFunc->uses()) {
107 auto CI = cast<CallInst>(U.getUser());
108 ExternalizeTypeId(CI, 1);
109 }
110 }
111
112 if (Function *TypeCheckedLoadFunc =
113 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load))) {
114 for (const Use &U : TypeCheckedLoadFunc->uses()) {
115 auto CI = cast<CallInst>(U.getUser());
116 ExternalizeTypeId(CI, 2);
117 }
118 }
119
120 for (GlobalObject &GO : M.global_objects()) {
121 SmallVector<MDNode *, 1> MDs;
122 GO.getMetadata(LLVMContext::MD_type, MDs);
123
124 GO.eraseMetadata(LLVMContext::MD_type);
125 for (auto MD : MDs) {
126 auto I = LocalToGlobal.find(MD->getOperand(1));
127 if (I == LocalToGlobal.end()) {
128 GO.addMetadata(LLVMContext::MD_type, *MD);
129 continue;
130 }
131 GO.addMetadata(
132 LLVMContext::MD_type,
Benjamin Kramer0deb9a92018-05-31 13:29:58 +0000133 *MDNode::get(M.getContext(), {MD->getOperand(0), I->second}));
Peter Collingbourne1398a322016-12-16 00:26:30 +0000134 }
135 }
136}
137
138// Drop unused globals, and drop type information from function declarations.
139// FIXME: If we made functions typeless then there would be no need to do this.
140void simplifyExternals(Module &M) {
141 FunctionType *EmptyFT =
142 FunctionType::get(Type::getVoidTy(M.getContext()), false);
143
144 for (auto I = M.begin(), E = M.end(); I != E;) {
145 Function &F = *I++;
146 if (F.isDeclaration() && F.use_empty()) {
147 F.eraseFromParent();
148 continue;
149 }
150
Peter Collingbourne93fdaca2017-07-19 17:54:29 +0000151 if (!F.isDeclaration() || F.getFunctionType() == EmptyFT ||
152 // Changing the type of an intrinsic may invalidate the IR.
153 F.getName().startswith("llvm."))
Peter Collingbourne1398a322016-12-16 00:26:30 +0000154 continue;
155
156 Function *NewF =
Dylan McKayf920da02018-12-18 09:52:52 +0000157 Function::Create(EmptyFT, GlobalValue::ExternalLinkage,
158 F.getAddressSpace(), "", &M);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000159 NewF->setVisibility(F.getVisibility());
160 NewF->takeName(&F);
161 F.replaceAllUsesWith(ConstantExpr::getBitCast(NewF, F.getType()));
162 F.eraseFromParent();
163 }
164
165 for (auto I = M.global_begin(), E = M.global_end(); I != E;) {
166 GlobalVariable &GV = *I++;
167 if (GV.isDeclaration() && GV.use_empty()) {
168 GV.eraseFromParent();
169 continue;
170 }
171 }
172}
173
George Rimard3704f62018-02-08 07:23:24 +0000174static void
175filterModule(Module *M,
176 function_ref<bool(const GlobalValue *)> ShouldKeepDefinition) {
177 std::vector<GlobalValue *> V;
178 for (GlobalValue &GV : M->global_values())
179 if (!ShouldKeepDefinition(&GV))
180 V.push_back(&GV);
George Rimar54565242018-02-07 08:46:36 +0000181
George Rimard3704f62018-02-08 07:23:24 +0000182 for (GlobalValue *GV : V)
183 if (!convertToDeclaration(*GV))
184 GV->eraseFromParent();
Peter Collingbourne1398a322016-12-16 00:26:30 +0000185}
186
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000187void forEachVirtualFunction(Constant *C, function_ref<void(Function *)> Fn) {
188 if (auto *F = dyn_cast<Function>(C))
189 return Fn(F);
Peter Collingbourne3baa72a2017-03-02 23:10:17 +0000190 if (isa<GlobalValue>(C))
191 return;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000192 for (Value *Op : C->operands())
193 forEachVirtualFunction(cast<Constant>(Op), Fn);
194}
195
Peter Collingbourne1398a322016-12-16 00:26:30 +0000196// If it's possible to split M into regular and thin LTO parts, do so and write
197// a multi-module bitcode file with the two parts to OS. Otherwise, write only a
198// regular LTO bitcode file to OS.
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000199void splitAndWriteThinLTOBitcode(
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000200 raw_ostream &OS, raw_ostream *ThinLinkOS,
201 function_ref<AAResults &(Function &)> AARGetter, Module &M) {
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000202 std::string ModuleId = getUniqueModuleId(&M);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000203 if (ModuleId.empty()) {
Vlad Tsyrklevich6867ab72018-06-01 15:20:47 +0000204 // We couldn't generate a module ID for this module, write it out as a
205 // regular LTO module with an index for summary-based dead stripping.
206 ProfileSummaryInfo PSI(M);
207 M.addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
208 ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
209 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, &Index);
210
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000211 if (ThinLinkOS)
212 // We don't have a ThinLTO part, but still write the module to the
213 // ThinLinkOS if requested so that the expected output file is produced.
Vlad Tsyrklevich6867ab72018-06-01 15:20:47 +0000214 WriteBitcodeToFile(M, *ThinLinkOS, /*ShouldPreserveUseListOrder=*/false,
215 &Index);
216
Peter Collingbourne1398a322016-12-16 00:26:30 +0000217 return;
218 }
219
220 promoteTypeIds(M, ModuleId);
221
Peter Collingbournedd968212019-07-29 17:22:40 +0000222 // Returns whether a global or its associated global has attached type
223 // metadata. The former may participate in CFI or whole-program
224 // devirtualization, so they need to appear in the merged module instead of
225 // the thin LTO module. Similarly, globals that are associated with globals
226 // with type metadata need to appear in the merged module because they will
227 // reference the global's section directly.
Benjamin Kramer0deb9a92018-05-31 13:29:58 +0000228 auto HasTypeMetadata = [](const GlobalObject *GO) {
Peter Collingbournedd968212019-07-29 17:22:40 +0000229 if (MDNode *MD = GO->getMetadata(LLVMContext::MD_associated))
230 if (auto *AssocVM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(0)))
231 if (auto *AssocGO = dyn_cast<GlobalObject>(AssocVM->getValue()))
232 if (AssocGO->hasMetadata(LLVMContext::MD_type))
233 return true;
Benjamin Kramer0deb9a92018-05-31 13:29:58 +0000234 return GO->hasMetadata(LLVMContext::MD_type);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000235 };
236
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000237 // Collect the set of virtual functions that are eligible for virtual constant
238 // propagation. Each eligible function must not access memory, must return
239 // an integer of width <=64 bits, must take at least one argument, must not
240 // use its first argument (assumed to be "this") and all arguments other than
241 // the first one must be of <=64 bit integer type.
242 //
243 // Note that we test whether this copy of the function is readnone, rather
244 // than testing function attributes, which must hold for any copy of the
245 // function, even a less optimized version substituted at link time. This is
246 // sound because the virtual constant propagation optimizations effectively
247 // inline all implementations of the virtual function into each call site,
248 // rather than using function attributes to perform local optimization.
George Burgess IVaa09a822018-08-27 22:10:59 +0000249 DenseSet<const Function *> EligibleVirtualFns;
Bob Haarman4075ccc2017-04-12 01:43:07 +0000250 // If any member of a comdat lives in MergedM, put all members of that
251 // comdat in MergedM to keep the comdat together.
252 DenseSet<const Comdat *> MergedMComdats;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000253 for (GlobalVariable &GV : M.globals())
Bob Haarman4075ccc2017-04-12 01:43:07 +0000254 if (HasTypeMetadata(&GV)) {
255 if (const auto *C = GV.getComdat())
256 MergedMComdats.insert(C);
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000257 forEachVirtualFunction(GV.getInitializer(), [&](Function *F) {
258 auto *RT = dyn_cast<IntegerType>(F->getReturnType());
259 if (!RT || RT->getBitWidth() > 64 || F->arg_empty() ||
260 !F->arg_begin()->use_empty())
261 return;
262 for (auto &Arg : make_range(std::next(F->arg_begin()), F->arg_end())) {
263 auto *ArgT = dyn_cast<IntegerType>(Arg.getType());
264 if (!ArgT || ArgT->getBitWidth() > 64)
265 return;
266 }
Chandler Carruth01f0c8a2017-07-11 05:39:20 +0000267 if (!F->isDeclaration() &&
268 computeFunctionBodyMemoryAccess(*F, AARGetter(*F)) == MAK_ReadNone)
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000269 EligibleVirtualFns.insert(F);
270 });
Bob Haarman4075ccc2017-04-12 01:43:07 +0000271 }
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000272
Peter Collingbourne1398a322016-12-16 00:26:30 +0000273 ValueToValueMapTy VMap;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000274 std::unique_ptr<Module> MergedM(
Rafael Espindola71867532018-02-14 19:50:40 +0000275 CloneModule(M, VMap, [&](const GlobalValue *GV) -> bool {
Bob Haarman4075ccc2017-04-12 01:43:07 +0000276 if (const auto *C = GV->getComdat())
277 if (MergedMComdats.count(C))
278 return true;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000279 if (auto *F = dyn_cast<Function>(GV))
280 return EligibleVirtualFns.count(F);
281 if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
282 return HasTypeMetadata(GVar);
283 return false;
284 }));
Peter Collingbourne28ffd322017-02-08 20:44:00 +0000285 StripDebugInfo(*MergedM);
Peter Collingbourne29c6f482018-02-06 03:29:18 +0000286 MergedM->setModuleInlineAsm("");
Peter Collingbourne1398a322016-12-16 00:26:30 +0000287
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000288 for (Function &F : *MergedM)
289 if (!F.isDeclaration()) {
290 // Reset the linkage of all functions eligible for virtual constant
291 // propagation. The canonical definitions live in the thin LTO module so
292 // that they can be imported.
293 F.setLinkage(GlobalValue::AvailableExternallyLinkage);
294 F.setComdat(nullptr);
295 }
296
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000297 SetVector<GlobalValue *> CfiFunctions;
298 for (auto &F : M)
299 if ((!F.hasLocalLinkage() || F.hasAddressTaken()) && HasTypeMetadata(&F))
300 CfiFunctions.insert(&F);
301
Bob Haarman4075ccc2017-04-12 01:43:07 +0000302 // Remove all globals with type metadata, globals with comdats that live in
303 // MergedM, and aliases pointing to such globals from the thin LTO module.
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000304 filterModule(&M, [&](const GlobalValue *GV) {
305 if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
Bob Haarman4075ccc2017-04-12 01:43:07 +0000306 if (HasTypeMetadata(GVar))
307 return false;
308 if (const auto *C = GV->getComdat())
309 if (MergedMComdats.count(C))
310 return false;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000311 return true;
312 });
Peter Collingbourne1398a322016-12-16 00:26:30 +0000313
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000314 promoteInternals(*MergedM, M, ModuleId, CfiFunctions);
315 promoteInternals(M, *MergedM, ModuleId, CfiFunctions);
316
Vlad Tsyrklevich230b2562018-04-20 01:36:48 +0000317 auto &Ctx = MergedM->getContext();
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000318 SmallVector<MDNode *, 8> CfiFunctionMDs;
319 for (auto V : CfiFunctions) {
320 Function &F = *cast<Function>(V);
321 SmallVector<MDNode *, 2> Types;
322 F.getMetadata(LLVMContext::MD_type, Types);
323
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000324 SmallVector<Metadata *, 4> Elts;
325 Elts.push_back(MDString::get(Ctx, F.getName()));
326 CfiFunctionLinkage Linkage;
Peter Collingbourne0e497d12019-08-09 22:31:59 +0000327 if (lowertypetests::isJumpTableCanonical(&F))
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000328 Linkage = CFL_Definition;
Peter Collingbourne0e497d12019-08-09 22:31:59 +0000329 else if (F.hasExternalWeakLinkage())
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000330 Linkage = CFL_WeakDeclaration;
331 else
332 Linkage = CFL_Declaration;
333 Elts.push_back(ConstantAsMetadata::get(
334 llvm::ConstantInt::get(Type::getInt8Ty(Ctx), Linkage)));
335 for (auto Type : Types)
336 Elts.push_back(Type);
337 CfiFunctionMDs.push_back(MDTuple::get(Ctx, Elts));
338 }
339
340 if(!CfiFunctionMDs.empty()) {
341 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("cfi.functions");
342 for (auto MD : CfiFunctionMDs)
343 NMD->addOperand(MD);
344 }
Peter Collingbourne1398a322016-12-16 00:26:30 +0000345
Vlad Tsyrklevichcdec22e2018-01-10 00:00:51 +0000346 SmallVector<MDNode *, 8> FunctionAliases;
347 for (auto &A : M.aliases()) {
348 if (!isa<Function>(A.getAliasee()))
349 continue;
350
351 auto *F = cast<Function>(A.getAliasee());
Vlad Tsyrklevichcdec22e2018-01-10 00:00:51 +0000352
Benjamin Kramer0deb9a92018-05-31 13:29:58 +0000353 Metadata *Elts[] = {
354 MDString::get(Ctx, A.getName()),
355 MDString::get(Ctx, F->getName()),
356 ConstantAsMetadata::get(
357 ConstantInt::get(Type::getInt8Ty(Ctx), A.getVisibility())),
358 ConstantAsMetadata::get(
359 ConstantInt::get(Type::getInt8Ty(Ctx), A.isWeakForLinker())),
360 };
Vlad Tsyrklevichcdec22e2018-01-10 00:00:51 +0000361
362 FunctionAliases.push_back(MDTuple::get(Ctx, Elts));
363 }
364
365 if (!FunctionAliases.empty()) {
366 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("aliases");
367 for (auto MD : FunctionAliases)
368 NMD->addOperand(MD);
369 }
370
Vlad Tsyrklevich230b2562018-04-20 01:36:48 +0000371 SmallVector<MDNode *, 8> Symvers;
372 ModuleSymbolTable::CollectAsmSymvers(M, [&](StringRef Name, StringRef Alias) {
373 Function *F = M.getFunction(Name);
374 if (!F || F->use_empty())
375 return;
376
Benjamin Kramer0deb9a92018-05-31 13:29:58 +0000377 Symvers.push_back(MDTuple::get(
378 Ctx, {MDString::get(Ctx, Name), MDString::get(Ctx, Alias)}));
Vlad Tsyrklevich230b2562018-04-20 01:36:48 +0000379 });
380
381 if (!Symvers.empty()) {
382 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("symvers");
383 for (auto MD : Symvers)
384 NMD->addOperand(MD);
385 }
386
Peter Collingbourne1398a322016-12-16 00:26:30 +0000387 simplifyExternals(*MergedM);
388
Peter Collingbourne1398a322016-12-16 00:26:30 +0000389 // FIXME: Try to re-use BSI and PFI from the original module here.
Teresa Johnson94624ac2017-05-10 18:52:16 +0000390 ProfileSummaryInfo PSI(M);
391 ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000392
Peter Collingbournee357fbd2017-06-08 23:01:49 +0000393 // Mark the merged module as requiring full LTO. We still want an index for
394 // it though, so that it can participate in summary-based dead stripping.
395 MergedM->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
396 ModuleSummaryIndex MergedMIndex =
397 buildModuleSummaryIndex(*MergedM, nullptr, &PSI);
398
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000399 SmallVector<char, 0> Buffer;
400
401 BitcodeWriter W(Buffer);
402 // Save the module hash produced for the full bitcode, which will
403 // be used in the backends, and use that in the minimized bitcode
404 // produced for the full link.
405 ModuleHash ModHash = {{0}};
Rafael Espindola6a86e252018-02-14 19:11:32 +0000406 W.writeModule(M, /*ShouldPreserveUseListOrder=*/false, &Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000407 /*GenerateHash=*/true, &ModHash);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000408 W.writeModule(*MergedM, /*ShouldPreserveUseListOrder=*/false, &MergedMIndex);
Peter Collingbourne92648c22017-06-27 23:50:11 +0000409 W.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000410 W.writeStrtab();
Peter Collingbourne1398a322016-12-16 00:26:30 +0000411 OS << Buffer;
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000412
Haojie Wang1dec57d2017-07-21 17:25:20 +0000413 // If a minimized bitcode module was requested for the thin link, only
414 // the information that is needed by thin link will be written in the
415 // given OS (the merged module will be written as usual).
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000416 if (ThinLinkOS) {
417 Buffer.clear();
418 BitcodeWriter W2(Buffer);
419 StripDebugInfo(M);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000420 W2.writeThinLinkBitcode(M, Index, ModHash);
421 W2.writeModule(*MergedM, /*ShouldPreserveUseListOrder=*/false,
Peter Collingbournee357fbd2017-06-08 23:01:49 +0000422 &MergedMIndex);
Peter Collingbourne92648c22017-06-27 23:50:11 +0000423 W2.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000424 W2.writeStrtab();
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000425 *ThinLinkOS << Buffer;
426 }
Peter Collingbourne1398a322016-12-16 00:26:30 +0000427}
428
Teresa Johnsona7004362019-07-02 19:38:02 +0000429// Check if the LTO Unit splitting has been enabled.
430bool enableSplitLTOUnit(Module &M) {
Teresa Johnson290a8392019-01-11 18:31:57 +0000431 bool EnableSplitLTOUnit = false;
432 if (auto *MD = mdconst::extract_or_null<ConstantInt>(
433 M.getModuleFlag("EnableSplitLTOUnit")))
434 EnableSplitLTOUnit = MD->getZExtValue();
Teresa Johnsona7004362019-07-02 19:38:02 +0000435 return EnableSplitLTOUnit;
436}
Teresa Johnson290a8392019-01-11 18:31:57 +0000437
Teresa Johnsona7004362019-07-02 19:38:02 +0000438// Returns whether this module needs to be split because it uses type metadata.
439bool hasTypeMetadata(Module &M) {
Peter Collingbourne1398a322016-12-16 00:26:30 +0000440 for (auto &GO : M.global_objects()) {
Benjamin Kramer0deb9a92018-05-31 13:29:58 +0000441 if (GO.hasMetadata(LLVMContext::MD_type))
Peter Collingbourne1398a322016-12-16 00:26:30 +0000442 return true;
443 }
Peter Collingbourne1398a322016-12-16 00:26:30 +0000444 return false;
445}
446
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000447void writeThinLTOBitcode(raw_ostream &OS, raw_ostream *ThinLinkOS,
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000448 function_ref<AAResults &(Function &)> AARGetter,
449 Module &M, const ModuleSummaryIndex *Index) {
Teresa Johnsona7004362019-07-02 19:38:02 +0000450 std::unique_ptr<ModuleSummaryIndex> NewIndex = nullptr;
451 // See if this module has any type metadata. If so, we try to split it
452 // or at least promote type ids to enable WPD.
453 if (hasTypeMetadata(M)) {
454 if (enableSplitLTOUnit(M))
455 return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M);
456 // Promote type ids as needed for index-based WPD.
457 std::string ModuleId = getUniqueModuleId(&M);
458 if (!ModuleId.empty()) {
459 promoteTypeIds(M, ModuleId);
460 // Need to rebuild the index so that it contains type metadata
461 // for the newly promoted type ids.
462 // FIXME: Probably should not bother building the index at all
463 // in the caller of writeThinLTOBitcode (which does so via the
464 // ModuleSummaryIndexAnalysis pass), since we have to rebuild it
465 // anyway whenever there is type metadata (here or in
466 // splitAndWriteThinLTOBitcode). Just always build it once via the
467 // buildModuleSummaryIndex when Module(s) are ready.
468 ProfileSummaryInfo PSI(M);
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000469 NewIndex = std::make_unique<ModuleSummaryIndex>(
Teresa Johnsona7004362019-07-02 19:38:02 +0000470 buildModuleSummaryIndex(M, nullptr, &PSI));
471 Index = NewIndex.get();
472 }
473 }
Peter Collingbourne1398a322016-12-16 00:26:30 +0000474
Teresa Johnsona7004362019-07-02 19:38:02 +0000475 // Write it out as an unsplit ThinLTO module.
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000476
477 // Save the module hash produced for the full bitcode, which will
478 // be used in the backends, and use that in the minimized bitcode
479 // produced for the full link.
480 ModuleHash ModHash = {{0}};
Rafael Espindola6a86e252018-02-14 19:11:32 +0000481 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000482 /*GenerateHash=*/true, &ModHash);
Haojie Wang1dec57d2017-07-21 17:25:20 +0000483 // If a minimized bitcode module was requested for the thin link, only
484 // the information that is needed by thin link will be written in the
485 // given OS.
486 if (ThinLinkOS && Index)
Rafael Espindola6a86e252018-02-14 19:11:32 +0000487 WriteThinLinkBitcodeToFile(M, *ThinLinkOS, *Index, ModHash);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000488}
489
490class WriteThinLTOBitcode : public ModulePass {
491 raw_ostream &OS; // raw_ostream to print on
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000492 // The output stream on which to emit a minimized module for use
493 // just in the thin link, if requested.
494 raw_ostream *ThinLinkOS;
Peter Collingbourne1398a322016-12-16 00:26:30 +0000495
496public:
497 static char ID; // Pass identification, replacement for typeid
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000498 WriteThinLTOBitcode() : ModulePass(ID), OS(dbgs()), ThinLinkOS(nullptr) {
Peter Collingbourne1398a322016-12-16 00:26:30 +0000499 initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
500 }
501
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000502 explicit WriteThinLTOBitcode(raw_ostream &o, raw_ostream *ThinLinkOS)
503 : ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS) {
Peter Collingbourne1398a322016-12-16 00:26:30 +0000504 initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
505 }
506
507 StringRef getPassName() const override { return "ThinLTO Bitcode Writer"; }
508
509 bool runOnModule(Module &M) override {
510 const ModuleSummaryIndex *Index =
511 &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex());
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000512 writeThinLTOBitcode(OS, ThinLinkOS, LegacyAARGetter(*this), M, Index);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000513 return true;
514 }
515 void getAnalysisUsage(AnalysisUsage &AU) const override {
516 AU.setPreservesAll();
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000517 AU.addRequired<AssumptionCacheTracker>();
Peter Collingbourne1398a322016-12-16 00:26:30 +0000518 AU.addRequired<ModuleSummaryIndexWrapperPass>();
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000519 AU.addRequired<TargetLibraryInfoWrapperPass>();
Peter Collingbourne1398a322016-12-16 00:26:30 +0000520 }
521};
522} // anonymous namespace
523
524char WriteThinLTOBitcode::ID = 0;
525INITIALIZE_PASS_BEGIN(WriteThinLTOBitcode, "write-thinlto-bitcode",
526 "Write ThinLTO Bitcode", false, true)
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000527INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Peter Collingbourne1398a322016-12-16 00:26:30 +0000528INITIALIZE_PASS_DEPENDENCY(ModuleSummaryIndexWrapperPass)
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000529INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Peter Collingbourne1398a322016-12-16 00:26:30 +0000530INITIALIZE_PASS_END(WriteThinLTOBitcode, "write-thinlto-bitcode",
531 "Write ThinLTO Bitcode", false, true)
532
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000533ModulePass *llvm::createWriteThinLTOBitcodePass(raw_ostream &Str,
534 raw_ostream *ThinLinkOS) {
535 return new WriteThinLTOBitcode(Str, ThinLinkOS);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000536}
Tim Shen6b4114182017-06-01 01:02:12 +0000537
538PreservedAnalyses
539llvm::ThinLTOBitcodeWriterPass::run(Module &M, ModuleAnalysisManager &AM) {
540 FunctionAnalysisManager &FAM =
541 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
542 writeThinLTOBitcode(OS, ThinLinkOS,
543 [&FAM](Function &F) -> AAResults & {
544 return FAM.getResult<AAManager>(F);
545 },
546 M, &AM.getResult<ModuleSummaryIndexAnalysis>(M));
547 return PreservedAnalyses::all();
548}