blob: 2f75c6b66143d492c1236fe2affc0210bf87d0c6 [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"
Adam Nemet0965da22017-10-09 23:19:02 +000054#include "llvm/Analysis/OptimizationRemarkEmitter.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"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000059#include "llvm/IR/DebugLoc.h"
60#include "llvm/IR/DerivedTypes.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000061#include "llvm/IR/Function.h"
62#include "llvm/IR/GlobalAlias.h"
63#include "llvm/IR/GlobalVariable.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000064#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000065#include "llvm/IR/InstrTypes.h"
66#include "llvm/IR/Instruction.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000067#include "llvm/IR/Instructions.h"
68#include "llvm/IR/Intrinsics.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000069#include "llvm/IR/LLVMContext.h"
70#include "llvm/IR/Metadata.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000071#include "llvm/IR/Module.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000072#include "llvm/IR/ModuleSummaryIndexYAML.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000073#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000074#include "llvm/PassRegistry.h"
75#include "llvm/PassSupport.h"
76#include "llvm/Support/Casting.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000077#include "llvm/Support/Error.h"
78#include "llvm/Support/FileSystem.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000079#include "llvm/Support/MathExtras.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000080#include "llvm/Transforms/IPO.h"
Peter Collingbourne37317f12017-02-17 18:17:04 +000081#include "llvm/Transforms/IPO/FunctionAttrs.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000082#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000083#include <algorithm>
84#include <cstddef>
85#include <map>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000086#include <set>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000087#include <string>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000088
89using namespace llvm;
90using namespace wholeprogramdevirt;
91
92#define DEBUG_TYPE "wholeprogramdevirt"
93
Peter Collingbourne2b33f652017-02-13 19:26:18 +000094static cl::opt<PassSummaryAction> ClSummaryAction(
95 "wholeprogramdevirt-summary-action",
96 cl::desc("What to do with the summary when running this pass"),
97 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
98 clEnumValN(PassSummaryAction::Import, "import",
99 "Import typeid resolutions from summary and globals"),
100 clEnumValN(PassSummaryAction::Export, "export",
101 "Export typeid resolutions to summary and globals")),
102 cl::Hidden);
103
104static cl::opt<std::string> ClReadSummary(
105 "wholeprogramdevirt-read-summary",
106 cl::desc("Read summary from given YAML file before running pass"),
107 cl::Hidden);
108
109static cl::opt<std::string> ClWriteSummary(
110 "wholeprogramdevirt-write-summary",
111 cl::desc("Write summary to given YAML file after running pass"),
112 cl::Hidden);
113
Vitaly Buka9cb59b92018-04-06 21:41:17 +0000114static cl::opt<unsigned>
115 ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden,
116 cl::init(10), cl::ZeroOrMore,
117 cl::desc("Maximum number of call targets per "
118 "call site to enable branch funnels"));
Vitaly Buka66f53d72018-04-06 21:32:36 +0000119
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000120// Find the minimum offset that we may store a value of size Size bits at. If
121// IsAfter is set, look for an offset before the object, otherwise look for an
122// offset after the object.
123uint64_t
124wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
125 bool IsAfter, uint64_t Size) {
126 // Find a minimum offset taking into account only vtable sizes.
127 uint64_t MinByte = 0;
128 for (const VirtualCallTarget &Target : Targets) {
129 if (IsAfter)
130 MinByte = std::max(MinByte, Target.minAfterBytes());
131 else
132 MinByte = std::max(MinByte, Target.minBeforeBytes());
133 }
134
135 // Build a vector of arrays of bytes covering, for each target, a slice of the
136 // used region (see AccumBitVector::BytesUsed in
137 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
138 // this aligns the used regions to start at MinByte.
139 //
140 // In this example, A, B and C are vtables, # is a byte already allocated for
141 // a virtual function pointer, AAAA... (etc.) are the used regions for the
142 // vtables and Offset(X) is the value computed for the Offset variable below
143 // for X.
144 //
145 // Offset(A)
146 // | |
147 // |MinByte
148 // A: ################AAAAAAAA|AAAAAAAA
149 // B: ########BBBBBBBBBBBBBBBB|BBBB
150 // C: ########################|CCCCCCCCCCCCCCCC
151 // | Offset(B) |
152 //
153 // This code produces the slices of A, B and C that appear after the divider
154 // at MinByte.
155 std::vector<ArrayRef<uint8_t>> Used;
156 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000157 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
158 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000159 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
160 : MinByte - Target.minBeforeBytes();
161
162 // Disregard used regions that are smaller than Offset. These are
163 // effectively all-free regions that do not need to be checked.
164 if (VTUsed.size() > Offset)
165 Used.push_back(VTUsed.slice(Offset));
166 }
167
168 if (Size == 1) {
169 // Find a free bit in each member of Used.
170 for (unsigned I = 0;; ++I) {
171 uint8_t BitsUsed = 0;
172 for (auto &&B : Used)
173 if (I < B.size())
174 BitsUsed |= B[I];
175 if (BitsUsed != 0xff)
176 return (MinByte + I) * 8 +
177 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
178 }
179 } else {
180 // Find a free (Size/8) byte region in each member of Used.
181 // FIXME: see if alignment helps.
182 for (unsigned I = 0;; ++I) {
183 for (auto &&B : Used) {
184 unsigned Byte = 0;
185 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
186 if (B[I + Byte])
187 goto NextI;
188 ++Byte;
189 }
190 }
191 return (MinByte + I) * 8;
192 NextI:;
193 }
194 }
195}
196
197void wholeprogramdevirt::setBeforeReturnValues(
198 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
199 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
200 if (BitWidth == 1)
201 OffsetByte = -(AllocBefore / 8 + 1);
202 else
203 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
204 OffsetBit = AllocBefore % 8;
205
206 for (VirtualCallTarget &Target : Targets) {
207 if (BitWidth == 1)
208 Target.setBeforeBit(AllocBefore);
209 else
210 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
211 }
212}
213
214void wholeprogramdevirt::setAfterReturnValues(
215 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
216 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
217 if (BitWidth == 1)
218 OffsetByte = AllocAfter / 8;
219 else
220 OffsetByte = (AllocAfter + 7) / 8;
221 OffsetBit = AllocAfter % 8;
222
223 for (VirtualCallTarget &Target : Targets) {
224 if (BitWidth == 1)
225 Target.setAfterBit(AllocAfter);
226 else
227 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
228 }
229}
230
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000231VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
232 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000233 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000234
235namespace {
236
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000237// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000238// tables, and the ByteOffset is the offset in bytes from the address point to
239// the virtual function pointer.
240struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000241 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000242 uint64_t ByteOffset;
243};
244
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000245} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000246
Peter Collingbourne9b656522016-02-09 23:01:38 +0000247namespace llvm {
248
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000249template <> struct DenseMapInfo<VTableSlot> {
250 static VTableSlot getEmptyKey() {
251 return {DenseMapInfo<Metadata *>::getEmptyKey(),
252 DenseMapInfo<uint64_t>::getEmptyKey()};
253 }
254 static VTableSlot getTombstoneKey() {
255 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
256 DenseMapInfo<uint64_t>::getTombstoneKey()};
257 }
258 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000259 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000260 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
261 }
262 static bool isEqual(const VTableSlot &LHS,
263 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000264 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000265 }
266};
267
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000268} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000269
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000270namespace {
271
272// A virtual call site. VTable is the loaded virtual table pointer, and CS is
273// the indirect virtual call.
274struct VirtualCallSite {
275 Value *VTable;
276 CallSite CS;
277
Peter Collingbourne0312f612016-06-25 00:23:04 +0000278 // If non-null, this field points to the associated unsafe use count stored in
279 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
280 // of that field for details.
281 unsigned *NumUnsafeUses;
282
Sam Elliotte963c892017-08-21 16:57:21 +0000283 void
284 emitRemark(const StringRef OptName, const StringRef TargetName,
285 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Ivan Krasin54746452016-07-12 02:38:37 +0000286 Function *F = CS.getCaller();
Sam Elliotte963c892017-08-21 16:57:21 +0000287 DebugLoc DLoc = CS->getDebugLoc();
288 BasicBlock *Block = CS.getParent();
289
Sam Elliotte963c892017-08-21 16:57:21 +0000290 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000291 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
292 << NV("Optimization", OptName)
293 << ": devirtualized a call to "
294 << NV("FunctionName", TargetName));
Ivan Krasin54746452016-07-12 02:38:37 +0000295 }
296
Sam Elliotte963c892017-08-21 16:57:21 +0000297 void replaceAndErase(
298 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
299 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
300 Value *New) {
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000301 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000302 emitRemark(OptName, TargetName, OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000303 CS->replaceAllUsesWith(New);
304 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
305 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
306 II->getUnwindDest()->removePredecessor(II->getParent());
307 }
308 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000309 // This use is no longer unsafe.
310 if (NumUnsafeUses)
311 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000312 }
313};
314
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000315// Call site information collected for a specific VTableSlot and possibly a list
316// of constant integer arguments. The grouping by arguments is handled by the
317// VTableSlotInfo class.
318struct CallSiteInfo {
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000319 /// The set of call sites for this slot. Used during regular LTO and the
320 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
321 /// call sites that appear in the merged module itself); in each of these
322 /// cases we are directly operating on the call sites at the IR level.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000323 std::vector<VirtualCallSite> CallSites;
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000324
Peter Collingbourne29748562018-03-09 19:11:44 +0000325 /// Whether all call sites represented by this CallSiteInfo, including those
326 /// in summaries, have been devirtualized. This starts off as true because a
327 /// default constructed CallSiteInfo represents no call sites.
328 bool AllCallSitesDevirted = true;
329
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000330 // These fields are used during the export phase of ThinLTO and reflect
331 // information collected from function summaries.
332
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000333 /// Whether any function summary contains an llvm.assume(llvm.type.test) for
334 /// this slot.
Peter Collingbourne29748562018-03-09 19:11:44 +0000335 bool SummaryHasTypeTestAssumeUsers = false;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000336
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000337 /// CFI-specific: a vector containing the list of function summaries that use
338 /// the llvm.type.checked.load intrinsic and therefore will require
339 /// resolutions for llvm.type.test in order to implement CFI checks if
340 /// devirtualization was unsuccessful. If devirtualization was successful, the
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000341 /// pass will clear this vector by calling markDevirt(). If at the end of the
342 /// pass the vector is non-empty, we will need to add a use of llvm.type.test
343 /// to each of the function summaries in the vector.
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000344 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000345
346 bool isExported() const {
347 return SummaryHasTypeTestAssumeUsers ||
348 !SummaryTypeCheckedLoadUsers.empty();
349 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000350
Peter Collingbourne29748562018-03-09 19:11:44 +0000351 void markSummaryHasTypeTestAssumeUsers() {
352 SummaryHasTypeTestAssumeUsers = true;
353 AllCallSitesDevirted = false;
354 }
355
356 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
357 SummaryTypeCheckedLoadUsers.push_back(FS);
358 AllCallSitesDevirted = false;
359 }
360
361 void markDevirt() {
362 AllCallSitesDevirted = true;
363
364 // As explained in the comment for SummaryTypeCheckedLoadUsers.
365 SummaryTypeCheckedLoadUsers.clear();
366 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000367};
368
369// Call site information collected for a specific VTableSlot.
370struct VTableSlotInfo {
371 // The set of call sites which do not have all constant integer arguments
372 // (excluding "this").
373 CallSiteInfo CSInfo;
374
375 // The set of call sites with all constant integer arguments (excluding
376 // "this"), grouped by argument list.
377 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
378
379 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
380
381private:
382 CallSiteInfo &findCallSiteInfo(CallSite CS);
383};
384
385CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
386 std::vector<uint64_t> Args;
387 auto *CI = dyn_cast<IntegerType>(CS.getType());
388 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
389 return CSInfo;
390 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
391 auto *CI = dyn_cast<ConstantInt>(Arg);
392 if (!CI || CI->getBitWidth() > 64)
393 return CSInfo;
394 Args.push_back(CI->getZExtValue());
395 }
396 return ConstCSInfo[Args];
397}
398
399void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
400 unsigned *NumUnsafeUses) {
Peter Collingbourne29748562018-03-09 19:11:44 +0000401 auto &CSI = findCallSiteInfo(CS);
402 CSI.AllCallSitesDevirted = false;
403 CSI.CallSites.push_back({VTable, CS, NumUnsafeUses});
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000404}
405
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000406struct DevirtModule {
407 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000408 function_ref<AAResults &(Function &)> AARGetter;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000409
Peter Collingbournef7691d82017-03-22 18:22:59 +0000410 ModuleSummaryIndex *ExportSummary;
411 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000412
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000413 IntegerType *Int8Ty;
414 PointerType *Int8PtrTy;
415 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000416 IntegerType *Int64Ty;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000417 IntegerType *IntPtrTy;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000418
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000419 bool RemarksEnabled;
Sam Elliotte963c892017-08-21 16:57:21 +0000420 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000421
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000422 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000423
Peter Collingbourne0312f612016-06-25 00:23:04 +0000424 // This map keeps track of the number of "unsafe" uses of a loaded function
425 // pointer. The key is the associated llvm.type.test intrinsic call generated
426 // by this pass. An unsafe use is one that calls the loaded function pointer
427 // directly. Every time we eliminate an unsafe use (for example, by
428 // devirtualizing it or by applying virtual constant propagation), we
429 // decrement the value stored in this map. If a value reaches zero, we can
430 // eliminate the type check by RAUWing the associated llvm.type.test call with
431 // true.
432 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
433
Peter Collingbourne37317f12017-02-17 18:17:04 +0000434 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
Sam Elliotte963c892017-08-21 16:57:21 +0000435 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000436 ModuleSummaryIndex *ExportSummary,
437 const ModuleSummaryIndex *ImportSummary)
438 : M(M), AARGetter(AARGetter), ExportSummary(ExportSummary),
439 ImportSummary(ImportSummary), Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000440 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000441 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000442 Int64Ty(Type::getInt64Ty(M.getContext())),
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000443 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Sam Elliotte963c892017-08-21 16:57:21 +0000444 RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000445 assert(!(ExportSummary && ImportSummary));
446 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000447
448 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000449
Peter Collingbourne0312f612016-06-25 00:23:04 +0000450 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
451 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
452
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000453 void buildTypeIdentifierMap(
454 std::vector<VTableBits> &Bits,
455 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000456 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000457 bool
458 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
459 const std::set<TypeMemberInfo> &TypeMemberInfos,
460 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000461
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000462 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
463 bool &IsExported);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000464 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000465 VTableSlotInfo &SlotInfo,
466 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000467
Peter Collingbourne29748562018-03-09 19:11:44 +0000468 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT,
469 bool &IsExported);
470 void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
471 VTableSlotInfo &SlotInfo,
472 WholeProgramDevirtResolution *Res, VTableSlot Slot);
473
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000474 bool tryEvaluateFunctionsWithArgs(
475 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000476 ArrayRef<uint64_t> Args);
477
478 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
479 uint64_t TheRetVal);
480 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000481 CallSiteInfo &CSInfo,
482 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000483
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000484 // Returns the global symbol name that is used to export information about the
485 // given vtable slot and list of arguments.
486 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
487 StringRef Name);
488
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000489 bool shouldExportConstantsAsAbsoluteSymbols();
490
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000491 // This function is called during the export phase to create a symbol
492 // definition containing information about the given vtable slot and list of
493 // arguments.
494 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
495 Constant *C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000496 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
497 uint32_t Const, uint32_t &Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000498
499 // This function is called during the import phase to create a reference to
500 // the symbol definition created during the export phase.
501 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000502 StringRef Name);
503 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
504 StringRef Name, IntegerType *IntTy,
505 uint32_t Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000506
Peter Collingbourne29748562018-03-09 19:11:44 +0000507 Constant *getMemberAddr(const TypeMemberInfo *M);
508
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000509 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
510 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000511 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000512 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000513 CallSiteInfo &CSInfo,
514 WholeProgramDevirtResolution::ByArg *Res,
515 VTableSlot Slot, ArrayRef<uint64_t> Args);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000516
517 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
518 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000519 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000520 VTableSlotInfo &SlotInfo,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000521 WholeProgramDevirtResolution *Res, VTableSlot Slot);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000522
523 void rebuildGlobal(VTableBits &B);
524
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000525 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
526 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
527
528 // If we were able to eliminate all unsafe uses for a type checked load,
529 // eliminate the associated type tests by replacing them with true.
530 void removeRedundantTypeTests();
531
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000532 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000533
534 // Lower the module using the action and summary passed as command line
535 // arguments. For testing purposes only.
Sam Elliotte963c892017-08-21 16:57:21 +0000536 static bool runForTesting(
537 Module &M, function_ref<AAResults &(Function &)> AARGetter,
538 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000539};
540
541struct WholeProgramDevirt : public ModulePass {
542 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000543
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000544 bool UseCommandLine = false;
545
Peter Collingbournef7691d82017-03-22 18:22:59 +0000546 ModuleSummaryIndex *ExportSummary;
547 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000548
549 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
550 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
551 }
552
Peter Collingbournef7691d82017-03-22 18:22:59 +0000553 WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
554 const ModuleSummaryIndex *ImportSummary)
555 : ModulePass(ID), ExportSummary(ExportSummary),
556 ImportSummary(ImportSummary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000557 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
558 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000559
560 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000561 if (skipModule(M))
562 return false;
Sam Elliotte963c892017-08-21 16:57:21 +0000563
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000564 // In the new pass manager, we can request the optimization
565 // remark emitter pass on a per-function-basis, which the
566 // OREGetter will do for us.
567 // In the old pass manager, this is harder, so we just build
568 // an optimization remark emitter on the fly, when we need it.
569 std::unique_ptr<OptimizationRemarkEmitter> ORE;
570 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
571 ORE = make_unique<OptimizationRemarkEmitter>(F);
572 return *ORE;
573 };
Sam Elliotte963c892017-08-21 16:57:21 +0000574
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000575 if (UseCommandLine)
Sam Elliotte963c892017-08-21 16:57:21 +0000576 return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter);
577
578 return DevirtModule(M, LegacyAARGetter(*this), OREGetter, ExportSummary,
579 ImportSummary)
Peter Collingbournef7691d82017-03-22 18:22:59 +0000580 .run();
Peter Collingbourne37317f12017-02-17 18:17:04 +0000581 }
582
583 void getAnalysisUsage(AnalysisUsage &AU) const override {
584 AU.addRequired<AssumptionCacheTracker>();
585 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000586 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000587};
588
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000589} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000590
Peter Collingbourne37317f12017-02-17 18:17:04 +0000591INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
592 "Whole program devirtualization", false, false)
593INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
594INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
595INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
596 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000597char WholeProgramDevirt::ID = 0;
598
Peter Collingbournef7691d82017-03-22 18:22:59 +0000599ModulePass *
600llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
601 const ModuleSummaryIndex *ImportSummary) {
602 return new WholeProgramDevirt(ExportSummary, ImportSummary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000603}
604
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000605PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000606 ModuleAnalysisManager &AM) {
607 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
608 auto AARGetter = [&](Function &F) -> AAResults & {
609 return FAM.getResult<AAManager>(F);
610 };
Sam Elliotte963c892017-08-21 16:57:21 +0000611 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
612 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
613 };
Teresa Johnson28023db2018-07-19 14:51:32 +0000614 if (!DevirtModule(M, AARGetter, OREGetter, ExportSummary, ImportSummary)
615 .run())
Davide Italianod737dd22016-06-14 21:44:19 +0000616 return PreservedAnalyses::all();
617 return PreservedAnalyses::none();
618}
619
Peter Collingbourne37317f12017-02-17 18:17:04 +0000620bool DevirtModule::runForTesting(
Sam Elliotte963c892017-08-21 16:57:21 +0000621 Module &M, function_ref<AAResults &(Function &)> AARGetter,
622 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000623 ModuleSummaryIndex Summary(/*HaveGVs=*/false);
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000624
625 // Handle the command-line summary arguments. This code is for testing
626 // purposes only, so we handle errors directly.
627 if (!ClReadSummary.empty()) {
628 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
629 ": ");
630 auto ReadSummaryFile =
631 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
632
633 yaml::Input In(ReadSummaryFile->getBuffer());
634 In >> Summary;
635 ExitOnErr(errorCodeToError(In.error()));
636 }
637
Peter Collingbournef7691d82017-03-22 18:22:59 +0000638 bool Changed =
639 DevirtModule(
Sam Elliotte963c892017-08-21 16:57:21 +0000640 M, AARGetter, OREGetter,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000641 ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
642 ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr)
643 .run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000644
645 if (!ClWriteSummary.empty()) {
646 ExitOnError ExitOnErr(
647 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
648 std::error_code EC;
649 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
650 ExitOnErr(errorCodeToError(EC));
651
652 yaml::Output Out(OS);
653 Out << Summary;
654 }
655
656 return Changed;
657}
658
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000659void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000660 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000661 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000662 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000663 Bits.reserve(M.getGlobalList().size());
664 SmallVector<MDNode *, 2> Types;
665 for (GlobalVariable &GV : M.globals()) {
666 Types.clear();
667 GV.getMetadata(LLVMContext::MD_type, Types);
668 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000669 continue;
670
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000671 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000672 if (!BitsPtr) {
673 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000674 Bits.back().GV = &GV;
675 Bits.back().ObjectSize =
676 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000677 BitsPtr = &Bits.back();
678 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000679
680 for (MDNode *Type : Types) {
681 auto TypeID = Type->getOperand(1).get();
682
683 uint64_t Offset =
684 cast<ConstantInt>(
685 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
686 ->getZExtValue();
687
688 TypeIdMap[TypeID].insert({BitsPtr, Offset});
689 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000690 }
691}
692
Peter Collingbourne87867542016-12-09 01:10:11 +0000693Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
694 if (I->getType()->isPointerTy()) {
695 if (Offset == 0)
696 return I;
697 return nullptr;
698 }
699
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000700 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000701
702 if (auto *C = dyn_cast<ConstantStruct>(I)) {
703 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000704 if (Offset >= SL->getSizeInBytes())
705 return nullptr;
706
Peter Collingbourne87867542016-12-09 01:10:11 +0000707 unsigned Op = SL->getElementContainingOffset(Offset);
708 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
709 Offset - SL->getElementOffset(Op));
710 }
711 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000712 ArrayType *VTableTy = C->getType();
713 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
714
Peter Collingbourne87867542016-12-09 01:10:11 +0000715 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000716 if (Op >= C->getNumOperands())
717 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000718
Peter Collingbourne87867542016-12-09 01:10:11 +0000719 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
720 Offset % ElemSize);
721 }
722 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000723}
724
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000725bool DevirtModule::tryFindVirtualCallTargets(
726 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000727 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
728 for (const TypeMemberInfo &TM : TypeMemberInfos) {
729 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000730 return false;
731
Peter Collingbourne87867542016-12-09 01:10:11 +0000732 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
733 TM.Offset + ByteOffset);
734 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000735 return false;
736
Peter Collingbourne87867542016-12-09 01:10:11 +0000737 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000738 if (!Fn)
739 return false;
740
741 // We can disregard __cxa_pure_virtual as a possible call target, as
742 // calls to pure virtuals are UB.
743 if (Fn->getName() == "__cxa_pure_virtual")
744 continue;
745
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000746 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000747 }
748
749 // Give up if we couldn't find any targets.
750 return !TargetsForSlot.empty();
751}
752
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000753void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000754 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000755 auto Apply = [&](CallSiteInfo &CSInfo) {
756 for (auto &&VCallSite : CSInfo.CallSites) {
757 if (RemarksEnabled)
Teresa Johnsonb0a1d3b2018-08-14 03:00:16 +0000758 VCallSite.emitRemark("single-impl",
759 TheFn->stripPointerCasts()->getName(), OREGetter);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000760 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
761 TheFn, VCallSite.CS.getCalledValue()->getType()));
762 // This use is no longer unsafe.
763 if (VCallSite.NumUnsafeUses)
764 --*VCallSite.NumUnsafeUses;
765 }
Peter Collingbourne29748562018-03-09 19:11:44 +0000766 if (CSInfo.isExported())
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000767 IsExported = true;
Peter Collingbourne29748562018-03-09 19:11:44 +0000768 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000769 };
770 Apply(SlotInfo.CSInfo);
771 for (auto &P : SlotInfo.ConstCSInfo)
772 Apply(P.second);
773}
774
Peter Collingbournee2367412017-02-15 02:13:08 +0000775bool DevirtModule::trySingleImplDevirt(
776 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000777 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000778 // See if the program contains a single implementation of this virtual
779 // function.
780 Function *TheFn = TargetsForSlot[0].Fn;
781 for (auto &&Target : TargetsForSlot)
782 if (TheFn != Target.Fn)
783 return false;
784
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000785 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000786 if (RemarksEnabled)
787 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000788
789 bool IsExported = false;
790 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
791 if (!IsExported)
792 return false;
793
794 // If the only implementation has local linkage, we must promote to external
795 // to make it visible to thin LTO objects. We can only get here during the
796 // ThinLTO export phase.
797 if (TheFn->hasLocalLinkage()) {
Peter Collingbourne88a58cf2017-09-08 00:10:53 +0000798 std::string NewName = (TheFn->getName() + "$merged").str();
799
800 // Since we are renaming the function, any comdats with the same name must
801 // also be renamed. This is required when targeting COFF, as the comdat name
802 // must match one of the names of the symbols in the comdat.
803 if (Comdat *C = TheFn->getComdat()) {
804 if (C->getName() == TheFn->getName()) {
805 Comdat *NewC = M.getOrInsertComdat(NewName);
806 NewC->setSelectionKind(C->getSelectionKind());
807 for (GlobalObject &GO : M.global_objects())
808 if (GO.getComdat() == C)
809 GO.setComdat(NewC);
810 }
811 }
812
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000813 TheFn->setLinkage(GlobalValue::ExternalLinkage);
814 TheFn->setVisibility(GlobalValue::HiddenVisibility);
Peter Collingbourne88a58cf2017-09-08 00:10:53 +0000815 TheFn->setName(NewName);
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000816 }
817
818 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
819 Res->SingleImplName = TheFn->getName();
820
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000821 return true;
822}
823
Peter Collingbourne29748562018-03-09 19:11:44 +0000824void DevirtModule::tryICallBranchFunnel(
825 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
826 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
827 Triple T(M.getTargetTriple());
828 if (T.getArch() != Triple::x86_64)
829 return;
830
Vitaly Buka66f53d72018-04-06 21:32:36 +0000831 if (TargetsForSlot.size() > ClThreshold)
Peter Collingbourne29748562018-03-09 19:11:44 +0000832 return;
833
834 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
835 if (!HasNonDevirt)
836 for (auto &P : SlotInfo.ConstCSInfo)
837 if (!P.second.AllCallSitesDevirted) {
838 HasNonDevirt = true;
839 break;
840 }
841
842 if (!HasNonDevirt)
843 return;
844
845 FunctionType *FT =
846 FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
847 Function *JT;
848 if (isa<MDString>(Slot.TypeID)) {
849 JT = Function::Create(FT, Function::ExternalLinkage,
850 getGlobalName(Slot, {}, "branch_funnel"), &M);
851 JT->setVisibility(GlobalValue::HiddenVisibility);
852 } else {
853 JT = Function::Create(FT, Function::InternalLinkage, "branch_funnel", &M);
854 }
855 JT->addAttribute(1, Attribute::Nest);
856
857 std::vector<Value *> JTArgs;
858 JTArgs.push_back(JT->arg_begin());
859 for (auto &T : TargetsForSlot) {
860 JTArgs.push_back(getMemberAddr(T.TM));
861 JTArgs.push_back(T.Fn);
862 }
863
864 BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
865 Constant *Intr =
866 Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
867
868 auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
869 CI->setTailCallKind(CallInst::TCK_MustTail);
870 ReturnInst::Create(M.getContext(), nullptr, BB);
871
872 bool IsExported = false;
873 applyICallBranchFunnel(SlotInfo, JT, IsExported);
874 if (IsExported)
875 Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
876}
877
878void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
879 Constant *JT, bool &IsExported) {
880 auto Apply = [&](CallSiteInfo &CSInfo) {
881 if (CSInfo.isExported())
882 IsExported = true;
883 if (CSInfo.AllCallSitesDevirted)
884 return;
885 for (auto &&VCallSite : CSInfo.CallSites) {
886 CallSite CS = VCallSite.CS;
887
888 // Jump tables are only profitable if the retpoline mitigation is enabled.
889 Attribute FSAttr = CS.getCaller()->getFnAttribute("target-features");
890 if (FSAttr.hasAttribute(Attribute::None) ||
891 !FSAttr.getValueAsString().contains("+retpoline"))
892 continue;
893
894 if (RemarksEnabled)
Teresa Johnsonb0a1d3b2018-08-14 03:00:16 +0000895 VCallSite.emitRemark("branch-funnel",
896 JT->stripPointerCasts()->getName(), OREGetter);
Peter Collingbourne29748562018-03-09 19:11:44 +0000897
898 // Pass the address of the vtable in the nest register, which is r10 on
899 // x86_64.
900 std::vector<Type *> NewArgs;
901 NewArgs.push_back(Int8PtrTy);
902 for (Type *T : CS.getFunctionType()->params())
903 NewArgs.push_back(T);
904 PointerType *NewFT = PointerType::getUnqual(
905 FunctionType::get(CS.getFunctionType()->getReturnType(), NewArgs,
906 CS.getFunctionType()->isVarArg()));
907
908 IRBuilder<> IRB(CS.getInstruction());
909 std::vector<Value *> Args;
910 Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
911 for (unsigned I = 0; I != CS.getNumArgOperands(); ++I)
912 Args.push_back(CS.getArgOperand(I));
913
914 CallSite NewCS;
915 if (CS.isCall())
916 NewCS = IRB.CreateCall(IRB.CreateBitCast(JT, NewFT), Args);
917 else
918 NewCS = IRB.CreateInvoke(
919 IRB.CreateBitCast(JT, NewFT),
920 cast<InvokeInst>(CS.getInstruction())->getNormalDest(),
921 cast<InvokeInst>(CS.getInstruction())->getUnwindDest(), Args);
922 NewCS.setCallingConv(CS.getCallingConv());
923
924 AttributeList Attrs = CS.getAttributes();
925 std::vector<AttributeSet> NewArgAttrs;
926 NewArgAttrs.push_back(AttributeSet::get(
927 M.getContext(), ArrayRef<Attribute>{Attribute::get(
928 M.getContext(), Attribute::Nest)}));
929 for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
930 NewArgAttrs.push_back(Attrs.getParamAttributes(I));
931 NewCS.setAttributes(
932 AttributeList::get(M.getContext(), Attrs.getFnAttributes(),
933 Attrs.getRetAttributes(), NewArgAttrs));
934
935 CS->replaceAllUsesWith(NewCS.getInstruction());
936 CS->eraseFromParent();
937
938 // This use is no longer unsafe.
939 if (VCallSite.NumUnsafeUses)
940 --*VCallSite.NumUnsafeUses;
941 }
942 // Don't mark as devirtualized because there may be callers compiled without
943 // retpoline mitigation, which would mean that they are lowered to
944 // llvm.type.test and therefore require an llvm.type.test resolution for the
945 // type identifier.
946 };
947 Apply(SlotInfo.CSInfo);
948 for (auto &P : SlotInfo.ConstCSInfo)
949 Apply(P.second);
950}
951
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000952bool DevirtModule::tryEvaluateFunctionsWithArgs(
953 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000954 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000955 // Evaluate each function and store the result in each target's RetVal
956 // field.
957 for (VirtualCallTarget &Target : TargetsForSlot) {
958 if (Target.Fn->arg_size() != Args.size() + 1)
959 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000960
961 Evaluator Eval(M.getDataLayout(), nullptr);
962 SmallVector<Constant *, 2> EvalArgs;
963 EvalArgs.push_back(
964 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000965 for (unsigned I = 0; I != Args.size(); ++I) {
966 auto *ArgTy = dyn_cast<IntegerType>(
967 Target.Fn->getFunctionType()->getParamType(I + 1));
968 if (!ArgTy)
969 return false;
970 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
971 }
972
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000973 Constant *RetVal;
974 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
975 !isa<ConstantInt>(RetVal))
976 return false;
977 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
978 }
979 return true;
980}
981
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000982void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
983 uint64_t TheRetVal) {
984 for (auto Call : CSInfo.CallSites)
985 Call.replaceAndErase(
Sam Elliotte963c892017-08-21 16:57:21 +0000986 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000987 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000988 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000989}
990
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000991bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000992 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
993 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000994 // Uniform return value optimization. If all functions return the same
995 // constant, replace all calls with that constant.
996 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
997 for (const VirtualCallTarget &Target : TargetsForSlot)
998 if (Target.RetVal != TheRetVal)
999 return false;
1000
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001001 if (CSInfo.isExported()) {
1002 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
1003 Res->Info = TheRetVal;
1004 }
1005
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001006 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001007 if (RemarksEnabled)
1008 for (auto &&Target : TargetsForSlot)
1009 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001010 return true;
1011}
1012
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001013std::string DevirtModule::getGlobalName(VTableSlot Slot,
1014 ArrayRef<uint64_t> Args,
1015 StringRef Name) {
1016 std::string FullName = "__typeid_";
1017 raw_string_ostream OS(FullName);
1018 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1019 for (uint64_t Arg : Args)
1020 OS << '_' << Arg;
1021 OS << '_' << Name;
1022 return OS.str();
1023}
1024
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001025bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1026 Triple T(M.getTargetTriple());
1027 return (T.getArch() == Triple::x86 || T.getArch() == Triple::x86_64) &&
1028 T.getObjectFormat() == Triple::ELF;
1029}
1030
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001031void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1032 StringRef Name, Constant *C) {
1033 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1034 getGlobalName(Slot, Args, Name), C, &M);
1035 GA->setVisibility(GlobalValue::HiddenVisibility);
1036}
1037
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001038void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1039 StringRef Name, uint32_t Const,
1040 uint32_t &Storage) {
1041 if (shouldExportConstantsAsAbsoluteSymbols()) {
1042 exportGlobal(
1043 Slot, Args, Name,
1044 ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1045 return;
1046 }
1047
1048 Storage = Const;
1049}
1050
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001051Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001052 StringRef Name) {
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001053 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
1054 auto *GV = dyn_cast<GlobalVariable>(C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001055 if (GV)
1056 GV->setVisibility(GlobalValue::HiddenVisibility);
1057 return C;
1058}
1059
1060Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1061 StringRef Name, IntegerType *IntTy,
1062 uint32_t Storage) {
1063 if (!shouldExportConstantsAsAbsoluteSymbols())
1064 return ConstantInt::get(IntTy, Storage);
1065
1066 Constant *C = importGlobal(Slot, Args, Name);
1067 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1068 C = ConstantExpr::getPtrToInt(C, IntTy);
1069
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001070 // We only need to set metadata if the global is newly created, in which
1071 // case it would not have hidden visibility.
Benjamin Kramer0deb9a92018-05-31 13:29:58 +00001072 if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001073 return C;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001074
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001075 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1076 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1077 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1078 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1079 MDNode::get(M.getContext(), {MinC, MaxC}));
1080 };
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001081 unsigned AbsWidth = IntTy->getBitWidth();
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001082 if (AbsWidth == IntPtrTy->getBitWidth())
1083 SetAbsRange(~0ull, ~0ull); // Full set.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001084 else
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001085 SetAbsRange(0, 1ull << AbsWidth);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001086 return C;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001087}
1088
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001089void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1090 bool IsOne,
1091 Constant *UniqueMemberAddr) {
1092 for (auto &&Call : CSInfo.CallSites) {
1093 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001094 Value *Cmp =
1095 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
1096 B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001097 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
Sam Elliotte963c892017-08-21 16:57:21 +00001098 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1099 Cmp);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001100 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001101 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001102}
1103
Peter Collingbourne29748562018-03-09 19:11:44 +00001104Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1105 Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
1106 return ConstantExpr::getGetElementPtr(Int8Ty, C,
1107 ConstantInt::get(Int64Ty, M->Offset));
1108}
1109
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001110bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001111 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001112 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1113 VTableSlot Slot, ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001114 // IsOne controls whether we look for a 0 or a 1.
1115 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001116 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001117 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +00001118 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001119 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001120 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001121 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001122 }
1123 }
1124
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001125 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001126 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001127 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001128
Peter Collingbourne29748562018-03-09 19:11:44 +00001129 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001130 if (CSInfo.isExported()) {
1131 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
1132 Res->Info = IsOne;
1133
1134 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1135 }
1136
1137 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001138 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1139 UniqueMemberAddr);
1140
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001141 // Update devirtualization statistics for targets.
1142 if (RemarksEnabled)
1143 for (auto &&Target : TargetsForSlot)
1144 Target.WasDevirt = true;
1145
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001146 return true;
1147 };
1148
1149 if (BitWidth == 1) {
1150 if (tryUniqueRetValOptFor(true))
1151 return true;
1152 if (tryUniqueRetValOptFor(false))
1153 return true;
1154 }
1155 return false;
1156}
1157
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001158void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1159 Constant *Byte, Constant *Bit) {
1160 for (auto Call : CSInfo.CallSites) {
1161 auto *RetType = cast<IntegerType>(Call.CS.getType());
1162 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001163 Value *Addr =
1164 B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001165 if (RetType->getBitWidth() == 1) {
1166 Value *Bits = B.CreateLoad(Addr);
1167 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1168 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1169 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
Sam Elliotte963c892017-08-21 16:57:21 +00001170 OREGetter, IsBitSet);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001171 } else {
1172 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
1173 Value *Val = B.CreateLoad(RetType, ValAddr);
Sam Elliotte963c892017-08-21 16:57:21 +00001174 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1175 OREGetter, Val);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001176 }
1177 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001178 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001179}
1180
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001181bool DevirtModule::tryVirtualConstProp(
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001182 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1183 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001184 // This only works if the function returns an integer.
1185 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
1186 if (!RetType)
1187 return false;
1188 unsigned BitWidth = RetType->getBitWidth();
1189 if (BitWidth > 64)
1190 return false;
1191
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001192 // Make sure that each function is defined, does not access memory, takes at
1193 // least one argument, does not use its first argument (which we assume is
1194 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +00001195 //
1196 // Note that we test whether this copy of the function is readnone, rather
1197 // than testing function attributes, which must hold for any copy of the
1198 // function, even a less optimized version substituted at link time. This is
1199 // sound because the virtual constant propagation optimizations effectively
1200 // inline all implementations of the virtual function into each call site,
1201 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001202 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +00001203 if (Target.Fn->isDeclaration() ||
1204 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
1205 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001206 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001207 Target.Fn->getReturnType() != RetType)
1208 return false;
1209 }
1210
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001211 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001212 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1213 continue;
1214
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001215 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1216 if (Res)
1217 ResByArg = &Res->ResByArg[CSByConstantArg.first];
1218
1219 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001220 continue;
1221
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001222 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1223 ResByArg, Slot, CSByConstantArg.first))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001224 continue;
1225
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001226 // Find an allocation offset in bits in all vtables associated with the
1227 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001228 uint64_t AllocBefore =
1229 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1230 uint64_t AllocAfter =
1231 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1232
1233 // Calculate the total amount of padding needed to store a value at both
1234 // ends of the object.
1235 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1236 for (auto &&Target : TargetsForSlot) {
1237 TotalPaddingBefore += std::max<int64_t>(
1238 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1239 TotalPaddingAfter += std::max<int64_t>(
1240 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1241 }
1242
1243 // If the amount of padding is too large, give up.
1244 // FIXME: do something smarter here.
1245 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1246 continue;
1247
1248 // Calculate the offset to the value as a (possibly negative) byte offset
1249 // and (if applicable) a bit offset, and store the values in the targets.
1250 int64_t OffsetByte;
1251 uint64_t OffsetBit;
1252 if (TotalPaddingBefore <= TotalPaddingAfter)
1253 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1254 OffsetBit);
1255 else
1256 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1257 OffsetBit);
1258
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001259 if (RemarksEnabled)
1260 for (auto &&Target : TargetsForSlot)
1261 Target.WasDevirt = true;
1262
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001263
1264 if (CSByConstantArg.second.isExported()) {
1265 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001266 exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
1267 ResByArg->Byte);
1268 exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
1269 ResByArg->Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001270 }
1271
1272 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001273 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
1274 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001275 applyVirtualConstProp(CSByConstantArg.second,
1276 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001277 }
1278 return true;
1279}
1280
1281void DevirtModule::rebuildGlobal(VTableBits &B) {
1282 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1283 return;
1284
1285 // Align each byte array to pointer width.
1286 unsigned PointerSize = M.getDataLayout().getPointerSize();
1287 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
1288 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
1289
1290 // Before was stored in reverse order; flip it now.
1291 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1292 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1293
1294 // Build an anonymous global containing the before bytes, followed by the
1295 // original initializer, followed by the after bytes.
1296 auto NewInit = ConstantStruct::getAnon(
1297 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1298 B.GV->getInitializer(),
1299 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1300 auto NewGV =
1301 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1302 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1303 NewGV->setSection(B.GV->getSection());
1304 NewGV->setComdat(B.GV->getComdat());
1305
Peter Collingbourne0312f612016-06-25 00:23:04 +00001306 // Copy the original vtable's metadata to the anonymous global, adjusting
1307 // offsets as required.
1308 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1309
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001310 // Build an alias named after the original global, pointing at the second
1311 // element (the original initializer).
1312 auto Alias = GlobalAlias::create(
1313 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1314 ConstantExpr::getGetElementPtr(
1315 NewInit->getType(), NewGV,
1316 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1317 ConstantInt::get(Int32Ty, 1)}),
1318 &M);
1319 Alias->setVisibility(B.GV->getVisibility());
1320 Alias->takeName(B.GV);
1321
1322 B.GV->replaceAllUsesWith(Alias);
1323 B.GV->eraseFromParent();
1324}
1325
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001326bool DevirtModule::areRemarksEnabled() {
1327 const auto &FL = M.getFunctionList();
1328 if (FL.empty())
1329 return false;
1330 const Function &Fn = FL.front();
Adam Nemetde53bfb2017-02-23 23:11:11 +00001331
1332 const auto &BBL = Fn.getBasicBlockList();
1333 if (BBL.empty())
1334 return false;
1335 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001336 return DI.isEnabled();
1337}
1338
Peter Collingbourne0312f612016-06-25 00:23:04 +00001339void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
1340 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001341 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001342 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1343 // points to a member of the type identifier %md. Group calls by (type ID,
1344 // offset) pair (effectively the identity of the virtual function) and store
1345 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001346 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001347 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001348 I != E;) {
1349 auto CI = dyn_cast<CallInst>(I->getUser());
1350 ++I;
1351 if (!CI)
1352 continue;
1353
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001354 // Search for virtual calls based on %p and add them to DevirtCalls.
1355 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001356 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +00001357 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001358
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001359 // If we found any, add them to CallSlots. Only do this if we haven't seen
1360 // the vtable pointer before, as it may have been CSE'd with pointers from
1361 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001362 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001363 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001364 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1365 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001366 if (SeenPtrs.insert(Ptr).second) {
1367 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne001052a2017-08-22 21:41:19 +00001368 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001369 }
1370 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001371 }
1372
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001373 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001374 for (auto Assume : Assumes)
1375 Assume->eraseFromParent();
1376 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1377 // may use the vtable argument later.
1378 if (CI->use_empty())
1379 CI->eraseFromParent();
1380 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001381}
1382
1383void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1384 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1385
1386 for (auto I = TypeCheckedLoadFunc->use_begin(),
1387 E = TypeCheckedLoadFunc->use_end();
1388 I != E;) {
1389 auto CI = dyn_cast<CallInst>(I->getUser());
1390 ++I;
1391 if (!CI)
1392 continue;
1393
1394 Value *Ptr = CI->getArgOperand(0);
1395 Value *Offset = CI->getArgOperand(1);
1396 Value *TypeIdValue = CI->getArgOperand(2);
1397 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1398
1399 SmallVector<DevirtCallSite, 1> DevirtCalls;
1400 SmallVector<Instruction *, 1> LoadedPtrs;
1401 SmallVector<Instruction *, 1> Preds;
1402 bool HasNonCallUses = false;
1403 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1404 HasNonCallUses, CI);
1405
1406 // Start by generating "pessimistic" code that explicitly loads the function
1407 // pointer from the vtable and performs the type check. If possible, we will
1408 // eliminate the load and the type check later.
1409
1410 // If possible, only generate the load at the point where it is used.
1411 // This helps avoid unnecessary spills.
1412 IRBuilder<> LoadB(
1413 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1414 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1415 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1416 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1417
1418 for (Instruction *LoadedPtr : LoadedPtrs) {
1419 LoadedPtr->replaceAllUsesWith(LoadedValue);
1420 LoadedPtr->eraseFromParent();
1421 }
1422
1423 // Likewise for the type test.
1424 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1425 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1426
1427 for (Instruction *Pred : Preds) {
1428 Pred->replaceAllUsesWith(TypeTestCall);
1429 Pred->eraseFromParent();
1430 }
1431
1432 // We have already erased any extractvalue instructions that refer to the
1433 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1434 // (although this is unlikely). In that case, explicitly build a pair and
1435 // RAUW it.
1436 if (!CI->use_empty()) {
1437 Value *Pair = UndefValue::get(CI->getType());
1438 IRBuilder<> B(CI);
1439 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1440 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1441 CI->replaceAllUsesWith(Pair);
1442 }
1443
1444 // The number of unsafe uses is initially the number of uses.
1445 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1446 NumUnsafeUses = DevirtCalls.size();
1447
1448 // If the function pointer has a non-call user, we cannot eliminate the type
1449 // check, as one of those users may eventually call the pointer. Increment
1450 // the unsafe use count to make sure it cannot reach zero.
1451 if (HasNonCallUses)
1452 ++NumUnsafeUses;
1453 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001454 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1455 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001456 }
1457
1458 CI->eraseFromParent();
1459 }
1460}
1461
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001462void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001463 const TypeIdSummary *TidSummary =
Peter Collingbournef7691d82017-03-22 18:22:59 +00001464 ImportSummary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString());
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001465 if (!TidSummary)
1466 return;
1467 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1468 if (ResI == TidSummary->WPDRes.end())
1469 return;
1470 const WholeProgramDevirtResolution &Res = ResI->second;
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001471
1472 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1473 // The type of the function in the declaration is irrelevant because every
1474 // call site will cast it to the correct type.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001475 auto *SingleImpl = M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001476 Res.SingleImplName, Type::getVoidTy(M.getContext()));
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001477
1478 // This is the import phase so we should not be exporting anything.
1479 bool IsExported = false;
1480 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1481 assert(!IsExported);
1482 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001483
1484 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1485 auto I = Res.ResByArg.find(CSByConstantArg.first);
1486 if (I == Res.ResByArg.end())
1487 continue;
1488 auto &ResByArg = I->second;
1489 // FIXME: We should figure out what to do about the "function name" argument
1490 // to the apply* functions, as the function names are unavailable during the
1491 // importing phase. For now we just pass the empty string. This does not
1492 // impact correctness because the function names are just used for remarks.
1493 switch (ResByArg.TheKind) {
1494 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1495 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1496 break;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001497 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1498 Constant *UniqueMemberAddr =
1499 importGlobal(Slot, CSByConstantArg.first, "unique_member");
1500 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1501 UniqueMemberAddr);
1502 break;
1503 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001504 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001505 Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
1506 Int32Ty, ResByArg.Byte);
1507 Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
1508 ResByArg.Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001509 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
Adrian Prantl0e6694d2017-12-19 22:05:25 +00001510 break;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001511 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001512 default:
1513 break;
1514 }
1515 }
Peter Collingbourne29748562018-03-09 19:11:44 +00001516
1517 if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
1518 auto *JT = M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
1519 Type::getVoidTy(M.getContext()));
1520 bool IsExported = false;
1521 applyICallBranchFunnel(SlotInfo, JT, IsExported);
1522 assert(!IsExported);
1523 }
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001524}
1525
1526void DevirtModule::removeRedundantTypeTests() {
1527 auto True = ConstantInt::getTrue(M.getContext());
1528 for (auto &&U : NumUnsafeUsesForTypeTest) {
1529 if (U.second == 0) {
1530 U.first->replaceAllUsesWith(True);
1531 U.first->eraseFromParent();
1532 }
1533 }
1534}
1535
Peter Collingbourne0312f612016-06-25 00:23:04 +00001536bool DevirtModule::run() {
1537 Function *TypeTestFunc =
1538 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1539 Function *TypeCheckedLoadFunc =
1540 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1541 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1542
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001543 // Normally if there are no users of the devirtualization intrinsics in the
1544 // module, this pass has nothing to do. But if we are exporting, we also need
1545 // to handle any users that appear only in the function summaries.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001546 if (!ExportSummary &&
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001547 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001548 AssumeFunc->use_empty()) &&
1549 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1550 return false;
1551
1552 if (TypeTestFunc && AssumeFunc)
1553 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1554
1555 if (TypeCheckedLoadFunc)
1556 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001557
Peter Collingbournef7691d82017-03-22 18:22:59 +00001558 if (ImportSummary) {
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001559 for (auto &S : CallSlots)
1560 importResolution(S.first, S.second);
1561
1562 removeRedundantTypeTests();
1563
1564 // The rest of the code is only necessary when exporting or during regular
1565 // LTO, so we are done.
1566 return true;
1567 }
1568
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001569 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001570 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001571 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1572 buildTypeIdentifierMap(Bits, TypeIdMap);
1573 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001574 return true;
1575
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001576 // Collect information from summary about which calls to try to devirtualize.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001577 if (ExportSummary) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001578 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1579 for (auto &P : TypeIdMap) {
1580 if (auto *TypeId = dyn_cast<MDString>(P.first))
1581 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1582 TypeId);
1583 }
1584
Peter Collingbournef7691d82017-03-22 18:22:59 +00001585 for (auto &P : *ExportSummary) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001586 for (auto &S : P.second.SummaryList) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001587 auto *FS = dyn_cast<FunctionSummary>(S.get());
1588 if (!FS)
1589 continue;
1590 // FIXME: Only add live functions.
George Rimar5d8aea12017-03-10 10:31:56 +00001591 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1592 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001593 CallSlots[{MD, VF.Offset}]
1594 .CSInfo.markSummaryHasTypeTestAssumeUsers();
George Rimar5d8aea12017-03-10 10:31:56 +00001595 }
1596 }
1597 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1598 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001599 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001600 }
1601 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001602 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001603 FS->type_test_assume_const_vcalls()) {
1604 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001605 CallSlots[{MD, VC.VFunc.Offset}]
George Rimar5d8aea12017-03-10 10:31:56 +00001606 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001607 .markSummaryHasTypeTestAssumeUsers();
George Rimar5d8aea12017-03-10 10:31:56 +00001608 }
1609 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001610 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001611 FS->type_checked_load_const_vcalls()) {
1612 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001613 CallSlots[{MD, VC.VFunc.Offset}]
1614 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001615 .addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001616 }
1617 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001618 }
1619 }
1620 }
1621
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001622 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001623 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001624 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001625 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001626 // Search each of the members of the type identifier for the virtual
1627 // function implementation at offset S.first.ByteOffset, and add to
1628 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001629 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001630 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1631 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001632 WholeProgramDevirtResolution *Res = nullptr;
Peter Collingbournef7691d82017-03-22 18:22:59 +00001633 if (ExportSummary && isa<MDString>(S.first.TypeID))
1634 Res = &ExportSummary
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001635 ->getOrInsertTypeIdSummary(
1636 cast<MDString>(S.first.TypeID)->getString())
1637 .WPDRes[S.first.ByteOffset];
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001638
Peter Collingbourne29748562018-03-09 19:11:44 +00001639 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res)) {
1640 DidVirtualConstProp |=
1641 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
1642
1643 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
1644 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001645
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001646 // Collect functions devirtualized at least for one call site for stats.
1647 if (RemarksEnabled)
1648 for (const auto &T : TargetsForSlot)
1649 if (T.WasDevirt)
1650 DevirtTargets[T.Fn->getName()] = T.Fn;
1651 }
1652
1653 // CFI-specific: if we are exporting and any llvm.type.checked.load
1654 // intrinsics were *not* devirtualized, we need to add the resulting
1655 // llvm.type.test intrinsics to the function summaries so that the
1656 // LowerTypeTests pass will export them.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001657 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001658 auto GUID =
1659 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1660 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1661 FS->addTypeTest(GUID);
1662 for (auto &CCS : S.second.ConstCSInfo)
1663 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1664 FS->addTypeTest(GUID);
1665 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001666 }
1667
1668 if (RemarksEnabled) {
1669 // Generate remarks for each devirtualized function.
1670 for (const auto &DT : DevirtTargets) {
1671 Function *F = DT.second;
Sam Elliotte963c892017-08-21 16:57:21 +00001672
Sam Elliotte963c892017-08-21 16:57:21 +00001673 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +00001674 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
1675 << "devirtualized "
1676 << NV("FunctionName", F->getName()));
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001677 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001678 }
1679
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001680 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00001681
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001682 // Rebuild each global we touched as part of virtual constant propagation to
1683 // include the before and after bytes.
1684 if (DidVirtualConstProp)
1685 for (VTableBits &B : Bits)
1686 rebuildGlobal(B);
1687
1688 return true;
1689}