blob: c4e6e3957d096eabb4f23daa0c7d85eea4a6ef55 [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"
49#include "llvm/ADT/MapVector.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000051#include "llvm/ADT/iterator_range.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000052#include "llvm/Analysis/AliasAnalysis.h"
53#include "llvm/Analysis/BasicAliasAnalysis.h"
Sam Elliotte963c892017-08-21 16:57:21 +000054#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Peter Collingbourne7efd7502016-06-24 21:21:32 +000055#include "llvm/Analysis/TypeMetadataUtils.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000056#include "llvm/IR/CallSite.h"
57#include "llvm/IR/Constants.h"
58#include "llvm/IR/DataLayout.h"
Ivan Krasinb05e06e2016-08-05 19:45:16 +000059#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000060#include "llvm/IR/DebugLoc.h"
61#include "llvm/IR/DerivedTypes.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
Sam Elliotte963c892017-08-21 16:57:21 +0000278 void
279 emitRemark(const StringRef OptName, const StringRef TargetName,
280 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Ivan Krasin54746452016-07-12 02:38:37 +0000281 Function *F = CS.getCaller();
Sam Elliotte963c892017-08-21 16:57:21 +0000282 DebugLoc DLoc = CS->getDebugLoc();
283 BasicBlock *Block = CS.getParent();
284
285 // In the new pass manager, we can request the optimization
286 // remark emitter pass on a per-function-basis, which the
287 // OREGetter will do for us.
288 // In the old pass manager, this is harder, so we just build
289 // a optimization remark emitter on the fly, when we need it.
290 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
291 OptimizationRemarkEmitter *ORE;
292 if (OREGetter)
293 ORE = &OREGetter(F);
294 else {
295 OwnedORE = make_unique<OptimizationRemarkEmitter>(F);
296 ORE = OwnedORE.get();
297 }
298
299 using namespace ore;
300 ORE->emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
301 << NV("Optimization", OptName) << ": devirtualized a call to "
302 << NV("FunctionName", TargetName));
Ivan Krasin54746452016-07-12 02:38:37 +0000303 }
304
Sam Elliotte963c892017-08-21 16:57:21 +0000305 void replaceAndErase(
306 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
307 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
308 Value *New) {
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000309 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000310 emitRemark(OptName, TargetName, OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000311 CS->replaceAllUsesWith(New);
312 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
313 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
314 II->getUnwindDest()->removePredecessor(II->getParent());
315 }
316 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000317 // This use is no longer unsafe.
318 if (NumUnsafeUses)
319 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000320 }
321};
322
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000323// Call site information collected for a specific VTableSlot and possibly a list
324// of constant integer arguments. The grouping by arguments is handled by the
325// VTableSlotInfo class.
326struct CallSiteInfo {
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000327 /// The set of call sites for this slot. Used during regular LTO and the
328 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
329 /// call sites that appear in the merged module itself); in each of these
330 /// cases we are directly operating on the call sites at the IR level.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000331 std::vector<VirtualCallSite> CallSites;
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000332
333 // These fields are used during the export phase of ThinLTO and reflect
334 // information collected from function summaries.
335
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000336 /// Whether any function summary contains an llvm.assume(llvm.type.test) for
337 /// this slot.
338 bool SummaryHasTypeTestAssumeUsers;
339
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000340 /// CFI-specific: a vector containing the list of function summaries that use
341 /// the llvm.type.checked.load intrinsic and therefore will require
342 /// resolutions for llvm.type.test in order to implement CFI checks if
343 /// devirtualization was unsuccessful. If devirtualization was successful, the
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000344 /// pass will clear this vector by calling markDevirt(). If at the end of the
345 /// pass the vector is non-empty, we will need to add a use of llvm.type.test
346 /// to each of the function summaries in the vector.
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000347 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000348
349 bool isExported() const {
350 return SummaryHasTypeTestAssumeUsers ||
351 !SummaryTypeCheckedLoadUsers.empty();
352 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000353
354 /// As explained in the comment for SummaryTypeCheckedLoadUsers.
355 void markDevirt() { SummaryTypeCheckedLoadUsers.clear(); }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000356};
357
358// Call site information collected for a specific VTableSlot.
359struct VTableSlotInfo {
360 // The set of call sites which do not have all constant integer arguments
361 // (excluding "this").
362 CallSiteInfo CSInfo;
363
364 // The set of call sites with all constant integer arguments (excluding
365 // "this"), grouped by argument list.
366 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
367
368 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
369
370private:
371 CallSiteInfo &findCallSiteInfo(CallSite CS);
372};
373
374CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
375 std::vector<uint64_t> Args;
376 auto *CI = dyn_cast<IntegerType>(CS.getType());
377 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
378 return CSInfo;
379 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
380 auto *CI = dyn_cast<ConstantInt>(Arg);
381 if (!CI || CI->getBitWidth() > 64)
382 return CSInfo;
383 Args.push_back(CI->getZExtValue());
384 }
385 return ConstCSInfo[Args];
386}
387
388void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
389 unsigned *NumUnsafeUses) {
390 findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses});
391}
392
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000393struct DevirtModule {
394 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000395 function_ref<AAResults &(Function &)> AARGetter;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000396
Peter Collingbournef7691d82017-03-22 18:22:59 +0000397 ModuleSummaryIndex *ExportSummary;
398 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000399
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000400 IntegerType *Int8Ty;
401 PointerType *Int8PtrTy;
402 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000403 IntegerType *Int64Ty;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000404 IntegerType *IntPtrTy;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000405
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000406 bool RemarksEnabled;
Sam Elliotte963c892017-08-21 16:57:21 +0000407 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000408
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000409 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000410
Peter Collingbourne0312f612016-06-25 00:23:04 +0000411 // This map keeps track of the number of "unsafe" uses of a loaded function
412 // pointer. The key is the associated llvm.type.test intrinsic call generated
413 // by this pass. An unsafe use is one that calls the loaded function pointer
414 // directly. Every time we eliminate an unsafe use (for example, by
415 // devirtualizing it or by applying virtual constant propagation), we
416 // decrement the value stored in this map. If a value reaches zero, we can
417 // eliminate the type check by RAUWing the associated llvm.type.test call with
418 // true.
419 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
420
Peter Collingbourne37317f12017-02-17 18:17:04 +0000421 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
Sam Elliotte963c892017-08-21 16:57:21 +0000422 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000423 ModuleSummaryIndex *ExportSummary,
424 const ModuleSummaryIndex *ImportSummary)
425 : M(M), AARGetter(AARGetter), ExportSummary(ExportSummary),
426 ImportSummary(ImportSummary), Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000427 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000428 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000429 Int64Ty(Type::getInt64Ty(M.getContext())),
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000430 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Sam Elliotte963c892017-08-21 16:57:21 +0000431 RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000432 assert(!(ExportSummary && ImportSummary));
433 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000434
435 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000436
Peter Collingbourne0312f612016-06-25 00:23:04 +0000437 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
438 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
439
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000440 void buildTypeIdentifierMap(
441 std::vector<VTableBits> &Bits,
442 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000443 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000444 bool
445 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
446 const std::set<TypeMemberInfo> &TypeMemberInfos,
447 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000448
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000449 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
450 bool &IsExported);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000451 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000452 VTableSlotInfo &SlotInfo,
453 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000454
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000455 bool tryEvaluateFunctionsWithArgs(
456 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000457 ArrayRef<uint64_t> Args);
458
459 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
460 uint64_t TheRetVal);
461 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000462 CallSiteInfo &CSInfo,
463 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000464
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000465 // Returns the global symbol name that is used to export information about the
466 // given vtable slot and list of arguments.
467 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
468 StringRef Name);
469
470 // This function is called during the export phase to create a symbol
471 // definition containing information about the given vtable slot and list of
472 // arguments.
473 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
474 Constant *C);
475
476 // This function is called during the import phase to create a reference to
477 // the symbol definition created during the export phase.
478 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000479 StringRef Name, unsigned AbsWidth = 0);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000480
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000481 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
482 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000483 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000484 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000485 CallSiteInfo &CSInfo,
486 WholeProgramDevirtResolution::ByArg *Res,
487 VTableSlot Slot, ArrayRef<uint64_t> Args);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000488
489 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
490 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000491 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000492 VTableSlotInfo &SlotInfo,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000493 WholeProgramDevirtResolution *Res, VTableSlot Slot);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000494
495 void rebuildGlobal(VTableBits &B);
496
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000497 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
498 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
499
500 // If we were able to eliminate all unsafe uses for a type checked load,
501 // eliminate the associated type tests by replacing them with true.
502 void removeRedundantTypeTests();
503
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000504 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000505
506 // Lower the module using the action and summary passed as command line
507 // arguments. For testing purposes only.
Sam Elliotte963c892017-08-21 16:57:21 +0000508 static bool runForTesting(
509 Module &M, function_ref<AAResults &(Function &)> AARGetter,
510 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000511};
512
513struct WholeProgramDevirt : public ModulePass {
514 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000515
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000516 bool UseCommandLine = false;
517
Peter Collingbournef7691d82017-03-22 18:22:59 +0000518 ModuleSummaryIndex *ExportSummary;
519 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000520
521 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
522 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
523 }
524
Peter Collingbournef7691d82017-03-22 18:22:59 +0000525 WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
526 const ModuleSummaryIndex *ImportSummary)
527 : ModulePass(ID), ExportSummary(ExportSummary),
528 ImportSummary(ImportSummary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000529 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
530 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000531
532 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000533 if (skipModule(M))
534 return false;
Sam Elliotte963c892017-08-21 16:57:21 +0000535
536 auto OREGetter = function_ref<OptimizationRemarkEmitter &(Function *)>();
537
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000538 if (UseCommandLine)
Sam Elliotte963c892017-08-21 16:57:21 +0000539 return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter);
540
541 return DevirtModule(M, LegacyAARGetter(*this), OREGetter, ExportSummary,
542 ImportSummary)
Peter Collingbournef7691d82017-03-22 18:22:59 +0000543 .run();
Peter Collingbourne37317f12017-02-17 18:17:04 +0000544 }
545
546 void getAnalysisUsage(AnalysisUsage &AU) const override {
547 AU.addRequired<AssumptionCacheTracker>();
548 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000549 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000550};
551
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000552} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000553
Peter Collingbourne37317f12017-02-17 18:17:04 +0000554INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
555 "Whole program devirtualization", false, false)
556INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
557INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
558INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
559 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000560char WholeProgramDevirt::ID = 0;
561
Peter Collingbournef7691d82017-03-22 18:22:59 +0000562ModulePass *
563llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
564 const ModuleSummaryIndex *ImportSummary) {
565 return new WholeProgramDevirt(ExportSummary, ImportSummary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000566}
567
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000568PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000569 ModuleAnalysisManager &AM) {
570 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
571 auto AARGetter = [&](Function &F) -> AAResults & {
572 return FAM.getResult<AAManager>(F);
573 };
Sam Elliotte963c892017-08-21 16:57:21 +0000574 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
575 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
576 };
577 if (!DevirtModule(M, AARGetter, OREGetter, nullptr, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000578 return PreservedAnalyses::all();
579 return PreservedAnalyses::none();
580}
581
Peter Collingbourne37317f12017-02-17 18:17:04 +0000582bool DevirtModule::runForTesting(
Sam Elliotte963c892017-08-21 16:57:21 +0000583 Module &M, function_ref<AAResults &(Function &)> AARGetter,
584 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000585 ModuleSummaryIndex Summary;
586
587 // Handle the command-line summary arguments. This code is for testing
588 // purposes only, so we handle errors directly.
589 if (!ClReadSummary.empty()) {
590 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
591 ": ");
592 auto ReadSummaryFile =
593 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
594
595 yaml::Input In(ReadSummaryFile->getBuffer());
596 In >> Summary;
597 ExitOnErr(errorCodeToError(In.error()));
598 }
599
Peter Collingbournef7691d82017-03-22 18:22:59 +0000600 bool Changed =
601 DevirtModule(
Sam Elliotte963c892017-08-21 16:57:21 +0000602 M, AARGetter, OREGetter,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000603 ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
604 ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr)
605 .run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000606
607 if (!ClWriteSummary.empty()) {
608 ExitOnError ExitOnErr(
609 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
610 std::error_code EC;
611 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
612 ExitOnErr(errorCodeToError(EC));
613
614 yaml::Output Out(OS);
615 Out << Summary;
616 }
617
618 return Changed;
619}
620
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000621void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000622 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000623 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000624 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000625 Bits.reserve(M.getGlobalList().size());
626 SmallVector<MDNode *, 2> Types;
627 for (GlobalVariable &GV : M.globals()) {
628 Types.clear();
629 GV.getMetadata(LLVMContext::MD_type, Types);
630 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000631 continue;
632
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000633 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000634 if (!BitsPtr) {
635 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000636 Bits.back().GV = &GV;
637 Bits.back().ObjectSize =
638 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000639 BitsPtr = &Bits.back();
640 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000641
642 for (MDNode *Type : Types) {
643 auto TypeID = Type->getOperand(1).get();
644
645 uint64_t Offset =
646 cast<ConstantInt>(
647 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
648 ->getZExtValue();
649
650 TypeIdMap[TypeID].insert({BitsPtr, Offset});
651 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000652 }
653}
654
Peter Collingbourne87867542016-12-09 01:10:11 +0000655Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
656 if (I->getType()->isPointerTy()) {
657 if (Offset == 0)
658 return I;
659 return nullptr;
660 }
661
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000662 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000663
664 if (auto *C = dyn_cast<ConstantStruct>(I)) {
665 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000666 if (Offset >= SL->getSizeInBytes())
667 return nullptr;
668
Peter Collingbourne87867542016-12-09 01:10:11 +0000669 unsigned Op = SL->getElementContainingOffset(Offset);
670 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
671 Offset - SL->getElementOffset(Op));
672 }
673 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000674 ArrayType *VTableTy = C->getType();
675 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
676
Peter Collingbourne87867542016-12-09 01:10:11 +0000677 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000678 if (Op >= C->getNumOperands())
679 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000680
Peter Collingbourne87867542016-12-09 01:10:11 +0000681 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
682 Offset % ElemSize);
683 }
684 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000685}
686
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000687bool DevirtModule::tryFindVirtualCallTargets(
688 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000689 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
690 for (const TypeMemberInfo &TM : TypeMemberInfos) {
691 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000692 return false;
693
Peter Collingbourne87867542016-12-09 01:10:11 +0000694 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
695 TM.Offset + ByteOffset);
696 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000697 return false;
698
Peter Collingbourne87867542016-12-09 01:10:11 +0000699 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000700 if (!Fn)
701 return false;
702
703 // We can disregard __cxa_pure_virtual as a possible call target, as
704 // calls to pure virtuals are UB.
705 if (Fn->getName() == "__cxa_pure_virtual")
706 continue;
707
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000708 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000709 }
710
711 // Give up if we couldn't find any targets.
712 return !TargetsForSlot.empty();
713}
714
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000715void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000716 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000717 auto Apply = [&](CallSiteInfo &CSInfo) {
718 for (auto &&VCallSite : CSInfo.CallSites) {
719 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000720 VCallSite.emitRemark("single-impl", TheFn->getName(), OREGetter);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000721 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
722 TheFn, VCallSite.CS.getCalledValue()->getType()));
723 // This use is no longer unsafe.
724 if (VCallSite.NumUnsafeUses)
725 --*VCallSite.NumUnsafeUses;
726 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000727 if (CSInfo.isExported()) {
728 IsExported = true;
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000729 CSInfo.markDevirt();
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000730 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000731 };
732 Apply(SlotInfo.CSInfo);
733 for (auto &P : SlotInfo.ConstCSInfo)
734 Apply(P.second);
735}
736
Peter Collingbournee2367412017-02-15 02:13:08 +0000737bool DevirtModule::trySingleImplDevirt(
738 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000739 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000740 // See if the program contains a single implementation of this virtual
741 // function.
742 Function *TheFn = TargetsForSlot[0].Fn;
743 for (auto &&Target : TargetsForSlot)
744 if (TheFn != Target.Fn)
745 return false;
746
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000747 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000748 if (RemarksEnabled)
749 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000750
751 bool IsExported = false;
752 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
753 if (!IsExported)
754 return false;
755
756 // If the only implementation has local linkage, we must promote to external
757 // to make it visible to thin LTO objects. We can only get here during the
758 // ThinLTO export phase.
759 if (TheFn->hasLocalLinkage()) {
760 TheFn->setLinkage(GlobalValue::ExternalLinkage);
761 TheFn->setVisibility(GlobalValue::HiddenVisibility);
762 TheFn->setName(TheFn->getName() + "$merged");
763 }
764
765 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
766 Res->SingleImplName = TheFn->getName();
767
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000768 return true;
769}
770
771bool DevirtModule::tryEvaluateFunctionsWithArgs(
772 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000773 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000774 // Evaluate each function and store the result in each target's RetVal
775 // field.
776 for (VirtualCallTarget &Target : TargetsForSlot) {
777 if (Target.Fn->arg_size() != Args.size() + 1)
778 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000779
780 Evaluator Eval(M.getDataLayout(), nullptr);
781 SmallVector<Constant *, 2> EvalArgs;
782 EvalArgs.push_back(
783 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000784 for (unsigned I = 0; I != Args.size(); ++I) {
785 auto *ArgTy = dyn_cast<IntegerType>(
786 Target.Fn->getFunctionType()->getParamType(I + 1));
787 if (!ArgTy)
788 return false;
789 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
790 }
791
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000792 Constant *RetVal;
793 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
794 !isa<ConstantInt>(RetVal))
795 return false;
796 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
797 }
798 return true;
799}
800
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000801void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
802 uint64_t TheRetVal) {
803 for (auto Call : CSInfo.CallSites)
804 Call.replaceAndErase(
Sam Elliotte963c892017-08-21 16:57:21 +0000805 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000806 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000807 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000808}
809
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000810bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000811 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
812 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000813 // Uniform return value optimization. If all functions return the same
814 // constant, replace all calls with that constant.
815 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
816 for (const VirtualCallTarget &Target : TargetsForSlot)
817 if (Target.RetVal != TheRetVal)
818 return false;
819
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000820 if (CSInfo.isExported()) {
821 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
822 Res->Info = TheRetVal;
823 }
824
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000825 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000826 if (RemarksEnabled)
827 for (auto &&Target : TargetsForSlot)
828 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000829 return true;
830}
831
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000832std::string DevirtModule::getGlobalName(VTableSlot Slot,
833 ArrayRef<uint64_t> Args,
834 StringRef Name) {
835 std::string FullName = "__typeid_";
836 raw_string_ostream OS(FullName);
837 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
838 for (uint64_t Arg : Args)
839 OS << '_' << Arg;
840 OS << '_' << Name;
841 return OS.str();
842}
843
844void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
845 StringRef Name, Constant *C) {
846 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
847 getGlobalName(Slot, Args, Name), C, &M);
848 GA->setVisibility(GlobalValue::HiddenVisibility);
849}
850
851Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000852 StringRef Name, unsigned AbsWidth) {
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000853 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
854 auto *GV = dyn_cast<GlobalVariable>(C);
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000855 // We only need to set metadata if the global is newly created, in which
856 // case it would not have hidden visibility.
857 if (!GV || GV->getVisibility() == GlobalValue::HiddenVisibility)
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000858 return C;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000859
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000860 GV->setVisibility(GlobalValue::HiddenVisibility);
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000861 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
862 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
863 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
864 GV->setMetadata(LLVMContext::MD_absolute_symbol,
865 MDNode::get(M.getContext(), {MinC, MaxC}));
866 };
867 if (AbsWidth == IntPtrTy->getBitWidth())
868 SetAbsRange(~0ull, ~0ull); // Full set.
869 else if (AbsWidth)
870 SetAbsRange(0, 1ull << AbsWidth);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000871 return GV;
872}
873
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000874void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
875 bool IsOne,
876 Constant *UniqueMemberAddr) {
877 for (auto &&Call : CSInfo.CallSites) {
878 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +0000879 Value *Cmp =
880 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
881 B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000882 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
Sam Elliotte963c892017-08-21 16:57:21 +0000883 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
884 Cmp);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000885 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000886 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000887}
888
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000889bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000890 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000891 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
892 VTableSlot Slot, ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000893 // IsOne controls whether we look for a 0 or a 1.
894 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000895 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000896 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +0000897 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000898 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000899 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000900 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000901 }
902 }
903
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000904 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000905 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000906 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000907
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000908 Constant *UniqueMemberAddr =
909 ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy);
910 UniqueMemberAddr = ConstantExpr::getGetElementPtr(
911 Int8Ty, UniqueMemberAddr,
912 ConstantInt::get(Int64Ty, UniqueMember->Offset));
913
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000914 if (CSInfo.isExported()) {
915 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
916 Res->Info = IsOne;
917
918 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
919 }
920
921 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000922 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
923 UniqueMemberAddr);
924
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000925 // Update devirtualization statistics for targets.
926 if (RemarksEnabled)
927 for (auto &&Target : TargetsForSlot)
928 Target.WasDevirt = true;
929
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000930 return true;
931 };
932
933 if (BitWidth == 1) {
934 if (tryUniqueRetValOptFor(true))
935 return true;
936 if (tryUniqueRetValOptFor(false))
937 return true;
938 }
939 return false;
940}
941
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000942void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
943 Constant *Byte, Constant *Bit) {
944 for (auto Call : CSInfo.CallSites) {
945 auto *RetType = cast<IntegerType>(Call.CS.getType());
946 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +0000947 Value *Addr =
948 B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000949 if (RetType->getBitWidth() == 1) {
950 Value *Bits = B.CreateLoad(Addr);
951 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
952 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
953 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
Sam Elliotte963c892017-08-21 16:57:21 +0000954 OREGetter, IsBitSet);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000955 } else {
956 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
957 Value *Val = B.CreateLoad(RetType, ValAddr);
Sam Elliotte963c892017-08-21 16:57:21 +0000958 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
959 OREGetter, Val);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000960 }
961 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000962 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000963}
964
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000965bool DevirtModule::tryVirtualConstProp(
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000966 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
967 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000968 // This only works if the function returns an integer.
969 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
970 if (!RetType)
971 return false;
972 unsigned BitWidth = RetType->getBitWidth();
973 if (BitWidth > 64)
974 return false;
975
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000976 // Make sure that each function is defined, does not access memory, takes at
977 // least one argument, does not use its first argument (which we assume is
978 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +0000979 //
980 // Note that we test whether this copy of the function is readnone, rather
981 // than testing function attributes, which must hold for any copy of the
982 // function, even a less optimized version substituted at link time. This is
983 // sound because the virtual constant propagation optimizations effectively
984 // inline all implementations of the virtual function into each call site,
985 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000986 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +0000987 if (Target.Fn->isDeclaration() ||
988 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
989 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000990 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000991 Target.Fn->getReturnType() != RetType)
992 return false;
993 }
994
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000995 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000996 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
997 continue;
998
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000999 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1000 if (Res)
1001 ResByArg = &Res->ResByArg[CSByConstantArg.first];
1002
1003 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001004 continue;
1005
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001006 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1007 ResByArg, Slot, CSByConstantArg.first))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001008 continue;
1009
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001010 // Find an allocation offset in bits in all vtables associated with the
1011 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001012 uint64_t AllocBefore =
1013 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1014 uint64_t AllocAfter =
1015 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1016
1017 // Calculate the total amount of padding needed to store a value at both
1018 // ends of the object.
1019 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1020 for (auto &&Target : TargetsForSlot) {
1021 TotalPaddingBefore += std::max<int64_t>(
1022 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1023 TotalPaddingAfter += std::max<int64_t>(
1024 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1025 }
1026
1027 // If the amount of padding is too large, give up.
1028 // FIXME: do something smarter here.
1029 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1030 continue;
1031
1032 // Calculate the offset to the value as a (possibly negative) byte offset
1033 // and (if applicable) a bit offset, and store the values in the targets.
1034 int64_t OffsetByte;
1035 uint64_t OffsetBit;
1036 if (TotalPaddingBefore <= TotalPaddingAfter)
1037 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1038 OffsetBit);
1039 else
1040 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1041 OffsetBit);
1042
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001043 if (RemarksEnabled)
1044 for (auto &&Target : TargetsForSlot)
1045 Target.WasDevirt = true;
1046
Peter Collingbourne184773d2017-02-17 19:43:45 +00001047 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001048 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001049
1050 if (CSByConstantArg.second.isExported()) {
1051 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
1052 exportGlobal(Slot, CSByConstantArg.first, "byte",
1053 ConstantExpr::getIntToPtr(ByteConst, Int8PtrTy));
1054 exportGlobal(Slot, CSByConstantArg.first, "bit",
1055 ConstantExpr::getIntToPtr(BitConst, Int8PtrTy));
1056 }
1057
1058 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001059 applyVirtualConstProp(CSByConstantArg.second,
1060 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001061 }
1062 return true;
1063}
1064
1065void DevirtModule::rebuildGlobal(VTableBits &B) {
1066 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1067 return;
1068
1069 // Align each byte array to pointer width.
1070 unsigned PointerSize = M.getDataLayout().getPointerSize();
1071 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
1072 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
1073
1074 // Before was stored in reverse order; flip it now.
1075 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1076 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1077
1078 // Build an anonymous global containing the before bytes, followed by the
1079 // original initializer, followed by the after bytes.
1080 auto NewInit = ConstantStruct::getAnon(
1081 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1082 B.GV->getInitializer(),
1083 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1084 auto NewGV =
1085 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1086 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1087 NewGV->setSection(B.GV->getSection());
1088 NewGV->setComdat(B.GV->getComdat());
1089
Peter Collingbourne0312f612016-06-25 00:23:04 +00001090 // Copy the original vtable's metadata to the anonymous global, adjusting
1091 // offsets as required.
1092 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1093
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001094 // Build an alias named after the original global, pointing at the second
1095 // element (the original initializer).
1096 auto Alias = GlobalAlias::create(
1097 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1098 ConstantExpr::getGetElementPtr(
1099 NewInit->getType(), NewGV,
1100 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1101 ConstantInt::get(Int32Ty, 1)}),
1102 &M);
1103 Alias->setVisibility(B.GV->getVisibility());
1104 Alias->takeName(B.GV);
1105
1106 B.GV->replaceAllUsesWith(Alias);
1107 B.GV->eraseFromParent();
1108}
1109
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001110bool DevirtModule::areRemarksEnabled() {
1111 const auto &FL = M.getFunctionList();
1112 if (FL.empty())
1113 return false;
1114 const Function &Fn = FL.front();
Adam Nemetde53bfb2017-02-23 23:11:11 +00001115
1116 const auto &BBL = Fn.getBasicBlockList();
1117 if (BBL.empty())
1118 return false;
1119 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001120 return DI.isEnabled();
1121}
1122
Peter Collingbourne0312f612016-06-25 00:23:04 +00001123void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
1124 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001125 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001126 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1127 // points to a member of the type identifier %md. Group calls by (type ID,
1128 // offset) pair (effectively the identity of the virtual function) and store
1129 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001130 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001131 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001132 I != E;) {
1133 auto CI = dyn_cast<CallInst>(I->getUser());
1134 ++I;
1135 if (!CI)
1136 continue;
1137
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001138 // Search for virtual calls based on %p and add them to DevirtCalls.
1139 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001140 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +00001141 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001142
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001143 // If we found any, add them to CallSlots. Only do this if we haven't seen
1144 // the vtable pointer before, as it may have been CSE'd with pointers from
1145 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001146 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001147 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001148 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1149 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001150 if (SeenPtrs.insert(Ptr).second) {
1151 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne001052a2017-08-22 21:41:19 +00001152 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001153 }
1154 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001155 }
1156
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001157 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001158 for (auto Assume : Assumes)
1159 Assume->eraseFromParent();
1160 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1161 // may use the vtable argument later.
1162 if (CI->use_empty())
1163 CI->eraseFromParent();
1164 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001165}
1166
1167void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1168 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1169
1170 for (auto I = TypeCheckedLoadFunc->use_begin(),
1171 E = TypeCheckedLoadFunc->use_end();
1172 I != E;) {
1173 auto CI = dyn_cast<CallInst>(I->getUser());
1174 ++I;
1175 if (!CI)
1176 continue;
1177
1178 Value *Ptr = CI->getArgOperand(0);
1179 Value *Offset = CI->getArgOperand(1);
1180 Value *TypeIdValue = CI->getArgOperand(2);
1181 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1182
1183 SmallVector<DevirtCallSite, 1> DevirtCalls;
1184 SmallVector<Instruction *, 1> LoadedPtrs;
1185 SmallVector<Instruction *, 1> Preds;
1186 bool HasNonCallUses = false;
1187 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1188 HasNonCallUses, CI);
1189
1190 // Start by generating "pessimistic" code that explicitly loads the function
1191 // pointer from the vtable and performs the type check. If possible, we will
1192 // eliminate the load and the type check later.
1193
1194 // If possible, only generate the load at the point where it is used.
1195 // This helps avoid unnecessary spills.
1196 IRBuilder<> LoadB(
1197 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1198 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1199 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1200 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1201
1202 for (Instruction *LoadedPtr : LoadedPtrs) {
1203 LoadedPtr->replaceAllUsesWith(LoadedValue);
1204 LoadedPtr->eraseFromParent();
1205 }
1206
1207 // Likewise for the type test.
1208 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1209 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1210
1211 for (Instruction *Pred : Preds) {
1212 Pred->replaceAllUsesWith(TypeTestCall);
1213 Pred->eraseFromParent();
1214 }
1215
1216 // We have already erased any extractvalue instructions that refer to the
1217 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1218 // (although this is unlikely). In that case, explicitly build a pair and
1219 // RAUW it.
1220 if (!CI->use_empty()) {
1221 Value *Pair = UndefValue::get(CI->getType());
1222 IRBuilder<> B(CI);
1223 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1224 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1225 CI->replaceAllUsesWith(Pair);
1226 }
1227
1228 // The number of unsafe uses is initially the number of uses.
1229 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1230 NumUnsafeUses = DevirtCalls.size();
1231
1232 // If the function pointer has a non-call user, we cannot eliminate the type
1233 // check, as one of those users may eventually call the pointer. Increment
1234 // the unsafe use count to make sure it cannot reach zero.
1235 if (HasNonCallUses)
1236 ++NumUnsafeUses;
1237 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001238 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1239 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001240 }
1241
1242 CI->eraseFromParent();
1243 }
1244}
1245
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001246void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001247 const TypeIdSummary *TidSummary =
Peter Collingbournef7691d82017-03-22 18:22:59 +00001248 ImportSummary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString());
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001249 if (!TidSummary)
1250 return;
1251 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1252 if (ResI == TidSummary->WPDRes.end())
1253 return;
1254 const WholeProgramDevirtResolution &Res = ResI->second;
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001255
1256 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1257 // The type of the function in the declaration is irrelevant because every
1258 // call site will cast it to the correct type.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001259 auto *SingleImpl = M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001260 Res.SingleImplName, Type::getVoidTy(M.getContext()));
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001261
1262 // This is the import phase so we should not be exporting anything.
1263 bool IsExported = false;
1264 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1265 assert(!IsExported);
1266 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001267
1268 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1269 auto I = Res.ResByArg.find(CSByConstantArg.first);
1270 if (I == Res.ResByArg.end())
1271 continue;
1272 auto &ResByArg = I->second;
1273 // FIXME: We should figure out what to do about the "function name" argument
1274 // to the apply* functions, as the function names are unavailable during the
1275 // importing phase. For now we just pass the empty string. This does not
1276 // impact correctness because the function names are just used for remarks.
1277 switch (ResByArg.TheKind) {
1278 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1279 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1280 break;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001281 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1282 Constant *UniqueMemberAddr =
1283 importGlobal(Slot, CSByConstantArg.first, "unique_member");
1284 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1285 UniqueMemberAddr);
1286 break;
1287 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001288 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
1289 Constant *Byte = importGlobal(Slot, CSByConstantArg.first, "byte", 32);
1290 Byte = ConstantExpr::getPtrToInt(Byte, Int32Ty);
1291 Constant *Bit = importGlobal(Slot, CSByConstantArg.first, "bit", 8);
1292 Bit = ConstantExpr::getPtrToInt(Bit, Int8Ty);
1293 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
1294 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001295 default:
1296 break;
1297 }
1298 }
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001299}
1300
1301void DevirtModule::removeRedundantTypeTests() {
1302 auto True = ConstantInt::getTrue(M.getContext());
1303 for (auto &&U : NumUnsafeUsesForTypeTest) {
1304 if (U.second == 0) {
1305 U.first->replaceAllUsesWith(True);
1306 U.first->eraseFromParent();
1307 }
1308 }
1309}
1310
Peter Collingbourne0312f612016-06-25 00:23:04 +00001311bool DevirtModule::run() {
1312 Function *TypeTestFunc =
1313 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1314 Function *TypeCheckedLoadFunc =
1315 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1316 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1317
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001318 // Normally if there are no users of the devirtualization intrinsics in the
1319 // module, this pass has nothing to do. But if we are exporting, we also need
1320 // to handle any users that appear only in the function summaries.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001321 if (!ExportSummary &&
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001322 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001323 AssumeFunc->use_empty()) &&
1324 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1325 return false;
1326
1327 if (TypeTestFunc && AssumeFunc)
1328 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1329
1330 if (TypeCheckedLoadFunc)
1331 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001332
Peter Collingbournef7691d82017-03-22 18:22:59 +00001333 if (ImportSummary) {
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001334 for (auto &S : CallSlots)
1335 importResolution(S.first, S.second);
1336
1337 removeRedundantTypeTests();
1338
1339 // The rest of the code is only necessary when exporting or during regular
1340 // LTO, so we are done.
1341 return true;
1342 }
1343
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001344 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001345 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001346 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1347 buildTypeIdentifierMap(Bits, TypeIdMap);
1348 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001349 return true;
1350
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001351 // Collect information from summary about which calls to try to devirtualize.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001352 if (ExportSummary) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001353 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1354 for (auto &P : TypeIdMap) {
1355 if (auto *TypeId = dyn_cast<MDString>(P.first))
1356 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1357 TypeId);
1358 }
1359
Peter Collingbournef7691d82017-03-22 18:22:59 +00001360 for (auto &P : *ExportSummary) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001361 for (auto &S : P.second.SummaryList) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001362 auto *FS = dyn_cast<FunctionSummary>(S.get());
1363 if (!FS)
1364 continue;
1365 // FIXME: Only add live functions.
George Rimar5d8aea12017-03-10 10:31:56 +00001366 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1367 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001368 CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers =
1369 true;
George Rimar5d8aea12017-03-10 10:31:56 +00001370 }
1371 }
1372 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1373 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001374 CallSlots[{MD, VF.Offset}]
1375 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001376 }
1377 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001378 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001379 FS->type_test_assume_const_vcalls()) {
1380 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001381 CallSlots[{MD, VC.VFunc.Offset}]
George Rimar5d8aea12017-03-10 10:31:56 +00001382 .ConstCSInfo[VC.Args]
1383 .SummaryHasTypeTestAssumeUsers = true;
1384 }
1385 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001386 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001387 FS->type_checked_load_const_vcalls()) {
1388 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001389 CallSlots[{MD, VC.VFunc.Offset}]
1390 .ConstCSInfo[VC.Args]
1391 .SummaryTypeCheckedLoadUsers.push_back(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001392 }
1393 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001394 }
1395 }
1396 }
1397
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001398 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001399 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001400 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001401 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001402 // Search each of the members of the type identifier for the virtual
1403 // function implementation at offset S.first.ByteOffset, and add to
1404 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001405 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001406 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1407 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001408 WholeProgramDevirtResolution *Res = nullptr;
Peter Collingbournef7691d82017-03-22 18:22:59 +00001409 if (ExportSummary && isa<MDString>(S.first.TypeID))
1410 Res = &ExportSummary
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001411 ->getOrInsertTypeIdSummary(
1412 cast<MDString>(S.first.TypeID)->getString())
1413 .WPDRes[S.first.ByteOffset];
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001414
1415 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) &&
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001416 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first))
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001417 DidVirtualConstProp = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001418
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001419 // Collect functions devirtualized at least for one call site for stats.
1420 if (RemarksEnabled)
1421 for (const auto &T : TargetsForSlot)
1422 if (T.WasDevirt)
1423 DevirtTargets[T.Fn->getName()] = T.Fn;
1424 }
1425
1426 // CFI-specific: if we are exporting and any llvm.type.checked.load
1427 // intrinsics were *not* devirtualized, we need to add the resulting
1428 // llvm.type.test intrinsics to the function summaries so that the
1429 // LowerTypeTests pass will export them.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001430 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001431 auto GUID =
1432 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1433 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1434 FS->addTypeTest(GUID);
1435 for (auto &CCS : S.second.ConstCSInfo)
1436 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1437 FS->addTypeTest(GUID);
1438 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001439 }
1440
1441 if (RemarksEnabled) {
1442 // Generate remarks for each devirtualized function.
1443 for (const auto &DT : DevirtTargets) {
1444 Function *F = DT.second;
Sam Elliotte963c892017-08-21 16:57:21 +00001445
1446 // In the new pass manager, we can request the optimization
1447 // remark emitter pass on a per-function-basis, which the
1448 // OREGetter will do for us.
1449 // In the old pass manager, this is harder, so we just build
1450 // a optimization remark emitter on the fly, when we need it.
1451 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1452 OptimizationRemarkEmitter *ORE;
1453 if (OREGetter)
1454 ORE = &OREGetter(F);
1455 else {
1456 OwnedORE = make_unique<OptimizationRemarkEmitter>(F);
1457 ORE = OwnedORE.get();
1458 }
1459
1460 using namespace ore;
1461 ORE->emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
1462 << "devirtualized " << NV("FunctionName", F->getName()));
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001463 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001464 }
1465
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001466 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00001467
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001468 // Rebuild each global we touched as part of virtual constant propagation to
1469 // include the before and after bytes.
1470 if (DidVirtualConstProp)
1471 for (VTableBits &B : Bits)
1472 rebuildGlobal(B);
1473
1474 return true;
1475}