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 
14 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
15 #include "llvm/IR/IRBuilder.h"
16 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
17 
18 using 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
25 /// 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 ///
47 static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
48                                       BasicBlock *MergeBlock) {
49   for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
50     int Idx = Phi.getBasicBlockIndex(OrigBlock);
51     if (Idx == -1)
52       continue;
53     Phi.setIncomingBlock(Idx, MergeBlock);
54   }
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.
61 /// 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 ///
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);
83     if (Idx == -1)
84       continue;
85     auto *V = Phi.getIncomingValue(Idx);
86     Phi.setIncomingBlock(Idx, ThenBlock);
87     Phi.addIncoming(V, ElseBlock);
88   }
89 }
90 
91 /// 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.
97 ///
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 ///
104 static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
105                              BasicBlock *MergeBlock, IRBuilder<> &Builder) {
106 
107   if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
108     return;
109 
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());
119 }
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.
127 ///
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 ///
161 static void createRetBitCast(CallSite CS, Type *RetTy, CastInst **RetBitCast) {
162 
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()))
173     InsertBefore =
174         &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front();
175   else
176     InsertBefore = &*std::next(CS.getInstruction()->getIterator());
177 
178   // Bitcast the return value to the correct type.
179   auto *Cast = CastInst::CreateBitOrPointerCast(CS.getInstruction(), RetTy, "",
180                                                 InsertBefore);
181   if (RetBitCast)
182     *RetBitCast = Cast;
183 
184   // Replace all the original uses of the calling instruction with the bitcast.
185   for (User *U : UsersToUpdate)
186     U->replaceUsesOfWith(CS.getInstruction(), Cast);
187 }
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.
196 ///
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 ///
256 static Instruction *versionCallSite(CallSite CS, Value *Callee,
257                                     MDNode *BranchWeights) {
258 
259   IRBuilder<> Builder(CS.getInstruction());
260   Instruction *OrigInst = CS.getInstruction();
261   BasicBlock *OrigBlock = OrigInst->getParent();
262 
263   // Create the compare. The called value and callee must have the same type to
264   // be compared.
265   if (CS.getCalledValue()->getType() != Callee->getType())
266     Callee = Builder.CreateBitCast(Callee, CS.getCalledValue()->getType());
267   auto *Cond = Builder.CreateICmpEQ(CS.getCalledValue(), Callee);
268 
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.
272   Instruction *ThenTerm = nullptr;
273   Instruction *ElseTerm = nullptr;
274   SplitBlockAndInsertIfThenElse(Cond, CS.getInstruction(), &ThenTerm, &ElseTerm,
275                                 BranchWeights);
276   BasicBlock *ThenBlock = ThenTerm->getParent();
277   BasicBlock *ElseBlock = ElseTerm->getParent();
278   BasicBlock *MergeBlock = OrigInst->getParent();
279 
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
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);
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 
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);
306 
307     // Now set the normal destinations of the invoke instructions to be the
308     // "merge" block.
309     OrigInvoke->setNormalDest(MergeBlock);
310     NewInvoke->setNormalDest(MergeBlock);
311   }
312 
313   // Create a phi node for the returned value of the call site.
314   createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
315 
316   return NewInst;
317 }
318 
319 bool llvm::isLegalToPromote(CallSite CS, Function *Callee,
320                             const char **FailureReason) {
321   assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
322 
323   auto &DL = Callee->getParent()->getDataLayout();
324 
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)) {
331       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;
355     if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) {
356       if (FailureReason)
357         *FailureReason = "Argument type mismatch";
358       return false;
359     }
360   }
361 
362   return true;
363 }
364 
365 Instruction *llvm::promoteCall(CallSite CS, Function *Callee,
366                                CastInst **RetBitCast) {
367   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 (but don't
370   // change the type).
371   cast<CallBase>(CS.getInstruction())->setCalledOperand(Callee);
372 
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
375   // metadata.
376   CS.getInstruction()->setMetadata(LLVMContext::MD_prof, nullptr);
377   CS.getInstruction()->setMetadata(LLVMContext::MD_callees, nullptr);
378 
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();
383 
384   // Save the return types of the call site and callee.
385   Type *CallSiteRetTy = CS.getInstruction()->getType();
386   Type *CalleeRetTy = Callee->getReturnType();
387 
388   // Change the function type of the call site the match that of the callee.
389   CS.mutateFunctionType(Callee->getFunctionType());
390 
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();
396 
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;
402 
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);
411 
412       // Remove any incompatible attributes for the argument.
413       AttrBuilder ArgAttrs(CallerPAL.getParamAttributes(ArgNo));
414       ArgAttrs.remove(AttributeFuncs::typeIncompatible(FormalTy));
415 
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());
422       }
423 
424       NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs));
425       AttributeChanged = true;
426     } else
427       NewArgAttrs.push_back(CallerPAL.getParamAttributes(ArgNo));
428   }
429 
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;
438   }
439 
440   // Set the new callsite attribute.
441   if (AttributeChanged)
442     CS.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttributes(),
443                                         AttributeSet::get(Ctx, RAttrs),
444                                         NewArgAttrs));
445 
446   return CS.getInstruction();
447 }
448 
449 Instruction *llvm::promoteCallWithIfThenElse(CallSite CS, Function *Callee,
450                                              MDNode *BranchWeights) {
451 
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
454   // be executed.
455   Instruction *NewInst = versionCallSite(CS, Callee, BranchWeights);
456 
457   // Promote 'NewInst' so that it directly calls the desired function.
458   return promoteCall(CallSite(NewInst), Callee);
459 }
460 
461 #undef DEBUG_TYPE
462