1 //===-- IndirectCallPromotion.cpp - Promote indirect calls to direct calls ===//
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 the transformation that promotes indirect calls to
11 // conditional direct calls when the indirect-call value profile metadata is
12 // available.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "IndirectCallSiteVisitor.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Analysis/CFG.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/InstIterator.h"
25 #include "llvm/IR/InstVisitor.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/MDBuilder.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Pass.h"
31 #include "llvm/ProfileData/InstrProfReader.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Transforms/Instrumentation.h"
34 #include "llvm/Transforms/PGOInstrumentation.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include <string>
37 #include <utility>
38 #include <vector>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "icall-promotion"
43 
44 STATISTIC(NumOfPGOICallPromotion, "Number of indirect call promotions.");
45 STATISTIC(NumOfPGOICallsites, "Number of indirect call candidate sites.");
46 
47 // Command line option to disable indirect-call promotion with the default as
48 // false. This is for debug purpose.
49 static cl::opt<bool> DisableICP("disable-icp", cl::init(false), cl::Hidden,
50                                 cl::desc("Disable indirect call promotion"));
51 
52 // The minimum call count for the direct-call target to be considered as the
53 // promotion candidate.
54 static cl::opt<unsigned>
55     ICPCountThreshold("icp-count-threshold", cl::Hidden, cl::ZeroOrMore,
56                       cl::init(1000),
57                       cl::desc("The minimum count to the direct call target "
58                                "for the promotion"));
59 
60 // The percent threshold for the direct-call target (this call site vs the
61 // total call count) for it to be considered as the promotion target.
62 static cl::opt<unsigned>
63     ICPPercentThreshold("icp-percent-threshold", cl::init(33), cl::Hidden,
64                         cl::ZeroOrMore,
65                         cl::desc("The percentage threshold for the promotion"));
66 
67 // Set the maximum number of targets to promote for a single indirect-call
68 // callsite.
69 static cl::opt<unsigned>
70     MaxNumPromotions("icp-max-prom", cl::init(2), cl::Hidden, cl::ZeroOrMore,
71                      cl::desc("Max number of promotions for a single indirect "
72                               "call callsite"));
73 
74 // Set the cutoff value for the promotion. If the value is other than 0, we
75 // stop the transformation once the total number of promotions equals the cutoff
76 // value.
77 // For debug use only.
78 static cl::opt<unsigned>
79     ICPCutOff("icp-cutoff", cl::init(0), cl::Hidden, cl::ZeroOrMore,
80               cl::desc("Max number of promotions for this compilaiton"));
81 
82 // If ICPCSSkip is non zero, the first ICPCSSkip callsites will be skipped.
83 // For debug use only.
84 static cl::opt<unsigned>
85     ICPCSSkip("icp-csskip", cl::init(0), cl::Hidden, cl::ZeroOrMore,
86               cl::desc("Skip Callsite up to this number for this compilaiton"));
87 
88 // Set if the pass is called in LTO optimization. The difference for LTO mode
89 // is the pass won't prefix the source module name to the internal linkage
90 // symbols.
91 static cl::opt<bool> ICPLTOMode("icp-lto", cl::init(false), cl::Hidden,
92                                 cl::desc("Run indirect-call promotion in LTO "
93                                          "mode"));
94 // If the option is set to true, only call instructions will be considered for
95 // transformation -- invoke instructions will be ignored.
96 static cl::opt<bool>
97     ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden,
98                 cl::desc("Run indirect-call promotion for call instructions "
99                          "only"));
100 
101 // If the option is set to true, only invoke instructions will be considered for
102 // transformation -- call instructions will be ignored.
103 static cl::opt<bool> ICPInvokeOnly("icp-invoke-only", cl::init(false),
104                                    cl::Hidden,
105                                    cl::desc("Run indirect-call promotion for "
106                                             "invoke instruction only"));
107 
108 // Dump the function level IR if the transformation happened in this
109 // function. For debug use only.
110 static cl::opt<bool>
111     ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden,
112                  cl::desc("Dump IR after transformation happens"));
113 
114 namespace {
115 class PGOIndirectCallPromotionLegacyPass : public ModulePass {
116 public:
117   static char ID;
118 
119   PGOIndirectCallPromotionLegacyPass(bool InLTO = false)
120       : ModulePass(ID), InLTO(InLTO) {
121     initializePGOIndirectCallPromotionLegacyPassPass(
122         *PassRegistry::getPassRegistry());
123   }
124 
125   const char *getPassName() const override {
126     return "PGOIndirectCallPromotion";
127   }
128 
129 private:
130   bool runOnModule(Module &M) override;
131 
132   // If this pass is called in LTO. We need to special handling the PGOFuncName
133   // for the static variables due to LTO's internalization.
134   bool InLTO;
135 };
136 } // end anonymous namespace
137 
138 char PGOIndirectCallPromotionLegacyPass::ID = 0;
139 INITIALIZE_PASS(PGOIndirectCallPromotionLegacyPass, "pgo-icall-prom",
140                 "Use PGO instrumentation profile to promote indirect calls to "
141                 "direct calls.",
142                 false, false)
143 
144 ModulePass *llvm::createPGOIndirectCallPromotionLegacyPass(bool InLTO) {
145   return new PGOIndirectCallPromotionLegacyPass(InLTO);
146 }
147 
148 namespace {
149 // The class for main data structure to promote indirect calls to conditional
150 // direct calls.
151 class ICallPromotionFunc {
152 private:
153   Function &F;
154   Module *M;
155 
156   // Symtab that maps indirect call profile values to function names and
157   // defines.
158   InstrProfSymtab *Symtab;
159 
160   // Allocate space to read the profile annotation.
161   std::unique_ptr<InstrProfValueData[]> ValueDataArray;
162 
163   // Count is the call count for the direct-call target and
164   // TotalCount is the call count for the indirect-call callsite.
165   // Return true we should promote this indirect-call target.
166   bool isPromotionProfitable(uint64_t Count, uint64_t TotalCount);
167 
168   enum TargetStatus {
169     OK,                   // Should be able to promote.
170     NotAvailableInModule, // Cannot find the target in current module.
171     ReturnTypeMismatch,   // Return type mismatch b/w target and indirect-call.
172     NumArgsMismatch,      // Number of arguments does not match.
173     ArgTypeMismatch       // Type mismatch in the arguments (cannot bitcast).
174   };
175 
176   // Test if we can legally promote this direct-call of Target.
177   TargetStatus isPromotionLegal(Instruction *Inst, uint64_t Target,
178                                 Function *&F);
179 
180   // A struct that records the direct target and it's call count.
181   struct PromotionCandidate {
182     Function *TargetFunction;
183     uint64_t Count;
184     PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {}
185   };
186 
187   // Check if the indirect-call call site should be promoted. Return the number
188   // of promotions.
189   std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(
190       Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
191       uint64_t TotalCount);
192 
193   // Main function that transforms Inst (either a indirect-call instruction, or
194   // an invoke instruction , to a conditional call to F. This is like:
195   //     if (Inst.CalledValue == F)
196   //        F(...);
197   //     else
198   //        Inst(...);
199   //     end
200   // TotalCount is the profile count value that the instruction executes.
201   // Count is the profile count value that F is the target function.
202   // These two values are being used to update the branch weight.
203   void promote(Instruction *Inst, Function *F, uint64_t Count,
204                uint64_t TotalCount);
205 
206   // Promote a list of targets for one indirect-call callsite. Return
207   // the number of promotions.
208   uint32_t tryToPromote(Instruction *Inst,
209                         const std::vector<PromotionCandidate> &Candidates,
210                         uint64_t &TotalCount);
211 
212   static const char *StatusToString(const TargetStatus S) {
213     switch (S) {
214     case OK:
215       return "OK to promote";
216     case NotAvailableInModule:
217       return "Cannot find the target";
218     case ReturnTypeMismatch:
219       return "Return type mismatch";
220     case NumArgsMismatch:
221       return "The number of arguments mismatch";
222     case ArgTypeMismatch:
223       return "Argument Type mismatch";
224     }
225     llvm_unreachable("Should not reach here");
226   }
227 
228   // Noncopyable
229   ICallPromotionFunc(const ICallPromotionFunc &other) = delete;
230   ICallPromotionFunc &operator=(const ICallPromotionFunc &other) = delete;
231 
232 public:
233   ICallPromotionFunc(Function &Func, Module *Modu, InstrProfSymtab *Symtab)
234       : F(Func), M(Modu), Symtab(Symtab) {
235     ValueDataArray = llvm::make_unique<InstrProfValueData[]>(MaxNumPromotions);
236   }
237   bool processFunction();
238 };
239 } // end anonymous namespace
240 
241 bool ICallPromotionFunc::isPromotionProfitable(uint64_t Count,
242                                                uint64_t TotalCount) {
243   if (Count < ICPCountThreshold)
244     return false;
245 
246   unsigned Percentage = (Count * 100) / TotalCount;
247   return (Percentage >= ICPPercentThreshold);
248 }
249 
250 ICallPromotionFunc::TargetStatus
251 ICallPromotionFunc::isPromotionLegal(Instruction *Inst, uint64_t Target,
252                                      Function *&TargetFunction) {
253   Function *DirectCallee = Symtab->getFunction(Target);
254   if (DirectCallee == nullptr)
255     return NotAvailableInModule;
256   // Check the return type.
257   Type *CallRetType = Inst->getType();
258   if (!CallRetType->isVoidTy()) {
259     Type *FuncRetType = DirectCallee->getReturnType();
260     if (FuncRetType != CallRetType &&
261         !CastInst::isBitCastable(FuncRetType, CallRetType))
262       return ReturnTypeMismatch;
263   }
264 
265   // Check if the arguments are compatible with the parameters
266   FunctionType *DirectCalleeType = DirectCallee->getFunctionType();
267   unsigned ParamNum = DirectCalleeType->getFunctionNumParams();
268   CallSite CS(Inst);
269   unsigned ArgNum = CS.arg_size();
270 
271   if (ParamNum != ArgNum && !DirectCalleeType->isVarArg())
272     return NumArgsMismatch;
273 
274   for (unsigned I = 0; I < ParamNum; ++I) {
275     Type *PTy = DirectCalleeType->getFunctionParamType(I);
276     Type *ATy = CS.getArgument(I)->getType();
277     if (PTy == ATy)
278       continue;
279     if (!CastInst::castIsValid(Instruction::BitCast, CS.getArgument(I), PTy))
280       return ArgTypeMismatch;
281   }
282 
283   DEBUG(dbgs() << " #" << NumOfPGOICallPromotion << " Promote the icall to "
284                << Symtab->getFuncName(Target) << "\n");
285   TargetFunction = DirectCallee;
286   return OK;
287 }
288 
289 // Indirect-call promotion heuristic. The direct targets are sorted based on
290 // the count. Stop at the first target that is not promoted.
291 std::vector<ICallPromotionFunc::PromotionCandidate>
292 ICallPromotionFunc::getPromotionCandidatesForCallSite(
293     Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
294     uint64_t TotalCount) {
295   uint32_t NumVals = ValueDataRef.size();
296   std::vector<PromotionCandidate> Ret;
297 
298   DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << *Inst
299                << " Num_targets: " << NumVals << "\n");
300   NumOfPGOICallsites++;
301   if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) {
302     DEBUG(dbgs() << " Skip: User options.\n");
303     return Ret;
304   }
305 
306   for (uint32_t I = 0; I < MaxNumPromotions && I < NumVals; I++) {
307     uint64_t Count = ValueDataRef[I].Count;
308     assert(Count <= TotalCount);
309     uint64_t Target = ValueDataRef[I].Value;
310     DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
311                  << "  Target_func: " << Target << "\n");
312 
313     if (ICPInvokeOnly && dyn_cast<CallInst>(Inst)) {
314       DEBUG(dbgs() << " Not promote: User options.\n");
315       break;
316     }
317     if (ICPCallOnly && dyn_cast<InvokeInst>(Inst)) {
318       DEBUG(dbgs() << " Not promote: User option.\n");
319       break;
320     }
321     if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
322       DEBUG(dbgs() << " Not promote: Cutoff reached.\n");
323       break;
324     }
325     if (!isPromotionProfitable(Count, TotalCount)) {
326       DEBUG(dbgs() << " Not promote: Cold target.\n");
327       break;
328     }
329     Function *TargetFunction = nullptr;
330     TargetStatus Status = isPromotionLegal(Inst, Target, TargetFunction);
331     if (Status != OK) {
332       StringRef TargetFuncName = Symtab->getFuncName(Target);
333       const char *Reason = StatusToString(Status);
334       DEBUG(dbgs() << " Not promote: " << Reason << "\n");
335       emitOptimizationRemarkMissed(
336           F.getContext(), "PGOIndirectCallPromotion", F, Inst->getDebugLoc(),
337           Twine("Cannot promote indirect call to ") +
338               (TargetFuncName.empty() ? Twine(Target) : Twine(TargetFuncName)) +
339               Twine(" with count of ") + Twine(Count) + ": " + Reason);
340       break;
341     }
342     Ret.push_back(PromotionCandidate(TargetFunction, Count));
343     TotalCount -= Count;
344   }
345   return Ret;
346 }
347 
348 // Create a diamond structure for If_Then_Else. Also update the profile
349 // count. Do the fix-up for the invoke instruction.
350 static void createIfThenElse(Instruction *Inst, Function *DirectCallee,
351                              uint64_t Count, uint64_t TotalCount,
352                              BasicBlock **DirectCallBB,
353                              BasicBlock **IndirectCallBB,
354                              BasicBlock **MergeBB) {
355   CallSite CS(Inst);
356   Value *OrigCallee = CS.getCalledValue();
357 
358   IRBuilder<> BBBuilder(Inst);
359   LLVMContext &Ctx = Inst->getContext();
360   Value *BCI1 =
361       BBBuilder.CreateBitCast(OrigCallee, Type::getInt8PtrTy(Ctx), "");
362   Value *BCI2 =
363       BBBuilder.CreateBitCast(DirectCallee, Type::getInt8PtrTy(Ctx), "");
364   Value *PtrCmp = BBBuilder.CreateICmpEQ(BCI1, BCI2, "");
365 
366   uint64_t ElseCount = TotalCount - Count;
367   uint64_t MaxCount = (Count >= ElseCount ? Count : ElseCount);
368   uint64_t Scale = calculateCountScale(MaxCount);
369   MDBuilder MDB(Inst->getContext());
370   MDNode *BranchWeights = MDB.createBranchWeights(
371       scaleBranchCount(Count, Scale), scaleBranchCount(ElseCount, Scale));
372   TerminatorInst *ThenTerm, *ElseTerm;
373   SplitBlockAndInsertIfThenElse(PtrCmp, Inst, &ThenTerm, &ElseTerm,
374                                 BranchWeights);
375   *DirectCallBB = ThenTerm->getParent();
376   (*DirectCallBB)->setName("if.true.direct_targ");
377   *IndirectCallBB = ElseTerm->getParent();
378   (*IndirectCallBB)->setName("if.false.orig_indirect");
379   *MergeBB = Inst->getParent();
380   (*MergeBB)->setName("if.end.icp");
381 
382   // Special handing of Invoke instructions.
383   InvokeInst *II = dyn_cast<InvokeInst>(Inst);
384   if (!II)
385     return;
386 
387   // We don't need branch instructions for invoke.
388   ThenTerm->eraseFromParent();
389   ElseTerm->eraseFromParent();
390 
391   // Add jump from Merge BB to the NormalDest. This is needed for the newly
392   // created direct invoke stmt -- as its NormalDst will be fixed up to MergeBB.
393   BranchInst::Create(II->getNormalDest(), *MergeBB);
394 }
395 
396 // Find the PHI in BB that have the CallResult as the operand.
397 static bool getCallRetPHINode(BasicBlock *BB, Instruction *Inst) {
398   BasicBlock *From = Inst->getParent();
399   for (auto &I : *BB) {
400     PHINode *PHI = dyn_cast<PHINode>(&I);
401     if (!PHI)
402       continue;
403     int IX = PHI->getBasicBlockIndex(From);
404     if (IX == -1)
405       continue;
406     Value *V = PHI->getIncomingValue(IX);
407     if (dyn_cast<Instruction>(V) == Inst)
408       return true;
409   }
410   return false;
411 }
412 
413 // This method fixes up PHI nodes in BB where BB is the UnwindDest of an
414 // invoke instruction. In BB, there may be PHIs with incoming block being
415 // OrigBB (the MergeBB after if-then-else splitting). After moving the invoke
416 // instructions to its own BB, OrigBB is no longer the predecessor block of BB.
417 // Instead two new predecessors are added: IndirectCallBB and DirectCallBB,
418 // so the PHI node's incoming BBs need to be fixed up accordingly.
419 static void fixupPHINodeForUnwind(Instruction *Inst, BasicBlock *BB,
420                                   BasicBlock *OrigBB,
421                                   BasicBlock *IndirectCallBB,
422                                   BasicBlock *DirectCallBB) {
423   for (auto &I : *BB) {
424     PHINode *PHI = dyn_cast<PHINode>(&I);
425     if (!PHI)
426       continue;
427     int IX = PHI->getBasicBlockIndex(OrigBB);
428     if (IX == -1)
429       continue;
430     Value *V = PHI->getIncomingValue(IX);
431     PHI->addIncoming(V, IndirectCallBB);
432     PHI->setIncomingBlock(IX, DirectCallBB);
433   }
434 }
435 
436 // This method fixes up PHI nodes in BB where BB is the NormalDest of an
437 // invoke instruction. In BB, there may be PHIs with incoming block being
438 // OrigBB (the MergeBB after if-then-else splitting). After moving the invoke
439 // instructions to its own BB, a new incoming edge will be added to the original
440 // NormalDstBB from the IndirectCallBB.
441 static void fixupPHINodeForNormalDest(Instruction *Inst, BasicBlock *BB,
442                                       BasicBlock *OrigBB,
443                                       BasicBlock *IndirectCallBB,
444                                       Instruction *NewInst) {
445   for (auto &I : *BB) {
446     PHINode *PHI = dyn_cast<PHINode>(&I);
447     if (!PHI)
448       continue;
449     int IX = PHI->getBasicBlockIndex(OrigBB);
450     if (IX == -1)
451       continue;
452     Value *V = PHI->getIncomingValue(IX);
453     if (dyn_cast<Instruction>(V) == Inst) {
454       PHI->setIncomingBlock(IX, IndirectCallBB);
455       PHI->addIncoming(NewInst, OrigBB);
456       continue;
457     }
458     PHI->addIncoming(V, IndirectCallBB);
459   }
460 }
461 
462 // Add a bitcast instruction to the direct-call return value if needed.
463 static Instruction *insertCallRetCast(const Instruction *Inst,
464                                       Instruction *DirectCallInst,
465                                       Function *DirectCallee) {
466   if (Inst->getType()->isVoidTy())
467     return DirectCallInst;
468 
469   Type *CallRetType = Inst->getType();
470   Type *FuncRetType = DirectCallee->getReturnType();
471   if (FuncRetType == CallRetType)
472     return DirectCallInst;
473 
474   BasicBlock *InsertionBB;
475   if (CallInst *CI = dyn_cast<CallInst>(DirectCallInst))
476     InsertionBB = CI->getParent();
477   else
478     InsertionBB = (dyn_cast<InvokeInst>(DirectCallInst))->getNormalDest();
479 
480   return (new BitCastInst(DirectCallInst, CallRetType, "",
481                           InsertionBB->getTerminator()));
482 }
483 
484 // Create a DirectCall instruction in the DirectCallBB.
485 // Parameter Inst is the indirect-call (invoke) instruction.
486 // DirectCallee is the decl of the direct-call (invoke) target.
487 // DirecallBB is the BB that the direct-call (invoke) instruction is inserted.
488 // MergeBB is the bottom BB of the if-then-else-diamond after the
489 // transformation. For invoke instruction, the edges from DirectCallBB and
490 // IndirectCallBB to MergeBB are removed before this call (during
491 // createIfThenElse).
492 static Instruction *createDirectCallInst(const Instruction *Inst,
493                                          Function *DirectCallee,
494                                          BasicBlock *DirectCallBB,
495                                          BasicBlock *MergeBB) {
496   Instruction *NewInst = Inst->clone();
497   if (CallInst *CI = dyn_cast<CallInst>(NewInst)) {
498     CI->setCalledFunction(DirectCallee);
499     CI->mutateFunctionType(DirectCallee->getFunctionType());
500   } else {
501     // Must be an invoke instruction. Direct invoke's normal destination is
502     // fixed up to MergeBB. MergeBB is the place where return cast is inserted.
503     // Also since IndirectCallBB does not have an edge to MergeBB, there is no
504     // need to insert new PHIs into MergeBB.
505     InvokeInst *II = dyn_cast<InvokeInst>(NewInst);
506     assert(II);
507     II->setCalledFunction(DirectCallee);
508     II->mutateFunctionType(DirectCallee->getFunctionType());
509     II->setNormalDest(MergeBB);
510   }
511 
512   DirectCallBB->getInstList().insert(DirectCallBB->getFirstInsertionPt(),
513                                      NewInst);
514 
515   // Clear the value profile data.
516   NewInst->setMetadata(LLVMContext::MD_prof, 0);
517   CallSite NewCS(NewInst);
518   FunctionType *DirectCalleeType = DirectCallee->getFunctionType();
519   unsigned ParamNum = DirectCalleeType->getFunctionNumParams();
520   for (unsigned I = 0; I < ParamNum; ++I) {
521     Type *ATy = NewCS.getArgument(I)->getType();
522     Type *PTy = DirectCalleeType->getParamType(I);
523     if (ATy != PTy) {
524       BitCastInst *BI = new BitCastInst(NewCS.getArgument(I), PTy, "", NewInst);
525       NewCS.setArgument(I, BI);
526     }
527   }
528 
529   return insertCallRetCast(Inst, NewInst, DirectCallee);
530 }
531 
532 // Create a PHI to unify the return values of calls.
533 static void insertCallRetPHI(Instruction *Inst, Instruction *CallResult,
534                              Function *DirectCallee) {
535   if (Inst->getType()->isVoidTy())
536     return;
537 
538   BasicBlock *RetValBB = CallResult->getParent();
539 
540   BasicBlock *PHIBB;
541   if (InvokeInst *II = dyn_cast<InvokeInst>(CallResult))
542     RetValBB = II->getNormalDest();
543 
544   PHIBB = RetValBB->getSingleSuccessor();
545   if (getCallRetPHINode(PHIBB, Inst))
546     return;
547 
548   PHINode *CallRetPHI = PHINode::Create(Inst->getType(), 0);
549   PHIBB->getInstList().push_front(CallRetPHI);
550   Inst->replaceAllUsesWith(CallRetPHI);
551   CallRetPHI->addIncoming(Inst, Inst->getParent());
552   CallRetPHI->addIncoming(CallResult, RetValBB);
553 }
554 
555 // This function does the actual indirect-call promotion transformation:
556 // For an indirect-call like:
557 //     Ret = (*Foo)(Args);
558 // It transforms to:
559 //     if (Foo == DirectCallee)
560 //        Ret1 = DirectCallee(Args);
561 //     else
562 //        Ret2 = (*Foo)(Args);
563 //     Ret = phi(Ret1, Ret2);
564 // It adds type casts for the args do not match the parameters and the return
565 // value. Branch weights metadata also updated.
566 void ICallPromotionFunc::promote(Instruction *Inst, Function *DirectCallee,
567                                  uint64_t Count, uint64_t TotalCount) {
568   assert(DirectCallee != nullptr);
569   BasicBlock *BB = Inst->getParent();
570   // Just to suppress the non-debug build warning.
571   (void)BB;
572   DEBUG(dbgs() << "\n\n== Basic Block Before ==\n");
573   DEBUG(dbgs() << *BB << "\n");
574 
575   BasicBlock *DirectCallBB, *IndirectCallBB, *MergeBB;
576   createIfThenElse(Inst, DirectCallee, Count, TotalCount, &DirectCallBB,
577                    &IndirectCallBB, &MergeBB);
578 
579   Instruction *NewInst =
580       createDirectCallInst(Inst, DirectCallee, DirectCallBB, MergeBB);
581 
582   // Move Inst from MergeBB to IndirectCallBB.
583   Inst->removeFromParent();
584   IndirectCallBB->getInstList().insert(IndirectCallBB->getFirstInsertionPt(),
585                                        Inst);
586 
587   if (InvokeInst *II = dyn_cast<InvokeInst>(Inst)) {
588     // At this point, the original indirect invoke instruction has the original
589     // UnwindDest and NormalDest. For the direct invoke instruction, the
590     // NormalDest points to MergeBB, and MergeBB jumps to the original
591     // NormalDest. MergeBB might have a new bitcast instruction for the return
592     // value. The PHIs are with the original NormalDest. Since we now have two
593     // incoming edges to NormalDest and UnwindDest, we have to do some fixups.
594     //
595     // UnwindDest will not use the return value. So pass nullptr here.
596     fixupPHINodeForUnwind(Inst, II->getUnwindDest(), MergeBB, IndirectCallBB,
597                           DirectCallBB);
598     // We don't need to update the operand from NormalDest for DirectCallBB.
599     // Pass nullptr here.
600     fixupPHINodeForNormalDest(Inst, II->getNormalDest(), MergeBB,
601                               IndirectCallBB, NewInst);
602   }
603 
604   insertCallRetPHI(Inst, NewInst, DirectCallee);
605 
606   DEBUG(dbgs() << "\n== Basic Blocks After ==\n");
607   DEBUG(dbgs() << *BB << *DirectCallBB << *IndirectCallBB << *MergeBB << "\n");
608 
609   emitOptimizationRemark(
610       F.getContext(), "PGOIndirectCallPromotion", F, Inst->getDebugLoc(),
611       Twine("Promote indirect call to ") + DirectCallee->getName() +
612           " with count " + Twine(Count) + " out of " + Twine(TotalCount));
613 }
614 
615 // Promote indirect-call to conditional direct-call for one callsite.
616 uint32_t ICallPromotionFunc::tryToPromote(
617     Instruction *Inst, const std::vector<PromotionCandidate> &Candidates,
618     uint64_t &TotalCount) {
619   uint32_t NumPromoted = 0;
620 
621   for (auto &C : Candidates) {
622     uint64_t Count = C.Count;
623     promote(Inst, C.TargetFunction, Count, TotalCount);
624     assert(TotalCount >= Count);
625     TotalCount -= Count;
626     NumOfPGOICallPromotion++;
627     NumPromoted++;
628   }
629   return NumPromoted;
630 }
631 
632 // Traverse all the indirect-call callsite and get the value profile
633 // annotation to perform indirect-call promotion.
634 bool ICallPromotionFunc::processFunction() {
635   bool Changed = false;
636   for (auto &I : findIndirectCallSites(F)) {
637     uint32_t NumVals;
638     uint64_t TotalCount;
639     bool Res =
640         getValueProfDataFromInst(*I, IPVK_IndirectCallTarget, MaxNumPromotions,
641                                  ValueDataArray.get(), NumVals, TotalCount);
642     if (!Res)
643       continue;
644     ArrayRef<InstrProfValueData> ValueDataArrayRef(ValueDataArray.get(),
645                                                    NumVals);
646     auto PromotionCandidates =
647         getPromotionCandidatesForCallSite(I, ValueDataArrayRef, TotalCount);
648     uint32_t NumPromoted = tryToPromote(I, PromotionCandidates, TotalCount);
649     if (NumPromoted == 0)
650       continue;
651 
652     Changed = true;
653     // Adjust the MD.prof metadata. First delete the old one.
654     I->setMetadata(LLVMContext::MD_prof, 0);
655     // If all promoted, we don't need the MD.prof metadata.
656     if (TotalCount == 0 || NumPromoted == NumVals)
657       continue;
658     // Otherwise we need update with the un-promoted records back.
659     annotateValueSite(*M, *I, ValueDataArrayRef.slice(NumPromoted), TotalCount,
660                       IPVK_IndirectCallTarget, MaxNumPromotions);
661   }
662   return Changed;
663 }
664 
665 // A wrapper function that does the actual work.
666 static bool promoteIndirectCalls(Module &M, bool InLTO) {
667   if (DisableICP)
668     return false;
669   InstrProfSymtab Symtab;
670   Symtab.create(M, InLTO);
671   bool Changed = false;
672   for (auto &F : M) {
673     if (F.isDeclaration())
674       continue;
675     if (F.hasFnAttribute(Attribute::OptimizeNone))
676       continue;
677     ICallPromotionFunc ICallPromotion(F, &M, &Symtab);
678     bool FuncChanged = ICallPromotion.processFunction();
679     if (ICPDUMPAFTER && FuncChanged) {
680       DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs()));
681       DEBUG(dbgs() << "\n");
682     }
683     Changed |= FuncChanged;
684     if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
685       DEBUG(dbgs() << " Stop: Cutoff reached.\n");
686       break;
687     }
688   }
689   return Changed;
690 }
691 
692 bool PGOIndirectCallPromotionLegacyPass::runOnModule(Module &M) {
693   // Command-line option has the priority for InLTO.
694   return promoteIndirectCalls(M, InLTO | ICPLTOMode);
695 }
696 
697 PreservedAnalyses PGOIndirectCallPromotion::run(Module &M, AnalysisManager<Module> &AM) {
698   if (!promoteIndirectCalls(M, InLTO | ICPLTOMode))
699     return PreservedAnalyses::all();
700 
701   return PreservedAnalyses::none();
702 }
703