blob: f321a8c8eb77e6f751fb289ab666764d327c2746 [file] [log] [blame]
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001//===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass implements whole program optimization of virtual calls in cases
Peter Collingbourne7efd7502016-06-24 21:21:32 +000011// where we know (via !type metadata) that the list of callees is fixed. This
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000012// includes the following:
13// - Single implementation devirtualization: if a virtual call has a single
14// possible callee, replace all calls with a direct call to that callee.
15// - Virtual constant propagation: if the virtual function's return type is an
16// integer <=64 bits and all possible callees are readnone, for each class and
17// each list of constant arguments: evaluate the function, store the return
18// value alongside the virtual table, and rewrite each virtual call as a load
19// from the virtual table.
20// - Uniform return value optimization: if the conditions for virtual constant
21// propagation hold and each function returns the same constant value, replace
22// each virtual call with that constant.
23// - Unique return value optimization for i1 return values: if the conditions
24// for virtual constant propagation hold and a single vtable's function
25// returns 0, or a single vtable's function returns 1, replace each virtual
26// call with a comparison of the vptr against that vtable's address.
27//
Peter Collingbourneb406baa2017-03-04 01:23:30 +000028// This pass is intended to be used during the regular and thin LTO pipelines.
29// 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
32// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics). During
33// ThinLTO, the pass operates in two phases:
34// - Export phase: this is run during the thin link over a single merged module
35// that contains all vtables with !type metadata that participate in the link.
36// The pass computes a resolution for each virtual call and stores it in the
37// type identifier summary.
38// - Import phase: this is run during the thin backends over the individual
39// modules. The pass applies the resolutions previously computed during the
40// import phase to each eligible virtual call.
41//
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000042//===----------------------------------------------------------------------===//
43
44#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000045#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000046#include "llvm/ADT/DenseMap.h"
47#include "llvm/ADT/DenseMapInfo.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000048#include "llvm/ADT/DenseSet.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000049#include "llvm/ADT/iterator_range.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000050#include "llvm/ADT/MapVector.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000051#include "llvm/ADT/SmallVector.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000052#include "llvm/Analysis/AliasAnalysis.h"
53#include "llvm/Analysis/BasicAliasAnalysis.h"
Peter Collingbourne7efd7502016-06-24 21:21:32 +000054#include "llvm/Analysis/TypeMetadataUtils.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000055#include "llvm/IR/CallSite.h"
56#include "llvm/IR/Constants.h"
57#include "llvm/IR/DataLayout.h"
Ivan Krasinb05e06e2016-08-05 19:45:16 +000058#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000059#include "llvm/IR/DebugLoc.h"
60#include "llvm/IR/DerivedTypes.h"
Ivan Krasin54746452016-07-12 02:38:37 +000061#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000062#include "llvm/IR/Function.h"
63#include "llvm/IR/GlobalAlias.h"
64#include "llvm/IR/GlobalVariable.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000065#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000066#include "llvm/IR/InstrTypes.h"
67#include "llvm/IR/Instruction.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000068#include "llvm/IR/Instructions.h"
69#include "llvm/IR/Intrinsics.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000070#include "llvm/IR/LLVMContext.h"
71#include "llvm/IR/Metadata.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000072#include "llvm/IR/Module.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000073#include "llvm/IR/ModuleSummaryIndexYAML.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000074#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000075#include "llvm/PassRegistry.h"
76#include "llvm/PassSupport.h"
77#include "llvm/Support/Casting.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000078#include "llvm/Support/Error.h"
79#include "llvm/Support/FileSystem.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000080#include "llvm/Support/MathExtras.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000081#include "llvm/Transforms/IPO.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000082#include "llvm/Transforms/IPO/FunctionAttrs.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000083#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000084#include <algorithm>
85#include <cstddef>
86#include <map>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000087#include <set>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000088#include <string>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000089
90using namespace llvm;
91using namespace wholeprogramdevirt;
92
93#define DEBUG_TYPE "wholeprogramdevirt"
94
Peter Collingbourne2b33f652017-02-13 19:26:18 +000095static cl::opt<PassSummaryAction> ClSummaryAction(
96 "wholeprogramdevirt-summary-action",
97 cl::desc("What to do with the summary when running this pass"),
98 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
99 clEnumValN(PassSummaryAction::Import, "import",
100 "Import typeid resolutions from summary and globals"),
101 clEnumValN(PassSummaryAction::Export, "export",
102 "Export typeid resolutions to summary and globals")),
103 cl::Hidden);
104
105static cl::opt<std::string> ClReadSummary(
106 "wholeprogramdevirt-read-summary",
107 cl::desc("Read summary from given YAML file before running pass"),
108 cl::Hidden);
109
110static cl::opt<std::string> ClWriteSummary(
111 "wholeprogramdevirt-write-summary",
112 cl::desc("Write summary to given YAML file after running pass"),
113 cl::Hidden);
114
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000115// Find the minimum offset that we may store a value of size Size bits at. If
116// IsAfter is set, look for an offset before the object, otherwise look for an
117// offset after the object.
118uint64_t
119wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
120 bool IsAfter, uint64_t Size) {
121 // Find a minimum offset taking into account only vtable sizes.
122 uint64_t MinByte = 0;
123 for (const VirtualCallTarget &Target : Targets) {
124 if (IsAfter)
125 MinByte = std::max(MinByte, Target.minAfterBytes());
126 else
127 MinByte = std::max(MinByte, Target.minBeforeBytes());
128 }
129
130 // Build a vector of arrays of bytes covering, for each target, a slice of the
131 // used region (see AccumBitVector::BytesUsed in
132 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
133 // this aligns the used regions to start at MinByte.
134 //
135 // In this example, A, B and C are vtables, # is a byte already allocated for
136 // a virtual function pointer, AAAA... (etc.) are the used regions for the
137 // vtables and Offset(X) is the value computed for the Offset variable below
138 // for X.
139 //
140 // Offset(A)
141 // | |
142 // |MinByte
143 // A: ################AAAAAAAA|AAAAAAAA
144 // B: ########BBBBBBBBBBBBBBBB|BBBB
145 // C: ########################|CCCCCCCCCCCCCCCC
146 // | Offset(B) |
147 //
148 // This code produces the slices of A, B and C that appear after the divider
149 // at MinByte.
150 std::vector<ArrayRef<uint8_t>> Used;
151 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000152 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
153 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000154 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
155 : MinByte - Target.minBeforeBytes();
156
157 // Disregard used regions that are smaller than Offset. These are
158 // effectively all-free regions that do not need to be checked.
159 if (VTUsed.size() > Offset)
160 Used.push_back(VTUsed.slice(Offset));
161 }
162
163 if (Size == 1) {
164 // Find a free bit in each member of Used.
165 for (unsigned I = 0;; ++I) {
166 uint8_t BitsUsed = 0;
167 for (auto &&B : Used)
168 if (I < B.size())
169 BitsUsed |= B[I];
170 if (BitsUsed != 0xff)
171 return (MinByte + I) * 8 +
172 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
173 }
174 } else {
175 // Find a free (Size/8) byte region in each member of Used.
176 // FIXME: see if alignment helps.
177 for (unsigned I = 0;; ++I) {
178 for (auto &&B : Used) {
179 unsigned Byte = 0;
180 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
181 if (B[I + Byte])
182 goto NextI;
183 ++Byte;
184 }
185 }
186 return (MinByte + I) * 8;
187 NextI:;
188 }
189 }
190}
191
192void wholeprogramdevirt::setBeforeReturnValues(
193 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
194 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
195 if (BitWidth == 1)
196 OffsetByte = -(AllocBefore / 8 + 1);
197 else
198 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
199 OffsetBit = AllocBefore % 8;
200
201 for (VirtualCallTarget &Target : Targets) {
202 if (BitWidth == 1)
203 Target.setBeforeBit(AllocBefore);
204 else
205 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
206 }
207}
208
209void wholeprogramdevirt::setAfterReturnValues(
210 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
211 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
212 if (BitWidth == 1)
213 OffsetByte = AllocAfter / 8;
214 else
215 OffsetByte = (AllocAfter + 7) / 8;
216 OffsetBit = AllocAfter % 8;
217
218 for (VirtualCallTarget &Target : Targets) {
219 if (BitWidth == 1)
220 Target.setAfterBit(AllocAfter);
221 else
222 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
223 }
224}
225
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000226VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
227 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000228 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000229
230namespace {
231
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000232// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000233// tables, and the ByteOffset is the offset in bytes from the address point to
234// the virtual function pointer.
235struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000236 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000237 uint64_t ByteOffset;
238};
239
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000240} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000241
Peter Collingbourne9b656522016-02-09 23:01:38 +0000242namespace llvm {
243
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000244template <> struct DenseMapInfo<VTableSlot> {
245 static VTableSlot getEmptyKey() {
246 return {DenseMapInfo<Metadata *>::getEmptyKey(),
247 DenseMapInfo<uint64_t>::getEmptyKey()};
248 }
249 static VTableSlot getTombstoneKey() {
250 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
251 DenseMapInfo<uint64_t>::getTombstoneKey()};
252 }
253 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000254 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000255 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
256 }
257 static bool isEqual(const VTableSlot &LHS,
258 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000259 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000260 }
261};
262
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000263} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000264
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000265namespace {
266
267// A virtual call site. VTable is the loaded virtual table pointer, and CS is
268// the indirect virtual call.
269struct VirtualCallSite {
270 Value *VTable;
271 CallSite CS;
272
Peter Collingbourne0312f612016-06-25 00:23:04 +0000273 // If non-null, this field points to the associated unsafe use count stored in
274 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
275 // of that field for details.
276 unsigned *NumUnsafeUses;
277
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000278 void emitRemark(const Twine &OptName, const Twine &TargetName) {
Ivan Krasin54746452016-07-12 02:38:37 +0000279 Function *F = CS.getCaller();
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000280 emitOptimizationRemark(
281 F->getContext(), DEBUG_TYPE, *F,
282 CS.getInstruction()->getDebugLoc(),
283 OptName + ": devirtualized a call to " + TargetName);
Ivan Krasin54746452016-07-12 02:38:37 +0000284 }
285
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000286 void replaceAndErase(const Twine &OptName, const Twine &TargetName,
287 bool RemarksEnabled, Value *New) {
288 if (RemarksEnabled)
289 emitRemark(OptName, TargetName);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000290 CS->replaceAllUsesWith(New);
291 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
292 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
293 II->getUnwindDest()->removePredecessor(II->getParent());
294 }
295 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000296 // This use is no longer unsafe.
297 if (NumUnsafeUses)
298 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000299 }
300};
301
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000302// Call site information collected for a specific VTableSlot and possibly a list
303// of constant integer arguments. The grouping by arguments is handled by the
304// VTableSlotInfo class.
305struct CallSiteInfo {
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000306 /// The set of call sites for this slot. Used during regular LTO and the
307 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
308 /// call sites that appear in the merged module itself); in each of these
309 /// cases we are directly operating on the call sites at the IR level.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000310 std::vector<VirtualCallSite> CallSites;
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000311
312 // These fields are used during the export phase of ThinLTO and reflect
313 // information collected from function summaries.
314
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000315 /// Whether any function summary contains an llvm.assume(llvm.type.test) for
316 /// this slot.
317 bool SummaryHasTypeTestAssumeUsers;
318
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000319 /// CFI-specific: a vector containing the list of function summaries that use
320 /// the llvm.type.checked.load intrinsic and therefore will require
321 /// resolutions for llvm.type.test in order to implement CFI checks if
322 /// devirtualization was unsuccessful. If devirtualization was successful, the
323 /// pass will clear this vector. If at the end of the pass the vector is
324 /// non-empty, we will need to add a use of llvm.type.test to each of the
325 /// function summaries in the vector.
326 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000327
328 bool isExported() const {
329 return SummaryHasTypeTestAssumeUsers ||
330 !SummaryTypeCheckedLoadUsers.empty();
331 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000332};
333
334// Call site information collected for a specific VTableSlot.
335struct VTableSlotInfo {
336 // The set of call sites which do not have all constant integer arguments
337 // (excluding "this").
338 CallSiteInfo CSInfo;
339
340 // The set of call sites with all constant integer arguments (excluding
341 // "this"), grouped by argument list.
342 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
343
344 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
345
346private:
347 CallSiteInfo &findCallSiteInfo(CallSite CS);
348};
349
350CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
351 std::vector<uint64_t> Args;
352 auto *CI = dyn_cast<IntegerType>(CS.getType());
353 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
354 return CSInfo;
355 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
356 auto *CI = dyn_cast<ConstantInt>(Arg);
357 if (!CI || CI->getBitWidth() > 64)
358 return CSInfo;
359 Args.push_back(CI->getZExtValue());
360 }
361 return ConstCSInfo[Args];
362}
363
364void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
365 unsigned *NumUnsafeUses) {
366 findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses});
367}
368
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000369struct DevirtModule {
370 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000371 function_ref<AAResults &(Function &)> AARGetter;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000372
373 PassSummaryAction Action;
374 ModuleSummaryIndex *Summary;
375
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000376 IntegerType *Int8Ty;
377 PointerType *Int8PtrTy;
378 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000379 IntegerType *Int64Ty;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000380
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000381 bool RemarksEnabled;
382
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000383 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000384
Peter Collingbourne0312f612016-06-25 00:23:04 +0000385 // This map keeps track of the number of "unsafe" uses of a loaded function
386 // pointer. The key is the associated llvm.type.test intrinsic call generated
387 // by this pass. An unsafe use is one that calls the loaded function pointer
388 // directly. Every time we eliminate an unsafe use (for example, by
389 // devirtualizing it or by applying virtual constant propagation), we
390 // decrement the value stored in this map. If a value reaches zero, we can
391 // eliminate the type check by RAUWing the associated llvm.type.test call with
392 // true.
393 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
394
Peter Collingbourne37317f12017-02-17 18:17:04 +0000395 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
396 PassSummaryAction Action, ModuleSummaryIndex *Summary)
397 : M(M), AARGetter(AARGetter), Action(Action), Summary(Summary),
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000398 Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000399 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000400 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000401 Int64Ty(Type::getInt64Ty(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000402 RemarksEnabled(areRemarksEnabled()) {}
403
404 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000405
Peter Collingbourne0312f612016-06-25 00:23:04 +0000406 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
407 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
408
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000409 void buildTypeIdentifierMap(
410 std::vector<VTableBits> &Bits,
411 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000412 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000413 bool
414 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
415 const std::set<TypeMemberInfo> &TypeMemberInfos,
416 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000417
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000418 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
419 bool &IsExported);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000420 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000421 VTableSlotInfo &SlotInfo,
422 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000423
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000424 bool tryEvaluateFunctionsWithArgs(
425 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000426 ArrayRef<uint64_t> Args);
427
428 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
429 uint64_t TheRetVal);
430 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000431 CallSiteInfo &CSInfo,
432 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000433
434 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
435 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000436 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000437 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000438 CallSiteInfo &CSInfo);
439
440 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
441 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000442 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000443 VTableSlotInfo &SlotInfo,
444 WholeProgramDevirtResolution *Res);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000445
446 void rebuildGlobal(VTableBits &B);
447
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000448 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
449 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
450
451 // If we were able to eliminate all unsafe uses for a type checked load,
452 // eliminate the associated type tests by replacing them with true.
453 void removeRedundantTypeTests();
454
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000455 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000456
457 // Lower the module using the action and summary passed as command line
458 // arguments. For testing purposes only.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000459 static bool runForTesting(Module &M,
460 function_ref<AAResults &(Function &)> AARGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000461};
462
463struct WholeProgramDevirt : public ModulePass {
464 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000465
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000466 bool UseCommandLine = false;
467
468 PassSummaryAction Action;
469 ModuleSummaryIndex *Summary;
470
471 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
472 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
473 }
474
475 WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary)
476 : ModulePass(ID), Action(Action), Summary(Summary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000477 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
478 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000479
480 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000481 if (skipModule(M))
482 return false;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000483 if (UseCommandLine)
Peter Collingbourne37317f12017-02-17 18:17:04 +0000484 return DevirtModule::runForTesting(M, LegacyAARGetter(*this));
485 return DevirtModule(M, LegacyAARGetter(*this), Action, Summary).run();
486 }
487
488 void getAnalysisUsage(AnalysisUsage &AU) const override {
489 AU.addRequired<AssumptionCacheTracker>();
490 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000491 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000492};
493
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000494} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000495
Peter Collingbourne37317f12017-02-17 18:17:04 +0000496INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
497 "Whole program devirtualization", false, false)
498INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
499INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
500INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
501 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000502char WholeProgramDevirt::ID = 0;
503
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000504ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action,
505 ModuleSummaryIndex *Summary) {
506 return new WholeProgramDevirt(Action, Summary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000507}
508
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000509PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000510 ModuleAnalysisManager &AM) {
511 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
512 auto AARGetter = [&](Function &F) -> AAResults & {
513 return FAM.getResult<AAManager>(F);
514 };
515 if (!DevirtModule(M, AARGetter, PassSummaryAction::None, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000516 return PreservedAnalyses::all();
517 return PreservedAnalyses::none();
518}
519
Peter Collingbourne37317f12017-02-17 18:17:04 +0000520bool DevirtModule::runForTesting(
521 Module &M, function_ref<AAResults &(Function &)> AARGetter) {
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000522 ModuleSummaryIndex Summary;
523
524 // Handle the command-line summary arguments. This code is for testing
525 // purposes only, so we handle errors directly.
526 if (!ClReadSummary.empty()) {
527 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
528 ": ");
529 auto ReadSummaryFile =
530 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
531
532 yaml::Input In(ReadSummaryFile->getBuffer());
533 In >> Summary;
534 ExitOnErr(errorCodeToError(In.error()));
535 }
536
Peter Collingbourne37317f12017-02-17 18:17:04 +0000537 bool Changed = DevirtModule(M, AARGetter, ClSummaryAction, &Summary).run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000538
539 if (!ClWriteSummary.empty()) {
540 ExitOnError ExitOnErr(
541 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
542 std::error_code EC;
543 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
544 ExitOnErr(errorCodeToError(EC));
545
546 yaml::Output Out(OS);
547 Out << Summary;
548 }
549
550 return Changed;
551}
552
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000553void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000554 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000555 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000556 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000557 Bits.reserve(M.getGlobalList().size());
558 SmallVector<MDNode *, 2> Types;
559 for (GlobalVariable &GV : M.globals()) {
560 Types.clear();
561 GV.getMetadata(LLVMContext::MD_type, Types);
562 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000563 continue;
564
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000565 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000566 if (!BitsPtr) {
567 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000568 Bits.back().GV = &GV;
569 Bits.back().ObjectSize =
570 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000571 BitsPtr = &Bits.back();
572 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000573
574 for (MDNode *Type : Types) {
575 auto TypeID = Type->getOperand(1).get();
576
577 uint64_t Offset =
578 cast<ConstantInt>(
579 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
580 ->getZExtValue();
581
582 TypeIdMap[TypeID].insert({BitsPtr, Offset});
583 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000584 }
585}
586
Peter Collingbourne87867542016-12-09 01:10:11 +0000587Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
588 if (I->getType()->isPointerTy()) {
589 if (Offset == 0)
590 return I;
591 return nullptr;
592 }
593
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000594 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000595
596 if (auto *C = dyn_cast<ConstantStruct>(I)) {
597 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000598 if (Offset >= SL->getSizeInBytes())
599 return nullptr;
600
Peter Collingbourne87867542016-12-09 01:10:11 +0000601 unsigned Op = SL->getElementContainingOffset(Offset);
602 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
603 Offset - SL->getElementOffset(Op));
604 }
605 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000606 ArrayType *VTableTy = C->getType();
607 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
608
Peter Collingbourne87867542016-12-09 01:10:11 +0000609 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000610 if (Op >= C->getNumOperands())
611 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000612
Peter Collingbourne87867542016-12-09 01:10:11 +0000613 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
614 Offset % ElemSize);
615 }
616 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000617}
618
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000619bool DevirtModule::tryFindVirtualCallTargets(
620 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000621 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
622 for (const TypeMemberInfo &TM : TypeMemberInfos) {
623 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000624 return false;
625
Peter Collingbourne87867542016-12-09 01:10:11 +0000626 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
627 TM.Offset + ByteOffset);
628 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000629 return false;
630
Peter Collingbourne87867542016-12-09 01:10:11 +0000631 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000632 if (!Fn)
633 return false;
634
635 // We can disregard __cxa_pure_virtual as a possible call target, as
636 // calls to pure virtuals are UB.
637 if (Fn->getName() == "__cxa_pure_virtual")
638 continue;
639
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000640 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000641 }
642
643 // Give up if we couldn't find any targets.
644 return !TargetsForSlot.empty();
645}
646
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000647void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000648 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000649 auto Apply = [&](CallSiteInfo &CSInfo) {
650 for (auto &&VCallSite : CSInfo.CallSites) {
651 if (RemarksEnabled)
652 VCallSite.emitRemark("single-impl", TheFn->getName());
653 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
654 TheFn, VCallSite.CS.getCalledValue()->getType()));
655 // This use is no longer unsafe.
656 if (VCallSite.NumUnsafeUses)
657 --*VCallSite.NumUnsafeUses;
658 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000659 if (CSInfo.isExported()) {
660 IsExported = true;
661 CSInfo.SummaryTypeCheckedLoadUsers.clear();
662 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000663 };
664 Apply(SlotInfo.CSInfo);
665 for (auto &P : SlotInfo.ConstCSInfo)
666 Apply(P.second);
667}
668
Peter Collingbournee2367412017-02-15 02:13:08 +0000669bool DevirtModule::trySingleImplDevirt(
670 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000671 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000672 // See if the program contains a single implementation of this virtual
673 // function.
674 Function *TheFn = TargetsForSlot[0].Fn;
675 for (auto &&Target : TargetsForSlot)
676 if (TheFn != Target.Fn)
677 return false;
678
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000679 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000680 if (RemarksEnabled)
681 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000682
683 bool IsExported = false;
684 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
685 if (!IsExported)
686 return false;
687
688 // If the only implementation has local linkage, we must promote to external
689 // to make it visible to thin LTO objects. We can only get here during the
690 // ThinLTO export phase.
691 if (TheFn->hasLocalLinkage()) {
692 TheFn->setLinkage(GlobalValue::ExternalLinkage);
693 TheFn->setVisibility(GlobalValue::HiddenVisibility);
694 TheFn->setName(TheFn->getName() + "$merged");
695 }
696
697 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
698 Res->SingleImplName = TheFn->getName();
699
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000700 return true;
701}
702
703bool DevirtModule::tryEvaluateFunctionsWithArgs(
704 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000705 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000706 // Evaluate each function and store the result in each target's RetVal
707 // field.
708 for (VirtualCallTarget &Target : TargetsForSlot) {
709 if (Target.Fn->arg_size() != Args.size() + 1)
710 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000711
712 Evaluator Eval(M.getDataLayout(), nullptr);
713 SmallVector<Constant *, 2> EvalArgs;
714 EvalArgs.push_back(
715 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000716 for (unsigned I = 0; I != Args.size(); ++I) {
717 auto *ArgTy = dyn_cast<IntegerType>(
718 Target.Fn->getFunctionType()->getParamType(I + 1));
719 if (!ArgTy)
720 return false;
721 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
722 }
723
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000724 Constant *RetVal;
725 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
726 !isa<ConstantInt>(RetVal))
727 return false;
728 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
729 }
730 return true;
731}
732
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000733void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
734 uint64_t TheRetVal) {
735 for (auto Call : CSInfo.CallSites)
736 Call.replaceAndErase(
737 "uniform-ret-val", FnName, RemarksEnabled,
738 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbournef0bb90b2017-03-04 01:38:05 +0000739 CSInfo.SummaryTypeCheckedLoadUsers.clear();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000740}
741
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000742bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000743 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
744 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000745 // Uniform return value optimization. If all functions return the same
746 // constant, replace all calls with that constant.
747 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
748 for (const VirtualCallTarget &Target : TargetsForSlot)
749 if (Target.RetVal != TheRetVal)
750 return false;
751
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000752 if (CSInfo.isExported()) {
753 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
754 Res->Info = TheRetVal;
755 }
756
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000757 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000758 if (RemarksEnabled)
759 for (auto &&Target : TargetsForSlot)
760 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000761 return true;
762}
763
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000764void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
765 bool IsOne,
766 Constant *UniqueMemberAddr) {
767 for (auto &&Call : CSInfo.CallSites) {
768 IRBuilder<> B(Call.CS.getInstruction());
769 Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
770 Call.VTable, UniqueMemberAddr);
771 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
772 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp);
773 }
774}
775
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000776bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000777 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000778 CallSiteInfo &CSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000779 // IsOne controls whether we look for a 0 or a 1.
780 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000781 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000782 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +0000783 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000784 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000785 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000786 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000787 }
788 }
789
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000790 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000791 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000792 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000793
794 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000795 Constant *UniqueMemberAddr =
796 ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy);
797 UniqueMemberAddr = ConstantExpr::getGetElementPtr(
798 Int8Ty, UniqueMemberAddr,
799 ConstantInt::get(Int64Ty, UniqueMember->Offset));
800
801 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
802 UniqueMemberAddr);
803
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000804 // Update devirtualization statistics for targets.
805 if (RemarksEnabled)
806 for (auto &&Target : TargetsForSlot)
807 Target.WasDevirt = true;
808
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000809 return true;
810 };
811
812 if (BitWidth == 1) {
813 if (tryUniqueRetValOptFor(true))
814 return true;
815 if (tryUniqueRetValOptFor(false))
816 return true;
817 }
818 return false;
819}
820
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000821void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
822 Constant *Byte, Constant *Bit) {
823 for (auto Call : CSInfo.CallSites) {
824 auto *RetType = cast<IntegerType>(Call.CS.getType());
825 IRBuilder<> B(Call.CS.getInstruction());
826 Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte);
827 if (RetType->getBitWidth() == 1) {
828 Value *Bits = B.CreateLoad(Addr);
829 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
830 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
831 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
832 IsBitSet);
833 } else {
834 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
835 Value *Val = B.CreateLoad(RetType, ValAddr);
836 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val);
837 }
838 }
839}
840
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000841bool DevirtModule::tryVirtualConstProp(
842 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000843 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000844 // This only works if the function returns an integer.
845 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
846 if (!RetType)
847 return false;
848 unsigned BitWidth = RetType->getBitWidth();
849 if (BitWidth > 64)
850 return false;
851
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000852 // Make sure that each function is defined, does not access memory, takes at
853 // least one argument, does not use its first argument (which we assume is
854 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000855 //
856 // Note that we test whether this copy of the function is readnone, rather
857 // than testing function attributes, which must hold for any copy of the
858 // function, even a less optimized version substituted at link time. This is
859 // sound because the virtual constant propagation optimizations effectively
860 // inline all implementations of the virtual function into each call site,
861 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000862 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +0000863 if (Target.Fn->isDeclaration() ||
864 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
865 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000866 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000867 Target.Fn->getReturnType() != RetType)
868 return false;
869 }
870
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000871 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000872 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
873 continue;
874
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000875 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
876 if (Res)
877 ResByArg = &Res->ResByArg[CSByConstantArg.first];
878
879 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000880 continue;
881
882 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second))
883 continue;
884
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000885 // Find an allocation offset in bits in all vtables associated with the
886 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000887 uint64_t AllocBefore =
888 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
889 uint64_t AllocAfter =
890 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
891
892 // Calculate the total amount of padding needed to store a value at both
893 // ends of the object.
894 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
895 for (auto &&Target : TargetsForSlot) {
896 TotalPaddingBefore += std::max<int64_t>(
897 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
898 TotalPaddingAfter += std::max<int64_t>(
899 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
900 }
901
902 // If the amount of padding is too large, give up.
903 // FIXME: do something smarter here.
904 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
905 continue;
906
907 // Calculate the offset to the value as a (possibly negative) byte offset
908 // and (if applicable) a bit offset, and store the values in the targets.
909 int64_t OffsetByte;
910 uint64_t OffsetBit;
911 if (TotalPaddingBefore <= TotalPaddingAfter)
912 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
913 OffsetBit);
914 else
915 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
916 OffsetBit);
917
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000918 if (RemarksEnabled)
919 for (auto &&Target : TargetsForSlot)
920 Target.WasDevirt = true;
921
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000922 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourne184773d2017-02-17 19:43:45 +0000923 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000924 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
925 applyVirtualConstProp(CSByConstantArg.second,
926 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000927 }
928 return true;
929}
930
931void DevirtModule::rebuildGlobal(VTableBits &B) {
932 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
933 return;
934
935 // Align each byte array to pointer width.
936 unsigned PointerSize = M.getDataLayout().getPointerSize();
937 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
938 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
939
940 // Before was stored in reverse order; flip it now.
941 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
942 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
943
944 // Build an anonymous global containing the before bytes, followed by the
945 // original initializer, followed by the after bytes.
946 auto NewInit = ConstantStruct::getAnon(
947 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
948 B.GV->getInitializer(),
949 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
950 auto NewGV =
951 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
952 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
953 NewGV->setSection(B.GV->getSection());
954 NewGV->setComdat(B.GV->getComdat());
955
Peter Collingbourne0312f612016-06-25 00:23:04 +0000956 // Copy the original vtable's metadata to the anonymous global, adjusting
957 // offsets as required.
958 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
959
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000960 // Build an alias named after the original global, pointing at the second
961 // element (the original initializer).
962 auto Alias = GlobalAlias::create(
963 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
964 ConstantExpr::getGetElementPtr(
965 NewInit->getType(), NewGV,
966 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
967 ConstantInt::get(Int32Ty, 1)}),
968 &M);
969 Alias->setVisibility(B.GV->getVisibility());
970 Alias->takeName(B.GV);
971
972 B.GV->replaceAllUsesWith(Alias);
973 B.GV->eraseFromParent();
974}
975
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000976bool DevirtModule::areRemarksEnabled() {
977 const auto &FL = M.getFunctionList();
978 if (FL.empty())
979 return false;
980 const Function &Fn = FL.front();
Adam Nemetde53bfb2017-02-23 23:11:11 +0000981
982 const auto &BBL = Fn.getBasicBlockList();
983 if (BBL.empty())
984 return false;
985 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000986 return DI.isEnabled();
987}
988
Peter Collingbourne0312f612016-06-25 00:23:04 +0000989void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
990 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000991 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000992 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
993 // points to a member of the type identifier %md. Group calls by (type ID,
994 // offset) pair (effectively the identity of the virtual function) and store
995 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000996 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000997 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000998 I != E;) {
999 auto CI = dyn_cast<CallInst>(I->getUser());
1000 ++I;
1001 if (!CI)
1002 continue;
1003
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001004 // Search for virtual calls based on %p and add them to DevirtCalls.
1005 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001006 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +00001007 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001008
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001009 // If we found any, add them to CallSlots. Only do this if we haven't seen
1010 // the vtable pointer before, as it may have been CSE'd with pointers from
1011 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001012 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001013 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001014 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1015 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001016 if (SeenPtrs.insert(Ptr).second) {
1017 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001018 CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0),
1019 Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001020 }
1021 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001022 }
1023
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001024 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001025 for (auto Assume : Assumes)
1026 Assume->eraseFromParent();
1027 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1028 // may use the vtable argument later.
1029 if (CI->use_empty())
1030 CI->eraseFromParent();
1031 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001032}
1033
1034void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1035 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1036
1037 for (auto I = TypeCheckedLoadFunc->use_begin(),
1038 E = TypeCheckedLoadFunc->use_end();
1039 I != E;) {
1040 auto CI = dyn_cast<CallInst>(I->getUser());
1041 ++I;
1042 if (!CI)
1043 continue;
1044
1045 Value *Ptr = CI->getArgOperand(0);
1046 Value *Offset = CI->getArgOperand(1);
1047 Value *TypeIdValue = CI->getArgOperand(2);
1048 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1049
1050 SmallVector<DevirtCallSite, 1> DevirtCalls;
1051 SmallVector<Instruction *, 1> LoadedPtrs;
1052 SmallVector<Instruction *, 1> Preds;
1053 bool HasNonCallUses = false;
1054 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1055 HasNonCallUses, CI);
1056
1057 // Start by generating "pessimistic" code that explicitly loads the function
1058 // pointer from the vtable and performs the type check. If possible, we will
1059 // eliminate the load and the type check later.
1060
1061 // If possible, only generate the load at the point where it is used.
1062 // This helps avoid unnecessary spills.
1063 IRBuilder<> LoadB(
1064 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1065 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1066 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1067 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1068
1069 for (Instruction *LoadedPtr : LoadedPtrs) {
1070 LoadedPtr->replaceAllUsesWith(LoadedValue);
1071 LoadedPtr->eraseFromParent();
1072 }
1073
1074 // Likewise for the type test.
1075 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1076 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1077
1078 for (Instruction *Pred : Preds) {
1079 Pred->replaceAllUsesWith(TypeTestCall);
1080 Pred->eraseFromParent();
1081 }
1082
1083 // We have already erased any extractvalue instructions that refer to the
1084 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1085 // (although this is unlikely). In that case, explicitly build a pair and
1086 // RAUW it.
1087 if (!CI->use_empty()) {
1088 Value *Pair = UndefValue::get(CI->getType());
1089 IRBuilder<> B(CI);
1090 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1091 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1092 CI->replaceAllUsesWith(Pair);
1093 }
1094
1095 // The number of unsafe uses is initially the number of uses.
1096 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1097 NumUnsafeUses = DevirtCalls.size();
1098
1099 // If the function pointer has a non-call user, we cannot eliminate the type
1100 // check, as one of those users may eventually call the pointer. Increment
1101 // the unsafe use count to make sure it cannot reach zero.
1102 if (HasNonCallUses)
1103 ++NumUnsafeUses;
1104 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001105 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1106 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001107 }
1108
1109 CI->eraseFromParent();
1110 }
1111}
1112
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001113void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
1114 const WholeProgramDevirtResolution &Res =
1115 Summary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString())
1116 .WPDRes[Slot.ByteOffset];
1117
1118 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1119 // The type of the function in the declaration is irrelevant because every
1120 // call site will cast it to the correct type.
1121 auto *SingleImpl = M.getOrInsertFunction(
1122 Res.SingleImplName, Type::getVoidTy(M.getContext()), nullptr);
1123
1124 // This is the import phase so we should not be exporting anything.
1125 bool IsExported = false;
1126 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1127 assert(!IsExported);
1128 }
1129}
1130
1131void DevirtModule::removeRedundantTypeTests() {
1132 auto True = ConstantInt::getTrue(M.getContext());
1133 for (auto &&U : NumUnsafeUsesForTypeTest) {
1134 if (U.second == 0) {
1135 U.first->replaceAllUsesWith(True);
1136 U.first->eraseFromParent();
1137 }
1138 }
1139}
1140
Peter Collingbourne0312f612016-06-25 00:23:04 +00001141bool DevirtModule::run() {
1142 Function *TypeTestFunc =
1143 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1144 Function *TypeCheckedLoadFunc =
1145 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1146 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1147
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001148 // Normally if there are no users of the devirtualization intrinsics in the
1149 // module, this pass has nothing to do. But if we are exporting, we also need
1150 // to handle any users that appear only in the function summaries.
1151 if (Action != PassSummaryAction::Export &&
1152 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001153 AssumeFunc->use_empty()) &&
1154 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1155 return false;
1156
1157 if (TypeTestFunc && AssumeFunc)
1158 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1159
1160 if (TypeCheckedLoadFunc)
1161 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001162
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001163 if (Action == PassSummaryAction::Import) {
1164 for (auto &S : CallSlots)
1165 importResolution(S.first, S.second);
1166
1167 removeRedundantTypeTests();
1168
1169 // The rest of the code is only necessary when exporting or during regular
1170 // LTO, so we are done.
1171 return true;
1172 }
1173
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001174 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001175 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001176 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1177 buildTypeIdentifierMap(Bits, TypeIdMap);
1178 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001179 return true;
1180
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001181 // Collect information from summary about which calls to try to devirtualize.
1182 if (Action == PassSummaryAction::Export) {
1183 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1184 for (auto &P : TypeIdMap) {
1185 if (auto *TypeId = dyn_cast<MDString>(P.first))
1186 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1187 TypeId);
1188 }
1189
1190 for (auto &P : *Summary) {
1191 for (auto &S : P.second) {
1192 auto *FS = dyn_cast<FunctionSummary>(S.get());
1193 if (!FS)
1194 continue;
1195 // FIXME: Only add live functions.
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001196 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls())
1197 for (Metadata *MD : MetadataByGUID[VF.GUID])
1198 CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers =
1199 true;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001200 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls())
1201 for (Metadata *MD : MetadataByGUID[VF.GUID])
1202 CallSlots[{MD, VF.Offset}]
1203 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS);
1204 for (const FunctionSummary::ConstVCall &VC :
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001205 FS->type_test_assume_const_vcalls())
1206 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID])
1207 CallSlots[{MD, VC.VFunc.Offset}]
1208 .ConstCSInfo[VC.Args].SummaryHasTypeTestAssumeUsers = true;
1209 for (const FunctionSummary::ConstVCall &VC :
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001210 FS->type_checked_load_const_vcalls())
1211 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID])
1212 CallSlots[{MD, VC.VFunc.Offset}]
1213 .ConstCSInfo[VC.Args]
1214 .SummaryTypeCheckedLoadUsers.push_back(FS);
1215 }
1216 }
1217 }
1218
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001219 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001220 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001221 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001222 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001223 // Search each of the members of the type identifier for the virtual
1224 // function implementation at offset S.first.ByteOffset, and add to
1225 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001226 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001227 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1228 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001229 WholeProgramDevirtResolution *Res = nullptr;
1230 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID))
1231 Res =
1232 &Summary
1233 ->getTypeIdSummary(cast<MDString>(S.first.TypeID)->getString())
1234 .WPDRes[S.first.ByteOffset];
1235
1236 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) &&
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001237 tryVirtualConstProp(TargetsForSlot, S.second, Res))
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001238 DidVirtualConstProp = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001239
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001240 // Collect functions devirtualized at least for one call site for stats.
1241 if (RemarksEnabled)
1242 for (const auto &T : TargetsForSlot)
1243 if (T.WasDevirt)
1244 DevirtTargets[T.Fn->getName()] = T.Fn;
1245 }
1246
1247 // CFI-specific: if we are exporting and any llvm.type.checked.load
1248 // intrinsics were *not* devirtualized, we need to add the resulting
1249 // llvm.type.test intrinsics to the function summaries so that the
1250 // LowerTypeTests pass will export them.
1251 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) {
1252 auto GUID =
1253 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1254 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1255 FS->addTypeTest(GUID);
1256 for (auto &CCS : S.second.ConstCSInfo)
1257 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1258 FS->addTypeTest(GUID);
1259 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001260 }
1261
1262 if (RemarksEnabled) {
1263 // Generate remarks for each devirtualized function.
1264 for (const auto &DT : DevirtTargets) {
1265 Function *F = DT.second;
1266 DISubprogram *SP = F->getSubprogram();
Justin Bogner7bc978b2017-02-18 02:00:27 +00001267 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, SP,
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001268 Twine("devirtualized ") + F->getName());
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001269 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001270 }
1271
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001272 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00001273
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001274 // Rebuild each global we touched as part of virtual constant propagation to
1275 // include the before and after bytes.
1276 if (DidVirtualConstProp)
1277 for (VTableBits &B : Bits)
1278 rebuildGlobal(B);
1279
1280 return true;
1281}