xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/SampleProfile.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the SampleProfileLoader transformation. This pass
100b57cec5SDimitry Andric // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
110b57cec5SDimitry Andric // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
120b57cec5SDimitry Andric // profile information in the given profile.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric // This pass generates branch weight annotations on the IR:
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric // - prof: Represents branch weights. This annotation is added to branches
170b57cec5SDimitry Andric //      to indicate the weights of each edge coming out of the branch.
180b57cec5SDimitry Andric //      The weight of each edge is the weight of the target block for
190b57cec5SDimitry Andric //      that edge. The weight of a block B is computed as the maximum
200b57cec5SDimitry Andric //      number of samples found in B.
210b57cec5SDimitry Andric //
220b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric #include "llvm/Transforms/IPO/SampleProfile.h"
250b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
260b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
270b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
28bdd1243dSDimitry Andric #include "llvm/ADT/MapVector.h"
29d409305fSDimitry Andric #include "llvm/ADT/PriorityQueue.h"
30480093f4SDimitry Andric #include "llvm/ADT/SCCIterator.h"
310b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
32480093f4SDimitry Andric #include "llvm/ADT/Statistic.h"
330b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
340b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
350b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
360b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
37fe6060f1SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
385ffd83dbSDimitry Andric #include "llvm/Analysis/InlineAdvisor.h"
390b57cec5SDimitry Andric #include "llvm/Analysis/InlineCost.h"
4006c3fb27SDimitry Andric #include "llvm/Analysis/LazyCallGraph.h"
410b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
420b57cec5SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
43e8d8bef9SDimitry Andric #include "llvm/Analysis/ReplayInlineAdvisor.h"
445ffd83dbSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
450b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
460b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
470b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
480b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
490b57cec5SDimitry Andric #include "llvm/IR/Function.h"
500b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
510b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
520b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
530b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
540b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
550b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
560b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
570b57cec5SDimitry Andric #include "llvm/IR/Module.h"
580b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
595f757f3fSDimitry Andric #include "llvm/IR/ProfDataUtils.h"
6081ad6265SDimitry Andric #include "llvm/IR/PseudoProbe.h"
610b57cec5SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
620b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
630b57cec5SDimitry Andric #include "llvm/ProfileData/SampleProf.h"
640b57cec5SDimitry Andric #include "llvm/ProfileData/SampleProfReader.h"
650b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
660b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
670b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
680b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
6906c3fb27SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
700b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
710b57cec5SDimitry Andric #include "llvm/Transforms/IPO.h"
72fe6060f1SDimitry Andric #include "llvm/Transforms/IPO/ProfiledCallGraph.h"
73e8d8bef9SDimitry Andric #include "llvm/Transforms/IPO/SampleContextTracker.h"
74*0fca6ea1SDimitry Andric #include "llvm/Transforms/IPO/SampleProfileMatcher.h"
75e8d8bef9SDimitry Andric #include "llvm/Transforms/IPO/SampleProfileProbe.h"
760b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation.h"
770b57cec5SDimitry Andric #include "llvm/Transforms/Utils/CallPromotionUtils.h"
780b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
79bdd1243dSDimitry Andric #include "llvm/Transforms/Utils/MisExpect.h"
80fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
81fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
820b57cec5SDimitry Andric #include <algorithm>
830b57cec5SDimitry Andric #include <cassert>
840b57cec5SDimitry Andric #include <cstdint>
850b57cec5SDimitry Andric #include <functional>
860b57cec5SDimitry Andric #include <limits>
870b57cec5SDimitry Andric #include <map>
880b57cec5SDimitry Andric #include <memory>
898bcb0991SDimitry Andric #include <queue>
900b57cec5SDimitry Andric #include <string>
910b57cec5SDimitry Andric #include <system_error>
920b57cec5SDimitry Andric #include <utility>
930b57cec5SDimitry Andric #include <vector>
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric using namespace llvm;
960b57cec5SDimitry Andric using namespace sampleprof;
97fe6060f1SDimitry Andric using namespace llvm::sampleprofutil;
980b57cec5SDimitry Andric using ProfileCount = Function::ProfileCount;
990b57cec5SDimitry Andric #define DEBUG_TYPE "sample-profile"
100480093f4SDimitry Andric #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
101480093f4SDimitry Andric 
102480093f4SDimitry Andric STATISTIC(NumCSInlined,
103480093f4SDimitry Andric           "Number of functions inlined with context sensitive profile");
104480093f4SDimitry Andric STATISTIC(NumCSNotInlined,
105480093f4SDimitry Andric           "Number of functions not inlined with context sensitive profile");
106e8d8bef9SDimitry Andric STATISTIC(NumMismatchedProfile,
107e8d8bef9SDimitry Andric           "Number of functions with CFG mismatched profile");
108e8d8bef9SDimitry Andric STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
109d409305fSDimitry Andric STATISTIC(NumDuplicatedInlinesite,
110d409305fSDimitry Andric           "Number of inlined callsites with a partial distribution factor");
111d409305fSDimitry Andric 
112d409305fSDimitry Andric STATISTIC(NumCSInlinedHitMinLimit,
113d409305fSDimitry Andric           "Number of functions with FDO inline stopped due to min size limit");
114d409305fSDimitry Andric STATISTIC(NumCSInlinedHitMaxLimit,
115d409305fSDimitry Andric           "Number of functions with FDO inline stopped due to max size limit");
116d409305fSDimitry Andric STATISTIC(
117d409305fSDimitry Andric     NumCSInlinedHitGrowthLimit,
118d409305fSDimitry Andric     "Number of functions with FDO inline stopped due to growth size limit");
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric // Command line option to specify the file to read samples from. This is
1210b57cec5SDimitry Andric // mainly used for debugging.
1220b57cec5SDimitry Andric static cl::opt<std::string> SampleProfileFile(
1230b57cec5SDimitry Andric     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
1240b57cec5SDimitry Andric     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric // The named file contains a set of transformations that may have been applied
1270b57cec5SDimitry Andric // to the symbol names between the program from which the sample data was
1280b57cec5SDimitry Andric // collected and the current program's symbols.
1290b57cec5SDimitry Andric static cl::opt<std::string> SampleProfileRemappingFile(
1300b57cec5SDimitry Andric     "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
1310b57cec5SDimitry Andric     cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
1320b57cec5SDimitry Andric 
133*0fca6ea1SDimitry Andric cl::opt<bool> SalvageStaleProfile(
13406c3fb27SDimitry Andric     "salvage-stale-profile", cl::Hidden, cl::init(false),
13506c3fb27SDimitry Andric     cl::desc("Salvage stale profile by fuzzy matching and use the remapped "
13606c3fb27SDimitry Andric              "location for sample profile query."));
137*0fca6ea1SDimitry Andric cl::opt<bool>
138*0fca6ea1SDimitry Andric     SalvageUnusedProfile("salvage-unused-profile", cl::Hidden, cl::init(false),
139*0fca6ea1SDimitry Andric                          cl::desc("Salvage unused profile by matching with new "
140*0fca6ea1SDimitry Andric                                   "functions on call graph."));
14106c3fb27SDimitry Andric 
142*0fca6ea1SDimitry Andric cl::opt<bool> ReportProfileStaleness(
143bdd1243dSDimitry Andric     "report-profile-staleness", cl::Hidden, cl::init(false),
144bdd1243dSDimitry Andric     cl::desc("Compute and report stale profile statistical metrics."));
145bdd1243dSDimitry Andric 
146*0fca6ea1SDimitry Andric cl::opt<bool> PersistProfileStaleness(
147bdd1243dSDimitry Andric     "persist-profile-staleness", cl::Hidden, cl::init(false),
148bdd1243dSDimitry Andric     cl::desc("Compute stale profile statistical metrics and write it into the "
149bdd1243dSDimitry Andric              "native object file(.llvm_stats section)."));
150bdd1243dSDimitry Andric 
1510b57cec5SDimitry Andric static cl::opt<bool> ProfileSampleAccurate(
1520b57cec5SDimitry Andric     "profile-sample-accurate", cl::Hidden, cl::init(false),
1530b57cec5SDimitry Andric     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
1540b57cec5SDimitry Andric              "callsite and function as having 0 samples. Otherwise, treat "
1550b57cec5SDimitry Andric              "un-sampled callsites and functions conservatively as unknown. "));
1560b57cec5SDimitry Andric 
157349cc55cSDimitry Andric static cl::opt<bool> ProfileSampleBlockAccurate(
158349cc55cSDimitry Andric     "profile-sample-block-accurate", cl::Hidden, cl::init(false),
159349cc55cSDimitry Andric     cl::desc("If the sample profile is accurate, we will mark all un-sampled "
160349cc55cSDimitry Andric              "branches and calls as having 0 samples. Otherwise, treat "
161349cc55cSDimitry Andric              "them conservatively as unknown. "));
162349cc55cSDimitry Andric 
1638bcb0991SDimitry Andric static cl::opt<bool> ProfileAccurateForSymsInList(
16481ad6265SDimitry Andric     "profile-accurate-for-symsinlist", cl::Hidden, cl::init(true),
1658bcb0991SDimitry Andric     cl::desc("For symbols in profile symbol list, regard their profiles to "
1668bcb0991SDimitry Andric              "be accurate. It may be overriden by profile-sample-accurate. "));
1678bcb0991SDimitry Andric 
168480093f4SDimitry Andric static cl::opt<bool> ProfileMergeInlinee(
1695ffd83dbSDimitry Andric     "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
170480093f4SDimitry Andric     cl::desc("Merge past inlinee's profile to outline version if sample "
1715ffd83dbSDimitry Andric              "profile loader decided not to inline a call site. It will "
1725ffd83dbSDimitry Andric              "only be enabled when top-down order of profile loading is "
1735ffd83dbSDimitry Andric              "enabled. "));
174480093f4SDimitry Andric 
175480093f4SDimitry Andric static cl::opt<bool> ProfileTopDownLoad(
1765ffd83dbSDimitry Andric     "sample-profile-top-down-load", cl::Hidden, cl::init(true),
177480093f4SDimitry Andric     cl::desc("Do profile annotation and inlining for functions in top-down "
1785ffd83dbSDimitry Andric              "order of call graph during sample profile loading. It only "
1795ffd83dbSDimitry Andric              "works for new pass manager. "));
180480093f4SDimitry Andric 
181fe6060f1SDimitry Andric static cl::opt<bool>
182fe6060f1SDimitry Andric     UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden,
183fe6060f1SDimitry Andric                          cl::desc("Process functions in a top-down order "
184fe6060f1SDimitry Andric                                   "defined by the profiled call graph when "
185fe6060f1SDimitry Andric                                   "-sample-profile-top-down-load is on."));
186d409305fSDimitry Andric 
187480093f4SDimitry Andric static cl::opt<bool> ProfileSizeInline(
188480093f4SDimitry Andric     "sample-profile-inline-size", cl::Hidden, cl::init(false),
189480093f4SDimitry Andric     cl::desc("Inline cold call sites in profile loader if it's beneficial "
190480093f4SDimitry Andric              "for code size."));
191480093f4SDimitry Andric 
19281ad6265SDimitry Andric // Since profiles are consumed by many passes, turning on this option has
19381ad6265SDimitry Andric // side effects. For instance, pre-link SCC inliner would see merged profiles
19481ad6265SDimitry Andric // and inline the hot functions (that are skipped in this pass).
19581ad6265SDimitry Andric static cl::opt<bool> DisableSampleLoaderInlining(
19681ad6265SDimitry Andric     "disable-sample-loader-inlining", cl::Hidden, cl::init(false),
19781ad6265SDimitry Andric     cl::desc("If true, artifically skip inline transformation in sample-loader "
19881ad6265SDimitry Andric              "pass, and merge (or scale) profiles (as configured by "
19981ad6265SDimitry Andric              "--sample-profile-merge-inlinee)."));
20081ad6265SDimitry Andric 
20106c3fb27SDimitry Andric namespace llvm {
20206c3fb27SDimitry Andric cl::opt<bool>
20306c3fb27SDimitry Andric     SortProfiledSCC("sort-profiled-scc-member", cl::init(true), cl::Hidden,
20406c3fb27SDimitry Andric                     cl::desc("Sort profiled recursion by edge weights."));
20506c3fb27SDimitry Andric 
206fe6060f1SDimitry Andric cl::opt<int> ProfileInlineGrowthLimit(
207d409305fSDimitry Andric     "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12),
208d409305fSDimitry Andric     cl::desc("The size growth ratio limit for proirity-based sample profile "
209d409305fSDimitry Andric              "loader inlining."));
210d409305fSDimitry Andric 
211fe6060f1SDimitry Andric cl::opt<int> ProfileInlineLimitMin(
212d409305fSDimitry Andric     "sample-profile-inline-limit-min", cl::Hidden, cl::init(100),
213d409305fSDimitry Andric     cl::desc("The lower bound of size growth limit for "
214d409305fSDimitry Andric              "proirity-based sample profile loader inlining."));
215d409305fSDimitry Andric 
216fe6060f1SDimitry Andric cl::opt<int> ProfileInlineLimitMax(
217d409305fSDimitry Andric     "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000),
218d409305fSDimitry Andric     cl::desc("The upper bound of size growth limit for "
219d409305fSDimitry Andric              "proirity-based sample profile loader inlining."));
220d409305fSDimitry Andric 
221fe6060f1SDimitry Andric cl::opt<int> SampleHotCallSiteThreshold(
222d409305fSDimitry Andric     "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000),
223d409305fSDimitry Andric     cl::desc("Hot callsite threshold for proirity-based sample profile loader "
224d409305fSDimitry Andric              "inlining."));
225d409305fSDimitry Andric 
226fe6060f1SDimitry Andric cl::opt<int> SampleColdCallSiteThreshold(
227fe6060f1SDimitry Andric     "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
228fe6060f1SDimitry Andric     cl::desc("Threshold for inlining cold callsites"));
22906c3fb27SDimitry Andric } // namespace llvm
230fe6060f1SDimitry Andric 
231fe6060f1SDimitry Andric static cl::opt<unsigned> ProfileICPRelativeHotness(
232fe6060f1SDimitry Andric     "sample-profile-icp-relative-hotness", cl::Hidden, cl::init(25),
233fe6060f1SDimitry Andric     cl::desc(
234fe6060f1SDimitry Andric         "Relative hotness percentage threshold for indirect "
235fe6060f1SDimitry Andric         "call promotion in proirity-based sample profile loader inlining."));
236fe6060f1SDimitry Andric 
237fe6060f1SDimitry Andric static cl::opt<unsigned> ProfileICPRelativeHotnessSkip(
238fe6060f1SDimitry Andric     "sample-profile-icp-relative-hotness-skip", cl::Hidden, cl::init(1),
239fe6060f1SDimitry Andric     cl::desc(
240fe6060f1SDimitry Andric         "Skip relative hotness check for ICP up to given number of targets."));
241fe6060f1SDimitry Andric 
242*0fca6ea1SDimitry Andric static cl::opt<unsigned> HotFuncCutoffForStalenessError(
243*0fca6ea1SDimitry Andric     "hot-func-cutoff-for-staleness-error", cl::Hidden, cl::init(800000),
244*0fca6ea1SDimitry Andric     cl::desc("A function is considered hot for staleness error check if its "
245*0fca6ea1SDimitry Andric              "total sample count is above the specified percentile"));
246*0fca6ea1SDimitry Andric 
247*0fca6ea1SDimitry Andric static cl::opt<unsigned> MinfuncsForStalenessError(
248*0fca6ea1SDimitry Andric     "min-functions-for-staleness-error", cl::Hidden, cl::init(50),
249*0fca6ea1SDimitry Andric     cl::desc("Skip the check if the number of hot functions is smaller than "
250*0fca6ea1SDimitry Andric              "the specified number."));
251*0fca6ea1SDimitry Andric 
252*0fca6ea1SDimitry Andric static cl::opt<unsigned> PrecentMismatchForStalenessError(
253*0fca6ea1SDimitry Andric     "precent-mismatch-for-staleness-error", cl::Hidden, cl::init(80),
254*0fca6ea1SDimitry Andric     cl::desc("Reject the profile if the mismatch percent is higher than the "
255*0fca6ea1SDimitry Andric              "given number."));
256*0fca6ea1SDimitry Andric 
257d409305fSDimitry Andric static cl::opt<bool> CallsitePrioritizedInline(
25881ad6265SDimitry Andric     "sample-profile-prioritized-inline", cl::Hidden,
259d409305fSDimitry Andric     cl::desc("Use call site prioritized inlining for sample profile loader."
260d409305fSDimitry Andric              "Currently only CSSPGO is supported."));
261d409305fSDimitry Andric 
262349cc55cSDimitry Andric static cl::opt<bool> UsePreInlinerDecision(
26381ad6265SDimitry Andric     "sample-profile-use-preinliner", cl::Hidden,
264349cc55cSDimitry Andric     cl::desc("Use the preinliner decisions stored in profile context."));
265349cc55cSDimitry Andric 
266349cc55cSDimitry Andric static cl::opt<bool> AllowRecursiveInline(
26781ad6265SDimitry Andric     "sample-profile-recursive-inline", cl::Hidden,
268349cc55cSDimitry Andric     cl::desc("Allow sample loader inliner to inline recursive calls."));
269349cc55cSDimitry Andric 
270*0fca6ea1SDimitry Andric static cl::opt<bool> RemoveProbeAfterProfileAnnotation(
271*0fca6ea1SDimitry Andric     "sample-profile-remove-probe", cl::Hidden, cl::init(false),
272*0fca6ea1SDimitry Andric     cl::desc("Remove pseudo-probe after sample profile annotation."));
273*0fca6ea1SDimitry Andric 
274e8d8bef9SDimitry Andric static cl::opt<std::string> ProfileInlineReplayFile(
275e8d8bef9SDimitry Andric     "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
276e8d8bef9SDimitry Andric     cl::desc(
277e8d8bef9SDimitry Andric         "Optimization remarks file containing inline remarks to be replayed "
278e8d8bef9SDimitry Andric         "by inlining from sample profile loader."),
279e8d8bef9SDimitry Andric     cl::Hidden);
280e8d8bef9SDimitry Andric 
281349cc55cSDimitry Andric static cl::opt<ReplayInlinerSettings::Scope> ProfileInlineReplayScope(
282349cc55cSDimitry Andric     "sample-profile-inline-replay-scope",
283349cc55cSDimitry Andric     cl::init(ReplayInlinerSettings::Scope::Function),
284349cc55cSDimitry Andric     cl::values(clEnumValN(ReplayInlinerSettings::Scope::Function, "Function",
285349cc55cSDimitry Andric                           "Replay on functions that have remarks associated "
286349cc55cSDimitry Andric                           "with them (default)"),
287349cc55cSDimitry Andric                clEnumValN(ReplayInlinerSettings::Scope::Module, "Module",
288349cc55cSDimitry Andric                           "Replay on the entire module")),
289349cc55cSDimitry Andric     cl::desc("Whether inline replay should be applied to the entire "
290349cc55cSDimitry Andric              "Module or just the Functions (default) that are present as "
291349cc55cSDimitry Andric              "callers in remarks during sample profile inlining."),
292349cc55cSDimitry Andric     cl::Hidden);
293349cc55cSDimitry Andric 
294349cc55cSDimitry Andric static cl::opt<ReplayInlinerSettings::Fallback> ProfileInlineReplayFallback(
295349cc55cSDimitry Andric     "sample-profile-inline-replay-fallback",
296349cc55cSDimitry Andric     cl::init(ReplayInlinerSettings::Fallback::Original),
297349cc55cSDimitry Andric     cl::values(
298349cc55cSDimitry Andric         clEnumValN(
299349cc55cSDimitry Andric             ReplayInlinerSettings::Fallback::Original, "Original",
300349cc55cSDimitry Andric             "All decisions not in replay send to original advisor (default)"),
301349cc55cSDimitry Andric         clEnumValN(ReplayInlinerSettings::Fallback::AlwaysInline,
302349cc55cSDimitry Andric                    "AlwaysInline", "All decisions not in replay are inlined"),
303349cc55cSDimitry Andric         clEnumValN(ReplayInlinerSettings::Fallback::NeverInline, "NeverInline",
304349cc55cSDimitry Andric                    "All decisions not in replay are not inlined")),
305349cc55cSDimitry Andric     cl::desc("How sample profile inline replay treats sites that don't come "
306349cc55cSDimitry Andric              "from the replay. Original: defers to original advisor, "
307349cc55cSDimitry Andric              "AlwaysInline: inline all sites not in replay, NeverInline: "
308349cc55cSDimitry Andric              "inline no sites not in replay"),
309349cc55cSDimitry Andric     cl::Hidden);
310349cc55cSDimitry Andric 
311349cc55cSDimitry Andric static cl::opt<CallSiteFormat::Format> ProfileInlineReplayFormat(
312349cc55cSDimitry Andric     "sample-profile-inline-replay-format",
313349cc55cSDimitry Andric     cl::init(CallSiteFormat::Format::LineColumnDiscriminator),
314349cc55cSDimitry Andric     cl::values(
315349cc55cSDimitry Andric         clEnumValN(CallSiteFormat::Format::Line, "Line", "<Line Number>"),
316349cc55cSDimitry Andric         clEnumValN(CallSiteFormat::Format::LineColumn, "LineColumn",
317349cc55cSDimitry Andric                    "<Line Number>:<Column Number>"),
318349cc55cSDimitry Andric         clEnumValN(CallSiteFormat::Format::LineDiscriminator,
319349cc55cSDimitry Andric                    "LineDiscriminator", "<Line Number>.<Discriminator>"),
320349cc55cSDimitry Andric         clEnumValN(CallSiteFormat::Format::LineColumnDiscriminator,
321349cc55cSDimitry Andric                    "LineColumnDiscriminator",
322349cc55cSDimitry Andric                    "<Line Number>:<Column Number>.<Discriminator> (default)")),
323349cc55cSDimitry Andric     cl::desc("How sample profile inline replay file is formatted"), cl::Hidden);
324349cc55cSDimitry Andric 
325fe6060f1SDimitry Andric static cl::opt<unsigned>
326fe6060f1SDimitry Andric     MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden,
327fe6060f1SDimitry Andric                      cl::desc("Max number of promotions for a single indirect "
328fe6060f1SDimitry Andric                               "call callsite in sample profile loader"));
329fe6060f1SDimitry Andric 
330fe6060f1SDimitry Andric static cl::opt<bool> OverwriteExistingWeights(
331fe6060f1SDimitry Andric     "overwrite-existing-weights", cl::Hidden, cl::init(false),
332fe6060f1SDimitry Andric     cl::desc("Ignore existing branch weights on IR and always overwrite."));
333fe6060f1SDimitry Andric 
33481ad6265SDimitry Andric static cl::opt<bool> AnnotateSampleProfileInlinePhase(
33581ad6265SDimitry Andric     "annotate-sample-profile-inline-phase", cl::Hidden, cl::init(false),
33681ad6265SDimitry Andric     cl::desc("Annotate LTO phase (prelink / postlink), or main (no LTO) for "
33781ad6265SDimitry Andric              "sample-profile inline pass name."));
33881ad6265SDimitry Andric 
33906c3fb27SDimitry Andric namespace llvm {
34081ad6265SDimitry Andric extern cl::opt<bool> EnableExtTspBlockPlacement;
34106c3fb27SDimitry Andric }
34281ad6265SDimitry Andric 
3430b57cec5SDimitry Andric namespace {
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
3460b57cec5SDimitry Andric using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
3470b57cec5SDimitry Andric using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
3480b57cec5SDimitry Andric using EdgeWeightMap = DenseMap<Edge, uint64_t>;
3490b57cec5SDimitry Andric using BlockEdgeMap =
3500b57cec5SDimitry Andric     DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
3510b57cec5SDimitry Andric 
3528bcb0991SDimitry Andric class GUIDToFuncNameMapper {
3538bcb0991SDimitry Andric public:
3548bcb0991SDimitry Andric   GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
3558bcb0991SDimitry Andric                        DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
3568bcb0991SDimitry Andric       : CurrentReader(Reader), CurrentModule(M),
3578bcb0991SDimitry Andric         CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
3585ffd83dbSDimitry Andric     if (!CurrentReader.useMD5())
3598bcb0991SDimitry Andric       return;
3608bcb0991SDimitry Andric 
3618bcb0991SDimitry Andric     for (const auto &F : CurrentModule) {
3628bcb0991SDimitry Andric       StringRef OrigName = F.getName();
3638bcb0991SDimitry Andric       CurrentGUIDToFuncNameMap.insert(
3648bcb0991SDimitry Andric           {Function::getGUID(OrigName), OrigName});
3658bcb0991SDimitry Andric 
3668bcb0991SDimitry Andric       // Local to global var promotion used by optimization like thinlto
3678bcb0991SDimitry Andric       // will rename the var and add suffix like ".llvm.xxx" to the
3688bcb0991SDimitry Andric       // original local name. In sample profile, the suffixes of function
3698bcb0991SDimitry Andric       // names are all stripped. Since it is possible that the mapper is
3708bcb0991SDimitry Andric       // built in post-thin-link phase and var promotion has been done,
3718bcb0991SDimitry Andric       // we need to add the substring of function name without the suffix
3728bcb0991SDimitry Andric       // into the GUIDToFuncNameMap.
3738bcb0991SDimitry Andric       StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
3748bcb0991SDimitry Andric       if (CanonName != OrigName)
3758bcb0991SDimitry Andric         CurrentGUIDToFuncNameMap.insert(
3768bcb0991SDimitry Andric             {Function::getGUID(CanonName), CanonName});
3778bcb0991SDimitry Andric     }
3788bcb0991SDimitry Andric 
3798bcb0991SDimitry Andric     // Update GUIDToFuncNameMap for each function including inlinees.
3808bcb0991SDimitry Andric     SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
3818bcb0991SDimitry Andric   }
3828bcb0991SDimitry Andric 
3838bcb0991SDimitry Andric   ~GUIDToFuncNameMapper() {
3845ffd83dbSDimitry Andric     if (!CurrentReader.useMD5())
3858bcb0991SDimitry Andric       return;
3868bcb0991SDimitry Andric 
3878bcb0991SDimitry Andric     CurrentGUIDToFuncNameMap.clear();
3888bcb0991SDimitry Andric 
3898bcb0991SDimitry Andric     // Reset GUIDToFuncNameMap for of each function as they're no
3908bcb0991SDimitry Andric     // longer valid at this point.
3918bcb0991SDimitry Andric     SetGUIDToFuncNameMapForAll(nullptr);
3928bcb0991SDimitry Andric   }
3938bcb0991SDimitry Andric 
3948bcb0991SDimitry Andric private:
3958bcb0991SDimitry Andric   void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
3968bcb0991SDimitry Andric     std::queue<FunctionSamples *> FSToUpdate;
3978bcb0991SDimitry Andric     for (auto &IFS : CurrentReader.getProfiles()) {
3988bcb0991SDimitry Andric       FSToUpdate.push(&IFS.second);
3998bcb0991SDimitry Andric     }
4008bcb0991SDimitry Andric 
4018bcb0991SDimitry Andric     while (!FSToUpdate.empty()) {
4028bcb0991SDimitry Andric       FunctionSamples *FS = FSToUpdate.front();
4038bcb0991SDimitry Andric       FSToUpdate.pop();
4048bcb0991SDimitry Andric       FS->GUIDToFuncNameMap = Map;
4058bcb0991SDimitry Andric       for (const auto &ICS : FS->getCallsiteSamples()) {
4068bcb0991SDimitry Andric         const FunctionSamplesMap &FSMap = ICS.second;
407bdd1243dSDimitry Andric         for (const auto &IFS : FSMap) {
4088bcb0991SDimitry Andric           FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
4098bcb0991SDimitry Andric           FSToUpdate.push(&FS);
4108bcb0991SDimitry Andric         }
4118bcb0991SDimitry Andric       }
4128bcb0991SDimitry Andric     }
4138bcb0991SDimitry Andric   }
4148bcb0991SDimitry Andric 
4158bcb0991SDimitry Andric   SampleProfileReader &CurrentReader;
4168bcb0991SDimitry Andric   Module &CurrentModule;
4178bcb0991SDimitry Andric   DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
4180b57cec5SDimitry Andric };
4190b57cec5SDimitry Andric 
420d409305fSDimitry Andric // Inline candidate used by iterative callsite prioritized inliner
421d409305fSDimitry Andric struct InlineCandidate {
422d409305fSDimitry Andric   CallBase *CallInstr;
423d409305fSDimitry Andric   const FunctionSamples *CalleeSamples;
424d409305fSDimitry Andric   // Prorated callsite count, which will be used to guide inlining. For example,
425d409305fSDimitry Andric   // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
426d409305fSDimitry Andric   // copies will get their own distribution factors and their prorated counts
427d409305fSDimitry Andric   // will be used to decide if they should be inlined independently.
428d409305fSDimitry Andric   uint64_t CallsiteCount;
429d409305fSDimitry Andric   // Call site distribution factor to prorate the profile samples for a
430d409305fSDimitry Andric   // duplicated callsite. Default value is 1.0.
431d409305fSDimitry Andric   float CallsiteDistribution;
432d409305fSDimitry Andric };
433d409305fSDimitry Andric 
434d409305fSDimitry Andric // Inline candidate comparer using call site weight
435d409305fSDimitry Andric struct CandidateComparer {
436d409305fSDimitry Andric   bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
437d409305fSDimitry Andric     if (LHS.CallsiteCount != RHS.CallsiteCount)
438d409305fSDimitry Andric       return LHS.CallsiteCount < RHS.CallsiteCount;
439d409305fSDimitry Andric 
440fe6060f1SDimitry Andric     const FunctionSamples *LCS = LHS.CalleeSamples;
441fe6060f1SDimitry Andric     const FunctionSamples *RCS = RHS.CalleeSamples;
442*0fca6ea1SDimitry Andric     // In inline replay mode, CalleeSamples may be null and the order doesn't
443*0fca6ea1SDimitry Andric     // matter.
444*0fca6ea1SDimitry Andric     if (!LCS || !RCS)
445*0fca6ea1SDimitry Andric       return LCS;
446fe6060f1SDimitry Andric 
447fe6060f1SDimitry Andric     // Tie breaker using number of samples try to favor smaller functions first
448fe6060f1SDimitry Andric     if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
449fe6060f1SDimitry Andric       return LCS->getBodySamples().size() > RCS->getBodySamples().size();
450fe6060f1SDimitry Andric 
451d409305fSDimitry Andric     // Tie breaker using GUID so we have stable/deterministic inlining order
4525f757f3fSDimitry Andric     return LCS->getGUID() < RCS->getGUID();
453d409305fSDimitry Andric   }
454d409305fSDimitry Andric };
455d409305fSDimitry Andric 
456d409305fSDimitry Andric using CandidateQueue =
457d409305fSDimitry Andric     PriorityQueue<InlineCandidate, std::vector<InlineCandidate>,
458d409305fSDimitry Andric                   CandidateComparer>;
459d409305fSDimitry Andric 
4600b57cec5SDimitry Andric /// Sample profile pass.
4610b57cec5SDimitry Andric ///
4620b57cec5SDimitry Andric /// This pass reads profile data from the file specified by
4630b57cec5SDimitry Andric /// -sample-profile-file and annotates every affected function with the
4640b57cec5SDimitry Andric /// profile information found in that file.
46506c3fb27SDimitry Andric class SampleProfileLoader final : public SampleProfileLoaderBaseImpl<Function> {
4660b57cec5SDimitry Andric public:
4670b57cec5SDimitry Andric   SampleProfileLoader(
468e8d8bef9SDimitry Andric       StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
46906c3fb27SDimitry Andric       IntrusiveRefCntPtr<vfs::FileSystem> FS,
4700b57cec5SDimitry Andric       std::function<AssumptionCache &(Function &)> GetAssumptionCache,
4715ffd83dbSDimitry Andric       std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
472*0fca6ea1SDimitry Andric       std::function<const TargetLibraryInfo &(Function &)> GetTLI,
473*0fca6ea1SDimitry Andric       LazyCallGraph &CG)
47406c3fb27SDimitry Andric       : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName),
47506c3fb27SDimitry Andric                                     std::move(FS)),
476fe6060f1SDimitry Andric         GetAC(std::move(GetAssumptionCache)),
4775ffd83dbSDimitry Andric         GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
478*0fca6ea1SDimitry Andric         CG(CG), LTOPhase(LTOPhase),
47981ad6265SDimitry Andric         AnnotatedPassName(AnnotateSampleProfileInlinePhase
48081ad6265SDimitry Andric                               ? llvm::AnnotateInlinePassName(InlineContext{
48181ad6265SDimitry Andric                                     LTOPhase, InlinePass::SampleProfileInliner})
48281ad6265SDimitry Andric                               : CSINLINE_DEBUG) {}
4830b57cec5SDimitry Andric 
484e8d8bef9SDimitry Andric   bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
4850b57cec5SDimitry Andric   bool runOnModule(Module &M, ModuleAnalysisManager *AM,
486*0fca6ea1SDimitry Andric                    ProfileSummaryInfo *_PSI);
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric protected:
4890b57cec5SDimitry Andric   bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
4900b57cec5SDimitry Andric   bool emitAnnotations(Function &F);
491fe6060f1SDimitry Andric   ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
4925ffd83dbSDimitry Andric   const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
493fe6060f1SDimitry Andric   const FunctionSamples *
494fe6060f1SDimitry Andric   findFunctionSamples(const Instruction &I) const override;
4950b57cec5SDimitry Andric   std::vector<const FunctionSamples *>
4960b57cec5SDimitry Andric   findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
497349cc55cSDimitry Andric   void findExternalInlineCandidate(CallBase *CB, const FunctionSamples *Samples,
498fe6060f1SDimitry Andric                                    DenseSet<GlobalValue::GUID> &InlinedGUIDs,
499fe6060f1SDimitry Andric                                    uint64_t Threshold);
500d409305fSDimitry Andric   // Attempt to promote indirect call and also inline the promoted call
501d409305fSDimitry Andric   bool tryPromoteAndInlineCandidate(
502d409305fSDimitry Andric       Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
503fe6060f1SDimitry Andric       uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
504349cc55cSDimitry Andric 
5050b57cec5SDimitry Andric   bool inlineHotFunctions(Function &F,
5060b57cec5SDimitry Andric                           DenseSet<GlobalValue::GUID> &InlinedGUIDs);
507bdd1243dSDimitry Andric   std::optional<InlineCost> getExternalInlineAdvisorCost(CallBase &CB);
508349cc55cSDimitry Andric   bool getExternalInlineAdvisorShouldInline(CallBase &CB);
509d409305fSDimitry Andric   InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
510d409305fSDimitry Andric   bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
511d409305fSDimitry Andric   bool
512d409305fSDimitry Andric   tryInlineCandidate(InlineCandidate &Candidate,
513d409305fSDimitry Andric                      SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
514d409305fSDimitry Andric   bool
515d409305fSDimitry Andric   inlineHotFunctionsWithPriority(Function &F,
516d409305fSDimitry Andric                                  DenseSet<GlobalValue::GUID> &InlinedGUIDs);
517480093f4SDimitry Andric   // Inline cold/small functions in addition to hot ones
5185ffd83dbSDimitry Andric   bool shouldInlineColdCallee(CallBase &CallInst);
519480093f4SDimitry Andric   void emitOptimizationRemarksForInlineCandidates(
5205ffd83dbSDimitry Andric       const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
5215ffd83dbSDimitry Andric       bool Hot);
5220eae32dcSDimitry Andric   void promoteMergeNotInlinedContextSamples(
523bdd1243dSDimitry Andric       MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
5240eae32dcSDimitry Andric       const Function &F);
52506c3fb27SDimitry Andric   std::vector<Function *> buildFunctionOrder(Module &M, LazyCallGraph &CG);
52606c3fb27SDimitry Andric   std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(Module &M);
527fe6060f1SDimitry Andric   void generateMDProfMetadata(Function &F);
528*0fca6ea1SDimitry Andric   bool rejectHighStalenessProfile(Module &M, ProfileSummaryInfo *PSI,
529*0fca6ea1SDimitry Andric                                   const SampleProfileMap &Profiles);
530*0fca6ea1SDimitry Andric   void removePseudoProbeInsts(Module &M);
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric   /// Map from function name to Function *. Used to find the function from
5330b57cec5SDimitry Andric   /// the function name. If the function name contains suffix, additional
5340b57cec5SDimitry Andric   /// entry is added to map from the stripped name to the function if there
5350b57cec5SDimitry Andric   /// is one-to-one mapping.
5365f757f3fSDimitry Andric   HashKeyMap<std::unordered_map, FunctionId, Function *> SymbolMap;
5370b57cec5SDimitry Andric 
538*0fca6ea1SDimitry Andric   /// Map from function name to profile name generated by call-graph based
539*0fca6ea1SDimitry Andric   /// profile fuzzy matching(--salvage-unused-profile).
540*0fca6ea1SDimitry Andric   HashKeyMap<std::unordered_map, FunctionId, FunctionId> FuncNameToProfNameMap;
541*0fca6ea1SDimitry Andric 
5420b57cec5SDimitry Andric   std::function<AssumptionCache &(Function &)> GetAC;
5430b57cec5SDimitry Andric   std::function<TargetTransformInfo &(Function &)> GetTTI;
5445ffd83dbSDimitry Andric   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
545*0fca6ea1SDimitry Andric   LazyCallGraph &CG;
5460b57cec5SDimitry Andric 
547e8d8bef9SDimitry Andric   /// Profile tracker for different context.
548e8d8bef9SDimitry Andric   std::unique_ptr<SampleContextTracker> ContextTracker;
549e8d8bef9SDimitry Andric 
550e8d8bef9SDimitry Andric   /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
5510b57cec5SDimitry Andric   ///
552e8d8bef9SDimitry Andric   /// We need to know the LTO phase because for example in ThinLTOPrelink
553e8d8bef9SDimitry Andric   /// phase, in annotation, we should not promote indirect calls. Instead,
554e8d8bef9SDimitry Andric   /// we will mark GUIDs that needs to be annotated to the function.
55581ad6265SDimitry Andric   const ThinOrFullLTOPhase LTOPhase;
55681ad6265SDimitry Andric   const std::string AnnotatedPassName;
5570b57cec5SDimitry Andric 
5588bcb0991SDimitry Andric   /// Profle Symbol list tells whether a function name appears in the binary
5598bcb0991SDimitry Andric   /// used to generate the current profile.
560*0fca6ea1SDimitry Andric   std::shared_ptr<ProfileSymbolList> PSL;
5618bcb0991SDimitry Andric 
5620b57cec5SDimitry Andric   /// Total number of samples collected in this profile.
5630b57cec5SDimitry Andric   ///
5640b57cec5SDimitry Andric   /// This is the sum of all the samples collected in all the functions executed
5650b57cec5SDimitry Andric   /// at runtime.
5660b57cec5SDimitry Andric   uint64_t TotalCollectedSamples = 0;
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   // Information recorded when we declined to inline a call site
5690b57cec5SDimitry Andric   // because we have determined it is too cold is accumulated for
5700b57cec5SDimitry Andric   // each callee function. Initially this is just the entry count.
5710b57cec5SDimitry Andric   struct NotInlinedProfileInfo {
5720b57cec5SDimitry Andric     uint64_t entryCount;
5730b57cec5SDimitry Andric   };
5740b57cec5SDimitry Andric   DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
5758bcb0991SDimitry Andric 
5768bcb0991SDimitry Andric   // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
5778bcb0991SDimitry Andric   // all the function symbols defined or declared in current module.
5788bcb0991SDimitry Andric   DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
5798bcb0991SDimitry Andric 
5808bcb0991SDimitry Andric   // All the Names used in FunctionSamples including outline function
5818bcb0991SDimitry Andric   // names, inline instance names and call target names.
5828bcb0991SDimitry Andric   StringSet<> NamesInProfile;
5835f757f3fSDimitry Andric   // MD5 version of NamesInProfile. Either NamesInProfile or GUIDsInProfile is
5845f757f3fSDimitry Andric   // populated, depends on whether the profile uses MD5. Because the name table
5855f757f3fSDimitry Andric   // generally contains several magnitude more entries than the number of
5865f757f3fSDimitry Andric   // functions, we do not want to convert all names from one form to another.
5875f757f3fSDimitry Andric   llvm::DenseSet<uint64_t> GUIDsInProfile;
5888bcb0991SDimitry Andric 
5898bcb0991SDimitry Andric   // For symbol in profile symbol list, whether to regard their profiles
5908bcb0991SDimitry Andric   // to be accurate. It is mainly decided by existance of profile symbol
5918bcb0991SDimitry Andric   // list and -profile-accurate-for-symsinlist flag, but it can be
5928bcb0991SDimitry Andric   // overriden by -profile-sample-accurate or profile-sample-accurate
5938bcb0991SDimitry Andric   // attribute.
5948bcb0991SDimitry Andric   bool ProfAccForSymsInList;
595e8d8bef9SDimitry Andric 
596e8d8bef9SDimitry Andric   // External inline advisor used to replay inline decision from remarks.
597349cc55cSDimitry Andric   std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
598e8d8bef9SDimitry Andric 
599bdd1243dSDimitry Andric   // A helper to implement the sample profile matching algorithm.
600bdd1243dSDimitry Andric   std::unique_ptr<SampleProfileMatcher> MatchingManager;
601bdd1243dSDimitry Andric 
60281ad6265SDimitry Andric private:
60381ad6265SDimitry Andric   const char *getAnnotatedRemarkPassName() const {
60481ad6265SDimitry Andric     return AnnotatedPassName.c_str();
60581ad6265SDimitry Andric   }
6060b57cec5SDimitry Andric };
6070b57cec5SDimitry Andric } // end anonymous namespace
6080b57cec5SDimitry Andric 
60906c3fb27SDimitry Andric namespace llvm {
61006c3fb27SDimitry Andric template <>
61106c3fb27SDimitry Andric inline bool SampleProfileInference<Function>::isExit(const BasicBlock *BB) {
61206c3fb27SDimitry Andric   return succ_empty(BB);
61306c3fb27SDimitry Andric }
61406c3fb27SDimitry Andric 
61506c3fb27SDimitry Andric template <>
61606c3fb27SDimitry Andric inline void SampleProfileInference<Function>::findUnlikelyJumps(
61706c3fb27SDimitry Andric     const std::vector<const BasicBlockT *> &BasicBlocks,
61806c3fb27SDimitry Andric     BlockEdgeMap &Successors, FlowFunction &Func) {
61906c3fb27SDimitry Andric   for (auto &Jump : Func.Jumps) {
62006c3fb27SDimitry Andric     const auto *BB = BasicBlocks[Jump.Source];
62106c3fb27SDimitry Andric     const auto *Succ = BasicBlocks[Jump.Target];
62206c3fb27SDimitry Andric     const Instruction *TI = BB->getTerminator();
62306c3fb27SDimitry Andric     // Check if a block ends with InvokeInst and mark non-taken branch unlikely.
62406c3fb27SDimitry Andric     // In that case block Succ should be a landing pad
62506c3fb27SDimitry Andric     if (Successors[BB].size() == 2 && Successors[BB].back() == Succ) {
62606c3fb27SDimitry Andric       if (isa<InvokeInst>(TI)) {
62706c3fb27SDimitry Andric         Jump.IsUnlikely = true;
62806c3fb27SDimitry Andric       }
62906c3fb27SDimitry Andric     }
63006c3fb27SDimitry Andric     const Instruction *SuccTI = Succ->getTerminator();
63106c3fb27SDimitry Andric     // Check if the target block contains UnreachableInst and mark it unlikely
63206c3fb27SDimitry Andric     if (SuccTI->getNumSuccessors() == 0) {
63306c3fb27SDimitry Andric       if (isa<UnreachableInst>(SuccTI)) {
63406c3fb27SDimitry Andric         Jump.IsUnlikely = true;
63506c3fb27SDimitry Andric       }
63606c3fb27SDimitry Andric     }
63706c3fb27SDimitry Andric   }
63806c3fb27SDimitry Andric }
63906c3fb27SDimitry Andric 
64006c3fb27SDimitry Andric template <>
64106c3fb27SDimitry Andric void SampleProfileLoaderBaseImpl<Function>::computeDominanceAndLoopInfo(
64206c3fb27SDimitry Andric     Function &F) {
64306c3fb27SDimitry Andric   DT.reset(new DominatorTree);
64406c3fb27SDimitry Andric   DT->recalculate(F);
64506c3fb27SDimitry Andric 
64606c3fb27SDimitry Andric   PDT.reset(new PostDominatorTree(F));
64706c3fb27SDimitry Andric 
64806c3fb27SDimitry Andric   LI.reset(new LoopInfo);
64906c3fb27SDimitry Andric   LI->analyze(*DT);
65006c3fb27SDimitry Andric }
65106c3fb27SDimitry Andric } // namespace llvm
65206c3fb27SDimitry Andric 
6530b57cec5SDimitry Andric ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
654e8d8bef9SDimitry Andric   if (FunctionSamples::ProfileIsProbeBased)
655e8d8bef9SDimitry Andric     return getProbeWeight(Inst);
656e8d8bef9SDimitry Andric 
6570b57cec5SDimitry Andric   const DebugLoc &DLoc = Inst.getDebugLoc();
6580b57cec5SDimitry Andric   if (!DLoc)
6590b57cec5SDimitry Andric     return std::error_code();
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   // Ignore all intrinsics, phinodes and branch instructions.
662fe6060f1SDimitry Andric   // Branch and phinodes instruction usually contains debug info from sources
663fe6060f1SDimitry Andric   // outside of the residing basic block, thus we ignore them during annotation.
6640b57cec5SDimitry Andric   if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
6650b57cec5SDimitry Andric     return std::error_code();
6660b57cec5SDimitry Andric 
667fe6060f1SDimitry Andric   // For non-CS profile, if a direct call/invoke instruction is inlined in
668fe6060f1SDimitry Andric   // profile (findCalleeFunctionSamples returns non-empty result), but not
669fe6060f1SDimitry Andric   // inlined here, it means that the inlined callsite has no sample, thus the
670fe6060f1SDimitry Andric   // call instruction should have 0 count.
671fe6060f1SDimitry Andric   // For CS profile, the callsite count of previously inlined callees is
672fe6060f1SDimitry Andric   // populated with the entry count of the callees.
67381ad6265SDimitry Andric   if (!FunctionSamples::ProfileIsCS)
674e8d8bef9SDimitry Andric     if (const auto *CB = dyn_cast<CallBase>(&Inst))
6755ffd83dbSDimitry Andric       if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
6760b57cec5SDimitry Andric         return 0;
6770b57cec5SDimitry Andric 
678fe6060f1SDimitry Andric   return getInstWeightImpl(Inst);
6790b57cec5SDimitry Andric }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric /// Get the FunctionSamples for a call instruction.
6820b57cec5SDimitry Andric ///
6830b57cec5SDimitry Andric /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
6840b57cec5SDimitry Andric /// instance in which that call instruction is calling to. It contains
6850b57cec5SDimitry Andric /// all samples that resides in the inlined instance. We first find the
6860b57cec5SDimitry Andric /// inlined instance in which the call instruction is from, then we
6870b57cec5SDimitry Andric /// traverse its children to find the callsite with the matching
6880b57cec5SDimitry Andric /// location.
6890b57cec5SDimitry Andric ///
6900b57cec5SDimitry Andric /// \param Inst Call/Invoke instruction to query.
6910b57cec5SDimitry Andric ///
6920b57cec5SDimitry Andric /// \returns The FunctionSamples pointer to the inlined instance.
6930b57cec5SDimitry Andric const FunctionSamples *
6945ffd83dbSDimitry Andric SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
6950b57cec5SDimitry Andric   const DILocation *DIL = Inst.getDebugLoc();
6960b57cec5SDimitry Andric   if (!DIL) {
6970b57cec5SDimitry Andric     return nullptr;
6980b57cec5SDimitry Andric   }
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   StringRef CalleeName;
701e8d8bef9SDimitry Andric   if (Function *Callee = Inst.getCalledFunction())
702fe6060f1SDimitry Andric     CalleeName = Callee->getName();
703e8d8bef9SDimitry Andric 
70481ad6265SDimitry Andric   if (FunctionSamples::ProfileIsCS)
705e8d8bef9SDimitry Andric     return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric   const FunctionSamples *FS = findFunctionSamples(Inst);
7080b57cec5SDimitry Andric   if (FS == nullptr)
7090b57cec5SDimitry Andric     return nullptr;
7100b57cec5SDimitry Andric 
711e8d8bef9SDimitry Andric   return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
712*0fca6ea1SDimitry Andric                                    CalleeName, Reader->getRemapper(),
713*0fca6ea1SDimitry Andric                                    &FuncNameToProfNameMap);
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric /// Returns a vector of FunctionSamples that are the indirect call targets
7170b57cec5SDimitry Andric /// of \p Inst. The vector is sorted by the total number of samples. Stores
7180b57cec5SDimitry Andric /// the total call count of the indirect call in \p Sum.
7190b57cec5SDimitry Andric std::vector<const FunctionSamples *>
7200b57cec5SDimitry Andric SampleProfileLoader::findIndirectCallFunctionSamples(
7210b57cec5SDimitry Andric     const Instruction &Inst, uint64_t &Sum) const {
7220b57cec5SDimitry Andric   const DILocation *DIL = Inst.getDebugLoc();
7230b57cec5SDimitry Andric   std::vector<const FunctionSamples *> R;
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   if (!DIL) {
7260b57cec5SDimitry Andric     return R;
7270b57cec5SDimitry Andric   }
7280b57cec5SDimitry Andric 
729d409305fSDimitry Andric   auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
730d409305fSDimitry Andric     assert(L && R && "Expect non-null FunctionSamples");
731fcaf7f86SDimitry Andric     if (L->getHeadSamplesEstimate() != R->getHeadSamplesEstimate())
732fcaf7f86SDimitry Andric       return L->getHeadSamplesEstimate() > R->getHeadSamplesEstimate();
7335f757f3fSDimitry Andric     return L->getGUID() < R->getGUID();
734d409305fSDimitry Andric   };
735d409305fSDimitry Andric 
73681ad6265SDimitry Andric   if (FunctionSamples::ProfileIsCS) {
737d409305fSDimitry Andric     auto CalleeSamples =
738d409305fSDimitry Andric         ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
739d409305fSDimitry Andric     if (CalleeSamples.empty())
740d409305fSDimitry Andric       return R;
741d409305fSDimitry Andric 
742d409305fSDimitry Andric     // For CSSPGO, we only use target context profile's entry count
743d409305fSDimitry Andric     // as that already includes both inlined callee and non-inlined ones..
744d409305fSDimitry Andric     Sum = 0;
745d409305fSDimitry Andric     for (const auto *const FS : CalleeSamples) {
746fcaf7f86SDimitry Andric       Sum += FS->getHeadSamplesEstimate();
747d409305fSDimitry Andric       R.push_back(FS);
748d409305fSDimitry Andric     }
749d409305fSDimitry Andric     llvm::sort(R, FSCompare);
750d409305fSDimitry Andric     return R;
751d409305fSDimitry Andric   }
752d409305fSDimitry Andric 
7530b57cec5SDimitry Andric   const FunctionSamples *FS = findFunctionSamples(Inst);
7540b57cec5SDimitry Andric   if (FS == nullptr)
7550b57cec5SDimitry Andric     return R;
7560b57cec5SDimitry Andric 
757e8d8bef9SDimitry Andric   auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
7580b57cec5SDimitry Andric   Sum = 0;
759cb14a3feSDimitry Andric   if (auto T = FS->findCallTargetMapAt(CallSite))
760cb14a3feSDimitry Andric     for (const auto &T_C : *T)
7610b57cec5SDimitry Andric       Sum += T_C.second;
762e8d8bef9SDimitry Andric   if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
7630b57cec5SDimitry Andric     if (M->empty())
7640b57cec5SDimitry Andric       return R;
7650b57cec5SDimitry Andric     for (const auto &NameFS : *M) {
766fcaf7f86SDimitry Andric       Sum += NameFS.second.getHeadSamplesEstimate();
7670b57cec5SDimitry Andric       R.push_back(&NameFS.second);
7680b57cec5SDimitry Andric     }
769d409305fSDimitry Andric     llvm::sort(R, FSCompare);
7700b57cec5SDimitry Andric   }
7710b57cec5SDimitry Andric   return R;
7720b57cec5SDimitry Andric }
7730b57cec5SDimitry Andric 
7740b57cec5SDimitry Andric const FunctionSamples *
7750b57cec5SDimitry Andric SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
776e8d8bef9SDimitry Andric   if (FunctionSamples::ProfileIsProbeBased) {
777bdd1243dSDimitry Andric     std::optional<PseudoProbe> Probe = extractProbe(Inst);
778e8d8bef9SDimitry Andric     if (!Probe)
779e8d8bef9SDimitry Andric       return nullptr;
780e8d8bef9SDimitry Andric   }
781e8d8bef9SDimitry Andric 
7820b57cec5SDimitry Andric   const DILocation *DIL = Inst.getDebugLoc();
7830b57cec5SDimitry Andric   if (!DIL)
7840b57cec5SDimitry Andric     return Samples;
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric   auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
787e8d8bef9SDimitry Andric   if (it.second) {
78881ad6265SDimitry Andric     if (FunctionSamples::ProfileIsCS)
789e8d8bef9SDimitry Andric       it.first->second = ContextTracker->getContextSamplesFor(DIL);
790e8d8bef9SDimitry Andric     else
791*0fca6ea1SDimitry Andric       it.first->second = Samples->findFunctionSamples(
792*0fca6ea1SDimitry Andric           DIL, Reader->getRemapper(), &FuncNameToProfNameMap);
793e8d8bef9SDimitry Andric   }
7940b57cec5SDimitry Andric   return it.first->second;
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric 
797fe6060f1SDimitry Andric /// Check whether the indirect call promotion history of \p Inst allows
798fe6060f1SDimitry Andric /// the promotion for \p Candidate.
799fe6060f1SDimitry Andric /// If the profile count for the promotion candidate \p Candidate is
800fe6060f1SDimitry Andric /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
801fe6060f1SDimitry Andric /// for \p Inst. If we already have at least MaxNumPromotions
802fe6060f1SDimitry Andric /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
803fe6060f1SDimitry Andric /// cannot promote for \p Inst anymore.
804fe6060f1SDimitry Andric static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) {
805fe6060f1SDimitry Andric   uint64_t TotalCount = 0;
806*0fca6ea1SDimitry Andric   auto ValueData = getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget,
807*0fca6ea1SDimitry Andric                                             MaxNumPromotions, TotalCount, true);
808fe6060f1SDimitry Andric   // No valid value profile so no promoted targets have been recorded
809fe6060f1SDimitry Andric   // before. Ok to do ICP.
810*0fca6ea1SDimitry Andric   if (ValueData.empty())
811fe6060f1SDimitry Andric     return true;
812fe6060f1SDimitry Andric 
813fe6060f1SDimitry Andric   unsigned NumPromoted = 0;
814*0fca6ea1SDimitry Andric   for (const auto &V : ValueData) {
815*0fca6ea1SDimitry Andric     if (V.Count != NOMORE_ICP_MAGICNUM)
816fe6060f1SDimitry Andric       continue;
817fe6060f1SDimitry Andric 
818fe6060f1SDimitry Andric     // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
819fe6060f1SDimitry Andric     // metadata, it means the candidate has been promoted for this
820fe6060f1SDimitry Andric     // indirect call.
821*0fca6ea1SDimitry Andric     if (V.Value == Function::getGUID(Candidate))
822fe6060f1SDimitry Andric       return false;
823fe6060f1SDimitry Andric     NumPromoted++;
824fe6060f1SDimitry Andric     // If already have MaxNumPromotions promotion, don't do it anymore.
825fe6060f1SDimitry Andric     if (NumPromoted == MaxNumPromotions)
826fe6060f1SDimitry Andric       return false;
827fe6060f1SDimitry Andric   }
828fe6060f1SDimitry Andric   return true;
829fe6060f1SDimitry Andric }
830fe6060f1SDimitry Andric 
831fe6060f1SDimitry Andric /// Update indirect call target profile metadata for \p Inst.
832fe6060f1SDimitry Andric /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
833fe6060f1SDimitry Andric /// If it is 0, it means updateIDTMetaData is used to mark a
834fe6060f1SDimitry Andric /// certain target to be promoted already. If it is not zero,
835fe6060f1SDimitry Andric /// we expect to use it to update the total count in the value profile.
836fe6060f1SDimitry Andric static void
837fe6060f1SDimitry Andric updateIDTMetaData(Instruction &Inst,
838fe6060f1SDimitry Andric                   const SmallVectorImpl<InstrProfValueData> &CallTargets,
839fe6060f1SDimitry Andric                   uint64_t Sum) {
84081ad6265SDimitry Andric   // Bail out early if MaxNumPromotions is zero.
84181ad6265SDimitry Andric   // This prevents allocating an array of zero length below.
84281ad6265SDimitry Andric   //
84381ad6265SDimitry Andric   // Note `updateIDTMetaData` is called in two places so check
84481ad6265SDimitry Andric   // `MaxNumPromotions` inside it.
84581ad6265SDimitry Andric   if (MaxNumPromotions == 0)
84681ad6265SDimitry Andric     return;
847fe6060f1SDimitry Andric   // OldSum is the existing total count in the value profile data.
848fe6060f1SDimitry Andric   uint64_t OldSum = 0;
849*0fca6ea1SDimitry Andric   auto ValueData = getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget,
850*0fca6ea1SDimitry Andric                                             MaxNumPromotions, OldSum, true);
851fe6060f1SDimitry Andric 
852fe6060f1SDimitry Andric   DenseMap<uint64_t, uint64_t> ValueCountMap;
853fe6060f1SDimitry Andric   if (Sum == 0) {
854fe6060f1SDimitry Andric     assert((CallTargets.size() == 1 &&
855fe6060f1SDimitry Andric             CallTargets[0].Count == NOMORE_ICP_MAGICNUM) &&
856fe6060f1SDimitry Andric            "If sum is 0, assume only one element in CallTargets "
857fe6060f1SDimitry Andric            "with count being NOMORE_ICP_MAGICNUM");
858fe6060f1SDimitry Andric     // Initialize ValueCountMap with existing value profile data.
859*0fca6ea1SDimitry Andric     for (const auto &V : ValueData)
860*0fca6ea1SDimitry Andric       ValueCountMap[V.Value] = V.Count;
861fe6060f1SDimitry Andric     auto Pair =
862fe6060f1SDimitry Andric         ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count);
863fe6060f1SDimitry Andric     // If the target already exists in value profile, decrease the total
864fe6060f1SDimitry Andric     // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
865fe6060f1SDimitry Andric     if (!Pair.second) {
866fe6060f1SDimitry Andric       OldSum -= Pair.first->second;
867fe6060f1SDimitry Andric       Pair.first->second = NOMORE_ICP_MAGICNUM;
868fe6060f1SDimitry Andric     }
869fe6060f1SDimitry Andric     Sum = OldSum;
870fe6060f1SDimitry Andric   } else {
871fe6060f1SDimitry Andric     // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
872fe6060f1SDimitry Andric     // counts in the value profile.
873*0fca6ea1SDimitry Andric     for (const auto &V : ValueData) {
874*0fca6ea1SDimitry Andric       if (V.Count == NOMORE_ICP_MAGICNUM)
875*0fca6ea1SDimitry Andric         ValueCountMap[V.Value] = V.Count;
876fe6060f1SDimitry Andric     }
877fe6060f1SDimitry Andric 
878fe6060f1SDimitry Andric     for (const auto &Data : CallTargets) {
879fe6060f1SDimitry Andric       auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
880fe6060f1SDimitry Andric       if (Pair.second)
881fe6060f1SDimitry Andric         continue;
882fe6060f1SDimitry Andric       // The target represented by Data.Value has already been promoted.
883fe6060f1SDimitry Andric       // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
884fe6060f1SDimitry Andric       // Sum by Data.Count.
885fe6060f1SDimitry Andric       assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
886fe6060f1SDimitry Andric       Sum -= Data.Count;
887fe6060f1SDimitry Andric     }
888fe6060f1SDimitry Andric   }
889fe6060f1SDimitry Andric 
890fe6060f1SDimitry Andric   SmallVector<InstrProfValueData, 8> NewCallTargets;
891fe6060f1SDimitry Andric   for (const auto &ValueCount : ValueCountMap) {
892fe6060f1SDimitry Andric     NewCallTargets.emplace_back(
893fe6060f1SDimitry Andric         InstrProfValueData{ValueCount.first, ValueCount.second});
894fe6060f1SDimitry Andric   }
895fe6060f1SDimitry Andric 
896fe6060f1SDimitry Andric   llvm::sort(NewCallTargets,
897fe6060f1SDimitry Andric              [](const InstrProfValueData &L, const InstrProfValueData &R) {
898fe6060f1SDimitry Andric                if (L.Count != R.Count)
899fe6060f1SDimitry Andric                  return L.Count > R.Count;
900fe6060f1SDimitry Andric                return L.Value > R.Value;
901fe6060f1SDimitry Andric              });
902fe6060f1SDimitry Andric 
903fe6060f1SDimitry Andric   uint32_t MaxMDCount =
904fe6060f1SDimitry Andric       std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions));
905fe6060f1SDimitry Andric   annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
906fe6060f1SDimitry Andric                     NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
907fe6060f1SDimitry Andric }
908fe6060f1SDimitry Andric 
909d409305fSDimitry Andric /// Attempt to promote indirect call and also inline the promoted call.
910d409305fSDimitry Andric ///
911d409305fSDimitry Andric /// \param F  Caller function.
912d409305fSDimitry Andric /// \param Candidate  ICP and inline candidate.
913fe6060f1SDimitry Andric /// \param SumOrigin  Original sum of target counts for indirect call before
914fe6060f1SDimitry Andric ///                   promoting given candidate.
915fe6060f1SDimitry Andric /// \param Sum        Prorated sum of remaining target counts for indirect call
916fe6060f1SDimitry Andric ///                   after promoting given candidate.
917d409305fSDimitry Andric /// \param InlinedCallSite  Output vector for new call sites exposed after
918d409305fSDimitry Andric /// inlining.
919d409305fSDimitry Andric bool SampleProfileLoader::tryPromoteAndInlineCandidate(
920d409305fSDimitry Andric     Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
921d409305fSDimitry Andric     SmallVector<CallBase *, 8> *InlinedCallSite) {
92281ad6265SDimitry Andric   // Bail out early if sample-loader inliner is disabled.
92381ad6265SDimitry Andric   if (DisableSampleLoaderInlining)
92481ad6265SDimitry Andric     return false;
92581ad6265SDimitry Andric 
92681ad6265SDimitry Andric   // Bail out early if MaxNumPromotions is zero.
92781ad6265SDimitry Andric   // This prevents allocating an array of zero length in callees below.
92881ad6265SDimitry Andric   if (MaxNumPromotions == 0)
92981ad6265SDimitry Andric     return false;
9305f757f3fSDimitry Andric   auto CalleeFunctionName = Candidate.CalleeSamples->getFunction();
931fe6060f1SDimitry Andric   auto R = SymbolMap.find(CalleeFunctionName);
9325f757f3fSDimitry Andric   if (R == SymbolMap.end() || !R->second)
933fe6060f1SDimitry Andric     return false;
934fe6060f1SDimitry Andric 
935fe6060f1SDimitry Andric   auto &CI = *Candidate.CallInstr;
9365f757f3fSDimitry Andric   if (!doesHistoryAllowICP(CI, R->second->getName()))
937fe6060f1SDimitry Andric     return false;
938fe6060f1SDimitry Andric 
939d409305fSDimitry Andric   const char *Reason = "Callee function not available";
940d409305fSDimitry Andric   // R->getValue() != &F is to prevent promoting a recursive call.
941d409305fSDimitry Andric   // If it is a recursive call, we do not inline it as it could bloat
942d409305fSDimitry Andric   // the code exponentially. There is way to better handle this, e.g.
943d409305fSDimitry Andric   // clone the caller first, and inline the cloned caller if it is
944d409305fSDimitry Andric   // recursive. As llvm does not inline recursive calls, we will
945d409305fSDimitry Andric   // simply ignore it instead of handling it explicitly.
9465f757f3fSDimitry Andric   if (!R->second->isDeclaration() && R->second->getSubprogram() &&
9475f757f3fSDimitry Andric       R->second->hasFnAttribute("use-sample-profile") &&
9485f757f3fSDimitry Andric       R->second != &F && isLegalToPromote(CI, R->second, &Reason)) {
949fe6060f1SDimitry Andric     // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
950fe6060f1SDimitry Andric     // in the value profile metadata so the target won't be promoted again.
951fe6060f1SDimitry Andric     SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
9525f757f3fSDimitry Andric         Function::getGUID(R->second->getName()), NOMORE_ICP_MAGICNUM}};
953fe6060f1SDimitry Andric     updateIDTMetaData(CI, SortedCallTargets, 0);
954fe6060f1SDimitry Andric 
955fe6060f1SDimitry Andric     auto *DI = &pgo::promoteIndirectCall(
9565f757f3fSDimitry Andric         CI, R->second, Candidate.CallsiteCount, Sum, false, ORE);
957d409305fSDimitry Andric     if (DI) {
958d409305fSDimitry Andric       Sum -= Candidate.CallsiteCount;
959fe6060f1SDimitry Andric       // Do not prorate the indirect callsite distribution since the original
960fe6060f1SDimitry Andric       // distribution will be used to scale down non-promoted profile target
961fe6060f1SDimitry Andric       // counts later. By doing this we lose track of the real callsite count
962fe6060f1SDimitry Andric       // for the leftover indirect callsite as a trade off for accurate call
963fe6060f1SDimitry Andric       // target counts.
964fe6060f1SDimitry Andric       // TODO: Ideally we would have two separate factors, one for call site
965fe6060f1SDimitry Andric       // counts and one is used to prorate call target counts.
966d409305fSDimitry Andric       // Do not update the promoted direct callsite distribution at this
967fe6060f1SDimitry Andric       // point since the original distribution combined with the callee profile
968fe6060f1SDimitry Andric       // will be used to prorate callsites from the callee if inlined. Once not
969fe6060f1SDimitry Andric       // inlined, the direct callsite distribution should be prorated so that
970fe6060f1SDimitry Andric       // the it will reflect the real callsite counts.
971d409305fSDimitry Andric       Candidate.CallInstr = DI;
972d409305fSDimitry Andric       if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
973d409305fSDimitry Andric         bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
974d409305fSDimitry Andric         if (!Inlined) {
975d409305fSDimitry Andric           // Prorate the direct callsite distribution so that it reflects real
976d409305fSDimitry Andric           // callsite counts.
977fe6060f1SDimitry Andric           setProbeDistributionFactor(
978fe6060f1SDimitry Andric               *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
979e8d8bef9SDimitry Andric         }
980d409305fSDimitry Andric         return Inlined;
981e8d8bef9SDimitry Andric       }
9820b57cec5SDimitry Andric     }
983d409305fSDimitry Andric   } else {
984d409305fSDimitry Andric     LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
9855f757f3fSDimitry Andric                       << FunctionSamples::getCanonicalFnName(
9865f757f3fSDimitry Andric                              Candidate.CallInstr->getName())<< " because "
987d409305fSDimitry Andric                       << Reason << "\n");
9880b57cec5SDimitry Andric   }
9890b57cec5SDimitry Andric   return false;
9900b57cec5SDimitry Andric }
9910b57cec5SDimitry Andric 
9925ffd83dbSDimitry Andric bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
993480093f4SDimitry Andric   if (!ProfileSizeInline)
994480093f4SDimitry Andric     return false;
995480093f4SDimitry Andric 
9965ffd83dbSDimitry Andric   Function *Callee = CallInst.getCalledFunction();
997480093f4SDimitry Andric   if (Callee == nullptr)
998480093f4SDimitry Andric     return false;
999480093f4SDimitry Andric 
10005ffd83dbSDimitry Andric   InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
10015ffd83dbSDimitry Andric                                   GetAC, GetTLI);
1002480093f4SDimitry Andric 
1003e8d8bef9SDimitry Andric   if (Cost.isNever())
1004e8d8bef9SDimitry Andric     return false;
1005e8d8bef9SDimitry Andric 
1006e8d8bef9SDimitry Andric   if (Cost.isAlways())
1007e8d8bef9SDimitry Andric     return true;
1008e8d8bef9SDimitry Andric 
1009480093f4SDimitry Andric   return Cost.getCost() <= SampleColdCallSiteThreshold;
1010480093f4SDimitry Andric }
1011480093f4SDimitry Andric 
1012480093f4SDimitry Andric void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
10135ffd83dbSDimitry Andric     const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
1014480093f4SDimitry Andric     bool Hot) {
1015bdd1243dSDimitry Andric   for (auto *I : Candidates) {
10165ffd83dbSDimitry Andric     Function *CalledFunction = I->getCalledFunction();
1017480093f4SDimitry Andric     if (CalledFunction) {
101881ad6265SDimitry Andric       ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
101981ad6265SDimitry Andric                                            "InlineAttempt", I->getDebugLoc(),
102081ad6265SDimitry Andric                                            I->getParent())
1021480093f4SDimitry Andric                 << "previous inlining reattempted for "
1022480093f4SDimitry Andric                 << (Hot ? "hotness: '" : "size: '")
1023480093f4SDimitry Andric                 << ore::NV("Callee", CalledFunction) << "' into '"
1024480093f4SDimitry Andric                 << ore::NV("Caller", &F) << "'");
1025480093f4SDimitry Andric     }
1026480093f4SDimitry Andric   }
1027480093f4SDimitry Andric }
1028480093f4SDimitry Andric 
1029fe6060f1SDimitry Andric void SampleProfileLoader::findExternalInlineCandidate(
1030349cc55cSDimitry Andric     CallBase *CB, const FunctionSamples *Samples,
10315f757f3fSDimitry Andric     DenseSet<GlobalValue::GUID> &InlinedGUIDs, uint64_t Threshold) {
1032349cc55cSDimitry Andric 
103306c3fb27SDimitry Andric   // If ExternalInlineAdvisor(ReplayInlineAdvisor) wants to inline an external
103406c3fb27SDimitry Andric   // function make sure it's imported
1035349cc55cSDimitry Andric   if (CB && getExternalInlineAdvisorShouldInline(*CB)) {
1036349cc55cSDimitry Andric     // Samples may not exist for replayed function, if so
1037349cc55cSDimitry Andric     // just add the direct GUID and move on
1038349cc55cSDimitry Andric     if (!Samples) {
1039349cc55cSDimitry Andric       InlinedGUIDs.insert(
10405f757f3fSDimitry Andric           Function::getGUID(CB->getCalledFunction()->getName()));
1041349cc55cSDimitry Andric       return;
1042349cc55cSDimitry Andric     }
1043349cc55cSDimitry Andric     // Otherwise, drop the threshold to import everything that we can
1044349cc55cSDimitry Andric     Threshold = 0;
1045349cc55cSDimitry Andric   }
1046349cc55cSDimitry Andric 
104706c3fb27SDimitry Andric   // In some rare cases, call instruction could be changed after being pushed
104806c3fb27SDimitry Andric   // into inline candidate queue, this is because earlier inlining may expose
104906c3fb27SDimitry Andric   // constant propagation which can change indirect call to direct call. When
105006c3fb27SDimitry Andric   // this happens, we may fail to find matching function samples for the
105106c3fb27SDimitry Andric   // candidate later, even if a match was found when the candidate was enqueued.
105206c3fb27SDimitry Andric   if (!Samples)
105306c3fb27SDimitry Andric     return;
1054fe6060f1SDimitry Andric 
1055fe6060f1SDimitry Andric   // For AutoFDO profile, retrieve candidate profiles by walking over
1056fe6060f1SDimitry Andric   // the nested inlinee profiles.
105781ad6265SDimitry Andric   if (!FunctionSamples::ProfileIsCS) {
1058*0fca6ea1SDimitry Andric     // Set threshold to zero to honor pre-inliner decision.
1059*0fca6ea1SDimitry Andric     if (UsePreInlinerDecision)
1060*0fca6ea1SDimitry Andric       Threshold = 0;
1061fe6060f1SDimitry Andric     Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold);
1062fe6060f1SDimitry Andric     return;
1063fe6060f1SDimitry Andric   }
1064fe6060f1SDimitry Andric 
106581ad6265SDimitry Andric   ContextTrieNode *Caller = ContextTracker->getContextNodeForProfile(Samples);
1066fe6060f1SDimitry Andric   std::queue<ContextTrieNode *> CalleeList;
1067fe6060f1SDimitry Andric   CalleeList.push(Caller);
1068fe6060f1SDimitry Andric   while (!CalleeList.empty()) {
1069fe6060f1SDimitry Andric     ContextTrieNode *Node = CalleeList.front();
1070fe6060f1SDimitry Andric     CalleeList.pop();
1071fe6060f1SDimitry Andric     FunctionSamples *CalleeSample = Node->getFunctionSamples();
1072fe6060f1SDimitry Andric     // For CSSPGO profile, retrieve candidate profile by walking over the
1073fe6060f1SDimitry Andric     // trie built for context profile. Note that also take call targets
1074fe6060f1SDimitry Andric     // even if callee doesn't have a corresponding context profile.
1075349cc55cSDimitry Andric     if (!CalleeSample)
1076349cc55cSDimitry Andric       continue;
1077349cc55cSDimitry Andric 
1078349cc55cSDimitry Andric     // If pre-inliner decision is used, honor that for importing as well.
1079349cc55cSDimitry Andric     bool PreInline =
1080349cc55cSDimitry Andric         UsePreInlinerDecision &&
1081349cc55cSDimitry Andric         CalleeSample->getContext().hasAttribute(ContextShouldBeInlined);
1082fcaf7f86SDimitry Andric     if (!PreInline && CalleeSample->getHeadSamplesEstimate() < Threshold)
1083fe6060f1SDimitry Andric       continue;
1084fe6060f1SDimitry Andric 
10855f757f3fSDimitry Andric     Function *Func = SymbolMap.lookup(CalleeSample->getFunction());
1086fe6060f1SDimitry Andric     // Add to the import list only when it's defined out of module.
1087fe6060f1SDimitry Andric     if (!Func || Func->isDeclaration())
10885f757f3fSDimitry Andric       InlinedGUIDs.insert(CalleeSample->getGUID());
1089fe6060f1SDimitry Andric 
1090fe6060f1SDimitry Andric     // Import hot CallTargets, which may not be available in IR because full
1091fe6060f1SDimitry Andric     // profile annotation cannot be done until backend compilation in ThinLTO.
1092fe6060f1SDimitry Andric     for (const auto &BS : CalleeSample->getBodySamples())
1093fe6060f1SDimitry Andric       for (const auto &TS : BS.second.getCallTargets())
10945f757f3fSDimitry Andric         if (TS.second > Threshold) {
10955f757f3fSDimitry Andric           const Function *Callee = SymbolMap.lookup(TS.first);
1096fe6060f1SDimitry Andric           if (!Callee || Callee->isDeclaration())
10975f757f3fSDimitry Andric             InlinedGUIDs.insert(TS.first.getHashCode());
1098fe6060f1SDimitry Andric         }
1099fe6060f1SDimitry Andric 
1100fe6060f1SDimitry Andric     // Import hot child context profile associted with callees. Note that this
1101fe6060f1SDimitry Andric     // may have some overlap with the call target loop above, but doing this
1102fe6060f1SDimitry Andric     // based child context profile again effectively allow us to use the max of
1103fe6060f1SDimitry Andric     // entry count and call target count to determine importing.
1104fe6060f1SDimitry Andric     for (auto &Child : Node->getAllChildContext()) {
1105fe6060f1SDimitry Andric       ContextTrieNode *CalleeNode = &Child.second;
1106fe6060f1SDimitry Andric       CalleeList.push(CalleeNode);
1107fe6060f1SDimitry Andric     }
1108fe6060f1SDimitry Andric   }
1109fe6060f1SDimitry Andric }
1110fe6060f1SDimitry Andric 
11110b57cec5SDimitry Andric /// Iteratively inline hot callsites of a function.
11120b57cec5SDimitry Andric ///
111381ad6265SDimitry Andric /// Iteratively traverse all callsites of the function \p F, so as to
111481ad6265SDimitry Andric /// find out callsites with corresponding inline instances.
111581ad6265SDimitry Andric ///
111681ad6265SDimitry Andric /// For such callsites,
111781ad6265SDimitry Andric /// - If it is hot enough, inline the callsites and adds callsites of the callee
111881ad6265SDimitry Andric ///   into the caller. If the call is an indirect call, first promote
11190b57cec5SDimitry Andric ///   it to direct call. Each indirect call is limited with a single target.
11200b57cec5SDimitry Andric ///
112181ad6265SDimitry Andric /// - If a callsite is not inlined, merge the its profile to the outline
112281ad6265SDimitry Andric ///   version (if --sample-profile-merge-inlinee is true), or scale the
112381ad6265SDimitry Andric ///   counters of standalone function based on the profile of inlined
112481ad6265SDimitry Andric ///   instances (if --sample-profile-merge-inlinee is false).
112581ad6265SDimitry Andric ///
112681ad6265SDimitry Andric ///   Later passes may consume the updated profiles.
112781ad6265SDimitry Andric ///
11280b57cec5SDimitry Andric /// \param F function to perform iterative inlining.
11290b57cec5SDimitry Andric /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
11300b57cec5SDimitry Andric ///     inlined in the profiled binary.
11310b57cec5SDimitry Andric ///
11320b57cec5SDimitry Andric /// \returns True if there is any inline happened.
11330b57cec5SDimitry Andric bool SampleProfileLoader::inlineHotFunctions(
11340b57cec5SDimitry Andric     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
11358bcb0991SDimitry Andric   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
11368bcb0991SDimitry Andric   // Profile symbol list is ignored when profile-sample-accurate is on.
11378bcb0991SDimitry Andric   assert((!ProfAccForSymsInList ||
11388bcb0991SDimitry Andric           (!ProfileSampleAccurate &&
11398bcb0991SDimitry Andric            !F.hasFnAttribute("profile-sample-accurate"))) &&
11408bcb0991SDimitry Andric          "ProfAccForSymsInList should be false when profile-sample-accurate "
11418bcb0991SDimitry Andric          "is enabled");
11428bcb0991SDimitry Andric 
1143bdd1243dSDimitry Andric   MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
11440b57cec5SDimitry Andric   bool Changed = false;
1145d409305fSDimitry Andric   bool LocalChanged = true;
1146d409305fSDimitry Andric   while (LocalChanged) {
1147d409305fSDimitry Andric     LocalChanged = false;
11485ffd83dbSDimitry Andric     SmallVector<CallBase *, 10> CIS;
11490b57cec5SDimitry Andric     for (auto &BB : F) {
11500b57cec5SDimitry Andric       bool Hot = false;
11515ffd83dbSDimitry Andric       SmallVector<CallBase *, 10> AllCandidates;
11525ffd83dbSDimitry Andric       SmallVector<CallBase *, 10> ColdCandidates;
1153bdd1243dSDimitry Andric       for (auto &I : BB) {
11540b57cec5SDimitry Andric         const FunctionSamples *FS = nullptr;
11555ffd83dbSDimitry Andric         if (auto *CB = dyn_cast<CallBase>(&I)) {
1156349cc55cSDimitry Andric           if (!isa<IntrinsicInst>(I)) {
1157349cc55cSDimitry Andric             if ((FS = findCalleeFunctionSamples(*CB))) {
1158e8d8bef9SDimitry Andric               assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
1159e8d8bef9SDimitry Andric                      "GUIDToFuncNameMap has to be populated");
11605ffd83dbSDimitry Andric               AllCandidates.push_back(CB);
1161fcaf7f86SDimitry Andric               if (FS->getHeadSamplesEstimate() > 0 ||
1162fcaf7f86SDimitry Andric                   FunctionSamples::ProfileIsCS)
1163bdd1243dSDimitry Andric                 LocalNotInlinedCallSites.insert({CB, FS});
1164fe6060f1SDimitry Andric               if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
11650b57cec5SDimitry Andric                 Hot = true;
11665ffd83dbSDimitry Andric               else if (shouldInlineColdCallee(*CB))
11675ffd83dbSDimitry Andric                 ColdCandidates.push_back(CB);
1168349cc55cSDimitry Andric             } else if (getExternalInlineAdvisorShouldInline(*CB)) {
1169349cc55cSDimitry Andric               AllCandidates.push_back(CB);
1170349cc55cSDimitry Andric             }
11715ffd83dbSDimitry Andric           }
11720b57cec5SDimitry Andric         }
11730b57cec5SDimitry Andric       }
1174e8d8bef9SDimitry Andric       if (Hot || ExternalInlineAdvisor) {
1175480093f4SDimitry Andric         CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
1176480093f4SDimitry Andric         emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
11775ffd83dbSDimitry Andric       } else {
1178480093f4SDimitry Andric         CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
1179480093f4SDimitry Andric         emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
11800b57cec5SDimitry Andric       }
11810b57cec5SDimitry Andric     }
11825ffd83dbSDimitry Andric     for (CallBase *I : CIS) {
11835ffd83dbSDimitry Andric       Function *CalledFunction = I->getCalledFunction();
11840eae32dcSDimitry Andric       InlineCandidate Candidate = {I, LocalNotInlinedCallSites.lookup(I),
11850eae32dcSDimitry Andric                                    0 /* dummy count */,
11860eae32dcSDimitry Andric                                    1.0 /* dummy distribution factor */};
11870b57cec5SDimitry Andric       // Do not inline recursive calls.
11880b57cec5SDimitry Andric       if (CalledFunction == &F)
11890b57cec5SDimitry Andric         continue;
11905ffd83dbSDimitry Andric       if (I->isIndirectCall()) {
11910b57cec5SDimitry Andric         uint64_t Sum;
11920b57cec5SDimitry Andric         for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1193d409305fSDimitry Andric           uint64_t SumOrigin = Sum;
1194e8d8bef9SDimitry Andric           if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
11955f757f3fSDimitry Andric             findExternalInlineCandidate(I, FS, InlinedGUIDs,
11960b57cec5SDimitry Andric                                         PSI->getOrCompHotCountThreshold());
11970b57cec5SDimitry Andric             continue;
11980b57cec5SDimitry Andric           }
1199fe6060f1SDimitry Andric           if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1200e8d8bef9SDimitry Andric             continue;
1201e8d8bef9SDimitry Andric 
1202fcaf7f86SDimitry Andric           Candidate = {I, FS, FS->getHeadSamplesEstimate(), 1.0};
1203fe6060f1SDimitry Andric           if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
1204d409305fSDimitry Andric             LocalNotInlinedCallSites.erase(I);
12050b57cec5SDimitry Andric             LocalChanged = true;
12060b57cec5SDimitry Andric           }
12070b57cec5SDimitry Andric         }
12080b57cec5SDimitry Andric       } else if (CalledFunction && CalledFunction->getSubprogram() &&
12090b57cec5SDimitry Andric                  !CalledFunction->isDeclaration()) {
1210d409305fSDimitry Andric         if (tryInlineCandidate(Candidate)) {
1211d409305fSDimitry Andric           LocalNotInlinedCallSites.erase(I);
12120b57cec5SDimitry Andric           LocalChanged = true;
12130b57cec5SDimitry Andric         }
1214e8d8bef9SDimitry Andric       } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1215349cc55cSDimitry Andric         findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
12165f757f3fSDimitry Andric                                     InlinedGUIDs,
1217fe6060f1SDimitry Andric                                     PSI->getOrCompHotCountThreshold());
12180b57cec5SDimitry Andric       }
12190b57cec5SDimitry Andric     }
1220d409305fSDimitry Andric     Changed |= LocalChanged;
12210b57cec5SDimitry Andric   }
12220b57cec5SDimitry Andric 
1223d409305fSDimitry Andric   // For CS profile, profile for not inlined context will be merged when
12240eae32dcSDimitry Andric   // base profile is being retrieved.
122581ad6265SDimitry Andric   if (!FunctionSamples::ProfileIsCS)
12260eae32dcSDimitry Andric     promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
12270b57cec5SDimitry Andric   return Changed;
12280b57cec5SDimitry Andric }
12290b57cec5SDimitry Andric 
1230d409305fSDimitry Andric bool SampleProfileLoader::tryInlineCandidate(
1231d409305fSDimitry Andric     InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
123281ad6265SDimitry Andric   // Do not attempt to inline a candidate if
123381ad6265SDimitry Andric   // --disable-sample-loader-inlining is true.
123481ad6265SDimitry Andric   if (DisableSampleLoaderInlining)
123581ad6265SDimitry Andric     return false;
1236d409305fSDimitry Andric 
1237d409305fSDimitry Andric   CallBase &CB = *Candidate.CallInstr;
1238d409305fSDimitry Andric   Function *CalledFunction = CB.getCalledFunction();
1239d409305fSDimitry Andric   assert(CalledFunction && "Expect a callee with definition");
1240d409305fSDimitry Andric   DebugLoc DLoc = CB.getDebugLoc();
1241d409305fSDimitry Andric   BasicBlock *BB = CB.getParent();
1242d409305fSDimitry Andric 
1243d409305fSDimitry Andric   InlineCost Cost = shouldInlineCandidate(Candidate);
1244d409305fSDimitry Andric   if (Cost.isNever()) {
124581ad6265SDimitry Andric     ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
124681ad6265SDimitry Andric                                          "InlineFail", DLoc, BB)
1247d409305fSDimitry Andric               << "incompatible inlining");
1248d409305fSDimitry Andric     return false;
1249d409305fSDimitry Andric   }
1250d409305fSDimitry Andric 
1251d409305fSDimitry Andric   if (!Cost)
1252d409305fSDimitry Andric     return false;
1253d409305fSDimitry Andric 
125406c3fb27SDimitry Andric   InlineFunctionInfo IFI(GetAC);
1255fe6060f1SDimitry Andric   IFI.UpdateProfile = false;
1256bdd1243dSDimitry Andric   InlineResult IR = InlineFunction(CB, IFI,
1257bdd1243dSDimitry Andric                                    /*MergeAttributes=*/true);
1258bdd1243dSDimitry Andric   if (!IR.isSuccess())
125981ad6265SDimitry Andric     return false;
126081ad6265SDimitry Andric 
1261d409305fSDimitry Andric   // The call to InlineFunction erases I, so we can't pass it here.
126281ad6265SDimitry Andric   emitInlinedIntoBasedOnCost(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(),
126381ad6265SDimitry Andric                              Cost, true, getAnnotatedRemarkPassName());
1264d409305fSDimitry Andric 
1265d409305fSDimitry Andric   // Now populate the list of newly exposed call sites.
1266d409305fSDimitry Andric   if (InlinedCallSites) {
1267d409305fSDimitry Andric     InlinedCallSites->clear();
1268d409305fSDimitry Andric     for (auto &I : IFI.InlinedCallSites)
1269d409305fSDimitry Andric       InlinedCallSites->push_back(I);
1270d409305fSDimitry Andric   }
1271d409305fSDimitry Andric 
127281ad6265SDimitry Andric   if (FunctionSamples::ProfileIsCS)
1273d409305fSDimitry Andric     ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1274d409305fSDimitry Andric   ++NumCSInlined;
1275d409305fSDimitry Andric 
1276d409305fSDimitry Andric   // Prorate inlined probes for a duplicated inlining callsite which probably
1277d409305fSDimitry Andric   // has a distribution less than 100%. Samples for an inlinee should be
1278d409305fSDimitry Andric   // distributed among the copies of the original callsite based on each
1279d409305fSDimitry Andric   // callsite's distribution factor for counts accuracy. Note that an inlined
1280d409305fSDimitry Andric   // probe may come with its own distribution factor if it has been duplicated
1281d409305fSDimitry Andric   // in the inlinee body. The two factor are multiplied to reflect the
1282d409305fSDimitry Andric   // aggregation of duplication.
1283d409305fSDimitry Andric   if (Candidate.CallsiteDistribution < 1) {
1284d409305fSDimitry Andric     for (auto &I : IFI.InlinedCallSites) {
1285bdd1243dSDimitry Andric       if (std::optional<PseudoProbe> Probe = extractProbe(*I))
1286d409305fSDimitry Andric         setProbeDistributionFactor(*I, Probe->Factor *
1287d409305fSDimitry Andric                                    Candidate.CallsiteDistribution);
1288d409305fSDimitry Andric     }
1289d409305fSDimitry Andric     NumDuplicatedInlinesite++;
1290d409305fSDimitry Andric   }
1291d409305fSDimitry Andric 
1292d409305fSDimitry Andric   return true;
1293d409305fSDimitry Andric }
1294d409305fSDimitry Andric 
1295d409305fSDimitry Andric bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1296d409305fSDimitry Andric                                              CallBase *CB) {
1297d409305fSDimitry Andric   assert(CB && "Expect non-null call instruction");
1298d409305fSDimitry Andric 
1299d409305fSDimitry Andric   if (isa<IntrinsicInst>(CB))
1300d409305fSDimitry Andric     return false;
1301d409305fSDimitry Andric 
1302d409305fSDimitry Andric   // Find the callee's profile. For indirect call, find hottest target profile.
1303d409305fSDimitry Andric   const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1304349cc55cSDimitry Andric   // If ExternalInlineAdvisor wants to inline this site, do so even
1305349cc55cSDimitry Andric   // if Samples are not present.
1306349cc55cSDimitry Andric   if (!CalleeSamples && !getExternalInlineAdvisorShouldInline(*CB))
1307d409305fSDimitry Andric     return false;
1308d409305fSDimitry Andric 
1309d409305fSDimitry Andric   float Factor = 1.0;
1310bdd1243dSDimitry Andric   if (std::optional<PseudoProbe> Probe = extractProbe(*CB))
1311d409305fSDimitry Andric     Factor = Probe->Factor;
1312d409305fSDimitry Andric 
131381ad6265SDimitry Andric   uint64_t CallsiteCount =
1314fcaf7f86SDimitry Andric       CalleeSamples ? CalleeSamples->getHeadSamplesEstimate() * Factor : 0;
1315d409305fSDimitry Andric   *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1316d409305fSDimitry Andric   return true;
1317d409305fSDimitry Andric }
1318d409305fSDimitry Andric 
1319bdd1243dSDimitry Andric std::optional<InlineCost>
1320349cc55cSDimitry Andric SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
1321d409305fSDimitry Andric   std::unique_ptr<InlineAdvice> Advice = nullptr;
1322d409305fSDimitry Andric   if (ExternalInlineAdvisor) {
1323349cc55cSDimitry Andric     Advice = ExternalInlineAdvisor->getAdvice(CB);
1324349cc55cSDimitry Andric     if (Advice) {
1325d409305fSDimitry Andric       if (!Advice->isInliningRecommended()) {
1326d409305fSDimitry Andric         Advice->recordUnattemptedInlining();
1327d409305fSDimitry Andric         return InlineCost::getNever("not previously inlined");
1328d409305fSDimitry Andric       }
1329d409305fSDimitry Andric       Advice->recordInlining();
1330d409305fSDimitry Andric       return InlineCost::getAlways("previously inlined");
1331d409305fSDimitry Andric     }
1332349cc55cSDimitry Andric   }
1333d409305fSDimitry Andric 
1334349cc55cSDimitry Andric   return {};
1335349cc55cSDimitry Andric }
1336349cc55cSDimitry Andric 
1337349cc55cSDimitry Andric bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
1338bdd1243dSDimitry Andric   std::optional<InlineCost> Cost = getExternalInlineAdvisorCost(CB);
1339bdd1243dSDimitry Andric   return Cost ? !!*Cost : false;
1340349cc55cSDimitry Andric }
1341349cc55cSDimitry Andric 
1342349cc55cSDimitry Andric InlineCost
1343349cc55cSDimitry Andric SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1344bdd1243dSDimitry Andric   if (std::optional<InlineCost> ReplayCost =
1345349cc55cSDimitry Andric           getExternalInlineAdvisorCost(*Candidate.CallInstr))
1346bdd1243dSDimitry Andric     return *ReplayCost;
1347d409305fSDimitry Andric   // Adjust threshold based on call site hotness, only do this for callsite
1348d409305fSDimitry Andric   // prioritized inliner because otherwise cost-benefit check is done earlier.
1349d409305fSDimitry Andric   int SampleThreshold = SampleColdCallSiteThreshold;
1350d409305fSDimitry Andric   if (CallsitePrioritizedInline) {
1351d409305fSDimitry Andric     if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1352d409305fSDimitry Andric       SampleThreshold = SampleHotCallSiteThreshold;
1353d409305fSDimitry Andric     else if (!ProfileSizeInline)
1354d409305fSDimitry Andric       return InlineCost::getNever("cold callsite");
1355d409305fSDimitry Andric   }
1356d409305fSDimitry Andric 
1357d409305fSDimitry Andric   Function *Callee = Candidate.CallInstr->getCalledFunction();
1358d409305fSDimitry Andric   assert(Callee && "Expect a definition for inline candidate of direct call");
1359d409305fSDimitry Andric 
1360d409305fSDimitry Andric   InlineParams Params = getInlineParams();
1361349cc55cSDimitry Andric   // We will ignore the threshold from inline cost, so always get full cost.
1362d409305fSDimitry Andric   Params.ComputeFullInlineCost = true;
1363349cc55cSDimitry Andric   Params.AllowRecursiveCall = AllowRecursiveInline;
1364d409305fSDimitry Andric   // Checks if there is anything in the reachable portion of the callee at
1365d409305fSDimitry Andric   // this callsite that makes this inlining potentially illegal. Need to
1366d409305fSDimitry Andric   // set ComputeFullInlineCost, otherwise getInlineCost may return early
1367d409305fSDimitry Andric   // when cost exceeds threshold without checking all IRs in the callee.
1368d409305fSDimitry Andric   // The acutal cost does not matter because we only checks isNever() to
1369d409305fSDimitry Andric   // see if it is legal to inline the callsite.
1370d409305fSDimitry Andric   InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
1371d409305fSDimitry Andric                                   GetTTI(*Callee), GetAC, GetTLI);
1372d409305fSDimitry Andric 
1373d409305fSDimitry Andric   // Honor always inline and never inline from call analyzer
1374d409305fSDimitry Andric   if (Cost.isNever() || Cost.isAlways())
1375d409305fSDimitry Andric     return Cost;
1376d409305fSDimitry Andric 
1377349cc55cSDimitry Andric   // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
1378349cc55cSDimitry Andric   // decisions based on hotness as well as accurate function byte sizes for
1379349cc55cSDimitry Andric   // given context using function/inlinee sizes from previous build. It
1380349cc55cSDimitry Andric   // stores the decision in profile, and also adjust/merge context profile
1381349cc55cSDimitry Andric   // aiming at better context-sensitive post-inline profile quality, assuming
1382349cc55cSDimitry Andric   // all inline decision estimates are going to be honored by compiler. Here
1383349cc55cSDimitry Andric   // we replay that inline decision under `sample-profile-use-preinliner`.
1384349cc55cSDimitry Andric   // Note that we don't need to handle negative decision from preinliner as
1385349cc55cSDimitry Andric   // context profile for not inlined calls are merged by preinliner already.
1386349cc55cSDimitry Andric   if (UsePreInlinerDecision && Candidate.CalleeSamples) {
1387349cc55cSDimitry Andric     // Once two node are merged due to promotion, we're losing some context
1388349cc55cSDimitry Andric     // so the original context-sensitive preinliner decision should be ignored
1389349cc55cSDimitry Andric     // for SyntheticContext.
1390349cc55cSDimitry Andric     SampleContext &Context = Candidate.CalleeSamples->getContext();
1391349cc55cSDimitry Andric     if (!Context.hasState(SyntheticContext) &&
1392349cc55cSDimitry Andric         Context.hasAttribute(ContextShouldBeInlined))
1393349cc55cSDimitry Andric       return InlineCost::getAlways("preinliner");
1394349cc55cSDimitry Andric   }
1395349cc55cSDimitry Andric 
1396*0fca6ea1SDimitry Andric   // For old FDO inliner, we inline the call site if it is below hot threshold,
1397*0fca6ea1SDimitry Andric   // even if the function is hot based on sample profile data. This is to
1398*0fca6ea1SDimitry Andric   // prevent huge functions from being inlined.
1399d409305fSDimitry Andric   if (!CallsitePrioritizedInline) {
1400*0fca6ea1SDimitry Andric     return InlineCost::get(Cost.getCost(), SampleHotCallSiteThreshold);
1401d409305fSDimitry Andric   }
1402d409305fSDimitry Andric 
1403d409305fSDimitry Andric   // Otherwise only use the cost from call analyzer, but overwite threshold with
1404d409305fSDimitry Andric   // Sample PGO threshold.
1405d409305fSDimitry Andric   return InlineCost::get(Cost.getCost(), SampleThreshold);
1406d409305fSDimitry Andric }
1407d409305fSDimitry Andric 
1408d409305fSDimitry Andric bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1409d409305fSDimitry Andric     Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1410d409305fSDimitry Andric   // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1411d409305fSDimitry Andric   // Profile symbol list is ignored when profile-sample-accurate is on.
1412d409305fSDimitry Andric   assert((!ProfAccForSymsInList ||
1413d409305fSDimitry Andric           (!ProfileSampleAccurate &&
1414d409305fSDimitry Andric            !F.hasFnAttribute("profile-sample-accurate"))) &&
1415d409305fSDimitry Andric          "ProfAccForSymsInList should be false when profile-sample-accurate "
1416d409305fSDimitry Andric          "is enabled");
1417d409305fSDimitry Andric 
1418d409305fSDimitry Andric   // Populating worklist with initial call sites from root inliner, along
1419d409305fSDimitry Andric   // with call site weights.
1420d409305fSDimitry Andric   CandidateQueue CQueue;
1421d409305fSDimitry Andric   InlineCandidate NewCandidate;
1422d409305fSDimitry Andric   for (auto &BB : F) {
1423bdd1243dSDimitry Andric     for (auto &I : BB) {
1424d409305fSDimitry Andric       auto *CB = dyn_cast<CallBase>(&I);
1425d409305fSDimitry Andric       if (!CB)
1426d409305fSDimitry Andric         continue;
1427d409305fSDimitry Andric       if (getInlineCandidate(&NewCandidate, CB))
1428d409305fSDimitry Andric         CQueue.push(NewCandidate);
1429d409305fSDimitry Andric     }
1430d409305fSDimitry Andric   }
1431d409305fSDimitry Andric 
1432d409305fSDimitry Andric   // Cap the size growth from profile guided inlining. This is needed even
1433d409305fSDimitry Andric   // though cost of each inline candidate already accounts for callee size,
1434d409305fSDimitry Andric   // because with top-down inlining, we can grow inliner size significantly
1435d409305fSDimitry Andric   // with large number of smaller inlinees each pass the cost check.
1436d409305fSDimitry Andric   assert(ProfileInlineLimitMax >= ProfileInlineLimitMin &&
1437d409305fSDimitry Andric          "Max inline size limit should not be smaller than min inline size "
1438d409305fSDimitry Andric          "limit.");
1439d409305fSDimitry Andric   unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit;
1440d409305fSDimitry Andric   SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax);
1441d409305fSDimitry Andric   SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin);
1442d409305fSDimitry Andric   if (ExternalInlineAdvisor)
1443d409305fSDimitry Andric     SizeLimit = std::numeric_limits<unsigned>::max();
1444d409305fSDimitry Andric 
1445bdd1243dSDimitry Andric   MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
14460eae32dcSDimitry Andric 
1447d409305fSDimitry Andric   // Perform iterative BFS call site prioritized inlining
1448d409305fSDimitry Andric   bool Changed = false;
1449d409305fSDimitry Andric   while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
1450d409305fSDimitry Andric     InlineCandidate Candidate = CQueue.top();
1451d409305fSDimitry Andric     CQueue.pop();
1452d409305fSDimitry Andric     CallBase *I = Candidate.CallInstr;
1453d409305fSDimitry Andric     Function *CalledFunction = I->getCalledFunction();
1454d409305fSDimitry Andric 
1455d409305fSDimitry Andric     if (CalledFunction == &F)
1456d409305fSDimitry Andric       continue;
1457d409305fSDimitry Andric     if (I->isIndirectCall()) {
1458fe6060f1SDimitry Andric       uint64_t Sum = 0;
1459d409305fSDimitry Andric       auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
1460d409305fSDimitry Andric       uint64_t SumOrigin = Sum;
1461d409305fSDimitry Andric       Sum *= Candidate.CallsiteDistribution;
1462fe6060f1SDimitry Andric       unsigned ICPCount = 0;
1463d409305fSDimitry Andric       for (const auto *FS : CalleeSamples) {
1464d409305fSDimitry Andric         // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1465d409305fSDimitry Andric         if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
14665f757f3fSDimitry Andric           findExternalInlineCandidate(I, FS, InlinedGUIDs,
1467d409305fSDimitry Andric                                       PSI->getOrCompHotCountThreshold());
1468d409305fSDimitry Andric           continue;
1469d409305fSDimitry Andric         }
1470d409305fSDimitry Andric         uint64_t EntryCountDistributed =
1471fcaf7f86SDimitry Andric             FS->getHeadSamplesEstimate() * Candidate.CallsiteDistribution;
1472d409305fSDimitry Andric         // In addition to regular inline cost check, we also need to make sure
1473d409305fSDimitry Andric         // ICP isn't introducing excessive speculative checks even if individual
1474d409305fSDimitry Andric         // target looks beneficial to promote and inline. That means we should
1475d409305fSDimitry Andric         // only do ICP when there's a small number dominant targets.
1476fe6060f1SDimitry Andric         if (ICPCount >= ProfileICPRelativeHotnessSkip &&
1477fe6060f1SDimitry Andric             EntryCountDistributed * 100 < SumOrigin * ProfileICPRelativeHotness)
1478d409305fSDimitry Andric           break;
1479d409305fSDimitry Andric         // TODO: Fix CallAnalyzer to handle all indirect calls.
1480d409305fSDimitry Andric         // For indirect call, we don't run CallAnalyzer to get InlineCost
1481d409305fSDimitry Andric         // before actual inlining. This is because we could see two different
1482d409305fSDimitry Andric         // types from the same definition, which makes CallAnalyzer choke as
1483d409305fSDimitry Andric         // it's expecting matching parameter type on both caller and callee
1484d409305fSDimitry Andric         // side. See example from PR18962 for the triggering cases (the bug was
1485d409305fSDimitry Andric         // fixed, but we generate different types).
1486d409305fSDimitry Andric         if (!PSI->isHotCount(EntryCountDistributed))
1487d409305fSDimitry Andric           break;
1488d409305fSDimitry Andric         SmallVector<CallBase *, 8> InlinedCallSites;
1489d409305fSDimitry Andric         // Attach function profile for promoted indirect callee, and update
1490d409305fSDimitry Andric         // call site count for the promoted inline candidate too.
1491d409305fSDimitry Andric         Candidate = {I, FS, EntryCountDistributed,
1492d409305fSDimitry Andric                      Candidate.CallsiteDistribution};
1493d409305fSDimitry Andric         if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
1494fe6060f1SDimitry Andric                                          &InlinedCallSites)) {
1495d409305fSDimitry Andric           for (auto *CB : InlinedCallSites) {
1496d409305fSDimitry Andric             if (getInlineCandidate(&NewCandidate, CB))
1497d409305fSDimitry Andric               CQueue.emplace(NewCandidate);
1498d409305fSDimitry Andric           }
1499fe6060f1SDimitry Andric           ICPCount++;
1500d409305fSDimitry Andric           Changed = true;
15010eae32dcSDimitry Andric         } else if (!ContextTracker) {
1502bdd1243dSDimitry Andric           LocalNotInlinedCallSites.insert({I, FS});
1503d409305fSDimitry Andric         }
1504d409305fSDimitry Andric       }
1505d409305fSDimitry Andric     } else if (CalledFunction && CalledFunction->getSubprogram() &&
1506d409305fSDimitry Andric                !CalledFunction->isDeclaration()) {
1507d409305fSDimitry Andric       SmallVector<CallBase *, 8> InlinedCallSites;
1508d409305fSDimitry Andric       if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1509d409305fSDimitry Andric         for (auto *CB : InlinedCallSites) {
1510d409305fSDimitry Andric           if (getInlineCandidate(&NewCandidate, CB))
1511d409305fSDimitry Andric             CQueue.emplace(NewCandidate);
1512d409305fSDimitry Andric         }
1513d409305fSDimitry Andric         Changed = true;
15140eae32dcSDimitry Andric       } else if (!ContextTracker) {
1515bdd1243dSDimitry Andric         LocalNotInlinedCallSites.insert({I, Candidate.CalleeSamples});
1516d409305fSDimitry Andric       }
1517d409305fSDimitry Andric     } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1518349cc55cSDimitry Andric       findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
15195f757f3fSDimitry Andric                                   InlinedGUIDs,
1520349cc55cSDimitry Andric                                   PSI->getOrCompHotCountThreshold());
1521d409305fSDimitry Andric     }
1522d409305fSDimitry Andric   }
1523d409305fSDimitry Andric 
1524d409305fSDimitry Andric   if (!CQueue.empty()) {
1525d409305fSDimitry Andric     if (SizeLimit == (unsigned)ProfileInlineLimitMax)
1526d409305fSDimitry Andric       ++NumCSInlinedHitMaxLimit;
1527d409305fSDimitry Andric     else if (SizeLimit == (unsigned)ProfileInlineLimitMin)
1528d409305fSDimitry Andric       ++NumCSInlinedHitMinLimit;
1529d409305fSDimitry Andric     else
1530d409305fSDimitry Andric       ++NumCSInlinedHitGrowthLimit;
1531d409305fSDimitry Andric   }
1532d409305fSDimitry Andric 
15330eae32dcSDimitry Andric   // For CS profile, profile for not inlined context will be merged when
15340eae32dcSDimitry Andric   // base profile is being retrieved.
153581ad6265SDimitry Andric   if (!FunctionSamples::ProfileIsCS)
15360eae32dcSDimitry Andric     promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
1537d409305fSDimitry Andric   return Changed;
1538d409305fSDimitry Andric }
1539d409305fSDimitry Andric 
15400eae32dcSDimitry Andric void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
1541bdd1243dSDimitry Andric     MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
15420eae32dcSDimitry Andric     const Function &F) {
15430eae32dcSDimitry Andric   // Accumulate not inlined callsite information into notInlinedSamples
15440eae32dcSDimitry Andric   for (const auto &Pair : NonInlinedCallSites) {
1545bdd1243dSDimitry Andric     CallBase *I = Pair.first;
15460eae32dcSDimitry Andric     Function *Callee = I->getCalledFunction();
15470eae32dcSDimitry Andric     if (!Callee || Callee->isDeclaration())
15480eae32dcSDimitry Andric       continue;
15490eae32dcSDimitry Andric 
155081ad6265SDimitry Andric     ORE->emit(
155181ad6265SDimitry Andric         OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(), "NotInline",
15520eae32dcSDimitry Andric                                    I->getDebugLoc(), I->getParent())
155381ad6265SDimitry Andric         << "previous inlining not repeated: '" << ore::NV("Callee", Callee)
155481ad6265SDimitry Andric         << "' into '" << ore::NV("Caller", &F) << "'");
15550eae32dcSDimitry Andric 
15560eae32dcSDimitry Andric     ++NumCSNotInlined;
1557bdd1243dSDimitry Andric     const FunctionSamples *FS = Pair.second;
1558fcaf7f86SDimitry Andric     if (FS->getTotalSamples() == 0 && FS->getHeadSamplesEstimate() == 0) {
15590eae32dcSDimitry Andric       continue;
15600eae32dcSDimitry Andric     }
15610eae32dcSDimitry Andric 
156281ad6265SDimitry Andric     // Do not merge a context that is already duplicated into the base profile.
156381ad6265SDimitry Andric     if (FS->getContext().hasAttribute(sampleprof::ContextDuplicatedIntoBase))
156481ad6265SDimitry Andric       continue;
156581ad6265SDimitry Andric 
15660eae32dcSDimitry Andric     if (ProfileMergeInlinee) {
15670eae32dcSDimitry Andric       // A function call can be replicated by optimizations like callsite
15680eae32dcSDimitry Andric       // splitting or jump threading and the replicates end up sharing the
15690eae32dcSDimitry Andric       // sample nested callee profile instead of slicing the original
15700eae32dcSDimitry Andric       // inlinee's profile. We want to do merge exactly once by filtering out
15710eae32dcSDimitry Andric       // callee profiles with a non-zero head sample count.
15720eae32dcSDimitry Andric       if (FS->getHeadSamples() == 0) {
15730eae32dcSDimitry Andric         // Use entry samples as head samples during the merge, as inlinees
15740eae32dcSDimitry Andric         // don't have head samples.
15750eae32dcSDimitry Andric         const_cast<FunctionSamples *>(FS)->addHeadSamples(
1576fcaf7f86SDimitry Andric             FS->getHeadSamplesEstimate());
15770eae32dcSDimitry Andric 
15780eae32dcSDimitry Andric         // Note that we have to do the merge right after processing function.
15790eae32dcSDimitry Andric         // This allows OutlineFS's profile to be used for annotation during
15800eae32dcSDimitry Andric         // top-down processing of functions' annotation.
15815f757f3fSDimitry Andric         FunctionSamples *OutlineFS = Reader->getSamplesFor(*Callee);
15825f757f3fSDimitry Andric         // If outlined function does not exist in the profile, add it to a
15835f757f3fSDimitry Andric         // separate map so that it does not rehash the original profile.
15845f757f3fSDimitry Andric         if (!OutlineFS)
15855f757f3fSDimitry Andric           OutlineFS = &OutlineFunctionSamples[
15865f757f3fSDimitry Andric               FunctionId(FunctionSamples::getCanonicalFnName(Callee->getName()))];
15870eae32dcSDimitry Andric         OutlineFS->merge(*FS, 1);
15880eae32dcSDimitry Andric         // Set outlined profile to be synthetic to not bias the inliner.
1589*0fca6ea1SDimitry Andric         OutlineFS->setContextSynthetic();
15900eae32dcSDimitry Andric       }
15910eae32dcSDimitry Andric     } else {
15920eae32dcSDimitry Andric       auto pair =
15930eae32dcSDimitry Andric           notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1594fcaf7f86SDimitry Andric       pair.first->second.entryCount += FS->getHeadSamplesEstimate();
15950eae32dcSDimitry Andric     }
15960eae32dcSDimitry Andric   }
15970eae32dcSDimitry Andric }
15980eae32dcSDimitry Andric 
15990b57cec5SDimitry Andric /// Returns the sorted CallTargetMap \p M by count in descending order.
1600fe6060f1SDimitry Andric static SmallVector<InstrProfValueData, 2>
1601fe6060f1SDimitry Andric GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) {
16020b57cec5SDimitry Andric   SmallVector<InstrProfValueData, 2> R;
1603*0fca6ea1SDimitry Andric   for (const auto &I : SampleRecord::sortCallTargets(M)) {
1604fe6060f1SDimitry Andric     R.emplace_back(
16055f757f3fSDimitry Andric         InstrProfValueData{I.first.getHashCode(), I.second});
16068bcb0991SDimitry Andric   }
16070b57cec5SDimitry Andric   return R;
16080b57cec5SDimitry Andric }
16090b57cec5SDimitry Andric 
1610fe6060f1SDimitry Andric // Generate MD_prof metadata for every branch instruction using the
1611fe6060f1SDimitry Andric // edge weights computed during propagation.
1612fe6060f1SDimitry Andric void SampleProfileLoader::generateMDProfMetadata(Function &F) {
16130b57cec5SDimitry Andric   // Generate MD_prof metadata for every branch instruction using the
16140b57cec5SDimitry Andric   // edge weights computed during propagation.
16150b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
16160b57cec5SDimitry Andric   LLVMContext &Ctx = F.getContext();
16170b57cec5SDimitry Andric   MDBuilder MDB(Ctx);
16180b57cec5SDimitry Andric   for (auto &BI : F) {
16190b57cec5SDimitry Andric     BasicBlock *BB = &BI;
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric     if (BlockWeights[BB]) {
1622bdd1243dSDimitry Andric       for (auto &I : *BB) {
16230b57cec5SDimitry Andric         if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
16240b57cec5SDimitry Andric           continue;
16255ffd83dbSDimitry Andric         if (!cast<CallBase>(I).getCalledFunction()) {
16260b57cec5SDimitry Andric           const DebugLoc &DLoc = I.getDebugLoc();
16270b57cec5SDimitry Andric           if (!DLoc)
16280b57cec5SDimitry Andric             continue;
16290b57cec5SDimitry Andric           const DILocation *DIL = DLoc;
16300b57cec5SDimitry Andric           const FunctionSamples *FS = findFunctionSamples(I);
16310b57cec5SDimitry Andric           if (!FS)
16320b57cec5SDimitry Andric             continue;
1633e8d8bef9SDimitry Andric           auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
1634cb14a3feSDimitry Andric           ErrorOr<SampleRecord::CallTargetMap> T =
1635cb14a3feSDimitry Andric               FS->findCallTargetMapAt(CallSite);
16360b57cec5SDimitry Andric           if (!T || T.get().empty())
16370b57cec5SDimitry Andric             continue;
1638d409305fSDimitry Andric           if (FunctionSamples::ProfileIsProbeBased) {
1639fe6060f1SDimitry Andric             // Prorate the callsite counts based on the pre-ICP distribution
1640fe6060f1SDimitry Andric             // factor to reflect what is already done to the callsite before
1641fe6060f1SDimitry Andric             // ICP, such as calliste cloning.
1642bdd1243dSDimitry Andric             if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
1643d409305fSDimitry Andric               if (Probe->Factor < 1)
1644d409305fSDimitry Andric                 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
1645d409305fSDimitry Andric             }
1646d409305fSDimitry Andric           }
16470b57cec5SDimitry Andric           SmallVector<InstrProfValueData, 2> SortedCallTargets =
16488bcb0991SDimitry Andric               GetSortedValueDataFromCallTargets(T.get());
1649fe6060f1SDimitry Andric           uint64_t Sum = 0;
1650fe6060f1SDimitry Andric           for (const auto &C : T.get())
1651fe6060f1SDimitry Andric             Sum += C.second;
1652fe6060f1SDimitry Andric           // With CSSPGO all indirect call targets are counted torwards the
1653fe6060f1SDimitry Andric           // original indirect call site in the profile, including both
1654fe6060f1SDimitry Andric           // inlined and non-inlined targets.
165581ad6265SDimitry Andric           if (!FunctionSamples::ProfileIsCS) {
1656fe6060f1SDimitry Andric             if (const FunctionSamplesMap *M =
1657fe6060f1SDimitry Andric                     FS->findFunctionSamplesMapAt(CallSite)) {
1658fe6060f1SDimitry Andric               for (const auto &NameFS : *M)
1659fcaf7f86SDimitry Andric                 Sum += NameFS.second.getHeadSamplesEstimate();
1660fe6060f1SDimitry Andric             }
1661fe6060f1SDimitry Andric           }
1662fe6060f1SDimitry Andric           if (Sum)
1663fe6060f1SDimitry Andric             updateIDTMetaData(I, SortedCallTargets, Sum);
1664fe6060f1SDimitry Andric           else if (OverwriteExistingWeights)
1665fe6060f1SDimitry Andric             I.setMetadata(LLVMContext::MD_prof, nullptr);
16660b57cec5SDimitry Andric         } else if (!isa<IntrinsicInst>(&I)) {
1667*0fca6ea1SDimitry Andric           setBranchWeights(I, {static_cast<uint32_t>(BlockWeights[BB])},
1668*0fca6ea1SDimitry Andric                            /*IsExpected=*/false);
16690b57cec5SDimitry Andric         }
16700b57cec5SDimitry Andric       }
1671349cc55cSDimitry Andric     } else if (OverwriteExistingWeights || ProfileSampleBlockAccurate) {
1672fe6060f1SDimitry Andric       // Set profile metadata (possibly annotated by LTO prelink) to zero or
1673fe6060f1SDimitry Andric       // clear it for cold code.
1674bdd1243dSDimitry Andric       for (auto &I : *BB) {
1675fe6060f1SDimitry Andric         if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
16765f757f3fSDimitry Andric           if (cast<CallBase>(I).isIndirectCall()) {
1677fe6060f1SDimitry Andric             I.setMetadata(LLVMContext::MD_prof, nullptr);
16785f757f3fSDimitry Andric           } else {
1679*0fca6ea1SDimitry Andric             setBranchWeights(I, {uint32_t(0)}, /*IsExpected=*/false);
16805f757f3fSDimitry Andric           }
16810b57cec5SDimitry Andric         }
1682fe6060f1SDimitry Andric       }
1683fe6060f1SDimitry Andric     }
1684fe6060f1SDimitry Andric 
16850b57cec5SDimitry Andric     Instruction *TI = BB->getTerminator();
16860b57cec5SDimitry Andric     if (TI->getNumSuccessors() == 1)
16870b57cec5SDimitry Andric       continue;
1688fe6060f1SDimitry Andric     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI) &&
1689fe6060f1SDimitry Andric         !isa<IndirectBrInst>(TI))
16900b57cec5SDimitry Andric       continue;
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric     DebugLoc BranchLoc = TI->getDebugLoc();
16930b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
16940b57cec5SDimitry Andric                       << ((BranchLoc) ? Twine(BranchLoc.getLine())
16950b57cec5SDimitry Andric                                       : Twine("<UNKNOWN LOCATION>"))
16960b57cec5SDimitry Andric                       << ".\n");
16970b57cec5SDimitry Andric     SmallVector<uint32_t, 4> Weights;
16980b57cec5SDimitry Andric     uint32_t MaxWeight = 0;
16990b57cec5SDimitry Andric     Instruction *MaxDestInst;
17004824e7fdSDimitry Andric     // Since profi treats multiple edges (multiway branches) as a single edge,
17014824e7fdSDimitry Andric     // we need to distribute the computed weight among the branches. We do
17024824e7fdSDimitry Andric     // this by evenly splitting the edge weight among destinations.
17034824e7fdSDimitry Andric     DenseMap<const BasicBlock *, uint64_t> EdgeMultiplicity;
17044824e7fdSDimitry Andric     std::vector<uint64_t> EdgeIndex;
17054824e7fdSDimitry Andric     if (SampleProfileUseProfi) {
17064824e7fdSDimitry Andric       EdgeIndex.resize(TI->getNumSuccessors());
17074824e7fdSDimitry Andric       for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
17084824e7fdSDimitry Andric         const BasicBlock *Succ = TI->getSuccessor(I);
17094824e7fdSDimitry Andric         EdgeIndex[I] = EdgeMultiplicity[Succ];
17104824e7fdSDimitry Andric         EdgeMultiplicity[Succ]++;
17114824e7fdSDimitry Andric       }
17124824e7fdSDimitry Andric     }
17130b57cec5SDimitry Andric     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
17140b57cec5SDimitry Andric       BasicBlock *Succ = TI->getSuccessor(I);
17150b57cec5SDimitry Andric       Edge E = std::make_pair(BB, Succ);
17160b57cec5SDimitry Andric       uint64_t Weight = EdgeWeights[E];
17170b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
17180b57cec5SDimitry Andric       // Use uint32_t saturated arithmetic to adjust the incoming weights,
17190b57cec5SDimitry Andric       // if needed. Sample counts in profiles are 64-bit unsigned values,
17200b57cec5SDimitry Andric       // but internally branch weights are expressed as 32-bit values.
17210b57cec5SDimitry Andric       if (Weight > std::numeric_limits<uint32_t>::max()) {
1722*0fca6ea1SDimitry Andric         LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)\n");
17230b57cec5SDimitry Andric         Weight = std::numeric_limits<uint32_t>::max();
17240b57cec5SDimitry Andric       }
17254824e7fdSDimitry Andric       if (!SampleProfileUseProfi) {
17260b57cec5SDimitry Andric         // Weight is added by one to avoid propagation errors introduced by
17270b57cec5SDimitry Andric         // 0 weights.
1728*0fca6ea1SDimitry Andric         Weights.push_back(static_cast<uint32_t>(
1729*0fca6ea1SDimitry Andric             Weight == std::numeric_limits<uint32_t>::max() ? Weight
1730*0fca6ea1SDimitry Andric                                                            : Weight + 1));
17314824e7fdSDimitry Andric       } else {
17324824e7fdSDimitry Andric         // Profi creates proper weights that do not require "+1" adjustments but
17334824e7fdSDimitry Andric         // we evenly split the weight among branches with the same destination.
17344824e7fdSDimitry Andric         uint64_t W = Weight / EdgeMultiplicity[Succ];
17354824e7fdSDimitry Andric         // Rounding up, if needed, so that first branches are hotter.
17364824e7fdSDimitry Andric         if (EdgeIndex[I] < Weight % EdgeMultiplicity[Succ])
17374824e7fdSDimitry Andric           W++;
17384824e7fdSDimitry Andric         Weights.push_back(static_cast<uint32_t>(W));
17394824e7fdSDimitry Andric       }
17400b57cec5SDimitry Andric       if (Weight != 0) {
17410b57cec5SDimitry Andric         if (Weight > MaxWeight) {
17420b57cec5SDimitry Andric           MaxWeight = Weight;
17430b57cec5SDimitry Andric           MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
17440b57cec5SDimitry Andric         }
17450b57cec5SDimitry Andric       }
17460b57cec5SDimitry Andric     }
17470b57cec5SDimitry Andric 
1748bdd1243dSDimitry Andric     misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
174981ad6265SDimitry Andric 
17500b57cec5SDimitry Andric     uint64_t TempWeight;
17510b57cec5SDimitry Andric     // Only set weights if there is at least one non-zero weight.
17520b57cec5SDimitry Andric     // In any other case, let the analyzer set weights.
1753fe6060f1SDimitry Andric     // Do not set weights if the weights are present unless under
1754fe6060f1SDimitry Andric     // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
1755fe6060f1SDimitry Andric     // twice. If the first annotation already set the weights, the second pass
1756fe6060f1SDimitry Andric     // does not need to set it. With OverwriteExistingWeights, Blocks with zero
1757fe6060f1SDimitry Andric     // weight should have their existing metadata (possibly annotated by LTO
1758fe6060f1SDimitry Andric     // prelink) cleared.
1759fe6060f1SDimitry Andric     if (MaxWeight > 0 &&
1760fe6060f1SDimitry Andric         (!TI->extractProfTotalWeight(TempWeight) || OverwriteExistingWeights)) {
17610b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1762*0fca6ea1SDimitry Andric       setBranchWeights(*TI, Weights, /*IsExpected=*/false);
17630b57cec5SDimitry Andric       ORE->emit([&]() {
17640b57cec5SDimitry Andric         return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
17650b57cec5SDimitry Andric                << "most popular destination for conditional branches at "
17660b57cec5SDimitry Andric                << ore::NV("CondBranchesLoc", BranchLoc);
17670b57cec5SDimitry Andric       });
17680b57cec5SDimitry Andric     } else {
1769fe6060f1SDimitry Andric       if (OverwriteExistingWeights) {
1770fe6060f1SDimitry Andric         TI->setMetadata(LLVMContext::MD_prof, nullptr);
1771fe6060f1SDimitry Andric         LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
1772fe6060f1SDimitry Andric       } else {
17730b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
17740b57cec5SDimitry Andric       }
17750b57cec5SDimitry Andric     }
17760b57cec5SDimitry Andric   }
17770b57cec5SDimitry Andric }
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric /// Once all the branch weights are computed, we emit the MD_prof
17800b57cec5SDimitry Andric /// metadata on BB using the computed values for each of its branches.
17810b57cec5SDimitry Andric ///
17820b57cec5SDimitry Andric /// \param F The function to query.
17830b57cec5SDimitry Andric ///
17840b57cec5SDimitry Andric /// \returns true if \p F was modified. Returns false, otherwise.
17850b57cec5SDimitry Andric bool SampleProfileLoader::emitAnnotations(Function &F) {
17860b57cec5SDimitry Andric   bool Changed = false;
17870b57cec5SDimitry Andric 
1788e8d8bef9SDimitry Andric   if (FunctionSamples::ProfileIsProbeBased) {
1789*0fca6ea1SDimitry Andric     LLVM_DEBUG({
1790*0fca6ea1SDimitry Andric       if (!ProbeManager->getDesc(F))
1791*0fca6ea1SDimitry Andric         dbgs() << "Probe descriptor missing for Function " << F.getName()
1792*0fca6ea1SDimitry Andric                << "\n";
1793*0fca6ea1SDimitry Andric     });
1794*0fca6ea1SDimitry Andric 
1795*0fca6ea1SDimitry Andric     if (ProbeManager->profileIsValid(F, *Samples)) {
1796*0fca6ea1SDimitry Andric       ++NumMatchedProfile;
1797*0fca6ea1SDimitry Andric     } else {
1798*0fca6ea1SDimitry Andric       ++NumMismatchedProfile;
1799e8d8bef9SDimitry Andric       LLVM_DEBUG(
1800e8d8bef9SDimitry Andric           dbgs() << "Profile is invalid due to CFG mismatch for Function "
180106c3fb27SDimitry Andric                  << F.getName() << "\n");
180206c3fb27SDimitry Andric       if (!SalvageStaleProfile)
1803e8d8bef9SDimitry Andric         return false;
1804e8d8bef9SDimitry Andric     }
1805e8d8bef9SDimitry Andric   } else {
18060b57cec5SDimitry Andric     if (getFunctionLoc(F) == 0)
18070b57cec5SDimitry Andric       return false;
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
18100b57cec5SDimitry Andric                       << F.getName() << ": " << getFunctionLoc(F) << "\n");
1811e8d8bef9SDimitry Andric   }
18120b57cec5SDimitry Andric 
18130b57cec5SDimitry Andric   DenseSet<GlobalValue::GUID> InlinedGUIDs;
18140eae32dcSDimitry Andric   if (CallsitePrioritizedInline)
1815d409305fSDimitry Andric     Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
1816d409305fSDimitry Andric   else
18170b57cec5SDimitry Andric     Changed |= inlineHotFunctions(F, InlinedGUIDs);
18180b57cec5SDimitry Andric 
1819fe6060f1SDimitry Andric   Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
18200b57cec5SDimitry Andric 
1821fe6060f1SDimitry Andric   if (Changed)
1822fe6060f1SDimitry Andric     generateMDProfMetadata(F);
18230b57cec5SDimitry Andric 
1824fe6060f1SDimitry Andric   emitCoverageRemarks(F);
18250b57cec5SDimitry Andric   return Changed;
18260b57cec5SDimitry Andric }
18270b57cec5SDimitry Andric 
1828fe6060f1SDimitry Andric std::unique_ptr<ProfiledCallGraph>
182906c3fb27SDimitry Andric SampleProfileLoader::buildProfiledCallGraph(Module &M) {
1830fe6060f1SDimitry Andric   std::unique_ptr<ProfiledCallGraph> ProfiledCG;
183181ad6265SDimitry Andric   if (FunctionSamples::ProfileIsCS)
1832fe6060f1SDimitry Andric     ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
1833fe6060f1SDimitry Andric   else
1834fe6060f1SDimitry Andric     ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1835d409305fSDimitry Andric 
1836fe6060f1SDimitry Andric   // Add all functions into the profiled call graph even if they are not in
1837fe6060f1SDimitry Andric   // the profile. This makes sure functions missing from the profile still
1838fe6060f1SDimitry Andric   // gets a chance to be processed.
183906c3fb27SDimitry Andric   for (Function &F : M) {
1840*0fca6ea1SDimitry Andric     if (skipProfileForFunction(F))
1841fe6060f1SDimitry Andric       continue;
18425f757f3fSDimitry Andric     ProfiledCG->addProfiledFunction(
18435f757f3fSDimitry Andric           getRepInFormat(FunctionSamples::getCanonicalFnName(F)));
1844d409305fSDimitry Andric   }
1845d409305fSDimitry Andric 
1846fe6060f1SDimitry Andric   return ProfiledCG;
1847d409305fSDimitry Andric }
1848d409305fSDimitry Andric 
1849480093f4SDimitry Andric std::vector<Function *>
185006c3fb27SDimitry Andric SampleProfileLoader::buildFunctionOrder(Module &M, LazyCallGraph &CG) {
1851480093f4SDimitry Andric   std::vector<Function *> FunctionOrderList;
1852480093f4SDimitry Andric   FunctionOrderList.reserve(M.size());
1853480093f4SDimitry Andric 
1854fe6060f1SDimitry Andric   if (!ProfileTopDownLoad && UseProfiledCallGraph)
1855fe6060f1SDimitry Andric     errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
1856fe6060f1SDimitry Andric               "together with -sample-profile-top-down-load.\n";
1857fe6060f1SDimitry Andric 
185806c3fb27SDimitry Andric   if (!ProfileTopDownLoad) {
18595ffd83dbSDimitry Andric     if (ProfileMergeInlinee) {
18605ffd83dbSDimitry Andric       // Disable ProfileMergeInlinee if profile is not loaded in top down order,
18615ffd83dbSDimitry Andric       // because the profile for a function may be used for the profile
18625ffd83dbSDimitry Andric       // annotation of its outline copy before the profile merging of its
18635ffd83dbSDimitry Andric       // non-inlined inline instances, and that is not the way how
18645ffd83dbSDimitry Andric       // ProfileMergeInlinee is supposed to work.
18655ffd83dbSDimitry Andric       ProfileMergeInlinee = false;
18665ffd83dbSDimitry Andric     }
18675ffd83dbSDimitry Andric 
1868480093f4SDimitry Andric     for (Function &F : M)
1869*0fca6ea1SDimitry Andric       if (!skipProfileForFunction(F))
1870480093f4SDimitry Andric         FunctionOrderList.push_back(&F);
1871480093f4SDimitry Andric     return FunctionOrderList;
1872480093f4SDimitry Andric   }
1873480093f4SDimitry Andric 
187481ad6265SDimitry Andric   if (UseProfiledCallGraph || (FunctionSamples::ProfileIsCS &&
187581ad6265SDimitry Andric                                !UseProfiledCallGraph.getNumOccurrences())) {
1876fe6060f1SDimitry Andric     // Use profiled call edges to augment the top-down order. There are cases
1877fe6060f1SDimitry Andric     // that the top-down order computed based on the static call graph doesn't
1878fe6060f1SDimitry Andric     // reflect real execution order. For example
1879fe6060f1SDimitry Andric     //
1880fe6060f1SDimitry Andric     // 1. Incomplete static call graph due to unknown indirect call targets.
1881fe6060f1SDimitry Andric     //    Adjusting the order by considering indirect call edges from the
1882fe6060f1SDimitry Andric     //    profile can enable the inlining of indirect call targets by allowing
1883fe6060f1SDimitry Andric     //    the caller processed before them.
1884fe6060f1SDimitry Andric     // 2. Mutual call edges in an SCC. The static processing order computed for
1885fe6060f1SDimitry Andric     //    an SCC may not reflect the call contexts in the context-sensitive
1886fe6060f1SDimitry Andric     //    profile, thus may cause potential inlining to be overlooked. The
1887fe6060f1SDimitry Andric     //    function order in one SCC is being adjusted to a top-down order based
1888fe6060f1SDimitry Andric     //    on the profile to favor more inlining. This is only a problem with CS
1889fe6060f1SDimitry Andric     //    profile.
1890fe6060f1SDimitry Andric     // 3. Transitive indirect call edges due to inlining. When a callee function
18915f757f3fSDimitry Andric     //    (say B) is inlined into a caller function (say A) in LTO prelink,
1892fe6060f1SDimitry Andric     //    every call edge originated from the callee B will be transferred to
1893fe6060f1SDimitry Andric     //    the caller A. If any transferred edge (say A->C) is indirect, the
1894fe6060f1SDimitry Andric     //    original profiled indirect edge B->C, even if considered, would not
1895fe6060f1SDimitry Andric     //    enforce a top-down order from the caller A to the potential indirect
1896fe6060f1SDimitry Andric     //    call target C in LTO postlink since the inlined callee B is gone from
1897fe6060f1SDimitry Andric     //    the static call graph.
1898fe6060f1SDimitry Andric     // 4. #3 can happen even for direct call targets, due to functions defined
1899fe6060f1SDimitry Andric     //    in header files. A header function (say A), when included into source
1900fe6060f1SDimitry Andric     //    files, is defined multiple times but only one definition survives due
1901fe6060f1SDimitry Andric     //    to ODR. Therefore, the LTO prelink inlining done on those dropped
1902fe6060f1SDimitry Andric     //    definitions can be useless based on a local file scope. More
1903fe6060f1SDimitry Andric     //    importantly, the inlinee (say B), once fully inlined to a
1904fe6060f1SDimitry Andric     //    to-be-dropped A, will have no profile to consume when its outlined
1905fe6060f1SDimitry Andric     //    version is compiled. This can lead to a profile-less prelink
1906fe6060f1SDimitry Andric     //    compilation for the outlined version of B which may be called from
1907fe6060f1SDimitry Andric     //    external modules. while this isn't easy to fix, we rely on the
1908fe6060f1SDimitry Andric     //    postlink AutoFDO pipeline to optimize B. Since the survived copy of
1909fe6060f1SDimitry Andric     //    the A can be inlined in its local scope in prelink, it may not exist
1910fe6060f1SDimitry Andric     //    in the merged IR in postlink, and we'll need the profiled call edges
1911fe6060f1SDimitry Andric     //    to enforce a top-down order for the rest of the functions.
1912fe6060f1SDimitry Andric     //
1913fe6060f1SDimitry Andric     // Considering those cases, a profiled call graph completely independent of
1914fe6060f1SDimitry Andric     // the static call graph is constructed based on profile data, where
1915fe6060f1SDimitry Andric     // function objects are not even needed to handle case #3 and case 4.
1916fe6060f1SDimitry Andric     //
1917fe6060f1SDimitry Andric     // Note that static callgraph edges are completely ignored since they
1918fe6060f1SDimitry Andric     // can be conflicting with profiled edges for cyclic SCCs and may result in
1919fe6060f1SDimitry Andric     // an SCC order incompatible with profile-defined one. Using strictly
1920fe6060f1SDimitry Andric     // profile order ensures a maximum inlining experience. On the other hand,
1921fe6060f1SDimitry Andric     // static call edges are not so important when they don't correspond to a
1922fe6060f1SDimitry Andric     // context in the profile.
1923d409305fSDimitry Andric 
192406c3fb27SDimitry Andric     std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(M);
1925fe6060f1SDimitry Andric     scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get());
1926480093f4SDimitry Andric     while (!CGI.isAtEnd()) {
19274824e7fdSDimitry Andric       auto Range = *CGI;
19284824e7fdSDimitry Andric       if (SortProfiledSCC) {
19294824e7fdSDimitry Andric         // Sort nodes in one SCC based on callsite hotness.
19304824e7fdSDimitry Andric         scc_member_iterator<ProfiledCallGraph *> SI(*CGI);
19314824e7fdSDimitry Andric         Range = *SI;
19324824e7fdSDimitry Andric       }
19334824e7fdSDimitry Andric       for (auto *Node : Range) {
1934fe6060f1SDimitry Andric         Function *F = SymbolMap.lookup(Node->Name);
1935*0fca6ea1SDimitry Andric         if (F && !skipProfileForFunction(*F))
1936fe6060f1SDimitry Andric           FunctionOrderList.push_back(F);
1937480093f4SDimitry Andric       }
1938480093f4SDimitry Andric       ++CGI;
1939480093f4SDimitry Andric     }
194006c3fb27SDimitry Andric     std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1941*0fca6ea1SDimitry Andric   } else
1942*0fca6ea1SDimitry Andric     buildTopDownFuncOrder(CG, FunctionOrderList);
194306c3fb27SDimitry Andric 
1944d409305fSDimitry Andric   LLVM_DEBUG({
1945d409305fSDimitry Andric     dbgs() << "Function processing order:\n";
194606c3fb27SDimitry Andric     for (auto F : FunctionOrderList) {
1947d409305fSDimitry Andric       dbgs() << F->getName() << "\n";
1948d409305fSDimitry Andric     }
1949d409305fSDimitry Andric   });
1950480093f4SDimitry Andric 
1951480093f4SDimitry Andric   return FunctionOrderList;
1952480093f4SDimitry Andric }
1953480093f4SDimitry Andric 
1954e8d8bef9SDimitry Andric bool SampleProfileLoader::doInitialization(Module &M,
1955e8d8bef9SDimitry Andric                                            FunctionAnalysisManager *FAM) {
19560b57cec5SDimitry Andric   auto &Ctx = M.getContext();
19578bcb0991SDimitry Andric 
1958fe6060f1SDimitry Andric   auto ReaderOrErr = SampleProfileReader::create(
195906c3fb27SDimitry Andric       Filename, Ctx, *FS, FSDiscriminatorPass::Base, RemappingFilename);
19600b57cec5SDimitry Andric   if (std::error_code EC = ReaderOrErr.getError()) {
19610b57cec5SDimitry Andric     std::string Msg = "Could not open profile: " + EC.message();
19620b57cec5SDimitry Andric     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
19630b57cec5SDimitry Andric     return false;
19640b57cec5SDimitry Andric   }
19650b57cec5SDimitry Andric   Reader = std::move(ReaderOrErr.get());
1966e8d8bef9SDimitry Andric   Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1967fe6060f1SDimitry Andric   // set module before reading the profile so reader may be able to only
1968fe6060f1SDimitry Andric   // read the function profiles which are used by the current module.
1969fe6060f1SDimitry Andric   Reader->setModule(&M);
1970e8d8bef9SDimitry Andric   if (std::error_code EC = Reader->read()) {
1971e8d8bef9SDimitry Andric     std::string Msg = "profile reading failed: " + EC.message();
1972e8d8bef9SDimitry Andric     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1973e8d8bef9SDimitry Andric     return false;
1974e8d8bef9SDimitry Andric   }
1975e8d8bef9SDimitry Andric 
19768bcb0991SDimitry Andric   PSL = Reader->getProfileSymbolList();
19770b57cec5SDimitry Andric 
19788bcb0991SDimitry Andric   // While profile-sample-accurate is on, ignore symbol list.
19798bcb0991SDimitry Andric   ProfAccForSymsInList =
19808bcb0991SDimitry Andric       ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
19818bcb0991SDimitry Andric   if (ProfAccForSymsInList) {
19828bcb0991SDimitry Andric     NamesInProfile.clear();
19835f757f3fSDimitry Andric     GUIDsInProfile.clear();
19845f757f3fSDimitry Andric     if (auto NameTable = Reader->getNameTable()) {
19855f757f3fSDimitry Andric       if (FunctionSamples::UseMD5) {
19865f757f3fSDimitry Andric         for (auto Name : *NameTable)
19875f757f3fSDimitry Andric           GUIDsInProfile.insert(Name.getHashCode());
19885f757f3fSDimitry Andric       } else {
19895f757f3fSDimitry Andric         for (auto Name : *NameTable)
19905f757f3fSDimitry Andric           NamesInProfile.insert(Name.stringRef());
19915f757f3fSDimitry Andric       }
19925f757f3fSDimitry Andric     }
1993fe6060f1SDimitry Andric     CoverageTracker.setProfAccForSymsInList(true);
19940b57cec5SDimitry Andric   }
19958bcb0991SDimitry Andric 
1996e8d8bef9SDimitry Andric   if (FAM && !ProfileInlineReplayFile.empty()) {
1997349cc55cSDimitry Andric     ExternalInlineAdvisor = getReplayInlineAdvisor(
1998349cc55cSDimitry Andric         M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr,
1999349cc55cSDimitry Andric         ReplayInlinerSettings{ProfileInlineReplayFile,
2000349cc55cSDimitry Andric                               ProfileInlineReplayScope,
2001349cc55cSDimitry Andric                               ProfileInlineReplayFallback,
2002349cc55cSDimitry Andric                               {ProfileInlineReplayFormat}},
200381ad6265SDimitry Andric         /*EmitRemarks=*/false, InlineContext{LTOPhase, InlinePass::ReplaySampleProfileInliner});
2004e8d8bef9SDimitry Andric   }
2005e8d8bef9SDimitry Andric 
200681ad6265SDimitry Andric   // Apply tweaks if context-sensitive or probe-based profile is available.
200781ad6265SDimitry Andric   if (Reader->profileIsCS() || Reader->profileIsPreInlined() ||
200881ad6265SDimitry Andric       Reader->profileIsProbeBased()) {
200981ad6265SDimitry Andric     if (!UseIterativeBFIInference.getNumOccurrences())
201081ad6265SDimitry Andric       UseIterativeBFIInference = true;
201181ad6265SDimitry Andric     if (!SampleProfileUseProfi.getNumOccurrences())
201281ad6265SDimitry Andric       SampleProfileUseProfi = true;
201381ad6265SDimitry Andric     if (!EnableExtTspBlockPlacement.getNumOccurrences())
201481ad6265SDimitry Andric       EnableExtTspBlockPlacement = true;
2015d409305fSDimitry Andric     // Enable priority-base inliner and size inline by default for CSSPGO.
2016d409305fSDimitry Andric     if (!ProfileSizeInline.getNumOccurrences())
2017d409305fSDimitry Andric       ProfileSizeInline = true;
2018d409305fSDimitry Andric     if (!CallsitePrioritizedInline.getNumOccurrences())
2019d409305fSDimitry Andric       CallsitePrioritizedInline = true;
2020349cc55cSDimitry Andric     // For CSSPGO, we also allow recursive inline to best use context profile.
2021349cc55cSDimitry Andric     if (!AllowRecursiveInline.getNumOccurrences())
2022349cc55cSDimitry Andric       AllowRecursiveInline = true;
2023349cc55cSDimitry Andric 
202481ad6265SDimitry Andric     if (Reader->profileIsPreInlined()) {
202581ad6265SDimitry Andric       if (!UsePreInlinerDecision.getNumOccurrences())
202681ad6265SDimitry Andric         UsePreInlinerDecision = true;
202781ad6265SDimitry Andric     }
2028fe6060f1SDimitry Andric 
202906c3fb27SDimitry Andric     // Enable stale profile matching by default for probe-based profile.
203006c3fb27SDimitry Andric     // Currently the matching relies on if the checksum mismatch is detected,
203106c3fb27SDimitry Andric     // which is currently only available for pseudo-probe mode. Removing the
203206c3fb27SDimitry Andric     // checksum check could cause regressions for some cases, so further tuning
203306c3fb27SDimitry Andric     // might be needed if we want to enable it for all cases.
203406c3fb27SDimitry Andric     if (Reader->profileIsProbeBased() &&
203506c3fb27SDimitry Andric         !SalvageStaleProfile.getNumOccurrences()) {
203606c3fb27SDimitry Andric       SalvageStaleProfile = true;
203706c3fb27SDimitry Andric     }
203806c3fb27SDimitry Andric 
203981ad6265SDimitry Andric     if (!Reader->profileIsCS()) {
204081ad6265SDimitry Andric       // Non-CS profile should be fine without a function size budget for the
204181ad6265SDimitry Andric       // inliner since the contexts in the profile are either all from inlining
204281ad6265SDimitry Andric       // in the prevoius build or pre-computed by the preinliner with a size
204381ad6265SDimitry Andric       // cap, thus they are bounded.
204481ad6265SDimitry Andric       if (!ProfileInlineLimitMin.getNumOccurrences())
204581ad6265SDimitry Andric         ProfileInlineLimitMin = std::numeric_limits<unsigned>::max();
204681ad6265SDimitry Andric       if (!ProfileInlineLimitMax.getNumOccurrences())
204781ad6265SDimitry Andric         ProfileInlineLimitMax = std::numeric_limits<unsigned>::max();
204881ad6265SDimitry Andric     }
204981ad6265SDimitry Andric   }
205081ad6265SDimitry Andric 
205181ad6265SDimitry Andric   if (Reader->profileIsCS()) {
2052e8d8bef9SDimitry Andric     // Tracker for profiles under different context
2053349cc55cSDimitry Andric     ContextTracker = std::make_unique<SampleContextTracker>(
2054349cc55cSDimitry Andric         Reader->getProfiles(), &GUIDToFuncNameMap);
2055e8d8bef9SDimitry Andric   }
2056e8d8bef9SDimitry Andric 
2057e8d8bef9SDimitry Andric   // Load pseudo probe descriptors for probe-based function samples.
2058e8d8bef9SDimitry Andric   if (Reader->profileIsProbeBased()) {
2059e8d8bef9SDimitry Andric     ProbeManager = std::make_unique<PseudoProbeManager>(M);
2060e8d8bef9SDimitry Andric     if (!ProbeManager->moduleIsProbed(M)) {
2061e8d8bef9SDimitry Andric       const char *Msg =
2062e8d8bef9SDimitry Andric           "Pseudo-probe-based profile requires SampleProfileProbePass";
20630eae32dcSDimitry Andric       Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg,
20640eae32dcSDimitry Andric                                                DS_Warning));
2065e8d8bef9SDimitry Andric       return false;
2066e8d8bef9SDimitry Andric     }
2067e8d8bef9SDimitry Andric   }
2068e8d8bef9SDimitry Andric 
206906c3fb27SDimitry Andric   if (ReportProfileStaleness || PersistProfileStaleness ||
207006c3fb27SDimitry Andric       SalvageStaleProfile) {
2071*0fca6ea1SDimitry Andric     MatchingManager = std::make_unique<SampleProfileMatcher>(
2072*0fca6ea1SDimitry Andric         M, *Reader, CG, ProbeManager.get(), LTOPhase, SymbolMap, PSL,
2073*0fca6ea1SDimitry Andric         FuncNameToProfNameMap);
2074bdd1243dSDimitry Andric   }
2075bdd1243dSDimitry Andric 
20760b57cec5SDimitry Andric   return true;
20770b57cec5SDimitry Andric }
20780b57cec5SDimitry Andric 
2079*0fca6ea1SDimitry Andric // Note that this is a module-level check. Even if one module is errored out,
2080*0fca6ea1SDimitry Andric // the entire build will be errored out. However, the user could make big
2081*0fca6ea1SDimitry Andric // changes to functions in single module but those changes might not be
2082*0fca6ea1SDimitry Andric // performance significant to the whole binary. Therefore, to avoid those false
2083*0fca6ea1SDimitry Andric // positives, we select a reasonable big set of hot functions that are supposed
2084*0fca6ea1SDimitry Andric // to be globally performance significant, only compute and check the mismatch
2085*0fca6ea1SDimitry Andric // within those functions. The function selection is based on two criteria:
2086*0fca6ea1SDimitry Andric // 1) The function is hot enough, which is tuned by a hotness-based
2087*0fca6ea1SDimitry Andric // flag(HotFuncCutoffForStalenessError). 2) The num of function is large enough
2088*0fca6ea1SDimitry Andric // which is tuned by the MinfuncsForStalenessError flag.
2089*0fca6ea1SDimitry Andric bool SampleProfileLoader::rejectHighStalenessProfile(
2090*0fca6ea1SDimitry Andric     Module &M, ProfileSummaryInfo *PSI, const SampleProfileMap &Profiles) {
2091*0fca6ea1SDimitry Andric   assert(FunctionSamples::ProfileIsProbeBased &&
2092*0fca6ea1SDimitry Andric          "Only support for probe-based profile");
2093*0fca6ea1SDimitry Andric   uint64_t TotalHotFunc = 0;
2094*0fca6ea1SDimitry Andric   uint64_t NumMismatchedFunc = 0;
2095*0fca6ea1SDimitry Andric   for (const auto &I : Profiles) {
2096*0fca6ea1SDimitry Andric     const auto &FS = I.second;
2097*0fca6ea1SDimitry Andric     const auto *FuncDesc = ProbeManager->getDesc(FS.getGUID());
2098*0fca6ea1SDimitry Andric     if (!FuncDesc)
2099*0fca6ea1SDimitry Andric       continue;
21005f757f3fSDimitry Andric 
2101*0fca6ea1SDimitry Andric     // Use a hotness-based threshold to control the function selection.
2102*0fca6ea1SDimitry Andric     if (!PSI->isHotCountNthPercentile(HotFuncCutoffForStalenessError,
2103*0fca6ea1SDimitry Andric                                       FS.getTotalSamples()))
2104*0fca6ea1SDimitry Andric       continue;
21055f757f3fSDimitry Andric 
2106*0fca6ea1SDimitry Andric     TotalHotFunc++;
2107*0fca6ea1SDimitry Andric     if (ProbeManager->profileIsHashMismatched(*FuncDesc, FS))
2108*0fca6ea1SDimitry Andric       NumMismatchedFunc++;
2109*0fca6ea1SDimitry Andric   }
2110*0fca6ea1SDimitry Andric   // Make sure that the num of selected function is not too small to distinguish
2111*0fca6ea1SDimitry Andric   // from the user's benign changes.
2112*0fca6ea1SDimitry Andric   if (TotalHotFunc < MinfuncsForStalenessError)
2113*0fca6ea1SDimitry Andric     return false;
21145f757f3fSDimitry Andric 
2115*0fca6ea1SDimitry Andric   // Finally check the mismatch percentage against the threshold.
2116*0fca6ea1SDimitry Andric   if (NumMismatchedFunc * 100 >=
2117*0fca6ea1SDimitry Andric       TotalHotFunc * PrecentMismatchForStalenessError) {
2118*0fca6ea1SDimitry Andric     auto &Ctx = M.getContext();
2119*0fca6ea1SDimitry Andric     const char *Msg =
2120*0fca6ea1SDimitry Andric         "The input profile significantly mismatches current source code. "
2121*0fca6ea1SDimitry Andric         "Please recollect profile to avoid performance regression.";
2122*0fca6ea1SDimitry Andric     Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg));
2123*0fca6ea1SDimitry Andric     return true;
2124*0fca6ea1SDimitry Andric   }
2125*0fca6ea1SDimitry Andric   return false;
2126*0fca6ea1SDimitry Andric }
2127*0fca6ea1SDimitry Andric 
2128*0fca6ea1SDimitry Andric void SampleProfileLoader::removePseudoProbeInsts(Module &M) {
2129*0fca6ea1SDimitry Andric   for (auto &F : M) {
2130*0fca6ea1SDimitry Andric     std::vector<Instruction *> InstsToDel;
21315f757f3fSDimitry Andric     for (auto &BB : F) {
21325f757f3fSDimitry Andric       for (auto &I : BB) {
2133*0fca6ea1SDimitry Andric         if (isa<PseudoProbeInst>(&I))
2134*0fca6ea1SDimitry Andric           InstsToDel.push_back(&I);
21355f757f3fSDimitry Andric       }
21365f757f3fSDimitry Andric     }
2137*0fca6ea1SDimitry Andric     for (auto *I : InstsToDel)
2138*0fca6ea1SDimitry Andric       I->eraseFromParent();
213906c3fb27SDimitry Andric   }
214006c3fb27SDimitry Andric }
214106c3fb27SDimitry Andric 
21420b57cec5SDimitry Andric bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
2143*0fca6ea1SDimitry Andric                                       ProfileSummaryInfo *_PSI) {
21445ffd83dbSDimitry Andric   GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric   PSI = _PSI;
21475ffd83dbSDimitry Andric   if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
21480b57cec5SDimitry Andric     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
21490b57cec5SDimitry Andric                         ProfileSummary::PSK_Sample);
21505ffd83dbSDimitry Andric     PSI->refresh();
21515ffd83dbSDimitry Andric   }
2152*0fca6ea1SDimitry Andric 
2153*0fca6ea1SDimitry Andric   if (FunctionSamples::ProfileIsProbeBased &&
2154*0fca6ea1SDimitry Andric       rejectHighStalenessProfile(M, PSI, Reader->getProfiles()))
2155*0fca6ea1SDimitry Andric     return false;
2156*0fca6ea1SDimitry Andric 
21570b57cec5SDimitry Andric   // Compute the total number of samples collected in this profile.
21580b57cec5SDimitry Andric   for (const auto &I : Reader->getProfiles())
21590b57cec5SDimitry Andric     TotalCollectedSamples += I.second.getTotalSamples();
21600b57cec5SDimitry Andric 
2161e8d8bef9SDimitry Andric   auto Remapper = Reader->getRemapper();
21620b57cec5SDimitry Andric   // Populate the symbol map.
21630b57cec5SDimitry Andric   for (const auto &N_F : M.getValueSymbolTable()) {
21640b57cec5SDimitry Andric     StringRef OrigName = N_F.getKey();
21650b57cec5SDimitry Andric     Function *F = dyn_cast<Function>(N_F.getValue());
2166fe6060f1SDimitry Andric     if (F == nullptr || OrigName.empty())
21670b57cec5SDimitry Andric       continue;
21685f757f3fSDimitry Andric     SymbolMap[FunctionId(OrigName)] = F;
2169fe6060f1SDimitry Andric     StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
2170fe6060f1SDimitry Andric     if (OrigName != NewName && !NewName.empty()) {
21715f757f3fSDimitry Andric       auto r = SymbolMap.emplace(FunctionId(NewName), F);
21720b57cec5SDimitry Andric       // Failiing to insert means there is already an entry in SymbolMap,
21730b57cec5SDimitry Andric       // thus there are multiple functions that are mapped to the same
21740b57cec5SDimitry Andric       // stripped name. In this case of name conflicting, set the value
21750b57cec5SDimitry Andric       // to nullptr to avoid confusion.
21760b57cec5SDimitry Andric       if (!r.second)
21770b57cec5SDimitry Andric         r.first->second = nullptr;
2178e8d8bef9SDimitry Andric       OrigName = NewName;
2179e8d8bef9SDimitry Andric     }
2180e8d8bef9SDimitry Andric     // Insert the remapped names into SymbolMap.
2181e8d8bef9SDimitry Andric     if (Remapper) {
2182e8d8bef9SDimitry Andric       if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
2183fe6060f1SDimitry Andric         if (*MapName != OrigName && !MapName->empty())
21845f757f3fSDimitry Andric           SymbolMap.emplace(FunctionId(*MapName), F);
2185e8d8bef9SDimitry Andric       }
21860b57cec5SDimitry Andric     }
21870b57cec5SDimitry Andric   }
21880b57cec5SDimitry Andric 
2189*0fca6ea1SDimitry Andric   // Stale profile matching.
219006c3fb27SDimitry Andric   if (ReportProfileStaleness || PersistProfileStaleness ||
219106c3fb27SDimitry Andric       SalvageStaleProfile) {
219206c3fb27SDimitry Andric     MatchingManager->runOnModule();
2193*0fca6ea1SDimitry Andric     MatchingManager->clearMatchingData();
219406c3fb27SDimitry Andric   }
2195*0fca6ea1SDimitry Andric   assert(SymbolMap.count(FunctionId()) == 0 &&
2196*0fca6ea1SDimitry Andric          "No empty StringRef should be added in SymbolMap");
2197*0fca6ea1SDimitry Andric   assert((SalvageUnusedProfile || FuncNameToProfNameMap.empty()) &&
2198*0fca6ea1SDimitry Andric          "FuncNameToProfNameMap is not empty when --salvage-unused-profile is "
2199*0fca6ea1SDimitry Andric          "not enabled");
2200bdd1243dSDimitry Andric 
22010b57cec5SDimitry Andric   bool retval = false;
2202bdd1243dSDimitry Andric   for (auto *F : buildFunctionOrder(M, CG)) {
2203480093f4SDimitry Andric     assert(!F->isDeclaration());
22040b57cec5SDimitry Andric     clearFunctionData();
2205480093f4SDimitry Andric     retval |= runOnFunction(*F, AM);
22060b57cec5SDimitry Andric   }
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric   // Account for cold calls not inlined....
220981ad6265SDimitry Andric   if (!FunctionSamples::ProfileIsCS)
22100b57cec5SDimitry Andric     for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
22110b57cec5SDimitry Andric          notInlinedCallInfo)
22120b57cec5SDimitry Andric       updateProfileCallee(pair.first, pair.second.entryCount);
22130b57cec5SDimitry Andric 
2214*0fca6ea1SDimitry Andric   if (RemoveProbeAfterProfileAnnotation && FunctionSamples::ProfileIsProbeBased)
2215*0fca6ea1SDimitry Andric     removePseudoProbeInsts(M);
2216*0fca6ea1SDimitry Andric 
22170b57cec5SDimitry Andric   return retval;
22180b57cec5SDimitry Andric }
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
2221d409305fSDimitry Andric   LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
22220b57cec5SDimitry Andric   DILocation2SampleMap.clear();
22230b57cec5SDimitry Andric   // By default the entry count is initialized to -1, which will be treated
22240b57cec5SDimitry Andric   // conservatively by getEntryCount as the same as unknown (None). This is
22250b57cec5SDimitry Andric   // to avoid newly added code to be treated as cold. If we have samples
22260b57cec5SDimitry Andric   // this will be overwritten in emitAnnotations.
22278bcb0991SDimitry Andric   uint64_t initialEntryCount = -1;
22288bcb0991SDimitry Andric 
22298bcb0991SDimitry Andric   ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
22308bcb0991SDimitry Andric   if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
22318bcb0991SDimitry Andric     // initialize all the function entry counts to 0. It means all the
22328bcb0991SDimitry Andric     // functions without profile will be regarded as cold.
22338bcb0991SDimitry Andric     initialEntryCount = 0;
22348bcb0991SDimitry Andric     // profile-sample-accurate is a user assertion which has a higher precedence
22358bcb0991SDimitry Andric     // than symbol list. When profile-sample-accurate is on, ignore symbol list.
22368bcb0991SDimitry Andric     ProfAccForSymsInList = false;
22378bcb0991SDimitry Andric   }
2238fe6060f1SDimitry Andric   CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
22398bcb0991SDimitry Andric 
22408bcb0991SDimitry Andric   // PSL -- profile symbol list include all the symbols in sampled binary.
22418bcb0991SDimitry Andric   // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
22428bcb0991SDimitry Andric   // old functions without samples being cold, without having to worry
22438bcb0991SDimitry Andric   // about new and hot functions being mistakenly treated as cold.
22448bcb0991SDimitry Andric   if (ProfAccForSymsInList) {
22458bcb0991SDimitry Andric     // Initialize the entry count to 0 for functions in the list.
22468bcb0991SDimitry Andric     if (PSL->contains(F.getName()))
22478bcb0991SDimitry Andric       initialEntryCount = 0;
22488bcb0991SDimitry Andric 
22498bcb0991SDimitry Andric     // Function in the symbol list but without sample will be regarded as
22508bcb0991SDimitry Andric     // cold. To minimize the potential negative performance impact it could
22518bcb0991SDimitry Andric     // have, we want to be a little conservative here saying if a function
22528bcb0991SDimitry Andric     // shows up in the profile, no matter as outline function, inline instance
22538bcb0991SDimitry Andric     // or call targets, treat the function as not being cold. This will handle
22548bcb0991SDimitry Andric     // the cases such as most callsites of a function are inlined in sampled
22558bcb0991SDimitry Andric     // binary but not inlined in current build (because of source code drift,
22568bcb0991SDimitry Andric     // imprecise debug information, or the callsites are all cold individually
22578bcb0991SDimitry Andric     // but not cold accumulatively...), so the outline function showing up as
22588bcb0991SDimitry Andric     // cold in sampled binary will actually not be cold after current build.
22598bcb0991SDimitry Andric     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
22605f757f3fSDimitry Andric     if ((FunctionSamples::UseMD5 &&
22615f757f3fSDimitry Andric          GUIDsInProfile.count(Function::getGUID(CanonName))) ||
22625f757f3fSDimitry Andric         (!FunctionSamples::UseMD5 && NamesInProfile.count(CanonName)))
22638bcb0991SDimitry Andric       initialEntryCount = -1;
22648bcb0991SDimitry Andric   }
22658bcb0991SDimitry Andric 
2266e8d8bef9SDimitry Andric   // Initialize entry count when the function has no existing entry
2267e8d8bef9SDimitry Andric   // count value.
226881ad6265SDimitry Andric   if (!F.getEntryCount())
22690b57cec5SDimitry Andric     F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
22700b57cec5SDimitry Andric   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
22710b57cec5SDimitry Andric   if (AM) {
22720b57cec5SDimitry Andric     auto &FAM =
22730b57cec5SDimitry Andric         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
22740b57cec5SDimitry Andric             .getManager();
22750b57cec5SDimitry Andric     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
22760b57cec5SDimitry Andric   } else {
22778bcb0991SDimitry Andric     OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
22780b57cec5SDimitry Andric     ORE = OwnedORE.get();
22790b57cec5SDimitry Andric   }
2280e8d8bef9SDimitry Andric 
228181ad6265SDimitry Andric   if (FunctionSamples::ProfileIsCS)
2282e8d8bef9SDimitry Andric     Samples = ContextTracker->getBaseSamplesFor(F);
22835f757f3fSDimitry Andric   else {
22840b57cec5SDimitry Andric     Samples = Reader->getSamplesFor(F);
22855f757f3fSDimitry Andric     // Try search in previously inlined functions that were split or duplicated
22865f757f3fSDimitry Andric     // into base.
22875f757f3fSDimitry Andric     if (!Samples) {
22885f757f3fSDimitry Andric       StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
22895f757f3fSDimitry Andric       auto It = OutlineFunctionSamples.find(FunctionId(CanonName));
22905f757f3fSDimitry Andric       if (It != OutlineFunctionSamples.end()) {
22915f757f3fSDimitry Andric         Samples = &It->second;
22925f757f3fSDimitry Andric       } else if (auto Remapper = Reader->getRemapper()) {
22935f757f3fSDimitry Andric         if (auto RemppedName = Remapper->lookUpNameInProfile(CanonName)) {
22945f757f3fSDimitry Andric           It = OutlineFunctionSamples.find(FunctionId(*RemppedName));
22955f757f3fSDimitry Andric           if (It != OutlineFunctionSamples.end())
22965f757f3fSDimitry Andric             Samples = &It->second;
22975f757f3fSDimitry Andric         }
22985f757f3fSDimitry Andric       }
22995f757f3fSDimitry Andric     }
23005f757f3fSDimitry Andric   }
2301e8d8bef9SDimitry Andric 
23020b57cec5SDimitry Andric   if (Samples && !Samples->empty())
23030b57cec5SDimitry Andric     return emitAnnotations(F);
23040b57cec5SDimitry Andric   return false;
23050b57cec5SDimitry Andric }
230606c3fb27SDimitry Andric SampleProfileLoaderPass::SampleProfileLoaderPass(
230706c3fb27SDimitry Andric     std::string File, std::string RemappingFile, ThinOrFullLTOPhase LTOPhase,
230806c3fb27SDimitry Andric     IntrusiveRefCntPtr<vfs::FileSystem> FS)
230906c3fb27SDimitry Andric     : ProfileFileName(File), ProfileRemappingFileName(RemappingFile),
231006c3fb27SDimitry Andric       LTOPhase(LTOPhase), FS(std::move(FS)) {}
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
23130b57cec5SDimitry Andric                                                ModuleAnalysisManager &AM) {
23140b57cec5SDimitry Andric   FunctionAnalysisManager &FAM =
23150b57cec5SDimitry Andric       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
23160b57cec5SDimitry Andric 
23170b57cec5SDimitry Andric   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
23180b57cec5SDimitry Andric     return FAM.getResult<AssumptionAnalysis>(F);
23190b57cec5SDimitry Andric   };
23200b57cec5SDimitry Andric   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
23210b57cec5SDimitry Andric     return FAM.getResult<TargetIRAnalysis>(F);
23220b57cec5SDimitry Andric   };
23235ffd83dbSDimitry Andric   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
23245ffd83dbSDimitry Andric     return FAM.getResult<TargetLibraryAnalysis>(F);
23255ffd83dbSDimitry Andric   };
23260b57cec5SDimitry Andric 
232706c3fb27SDimitry Andric   if (!FS)
232806c3fb27SDimitry Andric     FS = vfs::getRealFileSystem();
2329*0fca6ea1SDimitry Andric   LazyCallGraph &CG = AM.getResult<LazyCallGraphAnalysis>(M);
233006c3fb27SDimitry Andric 
23310b57cec5SDimitry Andric   SampleProfileLoader SampleLoader(
23320b57cec5SDimitry Andric       ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
23330b57cec5SDimitry Andric       ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
23340b57cec5SDimitry Andric                                        : ProfileRemappingFileName,
2335*0fca6ea1SDimitry Andric       LTOPhase, FS, GetAssumptionCache, GetTTI, GetTLI, CG);
2336e8d8bef9SDimitry Andric   if (!SampleLoader.doInitialization(M, &FAM))
2337480093f4SDimitry Andric     return PreservedAnalyses::all();
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
2340*0fca6ea1SDimitry Andric   if (!SampleLoader.runOnModule(M, &AM, PSI))
23410b57cec5SDimitry Andric     return PreservedAnalyses::all();
23420b57cec5SDimitry Andric 
23430b57cec5SDimitry Andric   return PreservedAnalyses::none();
23440b57cec5SDimitry Andric }
2345