blob: c19c667a51e5cf2e33939e244a4a75749e883e1c [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"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000032#include "llvm/ADT/DenseSet.h"
33#include "llvm/ADT/MapVector.h"
Peter Collingbourne7efd7502016-06-24 21:21:32 +000034#include "llvm/Analysis/TypeMetadataUtils.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000035#include "llvm/IR/CallSite.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/IRBuilder.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/Module.h"
42#include "llvm/Pass.h"
43#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000044#include "llvm/Transforms/IPO.h"
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000045#include "llvm/Transforms/Utils/Evaluator.h"
46#include "llvm/Transforms/Utils/Local.h"
47
48#include <set>
49
50using namespace llvm;
51using namespace wholeprogramdevirt;
52
53#define DEBUG_TYPE "wholeprogramdevirt"
54
55// Find the minimum offset that we may store a value of size Size bits at. If
56// IsAfter is set, look for an offset before the object, otherwise look for an
57// offset after the object.
58uint64_t
59wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
60 bool IsAfter, uint64_t Size) {
61 // Find a minimum offset taking into account only vtable sizes.
62 uint64_t MinByte = 0;
63 for (const VirtualCallTarget &Target : Targets) {
64 if (IsAfter)
65 MinByte = std::max(MinByte, Target.minAfterBytes());
66 else
67 MinByte = std::max(MinByte, Target.minBeforeBytes());
68 }
69
70 // Build a vector of arrays of bytes covering, for each target, a slice of the
71 // used region (see AccumBitVector::BytesUsed in
72 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
73 // this aligns the used regions to start at MinByte.
74 //
75 // In this example, A, B and C are vtables, # is a byte already allocated for
76 // a virtual function pointer, AAAA... (etc.) are the used regions for the
77 // vtables and Offset(X) is the value computed for the Offset variable below
78 // for X.
79 //
80 // Offset(A)
81 // | |
82 // |MinByte
83 // A: ################AAAAAAAA|AAAAAAAA
84 // B: ########BBBBBBBBBBBBBBBB|BBBB
85 // C: ########################|CCCCCCCCCCCCCCCC
86 // | Offset(B) |
87 //
88 // This code produces the slices of A, B and C that appear after the divider
89 // at MinByte.
90 std::vector<ArrayRef<uint8_t>> Used;
91 for (const VirtualCallTarget &Target : Targets) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +000092 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
93 : Target.TM->Bits->Before.BytesUsed;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +000094 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
95 : MinByte - Target.minBeforeBytes();
96
97 // Disregard used regions that are smaller than Offset. These are
98 // effectively all-free regions that do not need to be checked.
99 if (VTUsed.size() > Offset)
100 Used.push_back(VTUsed.slice(Offset));
101 }
102
103 if (Size == 1) {
104 // Find a free bit in each member of Used.
105 for (unsigned I = 0;; ++I) {
106 uint8_t BitsUsed = 0;
107 for (auto &&B : Used)
108 if (I < B.size())
109 BitsUsed |= B[I];
110 if (BitsUsed != 0xff)
111 return (MinByte + I) * 8 +
112 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
113 }
114 } else {
115 // Find a free (Size/8) byte region in each member of Used.
116 // FIXME: see if alignment helps.
117 for (unsigned I = 0;; ++I) {
118 for (auto &&B : Used) {
119 unsigned Byte = 0;
120 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
121 if (B[I + Byte])
122 goto NextI;
123 ++Byte;
124 }
125 }
126 return (MinByte + I) * 8;
127 NextI:;
128 }
129 }
130}
131
132void wholeprogramdevirt::setBeforeReturnValues(
133 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
134 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
135 if (BitWidth == 1)
136 OffsetByte = -(AllocBefore / 8 + 1);
137 else
138 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
139 OffsetBit = AllocBefore % 8;
140
141 for (VirtualCallTarget &Target : Targets) {
142 if (BitWidth == 1)
143 Target.setBeforeBit(AllocBefore);
144 else
145 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
146 }
147}
148
149void wholeprogramdevirt::setAfterReturnValues(
150 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
151 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
152 if (BitWidth == 1)
153 OffsetByte = AllocAfter / 8;
154 else
155 OffsetByte = (AllocAfter + 7) / 8;
156 OffsetBit = AllocAfter % 8;
157
158 for (VirtualCallTarget &Target : Targets) {
159 if (BitWidth == 1)
160 Target.setAfterBit(AllocAfter);
161 else
162 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
163 }
164}
165
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000166VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
167 : Fn(Fn), TM(TM),
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000168 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()) {}
169
170namespace {
171
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000172// A slot in a set of virtual tables. The TypeID identifies the set of virtual
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000173// tables, and the ByteOffset is the offset in bytes from the address point to
174// the virtual function pointer.
175struct VTableSlot {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000176 Metadata *TypeID;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000177 uint64_t ByteOffset;
178};
179
180}
181
Peter Collingbourne9b656522016-02-09 23:01:38 +0000182namespace llvm {
183
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000184template <> struct DenseMapInfo<VTableSlot> {
185 static VTableSlot getEmptyKey() {
186 return {DenseMapInfo<Metadata *>::getEmptyKey(),
187 DenseMapInfo<uint64_t>::getEmptyKey()};
188 }
189 static VTableSlot getTombstoneKey() {
190 return {DenseMapInfo<Metadata *>::getTombstoneKey(),
191 DenseMapInfo<uint64_t>::getTombstoneKey()};
192 }
193 static unsigned getHashValue(const VTableSlot &I) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000194 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000195 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
196 }
197 static bool isEqual(const VTableSlot &LHS,
198 const VTableSlot &RHS) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000199 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000200 }
201};
202
Peter Collingbourne9b656522016-02-09 23:01:38 +0000203}
204
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000205namespace {
206
207// A virtual call site. VTable is the loaded virtual table pointer, and CS is
208// the indirect virtual call.
209struct VirtualCallSite {
210 Value *VTable;
211 CallSite CS;
212
213 void replaceAndErase(Value *New) {
214 CS->replaceAllUsesWith(New);
215 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
216 BranchInst::Create(II->getNormalDest(), CS.getInstruction());
217 II->getUnwindDest()->removePredecessor(II->getParent());
218 }
219 CS->eraseFromParent();
220 }
221};
222
223struct DevirtModule {
224 Module &M;
225 IntegerType *Int8Ty;
226 PointerType *Int8PtrTy;
227 IntegerType *Int32Ty;
228
229 MapVector<VTableSlot, std::vector<VirtualCallSite>> CallSlots;
230
231 DevirtModule(Module &M)
232 : M(M), Int8Ty(Type::getInt8Ty(M.getContext())),
233 Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
234 Int32Ty(Type::getInt32Ty(M.getContext())) {}
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000235
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000236 void buildTypeIdentifierMap(
237 std::vector<VTableBits> &Bits,
238 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
239 bool
240 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
241 const std::set<TypeMemberInfo> &TypeMemberInfos,
242 uint64_t ByteOffset);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000243 bool trySingleImplDevirt(ArrayRef<VirtualCallTarget> TargetsForSlot,
244 MutableArrayRef<VirtualCallSite> CallSites);
245 bool tryEvaluateFunctionsWithArgs(
246 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
247 ArrayRef<ConstantInt *> Args);
248 bool tryUniformRetValOpt(IntegerType *RetType,
249 ArrayRef<VirtualCallTarget> TargetsForSlot,
250 MutableArrayRef<VirtualCallSite> CallSites);
251 bool tryUniqueRetValOpt(unsigned BitWidth,
252 ArrayRef<VirtualCallTarget> TargetsForSlot,
253 MutableArrayRef<VirtualCallSite> CallSites);
254 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
255 ArrayRef<VirtualCallSite> CallSites);
256
257 void rebuildGlobal(VTableBits &B);
258
259 bool run();
260};
261
262struct WholeProgramDevirt : public ModulePass {
263 static char ID;
264 WholeProgramDevirt() : ModulePass(ID) {
265 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
266 }
Andrew Kayloraa641a52016-04-22 22:06:11 +0000267 bool runOnModule(Module &M) {
268 if (skipModule(M))
269 return false;
270
271 return DevirtModule(M).run();
272 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000273};
274
275} // anonymous namespace
276
277INITIALIZE_PASS(WholeProgramDevirt, "wholeprogramdevirt",
278 "Whole program devirtualization", false, false)
279char WholeProgramDevirt::ID = 0;
280
281ModulePass *llvm::createWholeProgramDevirtPass() {
282 return new WholeProgramDevirt;
283}
284
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000285PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
286 ModuleAnalysisManager &) {
Davide Italianod737dd22016-06-14 21:44:19 +0000287 if (!DevirtModule(M).run())
288 return PreservedAnalyses::all();
289 return PreservedAnalyses::none();
290}
291
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000292void DevirtModule::buildTypeIdentifierMap(
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000293 std::vector<VTableBits> &Bits,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000294 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000295 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000296 Bits.reserve(M.getGlobalList().size());
297 SmallVector<MDNode *, 2> Types;
298 for (GlobalVariable &GV : M.globals()) {
299 Types.clear();
300 GV.getMetadata(LLVMContext::MD_type, Types);
301 if (Types.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000302 continue;
303
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000304 VTableBits *&BitsPtr = GVToBits[&GV];
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000305 if (!BitsPtr) {
306 Bits.emplace_back();
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000307 Bits.back().GV = &GV;
308 Bits.back().ObjectSize =
309 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000310 BitsPtr = &Bits.back();
311 }
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000312
313 for (MDNode *Type : Types) {
314 auto TypeID = Type->getOperand(1).get();
315
316 uint64_t Offset =
317 cast<ConstantInt>(
318 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
319 ->getZExtValue();
320
321 TypeIdMap[TypeID].insert({BitsPtr, Offset});
322 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000323 }
324}
325
326bool DevirtModule::tryFindVirtualCallTargets(
327 std::vector<VirtualCallTarget> &TargetsForSlot,
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000328 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
329 for (const TypeMemberInfo &TM : TypeMemberInfos) {
330 if (!TM.Bits->GV->isConstant())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000331 return false;
332
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000333 auto Init = dyn_cast<ConstantArray>(TM.Bits->GV->getInitializer());
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000334 if (!Init)
335 return false;
336 ArrayType *VTableTy = Init->getType();
337
338 uint64_t ElemSize =
339 M.getDataLayout().getTypeAllocSize(VTableTy->getElementType());
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000340 uint64_t GlobalSlotOffset = TM.Offset + ByteOffset;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000341 if (GlobalSlotOffset % ElemSize != 0)
342 return false;
343
344 unsigned Op = GlobalSlotOffset / ElemSize;
345 if (Op >= Init->getNumOperands())
346 return false;
347
348 auto Fn = dyn_cast<Function>(Init->getOperand(Op)->stripPointerCasts());
349 if (!Fn)
350 return false;
351
352 // We can disregard __cxa_pure_virtual as a possible call target, as
353 // calls to pure virtuals are UB.
354 if (Fn->getName() == "__cxa_pure_virtual")
355 continue;
356
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000357 TargetsForSlot.push_back({Fn, &TM});
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000358 }
359
360 // Give up if we couldn't find any targets.
361 return !TargetsForSlot.empty();
362}
363
364bool DevirtModule::trySingleImplDevirt(
365 ArrayRef<VirtualCallTarget> TargetsForSlot,
366 MutableArrayRef<VirtualCallSite> CallSites) {
367 // See if the program contains a single implementation of this virtual
368 // function.
369 Function *TheFn = TargetsForSlot[0].Fn;
370 for (auto &&Target : TargetsForSlot)
371 if (TheFn != Target.Fn)
372 return false;
373
374 // If so, update each call site to call that implementation directly.
375 for (auto &&VCallSite : CallSites) {
376 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
377 TheFn, VCallSite.CS.getCalledValue()->getType()));
378 }
379 return true;
380}
381
382bool DevirtModule::tryEvaluateFunctionsWithArgs(
383 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
384 ArrayRef<ConstantInt *> Args) {
385 // Evaluate each function and store the result in each target's RetVal
386 // field.
387 for (VirtualCallTarget &Target : TargetsForSlot) {
388 if (Target.Fn->arg_size() != Args.size() + 1)
389 return false;
390 for (unsigned I = 0; I != Args.size(); ++I)
391 if (Target.Fn->getFunctionType()->getParamType(I + 1) !=
392 Args[I]->getType())
393 return false;
394
395 Evaluator Eval(M.getDataLayout(), nullptr);
396 SmallVector<Constant *, 2> EvalArgs;
397 EvalArgs.push_back(
398 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
399 EvalArgs.insert(EvalArgs.end(), Args.begin(), Args.end());
400 Constant *RetVal;
401 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
402 !isa<ConstantInt>(RetVal))
403 return false;
404 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
405 }
406 return true;
407}
408
409bool DevirtModule::tryUniformRetValOpt(
410 IntegerType *RetType, ArrayRef<VirtualCallTarget> TargetsForSlot,
411 MutableArrayRef<VirtualCallSite> CallSites) {
412 // Uniform return value optimization. If all functions return the same
413 // constant, replace all calls with that constant.
414 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
415 for (const VirtualCallTarget &Target : TargetsForSlot)
416 if (Target.RetVal != TheRetVal)
417 return false;
418
419 auto TheRetValConst = ConstantInt::get(RetType, TheRetVal);
420 for (auto Call : CallSites)
421 Call.replaceAndErase(TheRetValConst);
422 return true;
423}
424
425bool DevirtModule::tryUniqueRetValOpt(
426 unsigned BitWidth, ArrayRef<VirtualCallTarget> TargetsForSlot,
427 MutableArrayRef<VirtualCallSite> CallSites) {
428 // IsOne controls whether we look for a 0 or a 1.
429 auto tryUniqueRetValOptFor = [&](bool IsOne) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000430 const TypeMemberInfo *UniqueMember = 0;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000431 for (const VirtualCallTarget &Target : TargetsForSlot) {
Peter Collingbourne3866cc52016-03-08 03:50:36 +0000432 if (Target.RetVal == (IsOne ? 1 : 0)) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000433 if (UniqueMember)
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000434 return false;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000435 UniqueMember = Target.TM;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000436 }
437 }
438
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000439 // We should have found a unique member or bailed out by now. We already
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000440 // checked for a uniform return value in tryUniformRetValOpt.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000441 assert(UniqueMember);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000442
443 // Replace each call with the comparison.
444 for (auto &&Call : CallSites) {
445 IRBuilder<> B(Call.CS.getInstruction());
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000446 Value *OneAddr = B.CreateBitCast(UniqueMember->Bits->GV, Int8PtrTy);
447 OneAddr = B.CreateConstGEP1_64(OneAddr, UniqueMember->Offset);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000448 Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
449 Call.VTable, OneAddr);
450 Call.replaceAndErase(Cmp);
451 }
452 return true;
453 };
454
455 if (BitWidth == 1) {
456 if (tryUniqueRetValOptFor(true))
457 return true;
458 if (tryUniqueRetValOptFor(false))
459 return true;
460 }
461 return false;
462}
463
464bool DevirtModule::tryVirtualConstProp(
465 MutableArrayRef<VirtualCallTarget> TargetsForSlot,
466 ArrayRef<VirtualCallSite> CallSites) {
467 // This only works if the function returns an integer.
468 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
469 if (!RetType)
470 return false;
471 unsigned BitWidth = RetType->getBitWidth();
472 if (BitWidth > 64)
473 return false;
474
475 // Make sure that each function does not access memory, takes at least one
476 // argument, does not use its first argument (which we assume is 'this'),
477 // and has the same return type.
478 for (VirtualCallTarget &Target : TargetsForSlot) {
479 if (!Target.Fn->doesNotAccessMemory() || Target.Fn->arg_empty() ||
480 !Target.Fn->arg_begin()->use_empty() ||
481 Target.Fn->getReturnType() != RetType)
482 return false;
483 }
484
485 // Group call sites by the list of constant arguments they pass.
486 // The comparator ensures deterministic ordering.
487 struct ByAPIntValue {
488 bool operator()(const std::vector<ConstantInt *> &A,
489 const std::vector<ConstantInt *> &B) const {
490 return std::lexicographical_compare(
491 A.begin(), A.end(), B.begin(), B.end(),
492 [](ConstantInt *AI, ConstantInt *BI) {
493 return AI->getValue().ult(BI->getValue());
494 });
495 }
496 };
497 std::map<std::vector<ConstantInt *>, std::vector<VirtualCallSite>,
498 ByAPIntValue>
499 VCallSitesByConstantArg;
500 for (auto &&VCallSite : CallSites) {
501 std::vector<ConstantInt *> Args;
502 if (VCallSite.CS.getType() != RetType)
503 continue;
504 for (auto &&Arg :
505 make_range(VCallSite.CS.arg_begin() + 1, VCallSite.CS.arg_end())) {
506 if (!isa<ConstantInt>(Arg))
507 break;
508 Args.push_back(cast<ConstantInt>(&Arg));
509 }
510 if (Args.size() + 1 != VCallSite.CS.arg_size())
511 continue;
512
513 VCallSitesByConstantArg[Args].push_back(VCallSite);
514 }
515
516 for (auto &&CSByConstantArg : VCallSitesByConstantArg) {
517 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
518 continue;
519
520 if (tryUniformRetValOpt(RetType, TargetsForSlot, CSByConstantArg.second))
521 continue;
522
523 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second))
524 continue;
525
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000526 // Find an allocation offset in bits in all vtables associated with the
527 // type.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000528 uint64_t AllocBefore =
529 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
530 uint64_t AllocAfter =
531 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
532
533 // Calculate the total amount of padding needed to store a value at both
534 // ends of the object.
535 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
536 for (auto &&Target : TargetsForSlot) {
537 TotalPaddingBefore += std::max<int64_t>(
538 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
539 TotalPaddingAfter += std::max<int64_t>(
540 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
541 }
542
543 // If the amount of padding is too large, give up.
544 // FIXME: do something smarter here.
545 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
546 continue;
547
548 // Calculate the offset to the value as a (possibly negative) byte offset
549 // and (if applicable) a bit offset, and store the values in the targets.
550 int64_t OffsetByte;
551 uint64_t OffsetBit;
552 if (TotalPaddingBefore <= TotalPaddingAfter)
553 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
554 OffsetBit);
555 else
556 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
557 OffsetBit);
558
559 // Rewrite each call to a load from OffsetByte/OffsetBit.
560 for (auto Call : CSByConstantArg.second) {
561 IRBuilder<> B(Call.CS.getInstruction());
562 Value *Addr = B.CreateConstGEP1_64(Call.VTable, OffsetByte);
563 if (BitWidth == 1) {
564 Value *Bits = B.CreateLoad(Addr);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +0000565 Value *Bit = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000566 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
567 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
568 Call.replaceAndErase(IsBitSet);
569 } else {
570 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
571 Value *Val = B.CreateLoad(RetType, ValAddr);
572 Call.replaceAndErase(Val);
573 }
574 }
575 }
576 return true;
577}
578
579void DevirtModule::rebuildGlobal(VTableBits &B) {
580 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
581 return;
582
583 // Align each byte array to pointer width.
584 unsigned PointerSize = M.getDataLayout().getPointerSize();
585 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
586 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
587
588 // Before was stored in reverse order; flip it now.
589 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
590 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
591
592 // Build an anonymous global containing the before bytes, followed by the
593 // original initializer, followed by the after bytes.
594 auto NewInit = ConstantStruct::getAnon(
595 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
596 B.GV->getInitializer(),
597 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
598 auto NewGV =
599 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
600 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
601 NewGV->setSection(B.GV->getSection());
602 NewGV->setComdat(B.GV->getComdat());
603
604 // Build an alias named after the original global, pointing at the second
605 // element (the original initializer).
606 auto Alias = GlobalAlias::create(
607 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
608 ConstantExpr::getGetElementPtr(
609 NewInit->getType(), NewGV,
610 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
611 ConstantInt::get(Int32Ty, 1)}),
612 &M);
613 Alias->setVisibility(B.GV->getVisibility());
614 Alias->takeName(B.GV);
615
616 B.GV->replaceAllUsesWith(Alias);
617 B.GV->eraseFromParent();
618}
619
620bool DevirtModule::run() {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000621 Function *TypeTestFunc =
622 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
623 if (!TypeTestFunc || TypeTestFunc->use_empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000624 return false;
625
626 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
627 if (!AssumeFunc || AssumeFunc->use_empty())
628 return false;
629
630 // Find all virtual calls via a virtual table pointer %p under an assumption
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000631 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
632 // points to a member of the type identifier %md. Group calls by (type ID,
633 // offset) pair (effectively the identity of the virtual function) and store
634 // to CallSlots.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000635 DenseSet<Value *> SeenPtrs;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000636 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000637 I != E;) {
638 auto CI = dyn_cast<CallInst>(I->getUser());
639 ++I;
640 if (!CI)
641 continue;
642
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000643 // Search for virtual calls based on %p and add them to DevirtCalls.
644 SmallVector<DevirtCallSite, 1> DevirtCalls;
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000645 SmallVector<CallInst *, 1> Assumes;
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000646 findDevirtualizableCalls(DevirtCalls, Assumes, CI);
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000647
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000648 // If we found any, add them to CallSlots. Only do this if we haven't seen
649 // the vtable pointer before, as it may have been CSE'd with pointers from
650 // other call sites, and we don't want to process call sites multiple times.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000651 if (!Assumes.empty()) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000652 Metadata *TypeId =
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000653 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
654 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000655 if (SeenPtrs.insert(Ptr).second) {
656 for (DevirtCallSite Call : DevirtCalls) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000657 CallSlots[{TypeId, Call.Offset}].push_back(
Peter Collingbourneccdc2252016-05-10 18:07:21 +0000658 {CI->getArgOperand(0), Call.CS});
659 }
660 }
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000661 }
662
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000663 // We no longer need the assumes or the type test.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000664 for (auto Assume : Assumes)
665 Assume->eraseFromParent();
666 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
667 // may use the vtable argument later.
668 if (CI->use_empty())
669 CI->eraseFromParent();
670 }
671
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000672 // Rebuild type metadata into a map for easy lookup.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000673 std::vector<VTableBits> Bits;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000674 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
675 buildTypeIdentifierMap(Bits, TypeIdMap);
676 if (TypeIdMap.empty())
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000677 return true;
678
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000679 // For each (type, offset) pair:
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000680 bool DidVirtualConstProp = false;
681 for (auto &S : CallSlots) {
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000682 // Search each of the members of the type identifier for the virtual
683 // function implementation at offset S.first.ByteOffset, and add to
684 // TargetsForSlot.
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000685 std::vector<VirtualCallTarget> TargetsForSlot;
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000686 if (!tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
Peter Collingbournedf49d1b2016-02-09 22:50:34 +0000687 S.first.ByteOffset))
688 continue;
689
690 if (trySingleImplDevirt(TargetsForSlot, S.second))
691 continue;
692
693 DidVirtualConstProp |= tryVirtualConstProp(TargetsForSlot, S.second);
694 }
695
696 // Rebuild each global we touched as part of virtual constant propagation to
697 // include the before and after bytes.
698 if (DidVirtualConstProp)
699 for (VTableBits &B : Bits)
700 rebuildGlobal(B);
701
702 return true;
703}