SampleProfile.cpp 90 KB

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