SampleProfile.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  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/SmallPtrSet.h"
  29. #include "llvm/ADT/SmallSet.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/StringMap.h"
  32. #include "llvm/ADT/StringRef.h"
  33. #include "llvm/ADT/Twine.h"
  34. #include "llvm/Analysis/AssumptionCache.h"
  35. #include "llvm/Analysis/InlineCost.h"
  36. #include "llvm/Analysis/LoopInfo.h"
  37. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  38. #include "llvm/Analysis/PostDominators.h"
  39. #include "llvm/Analysis/ProfileSummaryInfo.h"
  40. #include "llvm/Analysis/TargetTransformInfo.h"
  41. #include "llvm/IR/BasicBlock.h"
  42. #include "llvm/IR/CFG.h"
  43. #include "llvm/IR/CallSite.h"
  44. #include "llvm/IR/DebugInfoMetadata.h"
  45. #include "llvm/IR/DebugLoc.h"
  46. #include "llvm/IR/DiagnosticInfo.h"
  47. #include "llvm/IR/Dominators.h"
  48. #include "llvm/IR/Function.h"
  49. #include "llvm/IR/GlobalValue.h"
  50. #include "llvm/IR/InstrTypes.h"
  51. #include "llvm/IR/Instruction.h"
  52. #include "llvm/IR/Instructions.h"
  53. #include "llvm/IR/IntrinsicInst.h"
  54. #include "llvm/IR/LLVMContext.h"
  55. #include "llvm/IR/MDBuilder.h"
  56. #include "llvm/IR/Module.h"
  57. #include "llvm/IR/PassManager.h"
  58. #include "llvm/IR/ValueSymbolTable.h"
  59. #include "llvm/Pass.h"
  60. #include "llvm/ProfileData/InstrProf.h"
  61. #include "llvm/ProfileData/SampleProf.h"
  62. #include "llvm/ProfileData/SampleProfReader.h"
  63. #include "llvm/Support/Casting.h"
  64. #include "llvm/Support/CommandLine.h"
  65. #include "llvm/Support/Debug.h"
  66. #include "llvm/Support/ErrorHandling.h"
  67. #include "llvm/Support/ErrorOr.h"
  68. #include "llvm/Support/GenericDomTree.h"
  69. #include "llvm/Support/raw_ostream.h"
  70. #include "llvm/Transforms/IPO.h"
  71. #include "llvm/Transforms/Instrumentation.h"
  72. #include "llvm/Transforms/Utils/CallPromotionUtils.h"
  73. #include "llvm/Transforms/Utils/Cloning.h"
  74. #include "llvm/Transforms/Utils/MisExpect.h"
  75. #include <algorithm>
  76. #include <cassert>
  77. #include <cstdint>
  78. #include <functional>
  79. #include <limits>
  80. #include <map>
  81. #include <memory>
  82. #include <queue>
  83. #include <string>
  84. #include <system_error>
  85. #include <utility>
  86. #include <vector>
  87. using namespace llvm;
  88. using namespace sampleprof;
  89. using ProfileCount = Function::ProfileCount;
  90. #define DEBUG_TYPE "sample-profile"
  91. // Command line option to specify the file to read samples from. This is
  92. // mainly used for debugging.
  93. static cl::opt<std::string> SampleProfileFile(
  94. "sample-profile-file", cl::init(""), cl::value_desc("filename"),
  95. cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
  96. // The named file contains a set of transformations that may have been applied
  97. // to the symbol names between the program from which the sample data was
  98. // collected and the current program's symbols.
  99. static cl::opt<std::string> SampleProfileRemappingFile(
  100. "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
  101. cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
  102. static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
  103. "sample-profile-max-propagate-iterations", cl::init(100),
  104. cl::desc("Maximum number of iterations to go through when propagating "
  105. "sample block/edge weights through the CFG."));
  106. static cl::opt<unsigned> SampleProfileRecordCoverage(
  107. "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
  108. cl::desc("Emit a warning if less than N% of records in the input profile "
  109. "are matched to the IR."));
  110. static cl::opt<unsigned> SampleProfileSampleCoverage(
  111. "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
  112. cl::desc("Emit a warning if less than N% of samples in the input profile "
  113. "are matched to the IR."));
  114. static cl::opt<bool> NoWarnSampleUnused(
  115. "no-warn-sample-unused", cl::init(false), cl::Hidden,
  116. cl::desc("Use this option to turn off/on warnings about function with "
  117. "samples but without debug information to use those samples. "));
  118. static cl::opt<bool> ProfileSampleAccurate(
  119. "profile-sample-accurate", cl::Hidden, cl::init(false),
  120. cl::desc("If the sample profile is accurate, we will mark all un-sampled "
  121. "callsite and function as having 0 samples. Otherwise, treat "
  122. "un-sampled callsites and functions conservatively as unknown. "));
  123. namespace {
  124. using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
  125. using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
  126. using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
  127. using EdgeWeightMap = DenseMap<Edge, uint64_t>;
  128. using BlockEdgeMap =
  129. DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
  130. class SampleCoverageTracker {
  131. public:
  132. SampleCoverageTracker() = default;
  133. bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
  134. uint32_t Discriminator, uint64_t Samples);
  135. unsigned computeCoverage(unsigned Used, unsigned Total) const;
  136. unsigned countUsedRecords(const FunctionSamples *FS,
  137. ProfileSummaryInfo *PSI) const;
  138. unsigned countBodyRecords(const FunctionSamples *FS,
  139. ProfileSummaryInfo *PSI) const;
  140. uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
  141. uint64_t countBodySamples(const FunctionSamples *FS,
  142. ProfileSummaryInfo *PSI) const;
  143. void clear() {
  144. SampleCoverage.clear();
  145. TotalUsedSamples = 0;
  146. }
  147. private:
  148. using BodySampleCoverageMap = std::map<LineLocation, unsigned>;
  149. using FunctionSamplesCoverageMap =
  150. DenseMap<const FunctionSamples *, BodySampleCoverageMap>;
  151. /// Coverage map for sampling records.
  152. ///
  153. /// This map keeps a record of sampling records that have been matched to
  154. /// an IR instruction. This is used to detect some form of staleness in
  155. /// profiles (see flag -sample-profile-check-coverage).
  156. ///
  157. /// Each entry in the map corresponds to a FunctionSamples instance. This is
  158. /// another map that counts how many times the sample record at the
  159. /// given location has been used.
  160. FunctionSamplesCoverageMap SampleCoverage;
  161. /// Number of samples used from the profile.
  162. ///
  163. /// When a sampling record is used for the first time, the samples from
  164. /// that record are added to this accumulator. Coverage is later computed
  165. /// based on the total number of samples available in this function and
  166. /// its callsites.
  167. ///
  168. /// Note that this accumulator tracks samples used from a single function
  169. /// and all the inlined callsites. Strictly, we should have a map of counters
  170. /// keyed by FunctionSamples pointers, but these stats are cleared after
  171. /// every function, so we just need to keep a single counter.
  172. uint64_t TotalUsedSamples = 0;
  173. };
  174. class GUIDToFuncNameMapper {
  175. public:
  176. GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
  177. DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
  178. : CurrentReader(Reader), CurrentModule(M),
  179. CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
  180. if (CurrentReader.getFormat() != SPF_Compact_Binary)
  181. return;
  182. for (const auto &F : CurrentModule) {
  183. StringRef OrigName = F.getName();
  184. CurrentGUIDToFuncNameMap.insert(
  185. {Function::getGUID(OrigName), OrigName});
  186. // Local to global var promotion used by optimization like thinlto
  187. // will rename the var and add suffix like ".llvm.xxx" to the
  188. // original local name. In sample profile, the suffixes of function
  189. // names are all stripped. Since it is possible that the mapper is
  190. // built in post-thin-link phase and var promotion has been done,
  191. // we need to add the substring of function name without the suffix
  192. // into the GUIDToFuncNameMap.
  193. StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
  194. if (CanonName != OrigName)
  195. CurrentGUIDToFuncNameMap.insert(
  196. {Function::getGUID(CanonName), CanonName});
  197. }
  198. // Update GUIDToFuncNameMap for each function including inlinees.
  199. SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
  200. }
  201. ~GUIDToFuncNameMapper() {
  202. if (CurrentReader.getFormat() != SPF_Compact_Binary)
  203. return;
  204. CurrentGUIDToFuncNameMap.clear();
  205. // Reset GUIDToFuncNameMap for of each function as they're no
  206. // longer valid at this point.
  207. SetGUIDToFuncNameMapForAll(nullptr);
  208. }
  209. private:
  210. void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
  211. std::queue<FunctionSamples *> FSToUpdate;
  212. for (auto &IFS : CurrentReader.getProfiles()) {
  213. FSToUpdate.push(&IFS.second);
  214. }
  215. while (!FSToUpdate.empty()) {
  216. FunctionSamples *FS = FSToUpdate.front();
  217. FSToUpdate.pop();
  218. FS->GUIDToFuncNameMap = Map;
  219. for (const auto &ICS : FS->getCallsiteSamples()) {
  220. const FunctionSamplesMap &FSMap = ICS.second;
  221. for (auto &IFS : FSMap) {
  222. FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
  223. FSToUpdate.push(&FS);
  224. }
  225. }
  226. }
  227. }
  228. SampleProfileReader &CurrentReader;
  229. Module &CurrentModule;
  230. DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
  231. };
  232. /// Sample profile pass.
  233. ///
  234. /// This pass reads profile data from the file specified by
  235. /// -sample-profile-file and annotates every affected function with the
  236. /// profile information found in that file.
  237. class SampleProfileLoader {
  238. public:
  239. SampleProfileLoader(
  240. StringRef Name, StringRef RemapName, bool IsThinLTOPreLink,
  241. std::function<AssumptionCache &(Function &)> GetAssumptionCache,
  242. std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo)
  243. : GetAC(std::move(GetAssumptionCache)),
  244. GetTTI(std::move(GetTargetTransformInfo)), Filename(Name),
  245. RemappingFilename(RemapName), IsThinLTOPreLink(IsThinLTOPreLink) {}
  246. bool doInitialization(Module &M);
  247. bool runOnModule(Module &M, ModuleAnalysisManager *AM,
  248. ProfileSummaryInfo *_PSI);
  249. void dump() { Reader->dump(); }
  250. protected:
  251. bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
  252. unsigned getFunctionLoc(Function &F);
  253. bool emitAnnotations(Function &F);
  254. ErrorOr<uint64_t> getInstWeight(const Instruction &I);
  255. ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB);
  256. const FunctionSamples *findCalleeFunctionSamples(const Instruction &I) const;
  257. std::vector<const FunctionSamples *>
  258. findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
  259. mutable DenseMap<const DILocation *, const FunctionSamples *> DILocation2SampleMap;
  260. const FunctionSamples *findFunctionSamples(const Instruction &I) const;
  261. bool inlineCallInstruction(Instruction *I);
  262. bool inlineHotFunctions(Function &F,
  263. DenseSet<GlobalValue::GUID> &InlinedGUIDs);
  264. void printEdgeWeight(raw_ostream &OS, Edge E);
  265. void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
  266. void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
  267. bool computeBlockWeights(Function &F);
  268. void findEquivalenceClasses(Function &F);
  269. template <bool IsPostDom>
  270. void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
  271. DominatorTreeBase<BasicBlock, IsPostDom> *DomTree);
  272. void propagateWeights(Function &F);
  273. uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
  274. void buildEdges(Function &F);
  275. bool propagateThroughEdges(Function &F, bool UpdateBlockCount);
  276. void computeDominanceAndLoopInfo(Function &F);
  277. void clearFunctionData();
  278. /// Map basic blocks to their computed weights.
  279. ///
  280. /// The weight of a basic block is defined to be the maximum
  281. /// of all the instruction weights in that block.
  282. BlockWeightMap BlockWeights;
  283. /// Map edges to their computed weights.
  284. ///
  285. /// Edge weights are computed by propagating basic block weights in
  286. /// SampleProfile::propagateWeights.
  287. EdgeWeightMap EdgeWeights;
  288. /// Set of visited blocks during propagation.
  289. SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
  290. /// Set of visited edges during propagation.
  291. SmallSet<Edge, 32> VisitedEdges;
  292. /// Equivalence classes for block weights.
  293. ///
  294. /// Two blocks BB1 and BB2 are in the same equivalence class if they
  295. /// dominate and post-dominate each other, and they are in the same loop
  296. /// nest. When this happens, the two blocks are guaranteed to execute
  297. /// the same number of times.
  298. EquivalenceClassMap EquivalenceClass;
  299. /// Map from function name to Function *. Used to find the function from
  300. /// the function name. If the function name contains suffix, additional
  301. /// entry is added to map from the stripped name to the function if there
  302. /// is one-to-one mapping.
  303. StringMap<Function *> SymbolMap;
  304. /// Dominance, post-dominance and loop information.
  305. std::unique_ptr<DominatorTree> DT;
  306. std::unique_ptr<PostDominatorTree> PDT;
  307. std::unique_ptr<LoopInfo> LI;
  308. std::function<AssumptionCache &(Function &)> GetAC;
  309. std::function<TargetTransformInfo &(Function &)> GetTTI;
  310. /// Predecessors for each basic block in the CFG.
  311. BlockEdgeMap Predecessors;
  312. /// Successors for each basic block in the CFG.
  313. BlockEdgeMap Successors;
  314. SampleCoverageTracker CoverageTracker;
  315. /// Profile reader object.
  316. std::unique_ptr<SampleProfileReader> Reader;
  317. /// Samples collected for the body of this function.
  318. FunctionSamples *Samples = nullptr;
  319. /// Name of the profile file to load.
  320. std::string Filename;
  321. /// Name of the profile remapping file to load.
  322. std::string RemappingFilename;
  323. /// Flag indicating whether the profile input loaded successfully.
  324. bool ProfileIsValid = false;
  325. /// Flag indicating if the pass is invoked in ThinLTO compile phase.
  326. ///
  327. /// In this phase, in annotation, we should not promote indirect calls.
  328. /// Instead, we will mark GUIDs that needs to be annotated to the function.
  329. bool IsThinLTOPreLink;
  330. /// Profile Summary Info computed from sample profile.
  331. ProfileSummaryInfo *PSI = nullptr;
  332. /// Profle Symbol list tells whether a function name appears in the binary
  333. /// used to generate the current profile.
  334. std::unique_ptr<ProfileSymbolList> PSL;
  335. /// Total number of samples collected in this profile.
  336. ///
  337. /// This is the sum of all the samples collected in all the functions executed
  338. /// at runtime.
  339. uint64_t TotalCollectedSamples = 0;
  340. /// Optimization Remark Emitter used to emit diagnostic remarks.
  341. OptimizationRemarkEmitter *ORE = nullptr;
  342. // Information recorded when we declined to inline a call site
  343. // because we have determined it is too cold is accumulated for
  344. // each callee function. Initially this is just the entry count.
  345. struct NotInlinedProfileInfo {
  346. uint64_t entryCount;
  347. };
  348. DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
  349. // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
  350. // all the function symbols defined or declared in current module.
  351. DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
  352. };
  353. class SampleProfileLoaderLegacyPass : public ModulePass {
  354. public:
  355. // Class identification, replacement for typeinfo
  356. static char ID;
  357. SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile,
  358. bool IsThinLTOPreLink = false)
  359. : ModulePass(ID),
  360. SampleLoader(Name, SampleProfileRemappingFile, IsThinLTOPreLink,
  361. [&](Function &F) -> AssumptionCache & {
  362. return ACT->getAssumptionCache(F);
  363. },
  364. [&](Function &F) -> TargetTransformInfo & {
  365. return TTIWP->getTTI(F);
  366. }) {
  367. initializeSampleProfileLoaderLegacyPassPass(
  368. *PassRegistry::getPassRegistry());
  369. }
  370. void dump() { SampleLoader.dump(); }
  371. bool doInitialization(Module &M) override {
  372. return SampleLoader.doInitialization(M);
  373. }
  374. StringRef getPassName() const override { return "Sample profile pass"; }
  375. bool runOnModule(Module &M) override;
  376. void getAnalysisUsage(AnalysisUsage &AU) const override {
  377. AU.addRequired<AssumptionCacheTracker>();
  378. AU.addRequired<TargetTransformInfoWrapperPass>();
  379. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  380. }
  381. private:
  382. SampleProfileLoader SampleLoader;
  383. AssumptionCacheTracker *ACT = nullptr;
  384. TargetTransformInfoWrapperPass *TTIWP = nullptr;
  385. };
  386. } // end anonymous namespace
  387. /// Return true if the given callsite is hot wrt to hot cutoff threshold.
  388. ///
  389. /// Functions that were inlined in the original binary will be represented
  390. /// in the inline stack in the sample profile. If the profile shows that
  391. /// the original inline decision was "good" (i.e., the callsite is executed
  392. /// frequently), then we will recreate the inline decision and apply the
  393. /// profile from the inlined callsite.
  394. ///
  395. /// To decide whether an inlined callsite is hot, we compare the callsite
  396. /// sample count with the hot cutoff computed by ProfileSummaryInfo, it is
  397. /// regarded as hot if the count is above the cutoff value.
  398. static bool callsiteIsHot(const FunctionSamples *CallsiteFS,
  399. ProfileSummaryInfo *PSI) {
  400. if (!CallsiteFS)
  401. return false; // The callsite was not inlined in the original binary.
  402. assert(PSI && "PSI is expected to be non null");
  403. uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
  404. return PSI->isHotCount(CallsiteTotalSamples);
  405. }
  406. /// Mark as used the sample record for the given function samples at
  407. /// (LineOffset, Discriminator).
  408. ///
  409. /// \returns true if this is the first time we mark the given record.
  410. bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
  411. uint32_t LineOffset,
  412. uint32_t Discriminator,
  413. uint64_t Samples) {
  414. LineLocation Loc(LineOffset, Discriminator);
  415. unsigned &Count = SampleCoverage[FS][Loc];
  416. bool FirstTime = (++Count == 1);
  417. if (FirstTime)
  418. TotalUsedSamples += Samples;
  419. return FirstTime;
  420. }
  421. /// Return the number of sample records that were applied from this profile.
  422. ///
  423. /// This count does not include records from cold inlined callsites.
  424. unsigned
  425. SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS,
  426. ProfileSummaryInfo *PSI) const {
  427. auto I = SampleCoverage.find(FS);
  428. // The size of the coverage map for FS represents the number of records
  429. // that were marked used at least once.
  430. unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
  431. // If there are inlined callsites in this function, count the samples found
  432. // in the respective bodies. However, do not bother counting callees with 0
  433. // total samples, these are callees that were never invoked at runtime.
  434. for (const auto &I : FS->getCallsiteSamples())
  435. for (const auto &J : I.second) {
  436. const FunctionSamples *CalleeSamples = &J.second;
  437. if (callsiteIsHot(CalleeSamples, PSI))
  438. Count += countUsedRecords(CalleeSamples, PSI);
  439. }
  440. return Count;
  441. }
  442. /// Return the number of sample records in the body of this profile.
  443. ///
  444. /// This count does not include records from cold inlined callsites.
  445. unsigned
  446. SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS,
  447. ProfileSummaryInfo *PSI) const {
  448. unsigned Count = FS->getBodySamples().size();
  449. // Only count records in hot callsites.
  450. for (const auto &I : FS->getCallsiteSamples())
  451. for (const auto &J : I.second) {
  452. const FunctionSamples *CalleeSamples = &J.second;
  453. if (callsiteIsHot(CalleeSamples, PSI))
  454. Count += countBodyRecords(CalleeSamples, PSI);
  455. }
  456. return Count;
  457. }
  458. /// Return the number of samples collected in the body of this profile.
  459. ///
  460. /// This count does not include samples from cold inlined callsites.
  461. uint64_t
  462. SampleCoverageTracker::countBodySamples(const FunctionSamples *FS,
  463. ProfileSummaryInfo *PSI) const {
  464. uint64_t Total = 0;
  465. for (const auto &I : FS->getBodySamples())
  466. Total += I.second.getSamples();
  467. // Only count samples in hot callsites.
  468. for (const auto &I : FS->getCallsiteSamples())
  469. for (const auto &J : I.second) {
  470. const FunctionSamples *CalleeSamples = &J.second;
  471. if (callsiteIsHot(CalleeSamples, PSI))
  472. Total += countBodySamples(CalleeSamples, PSI);
  473. }
  474. return Total;
  475. }
  476. /// Return the fraction of sample records used in this profile.
  477. ///
  478. /// The returned value is an unsigned integer in the range 0-100 indicating
  479. /// the percentage of sample records that were used while applying this
  480. /// profile to the associated function.
  481. unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
  482. unsigned Total) const {
  483. assert(Used <= Total &&
  484. "number of used records cannot exceed the total number of records");
  485. return Total > 0 ? Used * 100 / Total : 100;
  486. }
  487. /// Clear all the per-function data used to load samples and propagate weights.
  488. void SampleProfileLoader::clearFunctionData() {
  489. BlockWeights.clear();
  490. EdgeWeights.clear();
  491. VisitedBlocks.clear();
  492. VisitedEdges.clear();
  493. EquivalenceClass.clear();
  494. DT = nullptr;
  495. PDT = nullptr;
  496. LI = nullptr;
  497. Predecessors.clear();
  498. Successors.clear();
  499. CoverageTracker.clear();
  500. }
  501. #ifndef NDEBUG
  502. /// Print the weight of edge \p E on stream \p OS.
  503. ///
  504. /// \param OS Stream to emit the output to.
  505. /// \param E Edge to print.
  506. void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
  507. OS << "weight[" << E.first->getName() << "->" << E.second->getName()
  508. << "]: " << EdgeWeights[E] << "\n";
  509. }
  510. /// Print the equivalence class of block \p BB on stream \p OS.
  511. ///
  512. /// \param OS Stream to emit the output to.
  513. /// \param BB Block to print.
  514. void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
  515. const BasicBlock *BB) {
  516. const BasicBlock *Equiv = EquivalenceClass[BB];
  517. OS << "equivalence[" << BB->getName()
  518. << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
  519. }
  520. /// Print the weight of block \p BB on stream \p OS.
  521. ///
  522. /// \param OS Stream to emit the output to.
  523. /// \param BB Block to print.
  524. void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
  525. const BasicBlock *BB) const {
  526. const auto &I = BlockWeights.find(BB);
  527. uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
  528. OS << "weight[" << BB->getName() << "]: " << W << "\n";
  529. }
  530. #endif
  531. /// Get the weight for an instruction.
  532. ///
  533. /// The "weight" of an instruction \p Inst is the number of samples
  534. /// collected on that instruction at runtime. To retrieve it, we
  535. /// need to compute the line number of \p Inst relative to the start of its
  536. /// function. We use HeaderLineno to compute the offset. We then
  537. /// look up the samples collected for \p Inst using BodySamples.
  538. ///
  539. /// \param Inst Instruction to query.
  540. ///
  541. /// \returns the weight of \p Inst.
  542. ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
  543. const DebugLoc &DLoc = Inst.getDebugLoc();
  544. if (!DLoc)
  545. return std::error_code();
  546. const FunctionSamples *FS = findFunctionSamples(Inst);
  547. if (!FS)
  548. return std::error_code();
  549. // Ignore all intrinsics, phinodes and branch instructions.
  550. // Branch and phinodes instruction usually contains debug info from sources outside of
  551. // the residing basic block, thus we ignore them during annotation.
  552. if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
  553. return std::error_code();
  554. // If a direct call/invoke instruction is inlined in profile
  555. // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
  556. // it means that the inlined callsite has no sample, thus the call
  557. // instruction should have 0 count.
  558. if ((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
  559. !ImmutableCallSite(&Inst).isIndirectCall() &&
  560. findCalleeFunctionSamples(Inst))
  561. return 0;
  562. const DILocation *DIL = DLoc;
  563. uint32_t LineOffset = FunctionSamples::getOffset(DIL);
  564. uint32_t Discriminator = DIL->getBaseDiscriminator();
  565. ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
  566. if (R) {
  567. bool FirstMark =
  568. CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
  569. if (FirstMark) {
  570. ORE->emit([&]() {
  571. OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
  572. Remark << "Applied " << ore::NV("NumSamples", *R);
  573. Remark << " samples from profile (offset: ";
  574. Remark << ore::NV("LineOffset", LineOffset);
  575. if (Discriminator) {
  576. Remark << ".";
  577. Remark << ore::NV("Discriminator", Discriminator);
  578. }
  579. Remark << ")";
  580. return Remark;
  581. });
  582. }
  583. LLVM_DEBUG(dbgs() << " " << DLoc.getLine() << "."
  584. << DIL->getBaseDiscriminator() << ":" << Inst
  585. << " (line offset: " << LineOffset << "."
  586. << DIL->getBaseDiscriminator() << " - weight: " << R.get()
  587. << ")\n");
  588. }
  589. return R;
  590. }
  591. /// Compute the weight of a basic block.
  592. ///
  593. /// The weight of basic block \p BB is the maximum weight of all the
  594. /// instructions in BB.
  595. ///
  596. /// \param BB The basic block to query.
  597. ///
  598. /// \returns the weight for \p BB.
  599. ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) {
  600. uint64_t Max = 0;
  601. bool HasWeight = false;
  602. for (auto &I : BB->getInstList()) {
  603. const ErrorOr<uint64_t> &R = getInstWeight(I);
  604. if (R) {
  605. Max = std::max(Max, R.get());
  606. HasWeight = true;
  607. }
  608. }
  609. return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
  610. }
  611. /// Compute and store the weights of every basic block.
  612. ///
  613. /// This populates the BlockWeights map by computing
  614. /// the weights of every basic block in the CFG.
  615. ///
  616. /// \param F The function to query.
  617. bool SampleProfileLoader::computeBlockWeights(Function &F) {
  618. bool Changed = false;
  619. LLVM_DEBUG(dbgs() << "Block weights\n");
  620. for (const auto &BB : F) {
  621. ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
  622. if (Weight) {
  623. BlockWeights[&BB] = Weight.get();
  624. VisitedBlocks.insert(&BB);
  625. Changed = true;
  626. }
  627. LLVM_DEBUG(printBlockWeight(dbgs(), &BB));
  628. }
  629. return Changed;
  630. }
  631. /// Get the FunctionSamples for a call instruction.
  632. ///
  633. /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
  634. /// instance in which that call instruction is calling to. It contains
  635. /// all samples that resides in the inlined instance. We first find the
  636. /// inlined instance in which the call instruction is from, then we
  637. /// traverse its children to find the callsite with the matching
  638. /// location.
  639. ///
  640. /// \param Inst Call/Invoke instruction to query.
  641. ///
  642. /// \returns The FunctionSamples pointer to the inlined instance.
  643. const FunctionSamples *
  644. SampleProfileLoader::findCalleeFunctionSamples(const Instruction &Inst) const {
  645. const DILocation *DIL = Inst.getDebugLoc();
  646. if (!DIL) {
  647. return nullptr;
  648. }
  649. StringRef CalleeName;
  650. if (const CallInst *CI = dyn_cast<CallInst>(&Inst))
  651. if (Function *Callee = CI->getCalledFunction())
  652. CalleeName = Callee->getName();
  653. const FunctionSamples *FS = findFunctionSamples(Inst);
  654. if (FS == nullptr)
  655. return nullptr;
  656. return FS->findFunctionSamplesAt(LineLocation(FunctionSamples::getOffset(DIL),
  657. DIL->getBaseDiscriminator()),
  658. CalleeName);
  659. }
  660. /// Returns a vector of FunctionSamples that are the indirect call targets
  661. /// of \p Inst. The vector is sorted by the total number of samples. Stores
  662. /// the total call count of the indirect call in \p Sum.
  663. std::vector<const FunctionSamples *>
  664. SampleProfileLoader::findIndirectCallFunctionSamples(
  665. const Instruction &Inst, uint64_t &Sum) const {
  666. const DILocation *DIL = Inst.getDebugLoc();
  667. std::vector<const FunctionSamples *> R;
  668. if (!DIL) {
  669. return R;
  670. }
  671. const FunctionSamples *FS = findFunctionSamples(Inst);
  672. if (FS == nullptr)
  673. return R;
  674. uint32_t LineOffset = FunctionSamples::getOffset(DIL);
  675. uint32_t Discriminator = DIL->getBaseDiscriminator();
  676. auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
  677. Sum = 0;
  678. if (T)
  679. for (const auto &T_C : T.get())
  680. Sum += T_C.second;
  681. if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(LineLocation(
  682. FunctionSamples::getOffset(DIL), DIL->getBaseDiscriminator()))) {
  683. if (M->empty())
  684. return R;
  685. for (const auto &NameFS : *M) {
  686. Sum += NameFS.second.getEntrySamples();
  687. R.push_back(&NameFS.second);
  688. }
  689. llvm::sort(R, [](const FunctionSamples *L, const FunctionSamples *R) {
  690. if (L->getEntrySamples() != R->getEntrySamples())
  691. return L->getEntrySamples() > R->getEntrySamples();
  692. return FunctionSamples::getGUID(L->getName()) <
  693. FunctionSamples::getGUID(R->getName());
  694. });
  695. }
  696. return R;
  697. }
  698. /// Get the FunctionSamples for an instruction.
  699. ///
  700. /// The FunctionSamples of an instruction \p Inst is the inlined instance
  701. /// in which that instruction is coming from. We traverse the inline stack
  702. /// of that instruction, and match it with the tree nodes in the profile.
  703. ///
  704. /// \param Inst Instruction to query.
  705. ///
  706. /// \returns the FunctionSamples pointer to the inlined instance.
  707. const FunctionSamples *
  708. SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
  709. const DILocation *DIL = Inst.getDebugLoc();
  710. if (!DIL)
  711. return Samples;
  712. auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
  713. if (it.second)
  714. it.first->second = Samples->findFunctionSamples(DIL);
  715. return it.first->second;
  716. }
  717. bool SampleProfileLoader::inlineCallInstruction(Instruction *I) {
  718. assert(isa<CallInst>(I) || isa<InvokeInst>(I));
  719. CallSite CS(I);
  720. Function *CalledFunction = CS.getCalledFunction();
  721. assert(CalledFunction);
  722. DebugLoc DLoc = I->getDebugLoc();
  723. BasicBlock *BB = I->getParent();
  724. InlineParams Params = getInlineParams();
  725. Params.ComputeFullInlineCost = true;
  726. // Checks if there is anything in the reachable portion of the callee at
  727. // this callsite that makes this inlining potentially illegal. Need to
  728. // set ComputeFullInlineCost, otherwise getInlineCost may return early
  729. // when cost exceeds threshold without checking all IRs in the callee.
  730. // The acutal cost does not matter because we only checks isNever() to
  731. // see if it is legal to inline the callsite.
  732. InlineCost Cost =
  733. getInlineCost(cast<CallBase>(*I), Params, GetTTI(*CalledFunction), GetAC,
  734. None, nullptr, nullptr);
  735. if (Cost.isNever()) {
  736. ORE->emit(OptimizationRemark(DEBUG_TYPE, "Not inline", DLoc, BB)
  737. << "incompatible inlining");
  738. return false;
  739. }
  740. InlineFunctionInfo IFI(nullptr, &GetAC);
  741. if (InlineFunction(CS, IFI)) {
  742. // The call to InlineFunction erases I, so we can't pass it here.
  743. ORE->emit(OptimizationRemark(DEBUG_TYPE, "HotInline", DLoc, BB)
  744. << "inlined hot callee '" << ore::NV("Callee", CalledFunction)
  745. << "' into '" << ore::NV("Caller", BB->getParent()) << "'");
  746. return true;
  747. }
  748. return false;
  749. }
  750. /// Iteratively inline hot callsites of a function.
  751. ///
  752. /// Iteratively traverse all callsites of the function \p F, and find if
  753. /// the corresponding inlined instance exists and is hot in profile. If
  754. /// it is hot enough, inline the callsites and adds new callsites of the
  755. /// callee into the caller. If the call is an indirect call, first promote
  756. /// it to direct call. Each indirect call is limited with a single target.
  757. ///
  758. /// \param F function to perform iterative inlining.
  759. /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
  760. /// inlined in the profiled binary.
  761. ///
  762. /// \returns True if there is any inline happened.
  763. bool SampleProfileLoader::inlineHotFunctions(
  764. Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
  765. DenseSet<Instruction *> PromotedInsns;
  766. DenseMap<Instruction *, const FunctionSamples *> localNotInlinedCallSites;
  767. bool Changed = false;
  768. while (true) {
  769. bool LocalChanged = false;
  770. SmallVector<Instruction *, 10> CIS;
  771. for (auto &BB : F) {
  772. bool Hot = false;
  773. SmallVector<Instruction *, 10> Candidates;
  774. for (auto &I : BB.getInstList()) {
  775. const FunctionSamples *FS = nullptr;
  776. if ((isa<CallInst>(I) || isa<InvokeInst>(I)) &&
  777. !isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(I))) {
  778. Candidates.push_back(&I);
  779. if (FS->getEntrySamples() > 0)
  780. localNotInlinedCallSites.try_emplace(&I, FS);
  781. if (callsiteIsHot(FS, PSI))
  782. Hot = true;
  783. }
  784. }
  785. if (Hot) {
  786. CIS.insert(CIS.begin(), Candidates.begin(), Candidates.end());
  787. }
  788. }
  789. for (auto I : CIS) {
  790. Function *CalledFunction = CallSite(I).getCalledFunction();
  791. // Do not inline recursive calls.
  792. if (CalledFunction == &F)
  793. continue;
  794. if (CallSite(I).isIndirectCall()) {
  795. if (PromotedInsns.count(I))
  796. continue;
  797. uint64_t Sum;
  798. for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
  799. if (IsThinLTOPreLink) {
  800. FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
  801. PSI->getOrCompHotCountThreshold());
  802. continue;
  803. }
  804. auto CalleeFunctionName = FS->getFuncNameInModule(F.getParent());
  805. // If it is a recursive call, we do not inline it as it could bloat
  806. // the code exponentially. There is way to better handle this, e.g.
  807. // clone the caller first, and inline the cloned caller if it is
  808. // recursive. As llvm does not inline recursive calls, we will
  809. // simply ignore it instead of handling it explicitly.
  810. if (CalleeFunctionName == F.getName())
  811. continue;
  812. if (!callsiteIsHot(FS, PSI))
  813. continue;
  814. const char *Reason = "Callee function not available";
  815. auto R = SymbolMap.find(CalleeFunctionName);
  816. if (R != SymbolMap.end() && R->getValue() &&
  817. !R->getValue()->isDeclaration() &&
  818. R->getValue()->getSubprogram() &&
  819. isLegalToPromote(CallSite(I), R->getValue(), &Reason)) {
  820. uint64_t C = FS->getEntrySamples();
  821. Instruction *DI =
  822. pgo::promoteIndirectCall(I, R->getValue(), C, Sum, false, ORE);
  823. Sum -= C;
  824. PromotedInsns.insert(I);
  825. // If profile mismatches, we should not attempt to inline DI.
  826. if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) &&
  827. inlineCallInstruction(DI)) {
  828. localNotInlinedCallSites.erase(I);
  829. LocalChanged = true;
  830. }
  831. } else {
  832. LLVM_DEBUG(dbgs()
  833. << "\nFailed to promote indirect call to "
  834. << CalleeFunctionName << " because " << Reason << "\n");
  835. }
  836. }
  837. } else if (CalledFunction && CalledFunction->getSubprogram() &&
  838. !CalledFunction->isDeclaration()) {
  839. if (inlineCallInstruction(I)) {
  840. localNotInlinedCallSites.erase(I);
  841. LocalChanged = true;
  842. }
  843. } else if (IsThinLTOPreLink) {
  844. findCalleeFunctionSamples(*I)->findInlinedFunctions(
  845. InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
  846. }
  847. }
  848. if (LocalChanged) {
  849. Changed = true;
  850. } else {
  851. break;
  852. }
  853. }
  854. // Accumulate not inlined callsite information into notInlinedSamples
  855. for (const auto &Pair : localNotInlinedCallSites) {
  856. Instruction *I = Pair.getFirst();
  857. Function *Callee = CallSite(I).getCalledFunction();
  858. if (!Callee || Callee->isDeclaration())
  859. continue;
  860. const FunctionSamples *FS = Pair.getSecond();
  861. auto pair =
  862. notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
  863. pair.first->second.entryCount += FS->getEntrySamples();
  864. }
  865. return Changed;
  866. }
  867. /// Find equivalence classes for the given block.
  868. ///
  869. /// This finds all the blocks that are guaranteed to execute the same
  870. /// number of times as \p BB1. To do this, it traverses all the
  871. /// descendants of \p BB1 in the dominator or post-dominator tree.
  872. ///
  873. /// A block BB2 will be in the same equivalence class as \p BB1 if
  874. /// the following holds:
  875. ///
  876. /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
  877. /// is a descendant of \p BB1 in the dominator tree, then BB2 should
  878. /// dominate BB1 in the post-dominator tree.
  879. ///
  880. /// 2- Both BB2 and \p BB1 must be in the same loop.
  881. ///
  882. /// For every block BB2 that meets those two requirements, we set BB2's
  883. /// equivalence class to \p BB1.
  884. ///
  885. /// \param BB1 Block to check.
  886. /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
  887. /// \param DomTree Opposite dominator tree. If \p Descendants is filled
  888. /// with blocks from \p BB1's dominator tree, then
  889. /// this is the post-dominator tree, and vice versa.
  890. template <bool IsPostDom>
  891. void SampleProfileLoader::findEquivalencesFor(
  892. BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
  893. DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) {
  894. const BasicBlock *EC = EquivalenceClass[BB1];
  895. uint64_t Weight = BlockWeights[EC];
  896. for (const auto *BB2 : Descendants) {
  897. bool IsDomParent = DomTree->dominates(BB2, BB1);
  898. bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
  899. if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
  900. EquivalenceClass[BB2] = EC;
  901. // If BB2 is visited, then the entire EC should be marked as visited.
  902. if (VisitedBlocks.count(BB2)) {
  903. VisitedBlocks.insert(EC);
  904. }
  905. // If BB2 is heavier than BB1, make BB2 have the same weight
  906. // as BB1.
  907. //
  908. // Note that we don't worry about the opposite situation here
  909. // (when BB2 is lighter than BB1). We will deal with this
  910. // during the propagation phase. Right now, we just want to
  911. // make sure that BB1 has the largest weight of all the
  912. // members of its equivalence set.
  913. Weight = std::max(Weight, BlockWeights[BB2]);
  914. }
  915. }
  916. if (EC == &EC->getParent()->getEntryBlock()) {
  917. BlockWeights[EC] = Samples->getHeadSamples() + 1;
  918. } else {
  919. BlockWeights[EC] = Weight;
  920. }
  921. }
  922. /// Find equivalence classes.
  923. ///
  924. /// Since samples may be missing from blocks, we can fill in the gaps by setting
  925. /// the weights of all the blocks in the same equivalence class to the same
  926. /// weight. To compute the concept of equivalence, we use dominance and loop
  927. /// information. Two blocks B1 and B2 are in the same equivalence class if B1
  928. /// dominates B2, B2 post-dominates B1 and both are in the same loop.
  929. ///
  930. /// \param F The function to query.
  931. void SampleProfileLoader::findEquivalenceClasses(Function &F) {
  932. SmallVector<BasicBlock *, 8> DominatedBBs;
  933. LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n");
  934. // Find equivalence sets based on dominance and post-dominance information.
  935. for (auto &BB : F) {
  936. BasicBlock *BB1 = &BB;
  937. // Compute BB1's equivalence class once.
  938. if (EquivalenceClass.count(BB1)) {
  939. LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
  940. continue;
  941. }
  942. // By default, blocks are in their own equivalence class.
  943. EquivalenceClass[BB1] = BB1;
  944. // Traverse all the blocks dominated by BB1. We are looking for
  945. // every basic block BB2 such that:
  946. //
  947. // 1- BB1 dominates BB2.
  948. // 2- BB2 post-dominates BB1.
  949. // 3- BB1 and BB2 are in the same loop nest.
  950. //
  951. // If all those conditions hold, it means that BB2 is executed
  952. // as many times as BB1, so they are placed in the same equivalence
  953. // class by making BB2's equivalence class be BB1.
  954. DominatedBBs.clear();
  955. DT->getDescendants(BB1, DominatedBBs);
  956. findEquivalencesFor(BB1, DominatedBBs, PDT.get());
  957. LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
  958. }
  959. // Assign weights to equivalence classes.
  960. //
  961. // All the basic blocks in the same equivalence class will execute
  962. // the same number of times. Since we know that the head block in
  963. // each equivalence class has the largest weight, assign that weight
  964. // to all the blocks in that equivalence class.
  965. LLVM_DEBUG(
  966. dbgs() << "\nAssign the same weight to all blocks in the same class\n");
  967. for (auto &BI : F) {
  968. const BasicBlock *BB = &BI;
  969. const BasicBlock *EquivBB = EquivalenceClass[BB];
  970. if (BB != EquivBB)
  971. BlockWeights[BB] = BlockWeights[EquivBB];
  972. LLVM_DEBUG(printBlockWeight(dbgs(), BB));
  973. }
  974. }
  975. /// Visit the given edge to decide if it has a valid weight.
  976. ///
  977. /// If \p E has not been visited before, we copy to \p UnknownEdge
  978. /// and increment the count of unknown edges.
  979. ///
  980. /// \param E Edge to visit.
  981. /// \param NumUnknownEdges Current number of unknown edges.
  982. /// \param UnknownEdge Set if E has not been visited before.
  983. ///
  984. /// \returns E's weight, if known. Otherwise, return 0.
  985. uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
  986. Edge *UnknownEdge) {
  987. if (!VisitedEdges.count(E)) {
  988. (*NumUnknownEdges)++;
  989. *UnknownEdge = E;
  990. return 0;
  991. }
  992. return EdgeWeights[E];
  993. }
  994. /// Propagate weights through incoming/outgoing edges.
  995. ///
  996. /// If the weight of a basic block is known, and there is only one edge
  997. /// with an unknown weight, we can calculate the weight of that edge.
  998. ///
  999. /// Similarly, if all the edges have a known count, we can calculate the
  1000. /// count of the basic block, if needed.
  1001. ///
  1002. /// \param F Function to process.
  1003. /// \param UpdateBlockCount Whether we should update basic block counts that
  1004. /// has already been annotated.
  1005. ///
  1006. /// \returns True if new weights were assigned to edges or blocks.
  1007. bool SampleProfileLoader::propagateThroughEdges(Function &F,
  1008. bool UpdateBlockCount) {
  1009. bool Changed = false;
  1010. LLVM_DEBUG(dbgs() << "\nPropagation through edges\n");
  1011. for (const auto &BI : F) {
  1012. const BasicBlock *BB = &BI;
  1013. const BasicBlock *EC = EquivalenceClass[BB];
  1014. // Visit all the predecessor and successor edges to determine
  1015. // which ones have a weight assigned already. Note that it doesn't
  1016. // matter that we only keep track of a single unknown edge. The
  1017. // only case we are interested in handling is when only a single
  1018. // edge is unknown (see setEdgeOrBlockWeight).
  1019. for (unsigned i = 0; i < 2; i++) {
  1020. uint64_t TotalWeight = 0;
  1021. unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
  1022. Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
  1023. if (i == 0) {
  1024. // First, visit all predecessor edges.
  1025. NumTotalEdges = Predecessors[BB].size();
  1026. for (auto *Pred : Predecessors[BB]) {
  1027. Edge E = std::make_pair(Pred, BB);
  1028. TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
  1029. if (E.first == E.second)
  1030. SelfReferentialEdge = E;
  1031. }
  1032. if (NumTotalEdges == 1) {
  1033. SingleEdge = std::make_pair(Predecessors[BB][0], BB);
  1034. }
  1035. } else {
  1036. // On the second round, visit all successor edges.
  1037. NumTotalEdges = Successors[BB].size();
  1038. for (auto *Succ : Successors[BB]) {
  1039. Edge E = std::make_pair(BB, Succ);
  1040. TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
  1041. }
  1042. if (NumTotalEdges == 1) {
  1043. SingleEdge = std::make_pair(BB, Successors[BB][0]);
  1044. }
  1045. }
  1046. // After visiting all the edges, there are three cases that we
  1047. // can handle immediately:
  1048. //
  1049. // - All the edge weights are known (i.e., NumUnknownEdges == 0).
  1050. // In this case, we simply check that the sum of all the edges
  1051. // is the same as BB's weight. If not, we change BB's weight
  1052. // to match. Additionally, if BB had not been visited before,
  1053. // we mark it visited.
  1054. //
  1055. // - Only one edge is unknown and BB has already been visited.
  1056. // In this case, we can compute the weight of the edge by
  1057. // subtracting the total block weight from all the known
  1058. // edge weights. If the edges weight more than BB, then the
  1059. // edge of the last remaining edge is set to zero.
  1060. //
  1061. // - There exists a self-referential edge and the weight of BB is
  1062. // known. In this case, this edge can be based on BB's weight.
  1063. // We add up all the other known edges and set the weight on
  1064. // the self-referential edge as we did in the previous case.
  1065. //
  1066. // In any other case, we must continue iterating. Eventually,
  1067. // all edges will get a weight, or iteration will stop when
  1068. // it reaches SampleProfileMaxPropagateIterations.
  1069. if (NumUnknownEdges <= 1) {
  1070. uint64_t &BBWeight = BlockWeights[EC];
  1071. if (NumUnknownEdges == 0) {
  1072. if (!VisitedBlocks.count(EC)) {
  1073. // If we already know the weight of all edges, the weight of the
  1074. // basic block can be computed. It should be no larger than the sum
  1075. // of all edge weights.
  1076. if (TotalWeight > BBWeight) {
  1077. BBWeight = TotalWeight;
  1078. Changed = true;
  1079. LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName()
  1080. << " known. Set weight for block: ";
  1081. printBlockWeight(dbgs(), BB););
  1082. }
  1083. } else if (NumTotalEdges == 1 &&
  1084. EdgeWeights[SingleEdge] < BlockWeights[EC]) {
  1085. // If there is only one edge for the visited basic block, use the
  1086. // block weight to adjust edge weight if edge weight is smaller.
  1087. EdgeWeights[SingleEdge] = BlockWeights[EC];
  1088. Changed = true;
  1089. }
  1090. } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
  1091. // If there is a single unknown edge and the block has been
  1092. // visited, then we can compute E's weight.
  1093. if (BBWeight >= TotalWeight)
  1094. EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
  1095. else
  1096. EdgeWeights[UnknownEdge] = 0;
  1097. const BasicBlock *OtherEC;
  1098. if (i == 0)
  1099. OtherEC = EquivalenceClass[UnknownEdge.first];
  1100. else
  1101. OtherEC = EquivalenceClass[UnknownEdge.second];
  1102. // Edge weights should never exceed the BB weights it connects.
  1103. if (VisitedBlocks.count(OtherEC) &&
  1104. EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
  1105. EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
  1106. VisitedEdges.insert(UnknownEdge);
  1107. Changed = true;
  1108. LLVM_DEBUG(dbgs() << "Set weight for edge: ";
  1109. printEdgeWeight(dbgs(), UnknownEdge));
  1110. }
  1111. } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
  1112. // If a block Weights 0, all its in/out edges should weight 0.
  1113. if (i == 0) {
  1114. for (auto *Pred : Predecessors[BB]) {
  1115. Edge E = std::make_pair(Pred, BB);
  1116. EdgeWeights[E] = 0;
  1117. VisitedEdges.insert(E);
  1118. }
  1119. } else {
  1120. for (auto *Succ : Successors[BB]) {
  1121. Edge E = std::make_pair(BB, Succ);
  1122. EdgeWeights[E] = 0;
  1123. VisitedEdges.insert(E);
  1124. }
  1125. }
  1126. } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
  1127. uint64_t &BBWeight = BlockWeights[BB];
  1128. // We have a self-referential edge and the weight of BB is known.
  1129. if (BBWeight >= TotalWeight)
  1130. EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
  1131. else
  1132. EdgeWeights[SelfReferentialEdge] = 0;
  1133. VisitedEdges.insert(SelfReferentialEdge);
  1134. Changed = true;
  1135. LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: ";
  1136. printEdgeWeight(dbgs(), SelfReferentialEdge));
  1137. }
  1138. if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
  1139. BlockWeights[EC] = TotalWeight;
  1140. VisitedBlocks.insert(EC);
  1141. Changed = true;
  1142. }
  1143. }
  1144. }
  1145. return Changed;
  1146. }
  1147. /// Build in/out edge lists for each basic block in the CFG.
  1148. ///
  1149. /// We are interested in unique edges. If a block B1 has multiple
  1150. /// edges to another block B2, we only add a single B1->B2 edge.
  1151. void SampleProfileLoader::buildEdges(Function &F) {
  1152. for (auto &BI : F) {
  1153. BasicBlock *B1 = &BI;
  1154. // Add predecessors for B1.
  1155. SmallPtrSet<BasicBlock *, 16> Visited;
  1156. if (!Predecessors[B1].empty())
  1157. llvm_unreachable("Found a stale predecessors list in a basic block.");
  1158. for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
  1159. BasicBlock *B2 = *PI;
  1160. if (Visited.insert(B2).second)
  1161. Predecessors[B1].push_back(B2);
  1162. }
  1163. // Add successors for B1.
  1164. Visited.clear();
  1165. if (!Successors[B1].empty())
  1166. llvm_unreachable("Found a stale successors list in a basic block.");
  1167. for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
  1168. BasicBlock *B2 = *SI;
  1169. if (Visited.insert(B2).second)
  1170. Successors[B1].push_back(B2);
  1171. }
  1172. }
  1173. }
  1174. /// Returns the sorted CallTargetMap \p M by count in descending order.
  1175. static SmallVector<InstrProfValueData, 2> GetSortedValueDataFromCallTargets(
  1176. const SampleRecord::CallTargetMap & M) {
  1177. SmallVector<InstrProfValueData, 2> R;
  1178. for (const auto &I : SampleRecord::SortCallTargets(M)) {
  1179. R.emplace_back(InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
  1180. }
  1181. return R;
  1182. }
  1183. /// Propagate weights into edges
  1184. ///
  1185. /// The following rules are applied to every block BB in the CFG:
  1186. ///
  1187. /// - If BB has a single predecessor/successor, then the weight
  1188. /// of that edge is the weight of the block.
  1189. ///
  1190. /// - If all incoming or outgoing edges are known except one, and the
  1191. /// weight of the block is already known, the weight of the unknown
  1192. /// edge will be the weight of the block minus the sum of all the known
  1193. /// edges. If the sum of all the known edges is larger than BB's weight,
  1194. /// we set the unknown edge weight to zero.
  1195. ///
  1196. /// - If there is a self-referential edge, and the weight of the block is
  1197. /// known, the weight for that edge is set to the weight of the block
  1198. /// minus the weight of the other incoming edges to that block (if
  1199. /// known).
  1200. void SampleProfileLoader::propagateWeights(Function &F) {
  1201. bool Changed = true;
  1202. unsigned I = 0;
  1203. // If BB weight is larger than its corresponding loop's header BB weight,
  1204. // use the BB weight to replace the loop header BB weight.
  1205. for (auto &BI : F) {
  1206. BasicBlock *BB = &BI;
  1207. Loop *L = LI->getLoopFor(BB);
  1208. if (!L) {
  1209. continue;
  1210. }
  1211. BasicBlock *Header = L->getHeader();
  1212. if (Header && BlockWeights[BB] > BlockWeights[Header]) {
  1213. BlockWeights[Header] = BlockWeights[BB];
  1214. }
  1215. }
  1216. // Before propagation starts, build, for each block, a list of
  1217. // unique predecessors and successors. This is necessary to handle
  1218. // identical edges in multiway branches. Since we visit all blocks and all
  1219. // edges of the CFG, it is cleaner to build these lists once at the start
  1220. // of the pass.
  1221. buildEdges(F);
  1222. // Propagate until we converge or we go past the iteration limit.
  1223. while (Changed && I++ < SampleProfileMaxPropagateIterations) {
  1224. Changed = propagateThroughEdges(F, false);
  1225. }
  1226. // The first propagation propagates BB counts from annotated BBs to unknown
  1227. // BBs. The 2nd propagation pass resets edges weights, and use all BB weights
  1228. // to propagate edge weights.
  1229. VisitedEdges.clear();
  1230. Changed = true;
  1231. while (Changed && I++ < SampleProfileMaxPropagateIterations) {
  1232. Changed = propagateThroughEdges(F, false);
  1233. }
  1234. // The 3rd propagation pass allows adjust annotated BB weights that are
  1235. // obviously wrong.
  1236. Changed = true;
  1237. while (Changed && I++ < SampleProfileMaxPropagateIterations) {
  1238. Changed = propagateThroughEdges(F, true);
  1239. }
  1240. // Generate MD_prof metadata for every branch instruction using the
  1241. // edge weights computed during propagation.
  1242. LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
  1243. LLVMContext &Ctx = F.getContext();
  1244. MDBuilder MDB(Ctx);
  1245. for (auto &BI : F) {
  1246. BasicBlock *BB = &BI;
  1247. if (BlockWeights[BB]) {
  1248. for (auto &I : BB->getInstList()) {
  1249. if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
  1250. continue;
  1251. CallSite CS(&I);
  1252. if (!CS.getCalledFunction()) {
  1253. const DebugLoc &DLoc = I.getDebugLoc();
  1254. if (!DLoc)
  1255. continue;
  1256. const DILocation *DIL = DLoc;
  1257. uint32_t LineOffset = FunctionSamples::getOffset(DIL);
  1258. uint32_t Discriminator = DIL->getBaseDiscriminator();
  1259. const FunctionSamples *FS = findFunctionSamples(I);
  1260. if (!FS)
  1261. continue;
  1262. auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
  1263. if (!T || T.get().empty())
  1264. continue;
  1265. SmallVector<InstrProfValueData, 2> SortedCallTargets =
  1266. GetSortedValueDataFromCallTargets(T.get());
  1267. uint64_t Sum;
  1268. findIndirectCallFunctionSamples(I, Sum);
  1269. annotateValueSite(*I.getParent()->getParent()->getParent(), I,
  1270. SortedCallTargets, Sum, IPVK_IndirectCallTarget,
  1271. SortedCallTargets.size());
  1272. } else if (!isa<IntrinsicInst>(&I)) {
  1273. I.setMetadata(LLVMContext::MD_prof,
  1274. MDB.createBranchWeights(
  1275. {static_cast<uint32_t>(BlockWeights[BB])}));
  1276. }
  1277. }
  1278. }
  1279. Instruction *TI = BB->getTerminator();
  1280. if (TI->getNumSuccessors() == 1)
  1281. continue;
  1282. if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
  1283. continue;
  1284. DebugLoc BranchLoc = TI->getDebugLoc();
  1285. LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
  1286. << ((BranchLoc) ? Twine(BranchLoc.getLine())
  1287. : Twine("<UNKNOWN LOCATION>"))
  1288. << ".\n");
  1289. SmallVector<uint32_t, 4> Weights;
  1290. uint32_t MaxWeight = 0;
  1291. Instruction *MaxDestInst;
  1292. for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
  1293. BasicBlock *Succ = TI->getSuccessor(I);
  1294. Edge E = std::make_pair(BB, Succ);
  1295. uint64_t Weight = EdgeWeights[E];
  1296. LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
  1297. // Use uint32_t saturated arithmetic to adjust the incoming weights,
  1298. // if needed. Sample counts in profiles are 64-bit unsigned values,
  1299. // but internally branch weights are expressed as 32-bit values.
  1300. if (Weight > std::numeric_limits<uint32_t>::max()) {
  1301. LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
  1302. Weight = std::numeric_limits<uint32_t>::max();
  1303. }
  1304. // Weight is added by one to avoid propagation errors introduced by
  1305. // 0 weights.
  1306. Weights.push_back(static_cast<uint32_t>(Weight + 1));
  1307. if (Weight != 0) {
  1308. if (Weight > MaxWeight) {
  1309. MaxWeight = Weight;
  1310. MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
  1311. }
  1312. }
  1313. }
  1314. misexpect::verifyMisExpect(TI, Weights, TI->getContext());
  1315. uint64_t TempWeight;
  1316. // Only set weights if there is at least one non-zero weight.
  1317. // In any other case, let the analyzer set weights.
  1318. // Do not set weights if the weights are present. In ThinLTO, the profile
  1319. // annotation is done twice. If the first annotation already set the
  1320. // weights, the second pass does not need to set it.
  1321. if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
  1322. LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
  1323. TI->setMetadata(LLVMContext::MD_prof,
  1324. MDB.createBranchWeights(Weights));
  1325. ORE->emit([&]() {
  1326. return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
  1327. << "most popular destination for conditional branches at "
  1328. << ore::NV("CondBranchesLoc", BranchLoc);
  1329. });
  1330. } else {
  1331. LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
  1332. }
  1333. }
  1334. }
  1335. /// Get the line number for the function header.
  1336. ///
  1337. /// This looks up function \p F in the current compilation unit and
  1338. /// retrieves the line number where the function is defined. This is
  1339. /// line 0 for all the samples read from the profile file. Every line
  1340. /// number is relative to this line.
  1341. ///
  1342. /// \param F Function object to query.
  1343. ///
  1344. /// \returns the line number where \p F is defined. If it returns 0,
  1345. /// it means that there is no debug information available for \p F.
  1346. unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
  1347. if (DISubprogram *S = F.getSubprogram())
  1348. return S->getLine();
  1349. if (NoWarnSampleUnused)
  1350. return 0;
  1351. // If the start of \p F is missing, emit a diagnostic to inform the user
  1352. // about the missed opportunity.
  1353. F.getContext().diagnose(DiagnosticInfoSampleProfile(
  1354. "No debug information found in function " + F.getName() +
  1355. ": Function profile not used",
  1356. DS_Warning));
  1357. return 0;
  1358. }
  1359. void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
  1360. DT.reset(new DominatorTree);
  1361. DT->recalculate(F);
  1362. PDT.reset(new PostDominatorTree(F));
  1363. LI.reset(new LoopInfo);
  1364. LI->analyze(*DT);
  1365. }
  1366. /// Generate branch weight metadata for all branches in \p F.
  1367. ///
  1368. /// Branch weights are computed out of instruction samples using a
  1369. /// propagation heuristic. Propagation proceeds in 3 phases:
  1370. ///
  1371. /// 1- Assignment of block weights. All the basic blocks in the function
  1372. /// are initial assigned the same weight as their most frequently
  1373. /// executed instruction.
  1374. ///
  1375. /// 2- Creation of equivalence classes. Since samples may be missing from
  1376. /// blocks, we can fill in the gaps by setting the weights of all the
  1377. /// blocks in the same equivalence class to the same weight. To compute
  1378. /// the concept of equivalence, we use dominance and loop information.
  1379. /// Two blocks B1 and B2 are in the same equivalence class if B1
  1380. /// dominates B2, B2 post-dominates B1 and both are in the same loop.
  1381. ///
  1382. /// 3- Propagation of block weights into edges. This uses a simple
  1383. /// propagation heuristic. The following rules are applied to every
  1384. /// block BB in the CFG:
  1385. ///
  1386. /// - If BB has a single predecessor/successor, then the weight
  1387. /// of that edge is the weight of the block.
  1388. ///
  1389. /// - If all the edges are known except one, and the weight of the
  1390. /// block is already known, the weight of the unknown edge will
  1391. /// be the weight of the block minus the sum of all the known
  1392. /// edges. If the sum of all the known edges is larger than BB's weight,
  1393. /// we set the unknown edge weight to zero.
  1394. ///
  1395. /// - If there is a self-referential edge, and the weight of the block is
  1396. /// known, the weight for that edge is set to the weight of the block
  1397. /// minus the weight of the other incoming edges to that block (if
  1398. /// known).
  1399. ///
  1400. /// Since this propagation is not guaranteed to finalize for every CFG, we
  1401. /// only allow it to proceed for a limited number of iterations (controlled
  1402. /// by -sample-profile-max-propagate-iterations).
  1403. ///
  1404. /// FIXME: Try to replace this propagation heuristic with a scheme
  1405. /// that is guaranteed to finalize. A work-list approach similar to
  1406. /// the standard value propagation algorithm used by SSA-CCP might
  1407. /// work here.
  1408. ///
  1409. /// Once all the branch weights are computed, we emit the MD_prof
  1410. /// metadata on BB using the computed values for each of its branches.
  1411. ///
  1412. /// \param F The function to query.
  1413. ///
  1414. /// \returns true if \p F was modified. Returns false, otherwise.
  1415. bool SampleProfileLoader::emitAnnotations(Function &F) {
  1416. bool Changed = false;
  1417. if (getFunctionLoc(F) == 0)
  1418. return false;
  1419. LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
  1420. << F.getName() << ": " << getFunctionLoc(F) << "\n");
  1421. DenseSet<GlobalValue::GUID> InlinedGUIDs;
  1422. Changed |= inlineHotFunctions(F, InlinedGUIDs);
  1423. // Compute basic block weights.
  1424. Changed |= computeBlockWeights(F);
  1425. if (Changed) {
  1426. // Add an entry count to the function using the samples gathered at the
  1427. // function entry.
  1428. // Sets the GUIDs that are inlined in the profiled binary. This is used
  1429. // for ThinLink to make correct liveness analysis, and also make the IR
  1430. // match the profiled binary before annotation.
  1431. F.setEntryCount(
  1432. ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
  1433. &InlinedGUIDs);
  1434. // Compute dominance and loop info needed for propagation.
  1435. computeDominanceAndLoopInfo(F);
  1436. // Find equivalence classes.
  1437. findEquivalenceClasses(F);
  1438. // Propagate weights to all edges.
  1439. propagateWeights(F);
  1440. }
  1441. // If coverage checking was requested, compute it now.
  1442. if (SampleProfileRecordCoverage) {
  1443. unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
  1444. unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
  1445. unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
  1446. if (Coverage < SampleProfileRecordCoverage) {
  1447. F.getContext().diagnose(DiagnosticInfoSampleProfile(
  1448. F.getSubprogram()->getFilename(), getFunctionLoc(F),
  1449. Twine(Used) + " of " + Twine(Total) + " available profile records (" +
  1450. Twine(Coverage) + "%) were applied",
  1451. DS_Warning));
  1452. }
  1453. }
  1454. if (SampleProfileSampleCoverage) {
  1455. uint64_t Used = CoverageTracker.getTotalUsedSamples();
  1456. uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
  1457. unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
  1458. if (Coverage < SampleProfileSampleCoverage) {
  1459. F.getContext().diagnose(DiagnosticInfoSampleProfile(
  1460. F.getSubprogram()->getFilename(), getFunctionLoc(F),
  1461. Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
  1462. Twine(Coverage) + "%) were applied",
  1463. DS_Warning));
  1464. }
  1465. }
  1466. return Changed;
  1467. }
  1468. char SampleProfileLoaderLegacyPass::ID = 0;
  1469. INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
  1470. "Sample Profile loader", false, false)
  1471. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1472. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  1473. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  1474. INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
  1475. "Sample Profile loader", false, false)
  1476. bool SampleProfileLoader::doInitialization(Module &M) {
  1477. auto &Ctx = M.getContext();
  1478. auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
  1479. if (std::error_code EC = ReaderOrErr.getError()) {
  1480. std::string Msg = "Could not open profile: " + EC.message();
  1481. Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
  1482. return false;
  1483. }
  1484. Reader = std::move(ReaderOrErr.get());
  1485. Reader->collectFuncsToUse(M);
  1486. ProfileIsValid = (Reader->read() == sampleprof_error::success);
  1487. PSL = Reader->getProfileSymbolList();
  1488. if (!RemappingFilename.empty()) {
  1489. // Apply profile remappings to the loaded profile data if requested.
  1490. // For now, we only support remapping symbols encoded using the Itanium
  1491. // C++ ABI's name mangling scheme.
  1492. ReaderOrErr = SampleProfileReaderItaniumRemapper::create(
  1493. RemappingFilename, Ctx, std::move(Reader));
  1494. if (std::error_code EC = ReaderOrErr.getError()) {
  1495. std::string Msg = "Could not open profile remapping file: " + EC.message();
  1496. Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
  1497. return false;
  1498. }
  1499. Reader = std::move(ReaderOrErr.get());
  1500. ProfileIsValid = (Reader->read() == sampleprof_error::success);
  1501. }
  1502. return true;
  1503. }
  1504. ModulePass *llvm::createSampleProfileLoaderPass() {
  1505. return new SampleProfileLoaderLegacyPass();
  1506. }
  1507. ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
  1508. return new SampleProfileLoaderLegacyPass(Name);
  1509. }
  1510. bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
  1511. ProfileSummaryInfo *_PSI) {
  1512. GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
  1513. if (!ProfileIsValid)
  1514. return false;
  1515. PSI = _PSI;
  1516. if (M.getProfileSummary(/* IsCS */ false) == nullptr)
  1517. M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
  1518. ProfileSummary::PSK_Sample);
  1519. // Compute the total number of samples collected in this profile.
  1520. for (const auto &I : Reader->getProfiles())
  1521. TotalCollectedSamples += I.second.getTotalSamples();
  1522. // Populate the symbol map.
  1523. for (const auto &N_F : M.getValueSymbolTable()) {
  1524. StringRef OrigName = N_F.getKey();
  1525. Function *F = dyn_cast<Function>(N_F.getValue());
  1526. if (F == nullptr)
  1527. continue;
  1528. SymbolMap[OrigName] = F;
  1529. auto pos = OrigName.find('.');
  1530. if (pos != StringRef::npos) {
  1531. StringRef NewName = OrigName.substr(0, pos);
  1532. auto r = SymbolMap.insert(std::make_pair(NewName, F));
  1533. // Failiing to insert means there is already an entry in SymbolMap,
  1534. // thus there are multiple functions that are mapped to the same
  1535. // stripped name. In this case of name conflicting, set the value
  1536. // to nullptr to avoid confusion.
  1537. if (!r.second)
  1538. r.first->second = nullptr;
  1539. }
  1540. }
  1541. bool retval = false;
  1542. for (auto &F : M)
  1543. if (!F.isDeclaration()) {
  1544. clearFunctionData();
  1545. retval |= runOnFunction(F, AM);
  1546. }
  1547. // Account for cold calls not inlined....
  1548. for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
  1549. notInlinedCallInfo)
  1550. updateProfileCallee(pair.first, pair.second.entryCount);
  1551. return retval;
  1552. }
  1553. bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
  1554. ACT = &getAnalysis<AssumptionCacheTracker>();
  1555. TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
  1556. ProfileSummaryInfo *PSI =
  1557. &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  1558. return SampleLoader.runOnModule(M, nullptr, PSI);
  1559. }
  1560. bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
  1561. DILocation2SampleMap.clear();
  1562. // By default the entry count is initialized to -1, which will be treated
  1563. // conservatively by getEntryCount as the same as unknown (None). This is
  1564. // to avoid newly added code to be treated as cold. If we have samples
  1565. // this will be overwritten in emitAnnotations.
  1566. //
  1567. // PSL -- profile symbol list include all the symbols in sampled binary.
  1568. // If ProfileSampleAccurate is true or F has profile-sample-accurate
  1569. // attribute, and if there is no profile symbol list read in, initialize
  1570. // all the function entry counts to 0; if there is profile symbol list, only
  1571. // initialize the entry count to 0 when current function is in the list.
  1572. uint64_t initialEntryCount =
  1573. ((ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) &&
  1574. (!PSL || PSL->contains(F.getName())))
  1575. ? 0
  1576. : -1;
  1577. F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
  1578. std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
  1579. if (AM) {
  1580. auto &FAM =
  1581. AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
  1582. .getManager();
  1583. ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  1584. } else {
  1585. OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
  1586. ORE = OwnedORE.get();
  1587. }
  1588. Samples = Reader->getSamplesFor(F);
  1589. if (Samples && !Samples->empty())
  1590. return emitAnnotations(F);
  1591. return false;
  1592. }
  1593. PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
  1594. ModuleAnalysisManager &AM) {
  1595. FunctionAnalysisManager &FAM =
  1596. AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  1597. auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
  1598. return FAM.getResult<AssumptionAnalysis>(F);
  1599. };
  1600. auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
  1601. return FAM.getResult<TargetIRAnalysis>(F);
  1602. };
  1603. SampleProfileLoader SampleLoader(
  1604. ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
  1605. ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
  1606. : ProfileRemappingFileName,
  1607. IsThinLTOPreLink, GetAssumptionCache, GetTTI);
  1608. SampleLoader.doInitialization(M);
  1609. ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
  1610. if (!SampleLoader.runOnModule(M, &AM, PSI))
  1611. return PreservedAnalyses::all();
  1612. return PreservedAnalyses::none();
  1613. }