blob: 681c5a7de936aa5fc64af39a59d99b1683400d75 [file] [log] [blame]
Matthew Simpsone363d2c2017-12-06 21:22:54 +00001//===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Matthew Simpsone363d2c2017-12-06 21:22:54 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements utilities useful for promoting indirect call sites to
10// direct call sites.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/CallPromotionUtils.h"
15#include "llvm/IR/IRBuilder.h"
16#include "llvm/Transforms/Utils/BasicBlockUtils.h"
17
18using namespace llvm;
19
20#define DEBUG_TYPE "call-promotion-utils"
21
22/// Fix-up phi nodes in an invoke instruction's normal destination.
23///
24/// After versioning an invoke instruction, values coming from the original
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000025/// block will now be coming from the "merge" block. For example, in the code
26/// below:
27///
28/// then_bb:
29/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
30///
31/// else_bb:
32/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
33///
34/// merge_bb:
35/// %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
36/// br %normal_dst
37///
38/// normal_dst:
39/// %t3 = phi i32 [ %x, %orig_bb ], ...
40///
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":
43///
44/// normal_dst:
45/// %t3 = phi i32 [ %x, %merge_bb ], ...
46///
Matthew Simpsone363d2c2017-12-06 21:22:54 +000047static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000048 BasicBlock *MergeBlock) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000049 for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
50 int Idx = Phi.getBasicBlockIndex(OrigBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000051 if (Idx == -1)
52 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000053 Phi.setIncomingBlock(Idx, MergeBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000054 }
55}
56
57/// Fix-up phi nodes in an invoke instruction's unwind destination.
58///
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.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000061/// For example, in the code below:
62///
63/// then_bb:
64/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
65///
66/// else_bb:
67/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
68///
69/// unwind_dst:
70/// %t3 = phi i32 [ %x, %orig_bb ], ...
71///
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":
74///
75/// unwind_dst:
76/// %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
77///
Matthew Simpsone363d2c2017-12-06 21:22:54 +000078static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
79 BasicBlock *ThenBlock,
80 BasicBlock *ElseBlock) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000081 for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
82 int Idx = Phi.getBasicBlockIndex(OrigBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000083 if (Idx == -1)
84 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000085 auto *V = Phi.getIncomingValue(Idx);
86 Phi.setIncomingBlock(Idx, ThenBlock);
87 Phi.addIncoming(V, ElseBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000088 }
89}
90
Matthew Simpsone363d2c2017-12-06 21:22:54 +000091/// Create a phi node for the returned value of a call or invoke instruction.
92///
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
96/// phi node.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000097///
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:
100///
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 ],
103///
104static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
105 BasicBlock *MergeBlock, IRBuilder<> &Builder) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000106
107 if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
108 return;
109
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000110 Builder.SetInsertPoint(&MergeBlock->front());
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000111 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());
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000118 Phi->addIncoming(NewInst, NewInst->getParent());
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000119}
120
121/// Cast a call or invoke instruction to the given type.
122///
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.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000127///
128/// For example, if the call instruction below requires a bitcast after
129/// promotion:
130///
131/// orig_bb:
132/// %t0 = call i32 @func()
133/// ...
134///
135/// The bitcast is placed after the call instruction:
136///
137/// orig_bb:
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 ...
141/// ...
142///
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:
146///
147/// orig_bb:
148/// %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
149///
150/// The edge between the original block and the invoke's normal destination is
151/// split, and the bitcast is placed there:
152///
153/// orig_bb:
154/// %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
155///
156/// split_bb:
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
160///
161static void createRetBitCast(CallSite CS, Type *RetTy, CastInst **RetBitCast) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000162
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);
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 Instruction *InsertBefore = nullptr;
172 if (auto *Invoke = dyn_cast<InvokeInst>(CS.getInstruction()))
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000173 InsertBefore =
174 &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000175 else
176 InsertBefore = &*std::next(CS.getInstruction()->getIterator());
177
178 // Bitcast the return value to the correct type.
Scott Linder3759efc2018-10-10 16:35:47 +0000179 auto *Cast = CastInst::CreateBitOrPointerCast(CS.getInstruction(), RetTy, "",
180 InsertBefore);
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000181 if (RetBitCast)
182 *RetBitCast = Cast;
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000183
184 // Replace all the original uses of the calling instruction with the bitcast.
185 for (User *U : UsersToUpdate)
186 U->replaceUsesOfWith(CS.getInstruction(), Cast);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000187}
188
189/// Predicate and clone the given call site.
190///
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
195/// returned.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000196///
197/// For example, the call instruction below:
198///
199/// orig_bb:
200/// %t0 = call i32 %ptr()
201/// ...
202///
203/// Is replace by the following:
204///
205/// orig_bb:
206/// %cond = icmp eq i32 ()* %ptr, @func
207/// br i1 %cond, %then_bb, %else_bb
208///
209/// then_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()
213/// br merge_bb
214///
215/// else_bb:
216/// ; The original call instruction is moved to the "else" block.
217/// %t0 = call i32 %ptr()
218/// br merge_bb
219///
220/// merge_bb:
221/// ; Uses of the original call instruction are replaced by uses of the phi
222/// ; node.
223/// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
224/// ...
225///
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:
229///
230/// orig_bb:
231/// %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
232///
233/// Is replace by the following:
234///
235/// orig_bb:
236/// %cond = icmp eq i32 ()* %ptr, @func
237/// br i1 %cond, %then_bb, %else_bb
238///
239/// then_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
244///
245/// else_bb:
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
249///
250/// merge_bb:
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 ]
254/// br %normal_dst
255///
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000256static Instruction *versionCallSite(CallSite CS, Value *Callee,
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000257 MDNode *BranchWeights) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000258
259 IRBuilder<> Builder(CS.getInstruction());
260 Instruction *OrigInst = CS.getInstruction();
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000261 BasicBlock *OrigBlock = OrigInst->getParent();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000262
263 // Create the compare. The called value and callee must have the same type to
264 // be compared.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000265 if (CS.getCalledValue()->getType() != Callee->getType())
266 Callee = Builder.CreateBitCast(Callee, CS.getCalledValue()->getType());
267 auto *Cond = Builder.CreateICmpEQ(CS.getCalledValue(), Callee);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000268
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
271 // "then" block.
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000272 Instruction *ThenTerm = nullptr;
273 Instruction *ElseTerm = nullptr;
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000274 SplitBlockAndInsertIfThenElse(Cond, CS.getInstruction(), &ThenTerm, &ElseTerm,
275 BranchWeights);
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000276 BasicBlock *ThenBlock = ThenTerm->getParent();
277 BasicBlock *ElseBlock = ElseTerm->getParent();
278 BasicBlock *MergeBlock = OrigInst->getParent();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000279
280 ThenBlock->setName("if.true.direct_targ");
281 ElseBlock->setName("if.false.orig_indirect");
282 MergeBlock->setName("if.end.icp");
283
284 Instruction *NewInst = OrigInst->clone();
285 OrigInst->moveBefore(ElseTerm);
286 NewInst->insertBefore(ThenTerm);
287
288 // If the original call site is an invoke instruction, we have extra work to
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000289 // do since invoke instructions are terminating. We have to fix-up phi nodes
290 // in the invoke's normal and unwind destinations.
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000291 if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) {
292 auto *NewInvoke = cast<InvokeInst>(NewInst);
293
294 // Invoke instructions are terminating, so we don't need the terminator
295 // instructions that were just created.
296 ThenTerm->eraseFromParent();
297 ElseTerm->eraseFromParent();
298
299 // Branch from the "merge" block to the original normal destination.
300 Builder.SetInsertPoint(MergeBlock);
301 Builder.CreateBr(OrigInvoke->getNormalDest());
302
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000303 // Fix-up phi nodes in the original invoke's normal and unwind destinations.
304 fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock);
305 fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock);
306
307 // Now set the normal destinations of the invoke instructions to be the
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000308 // "merge" block.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000309 OrigInvoke->setNormalDest(MergeBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000310 NewInvoke->setNormalDest(MergeBlock);
311 }
312
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000313 // Create a phi node for the returned value of the call site.
314 createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
315
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000316 return NewInst;
317}
318
319bool llvm::isLegalToPromote(CallSite CS, Function *Callee,
320 const char **FailureReason) {
321 assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
322
Scott Linder3759efc2018-10-10 16:35:47 +0000323 auto &DL = Callee->getParent()->getDataLayout();
324
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000325 // 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)
Scott Linder3759efc2018-10-10 16:35:47 +0000330 if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy, CallRetTy, DL)) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000331 if (FailureReason)
332 *FailureReason = "Return type mismatch";
333 return false;
334 }
335
336 // The number of formal arguments of the callee.
337 unsigned NumParams = Callee->getFunctionType()->getNumParams();
338
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()) {
342 if (FailureReason)
343 *FailureReason = "The number of arguments mismatch";
344 return false;
345 }
346
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
349 // site.
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)
354 continue;
Scott Linder3759efc2018-10-10 16:35:47 +0000355 if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000356 if (FailureReason)
357 *FailureReason = "Argument type mismatch";
358 return false;
359 }
360 }
361
362 return true;
363}
364
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000365Instruction *llvm::promoteCall(CallSite CS, Function *Callee,
366 CastInst **RetBitCast) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000367 assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
368
369 // Set the called function of the call site to be the given callee.
370 CS.setCalledFunction(Callee);
371
372 // Since the call site will no longer be direct, we must clear metadata that
373 // is only appropriate for indirect calls. This includes !prof and !callees
374 // metadata.
375 CS.getInstruction()->setMetadata(LLVMContext::MD_prof, nullptr);
376 CS.getInstruction()->setMetadata(LLVMContext::MD_callees, nullptr);
377
378 // If the function type of the call site matches that of the callee, no
379 // additional work is required.
380 if (CS.getFunctionType() == Callee->getFunctionType())
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000381 return CS.getInstruction();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000382
383 // Save the return types of the call site and callee.
384 Type *CallSiteRetTy = CS.getInstruction()->getType();
385 Type *CalleeRetTy = Callee->getReturnType();
386
387 // Change the function type of the call site the match that of the callee.
388 CS.mutateFunctionType(Callee->getFunctionType());
389
390 // Inspect the arguments of the call site. If an argument's type doesn't
391 // match the corresponding formal argument's type in the callee, bitcast it
392 // to the correct type.
Taewook Oh923c2162018-04-25 17:19:21 +0000393 auto CalleeType = Callee->getFunctionType();
394 auto CalleeParamNum = CalleeType->getNumParams();
Xin Tong04d49772018-11-26 22:03:52 +0000395
396 LLVMContext &Ctx = Callee->getContext();
397 const AttributeList &CallerPAL = CS.getAttributes();
398 // The new list of argument attributes.
399 SmallVector<AttributeSet, 4> NewArgAttrs;
400 bool AttributeChanged = false;
401
Taewook Oh923c2162018-04-25 17:19:21 +0000402 for (unsigned ArgNo = 0; ArgNo < CalleeParamNum; ++ArgNo) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000403 auto *Arg = CS.getArgument(ArgNo);
Taewook Oh923c2162018-04-25 17:19:21 +0000404 Type *FormalTy = CalleeType->getParamType(ArgNo);
405 Type *ActualTy = Arg->getType();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000406 if (FormalTy != ActualTy) {
Scott Linder3759efc2018-10-10 16:35:47 +0000407 auto *Cast = CastInst::CreateBitOrPointerCast(Arg, FormalTy, "",
408 CS.getInstruction());
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000409 CS.setArgument(ArgNo, Cast);
Xin Tong04d49772018-11-26 22:03:52 +0000410
411 // Remove any incompatible attributes for the argument.
412 AttrBuilder ArgAttrs(CallerPAL.getParamAttributes(ArgNo));
413 ArgAttrs.remove(AttributeFuncs::typeIncompatible(FormalTy));
414 NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs));
415 AttributeChanged = true;
416 } else
417 NewArgAttrs.push_back(CallerPAL.getParamAttributes(ArgNo));
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000418 }
419
420 // If the return type of the call site doesn't match that of the callee, cast
421 // the returned value to the appropriate type.
Xin Tong04d49772018-11-26 22:03:52 +0000422 // Remove any incompatible return value attribute.
423 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
424 if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy) {
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000425 createRetBitCast(CS, CallSiteRetTy, RetBitCast);
Xin Tong04d49772018-11-26 22:03:52 +0000426 RAttrs.remove(AttributeFuncs::typeIncompatible(CalleeRetTy));
427 AttributeChanged = true;
428 }
429
430 // Set the new callsite attribute.
431 if (AttributeChanged)
432 CS.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttributes(),
433 AttributeSet::get(Ctx, RAttrs),
434 NewArgAttrs));
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000435
436 return CS.getInstruction();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000437}
438
439Instruction *llvm::promoteCallWithIfThenElse(CallSite CS, Function *Callee,
440 MDNode *BranchWeights) {
441
442 // Version the indirect call site. If the called value is equal to the given
443 // callee, 'NewInst' will be executed, otherwise the original call site will
444 // be executed.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000445 Instruction *NewInst = versionCallSite(CS, Callee, BranchWeights);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000446
447 // Promote 'NewInst' so that it directly calls the desired function.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000448 return promoteCall(CallSite(NewInst), Callee);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000449}
450
451#undef DEBUG_TYPE