IndirectCallPromotion.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
  18. #include "llvm/Analysis/IndirectCallVisitor.h"
  19. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  20. #include "llvm/Analysis/ProfileSummaryInfo.h"
  21. #include "llvm/IR/DiagnosticInfo.h"
  22. #include "llvm/IR/Function.h"
  23. #include "llvm/IR/InstrTypes.h"
  24. #include "llvm/IR/Instructions.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/MDBuilder.h"
  27. #include "llvm/IR/PassManager.h"
  28. #include "llvm/IR/Value.h"
  29. #include "llvm/ProfileData/InstrProf.h"
  30. #include "llvm/Support/Casting.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/Error.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Transforms/Instrumentation.h"
  36. #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
  37. #include "llvm/Transforms/Utils/CallPromotionUtils.h"
  38. #include <cassert>
  39. #include <cstdint>
  40. #include <memory>
  41. #include <string>
  42. #include <utility>
  43. #include <vector>
  44. using namespace llvm;
  45. #define DEBUG_TYPE "pgo-icall-prom"
  46. STATISTIC(NumOfPGOICallPromotion, "Number of indirect call promotions.");
  47. STATISTIC(NumOfPGOICallsites, "Number of indirect call candidate sites.");
  48. // Command line option to disable indirect-call promotion with the default as
  49. // false. This is for debug purpose.
  50. static cl::opt<bool> DisableICP("disable-icp", cl::init(false), cl::Hidden,
  51. cl::desc("Disable indirect call promotion"));
  52. // Set the cutoff value for the promotion. If the value is other than 0, we
  53. // stop the transformation once the total number of promotions equals the cutoff
  54. // value.
  55. // For debug use only.
  56. static cl::opt<unsigned>
  57. ICPCutOff("icp-cutoff", cl::init(0), cl::Hidden,
  58. cl::desc("Max number of promotions for this compilation"));
  59. // If ICPCSSkip is non zero, the first ICPCSSkip callsites will be skipped.
  60. // For debug use only.
  61. static cl::opt<unsigned>
  62. ICPCSSkip("icp-csskip", cl::init(0), cl::Hidden,
  63. cl::desc("Skip Callsite up to this number for this compilation"));
  64. // Set if the pass is called in LTO optimization. The difference for LTO mode
  65. // is the pass won't prefix the source module name to the internal linkage
  66. // symbols.
  67. static cl::opt<bool> ICPLTOMode("icp-lto", cl::init(false), cl::Hidden,
  68. cl::desc("Run indirect-call promotion in LTO "
  69. "mode"));
  70. // Set if the pass is called in SamplePGO mode. The difference for SamplePGO
  71. // mode is it will add prof metadatato the created direct call.
  72. static cl::opt<bool>
  73. ICPSamplePGOMode("icp-samplepgo", cl::init(false), cl::Hidden,
  74. cl::desc("Run indirect-call promotion in SamplePGO mode"));
  75. // If the option is set to true, only call instructions will be considered for
  76. // transformation -- invoke instructions will be ignored.
  77. static cl::opt<bool>
  78. ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden,
  79. cl::desc("Run indirect-call promotion for call instructions "
  80. "only"));
  81. // If the option is set to true, only invoke instructions will be considered for
  82. // transformation -- call instructions will be ignored.
  83. static 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. // Dump the function level IR if the transformation happened in this
  88. // function. For debug use only.
  89. static cl::opt<bool>
  90. ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden,
  91. cl::desc("Dump IR after transformation happens"));
  92. namespace {
  93. // The class for main data structure to promote indirect calls to conditional
  94. // direct calls.
  95. class ICallPromotionFunc {
  96. private:
  97. Function &F;
  98. Module *M;
  99. // Symtab that maps indirect call profile values to function names and
  100. // defines.
  101. InstrProfSymtab *Symtab;
  102. bool SamplePGO;
  103. OptimizationRemarkEmitter &ORE;
  104. // A struct that records the direct target and it's call count.
  105. struct PromotionCandidate {
  106. Function *TargetFunction;
  107. uint64_t Count;
  108. PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {}
  109. };
  110. // Check if the indirect-call call site should be promoted. Return the number
  111. // of promotions. Inst is the candidate indirect call, ValueDataRef
  112. // contains the array of value profile data for profiled targets,
  113. // TotalCount is the total profiled count of call executions, and
  114. // NumCandidates is the number of candidate entries in ValueDataRef.
  115. std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(
  116. const CallBase &CB, const ArrayRef<InstrProfValueData> &ValueDataRef,
  117. uint64_t TotalCount, uint32_t NumCandidates);
  118. // Promote a list of targets for one indirect-call callsite. Return
  119. // the number of promotions.
  120. uint32_t tryToPromote(CallBase &CB,
  121. const std::vector<PromotionCandidate> &Candidates,
  122. uint64_t &TotalCount);
  123. public:
  124. ICallPromotionFunc(Function &Func, Module *Modu, InstrProfSymtab *Symtab,
  125. bool SamplePGO, OptimizationRemarkEmitter &ORE)
  126. : F(Func), M(Modu), Symtab(Symtab), SamplePGO(SamplePGO), ORE(ORE) {}
  127. ICallPromotionFunc(const ICallPromotionFunc &) = delete;
  128. ICallPromotionFunc &operator=(const ICallPromotionFunc &) = delete;
  129. bool processFunction(ProfileSummaryInfo *PSI);
  130. };
  131. } // end anonymous namespace
  132. // Indirect-call promotion heuristic. The direct targets are sorted based on
  133. // the count. Stop at the first target that is not promoted.
  134. std::vector<ICallPromotionFunc::PromotionCandidate>
  135. ICallPromotionFunc::getPromotionCandidatesForCallSite(
  136. const CallBase &CB, const ArrayRef<InstrProfValueData> &ValueDataRef,
  137. uint64_t TotalCount, uint32_t NumCandidates) {
  138. std::vector<PromotionCandidate> Ret;
  139. LLVM_DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << CB
  140. << " Num_targets: " << ValueDataRef.size()
  141. << " Num_candidates: " << NumCandidates << "\n");
  142. NumOfPGOICallsites++;
  143. if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) {
  144. LLVM_DEBUG(dbgs() << " Skip: User options.\n");
  145. return Ret;
  146. }
  147. for (uint32_t I = 0; I < NumCandidates; I++) {
  148. uint64_t Count = ValueDataRef[I].Count;
  149. assert(Count <= TotalCount);
  150. (void)TotalCount;
  151. uint64_t Target = ValueDataRef[I].Value;
  152. LLVM_DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
  153. << " Target_func: " << Target << "\n");
  154. if (ICPInvokeOnly && isa<CallInst>(CB)) {
  155. LLVM_DEBUG(dbgs() << " Not promote: User options.\n");
  156. ORE.emit([&]() {
  157. return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB)
  158. << " Not promote: User options";
  159. });
  160. break;
  161. }
  162. if (ICPCallOnly && isa<InvokeInst>(CB)) {
  163. LLVM_DEBUG(dbgs() << " Not promote: User option.\n");
  164. ORE.emit([&]() {
  165. return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB)
  166. << " Not promote: User options";
  167. });
  168. break;
  169. }
  170. if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
  171. LLVM_DEBUG(dbgs() << " Not promote: Cutoff reached.\n");
  172. ORE.emit([&]() {
  173. return OptimizationRemarkMissed(DEBUG_TYPE, "CutOffReached", &CB)
  174. << " Not promote: Cutoff reached";
  175. });
  176. break;
  177. }
  178. // Don't promote if the symbol is not defined in the module. This avoids
  179. // creating a reference to a symbol that doesn't exist in the module
  180. // This can happen when we compile with a sample profile collected from
  181. // one binary but used for another, which may have profiled targets that
  182. // aren't used in the new binary. We might have a declaration initially in
  183. // the case where the symbol is globally dead in the binary and removed by
  184. // ThinLTO.
  185. Function *TargetFunction = Symtab->getFunction(Target);
  186. if (TargetFunction == nullptr || TargetFunction->isDeclaration()) {
  187. LLVM_DEBUG(dbgs() << " Not promote: Cannot find the target\n");
  188. ORE.emit([&]() {
  189. return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToFindTarget", &CB)
  190. << "Cannot promote indirect call: target with md5sum "
  191. << ore::NV("target md5sum", Target) << " not found";
  192. });
  193. break;
  194. }
  195. const char *Reason = nullptr;
  196. if (!isLegalToPromote(CB, TargetFunction, &Reason)) {
  197. using namespace ore;
  198. ORE.emit([&]() {
  199. return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToPromote", &CB)
  200. << "Cannot promote indirect call to "
  201. << NV("TargetFunction", TargetFunction) << " with count of "
  202. << NV("Count", Count) << ": " << Reason;
  203. });
  204. break;
  205. }
  206. Ret.push_back(PromotionCandidate(TargetFunction, Count));
  207. TotalCount -= Count;
  208. }
  209. return Ret;
  210. }
  211. CallBase &llvm::pgo::promoteIndirectCall(CallBase &CB, Function *DirectCallee,
  212. uint64_t Count, uint64_t TotalCount,
  213. bool AttachProfToDirectCall,
  214. OptimizationRemarkEmitter *ORE) {
  215. uint64_t ElseCount = TotalCount - Count;
  216. uint64_t MaxCount = (Count >= ElseCount ? Count : ElseCount);
  217. uint64_t Scale = calculateCountScale(MaxCount);
  218. MDBuilder MDB(CB.getContext());
  219. MDNode *BranchWeights = MDB.createBranchWeights(
  220. scaleBranchCount(Count, Scale), scaleBranchCount(ElseCount, Scale));
  221. CallBase &NewInst =
  222. promoteCallWithIfThenElse(CB, DirectCallee, BranchWeights);
  223. if (AttachProfToDirectCall) {
  224. MDBuilder MDB(NewInst.getContext());
  225. NewInst.setMetadata(
  226. LLVMContext::MD_prof,
  227. MDB.createBranchWeights({static_cast<uint32_t>(Count)}));
  228. }
  229. using namespace ore;
  230. if (ORE)
  231. ORE->emit([&]() {
  232. return OptimizationRemark(DEBUG_TYPE, "Promoted", &CB)
  233. << "Promote indirect call to " << NV("DirectCallee", DirectCallee)
  234. << " with count " << NV("Count", Count) << " out of "
  235. << NV("TotalCount", TotalCount);
  236. });
  237. return NewInst;
  238. }
  239. // Promote indirect-call to conditional direct-call for one callsite.
  240. uint32_t ICallPromotionFunc::tryToPromote(
  241. CallBase &CB, const std::vector<PromotionCandidate> &Candidates,
  242. uint64_t &TotalCount) {
  243. uint32_t NumPromoted = 0;
  244. for (const auto &C : Candidates) {
  245. uint64_t Count = C.Count;
  246. pgo::promoteIndirectCall(CB, C.TargetFunction, Count, TotalCount, SamplePGO,
  247. &ORE);
  248. assert(TotalCount >= Count);
  249. TotalCount -= Count;
  250. NumOfPGOICallPromotion++;
  251. NumPromoted++;
  252. }
  253. return NumPromoted;
  254. }
  255. // Traverse all the indirect-call callsite and get the value profile
  256. // annotation to perform indirect-call promotion.
  257. bool ICallPromotionFunc::processFunction(ProfileSummaryInfo *PSI) {
  258. bool Changed = false;
  259. ICallPromotionAnalysis ICallAnalysis;
  260. for (auto *CB : findIndirectCalls(F)) {
  261. uint32_t NumVals, NumCandidates;
  262. uint64_t TotalCount;
  263. auto ICallProfDataRef = ICallAnalysis.getPromotionCandidatesForInstruction(
  264. CB, NumVals, TotalCount, NumCandidates);
  265. if (!NumCandidates ||
  266. (PSI && PSI->hasProfileSummary() && !PSI->isHotCount(TotalCount)))
  267. continue;
  268. auto PromotionCandidates = getPromotionCandidatesForCallSite(
  269. *CB, ICallProfDataRef, TotalCount, NumCandidates);
  270. uint32_t NumPromoted = tryToPromote(*CB, PromotionCandidates, TotalCount);
  271. if (NumPromoted == 0)
  272. continue;
  273. Changed = true;
  274. // Adjust the MD.prof metadata. First delete the old one.
  275. CB->setMetadata(LLVMContext::MD_prof, nullptr);
  276. // If all promoted, we don't need the MD.prof metadata.
  277. if (TotalCount == 0 || NumPromoted == NumVals)
  278. continue;
  279. // Otherwise we need update with the un-promoted records back.
  280. annotateValueSite(*M, *CB, ICallProfDataRef.slice(NumPromoted), TotalCount,
  281. IPVK_IndirectCallTarget, NumCandidates);
  282. }
  283. return Changed;
  284. }
  285. // A wrapper function that does the actual work.
  286. static bool promoteIndirectCalls(Module &M, ProfileSummaryInfo *PSI,
  287. bool InLTO, bool SamplePGO,
  288. ModuleAnalysisManager *AM = nullptr) {
  289. if (DisableICP)
  290. return false;
  291. InstrProfSymtab Symtab;
  292. if (Error E = Symtab.create(M, InLTO)) {
  293. std::string SymtabFailure = toString(std::move(E));
  294. M.getContext().emitError("Failed to create symtab: " + SymtabFailure);
  295. return false;
  296. }
  297. bool Changed = false;
  298. for (auto &F : M) {
  299. if (F.isDeclaration() || F.hasOptNone())
  300. continue;
  301. std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
  302. OptimizationRemarkEmitter *ORE;
  303. if (AM) {
  304. auto &FAM =
  305. AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  306. ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  307. } else {
  308. OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
  309. ORE = OwnedORE.get();
  310. }
  311. ICallPromotionFunc ICallPromotion(F, &M, &Symtab, SamplePGO, *ORE);
  312. bool FuncChanged = ICallPromotion.processFunction(PSI);
  313. if (ICPDUMPAFTER && FuncChanged) {
  314. LLVM_DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs()));
  315. LLVM_DEBUG(dbgs() << "\n");
  316. }
  317. Changed |= FuncChanged;
  318. if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
  319. LLVM_DEBUG(dbgs() << " Stop: Cutoff reached.\n");
  320. break;
  321. }
  322. }
  323. return Changed;
  324. }
  325. PreservedAnalyses PGOIndirectCallPromotion::run(Module &M,
  326. ModuleAnalysisManager &AM) {
  327. ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
  328. if (!promoteIndirectCalls(M, PSI, InLTO | ICPLTOMode,
  329. SamplePGO | ICPSamplePGOMode, &AM))
  330. return PreservedAnalyses::all();
  331. return PreservedAnalyses::none();
  332. }