38#define INSTR_PROF_VALUE_PROF_MEMOP_API
52#define DEBUG_TYPE "pgo-memop-opt"
54STATISTIC(NumOfPGOMemOPOpt,
"Number of memop intrinsics optimized.");
55STATISTIC(NumOfPGOMemOPAnnotate,
"Number of memop intrinsics annotated.");
64 switch (
MI->getIntrinsicID()) {
65 case Intrinsic::memcpy:
67 case Intrinsic::memmove:
69 case Intrinsic::memset:
79 MemOp(MemIntrinsic *
MI) : I(
MI) {}
80 MemOp(CallInst *CI) : I(CI) {}
90 return MI->getLength();
91 return asCI()->getArgOperand(2);
96 asCI()->setArgOperand(2,
Length);
98 StringRef getFuncName() {
100 return MI->getCalledFunction()->getName();
101 return asCI()->getCalledFunction()->getName();
104 if (
auto MI = asMI())
105 if (
MI->getIntrinsicID() == Intrinsic::memmove)
109 bool isMemcmp(TargetLibraryInfo &TLI) {
110 return asMI() ==
nullptr && TLI.
getLibFunc(*asCI()) == LibFunc_memcmp;
112 bool isBcmp(TargetLibraryInfo &TLI) {
113 return asMI() ==
nullptr && TLI.
getLibFunc(*asCI()) == LibFunc_bcmp;
115 const char *
getName(TargetLibraryInfo &TLI) {
116 if (
auto MI = asMI())
117 return getMIName(
MI);
119 if (Func == LibFunc_memcmp)
121 if (Func == LibFunc_bcmp)
128class MemOPSizeOpt :
public InstVisitor<MemOPSizeOpt> {
130 MemOPSizeOpt(
const InstrumentationOptions &Opts,
Function &Func,
131 BlockFrequencyInfo &BFI, OptimizationRemarkEmitter &ORE,
132 DominatorTree *DT, TargetLibraryInfo &TLI)
133 : Opts(Opts), Func(Func), BFI(BFI), ORE(ORE), DT(DT), TLI(TLI),
135 bool isChanged()
const {
return Changed; }
140 for (
auto &MO : WorkList) {
141 ++NumOfPGOMemOPAnnotate;
146 <<
"is Transformed.\n");
151 void visitMemIntrinsic(MemIntrinsic &
MI) {
156 WorkList.push_back(MemOp(&
MI));
159 void visitCallInst(CallInst &CI) {
160 LibFunc Func = TLI.getLibFunc(CI);
161 if ((Func == LibFunc_memcmp || Func == LibFunc_bcmp) &&
163 WorkList.push_back(MemOp(&CI));
168 const InstrumentationOptions &Opts;
170 BlockFrequencyInfo &BFI;
171 OptimizationRemarkEmitter &ORE;
173 TargetLibraryInfo &TLI;
175 std::vector<MemOp> WorkList;
176 bool perform(MemOp MO);
182 if (
Count < Opts.pgo_memop_count_threshold)
184 if (
Count < TotalCount * Opts.pgo_memop_percent_threshold / 100)
189static inline uint64_t getScaledCount(
const InstrumentationOptions &Opts,
192 if (!Opts.pgo_memop_scale_count)
196 return ScaleCount / Denom;
199bool MemOPSizeOpt::perform(
MemOp MO) {
203 if (!Opts.pgo_memop_optimize_memcmp_bcmp &&
204 (MO.isMemcmp(TLI) || MO.isBcmp(TLI)))
207 uint32_t MaxNumVals = INSTR_PROF_NUM_BUCKETS;
215 uint64_t SavedTotalCount = TotalCount;
216 if (Opts.pgo_memop_scale_count) {
220 ActualCount = *BBEdgeCount;
223 LLVM_DEBUG(
dbgs() <<
"Read one memory intrinsic profile with count "
224 << ActualCount <<
"\n");
227 : VDs) {
dbgs() <<
" (" << VD.Value <<
"," << VD.Count <<
")\n"; });
229 if (ActualCount < Opts.pgo_memop_count_threshold)
236 TotalCount = ActualCount;
237 if (Opts.pgo_memop_scale_count)
239 <<
" denominator = " << SavedTotalCount <<
"\n");
243 uint64_t SavedRemainCount = SavedTotalCount;
244 SmallVector<uint64_t, 16> SizeIds;
245 SmallVector<uint64_t, 16> CaseCounts;
251 for (
auto I = VDs.begin(),
E = VDs.end();
I !=
E; ++
I) {
253 int64_t
V = VD.Value;
255 if (Opts.pgo_memop_scale_count)
256 C = getScaledCount(Opts,
C, ActualCount, SavedTotalCount);
258 if (!InstrProfIsSingleValRange(V) ||
259 V > Opts.memop_value_prof_max_opt_size) {
278 assert(SavedRemainCount >= VD.Count);
279 SavedRemainCount -= VD.Count;
281 if (++
Version >= Opts.pgo_memop_max_version &&
282 Opts.pgo_memop_max_version != 0) {
291 CaseCounts[0] = RemainCount;
292 if (RemainCount > MaxCount)
293 MaxCount = RemainCount;
295 uint64_t SumForOpt = TotalCount - RemainCount;
298 <<
" Versions (covering " << SumForOpt <<
" out of "
299 << TotalCount <<
")\n");
327 MergeBB->
setName(
"MemOP.Merge");
329 DefaultBB->
setName(
"MemOP.Default");
331 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
332 auto &Ctx =
Func.getContext();
335 Value *SizeVar = MO.getLength();
336 SwitchInst *
SI = IRB.CreateSwitch(SizeVar, DefaultBB, SizeIds.
size());
337 Type *MemOpTy = MO.I->getType();
338 PHINode *
PHI =
nullptr;
342 PHI = IRBM.CreatePHI(MemOpTy, SizeIds.
size() + 1,
"MemOP.RVMerge");
343 MO.I->replaceAllUsesWith(
PHI);
344 PHI->addIncoming(MO.I, DefaultBB);
348 MO.I->setMetadata(LLVMContext::MD_prof,
nullptr);
350 if (SavedRemainCount > 0 ||
Version != VDs.size()) {
353 IPVK_MemOPSize, VDs.
size());
358 std::vector<DominatorTree::UpdateType> Updates;
360 Updates.reserve(2 * SizeIds.
size());
364 Ctx, Twine(
"MemOP.Case.") + Twine(SizeId), &Func, DefaultBB);
365 MemOp NewMO = MO.clone();
368 assert(SizeType &&
"Expected integer type size argument.");
369 ConstantInt *CaseSizeId = ConstantInt::get(SizeType, SizeId);
370 NewMO.setLength(CaseSizeId);
371 NewMO.I->insertInto(CaseBB, CaseBB->
end());
373 IRBCase.CreateBr(MergeBB);
374 SI->addCase(CaseSizeId, CaseBB);
376 PHI->addIncoming(NewMO.I, CaseBB);
378 Updates.push_back({DominatorTree::Insert, CaseBB, MergeBB});
379 Updates.push_back({DominatorTree::Insert, BB, CaseBB});
383 DTU.applyUpdates(Updates);
395 return OptimizationRemark(
DEBUG_TYPE,
"memopt-opt", MO.I)
396 <<
"optimized " <<
NV(
"Memop", MO.getName(TLI)) <<
" with count "
397 <<
NV(
"Count", SumForOpt) <<
" out of " <<
NV(
"Total", TotalCount)
398 <<
" for " <<
NV(
"Versions",
Version) <<
" versions";
409 if (Opts.disable_memop_opt)
414 MemOPSizeOpt MemOPSizeOpt(Opts,
F, BFI, ORE, DT, TLI);
415 MemOPSizeOpt.perform();
416 return MemOPSizeOpt.isChanged();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis false
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This header defines various interfaces for pass management in LLVM.
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
static bool pgoMemOPSizeOptImpl(const InstrumentationOptions &Opts, Function &F, BlockFrequencyInfo &BFI, OptimizationRemarkEmitter &ORE, DominatorTree *DT, TargetLibraryInfo &TLI)
FunctionAnalysisManager FAM
static StringRef getName(Value *V)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
static bool isProfitable(const StableFunctionMap::StableFunctionEntries &SFS)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Value * getArgOperand(unsigned i) const
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Base class for instruction visitors.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
This is the common base class for memset/memcpy/memmove.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &MAM)
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
bool isVoidTy() const
Return true if this is 'void'.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void setProfMetadata(Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.