blob: 700ed4e8576a9f580c83bd035a058c434145bc34 [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
Dehao Chencc75d242017-02-23 22:15:18 +000083// Set if the pass is called in SamplePGO mode. The difference for SamplePGO
84// mode is it will add prof metadatato the created direct call.
85static cl::opt<bool>
86 ICPSamplePGOMode("icp-samplepgo", cl::init(false), cl::Hidden,
87 cl::desc("Run indirect-call promotion in SamplePGO mode"));
88
Rong Xu6e34c492016-04-27 23:20:27 +000089// If the option is set to true, only call instructions will be considered for
90// transformation -- invoke instructions will be ignored.
91static cl::opt<bool>
92 ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden,
93 cl::desc("Run indirect-call promotion for call instructions "
94 "only"));
95
96// If the option is set to true, only invoke instructions will be considered for
97// transformation -- call instructions will be ignored.
98static cl::opt<bool> ICPInvokeOnly("icp-invoke-only", cl::init(false),
99 cl::Hidden,
100 cl::desc("Run indirect-call promotion for "
101 "invoke instruction only"));
102
103// Dump the function level IR if the transformation happened in this
104// function. For debug use only.
105static cl::opt<bool>
106 ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden,
107 cl::desc("Dump IR after transformation happens"));
108
109namespace {
Xinliang David Li72616182016-05-15 01:04:24 +0000110class PGOIndirectCallPromotionLegacyPass : public ModulePass {
Rong Xu6e34c492016-04-27 23:20:27 +0000111public:
112 static char ID;
113
Dehao Chencc75d242017-02-23 22:15:18 +0000114 PGOIndirectCallPromotionLegacyPass(bool InLTO = false, bool SamplePGO = false)
115 : ModulePass(ID), InLTO(InLTO), SamplePGO(SamplePGO) {
Xinliang David Li72616182016-05-15 01:04:24 +0000116 initializePGOIndirectCallPromotionLegacyPassPass(
117 *PassRegistry::getPassRegistry());
Rong Xu6e34c492016-04-27 23:20:27 +0000118 }
119
Mehdi Amini117296c2016-10-01 02:56:57 +0000120 StringRef getPassName() const override { return "PGOIndirectCallPromotion"; }
Rong Xu6e34c492016-04-27 23:20:27 +0000121
122private:
123 bool runOnModule(Module &M) override;
124
125 // If this pass is called in LTO. We need to special handling the PGOFuncName
126 // for the static variables due to LTO's internalization.
127 bool InLTO;
Dehao Chencc75d242017-02-23 22:15:18 +0000128
129 // If this pass is called in SamplePGO. We need to add the prof metadata to
130 // the promoted direct call.
131 bool SamplePGO;
Rong Xu6e34c492016-04-27 23:20:27 +0000132};
133} // end anonymous namespace
134
Xinliang David Li72616182016-05-15 01:04:24 +0000135char PGOIndirectCallPromotionLegacyPass::ID = 0;
136INITIALIZE_PASS(PGOIndirectCallPromotionLegacyPass, "pgo-icall-prom",
Rong Xu6e34c492016-04-27 23:20:27 +0000137 "Use PGO instrumentation profile to promote indirect calls to "
138 "direct calls.",
139 false, false)
140
Dehao Chencc75d242017-02-23 22:15:18 +0000141ModulePass *llvm::createPGOIndirectCallPromotionLegacyPass(bool InLTO,
142 bool SamplePGO) {
143 return new PGOIndirectCallPromotionLegacyPass(InLTO, SamplePGO);
Rong Xu6e34c492016-04-27 23:20:27 +0000144}
145
Benjamin Kramera65b6102016-05-15 15:18:11 +0000146namespace {
Rong Xu6e34c492016-04-27 23:20:27 +0000147// The class for main data structure to promote indirect calls to conditional
148// direct calls.
149class ICallPromotionFunc {
150private:
151 Function &F;
152 Module *M;
153
154 // Symtab that maps indirect call profile values to function names and
155 // defines.
156 InstrProfSymtab *Symtab;
157
Dehao Chencc75d242017-02-23 22:15:18 +0000158 bool SamplePGO;
159
Rong Xu6e34c492016-04-27 23:20:27 +0000160 // Test if we can legally promote this direct-call of Target.
Dehao Chen6775f5d2017-01-30 22:46:37 +0000161 bool isPromotionLegal(Instruction *Inst, uint64_t Target, Function *&F,
162 const char **Reason = nullptr);
Rong Xu6e34c492016-04-27 23:20:27 +0000163
164 // A struct that records the direct target and it's call count.
165 struct PromotionCandidate {
166 Function *TargetFunction;
167 uint64_t Count;
168 PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {}
169 };
170
171 // Check if the indirect-call call site should be promoted. Return the number
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000172 // of promotions. Inst is the candidate indirect call, ValueDataRef
173 // contains the array of value profile data for profiled targets,
174 // TotalCount is the total profiled count of call executions, and
175 // NumCandidates is the number of candidate entries in ValueDataRef.
Rong Xu6e34c492016-04-27 23:20:27 +0000176 std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(
177 Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000178 uint64_t TotalCount, uint32_t NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000179
Rong Xu6e34c492016-04-27 23:20:27 +0000180 // Promote a list of targets for one indirect-call callsite. Return
181 // the number of promotions.
182 uint32_t tryToPromote(Instruction *Inst,
183 const std::vector<PromotionCandidate> &Candidates,
184 uint64_t &TotalCount);
185
Rong Xu6e34c492016-04-27 23:20:27 +0000186 // Noncopyable
187 ICallPromotionFunc(const ICallPromotionFunc &other) = delete;
188 ICallPromotionFunc &operator=(const ICallPromotionFunc &other) = delete;
189
190public:
Dehao Chencc75d242017-02-23 22:15:18 +0000191 ICallPromotionFunc(Function &Func, Module *Modu, InstrProfSymtab *Symtab,
192 bool SamplePGO)
193 : F(Func), M(Modu), Symtab(Symtab), SamplePGO(SamplePGO) {}
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000194
Rong Xu6e34c492016-04-27 23:20:27 +0000195 bool processFunction();
196};
Benjamin Kramera65b6102016-05-15 15:18:11 +0000197} // end anonymous namespace
Rong Xu6e34c492016-04-27 23:20:27 +0000198
Dehao Chen6775f5d2017-01-30 22:46:37 +0000199bool llvm::isLegalToPromote(Instruction *Inst, Function *F,
200 const char **Reason) {
Rong Xu6e34c492016-04-27 23:20:27 +0000201 // Check the return type.
202 Type *CallRetType = Inst->getType();
203 if (!CallRetType->isVoidTy()) {
Dehao Chen6775f5d2017-01-30 22:46:37 +0000204 Type *FuncRetType = F->getReturnType();
Rong Xu6e34c492016-04-27 23:20:27 +0000205 if (FuncRetType != CallRetType &&
Dehao Chen6775f5d2017-01-30 22:46:37 +0000206 !CastInst::isBitCastable(FuncRetType, CallRetType)) {
207 if (Reason)
208 *Reason = "Return type mismatch";
209 return false;
210 }
Rong Xu6e34c492016-04-27 23:20:27 +0000211 }
212
213 // Check if the arguments are compatible with the parameters
Dehao Chen6775f5d2017-01-30 22:46:37 +0000214 FunctionType *DirectCalleeType = F->getFunctionType();
Rong Xu6e34c492016-04-27 23:20:27 +0000215 unsigned ParamNum = DirectCalleeType->getFunctionNumParams();
216 CallSite CS(Inst);
217 unsigned ArgNum = CS.arg_size();
218
Dehao Chen6775f5d2017-01-30 22:46:37 +0000219 if (ParamNum != ArgNum && !DirectCalleeType->isVarArg()) {
220 if (Reason)
221 *Reason = "The number of arguments mismatch";
222 return false;
223 }
Rong Xu6e34c492016-04-27 23:20:27 +0000224
225 for (unsigned I = 0; I < ParamNum; ++I) {
226 Type *PTy = DirectCalleeType->getFunctionParamType(I);
227 Type *ATy = CS.getArgument(I)->getType();
228 if (PTy == ATy)
229 continue;
Dehao Chen6775f5d2017-01-30 22:46:37 +0000230 if (!CastInst::castIsValid(Instruction::BitCast, CS.getArgument(I), PTy)) {
231 if (Reason)
Benjamin Kramer365c9bd2017-01-30 23:11:29 +0000232 *Reason = "Argument type mismatch";
Dehao Chen6775f5d2017-01-30 22:46:37 +0000233 return false;
234 }
Rong Xu6e34c492016-04-27 23:20:27 +0000235 }
236
237 DEBUG(dbgs() << " #" << NumOfPGOICallPromotion << " Promote the icall to "
Dehao Chen6775f5d2017-01-30 22:46:37 +0000238 << F->getName() << "\n");
239 return true;
240}
241
242bool ICallPromotionFunc::isPromotionLegal(Instruction *Inst, uint64_t Target,
243 Function *&TargetFunction,
244 const char **Reason) {
245 TargetFunction = Symtab->getFunction(Target);
246 if (TargetFunction == nullptr) {
247 *Reason = "Cannot find the target";
248 return false;
249 }
250 return isLegalToPromote(Inst, TargetFunction, Reason);
Rong Xu6e34c492016-04-27 23:20:27 +0000251}
252
253// Indirect-call promotion heuristic. The direct targets are sorted based on
254// the count. Stop at the first target that is not promoted.
255std::vector<ICallPromotionFunc::PromotionCandidate>
256ICallPromotionFunc::getPromotionCandidatesForCallSite(
257 Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000258 uint64_t TotalCount, uint32_t NumCandidates) {
Rong Xu6e34c492016-04-27 23:20:27 +0000259 std::vector<PromotionCandidate> Ret;
260
261 DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << *Inst
Teresa Johnson8950ad12016-07-12 21:29:05 +0000262 << " Num_targets: " << ValueDataRef.size()
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000263 << " Num_candidates: " << NumCandidates << "\n");
Rong Xu6e34c492016-04-27 23:20:27 +0000264 NumOfPGOICallsites++;
265 if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) {
266 DEBUG(dbgs() << " Skip: User options.\n");
267 return Ret;
268 }
269
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000270 for (uint32_t I = 0; I < NumCandidates; I++) {
Rong Xu6e34c492016-04-27 23:20:27 +0000271 uint64_t Count = ValueDataRef[I].Count;
272 assert(Count <= TotalCount);
273 uint64_t Target = ValueDataRef[I].Value;
274 DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
275 << " Target_func: " << Target << "\n");
276
Teresa Johnsonce7de9b2016-07-17 14:46:58 +0000277 if (ICPInvokeOnly && dyn_cast<CallInst>(Inst)) {
278 DEBUG(dbgs() << " Not promote: User options.\n");
279 break;
280 }
281 if (ICPCallOnly && dyn_cast<InvokeInst>(Inst)) {
282 DEBUG(dbgs() << " Not promote: User option.\n");
283 break;
284 }
Rong Xu6e34c492016-04-27 23:20:27 +0000285 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
286 DEBUG(dbgs() << " Not promote: Cutoff reached.\n");
287 break;
288 }
Rong Xu6e34c492016-04-27 23:20:27 +0000289 Function *TargetFunction = nullptr;
Dehao Chen6775f5d2017-01-30 22:46:37 +0000290 const char *Reason = nullptr;
291 if (!isPromotionLegal(Inst, Target, TargetFunction, &Reason)) {
Rong Xu6e34c492016-04-27 23:20:27 +0000292 StringRef TargetFuncName = Symtab->getFuncName(Target);
Rong Xu6e34c492016-04-27 23:20:27 +0000293 DEBUG(dbgs() << " Not promote: " << Reason << "\n");
Rong Xu62d5e472016-04-28 17:49:56 +0000294 emitOptimizationRemarkMissed(
Xinliang David Li0b293302016-06-02 01:52:05 +0000295 F.getContext(), "pgo-icall-prom", F, Inst->getDebugLoc(),
Rong Xu6e34c492016-04-27 23:20:27 +0000296 Twine("Cannot promote indirect call to ") +
Rong Xu62d5e472016-04-28 17:49:56 +0000297 (TargetFuncName.empty() ? Twine(Target) : Twine(TargetFuncName)) +
298 Twine(" with count of ") + Twine(Count) + ": " + Reason);
Rong Xu6e34c492016-04-27 23:20:27 +0000299 break;
300 }
301 Ret.push_back(PromotionCandidate(TargetFunction, Count));
302 TotalCount -= Count;
303 }
304 return Ret;
305}
306
307// Create a diamond structure for If_Then_Else. Also update the profile
308// count. Do the fix-up for the invoke instruction.
309static void createIfThenElse(Instruction *Inst, Function *DirectCallee,
310 uint64_t Count, uint64_t TotalCount,
311 BasicBlock **DirectCallBB,
312 BasicBlock **IndirectCallBB,
313 BasicBlock **MergeBB) {
314 CallSite CS(Inst);
315 Value *OrigCallee = CS.getCalledValue();
316
317 IRBuilder<> BBBuilder(Inst);
318 LLVMContext &Ctx = Inst->getContext();
319 Value *BCI1 =
320 BBBuilder.CreateBitCast(OrigCallee, Type::getInt8PtrTy(Ctx), "");
321 Value *BCI2 =
322 BBBuilder.CreateBitCast(DirectCallee, Type::getInt8PtrTy(Ctx), "");
323 Value *PtrCmp = BBBuilder.CreateICmpEQ(BCI1, BCI2, "");
324
325 uint64_t ElseCount = TotalCount - Count;
326 uint64_t MaxCount = (Count >= ElseCount ? Count : ElseCount);
327 uint64_t Scale = calculateCountScale(MaxCount);
328 MDBuilder MDB(Inst->getContext());
329 MDNode *BranchWeights = MDB.createBranchWeights(
330 scaleBranchCount(Count, Scale), scaleBranchCount(ElseCount, Scale));
331 TerminatorInst *ThenTerm, *ElseTerm;
332 SplitBlockAndInsertIfThenElse(PtrCmp, Inst, &ThenTerm, &ElseTerm,
333 BranchWeights);
334 *DirectCallBB = ThenTerm->getParent();
335 (*DirectCallBB)->setName("if.true.direct_targ");
336 *IndirectCallBB = ElseTerm->getParent();
337 (*IndirectCallBB)->setName("if.false.orig_indirect");
338 *MergeBB = Inst->getParent();
339 (*MergeBB)->setName("if.end.icp");
340
341 // Special handing of Invoke instructions.
342 InvokeInst *II = dyn_cast<InvokeInst>(Inst);
343 if (!II)
344 return;
345
346 // We don't need branch instructions for invoke.
347 ThenTerm->eraseFromParent();
348 ElseTerm->eraseFromParent();
349
350 // Add jump from Merge BB to the NormalDest. This is needed for the newly
351 // created direct invoke stmt -- as its NormalDst will be fixed up to MergeBB.
352 BranchInst::Create(II->getNormalDest(), *MergeBB);
353}
354
355// Find the PHI in BB that have the CallResult as the operand.
356static bool getCallRetPHINode(BasicBlock *BB, Instruction *Inst) {
357 BasicBlock *From = Inst->getParent();
358 for (auto &I : *BB) {
359 PHINode *PHI = dyn_cast<PHINode>(&I);
360 if (!PHI)
361 continue;
362 int IX = PHI->getBasicBlockIndex(From);
363 if (IX == -1)
364 continue;
365 Value *V = PHI->getIncomingValue(IX);
366 if (dyn_cast<Instruction>(V) == Inst)
367 return true;
368 }
369 return false;
370}
371
372// This method fixes up PHI nodes in BB where BB is the UnwindDest of an
373// invoke instruction. In BB, there may be PHIs with incoming block being
374// OrigBB (the MergeBB after if-then-else splitting). After moving the invoke
375// instructions to its own BB, OrigBB is no longer the predecessor block of BB.
376// Instead two new predecessors are added: IndirectCallBB and DirectCallBB,
377// so the PHI node's incoming BBs need to be fixed up accordingly.
378static void fixupPHINodeForUnwind(Instruction *Inst, BasicBlock *BB,
379 BasicBlock *OrigBB,
380 BasicBlock *IndirectCallBB,
381 BasicBlock *DirectCallBB) {
382 for (auto &I : *BB) {
383 PHINode *PHI = dyn_cast<PHINode>(&I);
384 if (!PHI)
385 continue;
386 int IX = PHI->getBasicBlockIndex(OrigBB);
387 if (IX == -1)
388 continue;
389 Value *V = PHI->getIncomingValue(IX);
390 PHI->addIncoming(V, IndirectCallBB);
391 PHI->setIncomingBlock(IX, DirectCallBB);
392 }
393}
394
395// This method fixes up PHI nodes in BB where BB is the NormalDest of an
396// invoke instruction. In BB, there may be PHIs with incoming block being
397// OrigBB (the MergeBB after if-then-else splitting). After moving the invoke
398// instructions to its own BB, a new incoming edge will be added to the original
399// NormalDstBB from the IndirectCallBB.
400static void fixupPHINodeForNormalDest(Instruction *Inst, BasicBlock *BB,
401 BasicBlock *OrigBB,
402 BasicBlock *IndirectCallBB,
403 Instruction *NewInst) {
404 for (auto &I : *BB) {
405 PHINode *PHI = dyn_cast<PHINode>(&I);
406 if (!PHI)
407 continue;
408 int IX = PHI->getBasicBlockIndex(OrigBB);
409 if (IX == -1)
410 continue;
411 Value *V = PHI->getIncomingValue(IX);
412 if (dyn_cast<Instruction>(V) == Inst) {
413 PHI->setIncomingBlock(IX, IndirectCallBB);
414 PHI->addIncoming(NewInst, OrigBB);
415 continue;
416 }
417 PHI->addIncoming(V, IndirectCallBB);
418 }
419}
420
421// Add a bitcast instruction to the direct-call return value if needed.
Rong Xu6e34c492016-04-27 23:20:27 +0000422static Instruction *insertCallRetCast(const Instruction *Inst,
423 Instruction *DirectCallInst,
424 Function *DirectCallee) {
425 if (Inst->getType()->isVoidTy())
426 return DirectCallInst;
427
428 Type *CallRetType = Inst->getType();
429 Type *FuncRetType = DirectCallee->getReturnType();
430 if (FuncRetType == CallRetType)
431 return DirectCallInst;
432
433 BasicBlock *InsertionBB;
434 if (CallInst *CI = dyn_cast<CallInst>(DirectCallInst))
435 InsertionBB = CI->getParent();
436 else
437 InsertionBB = (dyn_cast<InvokeInst>(DirectCallInst))->getNormalDest();
438
439 return (new BitCastInst(DirectCallInst, CallRetType, "",
440 InsertionBB->getTerminator()));
441}
442
443// Create a DirectCall instruction in the DirectCallBB.
444// Parameter Inst is the indirect-call (invoke) instruction.
445// DirectCallee is the decl of the direct-call (invoke) target.
446// DirecallBB is the BB that the direct-call (invoke) instruction is inserted.
447// MergeBB is the bottom BB of the if-then-else-diamond after the
448// transformation. For invoke instruction, the edges from DirectCallBB and
449// IndirectCallBB to MergeBB are removed before this call (during
450// createIfThenElse).
451static Instruction *createDirectCallInst(const Instruction *Inst,
452 Function *DirectCallee,
453 BasicBlock *DirectCallBB,
454 BasicBlock *MergeBB) {
455 Instruction *NewInst = Inst->clone();
456 if (CallInst *CI = dyn_cast<CallInst>(NewInst)) {
457 CI->setCalledFunction(DirectCallee);
458 CI->mutateFunctionType(DirectCallee->getFunctionType());
459 } else {
460 // Must be an invoke instruction. Direct invoke's normal destination is
461 // fixed up to MergeBB. MergeBB is the place where return cast is inserted.
462 // Also since IndirectCallBB does not have an edge to MergeBB, there is no
463 // need to insert new PHIs into MergeBB.
464 InvokeInst *II = dyn_cast<InvokeInst>(NewInst);
465 assert(II);
466 II->setCalledFunction(DirectCallee);
467 II->mutateFunctionType(DirectCallee->getFunctionType());
468 II->setNormalDest(MergeBB);
469 }
470
471 DirectCallBB->getInstList().insert(DirectCallBB->getFirstInsertionPt(),
472 NewInst);
473
474 // Clear the value profile data.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000475 NewInst->setMetadata(LLVMContext::MD_prof, nullptr);
Rong Xu6e34c492016-04-27 23:20:27 +0000476 CallSite NewCS(NewInst);
477 FunctionType *DirectCalleeType = DirectCallee->getFunctionType();
478 unsigned ParamNum = DirectCalleeType->getFunctionNumParams();
479 for (unsigned I = 0; I < ParamNum; ++I) {
480 Type *ATy = NewCS.getArgument(I)->getType();
481 Type *PTy = DirectCalleeType->getParamType(I);
482 if (ATy != PTy) {
483 BitCastInst *BI = new BitCastInst(NewCS.getArgument(I), PTy, "", NewInst);
484 NewCS.setArgument(I, BI);
485 }
486 }
487
488 return insertCallRetCast(Inst, NewInst, DirectCallee);
489}
490
491// Create a PHI to unify the return values of calls.
492static void insertCallRetPHI(Instruction *Inst, Instruction *CallResult,
493 Function *DirectCallee) {
494 if (Inst->getType()->isVoidTy())
495 return;
496
497 BasicBlock *RetValBB = CallResult->getParent();
498
499 BasicBlock *PHIBB;
500 if (InvokeInst *II = dyn_cast<InvokeInst>(CallResult))
501 RetValBB = II->getNormalDest();
502
503 PHIBB = RetValBB->getSingleSuccessor();
504 if (getCallRetPHINode(PHIBB, Inst))
505 return;
506
507 PHINode *CallRetPHI = PHINode::Create(Inst->getType(), 0);
508 PHIBB->getInstList().push_front(CallRetPHI);
509 Inst->replaceAllUsesWith(CallRetPHI);
510 CallRetPHI->addIncoming(Inst, Inst->getParent());
511 CallRetPHI->addIncoming(CallResult, RetValBB);
512}
513
514// This function does the actual indirect-call promotion transformation:
515// For an indirect-call like:
516// Ret = (*Foo)(Args);
517// It transforms to:
518// if (Foo == DirectCallee)
519// Ret1 = DirectCallee(Args);
520// else
521// Ret2 = (*Foo)(Args);
522// Ret = phi(Ret1, Ret2);
523// It adds type casts for the args do not match the parameters and the return
524// value. Branch weights metadata also updated.
Dehao Chencc75d242017-02-23 22:15:18 +0000525// If \p AttachProfToDirectCall is true, a prof metadata is attached to the
526// new direct call to contain \p Count. This is used by SamplePGO inliner to
527// check callsite hotness.
Dehao Chen14bf0292017-01-23 23:18:24 +0000528// Returns the promoted direct call instruction.
529Instruction *llvm::promoteIndirectCall(Instruction *Inst,
530 Function *DirectCallee, uint64_t Count,
Dehao Chencc75d242017-02-23 22:15:18 +0000531 uint64_t TotalCount,
532 bool AttachProfToDirectCall) {
Rong Xu6e34c492016-04-27 23:20:27 +0000533 assert(DirectCallee != nullptr);
534 BasicBlock *BB = Inst->getParent();
535 // Just to suppress the non-debug build warning.
536 (void)BB;
537 DEBUG(dbgs() << "\n\n== Basic Block Before ==\n");
538 DEBUG(dbgs() << *BB << "\n");
539
540 BasicBlock *DirectCallBB, *IndirectCallBB, *MergeBB;
541 createIfThenElse(Inst, DirectCallee, Count, TotalCount, &DirectCallBB,
542 &IndirectCallBB, &MergeBB);
543
544 Instruction *NewInst =
545 createDirectCallInst(Inst, DirectCallee, DirectCallBB, MergeBB);
546
Dehao Chencc75d242017-02-23 22:15:18 +0000547 if (AttachProfToDirectCall) {
548 SmallVector<uint32_t, 1> Weights;
549 Weights.push_back(Count);
550 MDBuilder MDB(NewInst->getContext());
551 dyn_cast<Instruction>(NewInst->stripPointerCasts())
552 ->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
553 }
554
Rong Xu6e34c492016-04-27 23:20:27 +0000555 // Move Inst from MergeBB to IndirectCallBB.
556 Inst->removeFromParent();
557 IndirectCallBB->getInstList().insert(IndirectCallBB->getFirstInsertionPt(),
558 Inst);
559
560 if (InvokeInst *II = dyn_cast<InvokeInst>(Inst)) {
561 // At this point, the original indirect invoke instruction has the original
562 // UnwindDest and NormalDest. For the direct invoke instruction, the
563 // NormalDest points to MergeBB, and MergeBB jumps to the original
564 // NormalDest. MergeBB might have a new bitcast instruction for the return
565 // value. The PHIs are with the original NormalDest. Since we now have two
566 // incoming edges to NormalDest and UnwindDest, we have to do some fixups.
567 //
568 // UnwindDest will not use the return value. So pass nullptr here.
569 fixupPHINodeForUnwind(Inst, II->getUnwindDest(), MergeBB, IndirectCallBB,
570 DirectCallBB);
571 // We don't need to update the operand from NormalDest for DirectCallBB.
572 // Pass nullptr here.
573 fixupPHINodeForNormalDest(Inst, II->getNormalDest(), MergeBB,
574 IndirectCallBB, NewInst);
575 }
576
577 insertCallRetPHI(Inst, NewInst, DirectCallee);
578
579 DEBUG(dbgs() << "\n== Basic Blocks After ==\n");
580 DEBUG(dbgs() << *BB << *DirectCallBB << *IndirectCallBB << *MergeBB << "\n");
581
Rong Xu62d5e472016-04-28 17:49:56 +0000582 emitOptimizationRemark(
Dehao Chen14bf0292017-01-23 23:18:24 +0000583 BB->getContext(), "pgo-icall-prom", *BB->getParent(), Inst->getDebugLoc(),
Rong Xu62d5e472016-04-28 17:49:56 +0000584 Twine("Promote indirect call to ") + DirectCallee->getName() +
585 " with count " + Twine(Count) + " out of " + Twine(TotalCount));
Dehao Chen14bf0292017-01-23 23:18:24 +0000586 return NewInst;
Rong Xu6e34c492016-04-27 23:20:27 +0000587}
588
589// Promote indirect-call to conditional direct-call for one callsite.
590uint32_t ICallPromotionFunc::tryToPromote(
591 Instruction *Inst, const std::vector<PromotionCandidate> &Candidates,
592 uint64_t &TotalCount) {
593 uint32_t NumPromoted = 0;
594
595 for (auto &C : Candidates) {
596 uint64_t Count = C.Count;
Dehao Chencc75d242017-02-23 22:15:18 +0000597 promoteIndirectCall(Inst, C.TargetFunction, Count, TotalCount, SamplePGO);
Rong Xu6e34c492016-04-27 23:20:27 +0000598 assert(TotalCount >= Count);
599 TotalCount -= Count;
600 NumOfPGOICallPromotion++;
601 NumPromoted++;
602 }
603 return NumPromoted;
604}
605
606// Traverse all the indirect-call callsite and get the value profile
607// annotation to perform indirect-call promotion.
608bool ICallPromotionFunc::processFunction() {
609 bool Changed = false;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000610 ICallPromotionAnalysis ICallAnalysis;
Rong Xu6e34c492016-04-27 23:20:27 +0000611 for (auto &I : findIndirectCallSites(F)) {
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000612 uint32_t NumVals, NumCandidates;
Rong Xu6e34c492016-04-27 23:20:27 +0000613 uint64_t TotalCount;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000614 auto ICallProfDataRef = ICallAnalysis.getPromotionCandidatesForInstruction(
615 I, NumVals, TotalCount, NumCandidates);
616 if (!NumCandidates)
Rong Xu6e34c492016-04-27 23:20:27 +0000617 continue;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000618 auto PromotionCandidates = getPromotionCandidatesForCallSite(
619 I, ICallProfDataRef, TotalCount, NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000620 uint32_t NumPromoted = tryToPromote(I, PromotionCandidates, TotalCount);
621 if (NumPromoted == 0)
622 continue;
623
624 Changed = true;
625 // Adjust the MD.prof metadata. First delete the old one.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000626 I->setMetadata(LLVMContext::MD_prof, nullptr);
Rong Xu6e34c492016-04-27 23:20:27 +0000627 // If all promoted, we don't need the MD.prof metadata.
628 if (TotalCount == 0 || NumPromoted == NumVals)
629 continue;
630 // Otherwise we need update with the un-promoted records back.
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000631 annotateValueSite(*M, *I, ICallProfDataRef.slice(NumPromoted), TotalCount,
632 IPVK_IndirectCallTarget, NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000633 }
634 return Changed;
635}
636
637// A wrapper function that does the actual work.
Dehao Chencc75d242017-02-23 22:15:18 +0000638static bool promoteIndirectCalls(Module &M, bool InLTO, bool SamplePGO) {
Rong Xu6e34c492016-04-27 23:20:27 +0000639 if (DisableICP)
640 return false;
641 InstrProfSymtab Symtab;
642 Symtab.create(M, InLTO);
643 bool Changed = false;
644 for (auto &F : M) {
645 if (F.isDeclaration())
646 continue;
647 if (F.hasFnAttribute(Attribute::OptimizeNone))
648 continue;
Dehao Chencc75d242017-02-23 22:15:18 +0000649 ICallPromotionFunc ICallPromotion(F, &M, &Symtab, SamplePGO);
Rong Xu6e34c492016-04-27 23:20:27 +0000650 bool FuncChanged = ICallPromotion.processFunction();
651 if (ICPDUMPAFTER && FuncChanged) {
652 DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs()));
653 DEBUG(dbgs() << "\n");
654 }
655 Changed |= FuncChanged;
656 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
657 DEBUG(dbgs() << " Stop: Cutoff reached.\n");
658 break;
659 }
660 }
661 return Changed;
662}
663
Xinliang David Li72616182016-05-15 01:04:24 +0000664bool PGOIndirectCallPromotionLegacyPass::runOnModule(Module &M) {
Rong Xu6e34c492016-04-27 23:20:27 +0000665 // Command-line option has the priority for InLTO.
Dehao Chencc75d242017-02-23 22:15:18 +0000666 return promoteIndirectCalls(M, InLTO | ICPLTOMode,
667 SamplePGO | ICPSamplePGOMode);
Rong Xu6e34c492016-04-27 23:20:27 +0000668}
Xinliang David Lif3c7a352016-05-16 16:31:07 +0000669
Dehao Chencc75d242017-02-23 22:15:18 +0000670PreservedAnalyses PGOIndirectCallPromotion::run(Module &M,
671 ModuleAnalysisManager &AM) {
672 if (!promoteIndirectCalls(M, InLTO | ICPLTOMode,
673 SamplePGO | ICPSamplePGOMode))
Xinliang David Lif3c7a352016-05-16 16:31:07 +0000674 return PreservedAnalyses::all();
675
676 return PreservedAnalyses::none();
677}