blob: 5dc6068d4a0b1e7fa9535058ef4d6da54b2835ab [file] [log] [blame]
Matthew Simpsone363d2c2017-12-06 21:22:54 +00001//===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements utilities useful for promoting indirect call sites to
11// direct call sites.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/CallPromotionUtils.h"
16#include "llvm/IR/IRBuilder.h"
17#include "llvm/Transforms/Utils/BasicBlockUtils.h"
18
19using namespace llvm;
20
21#define DEBUG_TYPE "call-promotion-utils"
22
23/// Fix-up phi nodes in an invoke instruction's normal destination.
24///
25/// After versioning an invoke instruction, values coming from the original
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000026/// block will now be coming from the "merge" block. For example, in the code
27/// below:
28///
29/// then_bb:
30/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
31///
32/// else_bb:
33/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
34///
35/// merge_bb:
36/// %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
37/// br %normal_dst
38///
39/// normal_dst:
40/// %t3 = phi i32 [ %x, %orig_bb ], ...
41///
42/// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in
43/// "normal_dst" must be fixed to refer to "merge_bb":
44///
45/// normal_dst:
46/// %t3 = phi i32 [ %x, %merge_bb ], ...
47///
Matthew Simpsone363d2c2017-12-06 21:22:54 +000048static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000049 BasicBlock *MergeBlock) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000050 for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
51 int Idx = Phi.getBasicBlockIndex(OrigBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000052 if (Idx == -1)
53 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000054 Phi.setIncomingBlock(Idx, MergeBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000055 }
56}
57
58/// Fix-up phi nodes in an invoke instruction's unwind destination.
59///
60/// After versioning an invoke instruction, values coming from the original
61/// block will now be coming from either the "then" block or the "else" block.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000062/// For example, in the code below:
63///
64/// then_bb:
65/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
66///
67/// else_bb:
68/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
69///
70/// unwind_dst:
71/// %t3 = phi i32 [ %x, %orig_bb ], ...
72///
73/// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in
74/// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb":
75///
76/// unwind_dst:
77/// %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
78///
Matthew Simpsone363d2c2017-12-06 21:22:54 +000079static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
80 BasicBlock *ThenBlock,
81 BasicBlock *ElseBlock) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000082 for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
83 int Idx = Phi.getBasicBlockIndex(OrigBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000084 if (Idx == -1)
85 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000086 auto *V = Phi.getIncomingValue(Idx);
87 Phi.setIncomingBlock(Idx, ThenBlock);
88 Phi.addIncoming(V, ElseBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000089 }
90}
91
Matthew Simpsone363d2c2017-12-06 21:22:54 +000092/// Create a phi node for the returned value of a call or invoke instruction.
93///
94/// After versioning a call or invoke instruction that returns a value, we have
95/// to merge the value of the original and new instructions. We do this by
96/// creating a phi node and replacing uses of the original instruction with this
97/// phi node.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000098///
99/// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is
100/// defined in "then_bb", we create the following phi node:
101///
102/// ; Uses of the original instruction are replaced by uses of the phi node.
103/// %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ],
104///
105static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
106 BasicBlock *MergeBlock, IRBuilder<> &Builder) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000107
108 if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
109 return;
110
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000111 Builder.SetInsertPoint(&MergeBlock->front());
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000112 PHINode *Phi = Builder.CreatePHI(OrigInst->getType(), 0);
113 SmallVector<User *, 16> UsersToUpdate;
114 for (User *U : OrigInst->users())
115 UsersToUpdate.push_back(U);
116 for (User *U : UsersToUpdate)
117 U->replaceUsesOfWith(OrigInst, Phi);
118 Phi->addIncoming(OrigInst, OrigInst->getParent());
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000119 Phi->addIncoming(NewInst, NewInst->getParent());
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000120}
121
122/// Cast a call or invoke instruction to the given type.
123///
124/// When promoting a call site, the return type of the call site might not match
125/// that of the callee. If this is the case, we have to cast the returned value
126/// to the correct type. The location of the cast depends on if we have a call
127/// or invoke instruction.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000128///
129/// For example, if the call instruction below requires a bitcast after
130/// promotion:
131///
132/// orig_bb:
133/// %t0 = call i32 @func()
134/// ...
135///
136/// The bitcast is placed after the call instruction:
137///
138/// orig_bb:
139/// ; Uses of the original return value are replaced by uses of the bitcast.
140/// %t0 = call i32 @func()
141/// %t1 = bitcast i32 %t0 to ...
142/// ...
143///
144/// A similar transformation is performed for invoke instructions. However,
145/// since invokes are terminating, a new block is created for the bitcast. For
146/// example, if the invoke instruction below requires a bitcast after promotion:
147///
148/// orig_bb:
149/// %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
150///
151/// The edge between the original block and the invoke's normal destination is
152/// split, and the bitcast is placed there:
153///
154/// orig_bb:
155/// %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
156///
157/// split_bb:
158/// ; Uses of the original return value are replaced by uses of the bitcast.
159/// %t1 = bitcast i32 %t0 to ...
160/// br label %normal_dst
161///
162static void createRetBitCast(CallSite CS, Type *RetTy, CastInst **RetBitCast) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000163
164 // Save the users of the calling instruction. These uses will be changed to
165 // use the bitcast after we create it.
166 SmallVector<User *, 16> UsersToUpdate;
167 for (User *U : CS.getInstruction()->users())
168 UsersToUpdate.push_back(U);
169
170 // Determine an appropriate location to create the bitcast for the return
171 // value. The location depends on if we have a call or invoke instruction.
172 Instruction *InsertBefore = nullptr;
173 if (auto *Invoke = dyn_cast<InvokeInst>(CS.getInstruction()))
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000174 InsertBefore =
175 &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000176 else
177 InsertBefore = &*std::next(CS.getInstruction()->getIterator());
178
179 // Bitcast the return value to the correct type.
180 auto *Cast = CastInst::Create(Instruction::BitCast, CS.getInstruction(),
181 RetTy, "", InsertBefore);
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000182 if (RetBitCast)
183 *RetBitCast = Cast;
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000184
185 // Replace all the original uses of the calling instruction with the bitcast.
186 for (User *U : UsersToUpdate)
187 U->replaceUsesOfWith(CS.getInstruction(), Cast);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000188}
189
190/// Predicate and clone the given call site.
191///
192/// This function creates an if-then-else structure at the location of the call
193/// site. The "if" condition compares the call site's called value to the given
194/// callee. The original call site is moved into the "else" block, and a clone
195/// of the call site is placed in the "then" block. The cloned instruction is
196/// returned.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000197///
198/// For example, the call instruction below:
199///
200/// orig_bb:
201/// %t0 = call i32 %ptr()
202/// ...
203///
204/// Is replace by the following:
205///
206/// orig_bb:
207/// %cond = icmp eq i32 ()* %ptr, @func
208/// br i1 %cond, %then_bb, %else_bb
209///
210/// then_bb:
211/// ; The clone of the original call instruction is placed in the "then"
212/// ; block. It is not yet promoted.
213/// %t1 = call i32 %ptr()
214/// br merge_bb
215///
216/// else_bb:
217/// ; The original call instruction is moved to the "else" block.
218/// %t0 = call i32 %ptr()
219/// br merge_bb
220///
221/// merge_bb:
222/// ; Uses of the original call instruction are replaced by uses of the phi
223/// ; node.
224/// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
225/// ...
226///
227/// A similar transformation is performed for invoke instructions. However,
228/// since invokes are terminating, more work is required. For example, the
229/// invoke instruction below:
230///
231/// orig_bb:
232/// %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
233///
234/// Is replace by the following:
235///
236/// orig_bb:
237/// %cond = icmp eq i32 ()* %ptr, @func
238/// br i1 %cond, %then_bb, %else_bb
239///
240/// then_bb:
241/// ; The clone of the original invoke instruction is placed in the "then"
242/// ; block, and its normal destination is set to the "merge" block. It is
243/// ; not yet promoted.
244/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
245///
246/// else_bb:
247/// ; The original invoke instruction is moved into the "else" block, and
248/// ; its normal destination is set to the "merge" block.
249/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
250///
251/// merge_bb:
252/// ; Uses of the original invoke instruction are replaced by uses of the
253/// ; phi node, and the merge block branches to the normal destination.
254/// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
255/// br %normal_dst
256///
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000257static Instruction *versionCallSite(CallSite CS, Value *Callee,
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000258 MDNode *BranchWeights) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000259
260 IRBuilder<> Builder(CS.getInstruction());
261 Instruction *OrigInst = CS.getInstruction();
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000262 BasicBlock *OrigBlock = OrigInst->getParent();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000263
264 // Create the compare. The called value and callee must have the same type to
265 // be compared.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000266 if (CS.getCalledValue()->getType() != Callee->getType())
267 Callee = Builder.CreateBitCast(Callee, CS.getCalledValue()->getType());
268 auto *Cond = Builder.CreateICmpEQ(CS.getCalledValue(), Callee);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000269
270 // Create an if-then-else structure. The original instruction is moved into
271 // the "else" block, and a clone of the original instruction is placed in the
272 // "then" block.
273 TerminatorInst *ThenTerm = nullptr;
274 TerminatorInst *ElseTerm = nullptr;
275 SplitBlockAndInsertIfThenElse(Cond, CS.getInstruction(), &ThenTerm, &ElseTerm,
276 BranchWeights);
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000277 BasicBlock *ThenBlock = ThenTerm->getParent();
278 BasicBlock *ElseBlock = ElseTerm->getParent();
279 BasicBlock *MergeBlock = OrigInst->getParent();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000280
281 ThenBlock->setName("if.true.direct_targ");
282 ElseBlock->setName("if.false.orig_indirect");
283 MergeBlock->setName("if.end.icp");
284
285 Instruction *NewInst = OrigInst->clone();
286 OrigInst->moveBefore(ElseTerm);
287 NewInst->insertBefore(ThenTerm);
288
289 // If the original call site is an invoke instruction, we have extra work to
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000290 // do since invoke instructions are terminating. We have to fix-up phi nodes
291 // in the invoke's normal and unwind destinations.
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000292 if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) {
293 auto *NewInvoke = cast<InvokeInst>(NewInst);
294
295 // Invoke instructions are terminating, so we don't need the terminator
296 // instructions that were just created.
297 ThenTerm->eraseFromParent();
298 ElseTerm->eraseFromParent();
299
300 // Branch from the "merge" block to the original normal destination.
301 Builder.SetInsertPoint(MergeBlock);
302 Builder.CreateBr(OrigInvoke->getNormalDest());
303
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000304 // Fix-up phi nodes in the original invoke's normal and unwind destinations.
305 fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock);
306 fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock);
307
308 // Now set the normal destinations of the invoke instructions to be the
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000309 // "merge" block.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000310 OrigInvoke->setNormalDest(MergeBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000311 NewInvoke->setNormalDest(MergeBlock);
312 }
313
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000314 // Create a phi node for the returned value of the call site.
315 createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
316
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000317 return NewInst;
318}
319
320bool llvm::isLegalToPromote(CallSite CS, Function *Callee,
321 const char **FailureReason) {
322 assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
323
324 // Check the return type. The callee's return value type must be bitcast
325 // compatible with the call site's type.
326 Type *CallRetTy = CS.getInstruction()->getType();
327 Type *FuncRetTy = Callee->getReturnType();
328 if (CallRetTy != FuncRetTy)
329 if (!CastInst::isBitCastable(FuncRetTy, CallRetTy)) {
330 if (FailureReason)
331 *FailureReason = "Return type mismatch";
332 return false;
333 }
334
335 // The number of formal arguments of the callee.
336 unsigned NumParams = Callee->getFunctionType()->getNumParams();
337
338 // Check the number of arguments. The callee and call site must agree on the
339 // number of arguments.
340 if (CS.arg_size() != NumParams && !Callee->isVarArg()) {
341 if (FailureReason)
342 *FailureReason = "The number of arguments mismatch";
343 return false;
344 }
345
346 // Check the argument types. The callee's formal argument types must be
347 // bitcast compatible with the corresponding actual argument types of the call
348 // site.
349 for (unsigned I = 0; I < NumParams; ++I) {
350 Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I);
351 Type *ActualTy = CS.getArgument(I)->getType();
352 if (FormalTy == ActualTy)
353 continue;
354 if (!CastInst::isBitCastable(ActualTy, FormalTy)) {
355 if (FailureReason)
356 *FailureReason = "Argument type mismatch";
357 return false;
358 }
359 }
360
361 return true;
362}
363
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000364Instruction *llvm::promoteCall(CallSite CS, Function *Callee,
365 CastInst **RetBitCast) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000366 assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
367
368 // Set the called function of the call site to be the given callee.
369 CS.setCalledFunction(Callee);
370
371 // Since the call site will no longer be direct, we must clear metadata that
372 // is only appropriate for indirect calls. This includes !prof and !callees
373 // metadata.
374 CS.getInstruction()->setMetadata(LLVMContext::MD_prof, nullptr);
375 CS.getInstruction()->setMetadata(LLVMContext::MD_callees, nullptr);
376
377 // If the function type of the call site matches that of the callee, no
378 // additional work is required.
379 if (CS.getFunctionType() == Callee->getFunctionType())
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000380 return CS.getInstruction();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000381
382 // Save the return types of the call site and callee.
383 Type *CallSiteRetTy = CS.getInstruction()->getType();
384 Type *CalleeRetTy = Callee->getReturnType();
385
386 // Change the function type of the call site the match that of the callee.
387 CS.mutateFunctionType(Callee->getFunctionType());
388
389 // Inspect the arguments of the call site. If an argument's type doesn't
390 // match the corresponding formal argument's type in the callee, bitcast it
391 // to the correct type.
392 for (Use &U : CS.args()) {
393 unsigned ArgNo = CS.getArgumentNo(&U);
394 Type *FormalTy = Callee->getFunctionType()->getParamType(ArgNo);
395 Type *ActualTy = U.get()->getType();
396 if (FormalTy != ActualTy) {
397 auto *Cast = CastInst::Create(Instruction::BitCast, U.get(), FormalTy, "",
398 CS.getInstruction());
399 CS.setArgument(ArgNo, Cast);
400 }
401 }
402
403 // If the return type of the call site doesn't match that of the callee, cast
404 // the returned value to the appropriate type.
405 if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy)
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000406 createRetBitCast(CS, CallSiteRetTy, RetBitCast);
407
408 return CS.getInstruction();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000409}
410
411Instruction *llvm::promoteCallWithIfThenElse(CallSite CS, Function *Callee,
412 MDNode *BranchWeights) {
413
414 // Version the indirect call site. If the called value is equal to the given
415 // callee, 'NewInst' will be executed, otherwise the original call site will
416 // be executed.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000417 Instruction *NewInst = versionCallSite(CS, Callee, BranchWeights);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000418
419 // Promote 'NewInst' so that it directly calls the desired function.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000420 return promoteCall(CallSite(NewInst), Callee);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000421}
422
423#undef DEBUG_TYPE