LLVM 24.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
16#include "llvm/Analysis/Loads.h"
19#include "llvm/IR/Constant.h"
20#include "llvm/IR/IRBuilder.h"
23#include "llvm/IR/Module.h"
26
27using namespace llvm;
28
29#define DEBUG_TYPE "call-promotion-utils"
30
31/// Fix-up phi nodes in an invoke instruction's normal destination.
32///
33/// After versioning an invoke instruction, values coming from the original
34/// block will now be coming from the "merge" block. For example, in the code
35/// below:
36///
37/// then_bb:
38/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
39///
40/// else_bb:
41/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
42///
43/// merge_bb:
44/// %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
45/// br %normal_dst
46///
47/// normal_dst:
48/// %t3 = phi i32 [ %x, %orig_bb ], ...
49///
50/// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in
51/// "normal_dst" must be fixed to refer to "merge_bb":
52///
53/// normal_dst:
54/// %t3 = phi i32 [ %x, %merge_bb ], ...
55///
56static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
57 BasicBlock *MergeBlock) {
58 for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
59 int Idx = Phi.getBasicBlockIndex(OrigBlock);
60 if (Idx == -1)
61 continue;
62 Phi.setIncomingBlock(Idx, MergeBlock);
63 }
64}
65
66/// Fix-up phi nodes in an invoke instruction's unwind destination.
67///
68/// After versioning an invoke instruction, values coming from the original
69/// block will now be coming from either the "then" block or the "else" block.
70/// For example, in the code below:
71///
72/// then_bb:
73/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
74///
75/// else_bb:
76/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
77///
78/// unwind_dst:
79/// %t3 = phi i32 [ %x, %orig_bb ], ...
80///
81/// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in
82/// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb":
83///
84/// unwind_dst:
85/// %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
86///
87static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
88 BasicBlock *ThenBlock,
89 BasicBlock *ElseBlock) {
90 for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
91 int Idx = Phi.getBasicBlockIndex(OrigBlock);
92 if (Idx == -1)
93 continue;
94 auto *V = Phi.getIncomingValue(Idx);
95 Phi.setIncomingBlock(Idx, ThenBlock);
96 Phi.addIncoming(V, ElseBlock);
97 }
98}
99
100/// Create a phi node for the returned value of a call or invoke instruction.
101///
102/// After versioning a call or invoke instruction that returns a value, we have
103/// to merge the value of the original and new instructions. We do this by
104/// creating a phi node and replacing uses of the original instruction with this
105/// phi node.
106///
107/// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is
108/// defined in "then_bb", we create the following phi node:
109///
110/// ; Uses of the original instruction are replaced by uses of the phi node.
111/// %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ],
112///
113static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
114 BasicBlock *MergeBlock, IRBuilder<> &Builder) {
115
116 if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
117 return;
118
119 Builder.SetInsertPoint(MergeBlock->begin());
120 PHINode *Phi = Builder.CreatePHI(OrigInst->getType(), 0);
121 SmallVector<User *, 16> UsersToUpdate(OrigInst->users());
122 for (User *U : UsersToUpdate)
123 U->replaceUsesOfWith(OrigInst, Phi);
124 Phi->addIncoming(OrigInst, OrigInst->getParent());
125 Phi->addIncoming(NewInst, NewInst->getParent());
126}
127
128/// Cast a call or invoke instruction to the given type.
129///
130/// When promoting a call site, the return type of the call site might not match
131/// that of the callee. If this is the case, we have to cast the returned value
132/// to the correct type. The location of the cast depends on if we have a call
133/// or invoke instruction.
134///
135/// For example, if the call instruction below requires a bitcast after
136/// promotion:
137///
138/// orig_bb:
139/// %t0 = call i32 @func()
140/// ...
141///
142/// The bitcast is placed after the call instruction:
143///
144/// orig_bb:
145/// ; Uses of the original return value are replaced by uses of the bitcast.
146/// %t0 = call i32 @func()
147/// %t1 = bitcast i32 %t0 to ...
148/// ...
149///
150/// A similar transformation is performed for invoke instructions. However,
151/// since invokes are terminating, a new block is created for the bitcast. For
152/// example, if the invoke instruction below requires a bitcast after promotion:
153///
154/// orig_bb:
155/// %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
156///
157/// The edge between the original block and the invoke's normal destination is
158/// split, and the bitcast is placed there:
159///
160/// orig_bb:
161/// %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
162///
163/// split_bb:
164/// ; Uses of the original return value are replaced by uses of the bitcast.
165/// %t1 = bitcast i32 %t0 to ...
166/// br label %normal_dst
167///
168static void createRetBitCast(CallBase &CB, Type *RetTy, CastInst **RetBitCast) {
169
170 // Save the users of the calling instruction. These uses will be changed to
171 // use the bitcast after we create it.
172 SmallVector<User *, 16> UsersToUpdate(CB.users());
173
174 // Determine an appropriate location to create the bitcast for the return
175 // value. The location depends on if we have a call or invoke instruction.
176 BasicBlock::iterator InsertBefore;
177 if (auto *Invoke = dyn_cast<InvokeInst>(&CB))
178 InsertBefore =
179 SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->begin();
180 else
181 InsertBefore = std::next(CB.getIterator());
182
183 // Bitcast the return value to the correct type.
184 auto *Cast = CastInst::CreateBitOrPointerCast(&CB, RetTy, "", InsertBefore);
185 if (RetBitCast)
186 *RetBitCast = Cast;
187
188 // Replace all the original uses of the calling instruction with the bitcast.
189 for (User *U : UsersToUpdate)
190 U->replaceUsesOfWith(&CB, Cast);
191}
192
193/// Predicate and clone the given call site.
194///
195/// This function creates an if-then-else structure at the location of the call
196/// site. The "if" condition is specified by `Cond`.
197/// The original call site is moved into the "else" block, and a clone of the
198/// call site is placed in the "then" block. The cloned instruction is returned.
199///
200/// For example, the call instruction below:
201///
202/// orig_bb:
203/// %t0 = call i32 %ptr()
204/// ...
205///
206/// Is replace by the following:
207///
208/// orig_bb:
209/// %cond = Cond
210/// br i1 %cond, %then_bb, %else_bb
211///
212/// then_bb:
213/// ; The clone of the original call instruction is placed in the "then"
214/// ; block. It is not yet promoted.
215/// %t1 = call i32 %ptr()
216/// br merge_bb
217///
218/// else_bb:
219/// ; The original call instruction is moved to the "else" block.
220/// %t0 = call i32 %ptr()
221/// br merge_bb
222///
223/// merge_bb:
224/// ; Uses of the original call instruction are replaced by uses of the phi
225/// ; node.
226/// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
227/// ...
228///
229/// A similar transformation is performed for invoke instructions. However,
230/// since invokes are terminating, more work is required. For example, the
231/// invoke instruction below:
232///
233/// orig_bb:
234/// %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
235///
236/// Is replace by the following:
237///
238/// orig_bb:
239/// %cond = Cond
240/// br i1 %cond, %then_bb, %else_bb
241///
242/// then_bb:
243/// ; The clone of the original invoke instruction is placed in the "then"
244/// ; block, and its normal destination is set to the "merge" block. It is
245/// ; not yet promoted.
246/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
247///
248/// else_bb:
249/// ; The original invoke instruction is moved into the "else" block, and
250/// ; its normal destination is set to the "merge" block.
251/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
252///
253/// merge_bb:
254/// ; Uses of the original invoke instruction are replaced by uses of the
255/// ; phi node, and the merge block branches to the normal destination.
256/// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
257/// br %normal_dst
258///
259/// An indirect musttail call is processed slightly differently in that:
260/// 1. No merge block needed for the orginal and the cloned callsite, since
261/// either one ends the flow. No phi node is needed either.
262/// 2. The return statement following the original call site is duplicated too
263/// and placed immediately after the cloned call site per the IR convention.
264///
265/// For example, the musttail call instruction below:
266///
267/// orig_bb:
268/// %t0 = musttail call i32 %ptr()
269/// ...
270///
271/// Is replaced by the following:
272///
273/// cond_bb:
274/// %cond = Cond
275/// br i1 %cond, %then_bb, %orig_bb
276///
277/// then_bb:
278/// ; The clone of the original call instruction is placed in the "then"
279/// ; block. It is not yet promoted.
280/// %t1 = musttail call i32 %ptr()
281/// ret %t1
282///
283/// orig_bb:
284/// ; The original call instruction stays in its original block.
285/// %t0 = musttail call i32 %ptr()
286/// ret %t0
288 MDNode *BranchWeights) {
289
290 IRBuilder<> Builder(&CB);
291 CallBase *OrigInst = &CB;
292 BasicBlock *OrigBlock = OrigInst->getParent();
293
294 if (OrigInst->isMustTailCall()) {
295 // Create an if-then structure. The original instruction stays in its block,
296 // and a clone of the original instruction is placed in the "then" block.
297 Instruction *ThenTerm =
298 SplitBlockAndInsertIfThen(Cond, &CB, false, BranchWeights);
299 BasicBlock *ThenBlock = ThenTerm->getParent();
300 ThenBlock->setName("if.true.direct_targ");
301 CallBase *NewInst = cast<CallBase>(OrigInst->clone());
302 NewInst->insertBefore(ThenTerm->getIterator());
303
304 // Place a clone of the optional bitcast after the new call site.
305 Value *NewRetVal = NewInst;
306 auto Next = OrigInst->getNextNode();
307 if (auto *BitCast = dyn_cast_or_null<BitCastInst>(Next)) {
308 assert(BitCast->getOperand(0) == OrigInst &&
309 "bitcast following musttail call must use the call");
310 auto NewBitCast = BitCast->clone();
311 NewBitCast->replaceUsesOfWith(OrigInst, NewInst);
312 NewBitCast->insertBefore(ThenTerm->getIterator());
313 NewRetVal = NewBitCast;
314 Next = BitCast->getNextNode();
315 }
316
317 // Place a clone of the return instruction after the new call site.
319 assert(Ret && "musttail call must precede a ret with an optional bitcast");
320 auto NewRet = Ret->clone();
321 if (Ret->getReturnValue())
322 NewRet->replaceUsesOfWith(Ret->getReturnValue(), NewRetVal);
323 NewRet->insertBefore(ThenTerm->getIterator());
324
325 // A return instructions is terminating, so we don't need the terminator
326 // instruction just created.
327 ThenTerm->eraseFromParent();
328
329 return *NewInst;
330 }
331
332 // Create an if-then-else structure. The original instruction is moved into
333 // the "else" block, and a clone of the original instruction is placed in the
334 // "then" block.
335 Instruction *ThenTerm = nullptr;
336 Instruction *ElseTerm = nullptr;
337 SplitBlockAndInsertIfThenElse(Cond, &CB, &ThenTerm, &ElseTerm, BranchWeights);
338 BasicBlock *ThenBlock = ThenTerm->getParent();
339 BasicBlock *ElseBlock = ElseTerm->getParent();
340 BasicBlock *MergeBlock = OrigInst->getParent();
341
342 ThenBlock->setName("if.true.direct_targ");
343 ElseBlock->setName("if.false.orig_indirect");
344 MergeBlock->setName("if.end.icp");
345
346 CallBase *NewInst = cast<CallBase>(OrigInst->clone());
347 OrigInst->moveBefore(ElseTerm->getIterator());
348 NewInst->insertBefore(ThenTerm->getIterator());
349
350 // If the original call site is an invoke instruction, we have extra work to
351 // do since invoke instructions are terminating. We have to fix-up phi nodes
352 // in the invoke's normal and unwind destinations.
353 if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) {
354 auto *NewInvoke = cast<InvokeInst>(NewInst);
355
356 // Invoke instructions are terminating, so we don't need the terminator
357 // instructions that were just created.
358 ThenTerm->eraseFromParent();
359 ElseTerm->eraseFromParent();
360
361 // Branch from the "merge" block to the original normal destination.
362 Builder.SetInsertPoint(MergeBlock);
363 Builder.CreateBr(OrigInvoke->getNormalDest());
364
365 // Fix-up phi nodes in the original invoke's normal and unwind destinations.
366 fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock);
367 fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock);
368
369 // Now set the normal destinations of the invoke instructions to be the
370 // "merge" block.
371 OrigInvoke->setNormalDest(MergeBlock);
372 NewInvoke->setNormalDest(MergeBlock);
373 }
374
375 // Create a phi node for the returned value of the call site.
376 createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
377
378 return *NewInst;
379}
380
381// Predicate and clone the given call site using condition `CB.callee ==
382// Callee`. See the comment `versionCallSiteWithCond` for the transformation.
384 MDNode *BranchWeights) {
385
386 IRBuilder<> Builder(&CB);
387
388 // Create the compare.
389 auto *Cond = Builder.CreateICmpEQ(CB.getCalledOperand(), Callee);
390
391 // The address comparison has made the callee's address significant.
392 // Strip unnamed_addr so the symbol is recorded as address-significant
393 // and kept unique by the linker.
394 if (auto *GV = dyn_cast<GlobalValue>(Callee->stripPointerCasts()))
395 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
396
397 return versionCallSiteWithCond(CB, Cond, BranchWeights);
398}
399
401 const char **FailureReason) {
402 assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted");
403
404 auto &DL = Callee->getDataLayout();
405
406 // Check the return type. The callee's return value type must be bitcast
407 // compatible with the call site's type.
408 Type *CallRetTy = CB.getType();
409 Type *FuncRetTy = Callee->getReturnType();
410 if (CallRetTy != FuncRetTy)
411 if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy, CallRetTy, DL)) {
412 if (FailureReason)
413 *FailureReason = "Return type mismatch";
414 return false;
415 }
416
417 // Capture components that are captured through only the return value require
418 // a pointer return type.
419 if (!FuncRetTy->isPointerTy()) {
420 for (unsigned I = 0, E = CB.arg_size(); I != E; ++I) {
423 if (FailureReason)
424 *FailureReason = "captures(ret: ...) with non-pointer return type";
425 return false;
426 }
427 }
428 }
429
430 // The number of formal arguments of the callee.
431 unsigned NumParams = Callee->getFunctionType()->getNumParams();
432
433 // The number of actual arguments in the call.
434 unsigned NumArgs = CB.arg_size();
435
436 // Check the number of arguments. The callee and call site must agree on the
437 // number of arguments.
438 if (NumArgs != NumParams && !Callee->isVarArg()) {
439 if (FailureReason)
440 *FailureReason = "The number of arguments mismatch";
441 return false;
442 }
443
444 // Check the argument types. The callee's formal argument types must be
445 // bitcast compatible with the corresponding actual argument types of the call
446 // site.
447 unsigned I = 0;
448 for (; I < NumParams; ++I) {
449 // Make sure that the callee and call agree on byval/inalloca. The types do
450 // not have to match.
451 if (Callee->hasParamAttribute(I, Attribute::ByVal) !=
452 CB.getAttributes().hasParamAttr(I, Attribute::ByVal)) {
453 if (FailureReason)
454 *FailureReason = "byval mismatch";
455 return false;
456 }
457 if (Callee->hasParamAttribute(I, Attribute::InAlloca) !=
458 CB.getAttributes().hasParamAttr(I, Attribute::InAlloca)) {
459 if (FailureReason)
460 *FailureReason = "inalloca mismatch";
461 return false;
462 }
463
464 Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I);
465 Type *ActualTy = CB.getArgOperand(I)->getType();
466 if (FormalTy == ActualTy)
467 continue;
468 if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) {
469 if (FailureReason)
470 *FailureReason = "Argument type mismatch";
471 return false;
472 }
473
474 // MustTail call needs stricter type match. See
475 // Verifier::verifyMustTailCall().
476 if (CB.isMustTailCall()) {
477 PointerType *PF = dyn_cast<PointerType>(FormalTy);
478 PointerType *PA = dyn_cast<PointerType>(ActualTy);
479 if (!PF || !PA || PF->getAddressSpace() != PA->getAddressSpace()) {
480 if (FailureReason)
481 *FailureReason = "Musttail call Argument type mismatch";
482 return false;
483 }
484 }
485 }
486 for (; I < NumArgs; I++) {
487 // Vararg functions can have more arguments than parameters.
488 assert(Callee->isVarArg());
489 if (CB.paramHasAttr(I, Attribute::StructRet)) {
490 if (FailureReason)
491 *FailureReason = "SRet arg to vararg function";
492 return false;
493 }
494 }
495
496 return true;
497}
498
500 CastInst **RetBitCast) {
501 assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted");
502
503 // Set the called function of the call site to be the given callee (but don't
504 // change the type).
505 CB.setCalledOperand(Callee);
506
507 // Since the call site will no longer be direct, we must clear metadata that
508 // is only appropriate for indirect calls. This includes !prof and !callees
509 // metadata.
510 CB.setMetadata(LLVMContext::MD_prof, nullptr);
511 CB.setMetadata(LLVMContext::MD_callees, nullptr);
512
513 // If the function type of the call site matches that of the callee, no
514 // additional work is required.
515 if (CB.getFunctionType() == Callee->getFunctionType())
516 return CB;
517
518 // Save the return types of the call site and callee.
519 Type *CallSiteRetTy = CB.getType();
520 Type *CalleeRetTy = Callee->getReturnType();
521
522 // Change the function type of the call site the match that of the callee.
523 CB.mutateFunctionType(Callee->getFunctionType());
524
525 // Inspect the arguments of the call site. If an argument's type doesn't
526 // match the corresponding formal argument's type in the callee, bitcast it
527 // to the correct type.
528 auto CalleeType = Callee->getFunctionType();
529 auto CalleeParamNum = CalleeType->getNumParams();
530
531 LLVMContext &Ctx = Callee->getContext();
532 const AttributeList &CallerPAL = CB.getAttributes();
533 // The new list of argument attributes.
535 bool AttributeChanged = false;
536
537 for (unsigned ArgNo = 0; ArgNo < CalleeParamNum; ++ArgNo) {
538 auto *Arg = CB.getArgOperand(ArgNo);
539 Type *FormalTy = CalleeType->getParamType(ArgNo);
540 Type *ActualTy = Arg->getType();
541 if (FormalTy != ActualTy) {
542 auto *Cast =
543 CastInst::CreateBitOrPointerCast(Arg, FormalTy, "", CB.getIterator());
544 CB.setArgOperand(ArgNo, Cast);
545
546 // Remove any incompatible attributes for the argument.
547 AttrBuilder ArgAttrs(Ctx, CallerPAL.getParamAttrs(ArgNo));
548 ArgAttrs.remove(AttributeFuncs::typeIncompatible(
549 FormalTy, CallerPAL.getParamAttrs(ArgNo)));
550
551 // We may have a different byval/inalloca type.
552 if (ArgAttrs.getByValType())
553 ArgAttrs.addByValAttr(Callee->getParamByValType(ArgNo));
554 if (ArgAttrs.getInAllocaType())
555 ArgAttrs.addInAllocaAttr(Callee->getParamInAllocaType(ArgNo));
556
557 NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs));
558 AttributeChanged = true;
559 } else
560 NewArgAttrs.push_back(CallerPAL.getParamAttrs(ArgNo));
561 }
562
563 // If the return type of the call site doesn't match that of the callee, cast
564 // the returned value to the appropriate type.
565 // Remove any incompatible return value attribute.
566 AttrBuilder RAttrs(Ctx, CallerPAL.getRetAttrs());
567 if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy) {
568 createRetBitCast(CB, CallSiteRetTy, RetBitCast);
569 RAttrs.remove(
570 AttributeFuncs::typeIncompatible(CalleeRetTy, CallerPAL.getRetAttrs()));
571 AttributeChanged = true;
572 }
573
574 // Set the new callsite attribute.
575 if (AttributeChanged)
576 CB.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttrs(),
577 AttributeSet::get(Ctx, RAttrs),
578 NewArgAttrs));
579
580 return CB;
581}
582
584 MDNode *BranchWeights) {
585
586 // Version the indirect call site. If the called value is equal to the given
587 // callee, 'NewInst' will be executed, otherwise the original call site will
588 // be executed.
589 CallBase &NewInst = versionCallSite(CB, Callee, BranchWeights);
590
591 // Promote 'NewInst' so that it directly calls the desired function.
592 return promoteCall(NewInst, Callee);
593}
594
596 PGOContextualProfile &CtxProf) {
598 if (!CtxProf.isFunctionKnown(Callee))
599 return nullptr;
600 auto &Caller = *CB.getFunction();
602 if (!CSInstr)
603 return nullptr;
604 const uint64_t CSIndex = CSInstr->getIndex()->getZExtValue();
605
607 versionCallSite(CB, &Callee, /*BranchWeights=*/nullptr), &Callee);
608 CSInstr->moveBefore(CB.getIterator());
609 const auto NewCSID = CtxProf.allocateNextCallsiteIndex(Caller);
610 auto *NewCSInstr = cast<InstrProfCallsite>(CSInstr->clone());
611 NewCSInstr->setIndex(NewCSID);
612 NewCSInstr->setCallee(&Callee);
613 NewCSInstr->insertBefore(DirectCall.getIterator());
614 auto &DirectBB = *DirectCall.getParent();
615 auto &IndirectBB = *CB.getParent();
616
617 assert((CtxProfAnalysis::getBBInstrumentation(IndirectBB) == nullptr) &&
618 "The ICP direct BB is new, it shouldn't have instrumentation");
619 assert((CtxProfAnalysis::getBBInstrumentation(DirectBB) == nullptr) &&
620 "The ICP indirect BB is new, it shouldn't have instrumentation");
621
622 // Allocate counters for the new basic blocks.
623 const uint32_t DirectID = CtxProf.allocateNextCounterIndex(Caller);
624 const uint32_t IndirectID = CtxProf.allocateNextCounterIndex(Caller);
625 auto *EntryBBIns =
626 CtxProfAnalysis::getBBInstrumentation(Caller.getEntryBlock());
627 auto *DirectBBIns = cast<InstrProfCntrInstBase>(EntryBBIns->clone());
628 DirectBBIns->setIndex(DirectID);
629 DirectBBIns->insertInto(&DirectBB, DirectBB.getFirstInsertionPt());
630
631 auto *IndirectBBIns = cast<InstrProfCntrInstBase>(EntryBBIns->clone());
632 IndirectBBIns->setIndex(IndirectID);
633 IndirectBBIns->insertInto(&IndirectBB, IndirectBB.getFirstInsertionPt());
634
635 const GlobalValue::GUID CalleeGUID = Callee.getGUID();
636 const uint32_t NewCountersSize = IndirectID + 1;
637
638 auto ProfileUpdater = [&](PGOCtxProfContext &Ctx) {
639 assert(Ctx.guid() == Caller.getGUID());
640 assert(NewCountersSize - 2 == Ctx.counters().size());
641 // All the ctx-es belonging to a function must have the same size counters.
642 Ctx.resizeCounters(NewCountersSize);
643
644 // Maybe in this context, the indirect callsite wasn't observed at all. That
645 // would make both direct and indirect BBs cold - which is what we already
646 // have from resising the counters.
647 if (!Ctx.hasCallsite(CSIndex))
648 return;
649 auto &CSData = Ctx.callsite(CSIndex);
650
651 uint64_t TotalCount = 0;
652 for (const auto &[_, V] : CSData)
653 TotalCount += V.getEntrycount();
654 uint64_t DirectCount = 0;
655 // If we called the direct target, update the DirectCount. If we didn't, we
656 // still want to update the indirect BB (to which the TotalCount goes, in
657 // that case).
658 if (auto It = CSData.find(CalleeGUID); It != CSData.end()) {
659 assert(CalleeGUID == It->second.guid());
660 DirectCount = It->second.getEntrycount();
661 // This direct target needs to be moved to this caller under the
662 // newly-allocated callsite index.
663 assert(Ctx.callsites().count(NewCSID) == 0);
664 Ctx.ingestContext(NewCSID, std::move(It->second));
665 CSData.erase(CalleeGUID);
666 }
667
668 assert(TotalCount >= DirectCount);
669 uint64_t IndirectCount = TotalCount - DirectCount;
670 // The ICP's effect is as-if the direct BB would have been taken DirectCount
671 // times, and the indirect BB, IndirectCount times
672 Ctx.counters()[DirectID] = DirectCount;
673 Ctx.counters()[IndirectID] = IndirectCount;
674 };
675 CtxProf.update(ProfileUpdater, Caller);
676 return &DirectCall;
677}
678
680 Function *Callee,
681 ArrayRef<Constant *> AddressPoints,
682 MDNode *BranchWeights) {
683 assert(!AddressPoints.empty() && "Caller should guarantee");
684 IRBuilder<> Builder(&CB);
686 for (auto &AddressPoint : AddressPoints) {
687 ICmps.push_back(Builder.CreateICmpEQ(VPtr, AddressPoint));
688 // The address comparison has made the vtable address significant.
689 // Strip unnamed_addr so the vtable is recorded as address-significant
690 // and kept unique by the linker.
691 if (auto *GV =
692 dyn_cast<GlobalValue>(AddressPoint->stripInBoundsConstantOffsets()))
693 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
694 }
695
696 // TODO: Perform tree height reduction if the number of ICmps is high.
697 Value *Cond = Builder.CreateOr(ICmps);
698
699 // Version the indirect call site. If Cond is true, 'NewInst' will be
700 // executed, otherwise the original call site will be executed.
701 CallBase &NewInst = versionCallSiteWithCond(CB, Cond, BranchWeights);
702
703 // Promote 'NewInst' so that it directly calls the desired function.
704 return promoteCall(NewInst, Callee);
705}
706
709 Module *M = CB.getCaller()->getParent();
710 const DataLayout &DL = M->getDataLayout();
711 Value *Callee = CB.getCalledOperand();
712
713 LoadInst *VTableEntryLoad = dyn_cast<LoadInst>(Callee);
714 if (!VTableEntryLoad)
715 return false; // Not a vtable entry load.
716 Value *VTableEntryPtr = VTableEntryLoad->getPointerOperand();
717 APInt VTableOffset(DL.getIndexTypeSizeInBits(VTableEntryPtr->getType()), 0);
718 Value *VTableBasePtr = VTableEntryPtr->stripAndAccumulateConstantOffsets(
719 DL, VTableOffset, /* AllowNonInbounds */ true);
720 LoadInst *VTablePtrLoad = dyn_cast<LoadInst>(VTableBasePtr);
721 if (!VTablePtrLoad)
722 return false; // Not a vtable load.
723 Value *Object = VTablePtrLoad->getPointerOperand();
724 APInt ObjectOffset(DL.getIndexTypeSizeInBits(Object->getType()), 0);
725 Value *ObjectBase = Object->stripAndAccumulateConstantOffsets(
726 DL, ObjectOffset, /* AllowNonInbounds */ true);
727 if (!(isa<AllocaInst>(ObjectBase) && ObjectOffset == 0))
728 // Not an Alloca or the offset isn't zero.
729 return false;
730
731 // Look for the vtable pointer store into the object by the ctor.
732 BasicBlock::iterator BBI(VTablePtrLoad);
733 Value *VTablePtr = FindAvailableLoadedValue(
734 VTablePtrLoad, VTablePtrLoad->getParent(), BBI, 0, nullptr, nullptr);
735 if (!VTablePtr || !VTablePtr->getType()->isPointerTy())
736 return false; // No vtable found.
737 APInt VTableOffsetGVBase(DL.getIndexTypeSizeInBits(VTablePtr->getType()), 0);
738 Value *VTableGVBase = VTablePtr->stripAndAccumulateConstantOffsets(
739 DL, VTableOffsetGVBase, /* AllowNonInbounds */ true);
740 GlobalVariable *GV = dyn_cast<GlobalVariable>(VTableGVBase);
741 if (!(GV && GV->isConstant() && GV->hasDefinitiveInitializer()))
742 // Not in the form of a global constant variable with an initializer.
743 return false;
744
745 APInt VTableGVOffset = VTableOffsetGVBase + VTableOffset;
746 if (!(VTableGVOffset.getActiveBits() <= 64))
747 return false; // Out of range.
748
749 Function *DirectCallee = nullptr;
750 std::tie(DirectCallee, std::ignore) =
751 getFunctionAtVTableOffset(GV, VTableGVOffset.getZExtValue(), *M);
752 if (!DirectCallee)
753 return false; // No function pointer found.
754
755 if (!isLegalToPromote(CB, DirectCallee))
756 return false;
757
758 // Success.
759 promoteCall(CB, DirectCallee);
760 return true;
761}
762
763#undef DEBUG_TYPE
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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.
#define _
Module.h This file contains the declarations for the Module class.
SmallVector< MachineOperand, 4 > Cond
#define I(x, y, z)
Definition MD5.cpp:57
Reader for contextual iFDO profile, which comes in bitstream format.
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM_ABI CaptureInfo getCaptureInfo() const
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:508
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
AttributeSet getParamAttributes(unsigned ArgNo) const
Return the param attributes for this call.
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
void mutateFunctionType(FunctionType *FTy)
void setArgOperand(unsigned i, Value *v)
FunctionType * getFunctionType() const
void setCalledOperand(Value *V)
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
Represents which components of the pointer may be captured in which location.
Definition ModRef.h:414
CaptureComponents getOtherComponents() const
Get components potentially captured through locations other than the return value.
Definition ModRef.h:446
CaptureComponents getRetComponents() const
Get components potentially captured by the return value.
Definition ModRef.h:442
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI 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 LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static LLVM_ABI InstrProfIncrementInst * getBBInstrumentation(BasicBlock &BB)
Get the instruction instrumenting a BB, or nullptr if not present.
static LLVM_ABI InstrProfCallsite * getCallsiteInstrumentation(CallBase &CB)
Get the instruction instrumenting a callsite, or nullptr if that cannot be found.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Module * getParent()
Get the module that this global value is contained inside of...
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...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Invoke instruction.
BasicBlock * getUnwindDest() const
BasicBlock * getNormalDest() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
Value * getPointerOperand()
Metadata node.
Definition Metadata.h:1087
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The instrumented contextual profile, produced by the CtxProfAnalysis.
LLVM_ABI void update(Visitor, const Function &F)
uint32_t allocateNextCounterIndex(const Function &F)
uint32_t allocateNextCallsiteIndex(const Function &F)
bool isFunctionKnown(const Function &F) const
A node (context) in the loaded contextual profile, suitable for mutation during IPO passes.
Class to represent pointers.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Return a value (possibly void), from a function.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:21
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
bool use_empty() const
Definition Value.h:348
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI 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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI CallBase & promoteCallWithIfThenElse(CallBase &CB, Function *Callee, MDNode *BranchWeights=nullptr)
Promote the given indirect call site to conditionally call Callee.
LLVM_ABI 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:555
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI 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...
LLVM_ABI CallBase & versionCallSite(CallBase &CB, Value *Callee, MDNode *BranchWeights)
Predicate and clone the given call site.
LLVM_ABI CallBase & promoteCall(CallBase &CB, Function *Callee, CastInst **RetBitCast=nullptr)
Promote the given indirect call site to unconditionally call Callee.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool tryPromoteCall(CallBase &CB)
Try to promote (devirtualize) a virtual call on an Alloca.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool capturesAnything(CaptureComponents CC)
Definition ModRef.h:379
LLVM_ABI 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 ...
LLVM_ABI 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...
LLVM_ABI CallBase & promoteCallWithVTableCmp(CallBase &CB, Instruction *VPtr, Function *Callee, ArrayRef< Constant * > AddressPoints, MDNode *BranchWeights)
This is similar to promoteCallWithIfThenElse except that the condition to promote a virtual call is t...
LLVM_ABI 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 ...