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