IndirectCallPromotion.cpp 17 KB

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