blob: 54e6fbd22f2740875ee9a114c0a6ac57c69c50dc [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//
28//===----------------------------------------------------------------------===//
29
30#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000031#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/DenseMapInfo.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000034#include "llvm/ADT/DenseSet.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000035#include "llvm/ADT/iterator_range.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000036#include "llvm/ADT/MapVector.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000037#include "llvm/ADT/SmallVector.h"
Peter Collingbourne7efd7502016-06-24 21:21:32 +000038#include "llvm/Analysis/TypeMetadataUtils.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000039#include "llvm/IR/CallSite.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
Ivan Krasinb05e06e2016-08-05 19:45:16 +000042#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000043#include "llvm/IR/DebugLoc.h"
44#include "llvm/IR/DerivedTypes.h"
Ivan Krasin54746452016-07-12 02:38:37 +000045#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000046#include "llvm/IR/Function.h"
47#include "llvm/IR/GlobalAlias.h"
48#include "llvm/IR/GlobalVariable.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000049#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000052#include "llvm/IR/Instructions.h"
53#include "llvm/IR/Intrinsics.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000054#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Metadata.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000056#include "llvm/IR/Module.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000057#include "llvm/IR/ModuleSummaryIndexYAML.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000058#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000059#include "llvm/PassRegistry.h"
60#include "llvm/PassSupport.h"
61#include "llvm/Support/Casting.h"
Peter Collingbourne2b33f652017-02-13 19:26:18 +000062#include "llvm/Support/Error.h"
63#include "llvm/Support/FileSystem.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000064#include "llvm/Support/MathExtras.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000065#include "llvm/Transforms/IPO.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000066#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000067#include <algorithm>
68#include <cstddef>
69#include <map>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000070#include <set>
Eugene Zelenkocdc71612016-08-11 17:20:18 +000071#include <string>
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000072
73using namespace llvm;
74using namespace wholeprogramdevirt;
75
76#define DEBUG_TYPE "wholeprogramdevirt"
77
Peter Collingbourne2b33f652017-02-13 19:26:18 +000078static cl::opt<PassSummaryAction> ClSummaryAction(
79 "wholeprogramdevirt-summary-action",
80 cl::desc("What to do with the summary when running this pass"),
81 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
82 clEnumValN(PassSummaryAction::Import, "import",
83 "Import typeid resolutions from summary and globals"),
84 clEnumValN(PassSummaryAction::Export, "export",
85 "Export typeid resolutions to summary and globals")),
86 cl::Hidden);
87
88static cl::opt<std::string> ClReadSummary(
89 "wholeprogramdevirt-read-summary",
90 cl::desc("Read summary from given YAML file before running pass"),
91 cl::Hidden);
92
93static cl::opt<std::string> ClWriteSummary(
94 "wholeprogramdevirt-write-summary",
95 cl::desc("Write summary to given YAML file after running pass"),
96 cl::Hidden);
97
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000098// Find the minimum offset that we may store a value of size Size bits at. If
99// IsAfter is set, look for an offset before the object, otherwise look for an
100// offset after the object.
101uint64_t
102wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
103 bool IsAfter, uint64_t Size) {
104 // Find a minimum offset taking into account only vtable sizes.
105 uint64_t MinByte = 0;
106 for (const VirtualCallTarget &Target : Targets) {
107 if (IsAfter)
108 MinByte = std::max(MinByte, Target.minAfterBytes());
109 else
110 MinByte = std::max(MinByte, Target.minBeforeBytes());
111 }
112
113 // Build a vector of arrays of bytes covering, for each target, a slice of the
114 // used region (see AccumBitVector::BytesUsed in
115 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
116 // this aligns the used regions to start at MinByte.
117 //
118 // In this example, A, B and C are vtables, # is a byte already allocated for
119 // a virtual function pointer, AAAA... (etc.) are the used regions for the
120 // vtables and Offset(X) is the value computed for the Offset variable below
121 // for X.
122 //
123 // Offset(A)
124 // | |
125 // |MinByte
126 // A: ################AAAAAAAA|AAAAAAAA
127 // B: ########BBBBBBBBBBBBBBBB|BBBB
128 // C: ########################|CCCCCCCCCCCCCCCC
129 // | Offset(B) |
130 //
131 // This code produces the slices of A, B and C that appear after the divider
132 // at MinByte.
133 std::vector<ArrayRef<uint8_t>> Used;
134 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000135 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
136 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000137 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
138 : MinByte - Target.minBeforeBytes();
139
140 // Disregard used regions that are smaller than Offset. These are
141 // effectively all-free regions that do not need to be checked.
142 if (VTUsed.size() > Offset)
143 Used.push_back(VTUsed.slice(Offset));
144 }
145
146 if (Size == 1) {
147 // Find a free bit in each member of Used.
148 for (unsigned I = 0;; ++I) {
149 uint8_t BitsUsed = 0;
150 for (auto &&B : Used)
151 if (I < B.size())
152 BitsUsed |= B[I];
153 if (BitsUsed != 0xff)
154 return (MinByte + I) * 8 +
155 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
156 }
157 } else {
158 // Find a free (Size/8) byte region in each member of Used.
159 // FIXME: see if alignment helps.
160 for (unsigned I = 0;; ++I) {
161 for (auto &&B : Used) {
162 unsigned Byte = 0;
163 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
164 if (B[I + Byte])
165 goto NextI;
166 ++Byte;
167 }
168 }
169 return (MinByte + I) * 8;
170 NextI:;
171 }
172 }
173}
174
175void wholeprogramdevirt::setBeforeReturnValues(
176 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
177 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
178 if (BitWidth == 1)
179 OffsetByte = -(AllocBefore / 8 + 1);
180 else
181 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
182 OffsetBit = AllocBefore % 8;
183
184 for (VirtualCallTarget &Target : Targets) {
185 if (BitWidth == 1)
186 Target.setBeforeBit(AllocBefore);
187 else
188 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
189 }
190}
191
192void wholeprogramdevirt::setAfterReturnValues(
193 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
194 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
195 if (BitWidth == 1)
196 OffsetByte = AllocAfter / 8;
197 else
198 OffsetByte = (AllocAfter + 7) / 8;
199 OffsetBit = AllocAfter % 8;
200
201 for (VirtualCallTarget &Target : Targets) {
202 if (BitWidth == 1)
203 Target.setAfterBit(AllocAfter);
204 else
205 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
206 }
207}
208
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000209VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
210 : Fn(Fn), TM(TM),
Ivan Krasin89439a72016-08-12 01:40:10 +0000211 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000212
213namespace {
214
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000215// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000216// tables, and the ByteOffset is the offset in bytes from the address point to
217// the virtual function pointer.
218struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000219 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000220 uint64_t ByteOffset;
221};
222
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000223} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000224
Peter Collingbourne9b656522016-02-09 23:01:38 +0000225namespace llvm {
226
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000227template <> struct DenseMapInfo<VTableSlot> {
228 static VTableSlot getEmptyKey() {
229 return {DenseMapInfo<Metadata *>::getEmptyKey(),
230 DenseMapInfo<uint64_t>::getEmptyKey()};
231 }
232 static VTableSlot getTombstoneKey() {
233 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
234 DenseMapInfo<uint64_t>::getTombstoneKey()};
235 }
236 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000237 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000238 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
239 }
240 static bool isEqual(const VTableSlot &LHS,
241 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000242 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000243 }
244};
245
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000246} // end namespace llvm
Peter Collingbourne9b656522016-02-09 23:01:38 +0000247
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000248namespace {
249
250// A virtual call site. VTable is the loaded virtual table pointer, and CS is
251// the indirect virtual call.
252struct VirtualCallSite {
253 Value *VTable;
254 CallSite CS;
255
Peter Collingbourne0312f612016-06-25 00:23:04 +0000256 // If non-null, this field points to the associated unsafe use count stored in
257 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
258 // of that field for details.
259 unsigned *NumUnsafeUses;
260
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000261 void emitRemark(const Twine &OptName, const Twine &TargetName) {
Ivan Krasin54746452016-07-12 02:38:37 +0000262 Function *F = CS.getCaller();
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000263 emitOptimizationRemark(
264 F->getContext(), DEBUG_TYPE, *F,
265 CS.getInstruction()->getDebugLoc(),
266 OptName + ": devirtualized a call to " + TargetName);
Ivan Krasin54746452016-07-12 02:38:37 +0000267 }
268
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000269 void replaceAndErase(const Twine &OptName, const Twine &TargetName,
270 bool RemarksEnabled, Value *New) {
271 if (RemarksEnabled)
272 emitRemark(OptName, TargetName);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000273 CS->replaceAllUsesWith(New);
274 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
275 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
276 II->getUnwindDest()->removePredecessor(II->getParent());
277 }
278 CS->eraseFromParent();
Peter Collingbourne0312f612016-06-25 00:23:04 +0000279 // This use is no longer unsafe.
280 if (NumUnsafeUses)
281 --*NumUnsafeUses;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000282 }
283};
284
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000285// Call site information collected for a specific VTableSlot and possibly a list
286// of constant integer arguments. The grouping by arguments is handled by the
287// VTableSlotInfo class.
288struct CallSiteInfo {
289 std::vector<VirtualCallSite> CallSites;
290};
291
292// Call site information collected for a specific VTableSlot.
293struct VTableSlotInfo {
294 // The set of call sites which do not have all constant integer arguments
295 // (excluding "this").
296 CallSiteInfo CSInfo;
297
298 // The set of call sites with all constant integer arguments (excluding
299 // "this"), grouped by argument list.
300 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
301
302 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
303
304private:
305 CallSiteInfo &findCallSiteInfo(CallSite CS);
306};
307
308CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
309 std::vector<uint64_t> Args;
310 auto *CI = dyn_cast<IntegerType>(CS.getType());
311 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
312 return CSInfo;
313 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
314 auto *CI = dyn_cast<ConstantInt>(Arg);
315 if (!CI || CI->getBitWidth() > 64)
316 return CSInfo;
317 Args.push_back(CI->getZExtValue());
318 }
319 return ConstCSInfo[Args];
320}
321
322void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
323 unsigned *NumUnsafeUses) {
324 findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses});
325}
326
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000327struct DevirtModule {
328 Module &M;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000329
330 PassSummaryAction Action;
331 ModuleSummaryIndex *Summary;
332
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000333 IntegerType *Int8Ty;
334 PointerType *Int8PtrTy;
335 IntegerType *Int32Ty;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000336 IntegerType *Int64Ty;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000337
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000338 bool RemarksEnabled;
339
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000340 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000341
Peter Collingbourne0312f612016-06-25 00:23:04 +0000342 // This map keeps track of the number of "unsafe" uses of a loaded function
343 // pointer. The key is the associated llvm.type.test intrinsic call generated
344 // by this pass. An unsafe use is one that calls the loaded function pointer
345 // directly. Every time we eliminate an unsafe use (for example, by
346 // devirtualizing it or by applying virtual constant propagation), we
347 // decrement the value stored in this map. If a value reaches zero, we can
348 // eliminate the type check by RAUWing the associated llvm.type.test call with
349 // true.
350 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
351
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000352 DevirtModule(Module &M, PassSummaryAction Action, ModuleSummaryIndex *Summary)
353 : M(M), Action(Action), Summary(Summary),
354 Int8Ty(Type::getInt8Ty(M.getContext())),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000355 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000356 Int32Ty(Type::getInt32Ty(M.getContext())),
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000357 Int64Ty(Type::getInt64Ty(M.getContext())),
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000358 RemarksEnabled(areRemarksEnabled()) {}
359
360 bool areRemarksEnabled();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000361
Peter Collingbourne0312f612016-06-25 00:23:04 +0000362 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
363 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
364
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000365 void buildTypeIdentifierMap(
366 std::vector<VTableBits> &Bits,
367 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
Peter Collingbourne87867542016-12-09 01:10:11 +0000368 Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000369 bool
370 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
371 const std::set<TypeMemberInfo> &TypeMemberInfos,
372 uint64_t ByteOffset);
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000373
374 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000375 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000376 VTableSlotInfo &SlotInfo);
377
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000378 bool tryEvaluateFunctionsWithArgs(
379 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000380 ArrayRef<uint64_t> Args);
381
382 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
383 uint64_t TheRetVal);
384 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
385 CallSiteInfo &CSInfo);
386
387 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
388 Constant *UniqueMemberAddr);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000389 bool tryUniqueRetValOpt(unsigned BitWidth,
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000390 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000391 CallSiteInfo &CSInfo);
392
393 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
394 Constant *Byte, Constant *Bit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000395 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000396 VTableSlotInfo &SlotInfo);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000397
398 void rebuildGlobal(VTableBits &B);
399
400 bool run();
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000401
402 // Lower the module using the action and summary passed as command line
403 // arguments. For testing purposes only.
404 static bool runForTesting(Module &M);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000405};
406
407struct WholeProgramDevirt : public ModulePass {
408 static char ID;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000409
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000410 bool UseCommandLine = false;
411
412 PassSummaryAction Action;
413 ModuleSummaryIndex *Summary;
414
415 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
416 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
417 }
418
419 WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary)
420 : ModulePass(ID), Action(Action), Summary(Summary) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000421 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
422 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000423
424 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000425 if (skipModule(M))
426 return false;
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000427 if (UseCommandLine)
428 return DevirtModule::runForTesting(M);
429 return DevirtModule(M, Action, Summary).run();
Andrew Kayloraa641a52016-04-22 22:06:11 +0000430 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000431};
432
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000433} // end anonymous namespace
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000434
435INITIALIZE_PASS(WholeProgramDevirt, "wholeprogramdevirt",
436 "Whole program devirtualization", false, false)
437char WholeProgramDevirt::ID = 0;
438
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000439ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action,
440 ModuleSummaryIndex *Summary) {
441 return new WholeProgramDevirt(Action, Summary);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000442}
443
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000444PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
445 ModuleAnalysisManager &) {
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000446 if (!DevirtModule(M, PassSummaryAction::None, nullptr).run())
Davide Italianod737dd22016-06-14 21:44:19 +0000447 return PreservedAnalyses::all();
448 return PreservedAnalyses::none();
449}
450
Peter Collingbourne2b33f652017-02-13 19:26:18 +0000451bool DevirtModule::runForTesting(Module &M) {
452 ModuleSummaryIndex Summary;
453
454 // Handle the command-line summary arguments. This code is for testing
455 // purposes only, so we handle errors directly.
456 if (!ClReadSummary.empty()) {
457 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
458 ": ");
459 auto ReadSummaryFile =
460 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
461
462 yaml::Input In(ReadSummaryFile->getBuffer());
463 In >> Summary;
464 ExitOnErr(errorCodeToError(In.error()));
465 }
466
467 bool Changed = DevirtModule(M, ClSummaryAction, &Summary).run();
468
469 if (!ClWriteSummary.empty()) {
470 ExitOnError ExitOnErr(
471 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
472 std::error_code EC;
473 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
474 ExitOnErr(errorCodeToError(EC));
475
476 yaml::Output Out(OS);
477 Out << Summary;
478 }
479
480 return Changed;
481}
482
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000483void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000484 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000485 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000486 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000487 Bits.reserve(M.getGlobalList().size());
488 SmallVector<MDNode *, 2> Types;
489 for (GlobalVariable &GV : M.globals()) {
490 Types.clear();
491 GV.getMetadata(LLVMContext::MD_type, Types);
492 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000493 continue;
494
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000495 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000496 if (!BitsPtr) {
497 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000498 Bits.back().GV = &GV;
499 Bits.back().ObjectSize =
500 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000501 BitsPtr = &Bits.back();
502 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000503
504 for (MDNode *Type : Types) {
505 auto TypeID = Type->getOperand(1).get();
506
507 uint64_t Offset =
508 cast<ConstantInt>(
509 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
510 ->getZExtValue();
511
512 TypeIdMap[TypeID].insert({BitsPtr, Offset});
513 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000514 }
515}
516
Peter Collingbourne87867542016-12-09 01:10:11 +0000517Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
518 if (I->getType()->isPointerTy()) {
519 if (Offset == 0)
520 return I;
521 return nullptr;
522 }
523
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000524 const DataLayout &DL = M.getDataLayout();
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000525
526 if (auto *C = dyn_cast<ConstantStruct>(I)) {
527 const StructLayout *SL = DL.getStructLayout(C->getType());
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000528 if (Offset >= SL->getSizeInBytes())
529 return nullptr;
530
Peter Collingbourne87867542016-12-09 01:10:11 +0000531 unsigned Op = SL->getElementContainingOffset(Offset);
532 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
533 Offset - SL->getElementOffset(Op));
534 }
535 if (auto *C = dyn_cast<ConstantArray>(I)) {
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000536 ArrayType *VTableTy = C->getType();
537 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
538
Peter Collingbourne87867542016-12-09 01:10:11 +0000539 unsigned Op = Offset / ElemSize;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000540 if (Op >= C->getNumOperands())
541 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000542
Peter Collingbourne87867542016-12-09 01:10:11 +0000543 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
544 Offset % ElemSize);
545 }
546 return nullptr;
Peter Collingbourne7a1e5bb2016-12-09 00:33:27 +0000547}
548
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000549bool DevirtModule::tryFindVirtualCallTargets(
550 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000551 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
552 for (const TypeMemberInfo &TM : TypeMemberInfos) {
553 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000554 return false;
555
Peter Collingbourne87867542016-12-09 01:10:11 +0000556 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
557 TM.Offset + ByteOffset);
558 if (!Ptr)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000559 return false;
560
Peter Collingbourne87867542016-12-09 01:10:11 +0000561 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000562 if (!Fn)
563 return false;
564
565 // We can disregard __cxa_pure_virtual as a possible call target, as
566 // calls to pure virtuals are UB.
567 if (Fn->getName() == "__cxa_pure_virtual")
568 continue;
569
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000570 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000571 }
572
573 // Give up if we couldn't find any targets.
574 return !TargetsForSlot.empty();
575}
576
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000577void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
578 Constant *TheFn) {
579 auto Apply = [&](CallSiteInfo &CSInfo) {
580 for (auto &&VCallSite : CSInfo.CallSites) {
581 if (RemarksEnabled)
582 VCallSite.emitRemark("single-impl", TheFn->getName());
583 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
584 TheFn, VCallSite.CS.getCalledValue()->getType()));
585 // This use is no longer unsafe.
586 if (VCallSite.NumUnsafeUses)
587 --*VCallSite.NumUnsafeUses;
588 }
589 };
590 Apply(SlotInfo.CSInfo);
591 for (auto &P : SlotInfo.ConstCSInfo)
592 Apply(P.second);
593}
594
Peter Collingbournee2367412017-02-15 02:13:08 +0000595bool DevirtModule::trySingleImplDevirt(
596 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000597 VTableSlotInfo &SlotInfo) {
Peter Collingbournee2367412017-02-15 02:13:08 +0000598 // See if the program contains a single implementation of this virtual
599 // function.
600 Function *TheFn = TargetsForSlot[0].Fn;
601 for (auto &&Target : TargetsForSlot)
602 if (TheFn != Target.Fn)
603 return false;
604
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000605 // If so, update each call site to call that implementation directly.
Peter Collingbournee2367412017-02-15 02:13:08 +0000606 if (RemarksEnabled)
607 TargetsForSlot[0].WasDevirt = true;
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000608 applySingleImplDevirt(SlotInfo, TheFn);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000609 return true;
610}
611
612bool DevirtModule::tryEvaluateFunctionsWithArgs(
613 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000614 ArrayRef<uint64_t> Args) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000615 // Evaluate each function and store the result in each target's RetVal
616 // field.
617 for (VirtualCallTarget &Target : TargetsForSlot) {
618 if (Target.Fn->arg_size() != Args.size() + 1)
619 return false;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000620
621 Evaluator Eval(M.getDataLayout(), nullptr);
622 SmallVector<Constant *, 2> EvalArgs;
623 EvalArgs.push_back(
624 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000625 for (unsigned I = 0; I != Args.size(); ++I) {
626 auto *ArgTy = dyn_cast<IntegerType>(
627 Target.Fn->getFunctionType()->getParamType(I + 1));
628 if (!ArgTy)
629 return false;
630 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
631 }
632
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000633 Constant *RetVal;
634 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
635 !isa<ConstantInt>(RetVal))
636 return false;
637 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
638 }
639 return true;
640}
641
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000642void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
643 uint64_t TheRetVal) {
644 for (auto Call : CSInfo.CallSites)
645 Call.replaceAndErase(
646 "uniform-ret-val", FnName, RemarksEnabled,
647 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
648}
649
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000650bool DevirtModule::tryUniformRetValOpt(
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000651 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000652 // Uniform return value optimization. If all functions return the same
653 // constant, replace all calls with that constant.
654 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
655 for (const VirtualCallTarget &Target : TargetsForSlot)
656 if (Target.RetVal != TheRetVal)
657 return false;
658
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000659 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000660 if (RemarksEnabled)
661 for (auto &&Target : TargetsForSlot)
662 Target.WasDevirt = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000663 return true;
664}
665
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000666void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
667 bool IsOne,
668 Constant *UniqueMemberAddr) {
669 for (auto &&Call : CSInfo.CallSites) {
670 IRBuilder<> B(Call.CS.getInstruction());
671 Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
672 Call.VTable, UniqueMemberAddr);
673 Cmp = B.CreateZExt(Cmp, Call.CS->getType());
674 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp);
675 }
676}
677
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000678bool DevirtModule::tryUniqueRetValOpt(
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000679 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000680 CallSiteInfo &CSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000681 // IsOne controls whether we look for a 0 or a 1.
682 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000683 const TypeMemberInfo *UniqueMember = nullptr;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000684 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +0000685 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000686 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000687 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000688 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000689 }
690 }
691
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000692 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000693 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000694 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000695
696 // Replace each call with the comparison.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000697 Constant *UniqueMemberAddr =
698 ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy);
699 UniqueMemberAddr = ConstantExpr::getGetElementPtr(
700 Int8Ty, UniqueMemberAddr,
701 ConstantInt::get(Int64Ty, UniqueMember->Offset));
702
703 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
704 UniqueMemberAddr);
705
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000706 // Update devirtualization statistics for targets.
707 if (RemarksEnabled)
708 for (auto &&Target : TargetsForSlot)
709 Target.WasDevirt = true;
710
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000711 return true;
712 };
713
714 if (BitWidth == 1) {
715 if (tryUniqueRetValOptFor(true))
716 return true;
717 if (tryUniqueRetValOptFor(false))
718 return true;
719 }
720 return false;
721}
722
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000723void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
724 Constant *Byte, Constant *Bit) {
725 for (auto Call : CSInfo.CallSites) {
726 auto *RetType = cast<IntegerType>(Call.CS.getType());
727 IRBuilder<> B(Call.CS.getInstruction());
728 Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte);
729 if (RetType->getBitWidth() == 1) {
730 Value *Bits = B.CreateLoad(Addr);
731 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
732 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
733 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
734 IsBitSet);
735 } else {
736 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
737 Value *Val = B.CreateLoad(RetType, ValAddr);
738 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val);
739 }
740 }
741}
742
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000743bool DevirtModule::tryVirtualConstProp(
744 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000745 VTableSlotInfo &SlotInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000746 // This only works if the function returns an integer.
747 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
748 if (!RetType)
749 return false;
750 unsigned BitWidth = RetType->getBitWidth();
751 if (BitWidth > 64)
752 return false;
753
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000754 // Make sure that each function is defined, does not access memory, takes at
755 // least one argument, does not use its first argument (which we assume is
756 // 'this'), and has the same return type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000757 for (VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne17febdb2017-02-09 23:46:26 +0000758 if (Target.Fn->isDeclaration() || !Target.Fn->doesNotAccessMemory() ||
759 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000760 Target.Fn->getReturnType() != RetType)
761 return false;
762 }
763
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000764 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000765 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
766 continue;
767
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000768 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second))
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000769 continue;
770
771 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second))
772 continue;
773
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000774 // Find an allocation offset in bits in all vtables associated with the
775 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000776 uint64_t AllocBefore =
777 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
778 uint64_t AllocAfter =
779 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
780
781 // Calculate the total amount of padding needed to store a value at both
782 // ends of the object.
783 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
784 for (auto &&Target : TargetsForSlot) {
785 TotalPaddingBefore += std::max<int64_t>(
786 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
787 TotalPaddingAfter += std::max<int64_t>(
788 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
789 }
790
791 // If the amount of padding is too large, give up.
792 // FIXME: do something smarter here.
793 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
794 continue;
795
796 // Calculate the offset to the value as a (possibly negative) byte offset
797 // and (if applicable) a bit offset, and store the values in the targets.
798 int64_t OffsetByte;
799 uint64_t OffsetBit;
800 if (TotalPaddingBefore <= TotalPaddingAfter)
801 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
802 OffsetBit);
803 else
804 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
805 OffsetBit);
806
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000807 if (RemarksEnabled)
808 for (auto &&Target : TargetsForSlot)
809 Target.WasDevirt = true;
810
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000811 // Rewrite each call to a load from OffsetByte/OffsetBit.
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000812 Constant *ByteConst = ConstantInt::get(Int64Ty, OffsetByte);
813 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
814 applyVirtualConstProp(CSByConstantArg.second,
815 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000816 }
817 return true;
818}
819
820void DevirtModule::rebuildGlobal(VTableBits &B) {
821 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
822 return;
823
824 // Align each byte array to pointer width.
825 unsigned PointerSize = M.getDataLayout().getPointerSize();
826 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
827 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
828
829 // Before was stored in reverse order; flip it now.
830 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
831 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
832
833 // Build an anonymous global containing the before bytes, followed by the
834 // original initializer, followed by the after bytes.
835 auto NewInit = ConstantStruct::getAnon(
836 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
837 B.GV->getInitializer(),
838 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
839 auto NewGV =
840 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
841 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
842 NewGV->setSection(B.GV->getSection());
843 NewGV->setComdat(B.GV->getComdat());
844
Peter Collingbourne0312f612016-06-25 00:23:04 +0000845 // Copy the original vtable's metadata to the anonymous global, adjusting
846 // offsets as required.
847 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
848
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000849 // Build an alias named after the original global, pointing at the second
850 // element (the original initializer).
851 auto Alias = GlobalAlias::create(
852 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
853 ConstantExpr::getGetElementPtr(
854 NewInit->getType(), NewGV,
855 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
856 ConstantInt::get(Int32Ty, 1)}),
857 &M);
858 Alias->setVisibility(B.GV->getVisibility());
859 Alias->takeName(B.GV);
860
861 B.GV->replaceAllUsesWith(Alias);
862 B.GV->eraseFromParent();
863}
864
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000865bool DevirtModule::areRemarksEnabled() {
866 const auto &FL = M.getFunctionList();
867 if (FL.empty())
868 return false;
869 const Function &Fn = FL.front();
Adam Nemet04758ba2016-09-27 22:19:23 +0000870 auto DI = OptimizationRemark(DEBUG_TYPE, Fn, DebugLoc(), "");
Ivan Krasinf3403fd2016-08-11 19:09:02 +0000871 return DI.isEnabled();
872}
873
Peter Collingbourne0312f612016-06-25 00:23:04 +0000874void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
875 Function *AssumeFunc) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000876 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000877 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
878 // points to a member of the type identifier %md. Group calls by (type ID,
879 // offset) pair (effectively the identity of the virtual function) and store
880 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000881 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000882 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000883 I != E;) {
884 auto CI = dyn_cast<CallInst>(I->getUser());
885 ++I;
886 if (!CI)
887 continue;
888
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000889 // Search for virtual calls based on %p and add them to DevirtCalls.
890 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000891 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourne0312f612016-06-25 00:23:04 +0000892 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000893
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000894 // If we found any, add them to CallSlots. Only do this if we haven't seen
895 // the vtable pointer before, as it may have been CSE'd with pointers from
896 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000897 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000898 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000899 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
900 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000901 if (SeenPtrs.insert(Ptr).second) {
902 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000903 CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0),
904 Call.CS, nullptr);
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000905 }
906 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000907 }
908
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000909 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000910 for (auto Assume : Assumes)
911 Assume->eraseFromParent();
912 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
913 // may use the vtable argument later.
914 if (CI->use_empty())
915 CI->eraseFromParent();
916 }
Peter Collingbourne0312f612016-06-25 00:23:04 +0000917}
918
919void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
920 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
921
922 for (auto I = TypeCheckedLoadFunc->use_begin(),
923 E = TypeCheckedLoadFunc->use_end();
924 I != E;) {
925 auto CI = dyn_cast<CallInst>(I->getUser());
926 ++I;
927 if (!CI)
928 continue;
929
930 Value *Ptr = CI->getArgOperand(0);
931 Value *Offset = CI->getArgOperand(1);
932 Value *TypeIdValue = CI->getArgOperand(2);
933 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
934
935 SmallVector<DevirtCallSite, 1> DevirtCalls;
936 SmallVector<Instruction *, 1> LoadedPtrs;
937 SmallVector<Instruction *, 1> Preds;
938 bool HasNonCallUses = false;
939 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
940 HasNonCallUses, CI);
941
942 // Start by generating "pessimistic" code that explicitly loads the function
943 // pointer from the vtable and performs the type check. If possible, we will
944 // eliminate the load and the type check later.
945
946 // If possible, only generate the load at the point where it is used.
947 // This helps avoid unnecessary spills.
948 IRBuilder<> LoadB(
949 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
950 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
951 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
952 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
953
954 for (Instruction *LoadedPtr : LoadedPtrs) {
955 LoadedPtr->replaceAllUsesWith(LoadedValue);
956 LoadedPtr->eraseFromParent();
957 }
958
959 // Likewise for the type test.
960 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
961 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
962
963 for (Instruction *Pred : Preds) {
964 Pred->replaceAllUsesWith(TypeTestCall);
965 Pred->eraseFromParent();
966 }
967
968 // We have already erased any extractvalue instructions that refer to the
969 // intrinsic call, but the intrinsic may have other non-extractvalue uses
970 // (although this is unlikely). In that case, explicitly build a pair and
971 // RAUW it.
972 if (!CI->use_empty()) {
973 Value *Pair = UndefValue::get(CI->getType());
974 IRBuilder<> B(CI);
975 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
976 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
977 CI->replaceAllUsesWith(Pair);
978 }
979
980 // The number of unsafe uses is initially the number of uses.
981 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
982 NumUnsafeUses = DevirtCalls.size();
983
984 // If the function pointer has a non-call user, we cannot eliminate the type
985 // check, as one of those users may eventually call the pointer. Increment
986 // the unsafe use count to make sure it cannot reach zero.
987 if (HasNonCallUses)
988 ++NumUnsafeUses;
989 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne50cbd7c2017-02-15 21:56:51 +0000990 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
991 &NumUnsafeUses);
Peter Collingbourne0312f612016-06-25 00:23:04 +0000992 }
993
994 CI->eraseFromParent();
995 }
996}
997
998bool DevirtModule::run() {
999 Function *TypeTestFunc =
1000 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1001 Function *TypeCheckedLoadFunc =
1002 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1003 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1004
1005 if ((!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
1006 AssumeFunc->use_empty()) &&
1007 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1008 return false;
1009
1010 if (TypeTestFunc && AssumeFunc)
1011 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1012
1013 if (TypeCheckedLoadFunc)
1014 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001015
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001016 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001017 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001018 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1019 buildTypeIdentifierMap(Bits, TypeIdMap);
1020 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001021 return true;
1022
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001023 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001024 bool DidVirtualConstProp = false;
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001025 std::map<std::string, Function*> DevirtTargets;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001026 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001027 // Search each of the members of the type identifier for the virtual
1028 // function implementation at offset S.first.ByteOffset, and add to
1029 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001030 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001031 if (!tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001032 S.first.ByteOffset))
1033 continue;
1034
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001035 if (!trySingleImplDevirt(TargetsForSlot, S.second) &&
1036 tryVirtualConstProp(TargetsForSlot, S.second))
1037 DidVirtualConstProp = true;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001038
Ivan Krasinf3403fd2016-08-11 19:09:02 +00001039 // Collect functions devirtualized at least for one call site for stats.
1040 if (RemarksEnabled)
1041 for (const auto &T : TargetsForSlot)
1042 if (T.WasDevirt)
1043 DevirtTargets[T.Fn->getName()] = T.Fn;
1044 }
1045
1046 if (RemarksEnabled) {
1047 // Generate remarks for each devirtualized function.
1048 for (const auto &DT : DevirtTargets) {
1049 Function *F = DT.second;
1050 DISubprogram *SP = F->getSubprogram();
1051 DebugLoc DL = SP ? DebugLoc::get(SP->getScopeLine(), 0, SP) : DebugLoc();
1052 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, DL,
1053 Twine("devirtualized ") + F->getName());
Ivan Krasinb05e06e2016-08-05 19:45:16 +00001054 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001055 }
1056
Peter Collingbourne0312f612016-06-25 00:23:04 +00001057 // If we were able to eliminate all unsafe uses for a type checked load,
1058 // eliminate the type test by replacing it with true.
1059 if (TypeCheckedLoadFunc) {
1060 auto True = ConstantInt::getTrue(M.getContext());
1061 for (auto &&U : NumUnsafeUsesForTypeTest) {
1062 if (U.second == 0) {
1063 U.first->replaceAllUsesWith(True);
1064 U.first->eraseFromParent();
1065 }
1066 }
1067 }
1068
Peter Collingbournedf49d1b2016-02-09 22:50:34 +00001069 // Rebuild each global we touched as part of virtual constant propagation to
1070 // include the before and after bytes.
1071 if (DidVirtualConstProp)
1072 for (VTableBits &B : Bits)
1073 rebuildGlobal(B);
1074
1075 return true;
1076}