1 //===- IndirectCallPromotion.cpp - Optimizations based on value profiling -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the transformation that promotes indirect calls to
10 // conditional direct calls when the indirect-call value profile metadata is
11 // available.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
19 #include "llvm/Analysis/IndirectCallVisitor.h"
20 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
21 #include "llvm/Analysis/ProfileSummaryInfo.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/InstrTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/MDBuilder.h"
28 #include "llvm/IR/PassManager.h"
29 #include "llvm/IR/Value.h"
30 #include "llvm/InitializePasses.h"
31 #include "llvm/Pass.h"
32 #include "llvm/ProfileData/InstrProf.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Error.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Instrumentation.h"
39 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
40 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
41 #include <cassert>
42 #include <cstdint>
43 #include <memory>
44 #include <string>
45 #include <utility>
46 #include <vector>
47 
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "pgo-icall-prom"
51 
52 STATISTIC(NumOfPGOICallPromotion, "Number of indirect call promotions.");
53 STATISTIC(NumOfPGOICallsites, "Number of indirect call candidate sites.");
54 
55 // Command line option to disable indirect-call promotion with the default as
56 // false. This is for debug purpose.
57 static cl::opt<bool> DisableICP("disable-icp", cl::init(false), cl::Hidden,
58                                 cl::desc("Disable indirect call promotion"));
59 
60 // Set the cutoff value for the promotion. If the value is other than 0, we
61 // stop the transformation once the total number of promotions equals the cutoff
62 // value.
63 // For debug use only.
64 static cl::opt<unsigned>
65     ICPCutOff("icp-cutoff", cl::init(0), cl::Hidden, cl::ZeroOrMore,
66               cl::desc("Max number of promotions for this compilation"));
67 
68 // If ICPCSSkip is non zero, the first ICPCSSkip callsites will be skipped.
69 // For debug use only.
70 static cl::opt<unsigned>
71     ICPCSSkip("icp-csskip", cl::init(0), cl::Hidden, cl::ZeroOrMore,
72               cl::desc("Skip Callsite up to this number for this compilation"));
73 
74 // Set if the pass is called in LTO optimization. The difference for LTO mode
75 // is the pass won't prefix the source module name to the internal linkage
76 // symbols.
77 static cl::opt<bool> ICPLTOMode("icp-lto", cl::init(false), cl::Hidden,
78                                 cl::desc("Run indirect-call promotion in LTO "
79                                          "mode"));
80 
81 // Set if the pass is called in SamplePGO mode. The difference for SamplePGO
82 // mode is it will add prof metadatato the created direct call.
83 static cl::opt<bool>
84     ICPSamplePGOMode("icp-samplepgo", cl::init(false), cl::Hidden,
85                      cl::desc("Run indirect-call promotion in SamplePGO mode"));
86 
87 // If the option is set to true, only call instructions will be considered for
88 // transformation -- invoke instructions will be ignored.
89 static cl::opt<bool>
90     ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden,
91                 cl::desc("Run indirect-call promotion for call instructions "
92                          "only"));
93 
94 // If the option is set to true, only invoke instructions will be considered for
95 // transformation -- call instructions will be ignored.
96 static cl::opt<bool> ICPInvokeOnly("icp-invoke-only", cl::init(false),
97                                    cl::Hidden,
98                                    cl::desc("Run indirect-call promotion for "
99                                             "invoke instruction only"));
100 
101 // Dump the function level IR if the transformation happened in this
102 // function. For debug use only.
103 static cl::opt<bool>
104     ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden,
105                  cl::desc("Dump IR after transformation happens"));
106 
107 namespace {
108 
109 class PGOIndirectCallPromotionLegacyPass : public ModulePass {
110 public:
111   static char ID;
112 
113   PGOIndirectCallPromotionLegacyPass(bool InLTO = false, bool SamplePGO = false)
114       : ModulePass(ID), InLTO(InLTO), SamplePGO(SamplePGO) {
115     initializePGOIndirectCallPromotionLegacyPassPass(
116         *PassRegistry::getPassRegistry());
117   }
118 
119   void getAnalysisUsage(AnalysisUsage &AU) const override {
120     AU.addRequired<ProfileSummaryInfoWrapperPass>();
121   }
122 
123   StringRef getPassName() const override { return "PGOIndirectCallPromotion"; }
124 
125 private:
126   bool runOnModule(Module &M) override;
127 
128   // If this pass is called in LTO. We need to special handling the PGOFuncName
129   // for the static variables due to LTO's internalization.
130   bool InLTO;
131 
132   // If this pass is called in SamplePGO. We need to add the prof metadata to
133   // the promoted direct call.
134   bool SamplePGO;
135 };
136 
137 } // end anonymous namespace
138 
139 char PGOIndirectCallPromotionLegacyPass::ID = 0;
140 
141 INITIALIZE_PASS_BEGIN(PGOIndirectCallPromotionLegacyPass, "pgo-icall-prom",
142                       "Use PGO instrumentation profile to promote indirect "
143                       "calls to direct calls.",
144                       false, false)
145 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
146 INITIALIZE_PASS_END(PGOIndirectCallPromotionLegacyPass, "pgo-icall-prom",
147                     "Use PGO instrumentation profile to promote indirect "
148                     "calls to direct calls.",
149                     false, false)
150 
151 ModulePass *llvm::createPGOIndirectCallPromotionLegacyPass(bool InLTO,
152                                                            bool SamplePGO) {
153   return new PGOIndirectCallPromotionLegacyPass(InLTO, SamplePGO);
154 }
155 
156 namespace {
157 
158 // The class for main data structure to promote indirect calls to conditional
159 // direct calls.
160 class ICallPromotionFunc {
161 private:
162   Function &F;
163   Module *M;
164 
165   // Symtab that maps indirect call profile values to function names and
166   // defines.
167   InstrProfSymtab *Symtab;
168 
169   bool SamplePGO;
170 
171   OptimizationRemarkEmitter &ORE;
172 
173   // A struct that records the direct target and it's call count.
174   struct PromotionCandidate {
175     Function *TargetFunction;
176     uint64_t Count;
177 
178     PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {}
179   };
180 
181   // Check if the indirect-call call site should be promoted. Return the number
182   // of promotions. Inst is the candidate indirect call, ValueDataRef
183   // contains the array of value profile data for profiled targets,
184   // TotalCount is the total profiled count of call executions, and
185   // NumCandidates is the number of candidate entries in ValueDataRef.
186   std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(
187       const CallBase &CB, const ArrayRef<InstrProfValueData> &ValueDataRef,
188       uint64_t TotalCount, uint32_t NumCandidates);
189 
190   // Promote a list of targets for one indirect-call callsite. Return
191   // the number of promotions.
192   uint32_t tryToPromote(CallBase &CB,
193                         const std::vector<PromotionCandidate> &Candidates,
194                         uint64_t &TotalCount);
195 
196 public:
197   ICallPromotionFunc(Function &Func, Module *Modu, InstrProfSymtab *Symtab,
198                      bool SamplePGO, OptimizationRemarkEmitter &ORE)
199       : F(Func), M(Modu), Symtab(Symtab), SamplePGO(SamplePGO), ORE(ORE) {}
200   ICallPromotionFunc(const ICallPromotionFunc &) = delete;
201   ICallPromotionFunc &operator=(const ICallPromotionFunc &) = delete;
202 
203   bool processFunction(ProfileSummaryInfo *PSI);
204 };
205 
206 } // end anonymous namespace
207 
208 // Indirect-call promotion heuristic. The direct targets are sorted based on
209 // the count. Stop at the first target that is not promoted.
210 std::vector<ICallPromotionFunc::PromotionCandidate>
211 ICallPromotionFunc::getPromotionCandidatesForCallSite(
212     const CallBase &CB, const ArrayRef<InstrProfValueData> &ValueDataRef,
213     uint64_t TotalCount, uint32_t NumCandidates) {
214   std::vector<PromotionCandidate> Ret;
215 
216   LLVM_DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << CB
217                     << " Num_targets: " << ValueDataRef.size()
218                     << " Num_candidates: " << NumCandidates << "\n");
219   NumOfPGOICallsites++;
220   if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) {
221     LLVM_DEBUG(dbgs() << " Skip: User options.\n");
222     return Ret;
223   }
224 
225   for (uint32_t I = 0; I < NumCandidates; I++) {
226     uint64_t Count = ValueDataRef[I].Count;
227     assert(Count <= TotalCount);
228     (void)TotalCount;
229     uint64_t Target = ValueDataRef[I].Value;
230     LLVM_DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
231                       << "  Target_func: " << Target << "\n");
232 
233     if (ICPInvokeOnly && isa<CallInst>(CB)) {
234       LLVM_DEBUG(dbgs() << " Not promote: User options.\n");
235       ORE.emit([&]() {
236         return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB)
237                << " Not promote: User options";
238       });
239       break;
240     }
241     if (ICPCallOnly && isa<InvokeInst>(CB)) {
242       LLVM_DEBUG(dbgs() << " Not promote: User option.\n");
243       ORE.emit([&]() {
244         return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB)
245                << " Not promote: User options";
246       });
247       break;
248     }
249     if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
250       LLVM_DEBUG(dbgs() << " Not promote: Cutoff reached.\n");
251       ORE.emit([&]() {
252         return OptimizationRemarkMissed(DEBUG_TYPE, "CutOffReached", &CB)
253                << " Not promote: Cutoff reached";
254       });
255       break;
256     }
257 
258     // Don't promote if the symbol is not defined in the module. This avoids
259     // creating a reference to a symbol that doesn't exist in the module
260     // This can happen when we compile with a sample profile collected from
261     // one binary but used for another, which may have profiled targets that
262     // aren't used in the new binary. We might have a declaration initially in
263     // the case where the symbol is globally dead in the binary and removed by
264     // ThinLTO.
265     Function *TargetFunction = Symtab->getFunction(Target);
266     if (TargetFunction == nullptr || TargetFunction->isDeclaration()) {
267       LLVM_DEBUG(dbgs() << " Not promote: Cannot find the target\n");
268       ORE.emit([&]() {
269         return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToFindTarget", &CB)
270                << "Cannot promote indirect call: target with md5sum "
271                << ore::NV("target md5sum", Target) << " not found";
272       });
273       break;
274     }
275 
276     const char *Reason = nullptr;
277     if (!isLegalToPromote(CB, TargetFunction, &Reason)) {
278       using namespace ore;
279 
280       ORE.emit([&]() {
281         return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToPromote", &CB)
282                << "Cannot promote indirect call to "
283                << NV("TargetFunction", TargetFunction) << " with count of "
284                << NV("Count", Count) << ": " << Reason;
285       });
286       break;
287     }
288 
289     Ret.push_back(PromotionCandidate(TargetFunction, Count));
290     TotalCount -= Count;
291   }
292   return Ret;
293 }
294 
295 CallBase &llvm::pgo::promoteIndirectCall(CallBase &CB, Function *DirectCallee,
296                                          uint64_t Count, uint64_t TotalCount,
297                                          bool AttachProfToDirectCall,
298                                          OptimizationRemarkEmitter *ORE) {
299 
300   uint64_t ElseCount = TotalCount - Count;
301   uint64_t MaxCount = (Count >= ElseCount ? Count : ElseCount);
302   uint64_t Scale = calculateCountScale(MaxCount);
303   MDBuilder MDB(CB.getContext());
304   MDNode *BranchWeights = MDB.createBranchWeights(
305       scaleBranchCount(Count, Scale), scaleBranchCount(ElseCount, Scale));
306 
307   CallBase &NewInst =
308       promoteCallWithIfThenElse(CB, DirectCallee, BranchWeights);
309 
310   if (AttachProfToDirectCall) {
311     MDBuilder MDB(NewInst.getContext());
312     NewInst.setMetadata(
313         LLVMContext::MD_prof,
314         MDB.createBranchWeights({static_cast<uint32_t>(Count)}));
315   }
316 
317   using namespace ore;
318 
319   if (ORE)
320     ORE->emit([&]() {
321       return OptimizationRemark(DEBUG_TYPE, "Promoted", &CB)
322              << "Promote indirect call to " << NV("DirectCallee", DirectCallee)
323              << " with count " << NV("Count", Count) << " out of "
324              << NV("TotalCount", TotalCount);
325     });
326   return NewInst;
327 }
328 
329 // Promote indirect-call to conditional direct-call for one callsite.
330 uint32_t ICallPromotionFunc::tryToPromote(
331     CallBase &CB, const std::vector<PromotionCandidate> &Candidates,
332     uint64_t &TotalCount) {
333   uint32_t NumPromoted = 0;
334 
335   for (auto &C : Candidates) {
336     uint64_t Count = C.Count;
337     pgo::promoteIndirectCall(CB, C.TargetFunction, Count, TotalCount, SamplePGO,
338                              &ORE);
339     assert(TotalCount >= Count);
340     TotalCount -= Count;
341     NumOfPGOICallPromotion++;
342     NumPromoted++;
343   }
344   return NumPromoted;
345 }
346 
347 // Traverse all the indirect-call callsite and get the value profile
348 // annotation to perform indirect-call promotion.
349 bool ICallPromotionFunc::processFunction(ProfileSummaryInfo *PSI) {
350   bool Changed = false;
351   ICallPromotionAnalysis ICallAnalysis;
352   for (auto *CB : findIndirectCalls(F)) {
353     uint32_t NumVals, NumCandidates;
354     uint64_t TotalCount;
355     auto ICallProfDataRef = ICallAnalysis.getPromotionCandidatesForInstruction(
356         CB, NumVals, TotalCount, NumCandidates);
357     if (!NumCandidates ||
358         (PSI && PSI->hasProfileSummary() && !PSI->isHotCount(TotalCount)))
359       continue;
360     auto PromotionCandidates = getPromotionCandidatesForCallSite(
361         *CB, ICallProfDataRef, TotalCount, NumCandidates);
362     uint32_t NumPromoted = tryToPromote(*CB, PromotionCandidates, TotalCount);
363     if (NumPromoted == 0)
364       continue;
365 
366     Changed = true;
367     // Adjust the MD.prof metadata. First delete the old one.
368     CB->setMetadata(LLVMContext::MD_prof, nullptr);
369     // If all promoted, we don't need the MD.prof metadata.
370     if (TotalCount == 0 || NumPromoted == NumVals)
371       continue;
372     // Otherwise we need update with the un-promoted records back.
373     annotateValueSite(*M, *CB, ICallProfDataRef.slice(NumPromoted), TotalCount,
374                       IPVK_IndirectCallTarget, NumCandidates);
375   }
376   return Changed;
377 }
378 
379 // A wrapper function that does the actual work.
380 static bool promoteIndirectCalls(Module &M, ProfileSummaryInfo *PSI,
381                                  bool InLTO, bool SamplePGO,
382                                  ModuleAnalysisManager *AM = nullptr) {
383   if (DisableICP)
384     return false;
385   InstrProfSymtab Symtab;
386   if (Error E = Symtab.create(M, InLTO)) {
387     std::string SymtabFailure = toString(std::move(E));
388     M.getContext().emitError("Failed to create symtab: " + SymtabFailure);
389     return false;
390   }
391   bool Changed = false;
392   for (auto &F : M) {
393     if (F.isDeclaration() || F.hasOptNone())
394       continue;
395 
396     std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
397     OptimizationRemarkEmitter *ORE;
398     if (AM) {
399       auto &FAM =
400           AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
401       ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
402     } else {
403       OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
404       ORE = OwnedORE.get();
405     }
406 
407     ICallPromotionFunc ICallPromotion(F, &M, &Symtab, SamplePGO, *ORE);
408     bool FuncChanged = ICallPromotion.processFunction(PSI);
409     if (ICPDUMPAFTER && FuncChanged) {
410       LLVM_DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs()));
411       LLVM_DEBUG(dbgs() << "\n");
412     }
413     Changed |= FuncChanged;
414     if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
415       LLVM_DEBUG(dbgs() << " Stop: Cutoff reached.\n");
416       break;
417     }
418   }
419   return Changed;
420 }
421 
422 bool PGOIndirectCallPromotionLegacyPass::runOnModule(Module &M) {
423   ProfileSummaryInfo *PSI =
424       &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
425 
426   // Command-line option has the priority for InLTO.
427   return promoteIndirectCalls(M, PSI, InLTO | ICPLTOMode,
428                               SamplePGO | ICPSamplePGOMode);
429 }
430 
431 PreservedAnalyses PGOIndirectCallPromotion::run(Module &M,
432                                                 ModuleAnalysisManager &AM) {
433   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
434 
435   if (!promoteIndirectCalls(M, PSI, InLTO | ICPLTOMode,
436                             SamplePGO | ICPSamplePGOMode, &AM))
437     return PreservedAnalyses::all();
438 
439   return PreservedAnalyses::none();
440 }
441