blob: 384407b7129c6be0a5c01fc723b989f680bc7c0e [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
Eugene Zelenkocdc71612016-08-11 17:20:18 +000016#include "llvm/ADT/ArrayRef.h"
Rong Xu6e34c492016-04-27 23:20:27 +000017#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000018#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000020#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
21#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000022#include "llvm/IR/BasicBlock.h"
Rong Xu6e34c492016-04-27 23:20:27 +000023#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000024#include "llvm/IR/DerivedTypes.h"
Rong Xu6e34c492016-04-27 23:20:27 +000025#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000026#include "llvm/IR/Function.h"
Rong Xu6e34c492016-04-27 23:20:27 +000027#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
Rong Xu6e34c492016-04-27 23:20:27 +000030#include "llvm/IR/Instructions.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000031#include "llvm/IR/LLVMContext.h"
Rong Xu6e34c492016-04-27 23:20:27 +000032#include "llvm/IR/MDBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000033#include "llvm/IR/PassManager.h"
34#include "llvm/IR/Type.h"
Rong Xu6e34c492016-04-27 23:20:27 +000035#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000036#include "llvm/PassRegistry.h"
37#include "llvm/PassSupport.h"
38#include "llvm/ProfileData/InstrProf.h"
39#include "llvm/Support/Casting.h"
40#include "llvm/Support/CommandLine.h"
Rong Xu6e34c492016-04-27 23:20:27 +000041#include "llvm/Support/Debug.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000042#include "llvm/Support/ErrorHandling.h"
Rong Xu6e34c492016-04-27 23:20:27 +000043#include "llvm/Transforms/Instrumentation.h"
Xinliang David Lif3c7a352016-05-16 16:31:07 +000044#include "llvm/Transforms/PGOInstrumentation.h"
Rong Xu6e34c492016-04-27 23:20:27 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000046#include <cassert>
47#include <cstdint>
Rong Xu6e34c492016-04-27 23:20:27 +000048#include <vector>
49
50using namespace llvm;
51
Xinliang David Li0b293302016-06-02 01:52:05 +000052#define DEBUG_TYPE "pgo-icall-prom"
Rong Xu6e34c492016-04-27 23:20:27 +000053
54STATISTIC(NumOfPGOICallPromotion, "Number of indirect call promotions.");
55STATISTIC(NumOfPGOICallsites, "Number of indirect call candidate sites.");
56
57// Command line option to disable indirect-call promotion with the default as
58// false. This is for debug purpose.
59static cl::opt<bool> DisableICP("disable-icp", cl::init(false), cl::Hidden,
60 cl::desc("Disable indirect call promotion"));
61
Rong Xu6e34c492016-04-27 23:20:27 +000062// Set the cutoff value for the promotion. If the value is other than 0, we
63// stop the transformation once the total number of promotions equals the cutoff
64// value.
65// For debug use only.
66static cl::opt<unsigned>
67 ICPCutOff("icp-cutoff", cl::init(0), cl::Hidden, cl::ZeroOrMore,
68 cl::desc("Max number of promotions for this compilaiton"));
69
70// If ICPCSSkip is non zero, the first ICPCSSkip callsites will be skipped.
71// For debug use only.
72static cl::opt<unsigned>
73 ICPCSSkip("icp-csskip", cl::init(0), cl::Hidden, cl::ZeroOrMore,
74 cl::desc("Skip Callsite up to this number for this compilaiton"));
75
76// Set if the pass is called in LTO optimization. The difference for LTO mode
77// is the pass won't prefix the source module name to the internal linkage
78// symbols.
79static cl::opt<bool> ICPLTOMode("icp-lto", cl::init(false), cl::Hidden,
80 cl::desc("Run indirect-call promotion in LTO "
81 "mode"));
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000082
Rong Xu6e34c492016-04-27 23:20:27 +000083// If the option is set to true, only call instructions will be considered for
84// transformation -- invoke instructions will be ignored.
85static cl::opt<bool>
86 ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden,
87 cl::desc("Run indirect-call promotion for call instructions "
88 "only"));
89
90// If the option is set to true, only invoke instructions will be considered for
91// transformation -- call instructions will be ignored.
92static cl::opt<bool> ICPInvokeOnly("icp-invoke-only", cl::init(false),
93 cl::Hidden,
94 cl::desc("Run indirect-call promotion for "
95 "invoke instruction only"));
96
97// Dump the function level IR if the transformation happened in this
98// function. For debug use only.
99static cl::opt<bool>
100 ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden,
101 cl::desc("Dump IR after transformation happens"));
102
103namespace {
Xinliang David Li72616182016-05-15 01:04:24 +0000104class PGOIndirectCallPromotionLegacyPass : public ModulePass {
Rong Xu6e34c492016-04-27 23:20:27 +0000105public:
106 static char ID;
107
Xinliang David Li72616182016-05-15 01:04:24 +0000108 PGOIndirectCallPromotionLegacyPass(bool InLTO = false)
109 : ModulePass(ID), InLTO(InLTO) {
110 initializePGOIndirectCallPromotionLegacyPassPass(
111 *PassRegistry::getPassRegistry());
Rong Xu6e34c492016-04-27 23:20:27 +0000112 }
113
Mehdi Amini117296c2016-10-01 02:56:57 +0000114 StringRef getPassName() const override { return "PGOIndirectCallPromotion"; }
Rong Xu6e34c492016-04-27 23:20:27 +0000115
116private:
117 bool runOnModule(Module &M) override;
118
119 // If this pass is called in LTO. We need to special handling the PGOFuncName
120 // for the static variables due to LTO's internalization.
121 bool InLTO;
122};
123} // end anonymous namespace
124
Xinliang David Li72616182016-05-15 01:04:24 +0000125char PGOIndirectCallPromotionLegacyPass::ID = 0;
126INITIALIZE_PASS(PGOIndirectCallPromotionLegacyPass, "pgo-icall-prom",
Rong Xu6e34c492016-04-27 23:20:27 +0000127 "Use PGO instrumentation profile to promote indirect calls to "
128 "direct calls.",
129 false, false)
130
Xinliang David Li72616182016-05-15 01:04:24 +0000131ModulePass *llvm::createPGOIndirectCallPromotionLegacyPass(bool InLTO) {
132 return new PGOIndirectCallPromotionLegacyPass(InLTO);
Rong Xu6e34c492016-04-27 23:20:27 +0000133}
134
Benjamin Kramera65b6102016-05-15 15:18:11 +0000135namespace {
Rong Xu6e34c492016-04-27 23:20:27 +0000136// The class for main data structure to promote indirect calls to conditional
137// direct calls.
138class ICallPromotionFunc {
139private:
140 Function &F;
141 Module *M;
142
143 // Symtab that maps indirect call profile values to function names and
144 // defines.
145 InstrProfSymtab *Symtab;
146
Rong Xu6e34c492016-04-27 23:20:27 +0000147 // Test if we can legally promote this direct-call of Target.
Dehao Chen6775f5d2017-01-30 22:46:37 +0000148 bool isPromotionLegal(Instruction *Inst, uint64_t Target, Function *&F,
149 const char **Reason = nullptr);
Rong Xu6e34c492016-04-27 23:20:27 +0000150
151 // A struct that records the direct target and it's call count.
152 struct PromotionCandidate {
153 Function *TargetFunction;
154 uint64_t Count;
155 PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {}
156 };
157
158 // Check if the indirect-call call site should be promoted. Return the number
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000159 // of promotions. Inst is the candidate indirect call, ValueDataRef
160 // contains the array of value profile data for profiled targets,
161 // TotalCount is the total profiled count of call executions, and
162 // NumCandidates is the number of candidate entries in ValueDataRef.
Rong Xu6e34c492016-04-27 23:20:27 +0000163 std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(
164 Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000165 uint64_t TotalCount, uint32_t NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000166
Rong Xu6e34c492016-04-27 23:20:27 +0000167 // Promote a list of targets for one indirect-call callsite. Return
168 // the number of promotions.
169 uint32_t tryToPromote(Instruction *Inst,
170 const std::vector<PromotionCandidate> &Candidates,
171 uint64_t &TotalCount);
172
Rong Xu6e34c492016-04-27 23:20:27 +0000173 // Noncopyable
174 ICallPromotionFunc(const ICallPromotionFunc &other) = delete;
175 ICallPromotionFunc &operator=(const ICallPromotionFunc &other) = delete;
176
177public:
178 ICallPromotionFunc(Function &Func, Module *Modu, InstrProfSymtab *Symtab)
179 : F(Func), M(Modu), Symtab(Symtab) {
Rong Xu6e34c492016-04-27 23:20:27 +0000180 }
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000181
Rong Xu6e34c492016-04-27 23:20:27 +0000182 bool processFunction();
183};
Benjamin Kramera65b6102016-05-15 15:18:11 +0000184} // end anonymous namespace
Rong Xu6e34c492016-04-27 23:20:27 +0000185
Dehao Chen6775f5d2017-01-30 22:46:37 +0000186bool llvm::isLegalToPromote(Instruction *Inst, Function *F,
187 const char **Reason) {
Rong Xu6e34c492016-04-27 23:20:27 +0000188 // Check the return type.
189 Type *CallRetType = Inst->getType();
190 if (!CallRetType->isVoidTy()) {
Dehao Chen6775f5d2017-01-30 22:46:37 +0000191 Type *FuncRetType = F->getReturnType();
Rong Xu6e34c492016-04-27 23:20:27 +0000192 if (FuncRetType != CallRetType &&
Dehao Chen6775f5d2017-01-30 22:46:37 +0000193 !CastInst::isBitCastable(FuncRetType, CallRetType)) {
194 if (Reason)
195 *Reason = "Return type mismatch";
196 return false;
197 }
Rong Xu6e34c492016-04-27 23:20:27 +0000198 }
199
200 // Check if the arguments are compatible with the parameters
Dehao Chen6775f5d2017-01-30 22:46:37 +0000201 FunctionType *DirectCalleeType = F->getFunctionType();
Rong Xu6e34c492016-04-27 23:20:27 +0000202 unsigned ParamNum = DirectCalleeType->getFunctionNumParams();
203 CallSite CS(Inst);
204 unsigned ArgNum = CS.arg_size();
205
Dehao Chen6775f5d2017-01-30 22:46:37 +0000206 if (ParamNum != ArgNum && !DirectCalleeType->isVarArg()) {
207 if (Reason)
208 *Reason = "The number of arguments mismatch";
209 return false;
210 }
Rong Xu6e34c492016-04-27 23:20:27 +0000211
212 for (unsigned I = 0; I < ParamNum; ++I) {
213 Type *PTy = DirectCalleeType->getFunctionParamType(I);
214 Type *ATy = CS.getArgument(I)->getType();
215 if (PTy == ATy)
216 continue;
Dehao Chen6775f5d2017-01-30 22:46:37 +0000217 if (!CastInst::castIsValid(Instruction::BitCast, CS.getArgument(I), PTy)) {
218 if (Reason)
Benjamin Kramer365c9bd2017-01-30 23:11:29 +0000219 *Reason = "Argument type mismatch";
Dehao Chen6775f5d2017-01-30 22:46:37 +0000220 return false;
221 }
Rong Xu6e34c492016-04-27 23:20:27 +0000222 }
223
224 DEBUG(dbgs() << " #" << NumOfPGOICallPromotion << " Promote the icall to "
Dehao Chen6775f5d2017-01-30 22:46:37 +0000225 << F->getName() << "\n");
226 return true;
227}
228
229bool ICallPromotionFunc::isPromotionLegal(Instruction *Inst, uint64_t Target,
230 Function *&TargetFunction,
231 const char **Reason) {
232 TargetFunction = Symtab->getFunction(Target);
233 if (TargetFunction == nullptr) {
234 *Reason = "Cannot find the target";
235 return false;
236 }
237 return isLegalToPromote(Inst, TargetFunction, Reason);
Rong Xu6e34c492016-04-27 23:20:27 +0000238}
239
240// Indirect-call promotion heuristic. The direct targets are sorted based on
241// the count. Stop at the first target that is not promoted.
242std::vector<ICallPromotionFunc::PromotionCandidate>
243ICallPromotionFunc::getPromotionCandidatesForCallSite(
244 Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000245 uint64_t TotalCount, uint32_t NumCandidates) {
Rong Xu6e34c492016-04-27 23:20:27 +0000246 std::vector<PromotionCandidate> Ret;
247
248 DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << *Inst
Teresa Johnson8950ad12016-07-12 21:29:05 +0000249 << " Num_targets: " << ValueDataRef.size()
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000250 << " Num_candidates: " << NumCandidates << "\n");
Rong Xu6e34c492016-04-27 23:20:27 +0000251 NumOfPGOICallsites++;
252 if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) {
253 DEBUG(dbgs() << " Skip: User options.\n");
254 return Ret;
255 }
256
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000257 for (uint32_t I = 0; I < NumCandidates; I++) {
Rong Xu6e34c492016-04-27 23:20:27 +0000258 uint64_t Count = ValueDataRef[I].Count;
259 assert(Count <= TotalCount);
260 uint64_t Target = ValueDataRef[I].Value;
261 DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
262 << " Target_func: " << Target << "\n");
263
Teresa Johnsonce7de9b2016-07-17 14:46:58 +0000264 if (ICPInvokeOnly && dyn_cast<CallInst>(Inst)) {
265 DEBUG(dbgs() << " Not promote: User options.\n");
266 break;
267 }
268 if (ICPCallOnly && dyn_cast<InvokeInst>(Inst)) {
269 DEBUG(dbgs() << " Not promote: User option.\n");
270 break;
271 }
Rong Xu6e34c492016-04-27 23:20:27 +0000272 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
273 DEBUG(dbgs() << " Not promote: Cutoff reached.\n");
274 break;
275 }
Rong Xu6e34c492016-04-27 23:20:27 +0000276 Function *TargetFunction = nullptr;
Dehao Chen6775f5d2017-01-30 22:46:37 +0000277 const char *Reason = nullptr;
278 if (!isPromotionLegal(Inst, Target, TargetFunction, &Reason)) {
Rong Xu6e34c492016-04-27 23:20:27 +0000279 StringRef TargetFuncName = Symtab->getFuncName(Target);
Rong Xu6e34c492016-04-27 23:20:27 +0000280 DEBUG(dbgs() << " Not promote: " << Reason << "\n");
Rong Xu62d5e472016-04-28 17:49:56 +0000281 emitOptimizationRemarkMissed(
Xinliang David Li0b293302016-06-02 01:52:05 +0000282 F.getContext(), "pgo-icall-prom", F, Inst->getDebugLoc(),
Rong Xu6e34c492016-04-27 23:20:27 +0000283 Twine("Cannot promote indirect call to ") +
Rong Xu62d5e472016-04-28 17:49:56 +0000284 (TargetFuncName.empty() ? Twine(Target) : Twine(TargetFuncName)) +
285 Twine(" with count of ") + Twine(Count) + ": " + Reason);
Rong Xu6e34c492016-04-27 23:20:27 +0000286 break;
287 }
288 Ret.push_back(PromotionCandidate(TargetFunction, Count));
289 TotalCount -= Count;
290 }
291 return Ret;
292}
293
294// Create a diamond structure for If_Then_Else. Also update the profile
295// count. Do the fix-up for the invoke instruction.
296static void createIfThenElse(Instruction *Inst, Function *DirectCallee,
297 uint64_t Count, uint64_t TotalCount,
298 BasicBlock **DirectCallBB,
299 BasicBlock **IndirectCallBB,
300 BasicBlock **MergeBB) {
301 CallSite CS(Inst);
302 Value *OrigCallee = CS.getCalledValue();
303
304 IRBuilder<> BBBuilder(Inst);
305 LLVMContext &Ctx = Inst->getContext();
306 Value *BCI1 =
307 BBBuilder.CreateBitCast(OrigCallee, Type::getInt8PtrTy(Ctx), "");
308 Value *BCI2 =
309 BBBuilder.CreateBitCast(DirectCallee, Type::getInt8PtrTy(Ctx), "");
310 Value *PtrCmp = BBBuilder.CreateICmpEQ(BCI1, BCI2, "");
311
312 uint64_t ElseCount = TotalCount - Count;
313 uint64_t MaxCount = (Count >= ElseCount ? Count : ElseCount);
314 uint64_t Scale = calculateCountScale(MaxCount);
315 MDBuilder MDB(Inst->getContext());
316 MDNode *BranchWeights = MDB.createBranchWeights(
317 scaleBranchCount(Count, Scale), scaleBranchCount(ElseCount, Scale));
318 TerminatorInst *ThenTerm, *ElseTerm;
319 SplitBlockAndInsertIfThenElse(PtrCmp, Inst, &ThenTerm, &ElseTerm,
320 BranchWeights);
321 *DirectCallBB = ThenTerm->getParent();
322 (*DirectCallBB)->setName("if.true.direct_targ");
323 *IndirectCallBB = ElseTerm->getParent();
324 (*IndirectCallBB)->setName("if.false.orig_indirect");
325 *MergeBB = Inst->getParent();
326 (*MergeBB)->setName("if.end.icp");
327
328 // Special handing of Invoke instructions.
329 InvokeInst *II = dyn_cast<InvokeInst>(Inst);
330 if (!II)
331 return;
332
333 // We don't need branch instructions for invoke.
334 ThenTerm->eraseFromParent();
335 ElseTerm->eraseFromParent();
336
337 // Add jump from Merge BB to the NormalDest. This is needed for the newly
338 // created direct invoke stmt -- as its NormalDst will be fixed up to MergeBB.
339 BranchInst::Create(II->getNormalDest(), *MergeBB);
340}
341
342// Find the PHI in BB that have the CallResult as the operand.
343static bool getCallRetPHINode(BasicBlock *BB, Instruction *Inst) {
344 BasicBlock *From = Inst->getParent();
345 for (auto &I : *BB) {
346 PHINode *PHI = dyn_cast<PHINode>(&I);
347 if (!PHI)
348 continue;
349 int IX = PHI->getBasicBlockIndex(From);
350 if (IX == -1)
351 continue;
352 Value *V = PHI->getIncomingValue(IX);
353 if (dyn_cast<Instruction>(V) == Inst)
354 return true;
355 }
356 return false;
357}
358
359// This method fixes up PHI nodes in BB where BB is the UnwindDest of an
360// invoke instruction. In BB, there may be PHIs with incoming block being
361// OrigBB (the MergeBB after if-then-else splitting). After moving the invoke
362// instructions to its own BB, OrigBB is no longer the predecessor block of BB.
363// Instead two new predecessors are added: IndirectCallBB and DirectCallBB,
364// so the PHI node's incoming BBs need to be fixed up accordingly.
365static void fixupPHINodeForUnwind(Instruction *Inst, BasicBlock *BB,
366 BasicBlock *OrigBB,
367 BasicBlock *IndirectCallBB,
368 BasicBlock *DirectCallBB) {
369 for (auto &I : *BB) {
370 PHINode *PHI = dyn_cast<PHINode>(&I);
371 if (!PHI)
372 continue;
373 int IX = PHI->getBasicBlockIndex(OrigBB);
374 if (IX == -1)
375 continue;
376 Value *V = PHI->getIncomingValue(IX);
377 PHI->addIncoming(V, IndirectCallBB);
378 PHI->setIncomingBlock(IX, DirectCallBB);
379 }
380}
381
382// This method fixes up PHI nodes in BB where BB is the NormalDest of an
383// invoke instruction. In BB, there may be PHIs with incoming block being
384// OrigBB (the MergeBB after if-then-else splitting). After moving the invoke
385// instructions to its own BB, a new incoming edge will be added to the original
386// NormalDstBB from the IndirectCallBB.
387static void fixupPHINodeForNormalDest(Instruction *Inst, BasicBlock *BB,
388 BasicBlock *OrigBB,
389 BasicBlock *IndirectCallBB,
390 Instruction *NewInst) {
391 for (auto &I : *BB) {
392 PHINode *PHI = dyn_cast<PHINode>(&I);
393 if (!PHI)
394 continue;
395 int IX = PHI->getBasicBlockIndex(OrigBB);
396 if (IX == -1)
397 continue;
398 Value *V = PHI->getIncomingValue(IX);
399 if (dyn_cast<Instruction>(V) == Inst) {
400 PHI->setIncomingBlock(IX, IndirectCallBB);
401 PHI->addIncoming(NewInst, OrigBB);
402 continue;
403 }
404 PHI->addIncoming(V, IndirectCallBB);
405 }
406}
407
408// Add a bitcast instruction to the direct-call return value if needed.
Rong Xu6e34c492016-04-27 23:20:27 +0000409static Instruction *insertCallRetCast(const Instruction *Inst,
410 Instruction *DirectCallInst,
411 Function *DirectCallee) {
412 if (Inst->getType()->isVoidTy())
413 return DirectCallInst;
414
415 Type *CallRetType = Inst->getType();
416 Type *FuncRetType = DirectCallee->getReturnType();
417 if (FuncRetType == CallRetType)
418 return DirectCallInst;
419
420 BasicBlock *InsertionBB;
421 if (CallInst *CI = dyn_cast<CallInst>(DirectCallInst))
422 InsertionBB = CI->getParent();
423 else
424 InsertionBB = (dyn_cast<InvokeInst>(DirectCallInst))->getNormalDest();
425
426 return (new BitCastInst(DirectCallInst, CallRetType, "",
427 InsertionBB->getTerminator()));
428}
429
430// Create a DirectCall instruction in the DirectCallBB.
431// Parameter Inst is the indirect-call (invoke) instruction.
432// DirectCallee is the decl of the direct-call (invoke) target.
433// DirecallBB is the BB that the direct-call (invoke) instruction is inserted.
434// MergeBB is the bottom BB of the if-then-else-diamond after the
435// transformation. For invoke instruction, the edges from DirectCallBB and
436// IndirectCallBB to MergeBB are removed before this call (during
437// createIfThenElse).
438static Instruction *createDirectCallInst(const Instruction *Inst,
439 Function *DirectCallee,
440 BasicBlock *DirectCallBB,
441 BasicBlock *MergeBB) {
442 Instruction *NewInst = Inst->clone();
443 if (CallInst *CI = dyn_cast<CallInst>(NewInst)) {
444 CI->setCalledFunction(DirectCallee);
445 CI->mutateFunctionType(DirectCallee->getFunctionType());
446 } else {
447 // Must be an invoke instruction. Direct invoke's normal destination is
448 // fixed up to MergeBB. MergeBB is the place where return cast is inserted.
449 // Also since IndirectCallBB does not have an edge to MergeBB, there is no
450 // need to insert new PHIs into MergeBB.
451 InvokeInst *II = dyn_cast<InvokeInst>(NewInst);
452 assert(II);
453 II->setCalledFunction(DirectCallee);
454 II->mutateFunctionType(DirectCallee->getFunctionType());
455 II->setNormalDest(MergeBB);
456 }
457
458 DirectCallBB->getInstList().insert(DirectCallBB->getFirstInsertionPt(),
459 NewInst);
460
461 // Clear the value profile data.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000462 NewInst->setMetadata(LLVMContext::MD_prof, nullptr);
Rong Xu6e34c492016-04-27 23:20:27 +0000463 CallSite NewCS(NewInst);
464 FunctionType *DirectCalleeType = DirectCallee->getFunctionType();
465 unsigned ParamNum = DirectCalleeType->getFunctionNumParams();
466 for (unsigned I = 0; I < ParamNum; ++I) {
467 Type *ATy = NewCS.getArgument(I)->getType();
468 Type *PTy = DirectCalleeType->getParamType(I);
469 if (ATy != PTy) {
470 BitCastInst *BI = new BitCastInst(NewCS.getArgument(I), PTy, "", NewInst);
471 NewCS.setArgument(I, BI);
472 }
473 }
474
475 return insertCallRetCast(Inst, NewInst, DirectCallee);
476}
477
478// Create a PHI to unify the return values of calls.
479static void insertCallRetPHI(Instruction *Inst, Instruction *CallResult,
480 Function *DirectCallee) {
481 if (Inst->getType()->isVoidTy())
482 return;
483
484 BasicBlock *RetValBB = CallResult->getParent();
485
486 BasicBlock *PHIBB;
487 if (InvokeInst *II = dyn_cast<InvokeInst>(CallResult))
488 RetValBB = II->getNormalDest();
489
490 PHIBB = RetValBB->getSingleSuccessor();
491 if (getCallRetPHINode(PHIBB, Inst))
492 return;
493
494 PHINode *CallRetPHI = PHINode::Create(Inst->getType(), 0);
495 PHIBB->getInstList().push_front(CallRetPHI);
496 Inst->replaceAllUsesWith(CallRetPHI);
497 CallRetPHI->addIncoming(Inst, Inst->getParent());
498 CallRetPHI->addIncoming(CallResult, RetValBB);
499}
500
501// This function does the actual indirect-call promotion transformation:
502// For an indirect-call like:
503// Ret = (*Foo)(Args);
504// It transforms to:
505// if (Foo == DirectCallee)
506// Ret1 = DirectCallee(Args);
507// else
508// Ret2 = (*Foo)(Args);
509// Ret = phi(Ret1, Ret2);
510// It adds type casts for the args do not match the parameters and the return
511// value. Branch weights metadata also updated.
Dehao Chen14bf0292017-01-23 23:18:24 +0000512// Returns the promoted direct call instruction.
513Instruction *llvm::promoteIndirectCall(Instruction *Inst,
514 Function *DirectCallee, uint64_t Count,
515 uint64_t TotalCount) {
Rong Xu6e34c492016-04-27 23:20:27 +0000516 assert(DirectCallee != nullptr);
517 BasicBlock *BB = Inst->getParent();
518 // Just to suppress the non-debug build warning.
519 (void)BB;
520 DEBUG(dbgs() << "\n\n== Basic Block Before ==\n");
521 DEBUG(dbgs() << *BB << "\n");
522
523 BasicBlock *DirectCallBB, *IndirectCallBB, *MergeBB;
524 createIfThenElse(Inst, DirectCallee, Count, TotalCount, &DirectCallBB,
525 &IndirectCallBB, &MergeBB);
526
527 Instruction *NewInst =
528 createDirectCallInst(Inst, DirectCallee, DirectCallBB, MergeBB);
529
530 // Move Inst from MergeBB to IndirectCallBB.
531 Inst->removeFromParent();
532 IndirectCallBB->getInstList().insert(IndirectCallBB->getFirstInsertionPt(),
533 Inst);
534
535 if (InvokeInst *II = dyn_cast<InvokeInst>(Inst)) {
536 // At this point, the original indirect invoke instruction has the original
537 // UnwindDest and NormalDest. For the direct invoke instruction, the
538 // NormalDest points to MergeBB, and MergeBB jumps to the original
539 // NormalDest. MergeBB might have a new bitcast instruction for the return
540 // value. The PHIs are with the original NormalDest. Since we now have two
541 // incoming edges to NormalDest and UnwindDest, we have to do some fixups.
542 //
543 // UnwindDest will not use the return value. So pass nullptr here.
544 fixupPHINodeForUnwind(Inst, II->getUnwindDest(), MergeBB, IndirectCallBB,
545 DirectCallBB);
546 // We don't need to update the operand from NormalDest for DirectCallBB.
547 // Pass nullptr here.
548 fixupPHINodeForNormalDest(Inst, II->getNormalDest(), MergeBB,
549 IndirectCallBB, NewInst);
550 }
551
552 insertCallRetPHI(Inst, NewInst, DirectCallee);
553
554 DEBUG(dbgs() << "\n== Basic Blocks After ==\n");
555 DEBUG(dbgs() << *BB << *DirectCallBB << *IndirectCallBB << *MergeBB << "\n");
556
Rong Xu62d5e472016-04-28 17:49:56 +0000557 emitOptimizationRemark(
Dehao Chen14bf0292017-01-23 23:18:24 +0000558 BB->getContext(), "pgo-icall-prom", *BB->getParent(), Inst->getDebugLoc(),
Rong Xu62d5e472016-04-28 17:49:56 +0000559 Twine("Promote indirect call to ") + DirectCallee->getName() +
560 " with count " + Twine(Count) + " out of " + Twine(TotalCount));
Dehao Chen14bf0292017-01-23 23:18:24 +0000561 return NewInst;
Rong Xu6e34c492016-04-27 23:20:27 +0000562}
563
564// Promote indirect-call to conditional direct-call for one callsite.
565uint32_t ICallPromotionFunc::tryToPromote(
566 Instruction *Inst, const std::vector<PromotionCandidate> &Candidates,
567 uint64_t &TotalCount) {
568 uint32_t NumPromoted = 0;
569
570 for (auto &C : Candidates) {
571 uint64_t Count = C.Count;
Dehao Chen14bf0292017-01-23 23:18:24 +0000572 promoteIndirectCall(Inst, C.TargetFunction, Count, TotalCount);
Rong Xu6e34c492016-04-27 23:20:27 +0000573 assert(TotalCount >= Count);
574 TotalCount -= Count;
575 NumOfPGOICallPromotion++;
576 NumPromoted++;
577 }
578 return NumPromoted;
579}
580
581// Traverse all the indirect-call callsite and get the value profile
582// annotation to perform indirect-call promotion.
583bool ICallPromotionFunc::processFunction() {
584 bool Changed = false;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000585 ICallPromotionAnalysis ICallAnalysis;
Rong Xu6e34c492016-04-27 23:20:27 +0000586 for (auto &I : findIndirectCallSites(F)) {
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000587 uint32_t NumVals, NumCandidates;
Rong Xu6e34c492016-04-27 23:20:27 +0000588 uint64_t TotalCount;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000589 auto ICallProfDataRef = ICallAnalysis.getPromotionCandidatesForInstruction(
590 I, NumVals, TotalCount, NumCandidates);
591 if (!NumCandidates)
Rong Xu6e34c492016-04-27 23:20:27 +0000592 continue;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000593 auto PromotionCandidates = getPromotionCandidatesForCallSite(
594 I, ICallProfDataRef, TotalCount, NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000595 uint32_t NumPromoted = tryToPromote(I, PromotionCandidates, TotalCount);
596 if (NumPromoted == 0)
597 continue;
598
599 Changed = true;
600 // Adjust the MD.prof metadata. First delete the old one.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000601 I->setMetadata(LLVMContext::MD_prof, nullptr);
Rong Xu6e34c492016-04-27 23:20:27 +0000602 // If all promoted, we don't need the MD.prof metadata.
603 if (TotalCount == 0 || NumPromoted == NumVals)
604 continue;
605 // Otherwise we need update with the un-promoted records back.
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000606 annotateValueSite(*M, *I, ICallProfDataRef.slice(NumPromoted), TotalCount,
607 IPVK_IndirectCallTarget, NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000608 }
609 return Changed;
610}
611
612// A wrapper function that does the actual work.
613static bool promoteIndirectCalls(Module &M, bool InLTO) {
614 if (DisableICP)
615 return false;
616 InstrProfSymtab Symtab;
617 Symtab.create(M, InLTO);
618 bool Changed = false;
619 for (auto &F : M) {
620 if (F.isDeclaration())
621 continue;
622 if (F.hasFnAttribute(Attribute::OptimizeNone))
623 continue;
624 ICallPromotionFunc ICallPromotion(F, &M, &Symtab);
625 bool FuncChanged = ICallPromotion.processFunction();
626 if (ICPDUMPAFTER && FuncChanged) {
627 DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs()));
628 DEBUG(dbgs() << "\n");
629 }
630 Changed |= FuncChanged;
631 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
632 DEBUG(dbgs() << " Stop: Cutoff reached.\n");
633 break;
634 }
635 }
636 return Changed;
637}
638
Xinliang David Li72616182016-05-15 01:04:24 +0000639bool PGOIndirectCallPromotionLegacyPass::runOnModule(Module &M) {
Rong Xu6e34c492016-04-27 23:20:27 +0000640 // Command-line option has the priority for InLTO.
Xinliang David Li7d0fed72016-05-17 21:06:16 +0000641 return promoteIndirectCalls(M, InLTO | ICPLTOMode);
Rong Xu6e34c492016-04-27 23:20:27 +0000642}
Xinliang David Lif3c7a352016-05-16 16:31:07 +0000643
Sean Silvafd03ac62016-08-09 00:28:38 +0000644PreservedAnalyses PGOIndirectCallPromotion::run(Module &M, ModuleAnalysisManager &AM) {
Xinliang David Li7d0fed72016-05-17 21:06:16 +0000645 if (!promoteIndirectCalls(M, InLTO | ICPLTOMode))
Xinliang David Lif3c7a352016-05-16 16:31:07 +0000646 return PreservedAnalyses::all();
647
648 return PreservedAnalyses::none();
649}