LLVM 19.0.0git
CallPromotionUtils.cpp
Go to the documentation of this file.
1//===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements utilities useful for promoting indirect call sites to
10// direct call sites.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/Analysis/Loads.h"
18#include "llvm/IR/IRBuilder.h"
21
22using namespace llvm;
23
24#define DEBUG_TYPE "call-promotion-utils"
25
26/// Fix-up phi nodes in an invoke instruction's normal destination.
27///
28/// After versioning an invoke instruction, values coming from the original
29/// block will now be coming from the "merge" block. For example, in the code
30/// below:
31///
32/// then_bb:
33/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
34///
35/// else_bb:
36/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
37///
38/// merge_bb:
39/// %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
40/// br %normal_dst
41///
42/// normal_dst:
43/// %t3 = phi i32 [ %x, %orig_bb ], ...
44///
45/// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in
46/// "normal_dst" must be fixed to refer to "merge_bb":
47///
48/// normal_dst:
49/// %t3 = phi i32 [ %x, %merge_bb ], ...
50///
51static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
52 BasicBlock *MergeBlock) {
53 for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
54 int Idx = Phi.getBasicBlockIndex(OrigBlock);
55 if (Idx == -1)
56 continue;
57 Phi.setIncomingBlock(Idx, MergeBlock);
58 }
59}
60
61/// Fix-up phi nodes in an invoke instruction's unwind destination.
62///
63/// After versioning an invoke instruction, values coming from the original
64/// block will now be coming from either the "then" block or the "else" block.
65/// For example, in the code below:
66///
67/// then_bb:
68/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
69///
70/// else_bb:
71/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
72///
73/// unwind_dst:
74/// %t3 = phi i32 [ %x, %orig_bb ], ...
75///
76/// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in
77/// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb":
78///
79/// unwind_dst:
80/// %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
81///
82static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
83 BasicBlock *ThenBlock,
84 BasicBlock *ElseBlock) {
85 for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
86 int Idx = Phi.getBasicBlockIndex(OrigBlock);
87 if (Idx == -1)
88 continue;
89 auto *V = Phi.getIncomingValue(Idx);
90 Phi.setIncomingBlock(Idx, ThenBlock);
91 Phi.addIncoming(V, ElseBlock);
92 }
93}
94
95/// Create a phi node for the returned value of a call or invoke instruction.
96///
97/// After versioning a call or invoke instruction that returns a value, we have
98/// to merge the value of the original and new instructions. We do this by
99/// creating a phi node and replacing uses of the original instruction with this
100/// phi node.
101///
102/// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is
103/// defined in "then_bb", we create the following phi node:
104///
105/// ; Uses of the original instruction are replaced by uses of the phi node.
106/// %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ],
107///
108static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
109 BasicBlock *MergeBlock, IRBuilder<> &Builder) {
110
111 if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
112 return;
113
114 Builder.SetInsertPoint(MergeBlock, MergeBlock->begin());
115 PHINode *Phi = Builder.CreatePHI(OrigInst->getType(), 0);
116 SmallVector<User *, 16> UsersToUpdate(OrigInst->users());
117 for (User *U : UsersToUpdate)
118 U->replaceUsesOfWith(OrigInst, Phi);
119 Phi->addIncoming(OrigInst, OrigInst->getParent());
120 Phi->addIncoming(NewInst, NewInst->getParent());
121}
122
123/// Cast a call or invoke instruction to the given type.
124///
125/// When promoting a call site, the return type of the call site might not match
126/// that of the callee. If this is the case, we have to cast the returned value
127/// to the correct type. The location of the cast depends on if we have a call
128/// or invoke instruction.
129///
130/// For example, if the call instruction below requires a bitcast after
131/// promotion:
132///
133/// orig_bb:
134/// %t0 = call i32 @func()
135/// ...
136///
137/// The bitcast is placed after the call instruction:
138///
139/// orig_bb:
140/// ; Uses of the original return value are replaced by uses of the bitcast.
141/// %t0 = call i32 @func()
142/// %t1 = bitcast i32 %t0 to ...
143/// ...
144///
145/// A similar transformation is performed for invoke instructions. However,
146/// since invokes are terminating, a new block is created for the bitcast. For
147/// example, if the invoke instruction below requires a bitcast after promotion:
148///
149/// orig_bb:
150/// %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
151///
152/// The edge between the original block and the invoke's normal destination is
153/// split, and the bitcast is placed there:
154///
155/// orig_bb:
156/// %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
157///
158/// split_bb:
159/// ; Uses of the original return value are replaced by uses of the bitcast.
160/// %t1 = bitcast i32 %t0 to ...
161/// br label %normal_dst
162///
163static void createRetBitCast(CallBase &CB, Type *RetTy, CastInst **RetBitCast) {
164
165 // Save the users of the calling instruction. These uses will be changed to
166 // use the bitcast after we create it.
167 SmallVector<User *, 16> UsersToUpdate(CB.users());
168
169 // Determine an appropriate location to create the bitcast for the return
170 // value. The location depends on if we have a call or invoke instruction.
171 BasicBlock::iterator InsertBefore;
172 if (auto *Invoke = dyn_cast<InvokeInst>(&CB))
173 InsertBefore =
174 SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->begin();
175 else
176 InsertBefore = std::next(CB.getIterator());
177
178 // Bitcast the return value to the correct type.
179 auto *Cast = CastInst::CreateBitOrPointerCast(&CB, RetTy, "", InsertBefore);
180 if (RetBitCast)
181 *RetBitCast = Cast;
182
183 // Replace all the original uses of the calling instruction with the bitcast.
184 for (User *U : UsersToUpdate)
185 U->replaceUsesOfWith(&CB, Cast);
186}
187
188/// Predicate and clone the given call site.
189///
190/// This function creates an if-then-else structure at the location of the call
191/// site. The "if" condition is specified by `Cond`. The original call site is
192/// moved into the "else" block, and a clone of the call site is placed in the
193/// "then" block. The cloned instruction is returned.
194///
195/// For example, the call instruction below:
196///
197/// orig_bb:
198/// %t0 = call i32 %ptr()
199/// ...
200///
201/// Is replace by the following:
202///
203/// orig_bb:
204/// %cond = Cond
205/// br i1 %cond, %then_bb, %else_bb
206///
207/// then_bb:
208/// ; The clone of the original call instruction is placed in the "then"
209/// ; block. It is not yet promoted.
210/// %t1 = call i32 %ptr()
211/// br merge_bb
212///
213/// else_bb:
214/// ; The original call instruction is moved to the "else" block.
215/// %t0 = call i32 %ptr()
216/// br merge_bb
217///
218/// merge_bb:
219/// ; Uses of the original call instruction are replaced by uses of the phi
220/// ; node.
221/// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
222/// ...
223///
224/// A similar transformation is performed for invoke instructions. However,
225/// since invokes are terminating, more work is required. For example, the
226/// invoke instruction below:
227///
228/// orig_bb:
229/// %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
230///
231/// Is replace by the following:
232///
233/// orig_bb:
234/// %cond = Cond
235/// br i1 %cond, %then_bb, %else_bb
236///
237/// then_bb:
238/// ; The clone of the original invoke instruction is placed in the "then"
239/// ; block, and its normal destination is set to the "merge" block. It is
240/// ; not yet promoted.
241/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
242///
243/// else_bb:
244/// ; The original invoke instruction is moved into the "else" block, and
245/// ; its normal destination is set to the "merge" block.
246/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
247///
248/// merge_bb:
249/// ; Uses of the original invoke instruction are replaced by uses of the
250/// ; phi node, and the merge block branches to the normal destination.
251/// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
252/// br %normal_dst
253///
254/// An indirect musttail call is processed slightly differently in that:
255/// 1. No merge block needed for the orginal and the cloned callsite, since
256/// either one ends the flow. No phi node is needed either.
257/// 2. The return statement following the original call site is duplicated too
258/// and placed immediately after the cloned call site per the IR convention.
259///
260/// For example, the musttail call instruction below:
261///
262/// orig_bb:
263/// %t0 = musttail call i32 %ptr()
264/// ...
265///
266/// Is replaced by the following:
267///
268/// cond_bb:
269/// %cond = Cond
270/// br i1 %cond, %then_bb, %orig_bb
271///
272/// then_bb:
273/// ; The clone of the original call instruction is placed in the "then"
274/// ; block. It is not yet promoted.
275/// %t1 = musttail call i32 %ptr()
276/// ret %t1
277///
278/// orig_bb:
279/// ; The original call instruction stays in its original block.
280/// %t0 = musttail call i32 %ptr()
281/// ret %t0
283 MDNode *BranchWeights) {
284
285 IRBuilder<> Builder(&CB);
286 CallBase *OrigInst = &CB;
287 BasicBlock *OrigBlock = OrigInst->getParent();
288
289 if (OrigInst->isMustTailCall()) {
290 // Create an if-then structure. The original instruction stays in its block,
291 // and a clone of the original instruction is placed in the "then" block.
292 Instruction *ThenTerm =
293 SplitBlockAndInsertIfThen(Cond, &CB, false, BranchWeights);
294 BasicBlock *ThenBlock = ThenTerm->getParent();
295 ThenBlock->setName("if.true.direct_targ");
296 CallBase *NewInst = cast<CallBase>(OrigInst->clone());
297 NewInst->insertBefore(ThenTerm);
298
299 // Place a clone of the optional bitcast after the new call site.
300 Value *NewRetVal = NewInst;
301 auto Next = OrigInst->getNextNode();
302 if (auto *BitCast = dyn_cast_or_null<BitCastInst>(Next)) {
303 assert(BitCast->getOperand(0) == OrigInst &&
304 "bitcast following musttail call must use the call");
305 auto NewBitCast = BitCast->clone();
306 NewBitCast->replaceUsesOfWith(OrigInst, NewInst);
307 NewBitCast->insertBefore(ThenTerm);
308 NewRetVal = NewBitCast;
309 Next = BitCast->getNextNode();
310 }
311
312 // Place a clone of the return instruction after the new call site.
313 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
314 assert(Ret && "musttail call must precede a ret with an optional bitcast");
315 auto NewRet = Ret->clone();
316 if (Ret->getReturnValue())
317 NewRet->replaceUsesOfWith(Ret->getReturnValue(), NewRetVal);
318 NewRet->insertBefore(ThenTerm);
319
320 // A return instructions is terminating, so we don't need the terminator
321 // instruction just created.
322 ThenTerm->eraseFromParent();
323
324 return *NewInst;
325 }
326
327 // Create an if-then-else structure. The original instruction is moved into
328 // the "else" block, and a clone of the original instruction is placed in the
329 // "then" block.
330 Instruction *ThenTerm = nullptr;
331 Instruction *ElseTerm = nullptr;
332 SplitBlockAndInsertIfThenElse(Cond, &CB, &ThenTerm, &ElseTerm, BranchWeights);
333 BasicBlock *ThenBlock = ThenTerm->getParent();
334 BasicBlock *ElseBlock = ElseTerm->getParent();
335 BasicBlock *MergeBlock = OrigInst->getParent();
336
337 ThenBlock->setName("if.true.direct_targ");
338 ElseBlock->setName("if.false.orig_indirect");
339 MergeBlock->setName("if.end.icp");
340
341 CallBase *NewInst = cast<CallBase>(OrigInst->clone());
342 OrigInst->moveBefore(ElseTerm);
343 NewInst->insertBefore(ThenTerm);
344
345 // If the original call site is an invoke instruction, we have extra work to
346 // do since invoke instructions are terminating. We have to fix-up phi nodes
347 // in the invoke's normal and unwind destinations.
348 if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) {
349 auto *NewInvoke = cast<InvokeInst>(NewInst);
350
351 // Invoke instructions are terminating, so we don't need the terminator
352 // instructions that were just created.
353 ThenTerm->eraseFromParent();
354 ElseTerm->eraseFromParent();
355
356 // Branch from the "merge" block to the original normal destination.
357 Builder.SetInsertPoint(MergeBlock);
358 Builder.CreateBr(OrigInvoke->getNormalDest());
359
360 // Fix-up phi nodes in the original invoke's normal and unwind destinations.
361 fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock);
362 fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock);
363
364 // Now set the normal destinations of the invoke instructions to be the
365 // "merge" block.
366 OrigInvoke->setNormalDest(MergeBlock);
367 NewInvoke->setNormalDest(MergeBlock);
368 }
369
370 // Create a phi node for the returned value of the call site.
371 createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
372
373 return *NewInst;
374}
375
376// Predicate and clone the given call site using condition `CB.callee ==
377// Callee`. See the comment `versionCallSiteWithCond` for the transformation.
379 MDNode *BranchWeights) {
380
381 IRBuilder<> Builder(&CB);
382
383 // Create the compare. The called value and callee must have the same type to
384 // be compared.
385 if (CB.getCalledOperand()->getType() != Callee->getType())
386 Callee = Builder.CreateBitCast(Callee, CB.getCalledOperand()->getType());
387 auto *Cond = Builder.CreateICmpEQ(CB.getCalledOperand(), Callee);
388
389 return versionCallSiteWithCond(CB, Cond, BranchWeights);
390}
391
393 const char **FailureReason) {
394 assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted");
395
396 auto &DL = Callee->getParent()->getDataLayout();
397
398 // Check the return type. The callee's return value type must be bitcast
399 // compatible with the call site's type.
400 Type *CallRetTy = CB.getType();
401 Type *FuncRetTy = Callee->getReturnType();
402 if (CallRetTy != FuncRetTy)
403 if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy, CallRetTy, DL)) {
404 if (FailureReason)
405 *FailureReason = "Return type mismatch";
406 return false;
407 }
408
409 // The number of formal arguments of the callee.
410 unsigned NumParams = Callee->getFunctionType()->getNumParams();
411
412 // The number of actual arguments in the call.
413 unsigned NumArgs = CB.arg_size();
414
415 // Check the number of arguments. The callee and call site must agree on the
416 // number of arguments.
417 if (NumArgs != NumParams && !Callee->isVarArg()) {
418 if (FailureReason)
419 *FailureReason = "The number of arguments mismatch";
420 return false;
421 }
422
423 // Check the argument types. The callee's formal argument types must be
424 // bitcast compatible with the corresponding actual argument types of the call
425 // site.
426 unsigned I = 0;
427 for (; I < NumParams; ++I) {
428 // Make sure that the callee and call agree on byval/inalloca. The types do
429 // not have to match.
430 if (Callee->hasParamAttribute(I, Attribute::ByVal) !=
431 CB.getAttributes().hasParamAttr(I, Attribute::ByVal)) {
432 if (FailureReason)
433 *FailureReason = "byval mismatch";
434 return false;
435 }
436 if (Callee->hasParamAttribute(I, Attribute::InAlloca) !=
437 CB.getAttributes().hasParamAttr(I, Attribute::InAlloca)) {
438 if (FailureReason)
439 *FailureReason = "inalloca mismatch";
440 return false;
441 }
442
443 Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I);
444 Type *ActualTy = CB.getArgOperand(I)->getType();
445 if (FormalTy == ActualTy)
446 continue;
447 if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) {
448 if (FailureReason)
449 *FailureReason = "Argument type mismatch";
450 return false;
451 }
452
453 // MustTail call needs stricter type match. See
454 // Verifier::verifyMustTailCall().
455 if (CB.isMustTailCall()) {
456 PointerType *PF = dyn_cast<PointerType>(FormalTy);
457 PointerType *PA = dyn_cast<PointerType>(ActualTy);
458 if (!PF || !PA || PF->getAddressSpace() != PA->getAddressSpace()) {
459 if (FailureReason)
460 *FailureReason = "Musttail call Argument type mismatch";
461 return false;
462 }
463 }
464 }
465 for (; I < NumArgs; I++) {
466 // Vararg functions can have more arguments than parameters.
467 assert(Callee->isVarArg());
468 if (CB.paramHasAttr(I, Attribute::StructRet)) {
469 if (FailureReason)
470 *FailureReason = "SRet arg to vararg function";
471 return false;
472 }
473 }
474
475 return true;
476}
477
479 CastInst **RetBitCast) {
480 assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted");
481
482 // Set the called function of the call site to be the given callee (but don't
483 // change the type).
484 CB.setCalledOperand(Callee);
485
486 // Since the call site will no longer be direct, we must clear metadata that
487 // is only appropriate for indirect calls. This includes !prof and !callees
488 // metadata.
489 CB.setMetadata(LLVMContext::MD_prof, nullptr);
490 CB.setMetadata(LLVMContext::MD_callees, nullptr);
491
492 // If the function type of the call site matches that of the callee, no
493 // additional work is required.
494 if (CB.getFunctionType() == Callee->getFunctionType())
495 return CB;
496
497 // Save the return types of the call site and callee.
498 Type *CallSiteRetTy = CB.getType();
499 Type *CalleeRetTy = Callee->getReturnType();
500
501 // Change the function type of the call site the match that of the callee.
502 CB.mutateFunctionType(Callee->getFunctionType());
503
504 // Inspect the arguments of the call site. If an argument's type doesn't
505 // match the corresponding formal argument's type in the callee, bitcast it
506 // to the correct type.
507 auto CalleeType = Callee->getFunctionType();
508 auto CalleeParamNum = CalleeType->getNumParams();
509
510 LLVMContext &Ctx = Callee->getContext();
511 const AttributeList &CallerPAL = CB.getAttributes();
512 // The new list of argument attributes.
514 bool AttributeChanged = false;
515
516 for (unsigned ArgNo = 0; ArgNo < CalleeParamNum; ++ArgNo) {
517 auto *Arg = CB.getArgOperand(ArgNo);
518 Type *FormalTy = CalleeType->getParamType(ArgNo);
519 Type *ActualTy = Arg->getType();
520 if (FormalTy != ActualTy) {
521 auto *Cast = CastInst::CreateBitOrPointerCast(Arg, FormalTy, "", CB.getIterator());
522 CB.setArgOperand(ArgNo, Cast);
523
524 // Remove any incompatible attributes for the argument.
525 AttrBuilder ArgAttrs(Ctx, CallerPAL.getParamAttrs(ArgNo));
526 ArgAttrs.remove(AttributeFuncs::typeIncompatible(FormalTy));
527
528 // We may have a different byval/inalloca type.
529 if (ArgAttrs.getByValType())
530 ArgAttrs.addByValAttr(Callee->getParamByValType(ArgNo));
531 if (ArgAttrs.getInAllocaType())
532 ArgAttrs.addInAllocaAttr(Callee->getParamInAllocaType(ArgNo));
533
534 NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs));
535 AttributeChanged = true;
536 } else
537 NewArgAttrs.push_back(CallerPAL.getParamAttrs(ArgNo));
538 }
539
540 // If the return type of the call site doesn't match that of the callee, cast
541 // the returned value to the appropriate type.
542 // Remove any incompatible return value attribute.
543 AttrBuilder RAttrs(Ctx, CallerPAL.getRetAttrs());
544 if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy) {
545 createRetBitCast(CB, CallSiteRetTy, RetBitCast);
546 RAttrs.remove(AttributeFuncs::typeIncompatible(CalleeRetTy));
547 AttributeChanged = true;
548 }
549
550 // Set the new callsite attribute.
551 if (AttributeChanged)
552 CB.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttrs(),
553 AttributeSet::get(Ctx, RAttrs),
554 NewArgAttrs));
555
556 return CB;
557}
558
560 MDNode *BranchWeights) {
561
562 // Version the indirect call site. If the called value is equal to the given
563 // callee, 'NewInst' will be executed, otherwise the original call site will
564 // be executed.
565 CallBase &NewInst = versionCallSite(CB, Callee, BranchWeights);
566
567 // Promote 'NewInst' so that it directly calls the desired function.
568 return promoteCall(NewInst, Callee);
569}
570
573 Module *M = CB.getCaller()->getParent();
574 const DataLayout &DL = M->getDataLayout();
575 Value *Callee = CB.getCalledOperand();
576
577 LoadInst *VTableEntryLoad = dyn_cast<LoadInst>(Callee);
578 if (!VTableEntryLoad)
579 return false; // Not a vtable entry load.
580 Value *VTableEntryPtr = VTableEntryLoad->getPointerOperand();
581 APInt VTableOffset(DL.getTypeSizeInBits(VTableEntryPtr->getType()), 0);
582 Value *VTableBasePtr = VTableEntryPtr->stripAndAccumulateConstantOffsets(
583 DL, VTableOffset, /* AllowNonInbounds */ true);
584 LoadInst *VTablePtrLoad = dyn_cast<LoadInst>(VTableBasePtr);
585 if (!VTablePtrLoad)
586 return false; // Not a vtable load.
587 Value *Object = VTablePtrLoad->getPointerOperand();
588 APInt ObjectOffset(DL.getTypeSizeInBits(Object->getType()), 0);
589 Value *ObjectBase = Object->stripAndAccumulateConstantOffsets(
590 DL, ObjectOffset, /* AllowNonInbounds */ true);
591 if (!(isa<AllocaInst>(ObjectBase) && ObjectOffset == 0))
592 // Not an Alloca or the offset isn't zero.
593 return false;
594
595 // Look for the vtable pointer store into the object by the ctor.
596 BasicBlock::iterator BBI(VTablePtrLoad);
597 Value *VTablePtr = FindAvailableLoadedValue(
598 VTablePtrLoad, VTablePtrLoad->getParent(), BBI, 0, nullptr, nullptr);
599 if (!VTablePtr)
600 return false; // No vtable found.
601 APInt VTableOffsetGVBase(DL.getTypeSizeInBits(VTablePtr->getType()), 0);
602 Value *VTableGVBase = VTablePtr->stripAndAccumulateConstantOffsets(
603 DL, VTableOffsetGVBase, /* AllowNonInbounds */ true);
604 GlobalVariable *GV = dyn_cast<GlobalVariable>(VTableGVBase);
605 if (!(GV && GV->isConstant() && GV->hasDefinitiveInitializer()))
606 // Not in the form of a global constant variable with an initializer.
607 return false;
608
609 APInt VTableGVOffset = VTableOffsetGVBase + VTableOffset;
610 if (!(VTableGVOffset.getActiveBits() <= 64))
611 return false; // Out of range.
612
613 Function *DirectCallee = nullptr;
614 std::tie(DirectCallee, std::ignore) =
615 getFunctionAtVTableOffset(GV, VTableGVOffset.getZExtValue(), *M);
616 if (!DirectCallee)
617 return false; // No function pointer found.
618
619 if (!isLegalToPromote(CB, DirectCallee))
620 return false;
621
622 // Success.
623 promoteCall(CB, DirectCallee);
624 return true;
625}
626
627#undef DEBUG_TYPE
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock, BasicBlock *MergeBlock)
Fix-up phi nodes in an invoke instruction's normal destination.
static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock, BasicBlock *ThenBlock, BasicBlock *ElseBlock)
Fix-up phi nodes in an invoke instruction's unwind destination.
static void createRetBitCast(CallBase &CB, Type *RetTy, CastInst **RetBitCast)
Cast a call or invoke instruction to the given type.
static CallBase & versionCallSiteWithCond(CallBase &CB, Value *Cond, MDNode *BranchWeights)
Predicate and clone the given call site.
static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst, BasicBlock *MergeBlock, IRBuilder<> &Builder)
Create a phi node for the returned value of a call or invoke instruction.
return RetTy
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define I(x, y, z)
Definition: MD5.cpp:58
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Class for arbitrary precision integers.
Definition: APInt.h:76
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1498
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1470
Type * getByValType() const
Retrieve the byval type.
Definition: Attributes.h:1115
AttrBuilder & addByValAttr(Type *Ty)
This turns a byval type into the form used internally in Attribute.
Type * getInAllocaType() const
Retrieve the inalloca type.
Definition: Attributes.h:1129
AttrBuilder & addInAllocaAttr(Type *Ty)
This turns an inalloca type into the form used internally in Attribute.
AttrBuilder & remove(const AttributeMask &AM)
Remove the attributes from the builder.
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeSet getRetAttrs() const
The attributes for the ret value are returned.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
Definition: Attributes.h:788
AttributeSet getParamAttrs(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Definition: Attributes.cpp:774
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:430
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:499
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1494
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1742
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
bool isMustTailCall() const
Tests if this call site must be tail call optimized.
Value * getCalledOperand() const
Definition: InstrTypes.h:1735
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1823
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1687
void mutateFunctionType(FunctionType *FTy)
Definition: InstrTypes.h:1602
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1692
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1600
void setCalledOperand(Value *V)
Definition: InstrTypes.h:1778
unsigned arg_size() const
Definition: InstrTypes.h:1685
AttributeList getAttributes() const
Return the parameter attributes for this call.
Definition: InstrTypes.h:1819
Function * getCaller()
Helper to get the caller (the parent function).
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:601
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2397
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2241
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2127
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition: IRBuilder.h:1114
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
const BasicBlock * getParent() const
Definition: Instruction.h:152
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1635
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Invoke instruction.
BasicBlock * getUnwindDest() const
BasicBlock * getNormalDest() const
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:184
Value * getPointerOperand()
Definition: Instructions.h:280
Metadata node.
Definition: Metadata.h:1067
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Class to represent pointers.
Definition: DerivedTypes.h:646
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:679
Return a value (possibly void), from a function.
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:140
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr) const
Accumulate the constant offset this value has compared to a base pointer.
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
iterator_range< user_iterator > users()
Definition: Value.h:421
bool use_empty() const
Definition: Value.h:344
self_iterator getIterator()
Definition: ilist_node.h:109
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:316
AttributeMask typeIncompatible(Type *Ty, AttributeSafetyKind ASK=ASK_ALL)
Which attributes cannot be applied to a type.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool isLegalToPromote(const CallBase &CB, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
CallBase & promoteCallWithIfThenElse(CallBase &CB, Function *Callee, MDNode *BranchWeights=nullptr)
Promote the given indirect call site to conditionally call Callee.
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition: Loads.cpp:455
void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
CallBase & versionCallSite(CallBase &CB, Value *Callee, MDNode *BranchWeights)
Predicate and clone the given call site.
CallBase & promoteCall(CallBase &CB, Function *Callee, CastInst **RetBitCast=nullptr)
Promote the given indirect call site to unconditionally call Callee.
bool tryPromoteCall(CallBase &CB)
Try to promote (devirtualize) a virtual call on an Alloca.
Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
std::pair< Function *, Constant * > getFunctionAtVTableOffset(GlobalVariable *GV, uint64_t Offset, Module &M)
Given a vtable and a specified offset, returns the function and the trivial pointer at the specified ...