1 //===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements utilities useful for promoting indirect call sites to
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
15 #include "llvm/IR/IRBuilder.h"
16 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 #define DEBUG_TYPE "call-promotion-utils"
22 /// Fix-up phi nodes in an invoke instruction's normal destination.
24 /// After versioning an invoke instruction, values coming from the original
25 /// block will now be coming from the "merge" block. For example, in the code
29 /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
32 /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
35 /// %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
39 /// %t3 = phi i32 [ %x, %orig_bb ], ...
41 /// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in
42 /// "normal_dst" must be fixed to refer to "merge_bb":
45 /// %t3 = phi i32 [ %x, %merge_bb ], ...
47 static void fixupPHINodeForNormalDest(InvokeInst
*Invoke
, BasicBlock
*OrigBlock
,
48 BasicBlock
*MergeBlock
) {
49 for (PHINode
&Phi
: Invoke
->getNormalDest()->phis()) {
50 int Idx
= Phi
.getBasicBlockIndex(OrigBlock
);
53 Phi
.setIncomingBlock(Idx
, MergeBlock
);
57 /// Fix-up phi nodes in an invoke instruction's unwind destination.
59 /// After versioning an invoke instruction, values coming from the original
60 /// block will now be coming from either the "then" block or the "else" block.
61 /// For example, in the code below:
64 /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
67 /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
70 /// %t3 = phi i32 [ %x, %orig_bb ], ...
72 /// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in
73 /// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb":
76 /// %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
78 static void fixupPHINodeForUnwindDest(InvokeInst
*Invoke
, BasicBlock
*OrigBlock
,
79 BasicBlock
*ThenBlock
,
80 BasicBlock
*ElseBlock
) {
81 for (PHINode
&Phi
: Invoke
->getUnwindDest()->phis()) {
82 int Idx
= Phi
.getBasicBlockIndex(OrigBlock
);
85 auto *V
= Phi
.getIncomingValue(Idx
);
86 Phi
.setIncomingBlock(Idx
, ThenBlock
);
87 Phi
.addIncoming(V
, ElseBlock
);
91 /// Create a phi node for the returned value of a call or invoke instruction.
93 /// After versioning a call or invoke instruction that returns a value, we have
94 /// to merge the value of the original and new instructions. We do this by
95 /// creating a phi node and replacing uses of the original instruction with this
98 /// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is
99 /// defined in "then_bb", we create the following phi node:
101 /// ; Uses of the original instruction are replaced by uses of the phi node.
102 /// %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ],
104 static void createRetPHINode(Instruction
*OrigInst
, Instruction
*NewInst
,
105 BasicBlock
*MergeBlock
, IRBuilder
<> &Builder
) {
107 if (OrigInst
->getType()->isVoidTy() || OrigInst
->use_empty())
110 Builder
.SetInsertPoint(&MergeBlock
->front());
111 PHINode
*Phi
= Builder
.CreatePHI(OrigInst
->getType(), 0);
112 SmallVector
<User
*, 16> UsersToUpdate
;
113 for (User
*U
: OrigInst
->users())
114 UsersToUpdate
.push_back(U
);
115 for (User
*U
: UsersToUpdate
)
116 U
->replaceUsesOfWith(OrigInst
, Phi
);
117 Phi
->addIncoming(OrigInst
, OrigInst
->getParent());
118 Phi
->addIncoming(NewInst
, NewInst
->getParent());
121 /// Cast a call or invoke instruction to the given type.
123 /// When promoting a call site, the return type of the call site might not match
124 /// that of the callee. If this is the case, we have to cast the returned value
125 /// to the correct type. The location of the cast depends on if we have a call
126 /// or invoke instruction.
128 /// For example, if the call instruction below requires a bitcast after
132 /// %t0 = call i32 @func()
135 /// The bitcast is placed after the call instruction:
138 /// ; Uses of the original return value are replaced by uses of the bitcast.
139 /// %t0 = call i32 @func()
140 /// %t1 = bitcast i32 %t0 to ...
143 /// A similar transformation is performed for invoke instructions. However,
144 /// since invokes are terminating, a new block is created for the bitcast. For
145 /// example, if the invoke instruction below requires a bitcast after promotion:
148 /// %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
150 /// The edge between the original block and the invoke's normal destination is
151 /// split, and the bitcast is placed there:
154 /// %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
157 /// ; Uses of the original return value are replaced by uses of the bitcast.
158 /// %t1 = bitcast i32 %t0 to ...
159 /// br label %normal_dst
161 static void createRetBitCast(CallSite CS
, Type
*RetTy
, CastInst
**RetBitCast
) {
163 // Save the users of the calling instruction. These uses will be changed to
164 // use the bitcast after we create it.
165 SmallVector
<User
*, 16> UsersToUpdate
;
166 for (User
*U
: CS
.getInstruction()->users())
167 UsersToUpdate
.push_back(U
);
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 Instruction
*InsertBefore
= nullptr;
172 if (auto *Invoke
= dyn_cast
<InvokeInst
>(CS
.getInstruction()))
174 &SplitEdge(Invoke
->getParent(), Invoke
->getNormalDest())->front();
176 InsertBefore
= &*std::next(CS
.getInstruction()->getIterator());
178 // Bitcast the return value to the correct type.
179 auto *Cast
= CastInst::CreateBitOrPointerCast(CS
.getInstruction(), RetTy
, "",
184 // Replace all the original uses of the calling instruction with the bitcast.
185 for (User
*U
: UsersToUpdate
)
186 U
->replaceUsesOfWith(CS
.getInstruction(), Cast
);
189 /// Predicate and clone the given call site.
191 /// This function creates an if-then-else structure at the location of the call
192 /// site. The "if" condition compares the call site's called value to the given
193 /// callee. The original call site is moved into the "else" block, and a clone
194 /// of the call site is placed in the "then" block. The cloned instruction is
197 /// For example, the call instruction below:
200 /// %t0 = call i32 %ptr()
203 /// Is replace by the following:
206 /// %cond = icmp eq i32 ()* %ptr, @func
207 /// br i1 %cond, %then_bb, %else_bb
210 /// ; The clone of the original call instruction is placed in the "then"
211 /// ; block. It is not yet promoted.
212 /// %t1 = call i32 %ptr()
216 /// ; The original call instruction is moved to the "else" block.
217 /// %t0 = call i32 %ptr()
221 /// ; Uses of the original call instruction are replaced by uses of the phi
223 /// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
226 /// A similar transformation is performed for invoke instructions. However,
227 /// since invokes are terminating, more work is required. For example, the
228 /// invoke instruction below:
231 /// %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
233 /// Is replace by the following:
236 /// %cond = icmp eq i32 ()* %ptr, @func
237 /// br i1 %cond, %then_bb, %else_bb
240 /// ; The clone of the original invoke instruction is placed in the "then"
241 /// ; block, and its normal destination is set to the "merge" block. It is
242 /// ; not yet promoted.
243 /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
246 /// ; The original invoke instruction is moved into the "else" block, and
247 /// ; its normal destination is set to the "merge" block.
248 /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
251 /// ; Uses of the original invoke instruction are replaced by uses of the
252 /// ; phi node, and the merge block branches to the normal destination.
253 /// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
256 static Instruction
*versionCallSite(CallSite CS
, Value
*Callee
,
257 MDNode
*BranchWeights
) {
259 IRBuilder
<> Builder(CS
.getInstruction());
260 Instruction
*OrigInst
= CS
.getInstruction();
261 BasicBlock
*OrigBlock
= OrigInst
->getParent();
263 // Create the compare. The called value and callee must have the same type to
265 if (CS
.getCalledValue()->getType() != Callee
->getType())
266 Callee
= Builder
.CreateBitCast(Callee
, CS
.getCalledValue()->getType());
267 auto *Cond
= Builder
.CreateICmpEQ(CS
.getCalledValue(), Callee
);
269 // Create an if-then-else structure. The original instruction is moved into
270 // the "else" block, and a clone of the original instruction is placed in the
272 Instruction
*ThenTerm
= nullptr;
273 Instruction
*ElseTerm
= nullptr;
274 SplitBlockAndInsertIfThenElse(Cond
, CS
.getInstruction(), &ThenTerm
, &ElseTerm
,
276 BasicBlock
*ThenBlock
= ThenTerm
->getParent();
277 BasicBlock
*ElseBlock
= ElseTerm
->getParent();
278 BasicBlock
*MergeBlock
= OrigInst
->getParent();
280 ThenBlock
->setName("if.true.direct_targ");
281 ElseBlock
->setName("if.false.orig_indirect");
282 MergeBlock
->setName("if.end.icp");
284 Instruction
*NewInst
= OrigInst
->clone();
285 OrigInst
->moveBefore(ElseTerm
);
286 NewInst
->insertBefore(ThenTerm
);
288 // If the original call site is an invoke instruction, we have extra work to
289 // do since invoke instructions are terminating. We have to fix-up phi nodes
290 // in the invoke's normal and unwind destinations.
291 if (auto *OrigInvoke
= dyn_cast
<InvokeInst
>(OrigInst
)) {
292 auto *NewInvoke
= cast
<InvokeInst
>(NewInst
);
294 // Invoke instructions are terminating, so we don't need the terminator
295 // instructions that were just created.
296 ThenTerm
->eraseFromParent();
297 ElseTerm
->eraseFromParent();
299 // Branch from the "merge" block to the original normal destination.
300 Builder
.SetInsertPoint(MergeBlock
);
301 Builder
.CreateBr(OrigInvoke
->getNormalDest());
303 // Fix-up phi nodes in the original invoke's normal and unwind destinations.
304 fixupPHINodeForNormalDest(OrigInvoke
, OrigBlock
, MergeBlock
);
305 fixupPHINodeForUnwindDest(OrigInvoke
, MergeBlock
, ThenBlock
, ElseBlock
);
307 // Now set the normal destinations of the invoke instructions to be the
309 OrigInvoke
->setNormalDest(MergeBlock
);
310 NewInvoke
->setNormalDest(MergeBlock
);
313 // Create a phi node for the returned value of the call site.
314 createRetPHINode(OrigInst
, NewInst
, MergeBlock
, Builder
);
319 bool llvm::isLegalToPromote(CallSite CS
, Function
*Callee
,
320 const char **FailureReason
) {
321 assert(!CS
.getCalledFunction() && "Only indirect call sites can be promoted");
323 auto &DL
= Callee
->getParent()->getDataLayout();
325 // Check the return type. The callee's return value type must be bitcast
326 // compatible with the call site's type.
327 Type
*CallRetTy
= CS
.getInstruction()->getType();
328 Type
*FuncRetTy
= Callee
->getReturnType();
329 if (CallRetTy
!= FuncRetTy
)
330 if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy
, CallRetTy
, DL
)) {
332 *FailureReason
= "Return type mismatch";
336 // The number of formal arguments of the callee.
337 unsigned NumParams
= Callee
->getFunctionType()->getNumParams();
339 // Check the number of arguments. The callee and call site must agree on the
340 // number of arguments.
341 if (CS
.arg_size() != NumParams
&& !Callee
->isVarArg()) {
343 *FailureReason
= "The number of arguments mismatch";
347 // Check the argument types. The callee's formal argument types must be
348 // bitcast compatible with the corresponding actual argument types of the call
350 for (unsigned I
= 0; I
< NumParams
; ++I
) {
351 Type
*FormalTy
= Callee
->getFunctionType()->getFunctionParamType(I
);
352 Type
*ActualTy
= CS
.getArgument(I
)->getType();
353 if (FormalTy
== ActualTy
)
355 if (!CastInst::isBitOrNoopPointerCastable(ActualTy
, FormalTy
, DL
)) {
357 *FailureReason
= "Argument type mismatch";
365 Instruction
*llvm::promoteCall(CallSite CS
, Function
*Callee
,
366 CastInst
**RetBitCast
) {
367 assert(!CS
.getCalledFunction() && "Only indirect call sites can be promoted");
369 // Set the called function of the call site to be the given callee (but don't
371 cast
<CallBase
>(CS
.getInstruction())->setCalledOperand(Callee
);
373 // Since the call site will no longer be direct, we must clear metadata that
374 // is only appropriate for indirect calls. This includes !prof and !callees
376 CS
.getInstruction()->setMetadata(LLVMContext::MD_prof
, nullptr);
377 CS
.getInstruction()->setMetadata(LLVMContext::MD_callees
, nullptr);
379 // If the function type of the call site matches that of the callee, no
380 // additional work is required.
381 if (CS
.getFunctionType() == Callee
->getFunctionType())
382 return CS
.getInstruction();
384 // Save the return types of the call site and callee.
385 Type
*CallSiteRetTy
= CS
.getInstruction()->getType();
386 Type
*CalleeRetTy
= Callee
->getReturnType();
388 // Change the function type of the call site the match that of the callee.
389 CS
.mutateFunctionType(Callee
->getFunctionType());
391 // Inspect the arguments of the call site. If an argument's type doesn't
392 // match the corresponding formal argument's type in the callee, bitcast it
393 // to the correct type.
394 auto CalleeType
= Callee
->getFunctionType();
395 auto CalleeParamNum
= CalleeType
->getNumParams();
397 LLVMContext
&Ctx
= Callee
->getContext();
398 const AttributeList
&CallerPAL
= CS
.getAttributes();
399 // The new list of argument attributes.
400 SmallVector
<AttributeSet
, 4> NewArgAttrs
;
401 bool AttributeChanged
= false;
403 for (unsigned ArgNo
= 0; ArgNo
< CalleeParamNum
; ++ArgNo
) {
404 auto *Arg
= CS
.getArgument(ArgNo
);
405 Type
*FormalTy
= CalleeType
->getParamType(ArgNo
);
406 Type
*ActualTy
= Arg
->getType();
407 if (FormalTy
!= ActualTy
) {
408 auto *Cast
= CastInst::CreateBitOrPointerCast(Arg
, FormalTy
, "",
409 CS
.getInstruction());
410 CS
.setArgument(ArgNo
, Cast
);
412 // Remove any incompatible attributes for the argument.
413 AttrBuilder
ArgAttrs(CallerPAL
.getParamAttributes(ArgNo
));
414 ArgAttrs
.remove(AttributeFuncs::typeIncompatible(FormalTy
));
416 // If byval is used, this must be a pointer type, and the byval type must
417 // match the element type. Update it if present.
418 if (ArgAttrs
.getByValType()) {
419 Type
*NewTy
= Callee
->getParamByValType(ArgNo
);
420 ArgAttrs
.addByValAttr(
421 NewTy
? NewTy
: cast
<PointerType
>(FormalTy
)->getElementType());
424 NewArgAttrs
.push_back(AttributeSet::get(Ctx
, ArgAttrs
));
425 AttributeChanged
= true;
427 NewArgAttrs
.push_back(CallerPAL
.getParamAttributes(ArgNo
));
430 // If the return type of the call site doesn't match that of the callee, cast
431 // the returned value to the appropriate type.
432 // Remove any incompatible return value attribute.
433 AttrBuilder
RAttrs(CallerPAL
, AttributeList::ReturnIndex
);
434 if (!CallSiteRetTy
->isVoidTy() && CallSiteRetTy
!= CalleeRetTy
) {
435 createRetBitCast(CS
, CallSiteRetTy
, RetBitCast
);
436 RAttrs
.remove(AttributeFuncs::typeIncompatible(CalleeRetTy
));
437 AttributeChanged
= true;
440 // Set the new callsite attribute.
441 if (AttributeChanged
)
442 CS
.setAttributes(AttributeList::get(Ctx
, CallerPAL
.getFnAttributes(),
443 AttributeSet::get(Ctx
, RAttrs
),
446 return CS
.getInstruction();
449 Instruction
*llvm::promoteCallWithIfThenElse(CallSite CS
, Function
*Callee
,
450 MDNode
*BranchWeights
) {
452 // Version the indirect call site. If the called value is equal to the given
453 // callee, 'NewInst' will be executed, otherwise the original call site will
455 Instruction
*NewInst
= versionCallSite(CS
, Callee
, BranchWeights
);
457 // Promote 'NewInst' so that it directly calls the desired function.
458 return promoteCall(CallSite(NewInst
), Callee
);