55 #define DEBUG_TYPE "pgo-memop-opt"
57 STATISTIC(NumOfPGOMemOPOpt,
"Number of memop intrinsics optimized.");
58 STATISTIC(NumOfPGOMemOPAnnotate,
"Number of memop intrinsics annotated.");
64 cl::desc(
"The minimum count to optimize memory "
76 cl::desc(
"The percentage threshold for the "
77 "memory intrinsic calls optimization"));
83 cl::desc(
"The max version for the optimized memory "
89 cl::desc(
"Scale the memop size counts using the basic "
90 " block count value"));
107 StringRef getPassName()
const override {
return "PGOMemOPSize"; }
110 bool runOnFunction(
Function &
F)
override;
120 "Optimize memory intrinsic using its size value profile",
124 "Optimize memory intrinsic using its size value
profile",
128 return new PGOMemOPSizeOptLegacyPass();
132 class MemOPSizeOpt :
public InstVisitor<MemOPSizeOpt> {
135 : Func(Func), BFI(BFI), Changed(
false) {
142 bool isChanged()
const {
return Changed; }
147 for (
auto &
MI : WorkList) {
148 ++NumOfPGOMemOPAnnotate;
152 DEBUG(
dbgs() <<
"MemOP call: " <<
MI->getCalledFunction()->getName()
153 <<
"is Transformed.\n");
161 if (dyn_cast<ConstantInt>(Length))
163 WorkList.push_back(&MI);
170 std::vector<MemIntrinsic *> WorkList;
172 int64_t PreciseRangeStart;
174 int64_t PreciseRangeLast;
176 std::unique_ptr<InstrProfValueData[]> ValueDataArray;
182 enum MemOPSizeKind { PreciseValue, NonLargeGroup, LargeGroup };
184 MemOPSizeKind getMemOPSizeKind(int64_t
Value)
const {
187 if (Value == PreciseRangeLast + 1)
188 return NonLargeGroup;
195 case Intrinsic::memcpy:
197 case Intrinsic::memmove:
199 case Intrinsic::memset:
206 static bool isProfitable(uint64_t Count, uint64_t TotalCount) {
207 assert(Count <= TotalCount);
215 static inline uint64_t getScaledCount(uint64_t Count, uint64_t Num,
221 return ScaleCount / Denom;
232 ValueDataArray.get(), NumVals, TotalCount))
235 uint64_t ActualCount = TotalCount;
236 uint64_t SavedTotalCount = TotalCount;
238 auto BBEdgeCount =
BFI.getBlockProfileCount(MI->
getParent());
241 ActualCount = *BBEdgeCount;
245 DEBUG(
dbgs() <<
"Read one memory intrinsic profile with count " << ActualCount
249 : VDs) {
dbgs() <<
" (" << VD.Value <<
"," << VD.Count <<
")\n"; });
258 TotalCount = ActualCount;
260 DEBUG(
dbgs() <<
"Scale counts: numerator = " << ActualCount
261 <<
" denominator = " << SavedTotalCount <<
"\n");
264 uint64_t RemainCount = TotalCount;
265 uint64_t SavedRemainCount = SavedTotalCount;
268 uint64_t MaxCount = 0;
272 for (
auto &VD : VDs) {
273 int64_t V = VD.Value;
274 uint64_t
C = VD.Count;
276 C = getScaledCount(C, ActualCount, SavedTotalCount);
279 if (getMemOPSizeKind(V) != PreciseValue)
284 if (!isProfitable(C, RemainCount))
294 assert(SavedRemainCount >= VD.Count);
295 SavedRemainCount -= VD.Count;
304 CaseCounts[0] = RemainCount;
305 if (RemainCount > MaxCount)
306 MaxCount = RemainCount;
308 uint64_t SumForOpt = TotalCount - RemainCount;
310 DEBUG(
dbgs() <<
"Optimize one memory intrinsic call to " << Version
311 <<
" Versions (covering " << SumForOpt <<
" out of "
312 << TotalCount <<
")\n");
331 DEBUG(
dbgs() <<
"\n\n== Basic Block Before ==\n");
333 auto OrigBBFreq =
BFI.getBlockFreq(BB);
340 MergeBB->setName(
"MemOP.Merge");
341 BFI.setBlockFreq(MergeBB, OrigBBFreq.getFrequency());
342 DefaultBB->
setName(
"MemOP.Default");
344 auto &Ctx = Func.getContext();
353 if (SavedRemainCount > 0 || Version != NumVals)
356 SavedRemainCount, IPVK_MemOPSize, NumVals);
358 DEBUG(
dbgs() <<
"\n\n== Basic Block After==\n");
360 for (uint64_t SizeId : SizeIds) {
363 Ctx,
Twine(
"MemOP.Case.") +
Twine(SizeId), &Func, DefaultBB);
369 IRBCase.CreateBr(MergeBB);
370 SI->
addCase(CaseSizeId, CaseBB);
381 Twine(
"optimize ") + getMIName(MI) +
" with count " +
382 Twine(SumForOpt) +
" out of " +
Twine(TotalCount) +
383 " for " +
Twine(Version) +
" versions");
395 MemOPSizeOpt MemOPSizeOpt(F, BFI);
396 MemOPSizeOpt.perform();
397 return MemOPSizeOpt.isChanged();
400 bool PGOMemOPSizeOptLegacyPass::runOnFunction(
Function &
F) {
402 getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
Legacy wrapper pass to provide the GlobalsAAResult object.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
void setProfMetadata(Module *M, Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Base class for instruction visitors.
STATISTIC(NumFunctions,"Total number of functions")
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
This is the interface for a simple mod/ref and alias analysis over globals.
FunctionPass * createPGOMemOPSizeOptLegacyPass()
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
cl::opt< unsigned > MemOPSizeLarge
static cl::opt< unsigned > MemOPMaxVersion("pgo-memop-max-version", cl::init(3), cl::Hidden, cl::ZeroOrMore, cl::desc("The max version for the optimized memory "" intrinsic calls"))
static IntegerType * getInt64Ty(LLVMContext &C)
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Legacy analysis pass which computes BlockFrequencyInfo.
void setName(const Twine &Name)
Change the name of the value.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
This file provides the interface for IR based instrumentation passes ( (profile-gen, and profile-use).
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart, int64_t &RangeLast)
Function Alias Analysis false
void emitOptimizationRemark(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization-applied message.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
bool getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, InstrProfValueData ValueData[], uint32_t &ActualNumValueData, uint64_t &TotalC)
Extract the value profile data from Inst which is annotated with value profile meta data...
INITIALIZE_PASS_BEGIN(PGOMemOPSizeOptLegacyPass,"pgo-memop-opt","Optimize memory intrinsic using its size value profile", false, false) INITIALIZE_PASS_END(PGOMemOPSizeOptLegacyPass
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
const InstListType & getInstList() const
Return the underlying instruction list container.
Analysis pass providing a never-invalidated alias analysis result.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static cl::opt< bool > MemOPScaleCount("pgo-memop-scale-count", cl::init(true), cl::Hidden, cl::desc("Scale the memop size counts using the basic "" block count value"))
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...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Analysis pass which computes BlockFrequencyInfo.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
static cl::opt< unsigned > MemOPPercentThreshold("pgo-memop-percent-threshold", cl::init(40), cl::Hidden, cl::ZeroOrMore, cl::desc("The percentage threshold for the ""memory intrinsic calls optimization"))
Value * getLength() const
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static cl::opt< bool > DisableMemOPOPT("disable-memop-opt", cl::init(false), cl::Hidden, cl::desc("Disable optimize"))
void push_back(pointer val)
pgo instr Read PGO instrumentation profile
static bool PGOMemOPSizeOptImpl(Function &F, BlockFrequencyInfo &BFI)
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
static cl::opt< unsigned > MemOPCountThreshold("pgo-memop-count-threshold", cl::Hidden, cl::ZeroOrMore, cl::init(1000), cl::desc("The minimum count to optimize memory ""intrinsic calls"))
cl::opt< std::string > MemOPSizeRange
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void initializePGOMemOPSizeOptLegacyPassPass(PassRegistry &)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This header defines various interfaces for pass management in LLVM.
const BasicBlock * getParent() const