InlineCost.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. //===- InlineCost.h - Cost analysis for inliner -----------------*- C++ -*-===//
  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 heuristics for inlining decisions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_ANALYSIS_INLINECOST_H
  13. #define LLVM_ANALYSIS_INLINECOST_H
  14. #include "llvm/Analysis/AssumptionCache.h"
  15. #include "llvm/Analysis/CallGraphSCCPass.h"
  16. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  17. #include <cassert>
  18. #include <climits>
  19. namespace llvm {
  20. class AssumptionCacheTracker;
  21. class BlockFrequencyInfo;
  22. class CallBase;
  23. class DataLayout;
  24. class Function;
  25. class ProfileSummaryInfo;
  26. class TargetTransformInfo;
  27. class TargetLibraryInfo;
  28. namespace InlineConstants {
  29. // Various thresholds used by inline cost analysis.
  30. /// Use when optsize (-Os) is specified.
  31. const int OptSizeThreshold = 50;
  32. /// Use when minsize (-Oz) is specified.
  33. const int OptMinSizeThreshold = 5;
  34. /// Use when -O3 is specified.
  35. const int OptAggressiveThreshold = 250;
  36. // Various magic constants used to adjust heuristics.
  37. const int InstrCost = 5;
  38. const int IndirectCallThreshold = 100;
  39. const int CallPenalty = 25;
  40. const int LastCallToStaticBonus = 15000;
  41. const int ColdccPenalty = 2000;
  42. /// Do not inline functions which allocate this many bytes on the stack
  43. /// when the caller is recursive.
  44. const unsigned TotalAllocaSizeRecursiveCaller = 1024;
  45. /// Do not inline dynamic allocas that have been constant propagated to be
  46. /// static allocas above this amount in bytes.
  47. const uint64_t MaxSimplifiedDynamicAllocaToInline = 65536;
  48. } // namespace InlineConstants
  49. /// Represents the cost of inlining a function.
  50. ///
  51. /// This supports special values for functions which should "always" or
  52. /// "never" be inlined. Otherwise, the cost represents a unitless amount;
  53. /// smaller values increase the likelihood of the function being inlined.
  54. ///
  55. /// Objects of this type also provide the adjusted threshold for inlining
  56. /// based on the information available for a particular callsite. They can be
  57. /// directly tested to determine if inlining should occur given the cost and
  58. /// threshold for this cost metric.
  59. class InlineCost {
  60. enum SentinelValues { AlwaysInlineCost = INT_MIN, NeverInlineCost = INT_MAX };
  61. /// The estimated cost of inlining this callsite.
  62. int Cost = 0;
  63. /// The adjusted threshold against which this cost was computed.
  64. int Threshold = 0;
  65. /// Must be set for Always and Never instances.
  66. const char *Reason = nullptr;
  67. // Trivial constructor, interesting logic in the factory functions below.
  68. InlineCost(int Cost, int Threshold, const char *Reason = nullptr)
  69. : Cost(Cost), Threshold(Threshold), Reason(Reason) {
  70. assert((isVariable() || Reason) &&
  71. "Reason must be provided for Never or Always");
  72. }
  73. public:
  74. static InlineCost get(int Cost, int Threshold) {
  75. assert(Cost > AlwaysInlineCost && "Cost crosses sentinel value");
  76. assert(Cost < NeverInlineCost && "Cost crosses sentinel value");
  77. return InlineCost(Cost, Threshold);
  78. }
  79. static InlineCost getAlways(const char *Reason) {
  80. return InlineCost(AlwaysInlineCost, 0, Reason);
  81. }
  82. static InlineCost getNever(const char *Reason) {
  83. return InlineCost(NeverInlineCost, 0, Reason);
  84. }
  85. /// Test whether the inline cost is low enough for inlining.
  86. explicit operator bool() const { return Cost < Threshold; }
  87. bool isAlways() const { return Cost == AlwaysInlineCost; }
  88. bool isNever() const { return Cost == NeverInlineCost; }
  89. bool isVariable() const { return !isAlways() && !isNever(); }
  90. /// Get the inline cost estimate.
  91. /// It is an error to call this on an "always" or "never" InlineCost.
  92. int getCost() const {
  93. assert(isVariable() && "Invalid access of InlineCost");
  94. return Cost;
  95. }
  96. /// Get the threshold against which the cost was computed
  97. int getThreshold() const {
  98. assert(isVariable() && "Invalid access of InlineCost");
  99. return Threshold;
  100. }
  101. /// Get the reason of Always or Never.
  102. const char *getReason() const {
  103. assert((Reason || isVariable()) &&
  104. "InlineCost reason must be set for Always or Never");
  105. return Reason;
  106. }
  107. /// Get the cost delta from the threshold for inlining.
  108. /// Only valid if the cost is of the variable kind. Returns a negative
  109. /// value if the cost is too high to inline.
  110. int getCostDelta() const { return Threshold - getCost(); }
  111. };
  112. /// InlineResult is basically true or false. For false results the message
  113. /// describes a reason.
  114. class InlineResult {
  115. const char *Message = nullptr;
  116. InlineResult(const char *Message = nullptr) : Message(Message) {}
  117. public:
  118. static InlineResult success() { return {}; }
  119. static InlineResult failure(const char *Reason) {
  120. return InlineResult(Reason);
  121. }
  122. bool isSuccess() const { return Message == nullptr; }
  123. const char *getFailureReason() const {
  124. assert(!isSuccess() &&
  125. "getFailureReason should only be called in failure cases");
  126. return Message;
  127. }
  128. };
  129. /// Thresholds to tune inline cost analysis. The inline cost analysis decides
  130. /// the condition to apply a threshold and applies it. Otherwise,
  131. /// DefaultThreshold is used. If a threshold is Optional, it is applied only
  132. /// when it has a valid value. Typically, users of inline cost analysis
  133. /// obtain an InlineParams object through one of the \c getInlineParams methods
  134. /// and pass it to \c getInlineCost. Some specialized versions of inliner
  135. /// (such as the pre-inliner) might have custom logic to compute \c InlineParams
  136. /// object.
  137. struct InlineParams {
  138. /// The default threshold to start with for a callee.
  139. int DefaultThreshold = -1;
  140. /// Threshold to use for callees with inline hint.
  141. Optional<int> HintThreshold;
  142. /// Threshold to use for cold callees.
  143. Optional<int> ColdThreshold;
  144. /// Threshold to use when the caller is optimized for size.
  145. Optional<int> OptSizeThreshold;
  146. /// Threshold to use when the caller is optimized for minsize.
  147. Optional<int> OptMinSizeThreshold;
  148. /// Threshold to use when the callsite is considered hot.
  149. Optional<int> HotCallSiteThreshold;
  150. /// Threshold to use when the callsite is considered hot relative to function
  151. /// entry.
  152. Optional<int> LocallyHotCallSiteThreshold;
  153. /// Threshold to use when the callsite is considered cold.
  154. Optional<int> ColdCallSiteThreshold;
  155. /// Compute inline cost even when the cost has exceeded the threshold.
  156. Optional<bool> ComputeFullInlineCost;
  157. /// Indicate whether we should allow inline deferral.
  158. Optional<bool> EnableDeferral = true;
  159. };
  160. /// Generate the parameters to tune the inline cost analysis based only on the
  161. /// commandline options.
  162. InlineParams getInlineParams();
  163. /// Generate the parameters to tune the inline cost analysis based on command
  164. /// line options. If -inline-threshold option is not explicitly passed,
  165. /// \p Threshold is used as the default threshold.
  166. InlineParams getInlineParams(int Threshold);
  167. /// Generate the parameters to tune the inline cost analysis based on command
  168. /// line options. If -inline-threshold option is not explicitly passed,
  169. /// the default threshold is computed from \p OptLevel and \p SizeOptLevel.
  170. /// An \p OptLevel value above 3 is considered an aggressive optimization mode.
  171. /// \p SizeOptLevel of 1 corresponds to the -Os flag and 2 corresponds to
  172. /// the -Oz flag.
  173. InlineParams getInlineParams(unsigned OptLevel, unsigned SizeOptLevel);
  174. /// Return the cost associated with a callsite, including parameter passing
  175. /// and the call/return instruction.
  176. int getCallsiteCost(CallBase &Call, const DataLayout &DL);
  177. /// Get an InlineCost object representing the cost of inlining this
  178. /// callsite.
  179. ///
  180. /// Note that a default threshold is passed into this function. This threshold
  181. /// could be modified based on callsite's properties and only costs below this
  182. /// new threshold are computed with any accuracy. The new threshold can be
  183. /// used to bound the computation necessary to determine whether the cost is
  184. /// sufficiently low to warrant inlining.
  185. ///
  186. /// Also note that calling this function *dynamically* computes the cost of
  187. /// inlining the callsite. It is an expensive, heavyweight call.
  188. InlineCost
  189. getInlineCost(CallBase &Call, const InlineParams &Params,
  190. TargetTransformInfo &CalleeTTI,
  191. function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
  192. function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
  193. function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
  194. ProfileSummaryInfo *PSI = nullptr,
  195. OptimizationRemarkEmitter *ORE = nullptr);
  196. /// Get an InlineCost with the callee explicitly specified.
  197. /// This allows you to calculate the cost of inlining a function via a
  198. /// pointer. This behaves exactly as the version with no explicit callee
  199. /// parameter in all other respects.
  200. //
  201. InlineCost
  202. getInlineCost(CallBase &Call, Function *Callee, const InlineParams &Params,
  203. TargetTransformInfo &CalleeTTI,
  204. function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
  205. function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
  206. function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
  207. ProfileSummaryInfo *PSI = nullptr,
  208. OptimizationRemarkEmitter *ORE = nullptr);
  209. /// Returns InlineResult::success() if the call site should be always inlined
  210. /// because of user directives, and the inlining is viable. Returns
  211. /// InlineResult::failure() if the inlining may never happen because of user
  212. /// directives or incompatibilities detectable without needing callee traversal.
  213. /// Otherwise returns None, meaning that inlining should be decided based on
  214. /// other criteria (e.g. cost modeling).
  215. Optional<InlineResult> getAttributeBasedInliningDecision(
  216. CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
  217. function_ref<const TargetLibraryInfo &(Function &)> GetTLI);
  218. /// Get the cost estimate ignoring thresholds. This is similar to getInlineCost
  219. /// when passed InlineParams::ComputeFullInlineCost, or a non-null ORE. It
  220. /// uses default InlineParams otherwise.
  221. /// Contrary to getInlineCost, which makes a threshold-based final evaluation of
  222. /// should/shouldn't inline, captured in InlineResult, getInliningCostEstimate
  223. /// returns:
  224. /// - None, if the inlining cannot happen (is illegal)
  225. /// - an integer, representing the cost.
  226. Optional<int> getInliningCostEstimate(
  227. CallBase &Call, TargetTransformInfo &CalleeTTI,
  228. function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
  229. function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
  230. ProfileSummaryInfo *PSI = nullptr,
  231. OptimizationRemarkEmitter *ORE = nullptr);
  232. /// Minimal filter to detect invalid constructs for inlining.
  233. InlineResult isInlineViable(Function &Callee);
  234. // This pass is used to annotate instructions during the inline process for
  235. // debugging and analysis. The main purpose of the pass is to see and test
  236. // inliner's decisions when creating new optimizations to InlineCost.
  237. struct InlineCostAnnotationPrinterPass
  238. : PassInfoMixin<InlineCostAnnotationPrinterPass> {
  239. raw_ostream &OS;
  240. public:
  241. explicit InlineCostAnnotationPrinterPass(raw_ostream &OS) : OS(OS) {}
  242. PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
  243. };
  244. } // namespace llvm
  245. #endif