SampleProfile.cpp 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  1. //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
  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 SampleProfileLoader transformation. This pass
  10. // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
  11. // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
  12. // profile information in the given profile.
  13. //
  14. // This pass generates branch weight annotations on the IR:
  15. //
  16. // - prof: Represents branch weights. This annotation is added to branches
  17. // to indicate the weights of each edge coming out of the branch.
  18. // The weight of each edge is the weight of the target block for
  19. // that edge. The weight of a block B is computed as the maximum
  20. // number of samples found in B.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/Transforms/IPO/SampleProfile.h"
  24. #include "llvm/ADT/ArrayRef.h"
  25. #include "llvm/ADT/DenseMap.h"
  26. #include "llvm/ADT/DenseSet.h"
  27. #include "llvm/ADT/MapVector.h"
  28. #include "llvm/ADT/PriorityQueue.h"
  29. #include "llvm/ADT/SCCIterator.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/Statistic.h"
  32. #include "llvm/ADT/StringMap.h"
  33. #include "llvm/ADT/StringRef.h"
  34. #include "llvm/ADT/Twine.h"
  35. #include "llvm/Analysis/AssumptionCache.h"
  36. #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
  37. #include "llvm/Analysis/CallGraph.h"
  38. #include "llvm/Analysis/InlineAdvisor.h"
  39. #include "llvm/Analysis/InlineCost.h"
  40. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  41. #include "llvm/Analysis/ProfileSummaryInfo.h"
  42. #include "llvm/Analysis/ReplayInlineAdvisor.h"
  43. #include "llvm/Analysis/TargetLibraryInfo.h"
  44. #include "llvm/Analysis/TargetTransformInfo.h"
  45. #include "llvm/IR/BasicBlock.h"
  46. #include "llvm/IR/DebugLoc.h"
  47. #include "llvm/IR/DiagnosticInfo.h"
  48. #include "llvm/IR/Function.h"
  49. #include "llvm/IR/GlobalValue.h"
  50. #include "llvm/IR/InstrTypes.h"
  51. #include "llvm/IR/Instruction.h"
  52. #include "llvm/IR/Instructions.h"
  53. #include "llvm/IR/IntrinsicInst.h"
  54. #include "llvm/IR/LLVMContext.h"
  55. #include "llvm/IR/MDBuilder.h"
  56. #include "llvm/IR/Module.h"
  57. #include "llvm/IR/PassManager.h"
  58. #include "llvm/IR/PseudoProbe.h"
  59. #include "llvm/IR/ValueSymbolTable.h"
  60. #include "llvm/InitializePasses.h"
  61. #include "llvm/Pass.h"
  62. #include "llvm/ProfileData/InstrProf.h"
  63. #include "llvm/ProfileData/SampleProf.h"
  64. #include "llvm/ProfileData/SampleProfReader.h"
  65. #include "llvm/Support/Casting.h"
  66. #include "llvm/Support/CommandLine.h"
  67. #include "llvm/Support/Debug.h"
  68. #include "llvm/Support/ErrorOr.h"
  69. #include "llvm/Support/raw_ostream.h"
  70. #include "llvm/Transforms/IPO.h"
  71. #include "llvm/Transforms/IPO/ProfiledCallGraph.h"
  72. #include "llvm/Transforms/IPO/SampleContextTracker.h"
  73. #include "llvm/Transforms/IPO/SampleProfileProbe.h"
  74. #include "llvm/Transforms/Instrumentation.h"
  75. #include "llvm/Transforms/Utils/CallPromotionUtils.h"
  76. #include "llvm/Transforms/Utils/Cloning.h"
  77. #include "llvm/Transforms/Utils/MisExpect.h"
  78. #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
  79. #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
  80. #include <algorithm>
  81. #include <cassert>
  82. #include <cstdint>
  83. #include <functional>
  84. #include <limits>
  85. #include <map>
  86. #include <memory>
  87. #include <queue>
  88. #include <string>
  89. #include <system_error>
  90. #include <utility>
  91. #include <vector>
  92. using namespace llvm;
  93. using namespace sampleprof;
  94. using namespace llvm::sampleprofutil;
  95. using ProfileCount = Function::ProfileCount;
  96. #define DEBUG_TYPE "sample-profile"
  97. #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
  98. STATISTIC(NumCSInlined,
  99. "Number of functions inlined with context sensitive profile");
  100. STATISTIC(NumCSNotInlined,
  101. "Number of functions not inlined with context sensitive profile");
  102. STATISTIC(NumMismatchedProfile,
  103. "Number of functions with CFG mismatched profile");
  104. STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
  105. STATISTIC(NumDuplicatedInlinesite,
  106. "Number of inlined callsites with a partial distribution factor");
  107. STATISTIC(NumCSInlinedHitMinLimit,
  108. "Number of functions with FDO inline stopped due to min size limit");
  109. STATISTIC(NumCSInlinedHitMaxLimit,
  110. "Number of functions with FDO inline stopped due to max size limit");
  111. STATISTIC(
  112. NumCSInlinedHitGrowthLimit,
  113. "Number of functions with FDO inline stopped due to growth size limit");
  114. // Command line option to specify the file to read samples from. This is
  115. // mainly used for debugging.
  116. static cl::opt<std::string> SampleProfileFile(
  117. "sample-profile-file", cl::init(""), cl::value_desc("filename"),
  118. cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
  119. // The named file contains a set of transformations that may have been applied
  120. // to the symbol names between the program from which the sample data was
  121. // collected and the current program's symbols.
  122. static cl::opt<std::string> SampleProfileRemappingFile(
  123. "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
  124. cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
  125. static cl::opt<bool> ReportProfileStaleness(
  126. "report-profile-staleness", cl::Hidden, cl::init(false),
  127. cl::desc("Compute and report stale profile statistical metrics."));
  128. static cl::opt<bool> PersistProfileStaleness(
  129. "persist-profile-staleness", cl::Hidden, cl::init(false),
  130. cl::desc("Compute stale profile statistical metrics and write it into the "
  131. "native object file(.llvm_stats section)."));
  132. static cl::opt<bool> ProfileSampleAccurate(
  133. "profile-sample-accurate", cl::Hidden, cl::init(false),
  134. cl::desc("If the sample profile is accurate, we will mark all un-sampled "
  135. "callsite and function as having 0 samples. Otherwise, treat "
  136. "un-sampled callsites and functions conservatively as unknown. "));
  137. static cl::opt<bool> ProfileSampleBlockAccurate(
  138. "profile-sample-block-accurate", cl::Hidden, cl::init(false),
  139. cl::desc("If the sample profile is accurate, we will mark all un-sampled "
  140. "branches and calls as having 0 samples. Otherwise, treat "
  141. "them conservatively as unknown. "));
  142. static cl::opt<bool> ProfileAccurateForSymsInList(
  143. "profile-accurate-for-symsinlist", cl::Hidden, cl::init(true),
  144. cl::desc("For symbols in profile symbol list, regard their profiles to "
  145. "be accurate. It may be overriden by profile-sample-accurate. "));
  146. static cl::opt<bool> ProfileMergeInlinee(
  147. "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
  148. cl::desc("Merge past inlinee's profile to outline version if sample "
  149. "profile loader decided not to inline a call site. It will "
  150. "only be enabled when top-down order of profile loading is "
  151. "enabled. "));
  152. static cl::opt<bool> ProfileTopDownLoad(
  153. "sample-profile-top-down-load", cl::Hidden, cl::init(true),
  154. cl::desc("Do profile annotation and inlining for functions in top-down "
  155. "order of call graph during sample profile loading. It only "
  156. "works for new pass manager. "));
  157. static cl::opt<bool>
  158. UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden,
  159. cl::desc("Process functions in a top-down order "
  160. "defined by the profiled call graph when "
  161. "-sample-profile-top-down-load is on."));
  162. cl::opt<bool>
  163. SortProfiledSCC("sort-profiled-scc-member", cl::init(true), cl::Hidden,
  164. cl::desc("Sort profiled recursion by edge weights."));
  165. static cl::opt<bool> ProfileSizeInline(
  166. "sample-profile-inline-size", cl::Hidden, cl::init(false),
  167. cl::desc("Inline cold call sites in profile loader if it's beneficial "
  168. "for code size."));
  169. // Since profiles are consumed by many passes, turning on this option has
  170. // side effects. For instance, pre-link SCC inliner would see merged profiles
  171. // and inline the hot functions (that are skipped in this pass).
  172. static cl::opt<bool> DisableSampleLoaderInlining(
  173. "disable-sample-loader-inlining", cl::Hidden, cl::init(false),
  174. cl::desc("If true, artifically skip inline transformation in sample-loader "
  175. "pass, and merge (or scale) profiles (as configured by "
  176. "--sample-profile-merge-inlinee)."));
  177. cl::opt<int> ProfileInlineGrowthLimit(
  178. "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12),
  179. cl::desc("The size growth ratio limit for proirity-based sample profile "
  180. "loader inlining."));
  181. cl::opt<int> ProfileInlineLimitMin(
  182. "sample-profile-inline-limit-min", cl::Hidden, cl::init(100),
  183. cl::desc("The lower bound of size growth limit for "
  184. "proirity-based sample profile loader inlining."));
  185. cl::opt<int> ProfileInlineLimitMax(
  186. "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000),
  187. cl::desc("The upper bound of size growth limit for "
  188. "proirity-based sample profile loader inlining."));
  189. cl::opt<int> SampleHotCallSiteThreshold(
  190. "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000),
  191. cl::desc("Hot callsite threshold for proirity-based sample profile loader "
  192. "inlining."));
  193. cl::opt<int> SampleColdCallSiteThreshold(
  194. "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
  195. cl::desc("Threshold for inlining cold callsites"));
  196. static cl::opt<unsigned> ProfileICPRelativeHotness(
  197. "sample-profile-icp-relative-hotness", cl::Hidden, cl::init(25),
  198. cl::desc(
  199. "Relative hotness percentage threshold for indirect "
  200. "call promotion in proirity-based sample profile loader inlining."));
  201. static cl::opt<unsigned> ProfileICPRelativeHotnessSkip(
  202. "sample-profile-icp-relative-hotness-skip", cl::Hidden, cl::init(1),
  203. cl::desc(
  204. "Skip relative hotness check for ICP up to given number of targets."));
  205. static cl::opt<bool> CallsitePrioritizedInline(
  206. "sample-profile-prioritized-inline", cl::Hidden,
  207. cl::desc("Use call site prioritized inlining for sample profile loader."
  208. "Currently only CSSPGO is supported."));
  209. static cl::opt<bool> UsePreInlinerDecision(
  210. "sample-profile-use-preinliner", cl::Hidden,
  211. cl::desc("Use the preinliner decisions stored in profile context."));
  212. static cl::opt<bool> AllowRecursiveInline(
  213. "sample-profile-recursive-inline", cl::Hidden,
  214. cl::desc("Allow sample loader inliner to inline recursive calls."));
  215. static cl::opt<std::string> ProfileInlineReplayFile(
  216. "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
  217. cl::desc(
  218. "Optimization remarks file containing inline remarks to be replayed "
  219. "by inlining from sample profile loader."),
  220. cl::Hidden);
  221. static cl::opt<ReplayInlinerSettings::Scope> ProfileInlineReplayScope(
  222. "sample-profile-inline-replay-scope",
  223. cl::init(ReplayInlinerSettings::Scope::Function),
  224. cl::values(clEnumValN(ReplayInlinerSettings::Scope::Function, "Function",
  225. "Replay on functions that have remarks associated "
  226. "with them (default)"),
  227. clEnumValN(ReplayInlinerSettings::Scope::Module, "Module",
  228. "Replay on the entire module")),
  229. cl::desc("Whether inline replay should be applied to the entire "
  230. "Module or just the Functions (default) that are present as "
  231. "callers in remarks during sample profile inlining."),
  232. cl::Hidden);
  233. static cl::opt<ReplayInlinerSettings::Fallback> ProfileInlineReplayFallback(
  234. "sample-profile-inline-replay-fallback",
  235. cl::init(ReplayInlinerSettings::Fallback::Original),
  236. cl::values(
  237. clEnumValN(
  238. ReplayInlinerSettings::Fallback::Original, "Original",
  239. "All decisions not in replay send to original advisor (default)"),
  240. clEnumValN(ReplayInlinerSettings::Fallback::AlwaysInline,
  241. "AlwaysInline", "All decisions not in replay are inlined"),
  242. clEnumValN(ReplayInlinerSettings::Fallback::NeverInline, "NeverInline",
  243. "All decisions not in replay are not inlined")),
  244. cl::desc("How sample profile inline replay treats sites that don't come "
  245. "from the replay. Original: defers to original advisor, "
  246. "AlwaysInline: inline all sites not in replay, NeverInline: "
  247. "inline no sites not in replay"),
  248. cl::Hidden);
  249. static cl::opt<CallSiteFormat::Format> ProfileInlineReplayFormat(
  250. "sample-profile-inline-replay-format",
  251. cl::init(CallSiteFormat::Format::LineColumnDiscriminator),
  252. cl::values(
  253. clEnumValN(CallSiteFormat::Format::Line, "Line", "<Line Number>"),
  254. clEnumValN(CallSiteFormat::Format::LineColumn, "LineColumn",
  255. "<Line Number>:<Column Number>"),
  256. clEnumValN(CallSiteFormat::Format::LineDiscriminator,
  257. "LineDiscriminator", "<Line Number>.<Discriminator>"),
  258. clEnumValN(CallSiteFormat::Format::LineColumnDiscriminator,
  259. "LineColumnDiscriminator",
  260. "<Line Number>:<Column Number>.<Discriminator> (default)")),
  261. cl::desc("How sample profile inline replay file is formatted"), cl::Hidden);
  262. static cl::opt<unsigned>
  263. MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden,
  264. cl::desc("Max number of promotions for a single indirect "
  265. "call callsite in sample profile loader"));
  266. static cl::opt<bool> OverwriteExistingWeights(
  267. "overwrite-existing-weights", cl::Hidden, cl::init(false),
  268. cl::desc("Ignore existing branch weights on IR and always overwrite."));
  269. static cl::opt<bool> AnnotateSampleProfileInlinePhase(
  270. "annotate-sample-profile-inline-phase", cl::Hidden, cl::init(false),
  271. cl::desc("Annotate LTO phase (prelink / postlink), or main (no LTO) for "
  272. "sample-profile inline pass name."));
  273. extern cl::opt<bool> EnableExtTspBlockPlacement;
  274. namespace {
  275. using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
  276. using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
  277. using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
  278. using EdgeWeightMap = DenseMap<Edge, uint64_t>;
  279. using BlockEdgeMap =
  280. DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
  281. class GUIDToFuncNameMapper {
  282. public:
  283. GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
  284. DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
  285. : CurrentReader(Reader), CurrentModule(M),
  286. CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
  287. if (!CurrentReader.useMD5())
  288. return;
  289. for (const auto &F : CurrentModule) {
  290. StringRef OrigName = F.getName();
  291. CurrentGUIDToFuncNameMap.insert(
  292. {Function::getGUID(OrigName), OrigName});
  293. // Local to global var promotion used by optimization like thinlto
  294. // will rename the var and add suffix like ".llvm.xxx" to the
  295. // original local name. In sample profile, the suffixes of function
  296. // names are all stripped. Since it is possible that the mapper is
  297. // built in post-thin-link phase and var promotion has been done,
  298. // we need to add the substring of function name without the suffix
  299. // into the GUIDToFuncNameMap.
  300. StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
  301. if (CanonName != OrigName)
  302. CurrentGUIDToFuncNameMap.insert(
  303. {Function::getGUID(CanonName), CanonName});
  304. }
  305. // Update GUIDToFuncNameMap for each function including inlinees.
  306. SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
  307. }
  308. ~GUIDToFuncNameMapper() {
  309. if (!CurrentReader.useMD5())
  310. return;
  311. CurrentGUIDToFuncNameMap.clear();
  312. // Reset GUIDToFuncNameMap for of each function as they're no
  313. // longer valid at this point.
  314. SetGUIDToFuncNameMapForAll(nullptr);
  315. }
  316. private:
  317. void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
  318. std::queue<FunctionSamples *> FSToUpdate;
  319. for (auto &IFS : CurrentReader.getProfiles()) {
  320. FSToUpdate.push(&IFS.second);
  321. }
  322. while (!FSToUpdate.empty()) {
  323. FunctionSamples *FS = FSToUpdate.front();
  324. FSToUpdate.pop();
  325. FS->GUIDToFuncNameMap = Map;
  326. for (const auto &ICS : FS->getCallsiteSamples()) {
  327. const FunctionSamplesMap &FSMap = ICS.second;
  328. for (const auto &IFS : FSMap) {
  329. FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
  330. FSToUpdate.push(&FS);
  331. }
  332. }
  333. }
  334. }
  335. SampleProfileReader &CurrentReader;
  336. Module &CurrentModule;
  337. DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
  338. };
  339. // Inline candidate used by iterative callsite prioritized inliner
  340. struct InlineCandidate {
  341. CallBase *CallInstr;
  342. const FunctionSamples *CalleeSamples;
  343. // Prorated callsite count, which will be used to guide inlining. For example,
  344. // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
  345. // copies will get their own distribution factors and their prorated counts
  346. // will be used to decide if they should be inlined independently.
  347. uint64_t CallsiteCount;
  348. // Call site distribution factor to prorate the profile samples for a
  349. // duplicated callsite. Default value is 1.0.
  350. float CallsiteDistribution;
  351. };
  352. // Inline candidate comparer using call site weight
  353. struct CandidateComparer {
  354. bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
  355. if (LHS.CallsiteCount != RHS.CallsiteCount)
  356. return LHS.CallsiteCount < RHS.CallsiteCount;
  357. const FunctionSamples *LCS = LHS.CalleeSamples;
  358. const FunctionSamples *RCS = RHS.CalleeSamples;
  359. assert(LCS && RCS && "Expect non-null FunctionSamples");
  360. // Tie breaker using number of samples try to favor smaller functions first
  361. if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
  362. return LCS->getBodySamples().size() > RCS->getBodySamples().size();
  363. // Tie breaker using GUID so we have stable/deterministic inlining order
  364. return LCS->getGUID(LCS->getName()) < RCS->getGUID(RCS->getName());
  365. }
  366. };
  367. using CandidateQueue =
  368. PriorityQueue<InlineCandidate, std::vector<InlineCandidate>,
  369. CandidateComparer>;
  370. // Sample profile matching - fuzzy match.
  371. class SampleProfileMatcher {
  372. Module &M;
  373. SampleProfileReader &Reader;
  374. const PseudoProbeManager *ProbeManager;
  375. // Profile mismatching statstics.
  376. uint64_t TotalProfiledCallsites = 0;
  377. uint64_t NumMismatchedCallsites = 0;
  378. uint64_t MismatchedCallsiteSamples = 0;
  379. uint64_t TotalCallsiteSamples = 0;
  380. uint64_t TotalProfiledFunc = 0;
  381. uint64_t NumMismatchedFuncHash = 0;
  382. uint64_t MismatchedFuncHashSamples = 0;
  383. uint64_t TotalFuncHashSamples = 0;
  384. public:
  385. SampleProfileMatcher(Module &M, SampleProfileReader &Reader,
  386. const PseudoProbeManager *ProbeManager)
  387. : M(M), Reader(Reader), ProbeManager(ProbeManager) {}
  388. void detectProfileMismatch();
  389. void detectProfileMismatch(const Function &F, const FunctionSamples &FS);
  390. };
  391. /// Sample profile pass.
  392. ///
  393. /// This pass reads profile data from the file specified by
  394. /// -sample-profile-file and annotates every affected function with the
  395. /// profile information found in that file.
  396. class SampleProfileLoader final
  397. : public SampleProfileLoaderBaseImpl<BasicBlock> {
  398. public:
  399. SampleProfileLoader(
  400. StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
  401. std::function<AssumptionCache &(Function &)> GetAssumptionCache,
  402. std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
  403. std::function<const TargetLibraryInfo &(Function &)> GetTLI)
  404. : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName)),
  405. GetAC(std::move(GetAssumptionCache)),
  406. GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
  407. LTOPhase(LTOPhase),
  408. AnnotatedPassName(AnnotateSampleProfileInlinePhase
  409. ? llvm::AnnotateInlinePassName(InlineContext{
  410. LTOPhase, InlinePass::SampleProfileInliner})
  411. : CSINLINE_DEBUG) {}
  412. bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
  413. bool runOnModule(Module &M, ModuleAnalysisManager *AM,
  414. ProfileSummaryInfo *_PSI, CallGraph *CG);
  415. protected:
  416. bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
  417. bool emitAnnotations(Function &F);
  418. ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
  419. ErrorOr<uint64_t> getProbeWeight(const Instruction &I);
  420. const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
  421. const FunctionSamples *
  422. findFunctionSamples(const Instruction &I) const override;
  423. std::vector<const FunctionSamples *>
  424. findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
  425. void findExternalInlineCandidate(CallBase *CB, const FunctionSamples *Samples,
  426. DenseSet<GlobalValue::GUID> &InlinedGUIDs,
  427. const StringMap<Function *> &SymbolMap,
  428. uint64_t Threshold);
  429. // Attempt to promote indirect call and also inline the promoted call
  430. bool tryPromoteAndInlineCandidate(
  431. Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
  432. uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
  433. bool inlineHotFunctions(Function &F,
  434. DenseSet<GlobalValue::GUID> &InlinedGUIDs);
  435. std::optional<InlineCost> getExternalInlineAdvisorCost(CallBase &CB);
  436. bool getExternalInlineAdvisorShouldInline(CallBase &CB);
  437. InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
  438. bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
  439. bool
  440. tryInlineCandidate(InlineCandidate &Candidate,
  441. SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
  442. bool
  443. inlineHotFunctionsWithPriority(Function &F,
  444. DenseSet<GlobalValue::GUID> &InlinedGUIDs);
  445. // Inline cold/small functions in addition to hot ones
  446. bool shouldInlineColdCallee(CallBase &CallInst);
  447. void emitOptimizationRemarksForInlineCandidates(
  448. const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
  449. bool Hot);
  450. void promoteMergeNotInlinedContextSamples(
  451. MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
  452. const Function &F);
  453. std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
  454. std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(CallGraph &CG);
  455. void generateMDProfMetadata(Function &F);
  456. /// Map from function name to Function *. Used to find the function from
  457. /// the function name. If the function name contains suffix, additional
  458. /// entry is added to map from the stripped name to the function if there
  459. /// is one-to-one mapping.
  460. StringMap<Function *> SymbolMap;
  461. std::function<AssumptionCache &(Function &)> GetAC;
  462. std::function<TargetTransformInfo &(Function &)> GetTTI;
  463. std::function<const TargetLibraryInfo &(Function &)> GetTLI;
  464. /// Profile tracker for different context.
  465. std::unique_ptr<SampleContextTracker> ContextTracker;
  466. /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
  467. ///
  468. /// We need to know the LTO phase because for example in ThinLTOPrelink
  469. /// phase, in annotation, we should not promote indirect calls. Instead,
  470. /// we will mark GUIDs that needs to be annotated to the function.
  471. const ThinOrFullLTOPhase LTOPhase;
  472. const std::string AnnotatedPassName;
  473. /// Profle Symbol list tells whether a function name appears in the binary
  474. /// used to generate the current profile.
  475. std::unique_ptr<ProfileSymbolList> PSL;
  476. /// Total number of samples collected in this profile.
  477. ///
  478. /// This is the sum of all the samples collected in all the functions executed
  479. /// at runtime.
  480. uint64_t TotalCollectedSamples = 0;
  481. // Information recorded when we declined to inline a call site
  482. // because we have determined it is too cold is accumulated for
  483. // each callee function. Initially this is just the entry count.
  484. struct NotInlinedProfileInfo {
  485. uint64_t entryCount;
  486. };
  487. DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
  488. // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
  489. // all the function symbols defined or declared in current module.
  490. DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
  491. // All the Names used in FunctionSamples including outline function
  492. // names, inline instance names and call target names.
  493. StringSet<> NamesInProfile;
  494. // For symbol in profile symbol list, whether to regard their profiles
  495. // to be accurate. It is mainly decided by existance of profile symbol
  496. // list and -profile-accurate-for-symsinlist flag, but it can be
  497. // overriden by -profile-sample-accurate or profile-sample-accurate
  498. // attribute.
  499. bool ProfAccForSymsInList;
  500. // External inline advisor used to replay inline decision from remarks.
  501. std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
  502. // A pseudo probe helper to correlate the imported sample counts.
  503. std::unique_ptr<PseudoProbeManager> ProbeManager;
  504. // A helper to implement the sample profile matching algorithm.
  505. std::unique_ptr<SampleProfileMatcher> MatchingManager;
  506. private:
  507. const char *getAnnotatedRemarkPassName() const {
  508. return AnnotatedPassName.c_str();
  509. }
  510. };
  511. } // end anonymous namespace
  512. ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
  513. if (FunctionSamples::ProfileIsProbeBased)
  514. return getProbeWeight(Inst);
  515. const DebugLoc &DLoc = Inst.getDebugLoc();
  516. if (!DLoc)
  517. return std::error_code();
  518. // Ignore all intrinsics, phinodes and branch instructions.
  519. // Branch and phinodes instruction usually contains debug info from sources
  520. // outside of the residing basic block, thus we ignore them during annotation.
  521. if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
  522. return std::error_code();
  523. // For non-CS profile, if a direct call/invoke instruction is inlined in
  524. // profile (findCalleeFunctionSamples returns non-empty result), but not
  525. // inlined here, it means that the inlined callsite has no sample, thus the
  526. // call instruction should have 0 count.
  527. // For CS profile, the callsite count of previously inlined callees is
  528. // populated with the entry count of the callees.
  529. if (!FunctionSamples::ProfileIsCS)
  530. if (const auto *CB = dyn_cast<CallBase>(&Inst))
  531. if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
  532. return 0;
  533. return getInstWeightImpl(Inst);
  534. }
  535. // Here use error_code to represent: 1) The dangling probe. 2) Ignore the weight
  536. // of non-probe instruction. So if all instructions of the BB give error_code,
  537. // tell the inference algorithm to infer the BB weight.
  538. ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) {
  539. assert(FunctionSamples::ProfileIsProbeBased &&
  540. "Profile is not pseudo probe based");
  541. std::optional<PseudoProbe> Probe = extractProbe(Inst);
  542. // Ignore the non-probe instruction. If none of the instruction in the BB is
  543. // probe, we choose to infer the BB's weight.
  544. if (!Probe)
  545. return std::error_code();
  546. const FunctionSamples *FS = findFunctionSamples(Inst);
  547. // If none of the instruction has FunctionSample, we choose to return zero
  548. // value sample to indicate the BB is cold. This could happen when the
  549. // instruction is from inlinee and no profile data is found.
  550. // FIXME: This should not be affected by the source drift issue as 1) if the
  551. // newly added function is top-level inliner, it won't match the CFG checksum
  552. // in the function profile or 2) if it's the inlinee, the inlinee should have
  553. // a profile, otherwise it wouldn't be inlined. For non-probe based profile,
  554. // we can improve it by adding a switch for profile-sample-block-accurate for
  555. // block level counts in the future.
  556. if (!FS)
  557. return 0;
  558. // For non-CS profile, If a direct call/invoke instruction is inlined in
  559. // profile (findCalleeFunctionSamples returns non-empty result), but not
  560. // inlined here, it means that the inlined callsite has no sample, thus the
  561. // call instruction should have 0 count.
  562. // For CS profile, the callsite count of previously inlined callees is
  563. // populated with the entry count of the callees.
  564. if (!FunctionSamples::ProfileIsCS)
  565. if (const auto *CB = dyn_cast<CallBase>(&Inst))
  566. if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
  567. return 0;
  568. const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0);
  569. if (R) {
  570. uint64_t Samples = R.get() * Probe->Factor;
  571. bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
  572. if (FirstMark) {
  573. ORE->emit([&]() {
  574. OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
  575. Remark << "Applied " << ore::NV("NumSamples", Samples);
  576. Remark << " samples from profile (ProbeId=";
  577. Remark << ore::NV("ProbeId", Probe->Id);
  578. Remark << ", Factor=";
  579. Remark << ore::NV("Factor", Probe->Factor);
  580. Remark << ", OriginalSamples=";
  581. Remark << ore::NV("OriginalSamples", R.get());
  582. Remark << ")";
  583. return Remark;
  584. });
  585. }
  586. LLVM_DEBUG(dbgs() << " " << Probe->Id << ":" << Inst
  587. << " - weight: " << R.get() << " - factor: "
  588. << format("%0.2f", Probe->Factor) << ")\n");
  589. return Samples;
  590. }
  591. return R;
  592. }
  593. /// Get the FunctionSamples for a call instruction.
  594. ///
  595. /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
  596. /// instance in which that call instruction is calling to. It contains
  597. /// all samples that resides in the inlined instance. We first find the
  598. /// inlined instance in which the call instruction is from, then we
  599. /// traverse its children to find the callsite with the matching
  600. /// location.
  601. ///
  602. /// \param Inst Call/Invoke instruction to query.
  603. ///
  604. /// \returns The FunctionSamples pointer to the inlined instance.
  605. const FunctionSamples *
  606. SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
  607. const DILocation *DIL = Inst.getDebugLoc();
  608. if (!DIL) {
  609. return nullptr;
  610. }
  611. StringRef CalleeName;
  612. if (Function *Callee = Inst.getCalledFunction())
  613. CalleeName = Callee->getName();
  614. if (FunctionSamples::ProfileIsCS)
  615. return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
  616. const FunctionSamples *FS = findFunctionSamples(Inst);
  617. if (FS == nullptr)
  618. return nullptr;
  619. return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
  620. CalleeName, Reader->getRemapper());
  621. }
  622. /// Returns a vector of FunctionSamples that are the indirect call targets
  623. /// of \p Inst. The vector is sorted by the total number of samples. Stores
  624. /// the total call count of the indirect call in \p Sum.
  625. std::vector<const FunctionSamples *>
  626. SampleProfileLoader::findIndirectCallFunctionSamples(
  627. const Instruction &Inst, uint64_t &Sum) const {
  628. const DILocation *DIL = Inst.getDebugLoc();
  629. std::vector<const FunctionSamples *> R;
  630. if (!DIL) {
  631. return R;
  632. }
  633. auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
  634. assert(L && R && "Expect non-null FunctionSamples");
  635. if (L->getHeadSamplesEstimate() != R->getHeadSamplesEstimate())
  636. return L->getHeadSamplesEstimate() > R->getHeadSamplesEstimate();
  637. return FunctionSamples::getGUID(L->getName()) <
  638. FunctionSamples::getGUID(R->getName());
  639. };
  640. if (FunctionSamples::ProfileIsCS) {
  641. auto CalleeSamples =
  642. ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
  643. if (CalleeSamples.empty())
  644. return R;
  645. // For CSSPGO, we only use target context profile's entry count
  646. // as that already includes both inlined callee and non-inlined ones..
  647. Sum = 0;
  648. for (const auto *const FS : CalleeSamples) {
  649. Sum += FS->getHeadSamplesEstimate();
  650. R.push_back(FS);
  651. }
  652. llvm::sort(R, FSCompare);
  653. return R;
  654. }
  655. const FunctionSamples *FS = findFunctionSamples(Inst);
  656. if (FS == nullptr)
  657. return R;
  658. auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
  659. auto T = FS->findCallTargetMapAt(CallSite);
  660. Sum = 0;
  661. if (T)
  662. for (const auto &T_C : T.get())
  663. Sum += T_C.second;
  664. if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
  665. if (M->empty())
  666. return R;
  667. for (const auto &NameFS : *M) {
  668. Sum += NameFS.second.getHeadSamplesEstimate();
  669. R.push_back(&NameFS.second);
  670. }
  671. llvm::sort(R, FSCompare);
  672. }
  673. return R;
  674. }
  675. const FunctionSamples *
  676. SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
  677. if (FunctionSamples::ProfileIsProbeBased) {
  678. std::optional<PseudoProbe> Probe = extractProbe(Inst);
  679. if (!Probe)
  680. return nullptr;
  681. }
  682. const DILocation *DIL = Inst.getDebugLoc();
  683. if (!DIL)
  684. return Samples;
  685. auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
  686. if (it.second) {
  687. if (FunctionSamples::ProfileIsCS)
  688. it.first->second = ContextTracker->getContextSamplesFor(DIL);
  689. else
  690. it.first->second =
  691. Samples->findFunctionSamples(DIL, Reader->getRemapper());
  692. }
  693. return it.first->second;
  694. }
  695. /// Check whether the indirect call promotion history of \p Inst allows
  696. /// the promotion for \p Candidate.
  697. /// If the profile count for the promotion candidate \p Candidate is
  698. /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
  699. /// for \p Inst. If we already have at least MaxNumPromotions
  700. /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
  701. /// cannot promote for \p Inst anymore.
  702. static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) {
  703. uint32_t NumVals = 0;
  704. uint64_t TotalCount = 0;
  705. std::unique_ptr<InstrProfValueData[]> ValueData =
  706. std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
  707. bool Valid =
  708. getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
  709. ValueData.get(), NumVals, TotalCount, true);
  710. // No valid value profile so no promoted targets have been recorded
  711. // before. Ok to do ICP.
  712. if (!Valid)
  713. return true;
  714. unsigned NumPromoted = 0;
  715. for (uint32_t I = 0; I < NumVals; I++) {
  716. if (ValueData[I].Count != NOMORE_ICP_MAGICNUM)
  717. continue;
  718. // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
  719. // metadata, it means the candidate has been promoted for this
  720. // indirect call.
  721. if (ValueData[I].Value == Function::getGUID(Candidate))
  722. return false;
  723. NumPromoted++;
  724. // If already have MaxNumPromotions promotion, don't do it anymore.
  725. if (NumPromoted == MaxNumPromotions)
  726. return false;
  727. }
  728. return true;
  729. }
  730. /// Update indirect call target profile metadata for \p Inst.
  731. /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
  732. /// If it is 0, it means updateIDTMetaData is used to mark a
  733. /// certain target to be promoted already. If it is not zero,
  734. /// we expect to use it to update the total count in the value profile.
  735. static void
  736. updateIDTMetaData(Instruction &Inst,
  737. const SmallVectorImpl<InstrProfValueData> &CallTargets,
  738. uint64_t Sum) {
  739. // Bail out early if MaxNumPromotions is zero.
  740. // This prevents allocating an array of zero length below.
  741. //
  742. // Note `updateIDTMetaData` is called in two places so check
  743. // `MaxNumPromotions` inside it.
  744. if (MaxNumPromotions == 0)
  745. return;
  746. uint32_t NumVals = 0;
  747. // OldSum is the existing total count in the value profile data.
  748. uint64_t OldSum = 0;
  749. std::unique_ptr<InstrProfValueData[]> ValueData =
  750. std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
  751. bool Valid =
  752. getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
  753. ValueData.get(), NumVals, OldSum, true);
  754. DenseMap<uint64_t, uint64_t> ValueCountMap;
  755. if (Sum == 0) {
  756. assert((CallTargets.size() == 1 &&
  757. CallTargets[0].Count == NOMORE_ICP_MAGICNUM) &&
  758. "If sum is 0, assume only one element in CallTargets "
  759. "with count being NOMORE_ICP_MAGICNUM");
  760. // Initialize ValueCountMap with existing value profile data.
  761. if (Valid) {
  762. for (uint32_t I = 0; I < NumVals; I++)
  763. ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
  764. }
  765. auto Pair =
  766. ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count);
  767. // If the target already exists in value profile, decrease the total
  768. // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
  769. if (!Pair.second) {
  770. OldSum -= Pair.first->second;
  771. Pair.first->second = NOMORE_ICP_MAGICNUM;
  772. }
  773. Sum = OldSum;
  774. } else {
  775. // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
  776. // counts in the value profile.
  777. if (Valid) {
  778. for (uint32_t I = 0; I < NumVals; I++) {
  779. if (ValueData[I].Count == NOMORE_ICP_MAGICNUM)
  780. ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
  781. }
  782. }
  783. for (const auto &Data : CallTargets) {
  784. auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
  785. if (Pair.second)
  786. continue;
  787. // The target represented by Data.Value has already been promoted.
  788. // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
  789. // Sum by Data.Count.
  790. assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
  791. Sum -= Data.Count;
  792. }
  793. }
  794. SmallVector<InstrProfValueData, 8> NewCallTargets;
  795. for (const auto &ValueCount : ValueCountMap) {
  796. NewCallTargets.emplace_back(
  797. InstrProfValueData{ValueCount.first, ValueCount.second});
  798. }
  799. llvm::sort(NewCallTargets,
  800. [](const InstrProfValueData &L, const InstrProfValueData &R) {
  801. if (L.Count != R.Count)
  802. return L.Count > R.Count;
  803. return L.Value > R.Value;
  804. });
  805. uint32_t MaxMDCount =
  806. std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions));
  807. annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
  808. NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
  809. }
  810. /// Attempt to promote indirect call and also inline the promoted call.
  811. ///
  812. /// \param F Caller function.
  813. /// \param Candidate ICP and inline candidate.
  814. /// \param SumOrigin Original sum of target counts for indirect call before
  815. /// promoting given candidate.
  816. /// \param Sum Prorated sum of remaining target counts for indirect call
  817. /// after promoting given candidate.
  818. /// \param InlinedCallSite Output vector for new call sites exposed after
  819. /// inlining.
  820. bool SampleProfileLoader::tryPromoteAndInlineCandidate(
  821. Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
  822. SmallVector<CallBase *, 8> *InlinedCallSite) {
  823. // Bail out early if sample-loader inliner is disabled.
  824. if (DisableSampleLoaderInlining)
  825. return false;
  826. // Bail out early if MaxNumPromotions is zero.
  827. // This prevents allocating an array of zero length in callees below.
  828. if (MaxNumPromotions == 0)
  829. return false;
  830. auto CalleeFunctionName = Candidate.CalleeSamples->getFuncName();
  831. auto R = SymbolMap.find(CalleeFunctionName);
  832. if (R == SymbolMap.end() || !R->getValue())
  833. return false;
  834. auto &CI = *Candidate.CallInstr;
  835. if (!doesHistoryAllowICP(CI, R->getValue()->getName()))
  836. return false;
  837. const char *Reason = "Callee function not available";
  838. // R->getValue() != &F is to prevent promoting a recursive call.
  839. // If it is a recursive call, we do not inline it as it could bloat
  840. // the code exponentially. There is way to better handle this, e.g.
  841. // clone the caller first, and inline the cloned caller if it is
  842. // recursive. As llvm does not inline recursive calls, we will
  843. // simply ignore it instead of handling it explicitly.
  844. if (!R->getValue()->isDeclaration() && R->getValue()->getSubprogram() &&
  845. R->getValue()->hasFnAttribute("use-sample-profile") &&
  846. R->getValue() != &F && isLegalToPromote(CI, R->getValue(), &Reason)) {
  847. // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
  848. // in the value profile metadata so the target won't be promoted again.
  849. SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
  850. Function::getGUID(R->getValue()->getName()), NOMORE_ICP_MAGICNUM}};
  851. updateIDTMetaData(CI, SortedCallTargets, 0);
  852. auto *DI = &pgo::promoteIndirectCall(
  853. CI, R->getValue(), Candidate.CallsiteCount, Sum, false, ORE);
  854. if (DI) {
  855. Sum -= Candidate.CallsiteCount;
  856. // Do not prorate the indirect callsite distribution since the original
  857. // distribution will be used to scale down non-promoted profile target
  858. // counts later. By doing this we lose track of the real callsite count
  859. // for the leftover indirect callsite as a trade off for accurate call
  860. // target counts.
  861. // TODO: Ideally we would have two separate factors, one for call site
  862. // counts and one is used to prorate call target counts.
  863. // Do not update the promoted direct callsite distribution at this
  864. // point since the original distribution combined with the callee profile
  865. // will be used to prorate callsites from the callee if inlined. Once not
  866. // inlined, the direct callsite distribution should be prorated so that
  867. // the it will reflect the real callsite counts.
  868. Candidate.CallInstr = DI;
  869. if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
  870. bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
  871. if (!Inlined) {
  872. // Prorate the direct callsite distribution so that it reflects real
  873. // callsite counts.
  874. setProbeDistributionFactor(
  875. *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
  876. }
  877. return Inlined;
  878. }
  879. }
  880. } else {
  881. LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
  882. << Candidate.CalleeSamples->getFuncName() << " because "
  883. << Reason << "\n");
  884. }
  885. return false;
  886. }
  887. bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
  888. if (!ProfileSizeInline)
  889. return false;
  890. Function *Callee = CallInst.getCalledFunction();
  891. if (Callee == nullptr)
  892. return false;
  893. InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
  894. GetAC, GetTLI);
  895. if (Cost.isNever())
  896. return false;
  897. if (Cost.isAlways())
  898. return true;
  899. return Cost.getCost() <= SampleColdCallSiteThreshold;
  900. }
  901. void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
  902. const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
  903. bool Hot) {
  904. for (auto *I : Candidates) {
  905. Function *CalledFunction = I->getCalledFunction();
  906. if (CalledFunction) {
  907. ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
  908. "InlineAttempt", I->getDebugLoc(),
  909. I->getParent())
  910. << "previous inlining reattempted for "
  911. << (Hot ? "hotness: '" : "size: '")
  912. << ore::NV("Callee", CalledFunction) << "' into '"
  913. << ore::NV("Caller", &F) << "'");
  914. }
  915. }
  916. }
  917. void SampleProfileLoader::findExternalInlineCandidate(
  918. CallBase *CB, const FunctionSamples *Samples,
  919. DenseSet<GlobalValue::GUID> &InlinedGUIDs,
  920. const StringMap<Function *> &SymbolMap, uint64_t Threshold) {
  921. // If ExternalInlineAdvisor wants to inline an external function
  922. // make sure it's imported
  923. if (CB && getExternalInlineAdvisorShouldInline(*CB)) {
  924. // Samples may not exist for replayed function, if so
  925. // just add the direct GUID and move on
  926. if (!Samples) {
  927. InlinedGUIDs.insert(
  928. FunctionSamples::getGUID(CB->getCalledFunction()->getName()));
  929. return;
  930. }
  931. // Otherwise, drop the threshold to import everything that we can
  932. Threshold = 0;
  933. }
  934. assert(Samples && "expect non-null caller profile");
  935. // For AutoFDO profile, retrieve candidate profiles by walking over
  936. // the nested inlinee profiles.
  937. if (!FunctionSamples::ProfileIsCS) {
  938. Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold);
  939. return;
  940. }
  941. ContextTrieNode *Caller = ContextTracker->getContextNodeForProfile(Samples);
  942. std::queue<ContextTrieNode *> CalleeList;
  943. CalleeList.push(Caller);
  944. while (!CalleeList.empty()) {
  945. ContextTrieNode *Node = CalleeList.front();
  946. CalleeList.pop();
  947. FunctionSamples *CalleeSample = Node->getFunctionSamples();
  948. // For CSSPGO profile, retrieve candidate profile by walking over the
  949. // trie built for context profile. Note that also take call targets
  950. // even if callee doesn't have a corresponding context profile.
  951. if (!CalleeSample)
  952. continue;
  953. // If pre-inliner decision is used, honor that for importing as well.
  954. bool PreInline =
  955. UsePreInlinerDecision &&
  956. CalleeSample->getContext().hasAttribute(ContextShouldBeInlined);
  957. if (!PreInline && CalleeSample->getHeadSamplesEstimate() < Threshold)
  958. continue;
  959. StringRef Name = CalleeSample->getFuncName();
  960. Function *Func = SymbolMap.lookup(Name);
  961. // Add to the import list only when it's defined out of module.
  962. if (!Func || Func->isDeclaration())
  963. InlinedGUIDs.insert(FunctionSamples::getGUID(CalleeSample->getName()));
  964. // Import hot CallTargets, which may not be available in IR because full
  965. // profile annotation cannot be done until backend compilation in ThinLTO.
  966. for (const auto &BS : CalleeSample->getBodySamples())
  967. for (const auto &TS : BS.second.getCallTargets())
  968. if (TS.getValue() > Threshold) {
  969. StringRef CalleeName = CalleeSample->getFuncName(TS.getKey());
  970. const Function *Callee = SymbolMap.lookup(CalleeName);
  971. if (!Callee || Callee->isDeclaration())
  972. InlinedGUIDs.insert(FunctionSamples::getGUID(TS.getKey()));
  973. }
  974. // Import hot child context profile associted with callees. Note that this
  975. // may have some overlap with the call target loop above, but doing this
  976. // based child context profile again effectively allow us to use the max of
  977. // entry count and call target count to determine importing.
  978. for (auto &Child : Node->getAllChildContext()) {
  979. ContextTrieNode *CalleeNode = &Child.second;
  980. CalleeList.push(CalleeNode);
  981. }
  982. }
  983. }
  984. /// Iteratively inline hot callsites of a function.
  985. ///
  986. /// Iteratively traverse all callsites of the function \p F, so as to
  987. /// find out callsites with corresponding inline instances.
  988. ///
  989. /// For such callsites,
  990. /// - If it is hot enough, inline the callsites and adds callsites of the callee
  991. /// into the caller. If the call is an indirect call, first promote
  992. /// it to direct call. Each indirect call is limited with a single target.
  993. ///
  994. /// - If a callsite is not inlined, merge the its profile to the outline
  995. /// version (if --sample-profile-merge-inlinee is true), or scale the
  996. /// counters of standalone function based on the profile of inlined
  997. /// instances (if --sample-profile-merge-inlinee is false).
  998. ///
  999. /// Later passes may consume the updated profiles.
  1000. ///
  1001. /// \param F function to perform iterative inlining.
  1002. /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
  1003. /// inlined in the profiled binary.
  1004. ///
  1005. /// \returns True if there is any inline happened.
  1006. bool SampleProfileLoader::inlineHotFunctions(
  1007. Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
  1008. // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
  1009. // Profile symbol list is ignored when profile-sample-accurate is on.
  1010. assert((!ProfAccForSymsInList ||
  1011. (!ProfileSampleAccurate &&
  1012. !F.hasFnAttribute("profile-sample-accurate"))) &&
  1013. "ProfAccForSymsInList should be false when profile-sample-accurate "
  1014. "is enabled");
  1015. MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
  1016. bool Changed = false;
  1017. bool LocalChanged = true;
  1018. while (LocalChanged) {
  1019. LocalChanged = false;
  1020. SmallVector<CallBase *, 10> CIS;
  1021. for (auto &BB : F) {
  1022. bool Hot = false;
  1023. SmallVector<CallBase *, 10> AllCandidates;
  1024. SmallVector<CallBase *, 10> ColdCandidates;
  1025. for (auto &I : BB) {
  1026. const FunctionSamples *FS = nullptr;
  1027. if (auto *CB = dyn_cast<CallBase>(&I)) {
  1028. if (!isa<IntrinsicInst>(I)) {
  1029. if ((FS = findCalleeFunctionSamples(*CB))) {
  1030. assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
  1031. "GUIDToFuncNameMap has to be populated");
  1032. AllCandidates.push_back(CB);
  1033. if (FS->getHeadSamplesEstimate() > 0 ||
  1034. FunctionSamples::ProfileIsCS)
  1035. LocalNotInlinedCallSites.insert({CB, FS});
  1036. if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
  1037. Hot = true;
  1038. else if (shouldInlineColdCallee(*CB))
  1039. ColdCandidates.push_back(CB);
  1040. } else if (getExternalInlineAdvisorShouldInline(*CB)) {
  1041. AllCandidates.push_back(CB);
  1042. }
  1043. }
  1044. }
  1045. }
  1046. if (Hot || ExternalInlineAdvisor) {
  1047. CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
  1048. emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
  1049. } else {
  1050. CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
  1051. emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
  1052. }
  1053. }
  1054. for (CallBase *I : CIS) {
  1055. Function *CalledFunction = I->getCalledFunction();
  1056. InlineCandidate Candidate = {I, LocalNotInlinedCallSites.lookup(I),
  1057. 0 /* dummy count */,
  1058. 1.0 /* dummy distribution factor */};
  1059. // Do not inline recursive calls.
  1060. if (CalledFunction == &F)
  1061. continue;
  1062. if (I->isIndirectCall()) {
  1063. uint64_t Sum;
  1064. for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
  1065. uint64_t SumOrigin = Sum;
  1066. if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
  1067. findExternalInlineCandidate(I, FS, InlinedGUIDs, SymbolMap,
  1068. PSI->getOrCompHotCountThreshold());
  1069. continue;
  1070. }
  1071. if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
  1072. continue;
  1073. Candidate = {I, FS, FS->getHeadSamplesEstimate(), 1.0};
  1074. if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
  1075. LocalNotInlinedCallSites.erase(I);
  1076. LocalChanged = true;
  1077. }
  1078. }
  1079. } else if (CalledFunction && CalledFunction->getSubprogram() &&
  1080. !CalledFunction->isDeclaration()) {
  1081. if (tryInlineCandidate(Candidate)) {
  1082. LocalNotInlinedCallSites.erase(I);
  1083. LocalChanged = true;
  1084. }
  1085. } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
  1086. findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
  1087. InlinedGUIDs, SymbolMap,
  1088. PSI->getOrCompHotCountThreshold());
  1089. }
  1090. }
  1091. Changed |= LocalChanged;
  1092. }
  1093. // For CS profile, profile for not inlined context will be merged when
  1094. // base profile is being retrieved.
  1095. if (!FunctionSamples::ProfileIsCS)
  1096. promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
  1097. return Changed;
  1098. }
  1099. bool SampleProfileLoader::tryInlineCandidate(
  1100. InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
  1101. // Do not attempt to inline a candidate if
  1102. // --disable-sample-loader-inlining is true.
  1103. if (DisableSampleLoaderInlining)
  1104. return false;
  1105. CallBase &CB = *Candidate.CallInstr;
  1106. Function *CalledFunction = CB.getCalledFunction();
  1107. assert(CalledFunction && "Expect a callee with definition");
  1108. DebugLoc DLoc = CB.getDebugLoc();
  1109. BasicBlock *BB = CB.getParent();
  1110. InlineCost Cost = shouldInlineCandidate(Candidate);
  1111. if (Cost.isNever()) {
  1112. ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
  1113. "InlineFail", DLoc, BB)
  1114. << "incompatible inlining");
  1115. return false;
  1116. }
  1117. if (!Cost)
  1118. return false;
  1119. InlineFunctionInfo IFI(nullptr, GetAC);
  1120. IFI.UpdateProfile = false;
  1121. InlineResult IR = InlineFunction(CB, IFI,
  1122. /*MergeAttributes=*/true);
  1123. if (!IR.isSuccess())
  1124. return false;
  1125. // The call to InlineFunction erases I, so we can't pass it here.
  1126. emitInlinedIntoBasedOnCost(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(),
  1127. Cost, true, getAnnotatedRemarkPassName());
  1128. // Now populate the list of newly exposed call sites.
  1129. if (InlinedCallSites) {
  1130. InlinedCallSites->clear();
  1131. for (auto &I : IFI.InlinedCallSites)
  1132. InlinedCallSites->push_back(I);
  1133. }
  1134. if (FunctionSamples::ProfileIsCS)
  1135. ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
  1136. ++NumCSInlined;
  1137. // Prorate inlined probes for a duplicated inlining callsite which probably
  1138. // has a distribution less than 100%. Samples for an inlinee should be
  1139. // distributed among the copies of the original callsite based on each
  1140. // callsite's distribution factor for counts accuracy. Note that an inlined
  1141. // probe may come with its own distribution factor if it has been duplicated
  1142. // in the inlinee body. The two factor are multiplied to reflect the
  1143. // aggregation of duplication.
  1144. if (Candidate.CallsiteDistribution < 1) {
  1145. for (auto &I : IFI.InlinedCallSites) {
  1146. if (std::optional<PseudoProbe> Probe = extractProbe(*I))
  1147. setProbeDistributionFactor(*I, Probe->Factor *
  1148. Candidate.CallsiteDistribution);
  1149. }
  1150. NumDuplicatedInlinesite++;
  1151. }
  1152. return true;
  1153. }
  1154. bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
  1155. CallBase *CB) {
  1156. assert(CB && "Expect non-null call instruction");
  1157. if (isa<IntrinsicInst>(CB))
  1158. return false;
  1159. // Find the callee's profile. For indirect call, find hottest target profile.
  1160. const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
  1161. // If ExternalInlineAdvisor wants to inline this site, do so even
  1162. // if Samples are not present.
  1163. if (!CalleeSamples && !getExternalInlineAdvisorShouldInline(*CB))
  1164. return false;
  1165. float Factor = 1.0;
  1166. if (std::optional<PseudoProbe> Probe = extractProbe(*CB))
  1167. Factor = Probe->Factor;
  1168. uint64_t CallsiteCount =
  1169. CalleeSamples ? CalleeSamples->getHeadSamplesEstimate() * Factor : 0;
  1170. *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
  1171. return true;
  1172. }
  1173. std::optional<InlineCost>
  1174. SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
  1175. std::unique_ptr<InlineAdvice> Advice = nullptr;
  1176. if (ExternalInlineAdvisor) {
  1177. Advice = ExternalInlineAdvisor->getAdvice(CB);
  1178. if (Advice) {
  1179. if (!Advice->isInliningRecommended()) {
  1180. Advice->recordUnattemptedInlining();
  1181. return InlineCost::getNever("not previously inlined");
  1182. }
  1183. Advice->recordInlining();
  1184. return InlineCost::getAlways("previously inlined");
  1185. }
  1186. }
  1187. return {};
  1188. }
  1189. bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
  1190. std::optional<InlineCost> Cost = getExternalInlineAdvisorCost(CB);
  1191. return Cost ? !!*Cost : false;
  1192. }
  1193. InlineCost
  1194. SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
  1195. if (std::optional<InlineCost> ReplayCost =
  1196. getExternalInlineAdvisorCost(*Candidate.CallInstr))
  1197. return *ReplayCost;
  1198. // Adjust threshold based on call site hotness, only do this for callsite
  1199. // prioritized inliner because otherwise cost-benefit check is done earlier.
  1200. int SampleThreshold = SampleColdCallSiteThreshold;
  1201. if (CallsitePrioritizedInline) {
  1202. if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
  1203. SampleThreshold = SampleHotCallSiteThreshold;
  1204. else if (!ProfileSizeInline)
  1205. return InlineCost::getNever("cold callsite");
  1206. }
  1207. Function *Callee = Candidate.CallInstr->getCalledFunction();
  1208. assert(Callee && "Expect a definition for inline candidate of direct call");
  1209. InlineParams Params = getInlineParams();
  1210. // We will ignore the threshold from inline cost, so always get full cost.
  1211. Params.ComputeFullInlineCost = true;
  1212. Params.AllowRecursiveCall = AllowRecursiveInline;
  1213. // Checks if there is anything in the reachable portion of the callee at
  1214. // this callsite that makes this inlining potentially illegal. Need to
  1215. // set ComputeFullInlineCost, otherwise getInlineCost may return early
  1216. // when cost exceeds threshold without checking all IRs in the callee.
  1217. // The acutal cost does not matter because we only checks isNever() to
  1218. // see if it is legal to inline the callsite.
  1219. InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
  1220. GetTTI(*Callee), GetAC, GetTLI);
  1221. // Honor always inline and never inline from call analyzer
  1222. if (Cost.isNever() || Cost.isAlways())
  1223. return Cost;
  1224. // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
  1225. // decisions based on hotness as well as accurate function byte sizes for
  1226. // given context using function/inlinee sizes from previous build. It
  1227. // stores the decision in profile, and also adjust/merge context profile
  1228. // aiming at better context-sensitive post-inline profile quality, assuming
  1229. // all inline decision estimates are going to be honored by compiler. Here
  1230. // we replay that inline decision under `sample-profile-use-preinliner`.
  1231. // Note that we don't need to handle negative decision from preinliner as
  1232. // context profile for not inlined calls are merged by preinliner already.
  1233. if (UsePreInlinerDecision && Candidate.CalleeSamples) {
  1234. // Once two node are merged due to promotion, we're losing some context
  1235. // so the original context-sensitive preinliner decision should be ignored
  1236. // for SyntheticContext.
  1237. SampleContext &Context = Candidate.CalleeSamples->getContext();
  1238. if (!Context.hasState(SyntheticContext) &&
  1239. Context.hasAttribute(ContextShouldBeInlined))
  1240. return InlineCost::getAlways("preinliner");
  1241. }
  1242. // For old FDO inliner, we inline the call site as long as cost is not
  1243. // "Never". The cost-benefit check is done earlier.
  1244. if (!CallsitePrioritizedInline) {
  1245. return InlineCost::get(Cost.getCost(), INT_MAX);
  1246. }
  1247. // Otherwise only use the cost from call analyzer, but overwite threshold with
  1248. // Sample PGO threshold.
  1249. return InlineCost::get(Cost.getCost(), SampleThreshold);
  1250. }
  1251. bool SampleProfileLoader::inlineHotFunctionsWithPriority(
  1252. Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
  1253. // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
  1254. // Profile symbol list is ignored when profile-sample-accurate is on.
  1255. assert((!ProfAccForSymsInList ||
  1256. (!ProfileSampleAccurate &&
  1257. !F.hasFnAttribute("profile-sample-accurate"))) &&
  1258. "ProfAccForSymsInList should be false when profile-sample-accurate "
  1259. "is enabled");
  1260. // Populating worklist with initial call sites from root inliner, along
  1261. // with call site weights.
  1262. CandidateQueue CQueue;
  1263. InlineCandidate NewCandidate;
  1264. for (auto &BB : F) {
  1265. for (auto &I : BB) {
  1266. auto *CB = dyn_cast<CallBase>(&I);
  1267. if (!CB)
  1268. continue;
  1269. if (getInlineCandidate(&NewCandidate, CB))
  1270. CQueue.push(NewCandidate);
  1271. }
  1272. }
  1273. // Cap the size growth from profile guided inlining. This is needed even
  1274. // though cost of each inline candidate already accounts for callee size,
  1275. // because with top-down inlining, we can grow inliner size significantly
  1276. // with large number of smaller inlinees each pass the cost check.
  1277. assert(ProfileInlineLimitMax >= ProfileInlineLimitMin &&
  1278. "Max inline size limit should not be smaller than min inline size "
  1279. "limit.");
  1280. unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit;
  1281. SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax);
  1282. SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin);
  1283. if (ExternalInlineAdvisor)
  1284. SizeLimit = std::numeric_limits<unsigned>::max();
  1285. MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
  1286. // Perform iterative BFS call site prioritized inlining
  1287. bool Changed = false;
  1288. while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
  1289. InlineCandidate Candidate = CQueue.top();
  1290. CQueue.pop();
  1291. CallBase *I = Candidate.CallInstr;
  1292. Function *CalledFunction = I->getCalledFunction();
  1293. if (CalledFunction == &F)
  1294. continue;
  1295. if (I->isIndirectCall()) {
  1296. uint64_t Sum = 0;
  1297. auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
  1298. uint64_t SumOrigin = Sum;
  1299. Sum *= Candidate.CallsiteDistribution;
  1300. unsigned ICPCount = 0;
  1301. for (const auto *FS : CalleeSamples) {
  1302. // TODO: Consider disable pre-lTO ICP for MonoLTO as well
  1303. if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
  1304. findExternalInlineCandidate(I, FS, InlinedGUIDs, SymbolMap,
  1305. PSI->getOrCompHotCountThreshold());
  1306. continue;
  1307. }
  1308. uint64_t EntryCountDistributed =
  1309. FS->getHeadSamplesEstimate() * Candidate.CallsiteDistribution;
  1310. // In addition to regular inline cost check, we also need to make sure
  1311. // ICP isn't introducing excessive speculative checks even if individual
  1312. // target looks beneficial to promote and inline. That means we should
  1313. // only do ICP when there's a small number dominant targets.
  1314. if (ICPCount >= ProfileICPRelativeHotnessSkip &&
  1315. EntryCountDistributed * 100 < SumOrigin * ProfileICPRelativeHotness)
  1316. break;
  1317. // TODO: Fix CallAnalyzer to handle all indirect calls.
  1318. // For indirect call, we don't run CallAnalyzer to get InlineCost
  1319. // before actual inlining. This is because we could see two different
  1320. // types from the same definition, which makes CallAnalyzer choke as
  1321. // it's expecting matching parameter type on both caller and callee
  1322. // side. See example from PR18962 for the triggering cases (the bug was
  1323. // fixed, but we generate different types).
  1324. if (!PSI->isHotCount(EntryCountDistributed))
  1325. break;
  1326. SmallVector<CallBase *, 8> InlinedCallSites;
  1327. // Attach function profile for promoted indirect callee, and update
  1328. // call site count for the promoted inline candidate too.
  1329. Candidate = {I, FS, EntryCountDistributed,
  1330. Candidate.CallsiteDistribution};
  1331. if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
  1332. &InlinedCallSites)) {
  1333. for (auto *CB : InlinedCallSites) {
  1334. if (getInlineCandidate(&NewCandidate, CB))
  1335. CQueue.emplace(NewCandidate);
  1336. }
  1337. ICPCount++;
  1338. Changed = true;
  1339. } else if (!ContextTracker) {
  1340. LocalNotInlinedCallSites.insert({I, FS});
  1341. }
  1342. }
  1343. } else if (CalledFunction && CalledFunction->getSubprogram() &&
  1344. !CalledFunction->isDeclaration()) {
  1345. SmallVector<CallBase *, 8> InlinedCallSites;
  1346. if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
  1347. for (auto *CB : InlinedCallSites) {
  1348. if (getInlineCandidate(&NewCandidate, CB))
  1349. CQueue.emplace(NewCandidate);
  1350. }
  1351. Changed = true;
  1352. } else if (!ContextTracker) {
  1353. LocalNotInlinedCallSites.insert({I, Candidate.CalleeSamples});
  1354. }
  1355. } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
  1356. findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
  1357. InlinedGUIDs, SymbolMap,
  1358. PSI->getOrCompHotCountThreshold());
  1359. }
  1360. }
  1361. if (!CQueue.empty()) {
  1362. if (SizeLimit == (unsigned)ProfileInlineLimitMax)
  1363. ++NumCSInlinedHitMaxLimit;
  1364. else if (SizeLimit == (unsigned)ProfileInlineLimitMin)
  1365. ++NumCSInlinedHitMinLimit;
  1366. else
  1367. ++NumCSInlinedHitGrowthLimit;
  1368. }
  1369. // For CS profile, profile for not inlined context will be merged when
  1370. // base profile is being retrieved.
  1371. if (!FunctionSamples::ProfileIsCS)
  1372. promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
  1373. return Changed;
  1374. }
  1375. void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
  1376. MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
  1377. const Function &F) {
  1378. // Accumulate not inlined callsite information into notInlinedSamples
  1379. for (const auto &Pair : NonInlinedCallSites) {
  1380. CallBase *I = Pair.first;
  1381. Function *Callee = I->getCalledFunction();
  1382. if (!Callee || Callee->isDeclaration())
  1383. continue;
  1384. ORE->emit(
  1385. OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(), "NotInline",
  1386. I->getDebugLoc(), I->getParent())
  1387. << "previous inlining not repeated: '" << ore::NV("Callee", Callee)
  1388. << "' into '" << ore::NV("Caller", &F) << "'");
  1389. ++NumCSNotInlined;
  1390. const FunctionSamples *FS = Pair.second;
  1391. if (FS->getTotalSamples() == 0 && FS->getHeadSamplesEstimate() == 0) {
  1392. continue;
  1393. }
  1394. // Do not merge a context that is already duplicated into the base profile.
  1395. if (FS->getContext().hasAttribute(sampleprof::ContextDuplicatedIntoBase))
  1396. continue;
  1397. if (ProfileMergeInlinee) {
  1398. // A function call can be replicated by optimizations like callsite
  1399. // splitting or jump threading and the replicates end up sharing the
  1400. // sample nested callee profile instead of slicing the original
  1401. // inlinee's profile. We want to do merge exactly once by filtering out
  1402. // callee profiles with a non-zero head sample count.
  1403. if (FS->getHeadSamples() == 0) {
  1404. // Use entry samples as head samples during the merge, as inlinees
  1405. // don't have head samples.
  1406. const_cast<FunctionSamples *>(FS)->addHeadSamples(
  1407. FS->getHeadSamplesEstimate());
  1408. // Note that we have to do the merge right after processing function.
  1409. // This allows OutlineFS's profile to be used for annotation during
  1410. // top-down processing of functions' annotation.
  1411. FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee);
  1412. OutlineFS->merge(*FS, 1);
  1413. // Set outlined profile to be synthetic to not bias the inliner.
  1414. OutlineFS->SetContextSynthetic();
  1415. }
  1416. } else {
  1417. auto pair =
  1418. notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
  1419. pair.first->second.entryCount += FS->getHeadSamplesEstimate();
  1420. }
  1421. }
  1422. }
  1423. /// Returns the sorted CallTargetMap \p M by count in descending order.
  1424. static SmallVector<InstrProfValueData, 2>
  1425. GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) {
  1426. SmallVector<InstrProfValueData, 2> R;
  1427. for (const auto &I : SampleRecord::SortCallTargets(M)) {
  1428. R.emplace_back(
  1429. InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
  1430. }
  1431. return R;
  1432. }
  1433. // Generate MD_prof metadata for every branch instruction using the
  1434. // edge weights computed during propagation.
  1435. void SampleProfileLoader::generateMDProfMetadata(Function &F) {
  1436. // Generate MD_prof metadata for every branch instruction using the
  1437. // edge weights computed during propagation.
  1438. LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
  1439. LLVMContext &Ctx = F.getContext();
  1440. MDBuilder MDB(Ctx);
  1441. for (auto &BI : F) {
  1442. BasicBlock *BB = &BI;
  1443. if (BlockWeights[BB]) {
  1444. for (auto &I : *BB) {
  1445. if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
  1446. continue;
  1447. if (!cast<CallBase>(I).getCalledFunction()) {
  1448. const DebugLoc &DLoc = I.getDebugLoc();
  1449. if (!DLoc)
  1450. continue;
  1451. const DILocation *DIL = DLoc;
  1452. const FunctionSamples *FS = findFunctionSamples(I);
  1453. if (!FS)
  1454. continue;
  1455. auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
  1456. auto T = FS->findCallTargetMapAt(CallSite);
  1457. if (!T || T.get().empty())
  1458. continue;
  1459. if (FunctionSamples::ProfileIsProbeBased) {
  1460. // Prorate the callsite counts based on the pre-ICP distribution
  1461. // factor to reflect what is already done to the callsite before
  1462. // ICP, such as calliste cloning.
  1463. if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
  1464. if (Probe->Factor < 1)
  1465. T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
  1466. }
  1467. }
  1468. SmallVector<InstrProfValueData, 2> SortedCallTargets =
  1469. GetSortedValueDataFromCallTargets(T.get());
  1470. uint64_t Sum = 0;
  1471. for (const auto &C : T.get())
  1472. Sum += C.second;
  1473. // With CSSPGO all indirect call targets are counted torwards the
  1474. // original indirect call site in the profile, including both
  1475. // inlined and non-inlined targets.
  1476. if (!FunctionSamples::ProfileIsCS) {
  1477. if (const FunctionSamplesMap *M =
  1478. FS->findFunctionSamplesMapAt(CallSite)) {
  1479. for (const auto &NameFS : *M)
  1480. Sum += NameFS.second.getHeadSamplesEstimate();
  1481. }
  1482. }
  1483. if (Sum)
  1484. updateIDTMetaData(I, SortedCallTargets, Sum);
  1485. else if (OverwriteExistingWeights)
  1486. I.setMetadata(LLVMContext::MD_prof, nullptr);
  1487. } else if (!isa<IntrinsicInst>(&I)) {
  1488. I.setMetadata(LLVMContext::MD_prof,
  1489. MDB.createBranchWeights(
  1490. {static_cast<uint32_t>(BlockWeights[BB])}));
  1491. }
  1492. }
  1493. } else if (OverwriteExistingWeights || ProfileSampleBlockAccurate) {
  1494. // Set profile metadata (possibly annotated by LTO prelink) to zero or
  1495. // clear it for cold code.
  1496. for (auto &I : *BB) {
  1497. if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
  1498. if (cast<CallBase>(I).isIndirectCall())
  1499. I.setMetadata(LLVMContext::MD_prof, nullptr);
  1500. else
  1501. I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(0));
  1502. }
  1503. }
  1504. }
  1505. Instruction *TI = BB->getTerminator();
  1506. if (TI->getNumSuccessors() == 1)
  1507. continue;
  1508. if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI) &&
  1509. !isa<IndirectBrInst>(TI))
  1510. continue;
  1511. DebugLoc BranchLoc = TI->getDebugLoc();
  1512. LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
  1513. << ((BranchLoc) ? Twine(BranchLoc.getLine())
  1514. : Twine("<UNKNOWN LOCATION>"))
  1515. << ".\n");
  1516. SmallVector<uint32_t, 4> Weights;
  1517. uint32_t MaxWeight = 0;
  1518. Instruction *MaxDestInst;
  1519. // Since profi treats multiple edges (multiway branches) as a single edge,
  1520. // we need to distribute the computed weight among the branches. We do
  1521. // this by evenly splitting the edge weight among destinations.
  1522. DenseMap<const BasicBlock *, uint64_t> EdgeMultiplicity;
  1523. std::vector<uint64_t> EdgeIndex;
  1524. if (SampleProfileUseProfi) {
  1525. EdgeIndex.resize(TI->getNumSuccessors());
  1526. for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
  1527. const BasicBlock *Succ = TI->getSuccessor(I);
  1528. EdgeIndex[I] = EdgeMultiplicity[Succ];
  1529. EdgeMultiplicity[Succ]++;
  1530. }
  1531. }
  1532. for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
  1533. BasicBlock *Succ = TI->getSuccessor(I);
  1534. Edge E = std::make_pair(BB, Succ);
  1535. uint64_t Weight = EdgeWeights[E];
  1536. LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
  1537. // Use uint32_t saturated arithmetic to adjust the incoming weights,
  1538. // if needed. Sample counts in profiles are 64-bit unsigned values,
  1539. // but internally branch weights are expressed as 32-bit values.
  1540. if (Weight > std::numeric_limits<uint32_t>::max()) {
  1541. LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
  1542. Weight = std::numeric_limits<uint32_t>::max();
  1543. }
  1544. if (!SampleProfileUseProfi) {
  1545. // Weight is added by one to avoid propagation errors introduced by
  1546. // 0 weights.
  1547. Weights.push_back(static_cast<uint32_t>(Weight + 1));
  1548. } else {
  1549. // Profi creates proper weights that do not require "+1" adjustments but
  1550. // we evenly split the weight among branches with the same destination.
  1551. uint64_t W = Weight / EdgeMultiplicity[Succ];
  1552. // Rounding up, if needed, so that first branches are hotter.
  1553. if (EdgeIndex[I] < Weight % EdgeMultiplicity[Succ])
  1554. W++;
  1555. Weights.push_back(static_cast<uint32_t>(W));
  1556. }
  1557. if (Weight != 0) {
  1558. if (Weight > MaxWeight) {
  1559. MaxWeight = Weight;
  1560. MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
  1561. }
  1562. }
  1563. }
  1564. misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
  1565. uint64_t TempWeight;
  1566. // Only set weights if there is at least one non-zero weight.
  1567. // In any other case, let the analyzer set weights.
  1568. // Do not set weights if the weights are present unless under
  1569. // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
  1570. // twice. If the first annotation already set the weights, the second pass
  1571. // does not need to set it. With OverwriteExistingWeights, Blocks with zero
  1572. // weight should have their existing metadata (possibly annotated by LTO
  1573. // prelink) cleared.
  1574. if (MaxWeight > 0 &&
  1575. (!TI->extractProfTotalWeight(TempWeight) || OverwriteExistingWeights)) {
  1576. LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
  1577. TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
  1578. ORE->emit([&]() {
  1579. return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
  1580. << "most popular destination for conditional branches at "
  1581. << ore::NV("CondBranchesLoc", BranchLoc);
  1582. });
  1583. } else {
  1584. if (OverwriteExistingWeights) {
  1585. TI->setMetadata(LLVMContext::MD_prof, nullptr);
  1586. LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
  1587. } else {
  1588. LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
  1589. }
  1590. }
  1591. }
  1592. }
  1593. /// Once all the branch weights are computed, we emit the MD_prof
  1594. /// metadata on BB using the computed values for each of its branches.
  1595. ///
  1596. /// \param F The function to query.
  1597. ///
  1598. /// \returns true if \p F was modified. Returns false, otherwise.
  1599. bool SampleProfileLoader::emitAnnotations(Function &F) {
  1600. bool Changed = false;
  1601. if (FunctionSamples::ProfileIsProbeBased) {
  1602. if (!ProbeManager->profileIsValid(F, *Samples)) {
  1603. LLVM_DEBUG(
  1604. dbgs() << "Profile is invalid due to CFG mismatch for Function "
  1605. << F.getName());
  1606. ++NumMismatchedProfile;
  1607. return false;
  1608. }
  1609. ++NumMatchedProfile;
  1610. } else {
  1611. if (getFunctionLoc(F) == 0)
  1612. return false;
  1613. LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
  1614. << F.getName() << ": " << getFunctionLoc(F) << "\n");
  1615. }
  1616. DenseSet<GlobalValue::GUID> InlinedGUIDs;
  1617. if (CallsitePrioritizedInline)
  1618. Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
  1619. else
  1620. Changed |= inlineHotFunctions(F, InlinedGUIDs);
  1621. Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
  1622. if (Changed)
  1623. generateMDProfMetadata(F);
  1624. emitCoverageRemarks(F);
  1625. return Changed;
  1626. }
  1627. std::unique_ptr<ProfiledCallGraph>
  1628. SampleProfileLoader::buildProfiledCallGraph(CallGraph &CG) {
  1629. std::unique_ptr<ProfiledCallGraph> ProfiledCG;
  1630. if (FunctionSamples::ProfileIsCS)
  1631. ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
  1632. else
  1633. ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
  1634. // Add all functions into the profiled call graph even if they are not in
  1635. // the profile. This makes sure functions missing from the profile still
  1636. // gets a chance to be processed.
  1637. for (auto &Node : CG) {
  1638. const auto *F = Node.first;
  1639. if (!F || F->isDeclaration() || !F->hasFnAttribute("use-sample-profile"))
  1640. continue;
  1641. ProfiledCG->addProfiledFunction(FunctionSamples::getCanonicalFnName(*F));
  1642. }
  1643. return ProfiledCG;
  1644. }
  1645. std::vector<Function *>
  1646. SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
  1647. std::vector<Function *> FunctionOrderList;
  1648. FunctionOrderList.reserve(M.size());
  1649. if (!ProfileTopDownLoad && UseProfiledCallGraph)
  1650. errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
  1651. "together with -sample-profile-top-down-load.\n";
  1652. if (!ProfileTopDownLoad || CG == nullptr) {
  1653. if (ProfileMergeInlinee) {
  1654. // Disable ProfileMergeInlinee if profile is not loaded in top down order,
  1655. // because the profile for a function may be used for the profile
  1656. // annotation of its outline copy before the profile merging of its
  1657. // non-inlined inline instances, and that is not the way how
  1658. // ProfileMergeInlinee is supposed to work.
  1659. ProfileMergeInlinee = false;
  1660. }
  1661. for (Function &F : M)
  1662. if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
  1663. FunctionOrderList.push_back(&F);
  1664. return FunctionOrderList;
  1665. }
  1666. assert(&CG->getModule() == &M);
  1667. if (UseProfiledCallGraph || (FunctionSamples::ProfileIsCS &&
  1668. !UseProfiledCallGraph.getNumOccurrences())) {
  1669. // Use profiled call edges to augment the top-down order. There are cases
  1670. // that the top-down order computed based on the static call graph doesn't
  1671. // reflect real execution order. For example
  1672. //
  1673. // 1. Incomplete static call graph due to unknown indirect call targets.
  1674. // Adjusting the order by considering indirect call edges from the
  1675. // profile can enable the inlining of indirect call targets by allowing
  1676. // the caller processed before them.
  1677. // 2. Mutual call edges in an SCC. The static processing order computed for
  1678. // an SCC may not reflect the call contexts in the context-sensitive
  1679. // profile, thus may cause potential inlining to be overlooked. The
  1680. // function order in one SCC is being adjusted to a top-down order based
  1681. // on the profile to favor more inlining. This is only a problem with CS
  1682. // profile.
  1683. // 3. Transitive indirect call edges due to inlining. When a callee function
  1684. // (say B) is inlined into into a caller function (say A) in LTO prelink,
  1685. // every call edge originated from the callee B will be transferred to
  1686. // the caller A. If any transferred edge (say A->C) is indirect, the
  1687. // original profiled indirect edge B->C, even if considered, would not
  1688. // enforce a top-down order from the caller A to the potential indirect
  1689. // call target C in LTO postlink since the inlined callee B is gone from
  1690. // the static call graph.
  1691. // 4. #3 can happen even for direct call targets, due to functions defined
  1692. // in header files. A header function (say A), when included into source
  1693. // files, is defined multiple times but only one definition survives due
  1694. // to ODR. Therefore, the LTO prelink inlining done on those dropped
  1695. // definitions can be useless based on a local file scope. More
  1696. // importantly, the inlinee (say B), once fully inlined to a
  1697. // to-be-dropped A, will have no profile to consume when its outlined
  1698. // version is compiled. This can lead to a profile-less prelink
  1699. // compilation for the outlined version of B which may be called from
  1700. // external modules. while this isn't easy to fix, we rely on the
  1701. // postlink AutoFDO pipeline to optimize B. Since the survived copy of
  1702. // the A can be inlined in its local scope in prelink, it may not exist
  1703. // in the merged IR in postlink, and we'll need the profiled call edges
  1704. // to enforce a top-down order for the rest of the functions.
  1705. //
  1706. // Considering those cases, a profiled call graph completely independent of
  1707. // the static call graph is constructed based on profile data, where
  1708. // function objects are not even needed to handle case #3 and case 4.
  1709. //
  1710. // Note that static callgraph edges are completely ignored since they
  1711. // can be conflicting with profiled edges for cyclic SCCs and may result in
  1712. // an SCC order incompatible with profile-defined one. Using strictly
  1713. // profile order ensures a maximum inlining experience. On the other hand,
  1714. // static call edges are not so important when they don't correspond to a
  1715. // context in the profile.
  1716. std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(*CG);
  1717. scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get());
  1718. while (!CGI.isAtEnd()) {
  1719. auto Range = *CGI;
  1720. if (SortProfiledSCC) {
  1721. // Sort nodes in one SCC based on callsite hotness.
  1722. scc_member_iterator<ProfiledCallGraph *> SI(*CGI);
  1723. Range = *SI;
  1724. }
  1725. for (auto *Node : Range) {
  1726. Function *F = SymbolMap.lookup(Node->Name);
  1727. if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
  1728. FunctionOrderList.push_back(F);
  1729. }
  1730. ++CGI;
  1731. }
  1732. } else {
  1733. scc_iterator<CallGraph *> CGI = scc_begin(CG);
  1734. while (!CGI.isAtEnd()) {
  1735. for (CallGraphNode *Node : *CGI) {
  1736. auto *F = Node->getFunction();
  1737. if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
  1738. FunctionOrderList.push_back(F);
  1739. }
  1740. ++CGI;
  1741. }
  1742. }
  1743. LLVM_DEBUG({
  1744. dbgs() << "Function processing order:\n";
  1745. for (auto F : reverse(FunctionOrderList)) {
  1746. dbgs() << F->getName() << "\n";
  1747. }
  1748. });
  1749. std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
  1750. return FunctionOrderList;
  1751. }
  1752. bool SampleProfileLoader::doInitialization(Module &M,
  1753. FunctionAnalysisManager *FAM) {
  1754. auto &Ctx = M.getContext();
  1755. auto ReaderOrErr = SampleProfileReader::create(
  1756. Filename, Ctx, FSDiscriminatorPass::Base, RemappingFilename);
  1757. if (std::error_code EC = ReaderOrErr.getError()) {
  1758. std::string Msg = "Could not open profile: " + EC.message();
  1759. Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
  1760. return false;
  1761. }
  1762. Reader = std::move(ReaderOrErr.get());
  1763. Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
  1764. // set module before reading the profile so reader may be able to only
  1765. // read the function profiles which are used by the current module.
  1766. Reader->setModule(&M);
  1767. if (std::error_code EC = Reader->read()) {
  1768. std::string Msg = "profile reading failed: " + EC.message();
  1769. Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
  1770. return false;
  1771. }
  1772. PSL = Reader->getProfileSymbolList();
  1773. // While profile-sample-accurate is on, ignore symbol list.
  1774. ProfAccForSymsInList =
  1775. ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
  1776. if (ProfAccForSymsInList) {
  1777. NamesInProfile.clear();
  1778. if (auto NameTable = Reader->getNameTable())
  1779. NamesInProfile.insert(NameTable->begin(), NameTable->end());
  1780. CoverageTracker.setProfAccForSymsInList(true);
  1781. }
  1782. if (FAM && !ProfileInlineReplayFile.empty()) {
  1783. ExternalInlineAdvisor = getReplayInlineAdvisor(
  1784. M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr,
  1785. ReplayInlinerSettings{ProfileInlineReplayFile,
  1786. ProfileInlineReplayScope,
  1787. ProfileInlineReplayFallback,
  1788. {ProfileInlineReplayFormat}},
  1789. /*EmitRemarks=*/false, InlineContext{LTOPhase, InlinePass::ReplaySampleProfileInliner});
  1790. }
  1791. // Apply tweaks if context-sensitive or probe-based profile is available.
  1792. if (Reader->profileIsCS() || Reader->profileIsPreInlined() ||
  1793. Reader->profileIsProbeBased()) {
  1794. if (!UseIterativeBFIInference.getNumOccurrences())
  1795. UseIterativeBFIInference = true;
  1796. if (!SampleProfileUseProfi.getNumOccurrences())
  1797. SampleProfileUseProfi = true;
  1798. if (!EnableExtTspBlockPlacement.getNumOccurrences())
  1799. EnableExtTspBlockPlacement = true;
  1800. // Enable priority-base inliner and size inline by default for CSSPGO.
  1801. if (!ProfileSizeInline.getNumOccurrences())
  1802. ProfileSizeInline = true;
  1803. if (!CallsitePrioritizedInline.getNumOccurrences())
  1804. CallsitePrioritizedInline = true;
  1805. // For CSSPGO, we also allow recursive inline to best use context profile.
  1806. if (!AllowRecursiveInline.getNumOccurrences())
  1807. AllowRecursiveInline = true;
  1808. if (Reader->profileIsPreInlined()) {
  1809. if (!UsePreInlinerDecision.getNumOccurrences())
  1810. UsePreInlinerDecision = true;
  1811. }
  1812. if (!Reader->profileIsCS()) {
  1813. // Non-CS profile should be fine without a function size budget for the
  1814. // inliner since the contexts in the profile are either all from inlining
  1815. // in the prevoius build or pre-computed by the preinliner with a size
  1816. // cap, thus they are bounded.
  1817. if (!ProfileInlineLimitMin.getNumOccurrences())
  1818. ProfileInlineLimitMin = std::numeric_limits<unsigned>::max();
  1819. if (!ProfileInlineLimitMax.getNumOccurrences())
  1820. ProfileInlineLimitMax = std::numeric_limits<unsigned>::max();
  1821. }
  1822. }
  1823. if (Reader->profileIsCS()) {
  1824. // Tracker for profiles under different context
  1825. ContextTracker = std::make_unique<SampleContextTracker>(
  1826. Reader->getProfiles(), &GUIDToFuncNameMap);
  1827. }
  1828. // Load pseudo probe descriptors for probe-based function samples.
  1829. if (Reader->profileIsProbeBased()) {
  1830. ProbeManager = std::make_unique<PseudoProbeManager>(M);
  1831. if (!ProbeManager->moduleIsProbed(M)) {
  1832. const char *Msg =
  1833. "Pseudo-probe-based profile requires SampleProfileProbePass";
  1834. Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg,
  1835. DS_Warning));
  1836. return false;
  1837. }
  1838. }
  1839. if (ReportProfileStaleness || PersistProfileStaleness) {
  1840. MatchingManager =
  1841. std::make_unique<SampleProfileMatcher>(M, *Reader, ProbeManager.get());
  1842. }
  1843. return true;
  1844. }
  1845. void SampleProfileMatcher::detectProfileMismatch(const Function &F,
  1846. const FunctionSamples &FS) {
  1847. if (FunctionSamples::ProfileIsProbeBased) {
  1848. uint64_t Count = FS.getTotalSamples();
  1849. TotalFuncHashSamples += Count;
  1850. TotalProfiledFunc++;
  1851. if (!ProbeManager->profileIsValid(F, FS)) {
  1852. MismatchedFuncHashSamples += Count;
  1853. NumMismatchedFuncHash++;
  1854. return;
  1855. }
  1856. }
  1857. std::unordered_set<LineLocation, LineLocationHash> MatchedCallsiteLocs;
  1858. // Go through all the callsites on the IR and flag the callsite if the target
  1859. // name is the same as the one in the profile.
  1860. for (auto &BB : F) {
  1861. for (auto &I : BB) {
  1862. if (!isa<CallBase>(&I) || isa<IntrinsicInst>(&I))
  1863. continue;
  1864. const auto *CB = dyn_cast<CallBase>(&I);
  1865. if (auto &DLoc = I.getDebugLoc()) {
  1866. LineLocation IRCallsite = FunctionSamples::getCallSiteIdentifier(DLoc);
  1867. StringRef CalleeName;
  1868. if (Function *Callee = CB->getCalledFunction())
  1869. CalleeName = FunctionSamples::getCanonicalFnName(Callee->getName());
  1870. const auto CTM = FS.findCallTargetMapAt(IRCallsite);
  1871. const auto CallsiteFS = FS.findFunctionSamplesMapAt(IRCallsite);
  1872. // Indirect call case.
  1873. if (CalleeName.empty()) {
  1874. // Since indirect call does not have the CalleeName, check
  1875. // conservatively if callsite in the profile is a callsite location.
  1876. // This is to avoid nums of false positive since otherwise all the
  1877. // indirect call samples will be reported as mismatching.
  1878. if ((CTM && !CTM->empty()) || (CallsiteFS && !CallsiteFS->empty()))
  1879. MatchedCallsiteLocs.insert(IRCallsite);
  1880. } else {
  1881. // Check if the call target name is matched for direct call case.
  1882. if ((CTM && CTM->count(CalleeName)) ||
  1883. (CallsiteFS && CallsiteFS->count(CalleeName)))
  1884. MatchedCallsiteLocs.insert(IRCallsite);
  1885. }
  1886. }
  1887. }
  1888. }
  1889. auto isInvalidLineOffset = [](uint32_t LineOffset) {
  1890. return LineOffset & 0x8000;
  1891. };
  1892. // Check if there are any callsites in the profile that does not match to any
  1893. // IR callsites, those callsite samples will be discarded.
  1894. for (auto &I : FS.getBodySamples()) {
  1895. const LineLocation &Loc = I.first;
  1896. if (isInvalidLineOffset(Loc.LineOffset))
  1897. continue;
  1898. uint64_t Count = I.second.getSamples();
  1899. if (!I.second.getCallTargets().empty()) {
  1900. TotalCallsiteSamples += Count;
  1901. TotalProfiledCallsites++;
  1902. if (!MatchedCallsiteLocs.count(Loc)) {
  1903. MismatchedCallsiteSamples += Count;
  1904. NumMismatchedCallsites++;
  1905. }
  1906. }
  1907. }
  1908. for (auto &I : FS.getCallsiteSamples()) {
  1909. const LineLocation &Loc = I.first;
  1910. if (isInvalidLineOffset(Loc.LineOffset))
  1911. continue;
  1912. uint64_t Count = 0;
  1913. for (auto &FM : I.second) {
  1914. Count += FM.second.getHeadSamplesEstimate();
  1915. }
  1916. TotalCallsiteSamples += Count;
  1917. TotalProfiledCallsites++;
  1918. if (!MatchedCallsiteLocs.count(Loc)) {
  1919. MismatchedCallsiteSamples += Count;
  1920. NumMismatchedCallsites++;
  1921. }
  1922. }
  1923. }
  1924. void SampleProfileMatcher::detectProfileMismatch() {
  1925. for (auto &F : M) {
  1926. if (F.isDeclaration() || !F.hasFnAttribute("use-sample-profile"))
  1927. continue;
  1928. FunctionSamples *FS = Reader.getSamplesFor(F);
  1929. if (!FS)
  1930. continue;
  1931. detectProfileMismatch(F, *FS);
  1932. }
  1933. if (ReportProfileStaleness) {
  1934. if (FunctionSamples::ProfileIsProbeBased) {
  1935. errs() << "(" << NumMismatchedFuncHash << "/" << TotalProfiledFunc << ")"
  1936. << " of functions' profile are invalid and "
  1937. << " (" << MismatchedFuncHashSamples << "/" << TotalFuncHashSamples
  1938. << ")"
  1939. << " of samples are discarded due to function hash mismatch.\n";
  1940. }
  1941. errs() << "(" << NumMismatchedCallsites << "/" << TotalProfiledCallsites
  1942. << ")"
  1943. << " of callsites' profile are invalid and "
  1944. << "(" << MismatchedCallsiteSamples << "/" << TotalCallsiteSamples
  1945. << ")"
  1946. << " of samples are discarded due to callsite location mismatch.\n";
  1947. }
  1948. if (PersistProfileStaleness) {
  1949. LLVMContext &Ctx = M.getContext();
  1950. MDBuilder MDB(Ctx);
  1951. SmallVector<std::pair<StringRef, uint64_t>> ProfStatsVec;
  1952. if (FunctionSamples::ProfileIsProbeBased) {
  1953. ProfStatsVec.emplace_back("NumMismatchedFuncHash", NumMismatchedFuncHash);
  1954. ProfStatsVec.emplace_back("TotalProfiledFunc", TotalProfiledFunc);
  1955. ProfStatsVec.emplace_back("MismatchedFuncHashSamples",
  1956. MismatchedFuncHashSamples);
  1957. ProfStatsVec.emplace_back("TotalFuncHashSamples", TotalFuncHashSamples);
  1958. }
  1959. ProfStatsVec.emplace_back("NumMismatchedCallsites", NumMismatchedCallsites);
  1960. ProfStatsVec.emplace_back("TotalProfiledCallsites", TotalProfiledCallsites);
  1961. ProfStatsVec.emplace_back("MismatchedCallsiteSamples",
  1962. MismatchedCallsiteSamples);
  1963. ProfStatsVec.emplace_back("TotalCallsiteSamples", TotalCallsiteSamples);
  1964. auto *MD = MDB.createLLVMStats(ProfStatsVec);
  1965. auto *NMD = M.getOrInsertNamedMetadata("llvm.stats");
  1966. NMD->addOperand(MD);
  1967. }
  1968. }
  1969. bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
  1970. ProfileSummaryInfo *_PSI, CallGraph *CG) {
  1971. GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
  1972. PSI = _PSI;
  1973. if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
  1974. M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
  1975. ProfileSummary::PSK_Sample);
  1976. PSI->refresh();
  1977. }
  1978. // Compute the total number of samples collected in this profile.
  1979. for (const auto &I : Reader->getProfiles())
  1980. TotalCollectedSamples += I.second.getTotalSamples();
  1981. auto Remapper = Reader->getRemapper();
  1982. // Populate the symbol map.
  1983. for (const auto &N_F : M.getValueSymbolTable()) {
  1984. StringRef OrigName = N_F.getKey();
  1985. Function *F = dyn_cast<Function>(N_F.getValue());
  1986. if (F == nullptr || OrigName.empty())
  1987. continue;
  1988. SymbolMap[OrigName] = F;
  1989. StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
  1990. if (OrigName != NewName && !NewName.empty()) {
  1991. auto r = SymbolMap.insert(std::make_pair(NewName, F));
  1992. // Failiing to insert means there is already an entry in SymbolMap,
  1993. // thus there are multiple functions that are mapped to the same
  1994. // stripped name. In this case of name conflicting, set the value
  1995. // to nullptr to avoid confusion.
  1996. if (!r.second)
  1997. r.first->second = nullptr;
  1998. OrigName = NewName;
  1999. }
  2000. // Insert the remapped names into SymbolMap.
  2001. if (Remapper) {
  2002. if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
  2003. if (*MapName != OrigName && !MapName->empty())
  2004. SymbolMap.insert(std::make_pair(*MapName, F));
  2005. }
  2006. }
  2007. }
  2008. assert(SymbolMap.count(StringRef()) == 0 &&
  2009. "No empty StringRef should be added in SymbolMap");
  2010. if (ReportProfileStaleness || PersistProfileStaleness)
  2011. MatchingManager->detectProfileMismatch();
  2012. bool retval = false;
  2013. for (auto *F : buildFunctionOrder(M, CG)) {
  2014. assert(!F->isDeclaration());
  2015. clearFunctionData();
  2016. retval |= runOnFunction(*F, AM);
  2017. }
  2018. // Account for cold calls not inlined....
  2019. if (!FunctionSamples::ProfileIsCS)
  2020. for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
  2021. notInlinedCallInfo)
  2022. updateProfileCallee(pair.first, pair.second.entryCount);
  2023. return retval;
  2024. }
  2025. bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
  2026. LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
  2027. DILocation2SampleMap.clear();
  2028. // By default the entry count is initialized to -1, which will be treated
  2029. // conservatively by getEntryCount as the same as unknown (None). This is
  2030. // to avoid newly added code to be treated as cold. If we have samples
  2031. // this will be overwritten in emitAnnotations.
  2032. uint64_t initialEntryCount = -1;
  2033. ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
  2034. if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
  2035. // initialize all the function entry counts to 0. It means all the
  2036. // functions without profile will be regarded as cold.
  2037. initialEntryCount = 0;
  2038. // profile-sample-accurate is a user assertion which has a higher precedence
  2039. // than symbol list. When profile-sample-accurate is on, ignore symbol list.
  2040. ProfAccForSymsInList = false;
  2041. }
  2042. CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
  2043. // PSL -- profile symbol list include all the symbols in sampled binary.
  2044. // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
  2045. // old functions without samples being cold, without having to worry
  2046. // about new and hot functions being mistakenly treated as cold.
  2047. if (ProfAccForSymsInList) {
  2048. // Initialize the entry count to 0 for functions in the list.
  2049. if (PSL->contains(F.getName()))
  2050. initialEntryCount = 0;
  2051. // Function in the symbol list but without sample will be regarded as
  2052. // cold. To minimize the potential negative performance impact it could
  2053. // have, we want to be a little conservative here saying if a function
  2054. // shows up in the profile, no matter as outline function, inline instance
  2055. // or call targets, treat the function as not being cold. This will handle
  2056. // the cases such as most callsites of a function are inlined in sampled
  2057. // binary but not inlined in current build (because of source code drift,
  2058. // imprecise debug information, or the callsites are all cold individually
  2059. // but not cold accumulatively...), so the outline function showing up as
  2060. // cold in sampled binary will actually not be cold after current build.
  2061. StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
  2062. if (NamesInProfile.count(CanonName))
  2063. initialEntryCount = -1;
  2064. }
  2065. // Initialize entry count when the function has no existing entry
  2066. // count value.
  2067. if (!F.getEntryCount())
  2068. F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
  2069. std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
  2070. if (AM) {
  2071. auto &FAM =
  2072. AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
  2073. .getManager();
  2074. ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  2075. } else {
  2076. OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
  2077. ORE = OwnedORE.get();
  2078. }
  2079. if (FunctionSamples::ProfileIsCS)
  2080. Samples = ContextTracker->getBaseSamplesFor(F);
  2081. else
  2082. Samples = Reader->getSamplesFor(F);
  2083. if (Samples && !Samples->empty())
  2084. return emitAnnotations(F);
  2085. return false;
  2086. }
  2087. PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
  2088. ModuleAnalysisManager &AM) {
  2089. FunctionAnalysisManager &FAM =
  2090. AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  2091. auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
  2092. return FAM.getResult<AssumptionAnalysis>(F);
  2093. };
  2094. auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
  2095. return FAM.getResult<TargetIRAnalysis>(F);
  2096. };
  2097. auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
  2098. return FAM.getResult<TargetLibraryAnalysis>(F);
  2099. };
  2100. SampleProfileLoader SampleLoader(
  2101. ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
  2102. ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
  2103. : ProfileRemappingFileName,
  2104. LTOPhase, GetAssumptionCache, GetTTI, GetTLI);
  2105. if (!SampleLoader.doInitialization(M, &FAM))
  2106. return PreservedAnalyses::all();
  2107. ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
  2108. CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
  2109. if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
  2110. return PreservedAnalyses::all();
  2111. return PreservedAnalyses::none();
  2112. }