blob: 58cd99abcb5f009d9dad388e6da49095a3775c9d [file] [log] [blame]
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001//===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===//
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 Collingbournedf49d1b2016-02-09 22:50:34 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements whole program optimization of virtual calls in cases
Peter Collingbourne7efd7502016-06-24 21:21:32 +000010// where we know (via !type metadata) that the list of callees is fixed. This
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000011// includes the following:
12// - Single implementation devirtualization: if a virtual call has a single
13// possible callee, replace all calls with a direct call to that callee.
14// - Virtual constant propagation: if the virtual function's return type is an
15// integer <=64 bits and all possible callees are readnone, for each class and
16// each list of constant arguments: evaluate the function, store the return
17// value alongside the virtual table, and rewrite each virtual call as a load
18// from the virtual table.
19// - Uniform return value optimization: if the conditions for virtual constant
20// propagation hold and each function returns the same constant value, replace
21// each virtual call with that constant.
22// - Unique return value optimization for i1 return values: if the conditions
23// for virtual constant propagation hold and a single vtable's function
24// returns 0, or a single vtable's function returns 1, replace each virtual
25// call with a comparison of the vptr against that vtable's address.
26//
Teresa Johnsond2df54e2019-08-02 13:10:52 +000027// This pass is intended to be used during the regular and thin LTO pipelines:
28//
Peter Collingbourneb406baa2017-03-04 01:23:30 +000029// During regular LTO, the pass determines the best optimization for each
30// virtual call and applies the resolutions directly to virtual calls that are
31// eligible for virtual call optimization (i.e. calls that use either of the
Teresa Johnsond2df54e2019-08-02 13:10:52 +000032// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics).
33//
34// During hybrid Regular/ThinLTO, the pass operates in two phases:
Peter Collingbourneb406baa2017-03-04 01:23:30 +000035// - Export phase: this is run during the thin link over a single merged module
36// that contains all vtables with !type metadata that participate in the link.
37// The pass computes a resolution for each virtual call and stores it in the
38// type identifier summary.
39// - Import phase: this is run during the thin backends over the individual
40// modules. The pass applies the resolutions previously computed during the
41// import phase to each eligible virtual call.
42//
Teresa Johnsond2df54e2019-08-02 13:10:52 +000043// During ThinLTO, the pass operates in two phases:
44// - Export phase: this is run during the thin link over the index which
45// contains a summary of all vtables with !type metadata that participate in
46// the link. It computes a resolution for each virtual call and stores it in
47// the type identifier summary. Only single implementation devirtualization
48// is supported.
49// - Import phase: (same as with hybrid case above).
50//
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000051//===----------------------------------------------------------------------===//
52
53#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000054#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000055#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/DenseMapInfo.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000057#include "llvm/ADT/DenseSet.h"
58#include "llvm/ADT/MapVector.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000059#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000060#include "llvm/ADT/iterator_range.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000061#include "llvm/Analysis/AliasAnalysis.h"
62#include "llvm/Analysis/BasicAliasAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000063#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Peter Collingbourne7efd7502016-06-24 21:21:32 +000064#include "llvm/Analysis/TypeMetadataUtils.h"
Evgeny Leviant8973fae2020-01-24 00:31:39 -080065#include "llvm/Bitcode/BitcodeReader.h"
66#include "llvm/Bitcode/BitcodeWriter.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000067#include "llvm/IR/CallSite.h"
68#include "llvm/IR/Constants.h"
69#include "llvm/IR/DataLayout.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000070#include "llvm/IR/DebugLoc.h"
71#include "llvm/IR/DerivedTypes.h"
Teresa Johnsonf24136f2018-09-27 14:55:32 +000072#include "llvm/IR/Dominators.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000073#include "llvm/IR/Function.h"
74#include "llvm/IR/GlobalAlias.h"
75#include "llvm/IR/GlobalVariable.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000076#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000077#include "llvm/IR/InstrTypes.h"
78#include "llvm/IR/Instruction.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000079#include "llvm/IR/Instructions.h"
80#include "llvm/IR/Intrinsics.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000081#include "llvm/IR/LLVMContext.h"
82#include "llvm/IR/Metadata.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000083#include "llvm/IR/Module.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000084#include "llvm/IR/ModuleSummaryIndexYAML.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080085#include "llvm/InitializePasses.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000086#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000087#include "llvm/PassRegistry.h"
88#include "llvm/PassSupport.h"
89#include "llvm/Support/Casting.h"
Reid Kleckner4c1a1d32019-11-14 15:15:48 -080090#include "llvm/Support/CommandLine.h"
Evgeny Leviant8973fae2020-01-24 00:31:39 -080091#include "llvm/Support/Errc.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000092#include "llvm/Support/Error.h"
93#include "llvm/Support/FileSystem.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000094#include "llvm/Support/MathExtras.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000095#include "llvm/Transforms/IPO.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000096#include "llvm/Transforms/IPO/FunctionAttrs.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000097#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000098#include <algorithm>
99#include <cstddef>
100#include <map>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000101#include <set>
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000102#include <string>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000103
104using namespace llvm;
105using namespace wholeprogramdevirt;
106
107#define DEBUG_TYPE "wholeprogramdevirt"
108
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000109static cl::opt<PassSummaryAction> ClSummaryAction(
110 "wholeprogramdevirt-summary-action",
111 cl::desc("What to do with the summary when running this pass"),
112 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
113 clEnumValN(PassSummaryAction::Import, "import",
114 "Import typeid resolutions from summary and globals"),
115 clEnumValN(PassSummaryAction::Export, "export",
116 "Export typeid resolutions to summary and globals")),
117 cl::Hidden);
118
119static cl::opt<std::string> ClReadSummary(
120 "wholeprogramdevirt-read-summary",
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800121 cl::desc(
122 "Read summary from given bitcode or YAML file before running pass"),
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000123 cl::Hidden);
124
125static cl::opt<std::string> ClWriteSummary(
126 "wholeprogramdevirt-write-summary",
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800127 cl::desc("Write summary to given bitcode or YAML file after running pass. "
128 "Output file format is deduced from extension: *.bc means writing "
129 "bitcode, otherwise YAML"),
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000130 cl::Hidden);
131
Vitaly Buka9cb59b92018-04-06 21:41:17 +0000132static cl::opt<unsigned>
133 ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden,
134 cl::init(10), cl::ZeroOrMore,
135 cl::desc("Maximum number of call targets per "
136 "call site to enable branch funnels"));
Vitaly Buka66f53d72018-04-06 21:32:36 +0000137
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000138static cl::opt<bool>
139 PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden,
140 cl::init(false), cl::ZeroOrMore,
141 cl::desc("Print index-based devirtualization messages"));
142
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000143// Find the minimum offset that we may store a value of size Size bits at. If
144// IsAfter is set, look for an offset before the object, otherwise look for an
145// offset after the object.
146uint64_t
147wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
148 bool IsAfter, uint64_t Size) {
149 // Find a minimum offset taking into account only vtable sizes.
150 uint64_t MinByte = 0;
151 for (const VirtualCallTarget &Target : Targets) {
152 if (IsAfter)
153 MinByte = std::max(MinByte, Target.minAfterBytes());
154 else
155 MinByte = std::max(MinByte, Target.minBeforeBytes());
156 }
157
158 // Build a vector of arrays of bytes covering, for each target, a slice of the
159 // used region (see AccumBitVector::BytesUsed in
160 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
161 // this aligns the used regions to start at MinByte.
162 //
163 // In this example, A, B and C are vtables, # is a byte already allocated for
164 // a virtual function pointer, AAAA... (etc.) are the used regions for the
165 // vtables and Offset(X) is the value computed for the Offset variable below
166 // for X.
167 //
168 // Offset(A)
169 // | |
170 // |MinByte
171 // A: ################AAAAAAAA|AAAAAAAA
172 // B: ########BBBBBBBBBBBBBBBB|BBBB
173 // C: ########################|CCCCCCCCCCCCCCCC
174 // | Offset(B) |
175 //
176 // This code produces the slices of A, B and C that appear after the divider
177 // at MinByte.
178 std::vector<ArrayRef<uint8_t>> Used;
179 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000180 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
181 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000182 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
183 : MinByte - Target.minBeforeBytes();
184
185 // Disregard used regions that are smaller than Offset. These are
186 // effectively all-free regions that do not need to be checked.
187 if (VTUsed.size() > Offset)
188 Used.push_back(VTUsed.slice(Offset));
189 }
190
191 if (Size == 1) {
192 // Find a free bit in each member of Used.
193 for (unsigned I = 0;; ++I) {
194 uint8_t BitsUsed = 0;
195 for (auto &&B : Used)
196 if (I < B.size())
197 BitsUsed |= B[I];
198 if (BitsUsed != 0xff)
199 return (MinByte + I) * 8 +
200 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
201 }
202 } else {
203 // Find a free (Size/8) byte region in each member of Used.
204 // FIXME: see if alignment helps.
205 for (unsigned I = 0;; ++I) {
206 for (auto &&B : Used) {
207 unsigned Byte = 0;
208 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
209 if (B[I + Byte])
210 goto NextI;
211 ++Byte;
212 }
213 }
214 return (MinByte + I) * 8;
215 NextI:;
216 }
217 }
218}
219
220void wholeprogramdevirt::setBeforeReturnValues(
221 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
222 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
223 if (BitWidth == 1)
224 OffsetByte = -(AllocBefore / 8 + 1);
225 else
226 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
227 OffsetBit = AllocBefore % 8;
228
229 for (VirtualCallTarget &Target : Targets) {
230 if (BitWidth == 1)
231 Target.setBeforeBit(AllocBefore);
232 else
233 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
234 }
235}
236
237void wholeprogramdevirt::setAfterReturnValues(
238 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
239 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
240 if (BitWidth == 1)
241 OffsetByte = AllocAfter / 8;
242 else
243 OffsetByte = (AllocAfter + 7) / 8;
244 OffsetBit = AllocAfter % 8;
245
246 for (VirtualCallTarget &Target : Targets) {
247 if (BitWidth == 1)
248 Target.setAfterBit(AllocAfter);
249 else
250 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
251 }
252}
253
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000254VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
255 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000256 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000257
258namespace {
259
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000260// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000261// tables, and the ByteOffset is the offset in bytes from the address point to
262// the virtual function pointer.
263struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000264 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000265 uint64_t ByteOffset;
266};
267
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000268} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000269
Peter Collingbourne9b656522016-02-09 23:01:38 +0000270namespace llvm {
271
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000272template <> struct DenseMapInfo<VTableSlot> {
273 static VTableSlot getEmptyKey() {
274 return {DenseMapInfo<Metadata *>::getEmptyKey(),
275 DenseMapInfo<uint64_t>::getEmptyKey()};
276 }
277 static VTableSlot getTombstoneKey() {
278 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
279 DenseMapInfo<uint64_t>::getTombstoneKey()};
280 }
281 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000282 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000283 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
284 }
285 static bool isEqual(const VTableSlot &LHS,
286 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000287 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000288 }
289};
290
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000291template <> struct DenseMapInfo<VTableSlotSummary> {
292 static VTableSlotSummary getEmptyKey() {
293 return {DenseMapInfo<StringRef>::getEmptyKey(),
294 DenseMapInfo<uint64_t>::getEmptyKey()};
295 }
296 static VTableSlotSummary getTombstoneKey() {
297 return {DenseMapInfo<StringRef>::getTombstoneKey(),
298 DenseMapInfo<uint64_t>::getTombstoneKey()};
299 }
300 static unsigned getHashValue(const VTableSlotSummary &I) {
301 return DenseMapInfo<StringRef>::getHashValue(I.TypeID) ^
302 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
303 }
304 static bool isEqual(const VTableSlotSummary &LHS,
305 const VTableSlotSummary &RHS) {
306 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
307 }
308};
309
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000310} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000311
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000312namespace {
313
314// A virtual call site. VTable is the loaded virtual table pointer, and CS is
315// the indirect virtual call.
316struct VirtualCallSite {
317 Value *VTable;
318 CallSite CS;
319
Peter Collingbourne0312f612016-06-25 00:23:04 +0000320 // If non-null, this field points to the associated unsafe use count stored in
321 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
322 // of that field for details.
323 unsigned *NumUnsafeUses;
324
Sam Elliotte963c892017-08-21 16:57:21 +0000325 void
326 emitRemark(const StringRef OptName, const StringRef TargetName,
327 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Ivan Krasin54746452016-07-12 02:38:37 +0000328 Function *F = CS.getCaller();
Sam Elliotte963c892017-08-21 16:57:21 +0000329 DebugLoc DLoc = CS->getDebugLoc();
330 BasicBlock *Block = CS.getParent();
331
Sam Elliotte963c892017-08-21 16:57:21 +0000332 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000333 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
334 << NV("Optimization", OptName)
335 << ": devirtualized a call to "
336 << NV("FunctionName", TargetName));
Ivan Krasin54746452016-07-12 02:38:37 +0000337 }
338
Sam Elliotte963c892017-08-21 16:57:21 +0000339 void replaceAndErase(
340 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
341 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
342 Value *New) {
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000343 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000344 emitRemark(OptName, TargetName, OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000345 CS->replaceAllUsesWith(New);
346 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
347 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
348 II->getUnwindDest()->removePredecessor(II->getParent());
349 }
350 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000351 // This use is no longer unsafe.
352 if (NumUnsafeUses)
353 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000354 }
355};
356
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000357// Call site information collected for a specific VTableSlot and possibly a list
358// of constant integer arguments. The grouping by arguments is handled by the
359// VTableSlotInfo class.
360struct CallSiteInfo {
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000361 /// The set of call sites for this slot. Used during regular LTO and the
362 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
363 /// call sites that appear in the merged module itself); in each of these
364 /// cases we are directly operating on the call sites at the IR level.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000365 std::vector<VirtualCallSite> CallSites;
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000366
Peter Collingbourne29748562018-03-09 19:11:44 +0000367 /// Whether all call sites represented by this CallSiteInfo, including those
368 /// in summaries, have been devirtualized. This starts off as true because a
369 /// default constructed CallSiteInfo represents no call sites.
370 bool AllCallSitesDevirted = true;
371
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000372 // These fields are used during the export phase of ThinLTO and reflect
373 // information collected from function summaries.
374
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000375 /// Whether any function summary contains an llvm.assume(llvm.type.test) for
376 /// this slot.
Peter Collingbourne29748562018-03-09 19:11:44 +0000377 bool SummaryHasTypeTestAssumeUsers = false;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000378
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000379 /// CFI-specific: a vector containing the list of function summaries that use
380 /// the llvm.type.checked.load intrinsic and therefore will require
381 /// resolutions for llvm.type.test in order to implement CFI checks if
382 /// devirtualization was unsuccessful. If devirtualization was successful, the
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000383 /// pass will clear this vector by calling markDevirt(). If at the end of the
384 /// pass the vector is non-empty, we will need to add a use of llvm.type.test
385 /// to each of the function summaries in the vector.
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000386 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000387 std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000388
389 bool isExported() const {
390 return SummaryHasTypeTestAssumeUsers ||
391 !SummaryTypeCheckedLoadUsers.empty();
392 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000393
Peter Collingbourne29748562018-03-09 19:11:44 +0000394 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
395 SummaryTypeCheckedLoadUsers.push_back(FS);
396 AllCallSitesDevirted = false;
397 }
398
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000399 void addSummaryTypeTestAssumeUser(FunctionSummary *FS) {
400 SummaryTypeTestAssumeUsers.push_back(FS);
Eugene Leviant943afb52019-10-17 07:46:18 +0000401 SummaryHasTypeTestAssumeUsers = true;
402 AllCallSitesDevirted = false;
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000403 }
404
Peter Collingbourne29748562018-03-09 19:11:44 +0000405 void markDevirt() {
406 AllCallSitesDevirted = true;
407
408 // As explained in the comment for SummaryTypeCheckedLoadUsers.
409 SummaryTypeCheckedLoadUsers.clear();
410 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000411};
412
413// Call site information collected for a specific VTableSlot.
414struct VTableSlotInfo {
415 // The set of call sites which do not have all constant integer arguments
416 // (excluding "this").
417 CallSiteInfo CSInfo;
418
419 // The set of call sites with all constant integer arguments (excluding
420 // "this"), grouped by argument list.
421 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
422
423 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
424
425private:
426 CallSiteInfo &findCallSiteInfo(CallSite CS);
427};
428
429CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
430 std::vector<uint64_t> Args;
431 auto *CI = dyn_cast<IntegerType>(CS.getType());
432 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
433 return CSInfo;
434 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
435 auto *CI = dyn_cast<ConstantInt>(Arg);
436 if (!CI || CI->getBitWidth() > 64)
437 return CSInfo;
438 Args.push_back(CI->getZExtValue());
439 }
440 return ConstCSInfo[Args];
441}
442
443void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
444 unsigned *NumUnsafeUses) {
Peter Collingbourne29748562018-03-09 19:11:44 +0000445 auto &CSI = findCallSiteInfo(CS);
446 CSI.AllCallSitesDevirted = false;
447 CSI.CallSites.push_back({VTable, CS, NumUnsafeUses});
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000448}
449
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000450struct DevirtModule {
451 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000452 function_ref<AAResults &(Function &)> AARGetter;
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000453 function_ref<DominatorTree &(Function &)> LookupDomTree;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000454
Peter Collingbournef7691d82017-03-22 18:22:59 +0000455 ModuleSummaryIndex *ExportSummary;
456 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000457
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000458 IntegerType *Int8Ty;
459 PointerType *Int8PtrTy;
460 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000461 IntegerType *Int64Ty;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000462 IntegerType *IntPtrTy;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000463
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000464 bool RemarksEnabled;
Sam Elliotte963c892017-08-21 16:57:21 +0000465 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000466
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000467 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000468
Peter Collingbourne0312f612016-06-25 00:23:04 +0000469 // This map keeps track of the number of "unsafe" uses of a loaded function
470 // pointer. The key is the associated llvm.type.test intrinsic call generated
471 // by this pass. An unsafe use is one that calls the loaded function pointer
472 // directly. Every time we eliminate an unsafe use (for example, by
473 // devirtualizing it or by applying virtual constant propagation), we
474 // decrement the value stored in this map. If a value reaches zero, we can
475 // eliminate the type check by RAUWing the associated llvm.type.test call with
476 // true.
477 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
478
Peter Collingbourne37317f12017-02-17 18:17:04 +0000479 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
Sam Elliotte963c892017-08-21 16:57:21 +0000480 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000481 function_ref<DominatorTree &(Function &)> LookupDomTree,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000482 ModuleSummaryIndex *ExportSummary,
483 const ModuleSummaryIndex *ImportSummary)
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000484 : M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree),
485 ExportSummary(ExportSummary), ImportSummary(ImportSummary),
486 Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000487 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000488 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000489 Int64Ty(Type::getInt64Ty(M.getContext())),
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000490 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Sam Elliotte963c892017-08-21 16:57:21 +0000491 RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000492 assert(!(ExportSummary && ImportSummary));
493 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000494
495 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000496
Teresa Johnsonc8e36862019-12-06 12:13:34 -0800497 void scanTypeTestUsers(Function *TypeTestFunc);
Peter Collingbourne0312f612016-06-25 00:23:04 +0000498 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
499
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000500 void buildTypeIdentifierMap(
501 std::vector<VTableBits> &Bits,
502 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
503 bool
504 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
505 const std::set<TypeMemberInfo> &TypeMemberInfos,
506 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000507
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000508 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
509 bool &IsExported);
Eugene Leviant943afb52019-10-17 07:46:18 +0000510 bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary,
511 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000512 VTableSlotInfo &SlotInfo,
513 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000514
Peter Collingbourne29748562018-03-09 19:11:44 +0000515 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT,
516 bool &IsExported);
517 void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
518 VTableSlotInfo &SlotInfo,
519 WholeProgramDevirtResolution *Res, VTableSlot Slot);
520
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000521 bool tryEvaluateFunctionsWithArgs(
522 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000523 ArrayRef<uint64_t> Args);
524
525 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
526 uint64_t TheRetVal);
527 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000528 CallSiteInfo &CSInfo,
529 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000530
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000531 // Returns the global symbol name that is used to export information about the
532 // given vtable slot and list of arguments.
533 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
534 StringRef Name);
535
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000536 bool shouldExportConstantsAsAbsoluteSymbols();
537
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000538 // This function is called during the export phase to create a symbol
539 // definition containing information about the given vtable slot and list of
540 // arguments.
541 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
542 Constant *C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000543 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
544 uint32_t Const, uint32_t &Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000545
546 // This function is called during the import phase to create a reference to
547 // the symbol definition created during the export phase.
548 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000549 StringRef Name);
550 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
551 StringRef Name, IntegerType *IntTy,
552 uint32_t Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000553
Peter Collingbourne29748562018-03-09 19:11:44 +0000554 Constant *getMemberAddr(const TypeMemberInfo *M);
555
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000556 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
557 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000558 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000559 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000560 CallSiteInfo &CSInfo,
561 WholeProgramDevirtResolution::ByArg *Res,
562 VTableSlot Slot, ArrayRef<uint64_t> Args);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000563
564 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
565 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000566 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000567 VTableSlotInfo &SlotInfo,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000568 WholeProgramDevirtResolution *Res, VTableSlot Slot);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000569
570 void rebuildGlobal(VTableBits &B);
571
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000572 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
573 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
574
575 // If we were able to eliminate all unsafe uses for a type checked load,
576 // eliminate the associated type tests by replacing them with true.
577 void removeRedundantTypeTests();
578
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000579 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000580
581 // Lower the module using the action and summary passed as command line
582 // arguments. For testing purposes only.
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000583 static bool
584 runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter,
585 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
586 function_ref<DominatorTree &(Function &)> LookupDomTree);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000587};
588
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000589struct DevirtIndex {
590 ModuleSummaryIndex &ExportSummary;
591 // The set in which to record GUIDs exported from their module by
592 // devirtualization, used by client to ensure they are not internalized.
593 std::set<GlobalValue::GUID> &ExportedGUIDs;
594 // A map in which to record the information necessary to locate the WPD
595 // resolution for local targets in case they are exported by cross module
596 // importing.
597 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap;
598
599 MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots;
600
601 DevirtIndex(
602 ModuleSummaryIndex &ExportSummary,
603 std::set<GlobalValue::GUID> &ExportedGUIDs,
604 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap)
605 : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs),
606 LocalWPDTargetsMap(LocalWPDTargetsMap) {}
607
608 bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot,
609 const TypeIdCompatibleVtableInfo TIdInfo,
610 uint64_t ByteOffset);
611
612 bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
613 VTableSlotSummary &SlotSummary,
614 VTableSlotInfo &SlotInfo,
615 WholeProgramDevirtResolution *Res,
616 std::set<ValueInfo> &DevirtTargets);
617
618 void run();
619};
620
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000621struct WholeProgramDevirt : public ModulePass {
622 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000623
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000624 bool UseCommandLine = false;
625
Simon Pilgrim39c08292019-11-14 13:54:29 +0000626 ModuleSummaryIndex *ExportSummary = nullptr;
627 const ModuleSummaryIndex *ImportSummary = nullptr;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000628
629 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
630 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
631 }
632
Peter Collingbournef7691d82017-03-22 18:22:59 +0000633 WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
634 const ModuleSummaryIndex *ImportSummary)
635 : ModulePass(ID), ExportSummary(ExportSummary),
636 ImportSummary(ImportSummary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000637 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
638 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000639
640 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000641 if (skipModule(M))
642 return false;
Sam Elliotte963c892017-08-21 16:57:21 +0000643
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000644 // In the new pass manager, we can request the optimization
645 // remark emitter pass on a per-function-basis, which the
646 // OREGetter will do for us.
647 // In the old pass manager, this is harder, so we just build
648 // an optimization remark emitter on the fly, when we need it.
649 std::unique_ptr<OptimizationRemarkEmitter> ORE;
650 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000651 ORE = std::make_unique<OptimizationRemarkEmitter>(F);
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000652 return *ORE;
653 };
Sam Elliotte963c892017-08-21 16:57:21 +0000654
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000655 auto LookupDomTree = [this](Function &F) -> DominatorTree & {
656 return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
657 };
Sam Elliotte963c892017-08-21 16:57:21 +0000658
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000659 if (UseCommandLine)
660 return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter,
661 LookupDomTree);
662
663 return DevirtModule(M, LegacyAARGetter(*this), OREGetter, LookupDomTree,
664 ExportSummary, ImportSummary)
Peter Collingbournef7691d82017-03-22 18:22:59 +0000665 .run();
Peter Collingbourne37317f12017-02-17 18:17:04 +0000666 }
667
668 void getAnalysisUsage(AnalysisUsage &AU) const override {
669 AU.addRequired<AssumptionCacheTracker>();
670 AU.addRequired<TargetLibraryInfoWrapperPass>();
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000671 AU.addRequired<DominatorTreeWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000672 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000673};
674
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000675} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000676
Peter Collingbourne37317f12017-02-17 18:17:04 +0000677INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
678 "Whole program devirtualization", false, false)
679INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
680INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000681INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Peter Collingbourne37317f12017-02-17 18:17:04 +0000682INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
683 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000684char WholeProgramDevirt::ID = 0;
685
Peter Collingbournef7691d82017-03-22 18:22:59 +0000686ModulePass *
687llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
688 const ModuleSummaryIndex *ImportSummary) {
689 return new WholeProgramDevirt(ExportSummary, ImportSummary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000690}
691
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000692PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000693 ModuleAnalysisManager &AM) {
694 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
695 auto AARGetter = [&](Function &F) -> AAResults & {
696 return FAM.getResult<AAManager>(F);
697 };
Sam Elliotte963c892017-08-21 16:57:21 +0000698 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
699 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
700 };
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000701 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & {
702 return FAM.getResult<DominatorTreeAnalysis>(F);
703 };
704 if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary,
705 ImportSummary)
Teresa Johnson28023db2018-07-19 14:51:32 +0000706 .run())
Davide Italianod737dd22016-06-14 21:44:19 +0000707 return PreservedAnalyses::all();
708 return PreservedAnalyses::none();
709}
710
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000711namespace llvm {
712void runWholeProgramDevirtOnIndex(
713 ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs,
714 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
715 DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run();
716}
717
718void updateIndexWPDForExports(
719 ModuleSummaryIndex &Summary,
evgeny3d708bf2019-11-15 16:13:19 +0300720 function_ref<bool(StringRef, ValueInfo)> isExported,
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000721 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
722 for (auto &T : LocalWPDTargetsMap) {
723 auto &VI = T.first;
724 // This was enforced earlier during trySingleImplDevirt.
725 assert(VI.getSummaryList().size() == 1 &&
726 "Devirt of local target has more than one copy");
727 auto &S = VI.getSummaryList()[0];
evgeny3d708bf2019-11-15 16:13:19 +0300728 if (!isExported(S->modulePath(), VI))
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000729 continue;
730
731 // It's been exported by a cross module import.
732 for (auto &SlotSummary : T.second) {
733 auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID);
734 assert(TIdSum);
735 auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset);
736 assert(WPDRes != TIdSum->WPDRes.end());
737 WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
738 WPDRes->second.SingleImplName,
739 Summary.getModuleHash(S->modulePath()));
740 }
741 }
742}
743
744} // end namespace llvm
745
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800746static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary) {
747 // Check that summary index contains regular LTO module when performing
748 // export to prevent occasional use of index from pure ThinLTO compilation
749 // (-fno-split-lto-module). This kind of summary index is passed to
750 // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting.
751 const auto &ModPaths = Summary->modulePaths();
752 if (ClSummaryAction != PassSummaryAction::Import &&
753 ModPaths.find(ModuleSummaryIndex::getRegularLTOModuleName()) ==
754 ModPaths.end())
755 return createStringError(
756 errc::invalid_argument,
757 "combined summary should contain Regular LTO module");
758 return ErrorSuccess();
759}
760
Peter Collingbourne37317f12017-02-17 18:17:04 +0000761bool DevirtModule::runForTesting(
Sam Elliotte963c892017-08-21 16:57:21 +0000762 Module &M, function_ref<AAResults &(Function &)> AARGetter,
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000763 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
764 function_ref<DominatorTree &(Function &)> LookupDomTree) {
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800765 std::unique_ptr<ModuleSummaryIndex> Summary =
766 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000767
768 // Handle the command-line summary arguments. This code is for testing
769 // purposes only, so we handle errors directly.
770 if (!ClReadSummary.empty()) {
771 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
772 ": ");
773 auto ReadSummaryFile =
774 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800775 if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr =
776 getModuleSummaryIndex(*ReadSummaryFile)) {
777 Summary = std::move(*SummaryOrErr);
778 ExitOnErr(checkCombinedSummaryForTesting(Summary.get()));
779 } else {
780 // Try YAML if we've failed with bitcode.
781 consumeError(SummaryOrErr.takeError());
782 yaml::Input In(ReadSummaryFile->getBuffer());
783 In >> *Summary;
784 ExitOnErr(errorCodeToError(In.error()));
785 }
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000786 }
787
Peter Collingbournef7691d82017-03-22 18:22:59 +0000788 bool Changed =
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800789 DevirtModule(M, AARGetter, OREGetter, LookupDomTree,
790 ClSummaryAction == PassSummaryAction::Export ? Summary.get()
791 : nullptr,
792 ClSummaryAction == PassSummaryAction::Import ? Summary.get()
793 : nullptr)
Peter Collingbournef7691d82017-03-22 18:22:59 +0000794 .run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000795
796 if (!ClWriteSummary.empty()) {
797 ExitOnError ExitOnErr(
798 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
799 std::error_code EC;
Evgeny Leviant8973fae2020-01-24 00:31:39 -0800800 if (StringRef(ClWriteSummary).endswith(".bc")) {
801 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None);
802 ExitOnErr(errorCodeToError(EC));
803 WriteIndexToFile(*Summary, OS);
804 } else {
805 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_Text);
806 ExitOnErr(errorCodeToError(EC));
807 yaml::Output Out(OS);
808 Out << *Summary;
809 }
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000810 }
811
812 return Changed;
813}
814
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000815void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000816 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000817 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000818 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000819 Bits.reserve(M.getGlobalList().size());
820 SmallVector<MDNode *, 2> Types;
821 for (GlobalVariable &GV : M.globals()) {
822 Types.clear();
823 GV.getMetadata(LLVMContext::MD_type, Types);
Eugene Leviant2b70d612018-09-23 13:27:47 +0000824 if (GV.isDeclaration() || Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000825 continue;
826
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000827 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000828 if (!BitsPtr) {
829 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000830 Bits.back().GV = &GV;
831 Bits.back().ObjectSize =
832 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000833 BitsPtr = &Bits.back();
834 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000835
836 for (MDNode *Type : Types) {
837 auto TypeID = Type->getOperand(1).get();
838
839 uint64_t Offset =
840 cast<ConstantInt>(
841 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
842 ->getZExtValue();
843
844 TypeIdMap[TypeID].insert({BitsPtr, Offset});
845 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000846 }
847}
848
849bool DevirtModule::tryFindVirtualCallTargets(
850 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000851 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
852 for (const TypeMemberInfo &TM : TypeMemberInfos) {
853 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000854 return false;
855
Peter Collingbourne87867542016-12-09 01:10:11 +0000856 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
Oliver Stannard3b598b92019-10-17 09:58:57 +0000857 TM.Offset + ByteOffset, M);
Peter Collingbourne87867542016-12-09 01:10:11 +0000858 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000859 return false;
860
Peter Collingbourne87867542016-12-09 01:10:11 +0000861 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000862 if (!Fn)
863 return false;
864
865 // We can disregard __cxa_pure_virtual as a possible call target, as
866 // calls to pure virtuals are UB.
867 if (Fn->getName() == "__cxa_pure_virtual")
868 continue;
869
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000870 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000871 }
872
873 // Give up if we couldn't find any targets.
874 return !TargetsForSlot.empty();
875}
876
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000877bool DevirtIndex::tryFindVirtualCallTargets(
878 std::vector<ValueInfo> &TargetsForSlot, const TypeIdCompatibleVtableInfo TIdInfo,
879 uint64_t ByteOffset) {
Mark de Wever098d3342019-12-22 19:20:17 +0100880 for (const TypeIdOffsetVtableInfo &P : TIdInfo) {
Teresa Johnsonc844f882019-10-25 14:56:12 -0700881 // Find the first non-available_externally linkage vtable initializer.
882 // We can have multiple available_externally, linkonce_odr and weak_odr
883 // vtable initializers, however we want to skip available_externally as they
884 // do not have type metadata attached, and therefore the summary will not
Teresa Johnson2cefb932020-01-13 13:50:41 -0800885 // contain any vtable functions. We can also have multiple external
886 // vtable initializers in the case of comdats, which we cannot check here.
887 // The linker should give an error in this case.
Teresa Johnsonc844f882019-10-25 14:56:12 -0700888 //
889 // Also, handle the case of same-named local Vtables with the same path
890 // and therefore the same GUID. This can happen if there isn't enough
891 // distinguishing path when compiling the source file. In that case we
892 // conservatively return false early.
893 const GlobalVarSummary *VS = nullptr;
894 bool LocalFound = false;
895 for (auto &S : P.VTableVI.getSummaryList()) {
896 if (GlobalValue::isLocalLinkage(S->linkage())) {
897 if (LocalFound)
898 return false;
899 LocalFound = true;
900 }
Teresa Johnson90e630a2020-01-23 17:26:51 -0800901 if (!GlobalValue::isAvailableExternallyLinkage(S->linkage()))
Teresa Johnson31441a32019-12-04 17:15:10 -0800902 VS = cast<GlobalVarSummary>(S->getBaseObject());
Teresa Johnsonc844f882019-10-25 14:56:12 -0700903 }
904 if (!VS->isLive())
Teresa Johnsond2df54e2019-08-02 13:10:52 +0000905 continue;
906 for (auto VTP : VS->vTableFuncs()) {
907 if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset)
908 continue;
909
910 TargetsForSlot.push_back(VTP.FuncVI);
911 }
912 }
913
914 // Give up if we couldn't find any targets.
915 return !TargetsForSlot.empty();
916}
917
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000918void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000919 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000920 auto Apply = [&](CallSiteInfo &CSInfo) {
921 for (auto &&VCallSite : CSInfo.CallSites) {
922 if (RemarksEnabled)
Teresa Johnsonb0a1d3b2018-08-14 03:00:16 +0000923 VCallSite.emitRemark("single-impl",
924 TheFn->stripPointerCasts()->getName(), OREGetter);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000925 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
926 TheFn, VCallSite.CS.getCalledValue()->getType()));
927 // This use is no longer unsafe.
928 if (VCallSite.NumUnsafeUses)
929 --*VCallSite.NumUnsafeUses;
930 }
Peter Collingbourne29748562018-03-09 19:11:44 +0000931 if (CSInfo.isExported())
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000932 IsExported = true;
Peter Collingbourne29748562018-03-09 19:11:44 +0000933 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000934 };
935 Apply(SlotInfo.CSInfo);
936 for (auto &P : SlotInfo.ConstCSInfo)
937 Apply(P.second);
938}
939
Eugene Leviant943afb52019-10-17 07:46:18 +0000940static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) {
941 // We can't add calls if we haven't seen a definition
942 if (Callee.getSummaryList().empty())
943 return false;
944
945 // Insert calls into the summary index so that the devirtualized targets
946 // are eligible for import.
947 // FIXME: Annotate type tests with hotness. For now, mark these as hot
948 // to better ensure we have the opportunity to inline them.
949 bool IsExported = false;
950 auto &S = Callee.getSummaryList()[0];
951 CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* RelBF = */ 0);
952 auto AddCalls = [&](CallSiteInfo &CSInfo) {
953 for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) {
954 FS->addCall({Callee, CI});
955 IsExported |= S->modulePath() != FS->modulePath();
956 }
957 for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) {
958 FS->addCall({Callee, CI});
959 IsExported |= S->modulePath() != FS->modulePath();
960 }
961 };
962 AddCalls(SlotInfo.CSInfo);
963 for (auto &P : SlotInfo.ConstCSInfo)
964 AddCalls(P.second);
965 return IsExported;
966}
967
Peter Collingbournee2367412017-02-15 02:13:08 +0000968bool DevirtModule::trySingleImplDevirt(
Eugene Leviant943afb52019-10-17 07:46:18 +0000969 ModuleSummaryIndex *ExportSummary,
970 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
971 WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000972 // See if the program contains a single implementation of this virtual
973 // function.
974 Function *TheFn = TargetsForSlot[0].Fn;
975 for (auto &&Target : TargetsForSlot)
976 if (TheFn != Target.Fn)
977 return false;
978
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000979 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000980 if (RemarksEnabled)
981 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000982
983 bool IsExported = false;
984 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
985 if (!IsExported)
986 return false;
987
988 // If the only implementation has local linkage, we must promote to external
989 // to make it visible to thin LTO objects. We can only get here during the
990 // ThinLTO export phase.
991 if (TheFn->hasLocalLinkage()) {
Peter Collingbourne88a58cf2017-09-08 00:10:53 +0000992 std::string NewName = (TheFn->getName() + "$merged").str();
993
994 // Since we are renaming the function, any comdats with the same name must
995 // also be renamed. This is required when targeting COFF, as the comdat name
996 // must match one of the names of the symbols in the comdat.
997 if (Comdat *C = TheFn->getComdat()) {
998 if (C->getName() == TheFn->getName()) {
999 Comdat *NewC = M.getOrInsertComdat(NewName);
1000 NewC->setSelectionKind(C->getSelectionKind());
1001 for (GlobalObject &GO : M.global_objects())
1002 if (GO.getComdat() == C)
1003 GO.setComdat(NewC);
1004 }
1005 }
1006
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001007 TheFn->setLinkage(GlobalValue::ExternalLinkage);
1008 TheFn->setVisibility(GlobalValue::HiddenVisibility);
Peter Collingbourne88a58cf2017-09-08 00:10:53 +00001009 TheFn->setName(NewName);
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001010 }
Eugene Leviant943afb52019-10-17 07:46:18 +00001011 if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID()))
1012 // Any needed promotion of 'TheFn' has already been done during
1013 // LTO unit split, so we can ignore return value of AddCalls.
1014 AddCalls(SlotInfo, TheFnVI);
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001015
1016 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
1017 Res->SingleImplName = TheFn->getName();
1018
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001019 return true;
1020}
1021
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001022bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
1023 VTableSlotSummary &SlotSummary,
1024 VTableSlotInfo &SlotInfo,
1025 WholeProgramDevirtResolution *Res,
1026 std::set<ValueInfo> &DevirtTargets) {
1027 // See if the program contains a single implementation of this virtual
1028 // function.
1029 auto TheFn = TargetsForSlot[0];
1030 for (auto &&Target : TargetsForSlot)
1031 if (TheFn != Target)
1032 return false;
1033
1034 // Don't devirtualize if we don't have target definition.
1035 auto Size = TheFn.getSummaryList().size();
1036 if (!Size)
1037 return false;
1038
1039 // If the summary list contains multiple summaries where at least one is
1040 // a local, give up, as we won't know which (possibly promoted) name to use.
1041 for (auto &S : TheFn.getSummaryList())
1042 if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1)
1043 return false;
1044
1045 // Collect functions devirtualized at least for one call site for stats.
1046 if (PrintSummaryDevirt)
1047 DevirtTargets.insert(TheFn);
1048
1049 auto &S = TheFn.getSummaryList()[0];
Eugene Leviant943afb52019-10-17 07:46:18 +00001050 bool IsExported = AddCalls(SlotInfo, TheFn);
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001051 if (IsExported)
1052 ExportedGUIDs.insert(TheFn.getGUID());
1053
1054 // Record in summary for use in devirtualization during the ThinLTO import
1055 // step.
1056 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
1057 if (GlobalValue::isLocalLinkage(S->linkage())) {
1058 if (IsExported)
1059 // If target is a local function and we are exporting it by
1060 // devirtualizing a call in another module, we need to record the
1061 // promoted name.
1062 Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
1063 TheFn.name(), ExportSummary.getModuleHash(S->modulePath()));
1064 else {
1065 LocalWPDTargetsMap[TheFn].push_back(SlotSummary);
1066 Res->SingleImplName = TheFn.name();
1067 }
1068 } else
1069 Res->SingleImplName = TheFn.name();
1070
1071 // Name will be empty if this thin link driven off of serialized combined
1072 // index (e.g. llvm-lto). However, WPD is not supported/invoked for the
1073 // legacy LTO API anyway.
1074 assert(!Res->SingleImplName.empty());
1075
1076 return true;
1077}
1078
Peter Collingbourne29748562018-03-09 19:11:44 +00001079void DevirtModule::tryICallBranchFunnel(
1080 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1081 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1082 Triple T(M.getTargetTriple());
1083 if (T.getArch() != Triple::x86_64)
1084 return;
1085
Vitaly Buka66f53d72018-04-06 21:32:36 +00001086 if (TargetsForSlot.size() > ClThreshold)
Peter Collingbourne29748562018-03-09 19:11:44 +00001087 return;
1088
1089 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
1090 if (!HasNonDevirt)
1091 for (auto &P : SlotInfo.ConstCSInfo)
1092 if (!P.second.AllCallSitesDevirted) {
1093 HasNonDevirt = true;
1094 break;
1095 }
1096
1097 if (!HasNonDevirt)
1098 return;
1099
1100 FunctionType *FT =
1101 FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
1102 Function *JT;
1103 if (isa<MDString>(Slot.TypeID)) {
1104 JT = Function::Create(FT, Function::ExternalLinkage,
Dylan McKayf920da02018-12-18 09:52:52 +00001105 M.getDataLayout().getProgramAddressSpace(),
Peter Collingbourne29748562018-03-09 19:11:44 +00001106 getGlobalName(Slot, {}, "branch_funnel"), &M);
1107 JT->setVisibility(GlobalValue::HiddenVisibility);
1108 } else {
Dylan McKayf920da02018-12-18 09:52:52 +00001109 JT = Function::Create(FT, Function::InternalLinkage,
1110 M.getDataLayout().getProgramAddressSpace(),
1111 "branch_funnel", &M);
Peter Collingbourne29748562018-03-09 19:11:44 +00001112 }
1113 JT->addAttribute(1, Attribute::Nest);
1114
1115 std::vector<Value *> JTArgs;
1116 JTArgs.push_back(JT->arg_begin());
1117 for (auto &T : TargetsForSlot) {
1118 JTArgs.push_back(getMemberAddr(T.TM));
1119 JTArgs.push_back(T.Fn);
1120 }
1121
1122 BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
James Y Knight7976eb52019-02-01 20:43:25 +00001123 Function *Intr =
Peter Collingbourne29748562018-03-09 19:11:44 +00001124 Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
1125
1126 auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
1127 CI->setTailCallKind(CallInst::TCK_MustTail);
1128 ReturnInst::Create(M.getContext(), nullptr, BB);
1129
1130 bool IsExported = false;
1131 applyICallBranchFunnel(SlotInfo, JT, IsExported);
1132 if (IsExported)
1133 Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
1134}
1135
1136void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
1137 Constant *JT, bool &IsExported) {
1138 auto Apply = [&](CallSiteInfo &CSInfo) {
1139 if (CSInfo.isExported())
1140 IsExported = true;
1141 if (CSInfo.AllCallSitesDevirted)
1142 return;
1143 for (auto &&VCallSite : CSInfo.CallSites) {
1144 CallSite CS = VCallSite.CS;
1145
1146 // Jump tables are only profitable if the retpoline mitigation is enabled.
1147 Attribute FSAttr = CS.getCaller()->getFnAttribute("target-features");
1148 if (FSAttr.hasAttribute(Attribute::None) ||
1149 !FSAttr.getValueAsString().contains("+retpoline"))
1150 continue;
1151
1152 if (RemarksEnabled)
Teresa Johnsonb0a1d3b2018-08-14 03:00:16 +00001153 VCallSite.emitRemark("branch-funnel",
1154 JT->stripPointerCasts()->getName(), OREGetter);
Peter Collingbourne29748562018-03-09 19:11:44 +00001155
1156 // Pass the address of the vtable in the nest register, which is r10 on
1157 // x86_64.
1158 std::vector<Type *> NewArgs;
1159 NewArgs.push_back(Int8PtrTy);
1160 for (Type *T : CS.getFunctionType()->params())
1161 NewArgs.push_back(T);
James Y Knight7976eb52019-02-01 20:43:25 +00001162 FunctionType *NewFT =
Peter Collingbourne29748562018-03-09 19:11:44 +00001163 FunctionType::get(CS.getFunctionType()->getReturnType(), NewArgs,
James Y Knight7976eb52019-02-01 20:43:25 +00001164 CS.getFunctionType()->isVarArg());
1165 PointerType *NewFTPtr = PointerType::getUnqual(NewFT);
Peter Collingbourne29748562018-03-09 19:11:44 +00001166
1167 IRBuilder<> IRB(CS.getInstruction());
1168 std::vector<Value *> Args;
1169 Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
1170 for (unsigned I = 0; I != CS.getNumArgOperands(); ++I)
1171 Args.push_back(CS.getArgOperand(I));
1172
1173 CallSite NewCS;
1174 if (CS.isCall())
James Y Knight7976eb52019-02-01 20:43:25 +00001175 NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args);
Peter Collingbourne29748562018-03-09 19:11:44 +00001176 else
1177 NewCS = IRB.CreateInvoke(
James Y Knightd9e85a02019-02-01 20:43:34 +00001178 NewFT, IRB.CreateBitCast(JT, NewFTPtr),
Peter Collingbourne29748562018-03-09 19:11:44 +00001179 cast<InvokeInst>(CS.getInstruction())->getNormalDest(),
1180 cast<InvokeInst>(CS.getInstruction())->getUnwindDest(), Args);
1181 NewCS.setCallingConv(CS.getCallingConv());
1182
1183 AttributeList Attrs = CS.getAttributes();
1184 std::vector<AttributeSet> NewArgAttrs;
1185 NewArgAttrs.push_back(AttributeSet::get(
1186 M.getContext(), ArrayRef<Attribute>{Attribute::get(
1187 M.getContext(), Attribute::Nest)}));
1188 for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
1189 NewArgAttrs.push_back(Attrs.getParamAttributes(I));
1190 NewCS.setAttributes(
1191 AttributeList::get(M.getContext(), Attrs.getFnAttributes(),
1192 Attrs.getRetAttributes(), NewArgAttrs));
1193
1194 CS->replaceAllUsesWith(NewCS.getInstruction());
1195 CS->eraseFromParent();
1196
1197 // This use is no longer unsafe.
1198 if (VCallSite.NumUnsafeUses)
1199 --*VCallSite.NumUnsafeUses;
1200 }
1201 // Don't mark as devirtualized because there may be callers compiled without
1202 // retpoline mitigation, which would mean that they are lowered to
1203 // llvm.type.test and therefore require an llvm.type.test resolution for the
1204 // type identifier.
1205 };
1206 Apply(SlotInfo.CSInfo);
1207 for (auto &P : SlotInfo.ConstCSInfo)
1208 Apply(P.second);
1209}
1210
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001211bool DevirtModule::tryEvaluateFunctionsWithArgs(
1212 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001213 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001214 // Evaluate each function and store the result in each target's RetVal
1215 // field.
1216 for (VirtualCallTarget &Target : TargetsForSlot) {
1217 if (Target.Fn->arg_size() != Args.size() + 1)
1218 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001219
1220 Evaluator Eval(M.getDataLayout(), nullptr);
1221 SmallVector<Constant *, 2> EvalArgs;
1222 EvalArgs.push_back(
1223 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001224 for (unsigned I = 0; I != Args.size(); ++I) {
1225 auto *ArgTy = dyn_cast<IntegerType>(
1226 Target.Fn->getFunctionType()->getParamType(I + 1));
1227 if (!ArgTy)
1228 return false;
1229 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
1230 }
1231
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001232 Constant *RetVal;
1233 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
1234 !isa<ConstantInt>(RetVal))
1235 return false;
1236 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
1237 }
1238 return true;
1239}
1240
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001241void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1242 uint64_t TheRetVal) {
1243 for (auto Call : CSInfo.CallSites)
1244 Call.replaceAndErase(
Sam Elliotte963c892017-08-21 16:57:21 +00001245 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001246 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001247 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001248}
1249
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001250bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001251 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
1252 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001253 // Uniform return value optimization. If all functions return the same
1254 // constant, replace all calls with that constant.
1255 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
1256 for (const VirtualCallTarget &Target : TargetsForSlot)
1257 if (Target.RetVal != TheRetVal)
1258 return false;
1259
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001260 if (CSInfo.isExported()) {
1261 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
1262 Res->Info = TheRetVal;
1263 }
1264
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001265 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001266 if (RemarksEnabled)
1267 for (auto &&Target : TargetsForSlot)
1268 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001269 return true;
1270}
1271
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001272std::string DevirtModule::getGlobalName(VTableSlot Slot,
1273 ArrayRef<uint64_t> Args,
1274 StringRef Name) {
1275 std::string FullName = "__typeid_";
1276 raw_string_ostream OS(FullName);
1277 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1278 for (uint64_t Arg : Args)
1279 OS << '_' << Arg;
1280 OS << '_' << Name;
1281 return OS.str();
1282}
1283
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001284bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1285 Triple T(M.getTargetTriple());
Fangrui Song6904cd92020-01-06 10:16:28 -08001286 return T.isX86() && T.getObjectFormat() == Triple::ELF;
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001287}
1288
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001289void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1290 StringRef Name, Constant *C) {
1291 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1292 getGlobalName(Slot, Args, Name), C, &M);
1293 GA->setVisibility(GlobalValue::HiddenVisibility);
1294}
1295
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001296void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1297 StringRef Name, uint32_t Const,
1298 uint32_t &Storage) {
1299 if (shouldExportConstantsAsAbsoluteSymbols()) {
1300 exportGlobal(
1301 Slot, Args, Name,
1302 ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1303 return;
1304 }
1305
1306 Storage = Const;
1307}
1308
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001309Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001310 StringRef Name) {
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001311 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
1312 auto *GV = dyn_cast<GlobalVariable>(C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001313 if (GV)
1314 GV->setVisibility(GlobalValue::HiddenVisibility);
1315 return C;
1316}
1317
1318Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1319 StringRef Name, IntegerType *IntTy,
1320 uint32_t Storage) {
1321 if (!shouldExportConstantsAsAbsoluteSymbols())
1322 return ConstantInt::get(IntTy, Storage);
1323
1324 Constant *C = importGlobal(Slot, Args, Name);
1325 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1326 C = ConstantExpr::getPtrToInt(C, IntTy);
1327
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001328 // We only need to set metadata if the global is newly created, in which
1329 // case it would not have hidden visibility.
Benjamin Kramer0deb9a92018-05-31 13:29:58 +00001330 if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001331 return C;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001332
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001333 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1334 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1335 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1336 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1337 MDNode::get(M.getContext(), {MinC, MaxC}));
1338 };
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001339 unsigned AbsWidth = IntTy->getBitWidth();
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001340 if (AbsWidth == IntPtrTy->getBitWidth())
1341 SetAbsRange(~0ull, ~0ull); // Full set.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001342 else
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001343 SetAbsRange(0, 1ull << AbsWidth);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001344 return C;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001345}
1346
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001347void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1348 bool IsOne,
1349 Constant *UniqueMemberAddr) {
1350 for (auto &&Call : CSInfo.CallSites) {
1351 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001352 Value *Cmp =
1353 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
1354 B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001355 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
Sam Elliotte963c892017-08-21 16:57:21 +00001356 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1357 Cmp);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001358 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001359 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001360}
1361
Peter Collingbourne29748562018-03-09 19:11:44 +00001362Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1363 Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
1364 return ConstantExpr::getGetElementPtr(Int8Ty, C,
1365 ConstantInt::get(Int64Ty, M->Offset));
1366}
1367
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001368bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001369 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001370 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1371 VTableSlot Slot, ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001372 // IsOne controls whether we look for a 0 or a 1.
1373 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001374 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001375 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +00001376 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001377 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001378 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001379 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001380 }
1381 }
1382
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001383 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001384 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001385 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001386
Peter Collingbourne29748562018-03-09 19:11:44 +00001387 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001388 if (CSInfo.isExported()) {
1389 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
1390 Res->Info = IsOne;
1391
1392 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1393 }
1394
1395 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001396 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1397 UniqueMemberAddr);
1398
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001399 // Update devirtualization statistics for targets.
1400 if (RemarksEnabled)
1401 for (auto &&Target : TargetsForSlot)
1402 Target.WasDevirt = true;
1403
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001404 return true;
1405 };
1406
1407 if (BitWidth == 1) {
1408 if (tryUniqueRetValOptFor(true))
1409 return true;
1410 if (tryUniqueRetValOptFor(false))
1411 return true;
1412 }
1413 return false;
1414}
1415
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001416void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1417 Constant *Byte, Constant *Bit) {
1418 for (auto Call : CSInfo.CallSites) {
1419 auto *RetType = cast<IntegerType>(Call.CS.getType());
1420 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001421 Value *Addr =
1422 B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001423 if (RetType->getBitWidth() == 1) {
James Y Knight14359ef2019-02-01 20:44:24 +00001424 Value *Bits = B.CreateLoad(Int8Ty, Addr);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001425 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1426 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1427 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
Sam Elliotte963c892017-08-21 16:57:21 +00001428 OREGetter, IsBitSet);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001429 } else {
1430 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
1431 Value *Val = B.CreateLoad(RetType, ValAddr);
Sam Elliotte963c892017-08-21 16:57:21 +00001432 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1433 OREGetter, Val);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001434 }
1435 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001436 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001437}
1438
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001439bool DevirtModule::tryVirtualConstProp(
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001440 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1441 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001442 // This only works if the function returns an integer.
1443 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
1444 if (!RetType)
1445 return false;
1446 unsigned BitWidth = RetType->getBitWidth();
1447 if (BitWidth > 64)
1448 return false;
1449
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001450 // Make sure that each function is defined, does not access memory, takes at
1451 // least one argument, does not use its first argument (which we assume is
1452 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +00001453 //
1454 // Note that we test whether this copy of the function is readnone, rather
1455 // than testing function attributes, which must hold for any copy of the
1456 // function, even a less optimized version substituted at link time. This is
1457 // sound because the virtual constant propagation optimizations effectively
1458 // inline all implementations of the virtual function into each call site,
1459 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001460 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +00001461 if (Target.Fn->isDeclaration() ||
1462 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
1463 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001464 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001465 Target.Fn->getReturnType() != RetType)
1466 return false;
1467 }
1468
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001469 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001470 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1471 continue;
1472
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001473 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1474 if (Res)
1475 ResByArg = &Res->ResByArg[CSByConstantArg.first];
1476
1477 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001478 continue;
1479
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001480 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1481 ResByArg, Slot, CSByConstantArg.first))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001482 continue;
1483
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001484 // Find an allocation offset in bits in all vtables associated with the
1485 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001486 uint64_t AllocBefore =
1487 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1488 uint64_t AllocAfter =
1489 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1490
1491 // Calculate the total amount of padding needed to store a value at both
1492 // ends of the object.
1493 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1494 for (auto &&Target : TargetsForSlot) {
1495 TotalPaddingBefore += std::max<int64_t>(
1496 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1497 TotalPaddingAfter += std::max<int64_t>(
1498 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1499 }
1500
1501 // If the amount of padding is too large, give up.
1502 // FIXME: do something smarter here.
1503 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1504 continue;
1505
1506 // Calculate the offset to the value as a (possibly negative) byte offset
1507 // and (if applicable) a bit offset, and store the values in the targets.
1508 int64_t OffsetByte;
1509 uint64_t OffsetBit;
1510 if (TotalPaddingBefore <= TotalPaddingAfter)
1511 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1512 OffsetBit);
1513 else
1514 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1515 OffsetBit);
1516
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001517 if (RemarksEnabled)
1518 for (auto &&Target : TargetsForSlot)
1519 Target.WasDevirt = true;
1520
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001521
1522 if (CSByConstantArg.second.isExported()) {
1523 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001524 exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
1525 ResByArg->Byte);
1526 exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
1527 ResByArg->Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001528 }
1529
1530 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001531 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
1532 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001533 applyVirtualConstProp(CSByConstantArg.second,
1534 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001535 }
1536 return true;
1537}
1538
1539void DevirtModule::rebuildGlobal(VTableBits &B) {
1540 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1541 return;
1542
Peter Collingbourneef5cfc22019-07-22 18:50:45 +00001543 // Align the before byte array to the global's minimum alignment so that we
1544 // don't break any alignment requirements on the global.
Guillaume Chatelet0e620112019-10-15 11:24:36 +00001545 MaybeAlign Alignment(B.GV->getAlignment());
1546 if (!Alignment)
1547 Alignment =
1548 Align(M.getDataLayout().getABITypeAlignment(B.GV->getValueType()));
1549 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment));
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001550
1551 // Before was stored in reverse order; flip it now.
1552 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1553 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1554
1555 // Build an anonymous global containing the before bytes, followed by the
1556 // original initializer, followed by the after bytes.
1557 auto NewInit = ConstantStruct::getAnon(
1558 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1559 B.GV->getInitializer(),
1560 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1561 auto NewGV =
1562 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1563 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1564 NewGV->setSection(B.GV->getSection());
1565 NewGV->setComdat(B.GV->getComdat());
Guillaume Chatelet0e620112019-10-15 11:24:36 +00001566 NewGV->setAlignment(MaybeAlign(B.GV->getAlignment()));
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001567
Peter Collingbourne0312f612016-06-25 00:23:04 +00001568 // Copy the original vtable's metadata to the anonymous global, adjusting
1569 // offsets as required.
1570 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1571
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001572 // Build an alias named after the original global, pointing at the second
1573 // element (the original initializer).
1574 auto Alias = GlobalAlias::create(
1575 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1576 ConstantExpr::getGetElementPtr(
1577 NewInit->getType(), NewGV,
1578 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1579 ConstantInt::get(Int32Ty, 1)}),
1580 &M);
1581 Alias->setVisibility(B.GV->getVisibility());
1582 Alias->takeName(B.GV);
1583
1584 B.GV->replaceAllUsesWith(Alias);
1585 B.GV->eraseFromParent();
1586}
1587
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001588bool DevirtModule::areRemarksEnabled() {
1589 const auto &FL = M.getFunctionList();
Teresa Johnson5e1c0e72018-09-18 13:42:24 +00001590 for (const Function &Fn : FL) {
1591 const auto &BBL = Fn.getBasicBlockList();
1592 if (BBL.empty())
1593 continue;
1594 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
1595 return DI.isEnabled();
1596 }
1597 return false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001598}
1599
Teresa Johnsonc8e36862019-12-06 12:13:34 -08001600void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001601 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001602 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1603 // points to a member of the type identifier %md. Group calls by (type ID,
1604 // offset) pair (effectively the identity of the virtual function) and store
1605 // to CallSlots.
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001606 DenseSet<CallSite> SeenCallSites;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001607 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001608 I != E;) {
1609 auto CI = dyn_cast<CallInst>(I->getUser());
1610 ++I;
1611 if (!CI)
1612 continue;
1613
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001614 // Search for virtual calls based on %p and add them to DevirtCalls.
1615 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001616 SmallVector<CallInst *, 1> Assumes;
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001617 auto &DT = LookupDomTree(*CI->getFunction());
1618 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001619
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001620 // If we found any, add them to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001621 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001622 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001623 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1624 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001625 for (DevirtCallSite Call : DevirtCalls) {
1626 // Only add this CallSite if we haven't seen it before. The vtable
1627 // pointer may have been CSE'd with pointers from other call sites,
1628 // and we don't want to process call sites multiple times. We can't
1629 // just skip the vtable Ptr if it has been seen before, however, since
1630 // it may be shared by type tests that dominate different calls.
1631 if (SeenCallSites.insert(Call.CS).second)
Peter Collingbourne001052a2017-08-22 21:41:19 +00001632 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001633 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001634 }
1635
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001636 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001637 for (auto Assume : Assumes)
1638 Assume->eraseFromParent();
1639 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1640 // may use the vtable argument later.
1641 if (CI->use_empty())
1642 CI->eraseFromParent();
1643 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001644}
1645
1646void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1647 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1648
1649 for (auto I = TypeCheckedLoadFunc->use_begin(),
1650 E = TypeCheckedLoadFunc->use_end();
1651 I != E;) {
1652 auto CI = dyn_cast<CallInst>(I->getUser());
1653 ++I;
1654 if (!CI)
1655 continue;
1656
1657 Value *Ptr = CI->getArgOperand(0);
1658 Value *Offset = CI->getArgOperand(1);
1659 Value *TypeIdValue = CI->getArgOperand(2);
1660 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1661
1662 SmallVector<DevirtCallSite, 1> DevirtCalls;
1663 SmallVector<Instruction *, 1> LoadedPtrs;
1664 SmallVector<Instruction *, 1> Preds;
1665 bool HasNonCallUses = false;
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001666 auto &DT = LookupDomTree(*CI->getFunction());
Peter Collingbourne0312f612016-06-25 00:23:04 +00001667 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
Teresa Johnsonf24136f2018-09-27 14:55:32 +00001668 HasNonCallUses, CI, DT);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001669
1670 // Start by generating "pessimistic" code that explicitly loads the function
1671 // pointer from the vtable and performs the type check. If possible, we will
1672 // eliminate the load and the type check later.
1673
1674 // If possible, only generate the load at the point where it is used.
1675 // This helps avoid unnecessary spills.
1676 IRBuilder<> LoadB(
1677 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1678 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1679 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1680 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1681
1682 for (Instruction *LoadedPtr : LoadedPtrs) {
1683 LoadedPtr->replaceAllUsesWith(LoadedValue);
1684 LoadedPtr->eraseFromParent();
1685 }
1686
1687 // Likewise for the type test.
1688 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1689 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1690
1691 for (Instruction *Pred : Preds) {
1692 Pred->replaceAllUsesWith(TypeTestCall);
1693 Pred->eraseFromParent();
1694 }
1695
1696 // We have already erased any extractvalue instructions that refer to the
1697 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1698 // (although this is unlikely). In that case, explicitly build a pair and
1699 // RAUW it.
1700 if (!CI->use_empty()) {
1701 Value *Pair = UndefValue::get(CI->getType());
1702 IRBuilder<> B(CI);
1703 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1704 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1705 CI->replaceAllUsesWith(Pair);
1706 }
1707
1708 // The number of unsafe uses is initially the number of uses.
1709 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1710 NumUnsafeUses = DevirtCalls.size();
1711
1712 // If the function pointer has a non-call user, we cannot eliminate the type
1713 // check, as one of those users may eventually call the pointer. Increment
1714 // the unsafe use count to make sure it cannot reach zero.
1715 if (HasNonCallUses)
1716 ++NumUnsafeUses;
1717 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001718 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1719 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001720 }
1721
1722 CI->eraseFromParent();
1723 }
1724}
1725
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001726void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001727 auto *TypeId = dyn_cast<MDString>(Slot.TypeID);
1728 if (!TypeId)
1729 return;
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001730 const TypeIdSummary *TidSummary =
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001731 ImportSummary->getTypeIdSummary(TypeId->getString());
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001732 if (!TidSummary)
1733 return;
1734 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1735 if (ResI == TidSummary->WPDRes.end())
1736 return;
1737 const WholeProgramDevirtResolution &Res = ResI->second;
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001738
1739 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001740 assert(!Res.SingleImplName.empty());
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001741 // The type of the function in the declaration is irrelevant because every
1742 // call site will cast it to the correct type.
James Y Knight13680222019-02-01 02:28:03 +00001743 Constant *SingleImpl =
1744 cast<Constant>(M.getOrInsertFunction(Res.SingleImplName,
1745 Type::getVoidTy(M.getContext()))
1746 .getCallee());
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001747
1748 // This is the import phase so we should not be exporting anything.
1749 bool IsExported = false;
1750 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1751 assert(!IsExported);
1752 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001753
1754 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1755 auto I = Res.ResByArg.find(CSByConstantArg.first);
1756 if (I == Res.ResByArg.end())
1757 continue;
1758 auto &ResByArg = I->second;
1759 // FIXME: We should figure out what to do about the "function name" argument
1760 // to the apply* functions, as the function names are unavailable during the
1761 // importing phase. For now we just pass the empty string. This does not
1762 // impact correctness because the function names are just used for remarks.
1763 switch (ResByArg.TheKind) {
1764 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1765 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1766 break;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001767 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1768 Constant *UniqueMemberAddr =
1769 importGlobal(Slot, CSByConstantArg.first, "unique_member");
1770 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1771 UniqueMemberAddr);
1772 break;
1773 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001774 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001775 Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
1776 Int32Ty, ResByArg.Byte);
1777 Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
1778 ResByArg.Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001779 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
Adrian Prantl0e6694d2017-12-19 22:05:25 +00001780 break;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001781 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001782 default:
1783 break;
1784 }
1785 }
Peter Collingbourne29748562018-03-09 19:11:44 +00001786
1787 if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
James Y Knight13680222019-02-01 02:28:03 +00001788 // The type of the function is irrelevant, because it's bitcast at calls
1789 // anyhow.
1790 Constant *JT = cast<Constant>(
1791 M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
1792 Type::getVoidTy(M.getContext()))
1793 .getCallee());
Peter Collingbourne29748562018-03-09 19:11:44 +00001794 bool IsExported = false;
1795 applyICallBranchFunnel(SlotInfo, JT, IsExported);
1796 assert(!IsExported);
1797 }
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001798}
1799
1800void DevirtModule::removeRedundantTypeTests() {
1801 auto True = ConstantInt::getTrue(M.getContext());
1802 for (auto &&U : NumUnsafeUsesForTypeTest) {
1803 if (U.second == 0) {
1804 U.first->replaceAllUsesWith(True);
1805 U.first->eraseFromParent();
1806 }
1807 }
1808}
1809
Peter Collingbourne0312f612016-06-25 00:23:04 +00001810bool DevirtModule::run() {
Teresa Johnsond0b1f302019-02-14 21:22:50 +00001811 // If only some of the modules were split, we cannot correctly perform
1812 // this transformation. We already checked for the presense of type tests
1813 // with partially split modules during the thin link, and would have emitted
1814 // an error if any were found, so here we can simply return.
1815 if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
1816 (ImportSummary && ImportSummary->partiallySplitLTOUnits()))
1817 return false;
1818
Peter Collingbourne0312f612016-06-25 00:23:04 +00001819 Function *TypeTestFunc =
1820 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1821 Function *TypeCheckedLoadFunc =
1822 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1823 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1824
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001825 // Normally if there are no users of the devirtualization intrinsics in the
1826 // module, this pass has nothing to do. But if we are exporting, we also need
1827 // to handle any users that appear only in the function summaries.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001828 if (!ExportSummary &&
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001829 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001830 AssumeFunc->use_empty()) &&
1831 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1832 return false;
1833
1834 if (TypeTestFunc && AssumeFunc)
Teresa Johnsonc8e36862019-12-06 12:13:34 -08001835 scanTypeTestUsers(TypeTestFunc);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001836
1837 if (TypeCheckedLoadFunc)
1838 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001839
Peter Collingbournef7691d82017-03-22 18:22:59 +00001840 if (ImportSummary) {
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001841 for (auto &S : CallSlots)
1842 importResolution(S.first, S.second);
1843
1844 removeRedundantTypeTests();
1845
1846 // The rest of the code is only necessary when exporting or during regular
1847 // LTO, so we are done.
1848 return true;
1849 }
1850
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001851 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001852 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001853 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1854 buildTypeIdentifierMap(Bits, TypeIdMap);
1855 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001856 return true;
1857
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001858 // Collect information from summary about which calls to try to devirtualize.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001859 if (ExportSummary) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001860 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1861 for (auto &P : TypeIdMap) {
1862 if (auto *TypeId = dyn_cast<MDString>(P.first))
1863 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1864 TypeId);
1865 }
1866
Peter Collingbournef7691d82017-03-22 18:22:59 +00001867 for (auto &P : *ExportSummary) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001868 for (auto &S : P.second.SummaryList) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001869 auto *FS = dyn_cast<FunctionSummary>(S.get());
1870 if (!FS)
1871 continue;
1872 // FIXME: Only add live functions.
George Rimar5d8aea12017-03-10 10:31:56 +00001873 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1874 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Eugene Leviant943afb52019-10-17 07:46:18 +00001875 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001876 }
1877 }
1878 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1879 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001880 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001881 }
1882 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001883 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001884 FS->type_test_assume_const_vcalls()) {
1885 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001886 CallSlots[{MD, VC.VFunc.Offset}]
George Rimar5d8aea12017-03-10 10:31:56 +00001887 .ConstCSInfo[VC.Args]
Eugene Leviant943afb52019-10-17 07:46:18 +00001888 .addSummaryTypeTestAssumeUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001889 }
1890 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001891 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001892 FS->type_checked_load_const_vcalls()) {
1893 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001894 CallSlots[{MD, VC.VFunc.Offset}]
1895 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001896 .addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001897 }
1898 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001899 }
1900 }
1901 }
1902
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001903 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001904 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001905 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001906 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001907 // Search each of the members of the type identifier for the virtual
1908 // function implementation at offset S.first.ByteOffset, and add to
1909 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001910 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001911 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1912 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001913 WholeProgramDevirtResolution *Res = nullptr;
Peter Collingbournef7691d82017-03-22 18:22:59 +00001914 if (ExportSummary && isa<MDString>(S.first.TypeID))
1915 Res = &ExportSummary
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001916 ->getOrInsertTypeIdSummary(
1917 cast<MDString>(S.first.TypeID)->getString())
1918 .WPDRes[S.first.ByteOffset];
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001919
Eugene Leviant943afb52019-10-17 07:46:18 +00001920 if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001921 DidVirtualConstProp |=
1922 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
1923
1924 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
1925 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001926
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001927 // Collect functions devirtualized at least for one call site for stats.
1928 if (RemarksEnabled)
1929 for (const auto &T : TargetsForSlot)
1930 if (T.WasDevirt)
1931 DevirtTargets[T.Fn->getName()] = T.Fn;
1932 }
1933
1934 // CFI-specific: if we are exporting and any llvm.type.checked.load
1935 // intrinsics were *not* devirtualized, we need to add the resulting
1936 // llvm.type.test intrinsics to the function summaries so that the
1937 // LowerTypeTests pass will export them.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001938 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001939 auto GUID =
1940 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1941 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1942 FS->addTypeTest(GUID);
1943 for (auto &CCS : S.second.ConstCSInfo)
1944 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1945 FS->addTypeTest(GUID);
1946 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001947 }
1948
1949 if (RemarksEnabled) {
1950 // Generate remarks for each devirtualized function.
1951 for (const auto &DT : DevirtTargets) {
1952 Function *F = DT.second;
Sam Elliotte963c892017-08-21 16:57:21 +00001953
Sam Elliotte963c892017-08-21 16:57:21 +00001954 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +00001955 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
1956 << "devirtualized "
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001957 << NV("FunctionName", DT.first));
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001958 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001959 }
1960
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001961 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00001962
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001963 // Rebuild each global we touched as part of virtual constant propagation to
1964 // include the before and after bytes.
1965 if (DidVirtualConstProp)
1966 for (VTableBits &B : Bits)
1967 rebuildGlobal(B);
1968
Teresa Johnson90e630a2020-01-23 17:26:51 -08001969 // We have lowered or deleted the type checked load intrinsics, so we no
Oliver Stannard3b598b92019-10-17 09:58:57 +00001970 // longer have enough information to reason about the liveness of virtual
1971 // function pointers in GlobalDCE.
1972 for (GlobalVariable &GV : M.globals())
1973 GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
1974
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001975 return true;
1976}
Teresa Johnsond2df54e2019-08-02 13:10:52 +00001977
1978void DevirtIndex::run() {
1979 if (ExportSummary.typeIdCompatibleVtableMap().empty())
1980 return;
1981
1982 DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID;
1983 for (auto &P : ExportSummary.typeIdCompatibleVtableMap()) {
1984 NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first);
1985 }
1986
1987 // Collect information from summary about which calls to try to devirtualize.
1988 for (auto &P : ExportSummary) {
1989 for (auto &S : P.second.SummaryList) {
1990 auto *FS = dyn_cast<FunctionSummary>(S.get());
1991 if (!FS)
1992 continue;
1993 // FIXME: Only add live functions.
1994 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1995 for (StringRef Name : NameByGUID[VF.GUID]) {
1996 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
1997 }
1998 }
1999 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
2000 for (StringRef Name : NameByGUID[VF.GUID]) {
2001 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2002 }
2003 }
2004 for (const FunctionSummary::ConstVCall &VC :
2005 FS->type_test_assume_const_vcalls()) {
2006 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2007 CallSlots[{Name, VC.VFunc.Offset}]
2008 .ConstCSInfo[VC.Args]
2009 .addSummaryTypeTestAssumeUser(FS);
2010 }
2011 }
2012 for (const FunctionSummary::ConstVCall &VC :
2013 FS->type_checked_load_const_vcalls()) {
2014 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2015 CallSlots[{Name, VC.VFunc.Offset}]
2016 .ConstCSInfo[VC.Args]
2017 .addSummaryTypeCheckedLoadUser(FS);
2018 }
2019 }
2020 }
2021 }
2022
2023 std::set<ValueInfo> DevirtTargets;
2024 // For each (type, offset) pair:
2025 for (auto &S : CallSlots) {
2026 // Search each of the members of the type identifier for the virtual
2027 // function implementation at offset S.first.ByteOffset, and add to
2028 // TargetsForSlot.
2029 std::vector<ValueInfo> TargetsForSlot;
2030 auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID);
2031 assert(TidSummary);
2032 if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary,
2033 S.first.ByteOffset)) {
2034 WholeProgramDevirtResolution *Res =
2035 &ExportSummary.getOrInsertTypeIdSummary(S.first.TypeID)
2036 .WPDRes[S.first.ByteOffset];
2037
2038 if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res,
2039 DevirtTargets))
2040 continue;
2041 }
2042 }
2043
2044 // Optionally have the thin link print message for each devirtualized
2045 // function.
2046 if (PrintSummaryDevirt)
2047 for (const auto &DT : DevirtTargets)
2048 errs() << "Devirtualized call to " << DT << "\n";
2049
2050 return;
2051}