27 #define DEBUG_TYPE "expandmemcmp" 29 STATISTIC(NumMemCmpCalls,
"Number of memcmp calls");
30 STATISTIC(NumMemCmpNotConstant,
"Number of memcmp calls without constant size");
32 "Number of memcmp calls with size greater than max size");
33 STATISTIC(NumMemCmpInlined,
"Number of inlined memcmp calls");
37 cl::desc(
"The number of loads per basic block for inline expansion of " 38 "memcmp that is only being compared against zero."));
45 class MemCmpExpansion {
51 ResultBlock() =
default;
58 uint64_t NumLoadsNonOneByte;
59 const uint64_t NumLoadsPerBlockForZeroCmp;
60 std::vector<BasicBlock *> LoadCmpBlocks;
63 const bool IsUsedForZeroCmp;
73 LoadEntry(
unsigned LoadSize, uint64_t
Offset)
74 : LoadSize(LoadSize), Offset(Offset) {
75 assert(Offset % LoadSize == 0 &&
"invalid load entry");
78 uint64_t getGEPIndex()
const {
return Offset / LoadSize; }
81 const unsigned LoadSize;
87 void createLoadCmpBlocks();
88 void createResultBlock();
89 void setupResultBlockPHINodes();
90 void setupEndBlockPHINodes();
91 Value *getCompareLoadPairs(
unsigned BlockIndex,
unsigned &LoadIndex);
92 void emitLoadCompareBlock(
unsigned BlockIndex);
93 void emitLoadCompareBlockMultipleLoads(
unsigned BlockIndex,
95 void emitLoadCompareByteBlock(
unsigned BlockIndex,
unsigned GEPIndex);
96 void emitMemCmpResultBlock();
97 Value *getMemCmpExpansionZeroCase();
98 Value *getMemCmpEqZeroOneBlock();
99 Value *getMemCmpOneBlock();
102 MemCmpExpansion(
CallInst *CI, uint64_t Size,
104 unsigned MaxNumLoads,
const bool IsUsedForZeroCmp,
105 unsigned MaxLoadsPerBlockForZeroCmp,
const DataLayout &TheDataLayout);
107 unsigned getNumBlocks();
108 uint64_t getNumLoads()
const {
return LoadSequence.
size(); }
110 Value *getMemCmpExpansion();
121 MemCmpExpansion::MemCmpExpansion(
124 const unsigned MaxNumLoads,
const bool IsUsedForZeroCmp,
125 const unsigned MaxLoadsPerBlockForZeroCmp,
const DataLayout &TheDataLayout)
129 NumLoadsNonOneByte(0),
130 NumLoadsPerBlockForZeroCmp(MaxLoadsPerBlockForZeroCmp),
131 IsUsedForZeroCmp(IsUsedForZeroCmp),
134 assert(Size > 0 &&
"zero blocks");
136 size_t LoadSizeIndex = 0;
141 this->MaxLoadSize = Options.
LoadSizes[LoadSizeIndex];
143 uint64_t CurSize =
Size;
145 while (CurSize && LoadSizeIndex < Options.
LoadSizes.
size()) {
146 const unsigned LoadSize = Options.
LoadSizes[LoadSizeIndex];
147 assert(LoadSize > 0 &&
"zero load size");
148 const uint64_t NumLoadsForThisSize = CurSize / LoadSize;
149 if (LoadSequence.
size() + NumLoadsForThisSize > MaxNumLoads) {
154 LoadSequence.
clear();
157 if (NumLoadsForThisSize > 0) {
158 for (uint64_t
I = 0;
I < NumLoadsForThisSize; ++
I) {
159 LoadSequence.
push_back({LoadSize, Offset});
163 ++NumLoadsNonOneByte;
165 CurSize = CurSize % LoadSize;
169 assert(LoadSequence.
size() <= MaxNumLoads &&
"broken invariant");
172 unsigned MemCmpExpansion::getNumBlocks() {
173 if (IsUsedForZeroCmp)
174 return getNumLoads() / NumLoadsPerBlockForZeroCmp +
175 (getNumLoads() % NumLoadsPerBlockForZeroCmp != 0 ? 1 : 0);
176 return getNumLoads();
179 void MemCmpExpansion::createLoadCmpBlocks() {
180 for (
unsigned i = 0; i < getNumBlocks(); i++) {
183 LoadCmpBlocks.push_back(BB);
187 void MemCmpExpansion::createResultBlock() {
188 ResBlock.BB = BasicBlock::Create(CI->
getContext(),
"res_block",
196 void MemCmpExpansion::emitLoadCompareByteBlock(
unsigned BlockIndex,
204 if (Source1->
getType() != LoadSizeType)
206 if (Source2->
getType() != LoadSizeType)
211 Source1 = Builder.
CreateGEP(LoadSizeType, Source1,
212 ConstantInt::get(LoadSizeType, GEPIndex));
213 Source2 = Builder.
CreateGEP(LoadSizeType, Source2,
214 ConstantInt::get(LoadSizeType, GEPIndex));
224 PhiRes->
addIncoming(Diff, LoadCmpBlocks[BlockIndex]);
226 if (BlockIndex < (LoadCmpBlocks.size() - 1)) {
230 ConstantInt::get(Diff->
getType(), 0));
232 BranchInst::Create(EndBlock, LoadCmpBlocks[BlockIndex + 1], Cmp);
236 BranchInst *CmpBr = BranchInst::Create(EndBlock);
244 Value *MemCmpExpansion::getCompareLoadPairs(
unsigned BlockIndex,
245 unsigned &LoadIndex) {
246 assert(LoadIndex < getNumLoads() &&
247 "getCompareLoadPairs() called with no remaining loads");
248 std::vector<Value *> XorList, OrList;
251 const unsigned NumLoads =
252 std::min(getNumLoads() - LoadIndex, NumLoadsPerBlockForZeroCmp);
255 if (LoadCmpBlocks.empty())
260 Value *Cmp =
nullptr;
265 NumLoads == 1 ? nullptr
266 : IntegerType::get(CI->
getContext(), MaxLoadSize * 8);
267 for (
unsigned i = 0; i < NumLoads; ++i, ++LoadIndex) {
268 const LoadEntry &CurLoadEntry = LoadSequence[LoadIndex];
271 IntegerType::get(CI->
getContext(), CurLoadEntry.LoadSize * 8);
277 if (Source1->getType() != LoadSizeType)
279 if (Source2->
getType() != LoadSizeType)
283 if (CurLoadEntry.Offset != 0) {
285 LoadSizeType, Source1,
286 ConstantInt::get(LoadSizeType, CurLoadEntry.getGEPIndex()));
288 LoadSizeType, Source2,
289 ConstantInt::get(LoadSizeType, CurLoadEntry.getGEPIndex()));
293 Value *LoadSrc1 =
nullptr;
294 if (
auto *Source1C = dyn_cast<Constant>(Source1))
297 LoadSrc1 = Builder.
CreateLoad(LoadSizeType, Source1);
299 Value *LoadSrc2 =
nullptr;
300 if (
auto *Source2C = dyn_cast<Constant>(Source2))
303 LoadSrc2 = Builder.
CreateLoad(LoadSizeType, Source2);
306 if (LoadSizeType != MaxLoadType) {
307 LoadSrc1 = Builder.
CreateZExt(LoadSrc1, MaxLoadType);
308 LoadSrc2 = Builder.
CreateZExt(LoadSrc2, MaxLoadType);
312 Diff = Builder.
CreateXor(LoadSrc1, LoadSrc2);
314 XorList.push_back(Diff);
321 auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
322 std::vector<Value *> OutList;
323 for (
unsigned i = 0; i < InList.size() - 1; i = i + 2) {
325 OutList.push_back(Or);
327 if (InList.size() % 2 != 0)
328 OutList.push_back(InList.back());
334 OrList = pairWiseOr(XorList);
337 while (OrList.size() != 1) {
338 OrList = pairWiseOr(OrList);
346 void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(
unsigned BlockIndex,
347 unsigned &LoadIndex) {
348 Value *Cmp = getCompareLoadPairs(BlockIndex, LoadIndex);
350 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
352 : LoadCmpBlocks[BlockIndex + 1];
355 BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
361 if (BlockIndex == LoadCmpBlocks.size() - 1) {
363 PhiRes->
addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
376 void MemCmpExpansion::emitLoadCompareBlock(
unsigned BlockIndex) {
378 const LoadEntry &CurLoadEntry = LoadSequence[BlockIndex];
380 if (CurLoadEntry.LoadSize == 1) {
381 MemCmpExpansion::emitLoadCompareByteBlock(BlockIndex,
382 CurLoadEntry.getGEPIndex());
387 IntegerType::get(CI->
getContext(), CurLoadEntry.LoadSize * 8);
388 Type *MaxLoadType = IntegerType::get(CI->
getContext(), MaxLoadSize * 8);
389 assert(CurLoadEntry.LoadSize <= MaxLoadSize &&
"Unexpected load type");
396 if (Source1->
getType() != LoadSizeType)
398 if (Source2->
getType() != LoadSizeType)
402 if (CurLoadEntry.Offset != 0) {
404 LoadSizeType, Source1,
405 ConstantInt::get(LoadSizeType, CurLoadEntry.getGEPIndex()));
407 LoadSizeType, Source2,
408 ConstantInt::get(LoadSizeType, CurLoadEntry.getGEPIndex()));
417 Intrinsic::bswap, LoadSizeType);
418 LoadSrc1 = Builder.
CreateCall(Bswap, LoadSrc1);
419 LoadSrc2 = Builder.
CreateCall(Bswap, LoadSrc2);
422 if (LoadSizeType != MaxLoadType) {
423 LoadSrc1 = Builder.
CreateZExt(LoadSrc1, MaxLoadType);
424 LoadSrc2 = Builder.
CreateZExt(LoadSrc2, MaxLoadType);
429 if (!IsUsedForZeroCmp) {
430 ResBlock.PhiSrc1->addIncoming(LoadSrc1, LoadCmpBlocks[BlockIndex]);
431 ResBlock.PhiSrc2->addIncoming(LoadSrc2, LoadCmpBlocks[BlockIndex]);
434 Value *Cmp = Builder.
CreateICmp(ICmpInst::ICMP_EQ, LoadSrc1, LoadSrc2);
435 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
437 : LoadCmpBlocks[BlockIndex + 1];
440 BranchInst *CmpBr = BranchInst::Create(NextBB, ResBlock.BB, Cmp);
446 if (BlockIndex == LoadCmpBlocks.size() - 1) {
448 PhiRes->
addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
455 void MemCmpExpansion::emitMemCmpResultBlock() {
458 if (IsUsedForZeroCmp) {
463 BranchInst *NewBr = BranchInst::Create(EndBlock);
477 BranchInst *NewBr = BranchInst::Create(EndBlock);
482 void MemCmpExpansion::setupResultBlockPHINodes() {
483 Type *MaxLoadType = IntegerType::get(CI->
getContext(), MaxLoadSize * 8);
487 Builder.
CreatePHI(MaxLoadType, NumLoadsNonOneByte,
"phi.src1");
489 Builder.
CreatePHI(MaxLoadType, NumLoadsNonOneByte,
"phi.src2");
492 void MemCmpExpansion::setupEndBlockPHINodes() {
497 Value *MemCmpExpansion::getMemCmpExpansionZeroCase() {
498 unsigned LoadIndex = 0;
501 for (
unsigned I = 0;
I < getNumBlocks(); ++
I) {
502 emitLoadCompareBlockMultipleLoads(
I, LoadIndex);
505 emitMemCmpResultBlock();
512 Value *MemCmpExpansion::getMemCmpEqZeroOneBlock() {
513 unsigned LoadIndex = 0;
514 Value *Cmp = getCompareLoadPairs(0, LoadIndex);
515 assert(LoadIndex == getNumLoads() &&
"some entries were not consumed");
521 Value *MemCmpExpansion::getMemCmpOneBlock() {
522 Type *LoadSizeType = IntegerType::get(CI->
getContext(), Size * 8);
527 if (Source1->getType() != LoadSizeType)
529 if (Source2->
getType() != LoadSizeType)
538 Intrinsic::bswap, LoadSizeType);
539 LoadSrc1 = Builder.
CreateCall(Bswap, LoadSrc1);
540 LoadSrc2 = Builder.
CreateCall(Bswap, LoadSrc2);
548 return Builder.
CreateSub(LoadSrc1, LoadSrc2);
561 return Builder.
CreateSub(ZextUGT, ZextULT);
566 Value *MemCmpExpansion::getMemCmpExpansion() {
568 if (getNumBlocks() != 1) {
571 setupEndBlockPHINodes();
578 if (!IsUsedForZeroCmp) setupResultBlockPHINodes();
581 createLoadCmpBlocks();
590 if (IsUsedForZeroCmp)
591 return getNumBlocks() == 1 ? getMemCmpEqZeroOneBlock()
592 : getMemCmpExpansionZeroCase();
594 if (getNumBlocks() == 1)
595 return getMemCmpOneBlock();
597 for (
unsigned I = 0;
I < getNumBlocks(); ++
I) {
598 emitLoadCompareBlock(
I);
601 emitMemCmpResultBlock();
689 NumMemCmpNotConstant++;
702 if (!Options)
return false;
704 const unsigned MaxNumLoads =
711 MemCmpExpansion Expansion(CI, SizeVal, *Options, MaxNumLoads,
712 IsUsedForZeroCmp, NumLoadsPerBlock, *DL);
715 if (Expansion.getNumLoads() == 0) {
716 NumMemCmpGreaterThanMax++;
722 Value *Res = Expansion.getMemCmpExpansion();
744 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
749 TPC->getTM<
TargetMachine>().getSubtargetImpl(F)->getTargetLowering();
752 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
754 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
755 auto PA =
runImpl(F, TLI, TTI, TL);
756 return !PA.areAllPreserved();
775 bool ExpandMemCmpPass::runOnBlock(
786 Func == LibFunc_memcmp && expandMemCmp(CI, TTI, TL, &DL)) {
798 bool MadeChanges =
false;
799 for (
auto BBIt = F.
begin(); BBIt != F.
end();) {
800 if (runOnBlock(*BBIt, TLI, TTI, TL, DL)) {
816 "Expand memcmp() to load/stores",
false,
false)
823 return new ExpandMemCmpPass();
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Compute iterated dominance frontiers using a linear time algorithm.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
INITIALIZE_PASS_BEGIN(ExpandMemCmpPass, "expandmemcmp", "Expand memcmp() to load/stores", false, false) INITIALIZE_PASS_END(ExpandMemCmpPass
This class represents a function call, abstracting a target machine's calling convention.
FunctionPass * createExpandMemCmpPass()
LLVMContext & getContext() const
All values hold a context through their type.
STATISTIC(NumFunctions, "Total number of functions")
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void initializeExpandMemCmpPassPass(PassRegistry &)
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Type * getType() const
All values are typed, get the type of this value.
Value * CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name="")
Predicate all(Predicate P0, Predicate P1)
True iff P0 and P1 are true.
bool isLittleEndian() const
Layout endianness...
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of converting the string to 'bool' fo...
initializer< Ty > init(const Ty &Val)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
A set of analyses that are preserved following a run of a transformation pass.
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
const Instruction & front() const
Represent the analysis usage information of a pass.
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
FunctionPass class - This class is used to implement most global optimizations.
Class to represent integer types.
Expand memcmp() to load/stores"
const Function * getFunction() const
Return the function this instruction belongs to.
Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, const DataLayout &DL)
ConstantFoldLoadFromConstPtr - Return the value that a load from C would produce if it is constant an...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
static cl::opt< unsigned > MemCmpEqZeroNumLoadsPerBlock("memcmp-num-loads-per-block", cl::Hidden, cl::init(1), cl::desc("The number of loads per basic block for inline expansion of " "memcmp that is only being compared against zero."))
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Provides information about what library functions are available for the current target.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
unsigned getMaxExpandSizeMemcmp(bool OptSize) const
Get maximum # of load operations permitted for memcmp.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Establish a view to a call site for examination.
const Function * getParent() const
Return the enclosing method, or null if none.
bool optForMinSize() const
Optimize this function for minimum size (-Oz).
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
virtual unsigned getMemcmpEqZeroLoadsPerBlock() const
For memcmp expansion when the memcmp result is only compared equal or not-equal to 0...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
Primary interface to the complete machine description for the target machine.
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
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 file describes how to lower LLVM code to machine code.
const BasicBlock * getParent() const
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)