100 using namespace llvm;
102 #define DEBUG_TYPE "loop-idiom" 104 STATISTIC(NumMemSet,
"Number of memset's formed from loop stores");
105 STATISTIC(NumMemCpy,
"Number of memcpy's formed from loop load+stores");
108 "use-lir-code-size-heurs",
109 cl::desc(
"Use loop idiom recognition code size heuristics when compiling" 115 class LoopIdiomRecognize {
116 Loop *CurLoop =
nullptr;
125 bool ApplyCodeSizeHeuristics;
134 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) {}
136 bool runOnLoop(
Loop *L);
142 StoreListMap StoreRefsForMemset;
143 StoreListMap StoreRefsForMemsetPattern;
144 StoreList StoreRefsForMemcpy;
146 bool HasMemsetPattern;
150 enum LegalStoreKind {
155 UnorderedAtomicMemcpy,
163 bool runOnCountableLoop();
169 enum class ForMemset {
No,
Yes };
174 bool processLoopStridedStore(
Value *DestPtr,
unsigned StoreSize,
179 bool NegStride,
bool IsLoopMemset =
false);
181 bool avoidLIRForMultiBlockLoop(
bool IsMemset =
false,
182 bool IsLoopMemset =
false);
188 bool runOnNoncountableLoop();
190 bool recognizePopcount();
193 bool recognizeAndInsertFFS();
198 bool IsCntPhiUsedOutsideLoop);
203 class LoopIdiomRecognizeLegacyPass :
public LoopPass {
207 explicit LoopIdiomRecognizeLegacyPass() :
LoopPass(ID) {
216 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
217 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
218 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
219 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
221 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
224 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
233 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL, ORE);
234 return LIR.runOnLoop(L);
257 Function *
F = L.getHeader()->getParent();
263 "LoopIdiomRecognizePass: OptimizationRemarkEmitterAnalysis not cached " 264 "at a higher level");
266 LoopIdiomRecognize LIR(&AR.
AA, &AR.
DT, &AR.
LI, &AR.
SE, &AR.
TLI, &AR.
TTI, DL,
268 if (!LIR.runOnLoop(&L))
275 "Recognize loop idioms",
false,
false)
295 bool LoopIdiomRecognize::runOnLoop(
Loop *L) {
304 if (Name ==
"memset" || Name ==
"memcpy")
308 ApplyCodeSizeHeuristics =
311 HasMemset = TLI->
has(LibFunc_memset);
312 HasMemsetPattern = TLI->
has(LibFunc_memset_pattern16);
313 HasMemcpy = TLI->
has(LibFunc_memcpy);
315 if (HasMemset || HasMemsetPattern || HasMemcpy)
317 return runOnCountableLoop();
319 return runOnNoncountableLoop();
322 bool LoopIdiomRecognize::runOnCountableLoop() {
324 assert(!isa<SCEVCouldNotCompute>(BECount) &&
325 "runOnCountableLoop() called on a loop without a predictable" 326 "backedge-taken count");
330 if (
const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
331 if (BECst->getAPInt() == 0)
335 CurLoop->getUniqueExitBlocks(ExitBlocks);
338 << CurLoop->getHeader()->getParent()->getName()
339 <<
"] Countable Loop %" << CurLoop->getHeader()->getName()
342 bool MadeChange =
false;
352 for (
auto *BB : CurLoop->getBlocks()) {
357 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
386 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
406 unsigned ArraySize = 16 /
Size;
411 LoopIdiomRecognize::LegalStoreKind
433 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->
getType());
434 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
446 if (!isa<SCEVConstant>(StoreEv->
getOperand(1)))
463 if (!UnorderedAtomic && HasMemset && SplatValue &&
466 CurLoop->isLoopInvariant(SplatValue)) {
468 return LegalStoreKind::Memset;
469 }
else if (!UnorderedAtomic && HasMemsetPattern &&
474 return LegalStoreKind::MemsetPattern;
483 if (StoreSize != Stride && StoreSize != -Stride)
509 UnorderedAtomic = UnorderedAtomic || LI->
isAtomic();
510 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
511 : LegalStoreKind::Memcpy;
517 void LoopIdiomRecognize::collectStores(
BasicBlock *BB) {
518 StoreRefsForMemset.clear();
519 StoreRefsForMemsetPattern.clear();
520 StoreRefsForMemcpy.clear();
527 switch (isLegalStore(SI)) {
531 case LegalStoreKind::Memset: {
534 StoreRefsForMemset[Ptr].push_back(SI);
536 case LegalStoreKind::MemsetPattern: {
539 StoreRefsForMemsetPattern[Ptr].push_back(SI);
541 case LegalStoreKind::Memcpy:
542 case LegalStoreKind::UnorderedAtomicMemcpy:
543 StoreRefsForMemcpy.push_back(SI);
546 assert(
false &&
"unhandled return value");
555 bool LoopIdiomRecognize::runOnLoopBlock(
561 for (
unsigned i = 0,
e = ExitBlocks.
size(); i !=
e; ++i)
565 bool MadeChange =
false;
572 for (
auto &SL : StoreRefsForMemset)
573 MadeChange |= processLoopStores(SL.second, BECount,
ForMemset::Yes);
575 for (
auto &SL : StoreRefsForMemsetPattern)
576 MadeChange |= processLoopStores(SL.second, BECount,
ForMemset::No);
579 for (
auto &SI : StoreRefsForMemcpy)
580 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
585 if (
MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
587 if (!processLoopMemSet(MSI, BECount))
604 const SCEV *BECount, ForMemset For) {
612 for (
unsigned i = 0,
e = SL.
size(); i <
e; ++i) {
613 assert(SL[i]->
isSimple() &&
"Expected only non-volatile stores.");
615 Value *FirstStoredVal = SL[i]->getValueOperand();
616 Value *FirstStorePtr = SL[i]->getPointerOperand();
618 cast<SCEVAddRecExpr>(SE->
getSCEV(FirstStorePtr));
620 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->
getType());
623 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
628 Value *FirstSplatValue =
nullptr;
629 Constant *FirstPatternValue =
nullptr;
636 assert((FirstSplatValue || FirstPatternValue) &&
637 "Expected either splat value or pattern value.");
645 for (j = i + 1; j <
e; ++j)
647 for (j = i; j > 0; --j)
650 for (
auto &k : IndexQueue) {
651 assert(SL[k]->
isSimple() &&
"Expected only non-volatile stores.");
652 Value *SecondStorePtr = SL[k]->getPointerOperand();
654 cast<SCEVAddRecExpr>(SE->
getSCEV(SecondStorePtr));
657 if (FirstStride != SecondStride)
660 Value *SecondStoredVal = SL[k]->getValueOperand();
661 Value *SecondSplatValue =
nullptr;
662 Constant *SecondPatternValue =
nullptr;
669 assert((SecondSplatValue || SecondPatternValue) &&
670 "Expected either splat value or pattern value.");
674 if (isa<UndefValue>(FirstSplatValue))
675 FirstSplatValue = SecondSplatValue;
676 if (FirstSplatValue != SecondSplatValue)
679 if (isa<UndefValue>(FirstPatternValue))
680 FirstPatternValue = SecondPatternValue;
681 if (FirstPatternValue != SecondPatternValue)
686 ConsecutiveChain[SL[i]] = SL[k];
695 bool Changed =
false;
700 if (Tails.
count(*it))
709 unsigned StoreSize = 0;
713 if (TransformedStores.
count(I))
719 I = ConsecutiveChain[
I];
729 if (StoreSize != Stride && StoreSize != -Stride)
732 bool NegStride = StoreSize == -Stride;
734 if (processLoopStridedStore(StorePtr, StoreSize,
736 StoredVal, HeadStore, AdjacentStores, StoreEv,
737 BECount, NegStride)) {
738 TransformedStores.
insert(AdjacentStores.
begin(), AdjacentStores.
end());
747 bool LoopIdiomRecognize::processLoopMemSet(
MemSetInst *MSI,
748 const SCEV *BECount) {
767 uint64_t SizeInBytes = cast<ConstantInt>(MSI->
getLength())->getZExtValue();
768 if ((SizeInBytes >> 32) != 0)
778 if (SizeInBytes != Stride && SizeInBytes != -Stride)
784 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
789 bool NegStride = SizeInBytes == -Stride;
790 return processLoopStridedStore(
792 SplatValue, MSI, MSIs, Ev, BECount, NegStride,
true);
800 const SCEV *BECount,
unsigned StoreSize,
810 if (
const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
823 if (IgnoredStores.
count(&
I) == 0 &&
835 Type *IntPtr,
unsigned StoreSize,
849 unsigned StoreSize,
Loop *CurLoop,
851 const SCEV *NumBytesS;
872 if (StoreSize != 1) {
881 bool LoopIdiomRecognize::processLoopStridedStore(
885 const SCEV *BECount,
bool NegStride,
bool IsLoopMemset) {
892 assert((SplatValue || PatternValue) &&
893 "Expected either splat value or pattern value.");
899 BasicBlock *Preheader = CurLoop->getLoopPreheader();
904 Type *IntIdxTy = DL->getIndexType(DestPtr->
getType());
922 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->
getTerminator());
924 StoreSize, *AA, Stores)) {
931 if (avoidLIRForMultiBlockLoop(
true, IsLoopMemset))
936 const SCEV *NumBytesS =
937 getNumBytes(BECount, IntIdxTy, StoreSize, CurLoop, DL, SE);
945 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->
getTerminator());
949 NewCall = Builder.CreateMemSet(BasePtr, SplatValue, NumBytes,
953 Type *Int8PtrTy = DestInt8PtrTy;
958 Int8PtrTy, Int8PtrTy, IntIdxTy);
965 PatternValue,
".memset_pattern");
969 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
973 <<
" from store to: " << *Ev <<
" at: " << *TheStore
980 <<
"Transformed loop-strided store into a call to " 987 for (
auto *
I : Stores)
996 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
StoreInst *SI,
997 const SCEV *BECount) {
1004 bool NegStride = StoreSize == -Stride;
1019 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1025 Type *IntIdxTy = Builder.
getIntNTy(DL->getIndexSizeInBits(StrAS));
1037 Value *StoreBasePtr = Expander.expandCodeFor(
1038 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->
getTerminator());
1043 StoreSize, *AA, Stores)) {
1050 const SCEV *LdStart = LoadEv->getStart();
1059 Value *LoadBasePtr = Expander.expandCodeFor(
1060 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->
getTerminator());
1063 StoreSize, *AA, Stores)) {
1071 if (avoidLIRForMultiBlockLoop())
1076 const SCEV *NumBytesS =
1077 getNumBytes(BECount, IntIdxTy, StoreSize, CurLoop, DL, SE);
1080 Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->
getTerminator());
1087 NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->
getAlign(), LoadBasePtr,
1093 if (Align < StoreSize)
1100 if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1106 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1108 NumBytes, StoreSize);
1113 <<
" from load ptr=" << *LoadEv <<
" at: " << *LI <<
"\n" 1114 <<
" from store ptr=" << *StoreEv <<
" at: " << *SI
1120 <<
"Formed a call to " 1135 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(
bool IsMemset,
1136 bool IsLoopMemset) {
1137 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1138 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
1139 LLVM_DEBUG(
dbgs() <<
" " << CurLoop->getHeader()->getParent()->getName()
1140 <<
" : LIR " << (IsMemset ?
"Memset" :
"Memcpy")
1141 <<
" avoided: multi-block top-level loop\n");
1149 bool LoopIdiomRecognize::runOnNoncountableLoop() {
1151 << CurLoop->getHeader()->getParent()->getName()
1152 <<
"] Noncountable Loop %" 1153 << CurLoop->getHeader()->getName() <<
"\n");
1155 return recognizePopcount() || recognizeAndInsertFFS();
1165 bool JmpOnZero =
false) {
1174 if (!CmpZero || !CmpZero->
isZero())
1195 if (PhiX && PhiX->getParent() == LoopEntry &&
1196 (PhiX->getOperand(0) == DefX || PhiX->
getOperand(1) == DefX))
1232 Value *VarX1, *VarX0;
1235 DefX2 = CountInst =
nullptr;
1236 VarX1 = VarX0 =
nullptr;
1237 PhiX = CountPhi =
nullptr;
1243 dyn_cast<BranchInst>(LoopEntry->
getTerminator()), LoopEntry))
1244 DefX2 = dyn_cast<Instruction>(
T);
1251 if (!DefX2 || DefX2->
getOpcode() != Instruction::And)
1256 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->
getOperand(0))))
1262 if (!SubOneOp || SubOneOp->
getOperand(0) != VarX1)
1281 CountInst =
nullptr;
1283 IterE = LoopEntry->
end();
1284 Iter != IterE; Iter++) {
1290 if (!Inc || !Inc->
isOne())
1298 bool LiveOutLoop =
false;
1300 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1325 CntInst = CountInst;
1365 Value *VarX =
nullptr;
1374 dyn_cast<BranchInst>(LoopEntry->
getTerminator()), LoopEntry))
1375 DefX = dyn_cast<Instruction>(
T);
1380 if (!DefX || !DefX->
isShift())
1382 IntrinID = DefX->
getOpcode() == Instruction::Shl ? Intrinsic::cttz :
1385 if (!Shft || !Shft->
isOne())
1408 IterE = LoopEntry->
end();
1409 Iter != IterE; Iter++) {
1415 if (!Inc || !Inc->
isOne())
1435 bool LoopIdiomRecognize::recognizeAndInsertFFS() {
1437 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1447 size_t IdiomCanonicalSize = 6;
1450 CntInst, CntPhi, DefX))
1453 bool IsCntPhiUsedOutsideLoop =
false;
1455 if (!CurLoop->contains(cast<Instruction>(U))) {
1456 IsCntPhiUsedOutsideLoop =
true;
1459 bool IsCntInstUsedOutsideLoop =
false;
1461 if (!CurLoop->contains(cast<Instruction>(U))) {
1462 IsCntInstUsedOutsideLoop =
true;
1467 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1473 bool ZeroCheck =
false;
1476 BasicBlock *PH = CurLoop->getLoopPreheader();
1482 if (!IsCntPhiUsedOutsideLoop) {
1510 auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug();
1512 std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());
1514 if (HeaderSize != IdiomCanonicalSize &&
1515 TTI->getIntrinsicCost(IntrinID, InitX->
getType(),
Args) >
1519 transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
1521 IsCntPhiUsedOutsideLoop);
1529 bool LoopIdiomRecognize::recognizePopcount() {
1539 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1542 BasicBlock *LoopBody = *(CurLoop->block_begin());
1543 if (LoopBody->
size() >= 20) {
1549 BasicBlock *PH = CurLoop->getLoopPreheader();
1553 if (!EntryBI || EntryBI->isConditional())
1562 if (!PreCondBI || PreCondBI->isUnconditional())
1571 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1577 Value *Ops[] = {Val};
1589 const DebugLoc &DL,
bool ZeroCheck,
1633 void LoopIdiomRecognize::transformLoopToCountable(
1636 bool ZeroCheck,
bool IsCntPhiUsedOutsideLoop) {
1641 Builder.SetCurrentDebugLocation(DL);
1642 Value *FFS, *Count, *CountPrev, *NewCount, *InitXNext;
1647 if (IsCntPhiUsedOutsideLoop) {
1648 if (DefX->
getOpcode() == Instruction::AShr)
1651 else if (DefX->
getOpcode() == Instruction::LShr)
1654 else if (DefX->
getOpcode() == Instruction::Shl)
1662 Count = Builder.CreateSub(
1666 if (IsCntPhiUsedOutsideLoop) {
1668 Count = Builder.CreateAdd(
1673 NewCount = Builder.CreateZExtOrTrunc(
1674 IsCntPhiUsedOutsideLoop ? CountPrev : Count,
1675 cast<IntegerType>(CntInst->
getType()));
1680 if (!InitConst || !InitConst->
isZero())
1681 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1691 BasicBlock *Body = *(CurLoop->block_begin());
1693 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1694 Type *Ty = Count->getType();
1698 Builder.SetInsertPoint(LbCond);
1701 "tcdec",
false,
true));
1708 LbCond->setPredicate(Pred);
1709 LbCond->setOperand(0, TcDec);
1714 if (IsCntPhiUsedOutsideLoop)
1724 void LoopIdiomRecognize::transformLoopToPopcount(
BasicBlock *PreCondBB,
1727 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1728 auto *PreCondBr = cast<BranchInst>(PreCondBB->
getTerminator());
1737 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1740 NewCount = PopCntZext =
1743 if (NewCount != PopCnt)
1744 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1752 if (!InitConst || !InitConst->
isZero()) {
1753 NewCount = Builder.
CreateAdd(NewCount, CntInitVal);
1754 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1763 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1765 Value *Opnd0 = PopCntZext;
1770 ICmpInst *NewPreCond = cast<ICmpInst>(
1772 PreCondBr->setCondition(NewPreCond);
1797 BasicBlock *Body = *(CurLoop->block_begin());
1800 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1808 "tcdec",
false,
true));
1815 LbCond->setPredicate(Pred);
1816 LbCond->setOperand(0, TcDec);
The access may reference and may modify the value stored in memory.
virtual void computeLoopSafetyInfo(const Loop *CurLoop)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Pass interface - Implemented by all 'passes'.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static CallInst * createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL)
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
const SCEV * getConstant(ConstantInt *V)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
BinaryOps getOpcode() const
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
ArrayRef< BasicBlock *>::const_iterator block_iterator
A Module instance is used to store all the information related to an LLVM module. ...
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static constexpr LocationSize unknown()
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
void push_back(const T &Elt)
The main scalar evolution driver.
This class represents a function call, abstracting a target machine's calling convention.
static PHINode * getRecurrenceVar(Value *VarX, Instruction *DefX, BasicBlock *LoopEntry)
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Like Internal, but omit from symbol table.
LLVMContext & getContext() const
All values hold a context through their type.
static LocationSize precise(uint64_t Value)
This class wraps the llvm.memset intrinsic.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
static Value * matchCondition(BranchInst *BI, BasicBlock *LoopEntry, bool JmpOnZero=false)
Check if the given conditional branch is based on the comparison between a variable and zero...
Value * getCondition() const
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Value * getLength() const
iterator end()
Get an iterator to the end of the SetVector.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
iterator begin()
Instruction iterator methods.
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
MaybeAlign getAlign() const
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
const Loop * getLoop() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This file contains the simple types necessary to represent the attributes associated with functions a...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
unsigned getDestAlignment() const
FIXME: Remove this function once transition to Align is over.
This file implements a class to represent arbitrary precision integral constant values and operations...
const APInt & getAPInt() const
BlockT * getHeader() const
static bool isSimple(Instruction *I)
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
This node represents a polynomial recurrence on the trip count of the specified loop.
static APInt getStoreStride(const SCEVAddRecExpr *StoreEv)
BasicBlock * GetInsertBlock() const
Class to represent array types.
static cl::opt< bool > UseLIRCodeSizeHeurs("use-lir-code-size-heurs", cl::desc("Use loop idiom recognition code size heuristics when compiling" "with -Os/-Oz"), cl::init(true), cl::Hidden)
bool has(LibFunc F) const
Tests whether a library function is available.
iterator begin()
Get an iterator to the beginning of the SetVector.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void initializeLoopIdiomRecognizeLegacyPassPass(PassRegistry &)
An instruction for storing to memory.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the give value is known to be non-negative.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static void deleteDeadInstruction(Instruction *I)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
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...
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS. ...
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
bool inferLibFuncAttributes(Function &F, const TargetLibraryInfo &TLI)
Analyze the name and prototype of the given function and set any applicable attributes.
initializer< Ty > init(const Ty &Val)
const SCEV * getOperand(unsigned i) const
MaybeAlign getAlign() const
Return the alignment of the access that is being performed.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
A set of analyses that are preserved following a run of a transformation pass.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
ConstantInt * getTrue()
Get the constant value for i1 true.
Conditional or Unconditional Branch instruction.
static CallInst * createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL, bool ZeroCheck, Intrinsic::ID IID)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL, Intrinsic::ID &IntrinID, Value *&InitX, Instruction *&CntInst, PHINode *&CntPhi, Instruction *&DefX)
Return true if the idiom is detected in the loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
Value * getPointerOperand()
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
const SCEV * getStart() const
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
Used in the streaming interface as the general argument type.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static wasm::ValType getType(const TargetRegisterClass *RC)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
const SCEV * getMulExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This struct is a compact representation of a valid (non-zero power of two) alignment.
TargetTransformInfo & TTI
Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
Representation for a specific memory location.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
typename vector_type::const_iterator iterator
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
Type * getType() const
Return the LLVM type of this SCEV expression.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
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.
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
static Constant * getMemSetPatternValue(Value *V, const DataLayout *DL)
getMemSetPatternValue - If a strided store of the specified value is safe to turn into a memset_patte...
static const SCEV * getNumBytes(const SCEV *BECount, Type *IntPtr, unsigned StoreSize, Loop *CurLoop, const DataLayout *DL, ScalarEvolution *SE)
Compute the number of bytes as a SCEV from the backedge taken count.
static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, Instruction *&CntInst, PHINode *&CntPhi, Value *&Var)
Return true iff the idiom is detected in the loop.
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
The access may modify the value stored in memory.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
loop Recognize loop idioms
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
iterator_range< user_iterator > users()
This class uses information about analyze scalars to rewrite expressions in canonical form...
Pass * createLoopIdiomPass()
ConstantInt * getFalse()
Get the constant value for i1 false.
const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
Predicate getPredicate() const
Return the predicate for this instruction.
bool isVolatile() const
Return true if this is a store to a volatile memory location.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void setAlignment(MaybeAlign Align)
INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom", "Recognize loop idioms", false, false) INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
void setUnnamedAddr(UnnamedAddr Val)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
This class represents an analyzed expression in the program.
unsigned getIntegerBitWidth() const
Represents a single loop in the control flow graph.
This file provides utility analysis objects describing memory locations.
StringRef getName() const
Return a constant reference to the value's name.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_NODISCARD ModRefInfo intersectModRef(const ModRefInfo MRI1, const ModRefInfo MRI2)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
block_iterator block_end() const
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
unsigned getAlignment() const
Return the alignment of the access that is being performed FIXME: Remove this function once transitio...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
static const SCEV * getStartForNegStride(const SCEV *Start, const SCEV *BECount, Type *IntPtr, unsigned StoreSize, ScalarEvolution *SE)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
A vector that has set insertion semantics.
static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, const SCEV *BECount, unsigned StoreSize, AliasAnalysis &AA, SmallPtrSetImpl< Instruction *> &IgnoredStores)
mayLoopAccessLocation - Return true if the specified loop might access the specified pointer location...
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
LLVM_NODISCARD bool isModOrRefSet(const ModRefInfo MRI)
This header defines various interfaces for pass management in LLVM.
ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
virtual bool anyBlockMayThrow() const
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
block_iterator block_begin() const
bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count...
Value * getPointerOperand()
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
This class represents a constant integer value.