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/Analysis/Loads.h"
16 #include "llvm/Analysis/TypeMetadataUtils.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
19 
20 using namespace llvm;
21 
22 #define DEBUG_TYPE "call-promotion-utils"
23 
24 /// Fix-up phi nodes in an invoke instruction's normal destination.
25 ///
26 /// After versioning an invoke instruction, values coming from the original
27 /// block will now be coming from the "merge" block. For example, in the code
28 /// below:
29 ///
30 ///   then_bb:
31 ///     %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
32 ///
33 ///   else_bb:
34 ///     %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
35 ///
36 ///   merge_bb:
37 ///     %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
38 ///     br %normal_dst
39 ///
40 ///   normal_dst:
41 ///     %t3 = phi i32 [ %x, %orig_bb ], ...
42 ///
43 /// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in
44 /// "normal_dst" must be fixed to refer to "merge_bb":
45 ///
46 ///    normal_dst:
47 ///      %t3 = phi i32 [ %x, %merge_bb ], ...
48 ///
49 static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
50                                       BasicBlock *MergeBlock) {
51   for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
52     int Idx = Phi.getBasicBlockIndex(OrigBlock);
53     if (Idx == -1)
54       continue;
55     Phi.setIncomingBlock(Idx, MergeBlock);
56   }
57 }
58 
59 /// Fix-up phi nodes in an invoke instruction's unwind destination.
60 ///
61 /// After versioning an invoke instruction, values coming from the original
62 /// block will now be coming from either the "then" block or the "else" block.
63 /// For example, in the code below:
64 ///
65 ///   then_bb:
66 ///     %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
67 ///
68 ///   else_bb:
69 ///     %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
70 ///
71 ///   unwind_dst:
72 ///     %t3 = phi i32 [ %x, %orig_bb ], ...
73 ///
74 /// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in
75 /// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb":
76 ///
77 ///   unwind_dst:
78 ///     %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
79 ///
80 static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
81                                       BasicBlock *ThenBlock,
82                                       BasicBlock *ElseBlock) {
83   for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
84     int Idx = Phi.getBasicBlockIndex(OrigBlock);
85     if (Idx == -1)
86       continue;
87     auto *V = Phi.getIncomingValue(Idx);
88     Phi.setIncomingBlock(Idx, ThenBlock);
89     Phi.addIncoming(V, ElseBlock);
90   }
91 }
92 
93 /// Create a phi node for the returned value of a call or invoke instruction.
94 ///
95 /// After versioning a call or invoke instruction that returns a value, we have
96 /// to merge the value of the original and new instructions. We do this by
97 /// creating a phi node and replacing uses of the original instruction with this
98 /// phi node.
99 ///
100 /// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is
101 /// defined in "then_bb", we create the following phi node:
102 ///
103 ///   ; Uses of the original instruction are replaced by uses of the phi node.
104 ///   %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ],
105 ///
106 static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
107                              BasicBlock *MergeBlock, IRBuilder<> &Builder) {
108 
109   if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
110     return;
111 
112   Builder.SetInsertPoint(&MergeBlock->front());
113   PHINode *Phi = Builder.CreatePHI(OrigInst->getType(), 0);
114   SmallVector<User *, 16> UsersToUpdate;
115   for (User *U : OrigInst->users())
116     UsersToUpdate.push_back(U);
117   for (User *U : UsersToUpdate)
118     U->replaceUsesOfWith(OrigInst, Phi);
119   Phi->addIncoming(OrigInst, OrigInst->getParent());
120   Phi->addIncoming(NewInst, NewInst->getParent());
121 }
122 
123 /// Cast a call or invoke instruction to the given type.
124 ///
125 /// When promoting a call site, the return type of the call site might not match
126 /// that of the callee. If this is the case, we have to cast the returned value
127 /// to the correct type. The location of the cast depends on if we have a call
128 /// or invoke instruction.
129 ///
130 /// For example, if the call instruction below requires a bitcast after
131 /// promotion:
132 ///
133 ///   orig_bb:
134 ///     %t0 = call i32 @func()
135 ///     ...
136 ///
137 /// The bitcast is placed after the call instruction:
138 ///
139 ///   orig_bb:
140 ///     ; Uses of the original return value are replaced by uses of the bitcast.
141 ///     %t0 = call i32 @func()
142 ///     %t1 = bitcast i32 %t0 to ...
143 ///     ...
144 ///
145 /// A similar transformation is performed for invoke instructions. However,
146 /// since invokes are terminating, a new block is created for the bitcast. For
147 /// example, if the invoke instruction below requires a bitcast after promotion:
148 ///
149 ///   orig_bb:
150 ///     %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
151 ///
152 /// The edge between the original block and the invoke's normal destination is
153 /// split, and the bitcast is placed there:
154 ///
155 ///   orig_bb:
156 ///     %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
157 ///
158 ///   split_bb:
159 ///     ; Uses of the original return value are replaced by uses of the bitcast.
160 ///     %t1 = bitcast i32 %t0 to ...
161 ///     br label %normal_dst
162 ///
163 static void createRetBitCast(CallSite CS, Type *RetTy, CastInst **RetBitCast) {
164 
165   // Save the users of the calling instruction. These uses will be changed to
166   // use the bitcast after we create it.
167   SmallVector<User *, 16> UsersToUpdate;
168   for (User *U : CS.getInstruction()->users())
169     UsersToUpdate.push_back(U);
170 
171   // Determine an appropriate location to create the bitcast for the return
172   // value. The location depends on if we have a call or invoke instruction.
173   Instruction *InsertBefore = nullptr;
174   if (auto *Invoke = dyn_cast<InvokeInst>(CS.getInstruction()))
175     InsertBefore =
176         &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front();
177   else
178     InsertBefore = &*std::next(CS.getInstruction()->getIterator());
179 
180   // Bitcast the return value to the correct type.
181   auto *Cast = CastInst::CreateBitOrPointerCast(CS.getInstruction(), RetTy, "",
182                                                 InsertBefore);
183   if (RetBitCast)
184     *RetBitCast = Cast;
185 
186   // Replace all the original uses of the calling instruction with the bitcast.
187   for (User *U : UsersToUpdate)
188     U->replaceUsesOfWith(CS.getInstruction(), Cast);
189 }
190 
191 /// Predicate and clone the given call site.
192 ///
193 /// This function creates an if-then-else structure at the location of the call
194 /// site. The "if" condition compares the call site's called value to the given
195 /// callee. The original call site is moved into the "else" block, and a clone
196 /// of the call site is placed in the "then" block. The cloned instruction is
197 /// returned.
198 ///
199 /// For example, the call instruction below:
200 ///
201 ///   orig_bb:
202 ///     %t0 = call i32 %ptr()
203 ///     ...
204 ///
205 /// Is replace by the following:
206 ///
207 ///   orig_bb:
208 ///     %cond = icmp eq i32 ()* %ptr, @func
209 ///     br i1 %cond, %then_bb, %else_bb
210 ///
211 ///   then_bb:
212 ///     ; The clone of the original call instruction is placed in the "then"
213 ///     ; block. It is not yet promoted.
214 ///     %t1 = call i32 %ptr()
215 ///     br merge_bb
216 ///
217 ///   else_bb:
218 ///     ; The original call instruction is moved to the "else" block.
219 ///     %t0 = call i32 %ptr()
220 ///     br merge_bb
221 ///
222 ///   merge_bb:
223 ///     ; Uses of the original call instruction are replaced by uses of the phi
224 ///     ; node.
225 ///     %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
226 ///     ...
227 ///
228 /// A similar transformation is performed for invoke instructions. However,
229 /// since invokes are terminating, more work is required. For example, the
230 /// invoke instruction below:
231 ///
232 ///   orig_bb:
233 ///     %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
234 ///
235 /// Is replace by the following:
236 ///
237 ///   orig_bb:
238 ///     %cond = icmp eq i32 ()* %ptr, @func
239 ///     br i1 %cond, %then_bb, %else_bb
240 ///
241 ///   then_bb:
242 ///     ; The clone of the original invoke instruction is placed in the "then"
243 ///     ; block, and its normal destination is set to the "merge" block. It is
244 ///     ; not yet promoted.
245 ///     %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
246 ///
247 ///   else_bb:
248 ///     ; The original invoke instruction is moved into the "else" block, and
249 ///     ; its normal destination is set to the "merge" block.
250 ///     %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
251 ///
252 ///   merge_bb:
253 ///     ; Uses of the original invoke instruction are replaced by uses of the
254 ///     ; phi node, and the merge block branches to the normal destination.
255 ///     %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
256 ///     br %normal_dst
257 ///
258 static Instruction *versionCallSite(CallSite CS, Value *Callee,
259                                     MDNode *BranchWeights) {
260 
261   IRBuilder<> Builder(CS.getInstruction());
262   Instruction *OrigInst = CS.getInstruction();
263   BasicBlock *OrigBlock = OrigInst->getParent();
264 
265   // Create the compare. The called value and callee must have the same type to
266   // be compared.
267   if (CS.getCalledValue()->getType() != Callee->getType())
268     Callee = Builder.CreateBitCast(Callee, CS.getCalledValue()->getType());
269   auto *Cond = Builder.CreateICmpEQ(CS.getCalledValue(), Callee);
270 
271   // Create an if-then-else structure. The original instruction is moved into
272   // the "else" block, and a clone of the original instruction is placed in the
273   // "then" block.
274   Instruction *ThenTerm = nullptr;
275   Instruction *ElseTerm = nullptr;
276   SplitBlockAndInsertIfThenElse(Cond, CS.getInstruction(), &ThenTerm, &ElseTerm,
277                                 BranchWeights);
278   BasicBlock *ThenBlock = ThenTerm->getParent();
279   BasicBlock *ElseBlock = ElseTerm->getParent();
280   BasicBlock *MergeBlock = OrigInst->getParent();
281 
282   ThenBlock->setName("if.true.direct_targ");
283   ElseBlock->setName("if.false.orig_indirect");
284   MergeBlock->setName("if.end.icp");
285 
286   Instruction *NewInst = OrigInst->clone();
287   OrigInst->moveBefore(ElseTerm);
288   NewInst->insertBefore(ThenTerm);
289 
290   // If the original call site is an invoke instruction, we have extra work to
291   // do since invoke instructions are terminating. We have to fix-up phi nodes
292   // in the invoke's normal and unwind destinations.
293   if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) {
294     auto *NewInvoke = cast<InvokeInst>(NewInst);
295 
296     // Invoke instructions are terminating, so we don't need the terminator
297     // instructions that were just created.
298     ThenTerm->eraseFromParent();
299     ElseTerm->eraseFromParent();
300 
301     // Branch from the "merge" block to the original normal destination.
302     Builder.SetInsertPoint(MergeBlock);
303     Builder.CreateBr(OrigInvoke->getNormalDest());
304 
305     // Fix-up phi nodes in the original invoke's normal and unwind destinations.
306     fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock);
307     fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock);
308 
309     // Now set the normal destinations of the invoke instructions to be the
310     // "merge" block.
311     OrigInvoke->setNormalDest(MergeBlock);
312     NewInvoke->setNormalDest(MergeBlock);
313   }
314 
315   // Create a phi node for the returned value of the call site.
316   createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
317 
318   return NewInst;
319 }
320 
321 bool llvm::isLegalToPromote(CallSite CS, Function *Callee,
322                             const char **FailureReason) {
323   assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
324 
325   auto &DL = Callee->getParent()->getDataLayout();
326 
327   // Check the return type. The callee's return value type must be bitcast
328   // compatible with the call site's type.
329   Type *CallRetTy = CS.getInstruction()->getType();
330   Type *FuncRetTy = Callee->getReturnType();
331   if (CallRetTy != FuncRetTy)
332     if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy, CallRetTy, DL)) {
333       if (FailureReason)
334         *FailureReason = "Return type mismatch";
335       return false;
336     }
337 
338   // The number of formal arguments of the callee.
339   unsigned NumParams = Callee->getFunctionType()->getNumParams();
340 
341   // Check the number of arguments. The callee and call site must agree on the
342   // number of arguments.
343   if (CS.arg_size() != NumParams && !Callee->isVarArg()) {
344     if (FailureReason)
345       *FailureReason = "The number of arguments mismatch";
346     return false;
347   }
348 
349   // Check the argument types. The callee's formal argument types must be
350   // bitcast compatible with the corresponding actual argument types of the call
351   // site.
352   for (unsigned I = 0; I < NumParams; ++I) {
353     Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I);
354     Type *ActualTy = CS.getArgument(I)->getType();
355     if (FormalTy == ActualTy)
356       continue;
357     if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) {
358       if (FailureReason)
359         *FailureReason = "Argument type mismatch";
360       return false;
361     }
362   }
363 
364   return true;
365 }
366 
367 Instruction *llvm::promoteCall(CallSite CS, Function *Callee,
368                                CastInst **RetBitCast) {
369   assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
370 
371   // Set the called function of the call site to be the given callee (but don't
372   // change the type).
373   cast<CallBase>(CS.getInstruction())->setCalledOperand(Callee);
374 
375   // Since the call site will no longer be direct, we must clear metadata that
376   // is only appropriate for indirect calls. This includes !prof and !callees
377   // metadata.
378   CS.getInstruction()->setMetadata(LLVMContext::MD_prof, nullptr);
379   CS.getInstruction()->setMetadata(LLVMContext::MD_callees, nullptr);
380 
381   // If the function type of the call site matches that of the callee, no
382   // additional work is required.
383   if (CS.getFunctionType() == Callee->getFunctionType())
384     return CS.getInstruction();
385 
386   // Save the return types of the call site and callee.
387   Type *CallSiteRetTy = CS.getInstruction()->getType();
388   Type *CalleeRetTy = Callee->getReturnType();
389 
390   // Change the function type of the call site the match that of the callee.
391   CS.mutateFunctionType(Callee->getFunctionType());
392 
393   // Inspect the arguments of the call site. If an argument's type doesn't
394   // match the corresponding formal argument's type in the callee, bitcast it
395   // to the correct type.
396   auto CalleeType = Callee->getFunctionType();
397   auto CalleeParamNum = CalleeType->getNumParams();
398 
399   LLVMContext &Ctx = Callee->getContext();
400   const AttributeList &CallerPAL = CS.getAttributes();
401   // The new list of argument attributes.
402   SmallVector<AttributeSet, 4> NewArgAttrs;
403   bool AttributeChanged = false;
404 
405   for (unsigned ArgNo = 0; ArgNo < CalleeParamNum; ++ArgNo) {
406     auto *Arg = CS.getArgument(ArgNo);
407     Type *FormalTy = CalleeType->getParamType(ArgNo);
408     Type *ActualTy = Arg->getType();
409     if (FormalTy != ActualTy) {
410       auto *Cast = CastInst::CreateBitOrPointerCast(Arg, FormalTy, "",
411                                                     CS.getInstruction());
412       CS.setArgument(ArgNo, Cast);
413 
414       // Remove any incompatible attributes for the argument.
415       AttrBuilder ArgAttrs(CallerPAL.getParamAttributes(ArgNo));
416       ArgAttrs.remove(AttributeFuncs::typeIncompatible(FormalTy));
417 
418       // If byval is used, this must be a pointer type, and the byval type must
419       // match the element type. Update it if present.
420       if (ArgAttrs.getByValType()) {
421         Type *NewTy = Callee->getParamByValType(ArgNo);
422         ArgAttrs.addByValAttr(
423             NewTy ? NewTy : cast<PointerType>(FormalTy)->getElementType());
424       }
425 
426       NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs));
427       AttributeChanged = true;
428     } else
429       NewArgAttrs.push_back(CallerPAL.getParamAttributes(ArgNo));
430   }
431 
432   // If the return type of the call site doesn't match that of the callee, cast
433   // the returned value to the appropriate type.
434   // Remove any incompatible return value attribute.
435   AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
436   if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy) {
437     createRetBitCast(CS, CallSiteRetTy, RetBitCast);
438     RAttrs.remove(AttributeFuncs::typeIncompatible(CalleeRetTy));
439     AttributeChanged = true;
440   }
441 
442   // Set the new callsite attribute.
443   if (AttributeChanged)
444     CS.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttributes(),
445                                         AttributeSet::get(Ctx, RAttrs),
446                                         NewArgAttrs));
447 
448   return CS.getInstruction();
449 }
450 
451 Instruction *llvm::promoteCallWithIfThenElse(CallSite CS, Function *Callee,
452                                              MDNode *BranchWeights) {
453 
454   // Version the indirect call site. If the called value is equal to the given
455   // callee, 'NewInst' will be executed, otherwise the original call site will
456   // be executed.
457   Instruction *NewInst = versionCallSite(CS, Callee, BranchWeights);
458 
459   // Promote 'NewInst' so that it directly calls the desired function.
460   return promoteCall(CallSite(NewInst), Callee);
461 }
462 
463 bool llvm::tryPromoteCall(CallSite &CS) {
464   assert(!CS.getCalledFunction());
465   Module *M = CS.getCaller()->getParent();
466   const DataLayout &DL = M->getDataLayout();
467   Value *Callee = CS.getCalledValue();
468 
469   LoadInst *VTableEntryLoad = dyn_cast<LoadInst>(Callee);
470   if (!VTableEntryLoad)
471     return false; // Not a vtable entry load.
472   Value *VTableEntryPtr = VTableEntryLoad->getPointerOperand();
473   APInt VTableOffset(DL.getTypeSizeInBits(VTableEntryPtr->getType()), 0);
474   Value *VTableBasePtr = VTableEntryPtr->stripAndAccumulateConstantOffsets(
475       DL, VTableOffset, /* AllowNonInbounds */ true);
476   LoadInst *VTablePtrLoad = dyn_cast<LoadInst>(VTableBasePtr);
477   if (!VTablePtrLoad)
478     return false; // Not a vtable load.
479   Value *Object = VTablePtrLoad->getPointerOperand();
480   APInt ObjectOffset(DL.getTypeSizeInBits(Object->getType()), 0);
481   Value *ObjectBase = Object->stripAndAccumulateConstantOffsets(
482       DL, ObjectOffset, /* AllowNonInbounds */ true);
483   if (!(isa<AllocaInst>(ObjectBase) && ObjectOffset == 0))
484     // Not an Alloca or the offset isn't zero.
485     return false;
486 
487   // Look for the vtable pointer store into the object by the ctor.
488   BasicBlock::iterator BBI(VTablePtrLoad);
489   Value *VTablePtr = FindAvailableLoadedValue(
490       VTablePtrLoad, VTablePtrLoad->getParent(), BBI, 0, nullptr, nullptr);
491   if (!VTablePtr)
492     return false; // No vtable found.
493   APInt VTableOffsetGVBase(DL.getTypeSizeInBits(VTablePtr->getType()), 0);
494   Value *VTableGVBase = VTablePtr->stripAndAccumulateConstantOffsets(
495       DL, VTableOffsetGVBase, /* AllowNonInbounds */ true);
496   GlobalVariable *GV = dyn_cast<GlobalVariable>(VTableGVBase);
497   if (!(GV && GV->isConstant() && GV->hasDefinitiveInitializer()))
498     // Not in the form of a global constant variable with an initializer.
499     return false;
500 
501   Constant *VTableGVInitializer = GV->getInitializer();
502   APInt VTableGVOffset = VTableOffsetGVBase + VTableOffset;
503   if (!(VTableGVOffset.getActiveBits() <= 64))
504     return false; // Out of range.
505   Constant *Ptr = getPointerAtOffset(VTableGVInitializer,
506                                      VTableGVOffset.getZExtValue(),
507                                      *M);
508   if (!Ptr)
509     return false; // No constant (function) pointer found.
510   Function *DirectCallee = dyn_cast<Function>(Ptr->stripPointerCasts());
511   if (!DirectCallee)
512     return false; // No function pointer found.
513 
514   if (!isLegalToPromote(CS, DirectCallee))
515     return false;
516 
517   // Success.
518   promoteCall(CS, DirectCallee);
519   return true;
520 }
521 
522 #undef DEBUG_TYPE
523