blob: a3aa7c42608e8a19d8ffa0407c80124d23bd4a2a [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
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000114// Find the minimum offset that we may store a value of size Size bits at. If
115// IsAfter is set, look for an offset before the object, otherwise look for an
116// offset after the object.
117uint64_t
118wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
119 bool IsAfter, uint64_t Size) {
120 // Find a minimum offset taking into account only vtable sizes.
121 uint64_t MinByte = 0;
122 for (const VirtualCallTarget &Target : Targets) {
123 if (IsAfter)
124 MinByte = std::max(MinByte, Target.minAfterBytes());
125 else
126 MinByte = std::max(MinByte, Target.minBeforeBytes());
127 }
128
129 // Build a vector of arrays of bytes covering, for each target, a slice of the
130 // used region (see AccumBitVector::BytesUsed in
131 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
132 // this aligns the used regions to start at MinByte.
133 //
134 // In this example, A, B and C are vtables, # is a byte already allocated for
135 // a virtual function pointer, AAAA... (etc.) are the used regions for the
136 // vtables and Offset(X) is the value computed for the Offset variable below
137 // for X.
138 //
139 // Offset(A)
140 // | |
141 // |MinByte
142 // A: ################AAAAAAAA|AAAAAAAA
143 // B: ########BBBBBBBBBBBBBBBB|BBBB
144 // C: ########################|CCCCCCCCCCCCCCCC
145 // | Offset(B) |
146 //
147 // This code produces the slices of A, B and C that appear after the divider
148 // at MinByte.
149 std::vector<ArrayRef<uint8_t>> Used;
150 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000151 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
152 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000153 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
154 : MinByte - Target.minBeforeBytes();
155
156 // Disregard used regions that are smaller than Offset. These are
157 // effectively all-free regions that do not need to be checked.
158 if (VTUsed.size() > Offset)
159 Used.push_back(VTUsed.slice(Offset));
160 }
161
162 if (Size == 1) {
163 // Find a free bit in each member of Used.
164 for (unsigned I = 0;; ++I) {
165 uint8_t BitsUsed = 0;
166 for (auto &&B : Used)
167 if (I < B.size())
168 BitsUsed |= B[I];
169 if (BitsUsed != 0xff)
170 return (MinByte + I) * 8 +
171 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
172 }
173 } else {
174 // Find a free (Size/8) byte region in each member of Used.
175 // FIXME: see if alignment helps.
176 for (unsigned I = 0;; ++I) {
177 for (auto &&B : Used) {
178 unsigned Byte = 0;
179 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
180 if (B[I + Byte])
181 goto NextI;
182 ++Byte;
183 }
184 }
185 return (MinByte + I) * 8;
186 NextI:;
187 }
188 }
189}
190
191void wholeprogramdevirt::setBeforeReturnValues(
192 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
193 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
194 if (BitWidth == 1)
195 OffsetByte = -(AllocBefore / 8 + 1);
196 else
197 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
198 OffsetBit = AllocBefore % 8;
199
200 for (VirtualCallTarget &Target : Targets) {
201 if (BitWidth == 1)
202 Target.setBeforeBit(AllocBefore);
203 else
204 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
205 }
206}
207
208void wholeprogramdevirt::setAfterReturnValues(
209 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
210 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
211 if (BitWidth == 1)
212 OffsetByte = AllocAfter / 8;
213 else
214 OffsetByte = (AllocAfter + 7) / 8;
215 OffsetBit = AllocAfter % 8;
216
217 for (VirtualCallTarget &Target : Targets) {
218 if (BitWidth == 1)
219 Target.setAfterBit(AllocAfter);
220 else
221 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
222 }
223}
224
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000225VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
226 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000227 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000228
229namespace {
230
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000231// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000232// tables, and the ByteOffset is the offset in bytes from the address point to
233// the virtual function pointer.
234struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000235 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000236 uint64_t ByteOffset;
237};
238
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000239} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000240
Peter Collingbourne9b656522016-02-09 23:01:38 +0000241namespace llvm {
242
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000243template <> struct DenseMapInfo<VTableSlot> {
244 static VTableSlot getEmptyKey() {
245 return {DenseMapInfo<Metadata *>::getEmptyKey(),
246 DenseMapInfo<uint64_t>::getEmptyKey()};
247 }
248 static VTableSlot getTombstoneKey() {
249 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
250 DenseMapInfo<uint64_t>::getTombstoneKey()};
251 }
252 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000253 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000254 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
255 }
256 static bool isEqual(const VTableSlot &LHS,
257 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000258 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000259 }
260};
261
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000262} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000263
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000264namespace {
265
266// A virtual call site. VTable is the loaded virtual table pointer, and CS is
267// the indirect virtual call.
268struct VirtualCallSite {
269 Value *VTable;
270 CallSite CS;
271
Peter Collingbourne0312f612016-06-25 00:23:04 +0000272 // If non-null, this field points to the associated unsafe use count stored in
273 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
274 // of that field for details.
275 unsigned *NumUnsafeUses;
276
Sam Elliotte963c892017-08-21 16:57:21 +0000277 void
278 emitRemark(const StringRef OptName, const StringRef TargetName,
279 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Ivan Krasin54746452016-07-12 02:38:37 +0000280 Function *F = CS.getCaller();
Sam Elliotte963c892017-08-21 16:57:21 +0000281 DebugLoc DLoc = CS->getDebugLoc();
282 BasicBlock *Block = CS.getParent();
283
Sam Elliotte963c892017-08-21 16:57:21 +0000284 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000285 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
286 << NV("Optimization", OptName)
287 << ": devirtualized a call to "
288 << NV("FunctionName", TargetName));
Ivan Krasin54746452016-07-12 02:38:37 +0000289 }
290
Sam Elliotte963c892017-08-21 16:57:21 +0000291 void replaceAndErase(
292 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
293 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
294 Value *New) {
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000295 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000296 emitRemark(OptName, TargetName, OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000297 CS->replaceAllUsesWith(New);
298 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
299 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
300 II->getUnwindDest()->removePredecessor(II->getParent());
301 }
302 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000303 // This use is no longer unsafe.
304 if (NumUnsafeUses)
305 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000306 }
307};
308
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000309// Call site information collected for a specific VTableSlot and possibly a list
310// of constant integer arguments. The grouping by arguments is handled by the
311// VTableSlotInfo class.
312struct CallSiteInfo {
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000313 /// The set of call sites for this slot. Used during regular LTO and the
314 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
315 /// call sites that appear in the merged module itself); in each of these
316 /// cases we are directly operating on the call sites at the IR level.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000317 std::vector<VirtualCallSite> CallSites;
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000318
Peter Collingbourne29748562018-03-09 19:11:44 +0000319 /// Whether all call sites represented by this CallSiteInfo, including those
320 /// in summaries, have been devirtualized. This starts off as true because a
321 /// default constructed CallSiteInfo represents no call sites.
322 bool AllCallSitesDevirted = true;
323
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000324 // These fields are used during the export phase of ThinLTO and reflect
325 // information collected from function summaries.
326
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000327 /// Whether any function summary contains an llvm.assume(llvm.type.test) for
328 /// this slot.
Peter Collingbourne29748562018-03-09 19:11:44 +0000329 bool SummaryHasTypeTestAssumeUsers = false;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000330
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000331 /// CFI-specific: a vector containing the list of function summaries that use
332 /// the llvm.type.checked.load intrinsic and therefore will require
333 /// resolutions for llvm.type.test in order to implement CFI checks if
334 /// devirtualization was unsuccessful. If devirtualization was successful, the
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000335 /// pass will clear this vector by calling markDevirt(). If at the end of the
336 /// pass the vector is non-empty, we will need to add a use of llvm.type.test
337 /// to each of the function summaries in the vector.
Peter Collingbourneb406baa2017-03-04 01:23:30 +0000338 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000339
340 bool isExported() const {
341 return SummaryHasTypeTestAssumeUsers ||
342 !SummaryTypeCheckedLoadUsers.empty();
343 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000344
Peter Collingbourne29748562018-03-09 19:11:44 +0000345 void markSummaryHasTypeTestAssumeUsers() {
346 SummaryHasTypeTestAssumeUsers = true;
347 AllCallSitesDevirted = false;
348 }
349
350 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
351 SummaryTypeCheckedLoadUsers.push_back(FS);
352 AllCallSitesDevirted = false;
353 }
354
355 void markDevirt() {
356 AllCallSitesDevirted = true;
357
358 // As explained in the comment for SummaryTypeCheckedLoadUsers.
359 SummaryTypeCheckedLoadUsers.clear();
360 }
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000361};
362
363// Call site information collected for a specific VTableSlot.
364struct VTableSlotInfo {
365 // The set of call sites which do not have all constant integer arguments
366 // (excluding "this").
367 CallSiteInfo CSInfo;
368
369 // The set of call sites with all constant integer arguments (excluding
370 // "this"), grouped by argument list.
371 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
372
373 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
374
375private:
376 CallSiteInfo &findCallSiteInfo(CallSite CS);
377};
378
379CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
380 std::vector<uint64_t> Args;
381 auto *CI = dyn_cast<IntegerType>(CS.getType());
382 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
383 return CSInfo;
384 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
385 auto *CI = dyn_cast<ConstantInt>(Arg);
386 if (!CI || CI->getBitWidth() > 64)
387 return CSInfo;
388 Args.push_back(CI->getZExtValue());
389 }
390 return ConstCSInfo[Args];
391}
392
393void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
394 unsigned *NumUnsafeUses) {
Peter Collingbourne29748562018-03-09 19:11:44 +0000395 auto &CSI = findCallSiteInfo(CS);
396 CSI.AllCallSitesDevirted = false;
397 CSI.CallSites.push_back({VTable, CS, NumUnsafeUses});
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000398}
399
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000400struct DevirtModule {
401 Module &M;
Peter Collingbourne37317f12017-02-17 18:17:04 +0000402 function_ref<AAResults &(Function &)> AARGetter;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000403
Peter Collingbournef7691d82017-03-22 18:22:59 +0000404 ModuleSummaryIndex *ExportSummary;
405 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000406
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000407 IntegerType *Int8Ty;
408 PointerType *Int8PtrTy;
409 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000410 IntegerType *Int64Ty;
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000411 IntegerType *IntPtrTy;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000412
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000413 bool RemarksEnabled;
Sam Elliotte963c892017-08-21 16:57:21 +0000414 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000415
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000416 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000417
Peter Collingbourne0312f612016-06-25 00:23:04 +0000418 // This map keeps track of the number of "unsafe" uses of a loaded function
419 // pointer. The key is the associated llvm.type.test intrinsic call generated
420 // by this pass. An unsafe use is one that calls the loaded function pointer
421 // directly. Every time we eliminate an unsafe use (for example, by
422 // devirtualizing it or by applying virtual constant propagation), we
423 // decrement the value stored in this map. If a value reaches zero, we can
424 // eliminate the type check by RAUWing the associated llvm.type.test call with
425 // true.
426 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
427
Peter Collingbourne37317f12017-02-17 18:17:04 +0000428 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
Sam Elliotte963c892017-08-21 16:57:21 +0000429 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000430 ModuleSummaryIndex *ExportSummary,
431 const ModuleSummaryIndex *ImportSummary)
432 : M(M), AARGetter(AARGetter), ExportSummary(ExportSummary),
433 ImportSummary(ImportSummary), Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000434 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000435 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000436 Int64Ty(Type::getInt64Ty(M.getContext())),
Peter Collingbourne14dcf022017-03-10 20:13:58 +0000437 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Sam Elliotte963c892017-08-21 16:57:21 +0000438 RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000439 assert(!(ExportSummary && ImportSummary));
440 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000441
442 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000443
Peter Collingbourne0312f612016-06-25 00:23:04 +0000444 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
445 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
446
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000447 void buildTypeIdentifierMap(
448 std::vector<VTableBits> &Bits,
449 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000450 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000451 bool
452 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
453 const std::set<TypeMemberInfo> &TypeMemberInfos,
454 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000455
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000456 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
457 bool &IsExported);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000458 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000459 VTableSlotInfo &SlotInfo,
460 WholeProgramDevirtResolution *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000461
Peter Collingbourne29748562018-03-09 19:11:44 +0000462 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT,
463 bool &IsExported);
464 void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
465 VTableSlotInfo &SlotInfo,
466 WholeProgramDevirtResolution *Res, VTableSlot Slot);
467
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000468 bool tryEvaluateFunctionsWithArgs(
469 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000470 ArrayRef<uint64_t> Args);
471
472 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
473 uint64_t TheRetVal);
474 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000475 CallSiteInfo &CSInfo,
476 WholeProgramDevirtResolution::ByArg *Res);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000477
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000478 // Returns the global symbol name that is used to export information about the
479 // given vtable slot and list of arguments.
480 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
481 StringRef Name);
482
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000483 bool shouldExportConstantsAsAbsoluteSymbols();
484
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000485 // This function is called during the export phase to create a symbol
486 // definition containing information about the given vtable slot and list of
487 // arguments.
488 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
489 Constant *C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000490 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
491 uint32_t Const, uint32_t &Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000492
493 // This function is called during the import phase to create a reference to
494 // the symbol definition created during the export phase.
495 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +0000496 StringRef Name);
497 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
498 StringRef Name, IntegerType *IntTy,
499 uint32_t Storage);
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000500
Peter Collingbourne29748562018-03-09 19:11:44 +0000501 Constant *getMemberAddr(const TypeMemberInfo *M);
502
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000503 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
504 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000505 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000506 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000507 CallSiteInfo &CSInfo,
508 WholeProgramDevirtResolution::ByArg *Res,
509 VTableSlot Slot, ArrayRef<uint64_t> Args);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000510
511 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
512 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000513 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000514 VTableSlotInfo &SlotInfo,
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000515 WholeProgramDevirtResolution *Res, VTableSlot Slot);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000516
517 void rebuildGlobal(VTableBits &B);
518
Peter Collingbourne6d284fa2017-03-09 00:21:25 +0000519 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
520 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
521
522 // If we were able to eliminate all unsafe uses for a type checked load,
523 // eliminate the associated type tests by replacing them with true.
524 void removeRedundantTypeTests();
525
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000526 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000527
528 // Lower the module using the action and summary passed as command line
529 // arguments. For testing purposes only.
Sam Elliotte963c892017-08-21 16:57:21 +0000530 static bool runForTesting(
531 Module &M, function_ref<AAResults &(Function &)> AARGetter,
532 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000533};
534
535struct WholeProgramDevirt : public ModulePass {
536 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000537
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000538 bool UseCommandLine = false;
539
Peter Collingbournef7691d82017-03-22 18:22:59 +0000540 ModuleSummaryIndex *ExportSummary;
541 const ModuleSummaryIndex *ImportSummary;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000542
543 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
544 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
545 }
546
Peter Collingbournef7691d82017-03-22 18:22:59 +0000547 WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
548 const ModuleSummaryIndex *ImportSummary)
549 : ModulePass(ID), ExportSummary(ExportSummary),
550 ImportSummary(ImportSummary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000551 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
552 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000553
554 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000555 if (skipModule(M))
556 return false;
Sam Elliotte963c892017-08-21 16:57:21 +0000557
Peter Collingbourne9110cb42018-01-05 00:27:51 +0000558 // In the new pass manager, we can request the optimization
559 // remark emitter pass on a per-function-basis, which the
560 // OREGetter will do for us.
561 // In the old pass manager, this is harder, so we just build
562 // an optimization remark emitter on the fly, when we need it.
563 std::unique_ptr<OptimizationRemarkEmitter> ORE;
564 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
565 ORE = make_unique<OptimizationRemarkEmitter>(F);
566 return *ORE;
567 };
Sam Elliotte963c892017-08-21 16:57:21 +0000568
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000569 if (UseCommandLine)
Sam Elliotte963c892017-08-21 16:57:21 +0000570 return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter);
571
572 return DevirtModule(M, LegacyAARGetter(*this), OREGetter, ExportSummary,
573 ImportSummary)
Peter Collingbournef7691d82017-03-22 18:22:59 +0000574 .run();
Peter Collingbourne37317f12017-02-17 18:17:04 +0000575 }
576
577 void getAnalysisUsage(AnalysisUsage &AU) const override {
578 AU.addRequired<AssumptionCacheTracker>();
579 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000580 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000581};
582
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000583} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000584
Peter Collingbourne37317f12017-02-17 18:17:04 +0000585INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
586 "Whole program devirtualization", false, false)
587INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
588INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
589INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
590 "Whole program devirtualization", false, false)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000591char WholeProgramDevirt::ID = 0;
592
Peter Collingbournef7691d82017-03-22 18:22:59 +0000593ModulePass *
594llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
595 const ModuleSummaryIndex *ImportSummary) {
596 return new WholeProgramDevirt(ExportSummary, ImportSummary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000597}
598
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000599PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
Peter Collingbourne37317f12017-02-17 18:17:04 +0000600 ModuleAnalysisManager &AM) {
601 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
602 auto AARGetter = [&](Function &F) -> AAResults & {
603 return FAM.getResult<AAManager>(F);
604 };
Sam Elliotte963c892017-08-21 16:57:21 +0000605 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
606 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
607 };
608 if (!DevirtModule(M, AARGetter, OREGetter, nullptr, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000609 return PreservedAnalyses::all();
610 return PreservedAnalyses::none();
611}
612
Peter Collingbourne37317f12017-02-17 18:17:04 +0000613bool DevirtModule::runForTesting(
Sam Elliotte963c892017-08-21 16:57:21 +0000614 Module &M, function_ref<AAResults &(Function &)> AARGetter,
615 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Eugene Leviant28d8a492018-01-22 13:35:40 +0000616 ModuleSummaryIndex Summary(/*IsPerformingAnalysis=*/false);
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000617
618 // Handle the command-line summary arguments. This code is for testing
619 // purposes only, so we handle errors directly.
620 if (!ClReadSummary.empty()) {
621 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
622 ": ");
623 auto ReadSummaryFile =
624 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
625
626 yaml::Input In(ReadSummaryFile->getBuffer());
627 In >> Summary;
628 ExitOnErr(errorCodeToError(In.error()));
629 }
630
Peter Collingbournef7691d82017-03-22 18:22:59 +0000631 bool Changed =
632 DevirtModule(
Sam Elliotte963c892017-08-21 16:57:21 +0000633 M, AARGetter, OREGetter,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000634 ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
635 ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr)
636 .run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000637
638 if (!ClWriteSummary.empty()) {
639 ExitOnError ExitOnErr(
640 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
641 std::error_code EC;
642 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
643 ExitOnErr(errorCodeToError(EC));
644
645 yaml::Output Out(OS);
646 Out << Summary;
647 }
648
649 return Changed;
650}
651
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000652void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000653 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000654 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000655 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000656 Bits.reserve(M.getGlobalList().size());
657 SmallVector<MDNode *, 2> Types;
658 for (GlobalVariable &GV : M.globals()) {
659 Types.clear();
660 GV.getMetadata(LLVMContext::MD_type, Types);
661 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000662 continue;
663
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000664 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000665 if (!BitsPtr) {
666 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000667 Bits.back().GV = &GV;
668 Bits.back().ObjectSize =
669 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000670 BitsPtr = &Bits.back();
671 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000672
673 for (MDNode *Type : Types) {
674 auto TypeID = Type->getOperand(1).get();
675
676 uint64_t Offset =
677 cast<ConstantInt>(
678 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
679 ->getZExtValue();
680
681 TypeIdMap[TypeID].insert({BitsPtr, Offset});
682 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000683 }
684}
685
Peter Collingbourne87867542016-12-09 01:10:11 +0000686Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
687 if (I->getType()->isPointerTy()) {
688 if (Offset == 0)
689 return I;
690 return nullptr;
691 }
692
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000693 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000694
695 if (auto *C = dyn_cast<ConstantStruct>(I)) {
696 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000697 if (Offset >= SL->getSizeInBytes())
698 return nullptr;
699
Peter Collingbourne87867542016-12-09 01:10:11 +0000700 unsigned Op = SL->getElementContainingOffset(Offset);
701 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
702 Offset - SL->getElementOffset(Op));
703 }
704 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000705 ArrayType *VTableTy = C->getType();
706 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
707
Peter Collingbourne87867542016-12-09 01:10:11 +0000708 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000709 if (Op >= C->getNumOperands())
710 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000711
Peter Collingbourne87867542016-12-09 01:10:11 +0000712 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
713 Offset % ElemSize);
714 }
715 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000716}
717
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000718bool DevirtModule::tryFindVirtualCallTargets(
719 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000720 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
721 for (const TypeMemberInfo &TM : TypeMemberInfos) {
722 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000723 return false;
724
Peter Collingbourne87867542016-12-09 01:10:11 +0000725 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
726 TM.Offset + ByteOffset);
727 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000728 return false;
729
Peter Collingbourne87867542016-12-09 01:10:11 +0000730 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000731 if (!Fn)
732 return false;
733
734 // We can disregard __cxa_pure_virtual as a possible call target, as
735 // calls to pure virtuals are UB.
736 if (Fn->getName() == "__cxa_pure_virtual")
737 continue;
738
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000739 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000740 }
741
742 // Give up if we couldn't find any targets.
743 return !TargetsForSlot.empty();
744}
745
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000746void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000747 Constant *TheFn, bool &IsExported) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000748 auto Apply = [&](CallSiteInfo &CSInfo) {
749 for (auto &&VCallSite : CSInfo.CallSites) {
750 if (RemarksEnabled)
Sam Elliotte963c892017-08-21 16:57:21 +0000751 VCallSite.emitRemark("single-impl", TheFn->getName(), OREGetter);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000752 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
753 TheFn, VCallSite.CS.getCalledValue()->getType()));
754 // This use is no longer unsafe.
755 if (VCallSite.NumUnsafeUses)
756 --*VCallSite.NumUnsafeUses;
757 }
Peter Collingbourne29748562018-03-09 19:11:44 +0000758 if (CSInfo.isExported())
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000759 IsExported = true;
Peter Collingbourne29748562018-03-09 19:11:44 +0000760 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000761 };
762 Apply(SlotInfo.CSInfo);
763 for (auto &P : SlotInfo.ConstCSInfo)
764 Apply(P.second);
765}
766
Peter Collingbournee2367412017-02-15 02:13:08 +0000767bool DevirtModule::trySingleImplDevirt(
768 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000769 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000770 // See if the program contains a single implementation of this virtual
771 // function.
772 Function *TheFn = TargetsForSlot[0].Fn;
773 for (auto &&Target : TargetsForSlot)
774 if (TheFn != Target.Fn)
775 return false;
776
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000777 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000778 if (RemarksEnabled)
779 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000780
781 bool IsExported = false;
782 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
783 if (!IsExported)
784 return false;
785
786 // If the only implementation has local linkage, we must promote to external
787 // to make it visible to thin LTO objects. We can only get here during the
788 // ThinLTO export phase.
789 if (TheFn->hasLocalLinkage()) {
Peter Collingbourne88a58cf2017-09-08 00:10:53 +0000790 std::string NewName = (TheFn->getName() + "$merged").str();
791
792 // Since we are renaming the function, any comdats with the same name must
793 // also be renamed. This is required when targeting COFF, as the comdat name
794 // must match one of the names of the symbols in the comdat.
795 if (Comdat *C = TheFn->getComdat()) {
796 if (C->getName() == TheFn->getName()) {
797 Comdat *NewC = M.getOrInsertComdat(NewName);
798 NewC->setSelectionKind(C->getSelectionKind());
799 for (GlobalObject &GO : M.global_objects())
800 if (GO.getComdat() == C)
801 GO.setComdat(NewC);
802 }
803 }
804
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000805 TheFn->setLinkage(GlobalValue::ExternalLinkage);
806 TheFn->setVisibility(GlobalValue::HiddenVisibility);
Peter Collingbourne88a58cf2017-09-08 00:10:53 +0000807 TheFn->setName(NewName);
Peter Collingbourne2325bb32017-03-04 01:31:01 +0000808 }
809
810 Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
811 Res->SingleImplName = TheFn->getName();
812
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000813 return true;
814}
815
Peter Collingbourne29748562018-03-09 19:11:44 +0000816void DevirtModule::tryICallBranchFunnel(
817 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
818 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
819 Triple T(M.getTargetTriple());
820 if (T.getArch() != Triple::x86_64)
821 return;
822
823 const unsigned kBranchFunnelThreshold = 10;
824 if (TargetsForSlot.size() > kBranchFunnelThreshold)
825 return;
826
827 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
828 if (!HasNonDevirt)
829 for (auto &P : SlotInfo.ConstCSInfo)
830 if (!P.second.AllCallSitesDevirted) {
831 HasNonDevirt = true;
832 break;
833 }
834
835 if (!HasNonDevirt)
836 return;
837
838 FunctionType *FT =
839 FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
840 Function *JT;
841 if (isa<MDString>(Slot.TypeID)) {
842 JT = Function::Create(FT, Function::ExternalLinkage,
843 getGlobalName(Slot, {}, "branch_funnel"), &M);
844 JT->setVisibility(GlobalValue::HiddenVisibility);
845 } else {
846 JT = Function::Create(FT, Function::InternalLinkage, "branch_funnel", &M);
847 }
848 JT->addAttribute(1, Attribute::Nest);
849
850 std::vector<Value *> JTArgs;
851 JTArgs.push_back(JT->arg_begin());
852 for (auto &T : TargetsForSlot) {
853 JTArgs.push_back(getMemberAddr(T.TM));
854 JTArgs.push_back(T.Fn);
855 }
856
857 BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
858 Constant *Intr =
859 Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
860
861 auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
862 CI->setTailCallKind(CallInst::TCK_MustTail);
863 ReturnInst::Create(M.getContext(), nullptr, BB);
864
865 bool IsExported = false;
866 applyICallBranchFunnel(SlotInfo, JT, IsExported);
867 if (IsExported)
868 Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
869}
870
871void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
872 Constant *JT, bool &IsExported) {
873 auto Apply = [&](CallSiteInfo &CSInfo) {
874 if (CSInfo.isExported())
875 IsExported = true;
876 if (CSInfo.AllCallSitesDevirted)
877 return;
878 for (auto &&VCallSite : CSInfo.CallSites) {
879 CallSite CS = VCallSite.CS;
880
881 // Jump tables are only profitable if the retpoline mitigation is enabled.
882 Attribute FSAttr = CS.getCaller()->getFnAttribute("target-features");
883 if (FSAttr.hasAttribute(Attribute::None) ||
884 !FSAttr.getValueAsString().contains("+retpoline"))
885 continue;
886
887 if (RemarksEnabled)
888 VCallSite.emitRemark("branch-funnel", JT->getName(), OREGetter);
889
890 // Pass the address of the vtable in the nest register, which is r10 on
891 // x86_64.
892 std::vector<Type *> NewArgs;
893 NewArgs.push_back(Int8PtrTy);
894 for (Type *T : CS.getFunctionType()->params())
895 NewArgs.push_back(T);
896 PointerType *NewFT = PointerType::getUnqual(
897 FunctionType::get(CS.getFunctionType()->getReturnType(), NewArgs,
898 CS.getFunctionType()->isVarArg()));
899
900 IRBuilder<> IRB(CS.getInstruction());
901 std::vector<Value *> Args;
902 Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
903 for (unsigned I = 0; I != CS.getNumArgOperands(); ++I)
904 Args.push_back(CS.getArgOperand(I));
905
906 CallSite NewCS;
907 if (CS.isCall())
908 NewCS = IRB.CreateCall(IRB.CreateBitCast(JT, NewFT), Args);
909 else
910 NewCS = IRB.CreateInvoke(
911 IRB.CreateBitCast(JT, NewFT),
912 cast<InvokeInst>(CS.getInstruction())->getNormalDest(),
913 cast<InvokeInst>(CS.getInstruction())->getUnwindDest(), Args);
914 NewCS.setCallingConv(CS.getCallingConv());
915
916 AttributeList Attrs = CS.getAttributes();
917 std::vector<AttributeSet> NewArgAttrs;
918 NewArgAttrs.push_back(AttributeSet::get(
919 M.getContext(), ArrayRef<Attribute>{Attribute::get(
920 M.getContext(), Attribute::Nest)}));
921 for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
922 NewArgAttrs.push_back(Attrs.getParamAttributes(I));
923 NewCS.setAttributes(
924 AttributeList::get(M.getContext(), Attrs.getFnAttributes(),
925 Attrs.getRetAttributes(), NewArgAttrs));
926
927 CS->replaceAllUsesWith(NewCS.getInstruction());
928 CS->eraseFromParent();
929
930 // This use is no longer unsafe.
931 if (VCallSite.NumUnsafeUses)
932 --*VCallSite.NumUnsafeUses;
933 }
934 // Don't mark as devirtualized because there may be callers compiled without
935 // retpoline mitigation, which would mean that they are lowered to
936 // llvm.type.test and therefore require an llvm.type.test resolution for the
937 // type identifier.
938 };
939 Apply(SlotInfo.CSInfo);
940 for (auto &P : SlotInfo.ConstCSInfo)
941 Apply(P.second);
942}
943
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000944bool DevirtModule::tryEvaluateFunctionsWithArgs(
945 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000946 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000947 // Evaluate each function and store the result in each target's RetVal
948 // field.
949 for (VirtualCallTarget &Target : TargetsForSlot) {
950 if (Target.Fn->arg_size() != Args.size() + 1)
951 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000952
953 Evaluator Eval(M.getDataLayout(), nullptr);
954 SmallVector<Constant *, 2> EvalArgs;
955 EvalArgs.push_back(
956 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000957 for (unsigned I = 0; I != Args.size(); ++I) {
958 auto *ArgTy = dyn_cast<IntegerType>(
959 Target.Fn->getFunctionType()->getParamType(I + 1));
960 if (!ArgTy)
961 return false;
962 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
963 }
964
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000965 Constant *RetVal;
966 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
967 !isa<ConstantInt>(RetVal))
968 return false;
969 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
970 }
971 return true;
972}
973
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000974void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
975 uint64_t TheRetVal) {
976 for (auto Call : CSInfo.CallSites)
977 Call.replaceAndErase(
Sam Elliotte963c892017-08-21 16:57:21 +0000978 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000979 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
Peter Collingbourne59675ba2017-03-10 20:09:11 +0000980 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000981}
982
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000983bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000984 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
985 WholeProgramDevirtResolution::ByArg *Res) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000986 // Uniform return value optimization. If all functions return the same
987 // constant, replace all calls with that constant.
988 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
989 for (const VirtualCallTarget &Target : TargetsForSlot)
990 if (Target.RetVal != TheRetVal)
991 return false;
992
Peter Collingbourne77a8d562017-03-04 01:34:53 +0000993 if (CSInfo.isExported()) {
994 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
995 Res->Info = TheRetVal;
996 }
997
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000998 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000999 if (RemarksEnabled)
1000 for (auto &&Target : TargetsForSlot)
1001 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001002 return true;
1003}
1004
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001005std::string DevirtModule::getGlobalName(VTableSlot Slot,
1006 ArrayRef<uint64_t> Args,
1007 StringRef Name) {
1008 std::string FullName = "__typeid_";
1009 raw_string_ostream OS(FullName);
1010 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1011 for (uint64_t Arg : Args)
1012 OS << '_' << Arg;
1013 OS << '_' << Name;
1014 return OS.str();
1015}
1016
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001017bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1018 Triple T(M.getTargetTriple());
1019 return (T.getArch() == Triple::x86 || T.getArch() == Triple::x86_64) &&
1020 T.getObjectFormat() == Triple::ELF;
1021}
1022
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001023void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1024 StringRef Name, Constant *C) {
1025 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1026 getGlobalName(Slot, Args, Name), C, &M);
1027 GA->setVisibility(GlobalValue::HiddenVisibility);
1028}
1029
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001030void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1031 StringRef Name, uint32_t Const,
1032 uint32_t &Storage) {
1033 if (shouldExportConstantsAsAbsoluteSymbols()) {
1034 exportGlobal(
1035 Slot, Args, Name,
1036 ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1037 return;
1038 }
1039
1040 Storage = Const;
1041}
1042
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001043Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001044 StringRef Name) {
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001045 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
1046 auto *GV = dyn_cast<GlobalVariable>(C);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001047 if (GV)
1048 GV->setVisibility(GlobalValue::HiddenVisibility);
1049 return C;
1050}
1051
1052Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1053 StringRef Name, IntegerType *IntTy,
1054 uint32_t Storage) {
1055 if (!shouldExportConstantsAsAbsoluteSymbols())
1056 return ConstantInt::get(IntTy, Storage);
1057
1058 Constant *C = importGlobal(Slot, Args, Name);
1059 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1060 C = ConstantExpr::getPtrToInt(C, IntTy);
1061
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001062 // We only need to set metadata if the global is newly created, in which
1063 // case it would not have hidden visibility.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001064 if (GV->getMetadata(LLVMContext::MD_absolute_symbol))
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001065 return C;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001066
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001067 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1068 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1069 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1070 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1071 MDNode::get(M.getContext(), {MinC, MaxC}));
1072 };
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001073 unsigned AbsWidth = IntTy->getBitWidth();
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001074 if (AbsWidth == IntPtrTy->getBitWidth())
1075 SetAbsRange(~0ull, ~0ull); // Full set.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001076 else
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001077 SetAbsRange(0, 1ull << AbsWidth);
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001078 return C;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001079}
1080
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001081void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1082 bool IsOne,
1083 Constant *UniqueMemberAddr) {
1084 for (auto &&Call : CSInfo.CallSites) {
1085 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001086 Value *Cmp =
1087 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
1088 B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001089 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
Sam Elliotte963c892017-08-21 16:57:21 +00001090 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1091 Cmp);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001092 }
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001093 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001094}
1095
Peter Collingbourne29748562018-03-09 19:11:44 +00001096Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1097 Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
1098 return ConstantExpr::getGetElementPtr(Int8Ty, C,
1099 ConstantInt::get(Int64Ty, M->Offset));
1100}
1101
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001102bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001103 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001104 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1105 VTableSlot Slot, ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001106 // IsOne controls whether we look for a 0 or a 1.
1107 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +00001108 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001109 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +00001110 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001111 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001112 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001113 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001114 }
1115 }
1116
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001117 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001118 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001119 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001120
Peter Collingbourne29748562018-03-09 19:11:44 +00001121 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001122 if (CSInfo.isExported()) {
1123 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
1124 Res->Info = IsOne;
1125
1126 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1127 }
1128
1129 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001130 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1131 UniqueMemberAddr);
1132
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001133 // Update devirtualization statistics for targets.
1134 if (RemarksEnabled)
1135 for (auto &&Target : TargetsForSlot)
1136 Target.WasDevirt = true;
1137
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001138 return true;
1139 };
1140
1141 if (BitWidth == 1) {
1142 if (tryUniqueRetValOptFor(true))
1143 return true;
1144 if (tryUniqueRetValOptFor(false))
1145 return true;
1146 }
1147 return false;
1148}
1149
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001150void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1151 Constant *Byte, Constant *Bit) {
1152 for (auto Call : CSInfo.CallSites) {
1153 auto *RetType = cast<IntegerType>(Call.CS.getType());
1154 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne001052a2017-08-22 21:41:19 +00001155 Value *Addr =
1156 B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001157 if (RetType->getBitWidth() == 1) {
1158 Value *Bits = B.CreateLoad(Addr);
1159 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1160 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1161 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
Sam Elliotte963c892017-08-21 16:57:21 +00001162 OREGetter, IsBitSet);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001163 } else {
1164 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
1165 Value *Val = B.CreateLoad(RetType, ValAddr);
Sam Elliotte963c892017-08-21 16:57:21 +00001166 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1167 OREGetter, Val);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001168 }
1169 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001170 CSInfo.markDevirt();
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001171}
1172
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001173bool DevirtModule::tryVirtualConstProp(
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001174 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1175 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001176 // This only works if the function returns an integer.
1177 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
1178 if (!RetType)
1179 return false;
1180 unsigned BitWidth = RetType->getBitWidth();
1181 if (BitWidth > 64)
1182 return false;
1183
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001184 // Make sure that each function is defined, does not access memory, takes at
1185 // least one argument, does not use its first argument (which we assume is
1186 // 'this'), and has the same return type.
Peter Collingbourne37317f12017-02-17 18:17:04 +00001187 //
1188 // Note that we test whether this copy of the function is readnone, rather
1189 // than testing function attributes, which must hold for any copy of the
1190 // function, even a less optimized version substituted at link time. This is
1191 // sound because the virtual constant propagation optimizations effectively
1192 // inline all implementations of the virtual function into each call site,
1193 // rather than using function attributes to perform local optimization.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001194 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne37317f12017-02-17 18:17:04 +00001195 if (Target.Fn->isDeclaration() ||
1196 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
1197 MAK_ReadNone ||
Peter Collingbourne17febdb2017-02-09 23:46:26 +00001198 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001199 Target.Fn->getReturnType() != RetType)
1200 return false;
1201 }
1202
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001203 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001204 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1205 continue;
1206
Peter Collingbourne77a8d562017-03-04 01:34:53 +00001207 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1208 if (Res)
1209 ResByArg = &Res->ResByArg[CSByConstantArg.first];
1210
1211 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001212 continue;
1213
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001214 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1215 ResByArg, Slot, CSByConstantArg.first))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001216 continue;
1217
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001218 // Find an allocation offset in bits in all vtables associated with the
1219 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001220 uint64_t AllocBefore =
1221 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1222 uint64_t AllocAfter =
1223 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1224
1225 // Calculate the total amount of padding needed to store a value at both
1226 // ends of the object.
1227 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1228 for (auto &&Target : TargetsForSlot) {
1229 TotalPaddingBefore += std::max<int64_t>(
1230 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1231 TotalPaddingAfter += std::max<int64_t>(
1232 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1233 }
1234
1235 // If the amount of padding is too large, give up.
1236 // FIXME: do something smarter here.
1237 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1238 continue;
1239
1240 // Calculate the offset to the value as a (possibly negative) byte offset
1241 // and (if applicable) a bit offset, and store the values in the targets.
1242 int64_t OffsetByte;
1243 uint64_t OffsetBit;
1244 if (TotalPaddingBefore <= TotalPaddingAfter)
1245 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1246 OffsetBit);
1247 else
1248 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1249 OffsetBit);
1250
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001251 if (RemarksEnabled)
1252 for (auto &&Target : TargetsForSlot)
1253 Target.WasDevirt = true;
1254
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001255
1256 if (CSByConstantArg.second.isExported()) {
1257 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001258 exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
1259 ResByArg->Byte);
1260 exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
1261 ResByArg->Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001262 }
1263
1264 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001265 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
1266 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001267 applyVirtualConstProp(CSByConstantArg.second,
1268 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001269 }
1270 return true;
1271}
1272
1273void DevirtModule::rebuildGlobal(VTableBits &B) {
1274 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1275 return;
1276
1277 // Align each byte array to pointer width.
1278 unsigned PointerSize = M.getDataLayout().getPointerSize();
1279 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
1280 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
1281
1282 // Before was stored in reverse order; flip it now.
1283 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1284 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1285
1286 // Build an anonymous global containing the before bytes, followed by the
1287 // original initializer, followed by the after bytes.
1288 auto NewInit = ConstantStruct::getAnon(
1289 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1290 B.GV->getInitializer(),
1291 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1292 auto NewGV =
1293 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1294 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1295 NewGV->setSection(B.GV->getSection());
1296 NewGV->setComdat(B.GV->getComdat());
1297
Peter Collingbourne0312f612016-06-25 00:23:04 +00001298 // Copy the original vtable's metadata to the anonymous global, adjusting
1299 // offsets as required.
1300 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1301
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001302 // Build an alias named after the original global, pointing at the second
1303 // element (the original initializer).
1304 auto Alias = GlobalAlias::create(
1305 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1306 ConstantExpr::getGetElementPtr(
1307 NewInit->getType(), NewGV,
1308 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1309 ConstantInt::get(Int32Ty, 1)}),
1310 &M);
1311 Alias->setVisibility(B.GV->getVisibility());
1312 Alias->takeName(B.GV);
1313
1314 B.GV->replaceAllUsesWith(Alias);
1315 B.GV->eraseFromParent();
1316}
1317
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001318bool DevirtModule::areRemarksEnabled() {
1319 const auto &FL = M.getFunctionList();
1320 if (FL.empty())
1321 return false;
1322 const Function &Fn = FL.front();
Adam Nemetde53bfb2017-02-23 23:11:11 +00001323
1324 const auto &BBL = Fn.getBasicBlockList();
1325 if (BBL.empty())
1326 return false;
1327 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001328 return DI.isEnabled();
1329}
1330
Peter Collingbourne0312f612016-06-25 00:23:04 +00001331void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
1332 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001333 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001334 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1335 // points to a member of the type identifier %md. Group calls by (type ID,
1336 // offset) pair (effectively the identity of the virtual function) and store
1337 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001338 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001339 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001340 I != E;) {
1341 auto CI = dyn_cast<CallInst>(I->getUser());
1342 ++I;
1343 if (!CI)
1344 continue;
1345
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001346 // Search for virtual calls based on %p and add them to DevirtCalls.
1347 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001348 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +00001349 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001350
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001351 // If we found any, add them to CallSlots. Only do this if we haven't seen
1352 // the vtable pointer before, as it may have been CSE'd with pointers from
1353 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001354 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001355 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001356 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1357 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001358 if (SeenPtrs.insert(Ptr).second) {
1359 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne001052a2017-08-22 21:41:19 +00001360 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +00001361 }
1362 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001363 }
1364
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001365 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001366 for (auto Assume : Assumes)
1367 Assume->eraseFromParent();
1368 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1369 // may use the vtable argument later.
1370 if (CI->use_empty())
1371 CI->eraseFromParent();
1372 }
Peter Collingbourne0312f612016-06-25 00:23:04 +00001373}
1374
1375void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1376 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1377
1378 for (auto I = TypeCheckedLoadFunc->use_begin(),
1379 E = TypeCheckedLoadFunc->use_end();
1380 I != E;) {
1381 auto CI = dyn_cast<CallInst>(I->getUser());
1382 ++I;
1383 if (!CI)
1384 continue;
1385
1386 Value *Ptr = CI->getArgOperand(0);
1387 Value *Offset = CI->getArgOperand(1);
1388 Value *TypeIdValue = CI->getArgOperand(2);
1389 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1390
1391 SmallVector<DevirtCallSite, 1> DevirtCalls;
1392 SmallVector<Instruction *, 1> LoadedPtrs;
1393 SmallVector<Instruction *, 1> Preds;
1394 bool HasNonCallUses = false;
1395 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1396 HasNonCallUses, CI);
1397
1398 // Start by generating "pessimistic" code that explicitly loads the function
1399 // pointer from the vtable and performs the type check. If possible, we will
1400 // eliminate the load and the type check later.
1401
1402 // If possible, only generate the load at the point where it is used.
1403 // This helps avoid unnecessary spills.
1404 IRBuilder<> LoadB(
1405 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1406 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1407 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1408 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1409
1410 for (Instruction *LoadedPtr : LoadedPtrs) {
1411 LoadedPtr->replaceAllUsesWith(LoadedValue);
1412 LoadedPtr->eraseFromParent();
1413 }
1414
1415 // Likewise for the type test.
1416 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1417 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1418
1419 for (Instruction *Pred : Preds) {
1420 Pred->replaceAllUsesWith(TypeTestCall);
1421 Pred->eraseFromParent();
1422 }
1423
1424 // We have already erased any extractvalue instructions that refer to the
1425 // intrinsic call, but the intrinsic may have other non-extractvalue uses
1426 // (although this is unlikely). In that case, explicitly build a pair and
1427 // RAUW it.
1428 if (!CI->use_empty()) {
1429 Value *Pair = UndefValue::get(CI->getType());
1430 IRBuilder<> B(CI);
1431 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1432 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1433 CI->replaceAllUsesWith(Pair);
1434 }
1435
1436 // The number of unsafe uses is initially the number of uses.
1437 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1438 NumUnsafeUses = DevirtCalls.size();
1439
1440 // If the function pointer has a non-call user, we cannot eliminate the type
1441 // check, as one of those users may eventually call the pointer. Increment
1442 // the unsafe use count to make sure it cannot reach zero.
1443 if (HasNonCallUses)
1444 ++NumUnsafeUses;
1445 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +00001446 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1447 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +00001448 }
1449
1450 CI->eraseFromParent();
1451 }
1452}
1453
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001454void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001455 const TypeIdSummary *TidSummary =
Peter Collingbournef7691d82017-03-22 18:22:59 +00001456 ImportSummary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString());
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001457 if (!TidSummary)
1458 return;
1459 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1460 if (ResI == TidSummary->WPDRes.end())
1461 return;
1462 const WholeProgramDevirtResolution &Res = ResI->second;
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001463
1464 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1465 // The type of the function in the declaration is irrelevant because every
1466 // call site will cast it to the correct type.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001467 auto *SingleImpl = M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001468 Res.SingleImplName, Type::getVoidTy(M.getContext()));
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001469
1470 // This is the import phase so we should not be exporting anything.
1471 bool IsExported = false;
1472 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1473 assert(!IsExported);
1474 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001475
1476 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1477 auto I = Res.ResByArg.find(CSByConstantArg.first);
1478 if (I == Res.ResByArg.end())
1479 continue;
1480 auto &ResByArg = I->second;
1481 // FIXME: We should figure out what to do about the "function name" argument
1482 // to the apply* functions, as the function names are unavailable during the
1483 // importing phase. For now we just pass the empty string. This does not
1484 // impact correctness because the function names are just used for remarks.
1485 switch (ResByArg.TheKind) {
1486 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1487 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1488 break;
Peter Collingbourne59675ba2017-03-10 20:09:11 +00001489 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1490 Constant *UniqueMemberAddr =
1491 importGlobal(Slot, CSByConstantArg.first, "unique_member");
1492 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1493 UniqueMemberAddr);
1494 break;
1495 }
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001496 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
Peter Collingbourneb15a35e2017-09-11 22:34:42 +00001497 Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
1498 Int32Ty, ResByArg.Byte);
1499 Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
1500 ResByArg.Bit);
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001501 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
Adrian Prantl0e6694d2017-12-19 22:05:25 +00001502 break;
Peter Collingbourne14dcf022017-03-10 20:13:58 +00001503 }
Peter Collingbourne0152c812017-03-09 01:11:15 +00001504 default:
1505 break;
1506 }
1507 }
Peter Collingbourne29748562018-03-09 19:11:44 +00001508
1509 if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
1510 auto *JT = M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
1511 Type::getVoidTy(M.getContext()));
1512 bool IsExported = false;
1513 applyICallBranchFunnel(SlotInfo, JT, IsExported);
1514 assert(!IsExported);
1515 }
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001516}
1517
1518void DevirtModule::removeRedundantTypeTests() {
1519 auto True = ConstantInt::getTrue(M.getContext());
1520 for (auto &&U : NumUnsafeUsesForTypeTest) {
1521 if (U.second == 0) {
1522 U.first->replaceAllUsesWith(True);
1523 U.first->eraseFromParent();
1524 }
1525 }
1526}
1527
Peter Collingbourne0312f612016-06-25 00:23:04 +00001528bool DevirtModule::run() {
1529 Function *TypeTestFunc =
1530 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1531 Function *TypeCheckedLoadFunc =
1532 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1533 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1534
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001535 // Normally if there are no users of the devirtualization intrinsics in the
1536 // module, this pass has nothing to do. But if we are exporting, we also need
1537 // to handle any users that appear only in the function summaries.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001538 if (!ExportSummary &&
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001539 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
Peter Collingbourne0312f612016-06-25 00:23:04 +00001540 AssumeFunc->use_empty()) &&
1541 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1542 return false;
1543
1544 if (TypeTestFunc && AssumeFunc)
1545 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1546
1547 if (TypeCheckedLoadFunc)
1548 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001549
Peter Collingbournef7691d82017-03-22 18:22:59 +00001550 if (ImportSummary) {
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001551 for (auto &S : CallSlots)
1552 importResolution(S.first, S.second);
1553
1554 removeRedundantTypeTests();
1555
1556 // The rest of the code is only necessary when exporting or during regular
1557 // LTO, so we are done.
1558 return true;
1559 }
1560
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001561 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001562 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001563 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1564 buildTypeIdentifierMap(Bits, TypeIdMap);
1565 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001566 return true;
1567
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001568 // Collect information from summary about which calls to try to devirtualize.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001569 if (ExportSummary) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001570 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1571 for (auto &P : TypeIdMap) {
1572 if (auto *TypeId = dyn_cast<MDString>(P.first))
1573 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1574 TypeId);
1575 }
1576
Peter Collingbournef7691d82017-03-22 18:22:59 +00001577 for (auto &P : *ExportSummary) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001578 for (auto &S : P.second.SummaryList) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001579 auto *FS = dyn_cast<FunctionSummary>(S.get());
1580 if (!FS)
1581 continue;
1582 // FIXME: Only add live functions.
George Rimar5d8aea12017-03-10 10:31:56 +00001583 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1584 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001585 CallSlots[{MD, VF.Offset}]
1586 .CSInfo.markSummaryHasTypeTestAssumeUsers();
George Rimar5d8aea12017-03-10 10:31:56 +00001587 }
1588 }
1589 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1590 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
Peter Collingbourne29748562018-03-09 19:11:44 +00001591 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001592 }
1593 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001594 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001595 FS->type_test_assume_const_vcalls()) {
1596 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001597 CallSlots[{MD, VC.VFunc.Offset}]
George Rimar5d8aea12017-03-10 10:31:56 +00001598 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001599 .markSummaryHasTypeTestAssumeUsers();
George Rimar5d8aea12017-03-10 10:31:56 +00001600 }
1601 }
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001602 for (const FunctionSummary::ConstVCall &VC :
George Rimar5d8aea12017-03-10 10:31:56 +00001603 FS->type_checked_load_const_vcalls()) {
1604 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001605 CallSlots[{MD, VC.VFunc.Offset}]
1606 .ConstCSInfo[VC.Args]
Peter Collingbourne29748562018-03-09 19:11:44 +00001607 .addSummaryTypeCheckedLoadUser(FS);
George Rimar5d8aea12017-03-10 10:31:56 +00001608 }
1609 }
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001610 }
1611 }
1612 }
1613
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001614 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001615 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001616 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001617 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001618 // Search each of the members of the type identifier for the virtual
1619 // function implementation at offset S.first.ByteOffset, and add to
1620 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001621 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001622 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1623 S.first.ByteOffset)) {
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001624 WholeProgramDevirtResolution *Res = nullptr;
Peter Collingbournef7691d82017-03-22 18:22:59 +00001625 if (ExportSummary && isa<MDString>(S.first.TypeID))
1626 Res = &ExportSummary
Peter Collingbourne9a3f9792017-03-22 18:04:39 +00001627 ->getOrInsertTypeIdSummary(
1628 cast<MDString>(S.first.TypeID)->getString())
1629 .WPDRes[S.first.ByteOffset];
Peter Collingbourne2325bb32017-03-04 01:31:01 +00001630
Peter Collingbourne29748562018-03-09 19:11:44 +00001631 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res)) {
1632 DidVirtualConstProp |=
1633 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
1634
1635 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
1636 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001637
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001638 // Collect functions devirtualized at least for one call site for stats.
1639 if (RemarksEnabled)
1640 for (const auto &T : TargetsForSlot)
1641 if (T.WasDevirt)
1642 DevirtTargets[T.Fn->getName()] = T.Fn;
1643 }
1644
1645 // CFI-specific: if we are exporting and any llvm.type.checked.load
1646 // intrinsics were *not* devirtualized, we need to add the resulting
1647 // llvm.type.test intrinsics to the function summaries so that the
1648 // LowerTypeTests pass will export them.
Peter Collingbournef7691d82017-03-22 18:22:59 +00001649 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
Peter Collingbourneb406baa2017-03-04 01:23:30 +00001650 auto GUID =
1651 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1652 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1653 FS->addTypeTest(GUID);
1654 for (auto &CCS : S.second.ConstCSInfo)
1655 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1656 FS->addTypeTest(GUID);
1657 }
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001658 }
1659
1660 if (RemarksEnabled) {
1661 // Generate remarks for each devirtualized function.
1662 for (const auto &DT : DevirtTargets) {
1663 Function *F = DT.second;
Sam Elliotte963c892017-08-21 16:57:21 +00001664
Sam Elliotte963c892017-08-21 16:57:21 +00001665 using namespace ore;
Peter Collingbourne9110cb42018-01-05 00:27:51 +00001666 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
1667 << "devirtualized "
1668 << NV("FunctionName", F->getName()));
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001669 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001670 }
1671
Peter Collingbourne6d284fa2017-03-09 00:21:25 +00001672 removeRedundantTypeTests();
Peter Collingbourne0312f612016-06-25 00:23:04 +00001673
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001674 // Rebuild each global we touched as part of virtual constant propagation to
1675 // include the before and after bytes.
1676 if (DidVirtualConstProp)
1677 for (VTableBits &B : Bits)
1678 rebuildGlobal(B);
1679
1680 return true;
1681}