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