LLVM  5.0.0
LoopIdiomRecognize.cpp
Go to the documentation of this file.
1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements an idiom recognizer that transforms simple loops into a
11 // non-loop form. In cases that this kicks in, it can be a significant
12 // performance win.
13 //
14 // If compiling for code size we avoid idiom recognition if the resulting
15 // code could be larger than the code for the original loop. One way this could
16 // happen is if the loop is not removable after idiom recognition due to the
17 // presence of non-idiom instructions. The initial implementation of the
18 // heuristics applies to idioms in multi-block loops.
19 //
20 //===----------------------------------------------------------------------===//
21 //
22 // TODO List:
23 //
24 // Future loop memory idioms to recognize:
25 // memcmp, memmove, strlen, etc.
26 // Future floating point idioms to recognize in -ffast-math mode:
27 // fpowi
28 // Future integer operation idioms to recognize:
29 // ctpop, ctlz, cttz
30 //
31 // Beware that isel's default lowering for ctpop is highly inefficient for
32 // i64 and larger types when i64 is legal and the value has few bits set. It
33 // would be good to enhance isel to emit a loop for ctpop in this case.
34 //
35 // This could recognize common matrix multiplies and dot product idioms and
36 // replace them with calls to BLAS (if linked in??).
37 //
38 //===----------------------------------------------------------------------===//
39 
41 #include "llvm/ADT/MapVector.h"
42 #include "llvm/ADT/SetVector.h"
43 #include "llvm/ADT/Statistic.h"
48 #include "llvm/Analysis/LoopPass.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/Support/Debug.h"
62 #include "llvm/Transforms/Scalar.h"
67 using namespace llvm;
68 
69 #define DEBUG_TYPE "loop-idiom"
70 
71 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
72 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
73 
75  "use-lir-code-size-heurs",
76  cl::desc("Use loop idiom recognition code size heuristics when compiling"
77  "with -Os/-Oz"),
78  cl::init(true), cl::Hidden);
79 
80 namespace {
81 
82 class LoopIdiomRecognize {
83  Loop *CurLoop;
84  AliasAnalysis *AA;
85  DominatorTree *DT;
86  LoopInfo *LI;
87  ScalarEvolution *SE;
88  TargetLibraryInfo *TLI;
89  const TargetTransformInfo *TTI;
90  const DataLayout *DL;
91  bool ApplyCodeSizeHeuristics;
92 
93 public:
94  explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
95  LoopInfo *LI, ScalarEvolution *SE,
96  TargetLibraryInfo *TLI,
97  const TargetTransformInfo *TTI,
98  const DataLayout *DL)
99  : CurLoop(nullptr), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI),
100  DL(DL) {}
101 
102  bool runOnLoop(Loop *L);
103 
104 private:
105  typedef SmallVector<StoreInst *, 8> StoreList;
106  typedef MapVector<Value *, StoreList> StoreListMap;
107  StoreListMap StoreRefsForMemset;
108  StoreListMap StoreRefsForMemsetPattern;
109  StoreList StoreRefsForMemcpy;
110  bool HasMemset;
111  bool HasMemsetPattern;
112  bool HasMemcpy;
113  /// Return code for isLegalStore()
114  enum LegalStoreKind {
115  None = 0,
116  Memset,
117  MemsetPattern,
118  Memcpy,
119  UnorderedAtomicMemcpy,
120  DontUse // Dummy retval never to be used. Allows catching errors in retval
121  // handling.
122  };
123 
124  /// \name Countable Loop Idiom Handling
125  /// @{
126 
127  bool runOnCountableLoop();
128  bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
129  SmallVectorImpl<BasicBlock *> &ExitBlocks);
130 
131  void collectStores(BasicBlock *BB);
132  LegalStoreKind isLegalStore(StoreInst *SI);
133  bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
134  bool ForMemset);
135  bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
136 
137  bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
138  unsigned StoreAlignment, Value *StoredVal,
139  Instruction *TheStore,
141  const SCEVAddRecExpr *Ev, const SCEV *BECount,
142  bool NegStride, bool IsLoopMemset = false);
143  bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
144  bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
145  bool IsLoopMemset = false);
146 
147  /// @}
148  /// \name Noncountable Loop Idiom Handling
149  /// @{
150 
151  bool runOnNoncountableLoop();
152 
153  bool recognizePopcount();
154  void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
155  PHINode *CntPhi, Value *Var);
156  bool recognizeAndInsertCTLZ();
157  void transformLoopToCountable(BasicBlock *PreCondBB, Instruction *CntInst,
158  PHINode *CntPhi, Value *Var, const DebugLoc DL,
159  bool ZeroCheck, bool IsCntPhiUsedOutsideLoop);
160 
161  /// @}
162 };
163 
164 class LoopIdiomRecognizeLegacyPass : public LoopPass {
165 public:
166  static char ID;
167  explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
170  }
171 
172  bool runOnLoop(Loop *L, LPPassManager &LPM) override {
173  if (skipLoop(L))
174  return false;
175 
176  AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
177  DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
178  LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
179  ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
180  TargetLibraryInfo *TLI =
181  &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
182  const TargetTransformInfo *TTI =
183  &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
184  *L->getHeader()->getParent());
185  const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
186 
187  LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
188  return LIR.runOnLoop(L);
189  }
190 
191  /// This transformation requires natural loop information & requires that
192  /// loop preheaders be inserted into the CFG.
193  ///
194  void getAnalysisUsage(AnalysisUsage &AU) const override {
198  }
199 };
200 } // End anonymous namespace.
201 
204  LPMUpdater &) {
205  const auto *DL = &L.getHeader()->getModule()->getDataLayout();
206 
207  LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, DL);
208  if (!LIR.runOnLoop(&L))
209  return PreservedAnalyses::all();
210 
212 }
213 
215 INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
216  "Recognize loop idioms", false, false)
220 INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
221  "Recognize loop idioms", false, false)
222 
223 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
224 
227  I->eraseFromParent();
228 }
229 
230 //===----------------------------------------------------------------------===//
231 //
232 // Implementation of LoopIdiomRecognize
233 //
234 //===----------------------------------------------------------------------===//
235 
236 bool LoopIdiomRecognize::runOnLoop(Loop *L) {
237  CurLoop = L;
238  // If the loop could not be converted to canonical form, it must have an
239  // indirectbr in it, just give up.
240  if (!L->getLoopPreheader())
241  return false;
242 
243  // Disable loop idiom recognition if the function's name is a common idiom.
244  StringRef Name = L->getHeader()->getParent()->getName();
245  if (Name == "memset" || Name == "memcpy")
246  return false;
247 
248  // Determine if code size heuristics need to be applied.
249  ApplyCodeSizeHeuristics =
250  L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs;
251 
252  HasMemset = TLI->has(LibFunc_memset);
253  HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
254  HasMemcpy = TLI->has(LibFunc_memcpy);
255 
256  if (HasMemset || HasMemsetPattern || HasMemcpy)
258  return runOnCountableLoop();
259 
260  return runOnNoncountableLoop();
261 }
262 
263 bool LoopIdiomRecognize::runOnCountableLoop() {
264  const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
265  assert(!isa<SCEVCouldNotCompute>(BECount) &&
266  "runOnCountableLoop() called on a loop without a predictable"
267  "backedge-taken count");
268 
269  // If this loop executes exactly one time, then it should be peeled, not
270  // optimized by this pass.
271  if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
272  if (BECst->getAPInt() == 0)
273  return false;
274 
275  SmallVector<BasicBlock *, 8> ExitBlocks;
276  CurLoop->getUniqueExitBlocks(ExitBlocks);
277 
278  DEBUG(dbgs() << "loop-idiom Scanning: F["
279  << CurLoop->getHeader()->getParent()->getName() << "] Loop %"
280  << CurLoop->getHeader()->getName() << "\n");
281 
282  bool MadeChange = false;
283 
284  // The following transforms hoist stores/memsets into the loop pre-header.
285  // Give up if the loop has instructions may throw.
286  LoopSafetyInfo SafetyInfo;
287  computeLoopSafetyInfo(&SafetyInfo, CurLoop);
288  if (SafetyInfo.MayThrow)
289  return MadeChange;
290 
291  // Scan all the blocks in the loop that are not in subloops.
292  for (auto *BB : CurLoop->getBlocks()) {
293  // Ignore blocks in subloops.
294  if (LI->getLoopFor(BB) != CurLoop)
295  continue;
296 
297  MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
298  }
299  return MadeChange;
300 }
301 
302 static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL) {
303  uint64_t SizeInBits = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
304  assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
305  "Don't overflow unsigned.");
306  return (unsigned)SizeInBits >> 3;
307 }
308 
309 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
310  const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
311  return ConstStride->getAPInt();
312 }
313 
314 /// getMemSetPatternValue - If a strided store of the specified value is safe to
315 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
316 /// be passed in. Otherwise, return null.
317 ///
318 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
319 /// just replicate their input array and then pass on to memset_pattern16.
321  // If the value isn't a constant, we can't promote it to being in a constant
322  // array. We could theoretically do a store to an alloca or something, but
323  // that doesn't seem worthwhile.
324  Constant *C = dyn_cast<Constant>(V);
325  if (!C)
326  return nullptr;
327 
328  // Only handle simple values that are a power of two bytes in size.
329  uint64_t Size = DL->getTypeSizeInBits(V->getType());
330  if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
331  return nullptr;
332 
333  // Don't care enough about darwin/ppc to implement this.
334  if (DL->isBigEndian())
335  return nullptr;
336 
337  // Convert to size in bytes.
338  Size /= 8;
339 
340  // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
341  // if the top and bottom are the same (e.g. for vectors and large integers).
342  if (Size > 16)
343  return nullptr;
344 
345  // If the constant is exactly 16 bytes, just use it.
346  if (Size == 16)
347  return C;
348 
349  // Otherwise, we'll use an array of the constants.
350  unsigned ArraySize = 16 / Size;
351  ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
352  return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
353 }
354 
355 LoopIdiomRecognize::LegalStoreKind
356 LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
357 
358  // Don't touch volatile stores.
359  if (SI->isVolatile())
360  return LegalStoreKind::None;
361  // We only want simple or unordered-atomic stores.
362  if (!SI->isUnordered())
363  return LegalStoreKind::None;
364 
365  // Don't convert stores of non-integral pointer types to memsets (which stores
366  // integers).
367  if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType()))
368  return LegalStoreKind::None;
369 
370  // Avoid merging nontemporal stores.
372  return LegalStoreKind::None;
373 
374  Value *StoredVal = SI->getValueOperand();
375  Value *StorePtr = SI->getPointerOperand();
376 
377  // Reject stores that are so large that they overflow an unsigned.
378  uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
379  if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
380  return LegalStoreKind::None;
381 
382  // See if the pointer expression is an AddRec like {base,+,1} on the current
383  // loop, which indicates a strided store. If we have something else, it's a
384  // random store we can't handle.
385  const SCEVAddRecExpr *StoreEv =
386  dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
387  if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
388  return LegalStoreKind::None;
389 
390  // Check to see if we have a constant stride.
391  if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
392  return LegalStoreKind::None;
393 
394  // See if the store can be turned into a memset.
395 
396  // If the stored value is a byte-wise value (like i32 -1), then it may be
397  // turned into a memset of i8 -1, assuming that all the consecutive bytes
398  // are stored. A store of i32 0x01020304 can never be turned into a memset,
399  // but it can be turned into memset_pattern if the target supports it.
400  Value *SplatValue = isBytewiseValue(StoredVal);
401  Constant *PatternValue = nullptr;
402 
403  // Note: memset and memset_pattern on unordered-atomic is yet not supported
404  bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
405 
406  // If we're allowed to form a memset, and the stored value would be
407  // acceptable for memset, use it.
408  if (!UnorderedAtomic && HasMemset && SplatValue &&
409  // Verify that the stored value is loop invariant. If not, we can't
410  // promote the memset.
411  CurLoop->isLoopInvariant(SplatValue)) {
412  // It looks like we can use SplatValue.
413  return LegalStoreKind::Memset;
414  } else if (!UnorderedAtomic && HasMemsetPattern &&
415  // Don't create memset_pattern16s with address spaces.
416  StorePtr->getType()->getPointerAddressSpace() == 0 &&
417  (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
418  // It looks like we can use PatternValue!
419  return LegalStoreKind::MemsetPattern;
420  }
421 
422  // Otherwise, see if the store can be turned into a memcpy.
423  if (HasMemcpy) {
424  // Check to see if the stride matches the size of the store. If so, then we
425  // know that every byte is touched in the loop.
426  APInt Stride = getStoreStride(StoreEv);
427  unsigned StoreSize = getStoreSizeInBytes(SI, DL);
428  if (StoreSize != Stride && StoreSize != -Stride)
429  return LegalStoreKind::None;
430 
431  // The store must be feeding a non-volatile load.
433 
434  // Only allow non-volatile loads
435  if (!LI || LI->isVolatile())
436  return LegalStoreKind::None;
437  // Only allow simple or unordered-atomic loads
438  if (!LI->isUnordered())
439  return LegalStoreKind::None;
440 
441  // See if the pointer expression is an AddRec like {base,+,1} on the current
442  // loop, which indicates a strided load. If we have something else, it's a
443  // random load we can't handle.
444  const SCEVAddRecExpr *LoadEv =
446  if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
447  return LegalStoreKind::None;
448 
449  // The store and load must share the same stride.
450  if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
451  return LegalStoreKind::None;
452 
453  // Success. This store can be converted into a memcpy.
454  UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
455  return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
456  : LegalStoreKind::Memcpy;
457  }
458  // This store can't be transformed into a memset/memcpy.
459  return LegalStoreKind::None;
460 }
461 
462 void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
463  StoreRefsForMemset.clear();
464  StoreRefsForMemsetPattern.clear();
465  StoreRefsForMemcpy.clear();
466  for (Instruction &I : *BB) {
467  StoreInst *SI = dyn_cast<StoreInst>(&I);
468  if (!SI)
469  continue;
470 
471  // Make sure this is a strided store with a constant stride.
472  switch (isLegalStore(SI)) {
474  // Nothing to do
475  break;
476  case LegalStoreKind::Memset: {
477  // Find the base pointer.
479  StoreRefsForMemset[Ptr].push_back(SI);
480  } break;
481  case LegalStoreKind::MemsetPattern: {
482  // Find the base pointer.
484  StoreRefsForMemsetPattern[Ptr].push_back(SI);
485  } break;
486  case LegalStoreKind::Memcpy:
487  case LegalStoreKind::UnorderedAtomicMemcpy:
488  StoreRefsForMemcpy.push_back(SI);
489  break;
490  default:
491  assert(false && "unhandled return value");
492  break;
493  }
494  }
495 }
496 
497 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
498 /// with the specified backedge count. This block is known to be in the current
499 /// loop and not in any subloops.
500 bool LoopIdiomRecognize::runOnLoopBlock(
501  BasicBlock *BB, const SCEV *BECount,
502  SmallVectorImpl<BasicBlock *> &ExitBlocks) {
503  // We can only promote stores in this block if they are unconditionally
504  // executed in the loop. For a block to be unconditionally executed, it has
505  // to dominate all the exit blocks of the loop. Verify this now.
506  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
507  if (!DT->dominates(BB, ExitBlocks[i]))
508  return false;
509 
510  bool MadeChange = false;
511  // Look for store instructions, which may be optimized to memset/memcpy.
512  collectStores(BB);
513 
514  // Look for a single store or sets of stores with a common base, which can be
515  // optimized into a memset (memset_pattern). The latter most commonly happens
516  // with structs and handunrolled loops.
517  for (auto &SL : StoreRefsForMemset)
518  MadeChange |= processLoopStores(SL.second, BECount, true);
519 
520  for (auto &SL : StoreRefsForMemsetPattern)
521  MadeChange |= processLoopStores(SL.second, BECount, false);
522 
523  // Optimize the store into a memcpy, if it feeds an similarly strided load.
524  for (auto &SI : StoreRefsForMemcpy)
525  MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
526 
527  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
528  Instruction *Inst = &*I++;
529  // Look for memset instructions, which may be optimized to a larger memset.
530  if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
531  WeakTrackingVH InstPtr(&*I);
532  if (!processLoopMemSet(MSI, BECount))
533  continue;
534  MadeChange = true;
535 
536  // If processing the memset invalidated our iterator, start over from the
537  // top of the block.
538  if (!InstPtr)
539  I = BB->begin();
540  continue;
541  }
542  }
543 
544  return MadeChange;
545 }
546 
547 /// processLoopStores - See if this store(s) can be promoted to a memset.
548 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
549  const SCEV *BECount,
550  bool ForMemset) {
551  // Try to find consecutive stores that can be transformed into memsets.
552  SetVector<StoreInst *> Heads, Tails;
554 
555  // Do a quadratic search on all of the given stores and find
556  // all of the pairs of stores that follow each other.
557  SmallVector<unsigned, 16> IndexQueue;
558  for (unsigned i = 0, e = SL.size(); i < e; ++i) {
559  assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
560 
561  Value *FirstStoredVal = SL[i]->getValueOperand();
562  Value *FirstStorePtr = SL[i]->getPointerOperand();
563  const SCEVAddRecExpr *FirstStoreEv =
564  cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
565  APInt FirstStride = getStoreStride(FirstStoreEv);
566  unsigned FirstStoreSize = getStoreSizeInBytes(SL[i], DL);
567 
568  // See if we can optimize just this store in isolation.
569  if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
570  Heads.insert(SL[i]);
571  continue;
572  }
573 
574  Value *FirstSplatValue = nullptr;
575  Constant *FirstPatternValue = nullptr;
576 
577  if (ForMemset)
578  FirstSplatValue = isBytewiseValue(FirstStoredVal);
579  else
580  FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
581 
582  assert((FirstSplatValue || FirstPatternValue) &&
583  "Expected either splat value or pattern value.");
584 
585  IndexQueue.clear();
586  // If a store has multiple consecutive store candidates, search Stores
587  // array according to the sequence: from i+1 to e, then from i-1 to 0.
588  // This is because usually pairing with immediate succeeding or preceding
589  // candidate create the best chance to find memset opportunity.
590  unsigned j = 0;
591  for (j = i + 1; j < e; ++j)
592  IndexQueue.push_back(j);
593  for (j = i; j > 0; --j)
594  IndexQueue.push_back(j - 1);
595 
596  for (auto &k : IndexQueue) {
597  assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
598  Value *SecondStorePtr = SL[k]->getPointerOperand();
599  const SCEVAddRecExpr *SecondStoreEv =
600  cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
601  APInt SecondStride = getStoreStride(SecondStoreEv);
602 
603  if (FirstStride != SecondStride)
604  continue;
605 
606  Value *SecondStoredVal = SL[k]->getValueOperand();
607  Value *SecondSplatValue = nullptr;
608  Constant *SecondPatternValue = nullptr;
609 
610  if (ForMemset)
611  SecondSplatValue = isBytewiseValue(SecondStoredVal);
612  else
613  SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
614 
615  assert((SecondSplatValue || SecondPatternValue) &&
616  "Expected either splat value or pattern value.");
617 
618  if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
619  if (ForMemset) {
620  if (FirstSplatValue != SecondSplatValue)
621  continue;
622  } else {
623  if (FirstPatternValue != SecondPatternValue)
624  continue;
625  }
626  Tails.insert(SL[k]);
627  Heads.insert(SL[i]);
628  ConsecutiveChain[SL[i]] = SL[k];
629  break;
630  }
631  }
632  }
633 
634  // We may run into multiple chains that merge into a single chain. We mark the
635  // stores that we transformed so that we don't visit the same store twice.
636  SmallPtrSet<Value *, 16> TransformedStores;
637  bool Changed = false;
638 
639  // For stores that start but don't end a link in the chain:
640  for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
641  it != e; ++it) {
642  if (Tails.count(*it))
643  continue;
644 
645  // We found a store instr that starts a chain. Now follow the chain and try
646  // to transform it.
647  SmallPtrSet<Instruction *, 8> AdjacentStores;
648  StoreInst *I = *it;
649 
650  StoreInst *HeadStore = I;
651  unsigned StoreSize = 0;
652 
653  // Collect the chain into a list.
654  while (Tails.count(I) || Heads.count(I)) {
655  if (TransformedStores.count(I))
656  break;
657  AdjacentStores.insert(I);
658 
659  StoreSize += getStoreSizeInBytes(I, DL);
660  // Move to the next value in the chain.
661  I = ConsecutiveChain[I];
662  }
663 
664  Value *StoredVal = HeadStore->getValueOperand();
665  Value *StorePtr = HeadStore->getPointerOperand();
666  const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
667  APInt Stride = getStoreStride(StoreEv);
668 
669  // Check to see if the stride matches the size of the stores. If so, then
670  // we know that every byte is touched in the loop.
671  if (StoreSize != Stride && StoreSize != -Stride)
672  continue;
673 
674  bool NegStride = StoreSize == -Stride;
675 
676  if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
677  StoredVal, HeadStore, AdjacentStores, StoreEv,
678  BECount, NegStride)) {
679  TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
680  Changed = true;
681  }
682  }
683 
684  return Changed;
685 }
686 
687 /// processLoopMemSet - See if this memset can be promoted to a large memset.
688 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
689  const SCEV *BECount) {
690  // We can only handle non-volatile memsets with a constant size.
691  if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
692  return false;
693 
694  // If we're not allowed to hack on memset, we fail.
695  if (!HasMemset)
696  return false;
697 
698  Value *Pointer = MSI->getDest();
699 
700  // See if the pointer expression is an AddRec like {base,+,1} on the current
701  // loop, which indicates a strided store. If we have something else, it's a
702  // random store we can't handle.
703  const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
704  if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
705  return false;
706 
707  // Reject memsets that are so large that they overflow an unsigned.
708  uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
709  if ((SizeInBytes >> 32) != 0)
710  return false;
711 
712  // Check to see if the stride matches the size of the memset. If so, then we
713  // know that every byte is touched in the loop.
714  const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
715  if (!ConstStride)
716  return false;
717 
718  APInt Stride = ConstStride->getAPInt();
719  if (SizeInBytes != Stride && SizeInBytes != -Stride)
720  return false;
721 
722  // Verify that the memset value is loop invariant. If not, we can't promote
723  // the memset.
724  Value *SplatValue = MSI->getValue();
725  if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
726  return false;
727 
729  MSIs.insert(MSI);
730  bool NegStride = SizeInBytes == -Stride;
731  return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
732  MSI->getAlignment(), SplatValue, MSI, MSIs, Ev,
733  BECount, NegStride, /*IsLoopMemset=*/true);
734 }
735 
736 /// mayLoopAccessLocation - Return true if the specified loop might access the
737 /// specified pointer location, which is a loop-strided access. The 'Access'
738 /// argument specifies what the verboten forms of access are (read or write).
739 static bool
741  const SCEV *BECount, unsigned StoreSize,
742  AliasAnalysis &AA,
743  SmallPtrSetImpl<Instruction *> &IgnoredStores) {
744  // Get the location that may be stored across the loop. Since the access is
745  // strided positively through memory, we say that the modified location starts
746  // at the pointer and has infinite size.
747  uint64_t AccessSize = MemoryLocation::UnknownSize;
748 
749  // If the loop iterates a fixed number of times, we can refine the access size
750  // to be exactly the size of the memset, which is (BECount+1)*StoreSize
751  if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
752  AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
753 
754  // TODO: For this to be really effective, we have to dive into the pointer
755  // operand in the store. Store to &A[i] of 100 will always return may alias
756  // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
757  // which will then no-alias a store to &A[100].
758  MemoryLocation StoreLoc(Ptr, AccessSize);
759 
760  for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
761  ++BI)
762  for (Instruction &I : **BI)
763  if (IgnoredStores.count(&I) == 0 &&
764  (AA.getModRefInfo(&I, StoreLoc) & Access))
765  return true;
766 
767  return false;
768 }
769 
770 // If we have a negative stride, Start refers to the end of the memory location
771 // we're trying to memset. Therefore, we need to recompute the base pointer,
772 // which is just Start - BECount*Size.
773 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
774  Type *IntPtr, unsigned StoreSize,
775  ScalarEvolution *SE) {
776  const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
777  if (StoreSize != 1)
778  Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
779  SCEV::FlagNUW);
780  return SE->getMinusSCEV(Start, Index);
781 }
782 
783 /// processLoopStridedStore - We see a strided store of some value. If we can
784 /// transform this into a memset or memset_pattern in the loop preheader, do so.
785 bool LoopIdiomRecognize::processLoopStridedStore(
786  Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
787  Value *StoredVal, Instruction *TheStore,
789  const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
790  Value *SplatValue = isBytewiseValue(StoredVal);
791  Constant *PatternValue = nullptr;
792 
793  if (!SplatValue)
794  PatternValue = getMemSetPatternValue(StoredVal, DL);
795 
796  assert((SplatValue || PatternValue) &&
797  "Expected either splat value or pattern value.");
798 
799  // The trip count of the loop and the base pointer of the addrec SCEV is
800  // guaranteed to be loop invariant, which means that it should dominate the
801  // header. This allows us to insert code for it in the preheader.
802  unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
803  BasicBlock *Preheader = CurLoop->getLoopPreheader();
804  IRBuilder<> Builder(Preheader->getTerminator());
805  SCEVExpander Expander(*SE, *DL, "loop-idiom");
806 
807  Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
808  Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
809 
810  const SCEV *Start = Ev->getStart();
811  // Handle negative strided loops.
812  if (NegStride)
813  Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
814 
815  // TODO: ideally we should still be able to generate memset if SCEV expander
816  // is taught to generate the dependencies at the latest point.
817  if (!isSafeToExpand(Start, *SE))
818  return false;
819 
820  // Okay, we have a strided store "p[i]" of a splattable value. We can turn
821  // this into a memset in the loop preheader now if we want. However, this
822  // would be unsafe to do if there is anything else in the loop that may read
823  // or write to the aliased location. Check for any overlap by generating the
824  // base pointer and checking the region.
825  Value *BasePtr =
826  Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
827  if (mayLoopAccessLocation(BasePtr, MRI_ModRef, CurLoop, BECount, StoreSize,
828  *AA, Stores)) {
829  Expander.clear();
830  // If we generated new code for the base pointer, clean up.
832  return false;
833  }
834 
835  if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
836  return false;
837 
838  // Okay, everything looks good, insert the memset.
839 
840  // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
841  // pointer size if it isn't already.
842  BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
843 
844  const SCEV *NumBytesS =
845  SE->getAddExpr(BECount, SE->getOne(IntPtr), SCEV::FlagNUW);
846  if (StoreSize != 1) {
847  NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
848  SCEV::FlagNUW);
849  }
850 
851  // TODO: ideally we should still be able to generate memset if SCEV expander
852  // is taught to generate the dependencies at the latest point.
853  if (!isSafeToExpand(NumBytesS, *SE))
854  return false;
855 
856  Value *NumBytes =
857  Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
858 
859  CallInst *NewCall;
860  if (SplatValue) {
861  NewCall =
862  Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
863  } else {
864  // Everything is emitted in default address space
865  Type *Int8PtrTy = DestInt8PtrTy;
866 
867  Module *M = TheStore->getModule();
868  Value *MSP =
869  M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
870  Int8PtrTy, Int8PtrTy, IntPtr);
871  inferLibFuncAttributes(*M->getFunction("memset_pattern16"), *TLI);
872 
873  // Otherwise we should form a memset_pattern16. PatternValue is known to be
874  // an constant array of 16-bytes. Plop the value into a mergable global.
875  GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
877  PatternValue, ".memset_pattern");
878  GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
879  GV->setAlignment(16);
880  Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
881  NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
882  }
883 
884  DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
885  << " from store to: " << *Ev << " at: " << *TheStore << "\n");
886  NewCall->setDebugLoc(TheStore->getDebugLoc());
887 
888  // Okay, the memset has been formed. Zap the original store and anything that
889  // feeds into it.
890  for (auto *I : Stores)
892  ++NumMemSet;
893  return true;
894 }
895 
896 /// If the stored value is a strided load in the same loop with the same stride
897 /// this may be transformable into a memcpy. This kicks in for stuff like
898 /// for (i) A[i] = B[i];
899 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
900  const SCEV *BECount) {
901  assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
902 
903  Value *StorePtr = SI->getPointerOperand();
904  const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
905  APInt Stride = getStoreStride(StoreEv);
906  unsigned StoreSize = getStoreSizeInBytes(SI, DL);
907  bool NegStride = StoreSize == -Stride;
908 
909  // The store must be feeding a non-volatile load.
910  LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
911  assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
912 
913  // See if the pointer expression is an AddRec like {base,+,1} on the current
914  // loop, which indicates a strided load. If we have something else, it's a
915  // random load we can't handle.
916  const SCEVAddRecExpr *LoadEv =
917  cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
918 
919  // The trip count of the loop and the base pointer of the addrec SCEV is
920  // guaranteed to be loop invariant, which means that it should dominate the
921  // header. This allows us to insert code for it in the preheader.
922  BasicBlock *Preheader = CurLoop->getLoopPreheader();
923  IRBuilder<> Builder(Preheader->getTerminator());
924  SCEVExpander Expander(*SE, *DL, "loop-idiom");
925 
926  const SCEV *StrStart = StoreEv->getStart();
927  unsigned StrAS = SI->getPointerAddressSpace();
928  Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
929 
930  // Handle negative strided loops.
931  if (NegStride)
932  StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
933 
934  // Okay, we have a strided store "p[i]" of a loaded value. We can turn
935  // this into a memcpy in the loop preheader now if we want. However, this
936  // would be unsafe to do if there is anything else in the loop that may read
937  // or write the memory region we're storing to. This includes the load that
938  // feeds the stores. Check for an alias by generating the base address and
939  // checking everything.
940  Value *StoreBasePtr = Expander.expandCodeFor(
941  StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
942 
944  Stores.insert(SI);
945  if (mayLoopAccessLocation(StoreBasePtr, MRI_ModRef, CurLoop, BECount,
946  StoreSize, *AA, Stores)) {
947  Expander.clear();
948  // If we generated new code for the base pointer, clean up.
950  return false;
951  }
952 
953  const SCEV *LdStart = LoadEv->getStart();
954  unsigned LdAS = LI->getPointerAddressSpace();
955 
956  // Handle negative strided loops.
957  if (NegStride)
958  LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
959 
960  // For a memcpy, we have to make sure that the input array is not being
961  // mutated by the loop.
962  Value *LoadBasePtr = Expander.expandCodeFor(
963  LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
964 
965  if (mayLoopAccessLocation(LoadBasePtr, MRI_Mod, CurLoop, BECount, StoreSize,
966  *AA, Stores)) {
967  Expander.clear();
968  // If we generated new code for the base pointer, clean up.
971  return false;
972  }
973 
974  if (avoidLIRForMultiBlockLoop())
975  return false;
976 
977  // Okay, everything is safe, we can transform this!
978 
979  // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
980  // pointer size if it isn't already.
981  BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
982 
983  const SCEV *NumBytesS =
984  SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
985 
986  if (StoreSize != 1)
987  NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
988  SCEV::FlagNUW);
989 
990  Value *NumBytes =
991  Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
992 
993  unsigned Align = std::min(SI->getAlignment(), LI->getAlignment());
994  CallInst *NewCall = nullptr;
995  // Check whether to generate an unordered atomic memcpy:
996  // If the load or store are atomic, then they must neccessarily be unordered
997  // by previous checks.
998  if (!SI->isAtomic() && !LI->isAtomic())
999  NewCall = Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, Align);
1000  else {
1001  // We cannot allow unaligned ops for unordered load/store, so reject
1002  // anything where the alignment isn't at least the element size.
1003  if (Align < StoreSize)
1004  return false;
1005 
1006  // If the element.atomic memcpy is not lowered into explicit
1007  // loads/stores later, then it will be lowered into an element-size
1008  // specific lib call. If the lib call doesn't exist for our store size, then
1009  // we shouldn't generate the memcpy.
1010  if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1011  return false;
1012 
1013  NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1014  StoreBasePtr, LoadBasePtr, NumBytes, StoreSize);
1015 
1016  // Propagate alignment info onto the pointer args. Note that unordered
1017  // atomic loads/stores are *required* by the spec to have an alignment
1018  // but non-atomic loads/stores may not.
1019  NewCall->addParamAttr(0, Attribute::getWithAlignment(NewCall->getContext(),
1020  SI->getAlignment()));
1021  NewCall->addParamAttr(1, Attribute::getWithAlignment(NewCall->getContext(),
1022  LI->getAlignment()));
1023  }
1024  NewCall->setDebugLoc(SI->getDebugLoc());
1025 
1026  DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
1027  << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1028  << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
1029 
1030  // Okay, the memcpy has been formed. Zap the original store and anything that
1031  // feeds into it.
1033  ++NumMemCpy;
1034  return true;
1035 }
1036 
1037 // When compiling for codesize we avoid idiom recognition for a multi-block loop
1038 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1039 //
1040 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1041  bool IsLoopMemset) {
1042  if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1043  if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
1044  DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()
1045  << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1046  << " avoided: multi-block top-level loop\n");
1047  return true;
1048  }
1049  }
1050 
1051  return false;
1052 }
1053 
1054 bool LoopIdiomRecognize::runOnNoncountableLoop() {
1055  return recognizePopcount() || recognizeAndInsertCTLZ();
1056 }
1057 
1058 /// Check if the given conditional branch is based on the comparison between
1059 /// a variable and zero, and if the variable is non-zero, the control yields to
1060 /// the loop entry. If the branch matches the behavior, the variable involved
1061 /// in the comparison is returned. This function will be called to see if the
1062 /// precondition and postcondition of the loop are in desirable form.
1063 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
1064  if (!BI || !BI->isConditional())
1065  return nullptr;
1066 
1067  ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1068  if (!Cond)
1069  return nullptr;
1070 
1071  ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1072  if (!CmpZero || !CmpZero->isZero())
1073  return nullptr;
1074 
1075  ICmpInst::Predicate Pred = Cond->getPredicate();
1076  if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
1077  (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
1078  return Cond->getOperand(0);
1079 
1080  return nullptr;
1081 }
1082 
1083 // Check if the recurrence variable `VarX` is in the right form to create
1084 // the idiom. Returns the value coerced to a PHINode if so.
1086  BasicBlock *LoopEntry) {
1087  auto *PhiX = dyn_cast<PHINode>(VarX);
1088  if (PhiX && PhiX->getParent() == LoopEntry &&
1089  (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1090  return PhiX;
1091  return nullptr;
1092 }
1093 
1094 /// Return true iff the idiom is detected in the loop.
1095 ///
1096 /// Additionally:
1097 /// 1) \p CntInst is set to the instruction counting the population bit.
1098 /// 2) \p CntPhi is set to the corresponding phi node.
1099 /// 3) \p Var is set to the value whose population bits are being counted.
1100 ///
1101 /// The core idiom we are trying to detect is:
1102 /// \code
1103 /// if (x0 != 0)
1104 /// goto loop-exit // the precondition of the loop
1105 /// cnt0 = init-val;
1106 /// do {
1107 /// x1 = phi (x0, x2);
1108 /// cnt1 = phi(cnt0, cnt2);
1109 ///
1110 /// cnt2 = cnt1 + 1;
1111 /// ...
1112 /// x2 = x1 & (x1 - 1);
1113 /// ...
1114 /// } while(x != 0);
1115 ///
1116 /// loop-exit:
1117 /// \endcode
1118 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1119  Instruction *&CntInst, PHINode *&CntPhi,
1120  Value *&Var) {
1121  // step 1: Check to see if the look-back branch match this pattern:
1122  // "if (a!=0) goto loop-entry".
1123  BasicBlock *LoopEntry;
1124  Instruction *DefX2, *CountInst;
1125  Value *VarX1, *VarX0;
1126  PHINode *PhiX, *CountPhi;
1127 
1128  DefX2 = CountInst = nullptr;
1129  VarX1 = VarX0 = nullptr;
1130  PhiX = CountPhi = nullptr;
1131  LoopEntry = *(CurLoop->block_begin());
1132 
1133  // step 1: Check if the loop-back branch is in desirable form.
1134  {
1135  if (Value *T = matchCondition(
1136  dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1137  DefX2 = dyn_cast<Instruction>(T);
1138  else
1139  return false;
1140  }
1141 
1142  // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1143  {
1144  if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1145  return false;
1146 
1147  BinaryOperator *SubOneOp;
1148 
1149  if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1150  VarX1 = DefX2->getOperand(1);
1151  else {
1152  VarX1 = DefX2->getOperand(0);
1153  SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1154  }
1155  if (!SubOneOp)
1156  return false;
1157 
1158  Instruction *SubInst = cast<Instruction>(SubOneOp);
1159  ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
1160  if (!Dec ||
1161  !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1162  (SubInst->getOpcode() == Instruction::Add &&
1163  Dec->isMinusOne()))) {
1164  return false;
1165  }
1166  }
1167 
1168  // step 3: Check the recurrence of variable X
1169  PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1170  if (!PhiX)
1171  return false;
1172 
1173  // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1174  {
1175  CountInst = nullptr;
1176  for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1177  IterE = LoopEntry->end();
1178  Iter != IterE; Iter++) {
1179  Instruction *Inst = &*Iter;
1180  if (Inst->getOpcode() != Instruction::Add)
1181  continue;
1182 
1183  ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1184  if (!Inc || !Inc->isOne())
1185  continue;
1186 
1187  PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1188  if (!Phi)
1189  continue;
1190 
1191  // Check if the result of the instruction is live of the loop.
1192  bool LiveOutLoop = false;
1193  for (User *U : Inst->users()) {
1194  if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1195  LiveOutLoop = true;
1196  break;
1197  }
1198  }
1199 
1200  if (LiveOutLoop) {
1201  CountInst = Inst;
1202  CountPhi = Phi;
1203  break;
1204  }
1205  }
1206 
1207  if (!CountInst)
1208  return false;
1209  }
1210 
1211  // step 5: check if the precondition is in this form:
1212  // "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1213  {
1214  auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1215  Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1216  if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1217  return false;
1218 
1219  CntInst = CountInst;
1220  CntPhi = CountPhi;
1221  Var = T;
1222  }
1223 
1224  return true;
1225 }
1226 
1227 /// Return true if the idiom is detected in the loop.
1228 ///
1229 /// Additionally:
1230 /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1231 /// or nullptr if there is no such.
1232 /// 2) \p CntPhi is set to the corresponding phi node
1233 /// or nullptr if there is no such.
1234 /// 3) \p Var is set to the value whose CTLZ could be used.
1235 /// 4) \p DefX is set to the instruction calculating Loop exit condition.
1236 ///
1237 /// The core idiom we are trying to detect is:
1238 /// \code
1239 /// if (x0 == 0)
1240 /// goto loop-exit // the precondition of the loop
1241 /// cnt0 = init-val;
1242 /// do {
1243 /// x = phi (x0, x.next); //PhiX
1244 /// cnt = phi(cnt0, cnt.next);
1245 ///
1246 /// cnt.next = cnt + 1;
1247 /// ...
1248 /// x.next = x >> 1; // DefX
1249 /// ...
1250 /// } while(x.next != 0);
1251 ///
1252 /// loop-exit:
1253 /// \endcode
1254 static bool detectCTLZIdiom(Loop *CurLoop, PHINode *&PhiX,
1255  Instruction *&CntInst, PHINode *&CntPhi,
1256  Instruction *&DefX) {
1257  BasicBlock *LoopEntry;
1258  Value *VarX = nullptr;
1259 
1260  DefX = nullptr;
1261  PhiX = nullptr;
1262  CntInst = nullptr;
1263  CntPhi = nullptr;
1264  LoopEntry = *(CurLoop->block_begin());
1265 
1266  // step 1: Check if the loop-back branch is in desirable form.
1267  if (Value *T = matchCondition(
1268  dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1269  DefX = dyn_cast<Instruction>(T);
1270  else
1271  return false;
1272 
1273  // step 2: detect instructions corresponding to "x.next = x >> 1"
1274  if (!DefX || DefX->getOpcode() != Instruction::AShr)
1275  return false;
1276  if (ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1)))
1277  if (!Shft || !Shft->isOne())
1278  return false;
1279  VarX = DefX->getOperand(0);
1280 
1281  // step 3: Check the recurrence of variable X
1282  PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
1283  if (!PhiX)
1284  return false;
1285 
1286  // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1287  // TODO: We can skip the step. If loop trip count is known (CTLZ),
1288  // then all uses of "cnt.next" could be optimized to the trip count
1289  // plus "cnt0". Currently it is not optimized.
1290  // This step could be used to detect POPCNT instruction:
1291  // cnt.next = cnt + (x.next & 1)
1292  for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1293  IterE = LoopEntry->end();
1294  Iter != IterE; Iter++) {
1295  Instruction *Inst = &*Iter;
1296  if (Inst->getOpcode() != Instruction::Add)
1297  continue;
1298 
1299  ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1300  if (!Inc || !Inc->isOne())
1301  continue;
1302 
1303  PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1304  if (!Phi)
1305  continue;
1306 
1307  CntInst = Inst;
1308  CntPhi = Phi;
1309  break;
1310  }
1311  if (!CntInst)
1312  return false;
1313 
1314  return true;
1315 }
1316 
1317 /// Recognize CTLZ idiom in a non-countable loop and convert the loop
1318 /// to countable (with CTLZ trip count).
1319 /// If CTLZ inserted as a new trip count returns true; otherwise, returns false.
1320 bool LoopIdiomRecognize::recognizeAndInsertCTLZ() {
1321  // Give up if the loop has multiple blocks or multiple backedges.
1322  if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1323  return false;
1324 
1325  Instruction *CntInst, *DefX;
1326  PHINode *CntPhi, *PhiX;
1327  if (!detectCTLZIdiom(CurLoop, PhiX, CntInst, CntPhi, DefX))
1328  return false;
1329 
1330  bool IsCntPhiUsedOutsideLoop = false;
1331  for (User *U : CntPhi->users())
1332  if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1333  IsCntPhiUsedOutsideLoop = true;
1334  break;
1335  }
1336  bool IsCntInstUsedOutsideLoop = false;
1337  for (User *U : CntInst->users())
1338  if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1339  IsCntInstUsedOutsideLoop = true;
1340  break;
1341  }
1342  // If both CntInst and CntPhi are used outside the loop the profitability
1343  // is questionable.
1344  if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1345  return false;
1346 
1347  // For some CPUs result of CTLZ(X) intrinsic is undefined
1348  // when X is 0. If we can not guarantee X != 0, we need to check this
1349  // when expand.
1350  bool ZeroCheck = false;
1351  // It is safe to assume Preheader exist as it was checked in
1352  // parent function RunOnLoop.
1353  BasicBlock *PH = CurLoop->getLoopPreheader();
1354  Value *InitX = PhiX->getIncomingValueForBlock(PH);
1355  // If we check X != 0 before entering the loop we don't need a zero
1356  // check in CTLZ intrinsic, but only if Cnt Phi is not used outside of the
1357  // loop (if it is used we count CTLZ(X >> 1)).
1358  if (!IsCntPhiUsedOutsideLoop)
1359  if (BasicBlock *PreCondBB = PH->getSinglePredecessor())
1360  if (BranchInst *PreCondBr =
1361  dyn_cast<BranchInst>(PreCondBB->getTerminator())) {
1362  if (matchCondition(PreCondBr, PH) == InitX)
1363  ZeroCheck = true;
1364  }
1365 
1366  // Check if CTLZ intrinsic is profitable. Assume it is always profitable
1367  // if we delete the loop (the loop has only 6 instructions):
1368  // %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1369  // %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1370  // %shr = ashr %n.addr.0, 1
1371  // %tobool = icmp eq %shr, 0
1372  // %inc = add nsw %i.0, 1
1373  // br i1 %tobool
1374 
1375  IRBuilder<> Builder(PH->getTerminator());
1377  {InitX, ZeroCheck ? Builder.getTrue() : Builder.getFalse()};
1379  if (CurLoop->getHeader()->size() != 6 &&
1380  TTI->getIntrinsicCost(Intrinsic::ctlz, InitX->getType(), Args) >
1382  return false;
1383 
1384  const DebugLoc DL = DefX->getDebugLoc();
1385  transformLoopToCountable(PH, CntInst, CntPhi, InitX, DL, ZeroCheck,
1386  IsCntPhiUsedOutsideLoop);
1387  return true;
1388 }
1389 
1390 /// Recognizes a population count idiom in a non-countable loop.
1391 ///
1392 /// If detected, transforms the relevant code to issue the popcount intrinsic
1393 /// function call, and returns true; otherwise, returns false.
1394 bool LoopIdiomRecognize::recognizePopcount() {
1396  return false;
1397 
1398  // Counting population are usually conducted by few arithmetic instructions.
1399  // Such instructions can be easily "absorbed" by vacant slots in a
1400  // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1401  // in a compact loop.
1402 
1403  // Give up if the loop has multiple blocks or multiple backedges.
1404  if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1405  return false;
1406 
1407  BasicBlock *LoopBody = *(CurLoop->block_begin());
1408  if (LoopBody->size() >= 20) {
1409  // The loop is too big, bail out.
1410  return false;
1411  }
1412 
1413  // It should have a preheader containing nothing but an unconditional branch.
1414  BasicBlock *PH = CurLoop->getLoopPreheader();
1415  if (!PH || &PH->front() != PH->getTerminator())
1416  return false;
1417  auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
1418  if (!EntryBI || EntryBI->isConditional())
1419  return false;
1420 
1421  // It should have a precondition block where the generated popcount instrinsic
1422  // function can be inserted.
1423  auto *PreCondBB = PH->getSinglePredecessor();
1424  if (!PreCondBB)
1425  return false;
1426  auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1427  if (!PreCondBI || PreCondBI->isUnconditional())
1428  return false;
1429 
1430  Instruction *CntInst;
1431  PHINode *CntPhi;
1432  Value *Val;
1433  if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1434  return false;
1435 
1436  transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1437  return true;
1438 }
1439 
1441  const DebugLoc &DL) {
1442  Value *Ops[] = {Val};
1443  Type *Tys[] = {Val->getType()};
1444 
1445  Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1446  Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1447  CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1448  CI->setDebugLoc(DL);
1449 
1450  return CI;
1451 }
1452 
1454  const DebugLoc &DL, bool ZeroCheck) {
1455  Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()};
1456  Type *Tys[] = {Val->getType()};
1457 
1458  Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1459  Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctlz, Tys);
1460  CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1461  CI->setDebugLoc(DL);
1462 
1463  return CI;
1464 }
1465 
1466 /// Transform the following loop:
1467 /// loop:
1468 /// CntPhi = PHI [Cnt0, CntInst]
1469 /// PhiX = PHI [InitX, DefX]
1470 /// CntInst = CntPhi + 1
1471 /// DefX = PhiX >> 1
1472 // LOOP_BODY
1473 /// Br: loop if (DefX != 0)
1474 /// Use(CntPhi) or Use(CntInst)
1475 ///
1476 /// Into:
1477 /// If CntPhi used outside the loop:
1478 /// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1479 /// Count = CountPrev + 1
1480 /// else
1481 /// Count = BitWidth(InitX) - CTLZ(InitX)
1482 /// loop:
1483 /// CntPhi = PHI [Cnt0, CntInst]
1484 /// PhiX = PHI [InitX, DefX]
1485 /// PhiCount = PHI [Count, Dec]
1486 /// CntInst = CntPhi + 1
1487 /// DefX = PhiX >> 1
1488 /// Dec = PhiCount - 1
1489 /// LOOP_BODY
1490 /// Br: loop if (Dec != 0)
1491 /// Use(CountPrev + Cnt0) // Use(CntPhi)
1492 /// or
1493 /// Use(Count + Cnt0) // Use(CntInst)
1494 ///
1495 /// If LOOP_BODY is empty the loop will be deleted.
1496 /// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1497 void LoopIdiomRecognize::transformLoopToCountable(
1498  BasicBlock *Preheader, Instruction *CntInst, PHINode *CntPhi, Value *InitX,
1499  const DebugLoc DL, bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
1500  BranchInst *PreheaderBr = dyn_cast<BranchInst>(Preheader->getTerminator());
1501 
1502  // Step 1: Insert the CTLZ instruction at the end of the preheader block
1503  // Count = BitWidth - CTLZ(InitX);
1504  // If there are uses of CntPhi create:
1505  // CountPrev = BitWidth - CTLZ(InitX >> 1);
1506  IRBuilder<> Builder(PreheaderBr);
1507  Builder.SetCurrentDebugLocation(DL);
1508  Value *CTLZ, *Count, *CountPrev, *NewCount, *InitXNext;
1509 
1510  if (IsCntPhiUsedOutsideLoop)
1511  InitXNext = Builder.CreateAShr(InitX,
1512  ConstantInt::get(InitX->getType(), 1));
1513  else
1514  InitXNext = InitX;
1515  CTLZ = createCTLZIntrinsic(Builder, InitXNext, DL, ZeroCheck);
1516  Count = Builder.CreateSub(
1517  ConstantInt::get(CTLZ->getType(),
1518  CTLZ->getType()->getIntegerBitWidth()),
1519  CTLZ);
1520  if (IsCntPhiUsedOutsideLoop) {
1521  CountPrev = Count;
1522  Count = Builder.CreateAdd(
1523  CountPrev,
1524  ConstantInt::get(CountPrev->getType(), 1));
1525  }
1526  if (IsCntPhiUsedOutsideLoop)
1527  NewCount = Builder.CreateZExtOrTrunc(CountPrev,
1528  cast<IntegerType>(CntInst->getType()));
1529  else
1530  NewCount = Builder.CreateZExtOrTrunc(Count,
1531  cast<IntegerType>(CntInst->getType()));
1532 
1533  // If the CTLZ counter's initial value is not zero, insert Add Inst.
1534  Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1535  ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1536  if (!InitConst || !InitConst->isZero())
1537  NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1538 
1539  // Step 2: Insert new IV and loop condition:
1540  // loop:
1541  // ...
1542  // PhiCount = PHI [Count, Dec]
1543  // ...
1544  // Dec = PhiCount - 1
1545  // ...
1546  // Br: loop if (Dec != 0)
1547  BasicBlock *Body = *(CurLoop->block_begin());
1548  auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1549  ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1550  Type *Ty = Count->getType();
1551 
1552  PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1553 
1554  Builder.SetInsertPoint(LbCond);
1555  Instruction *TcDec = cast<Instruction>(
1556  Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1557  "tcdec", false, true));
1558 
1559  TcPhi->addIncoming(Count, Preheader);
1560  TcPhi->addIncoming(TcDec, Body);
1561 
1562  CmpInst::Predicate Pred =
1563  (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
1564  LbCond->setPredicate(Pred);
1565  LbCond->setOperand(0, TcDec);
1566  LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1567 
1568  // Step 3: All the references to the original counter outside
1569  // the loop are replaced with the NewCount -- the value returned from
1570  // __builtin_ctlz(x).
1571  if (IsCntPhiUsedOutsideLoop)
1572  CntPhi->replaceUsesOutsideBlock(NewCount, Body);
1573  else
1574  CntInst->replaceUsesOutsideBlock(NewCount, Body);
1575 
1576  // step 4: Forget the "non-computable" trip-count SCEV associated with the
1577  // loop. The loop would otherwise not be deleted even if it becomes empty.
1578  SE->forgetLoop(CurLoop);
1579 }
1580 
1581 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1582  Instruction *CntInst,
1583  PHINode *CntPhi, Value *Var) {
1584  BasicBlock *PreHead = CurLoop->getLoopPreheader();
1585  auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1586  const DebugLoc DL = CntInst->getDebugLoc();
1587 
1588  // Assuming before transformation, the loop is following:
1589  // if (x) // the precondition
1590  // do { cnt++; x &= x - 1; } while(x);
1591 
1592  // Step 1: Insert the ctpop instruction at the end of the precondition block
1593  IRBuilder<> Builder(PreCondBr);
1594  Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1595  {
1596  PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1597  NewCount = PopCntZext =
1598  Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1599 
1600  if (NewCount != PopCnt)
1601  (cast<Instruction>(NewCount))->setDebugLoc(DL);
1602 
1603  // TripCnt is exactly the number of iterations the loop has
1604  TripCnt = NewCount;
1605 
1606  // If the population counter's initial value is not zero, insert Add Inst.
1607  Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1608  ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1609  if (!InitConst || !InitConst->isZero()) {
1610  NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1611  (cast<Instruction>(NewCount))->setDebugLoc(DL);
1612  }
1613  }
1614 
1615  // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
1616  // "if (NewCount == 0) loop-exit". Without this change, the intrinsic
1617  // function would be partial dead code, and downstream passes will drag
1618  // it back from the precondition block to the preheader.
1619  {
1620  ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1621 
1622  Value *Opnd0 = PopCntZext;
1623  Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1624  if (PreCond->getOperand(0) != Var)
1625  std::swap(Opnd0, Opnd1);
1626 
1627  ICmpInst *NewPreCond = cast<ICmpInst>(
1628  Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1629  PreCondBr->setCondition(NewPreCond);
1630 
1632  }
1633 
1634  // Step 3: Note that the population count is exactly the trip count of the
1635  // loop in question, which enable us to to convert the loop from noncountable
1636  // loop into a countable one. The benefit is twofold:
1637  //
1638  // - If the loop only counts population, the entire loop becomes dead after
1639  // the transformation. It is a lot easier to prove a countable loop dead
1640  // than to prove a noncountable one. (In some C dialects, an infinite loop
1641  // isn't dead even if it computes nothing useful. In general, DCE needs
1642  // to prove a noncountable loop finite before safely delete it.)
1643  //
1644  // - If the loop also performs something else, it remains alive.
1645  // Since it is transformed to countable form, it can be aggressively
1646  // optimized by some optimizations which are in general not applicable
1647  // to a noncountable loop.
1648  //
1649  // After this step, this loop (conceptually) would look like following:
1650  // newcnt = __builtin_ctpop(x);
1651  // t = newcnt;
1652  // if (x)
1653  // do { cnt++; x &= x-1; t--) } while (t > 0);
1654  BasicBlock *Body = *(CurLoop->block_begin());
1655  {
1656  auto *LbBr = dyn_cast<BranchInst>(Body->getTerminator());
1657  ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1658  Type *Ty = TripCnt->getType();
1659 
1660  PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1661 
1662  Builder.SetInsertPoint(LbCond);
1663  Instruction *TcDec = cast<Instruction>(
1664  Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1665  "tcdec", false, true));
1666 
1667  TcPhi->addIncoming(TripCnt, PreHead);
1668  TcPhi->addIncoming(TcDec, Body);
1669 
1670  CmpInst::Predicate Pred =
1671  (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1672  LbCond->setPredicate(Pred);
1673  LbCond->setOperand(0, TcDec);
1674  LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1675  }
1676 
1677  // Step 4: All the references to the original population counter outside
1678  // the loop are replaced with the NewCount -- the value returned from
1679  // __builtin_ctpop().
1680  CntInst->replaceUsesOutsideBlock(NewCount, Body);
1681 
1682  // step 5: Forget the "non-computable" trip-count SCEV associated with the
1683  // loop. The loop would otherwise not be deleted even if it becomes empty.
1684  SE->forgetLoop(CurLoop);
1685 }
unsigned getAlignment() const
MachineLoop * L
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:81
PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const
Return hardware support for population count.
Value * getValueOperand()
Definition: Instructions.h:395
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:69
void push_back(const T &Elt)
Definition: SmallVector.h:211
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
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.
const SCEV * getConstant(ConstantInt *V)
STATISTIC(NumFunctions,"Total number of functions")
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Definition: Instructions.h:339
Value * isBytewiseValue(Value *V)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
bool isVolatile() const
This is the interface for a simple mod/ref and alias analysis over globals.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:142
static Attribute getWithAlignment(LLVMContext &Context, uint64_t Align)
Return a uniquified Attribute object that has the specific alignment set.
Definition: Attributes.cpp:125
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
unsigned getAtomicMemIntrinsicMaxElementSize() const
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
Value * getValue() const
Return the arguments to the instruction.
The main scalar evolution driver.
bool isSimple() const
Definition: Instructions.h:387
DataLayout DL
static bool detectCTLZIdiom(Loop *CurLoop, PHINode *&PhiX, Instruction *&CntInst, PHINode *&CntPhi, Instruction *&DefX)
Return true if the idiom is detected in the loop.
This class represents a function call, abstracting a target machine's calling convention.
static PHINode * getRecurrenceVar(Value *VarX, Instruction *DefX, BasicBlock *LoopEntry)
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
This class wraps the llvm.memset intrinsic.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
A debug info location.
Definition: DebugLoc.h:34
const Instruction & front() const
Definition: BasicBlock.h:264
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
An instruction for reading from memory.
Definition: Instructions.h:164
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Definition: LoopInfo.h:585
iterator end()
Get an iterator to the end of the SetVector.
Definition: SetVector.h:93
The access modifies the value stored in memory.
BlockT * getHeader() const
Definition: LoopInfo.h:103
const SCEV * getStart() const
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition: AliasAnalysis.h:94
This is the interface for a SCEV-based alias analysis.
static CallInst * createCTLZIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL, bool ZeroCheck)
bool isUnordered() const
Definition: Instructions.h:264
INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass,"loop-idiom","Recognize loop idioms", false, false) INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:664
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:404
void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Definition: LICM.cpp:479
static bool isSimple(Instruction *I)
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:182
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:142
This node represents a polynomial recurrence on the trip count of the specified loop.
static APInt getStoreStride(const SCEVAddRecExpr *StoreEv)
#define T
Class to represent array types.
Definition: DerivedTypes.h:369
BasicBlock * getSuccessor(unsigned i) const
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition: SetVector.h:83
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:975
void initializeLoopIdiomRecognizeLegacyPassPass(PassRegistry &)
An instruction for storing to memory.
Definition: Instructions.h:306
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:428
int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< Type * > ParamTys) const
Estimate the cost of an intrinsic when lowered.
static void deleteDeadInstruction(Instruction *I)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:134
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
const char * Name
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:172
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1678
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)
Definition: CommandLine.h:401
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)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:351
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
Wrapper pass for TargetTransformInfo.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
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.
Definition: Instruction.h:277
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:101
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:288
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
Definition: Constant.h:42
const SCEV * getOperand(unsigned i) const
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:888
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:372
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:280
Represent the analysis usage information of a pass.
static Value * matchCondition(BranchInst *BI, BasicBlock *LoopEntry)
Check if the given conditional branch is based on the comparison between a variable and zero...
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:860
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
Value * getOperand(unsigned i) const
Definition: User.h:154
Value * getPointerOperand()
Definition: Instructions.h:270
self_iterator getIterator()
Definition: ilist_node.h:82
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:97
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:934
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 isUnordered() const
Definition: Instructions.h:389
const APInt & getAPInt() const
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1320
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
Definition: Local.cpp:370
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
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...
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...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:234
bool isConditional() const
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
Definition: SetVector.h:49
Iterator for intrusive lists based on ilist_node.
loop Recognize loop false
#define E
Definition: LargeTest.cpp:27
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions that feed it, giving the original input.
iterator end()
Definition: BasicBlock.h:254
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:57
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
Provides information about what library functions are available for the current target.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:190
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:383
bool isVolatile() const
Return true if this is a load from a volatile memory location.
Definition: Instructions.h:217
Value * getLength() const
BasicBlock * GetInsertBlock() const
Definition: IRBuilder.h:122
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.
Definition: Constants.cpp:560
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:193
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...
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...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:276
static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, Instruction *&CntInst, PHINode *&CntPhi, Value *&Var)
Return true iff the idiom is detected in the loop.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:217
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
signed less or equal
Definition: InstrTypes.h:890
loop Recognize loop idioms
Class for arbitrary precision integers.
Definition: APInt.h:69
loop idiom
ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
iterator_range< user_iterator > users()
Definition: Value.h:395
This class uses information about analyze scalars to rewrite expressions in canonical form...
std::vector< BlockT * >::const_iterator block_iterator
Definition: LoopInfo.h:141
Pass * createLoopIdiomPass()
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition: IRBuilder.h:293
block_iterator block_end() const
Definition: LoopInfo.h:143
Value * getCondition() const
Captures loop safety information.
Definition: LoopUtils.h:50
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...
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:211
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:203
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:360
#define C
Definition: LargeTest.cpp:25
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:226
The access both references and modifies the value stored in memory.
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1659
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
Definition: LoopUtils.cpp:1022
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:568
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
const Loop * getLoop() const
size_t size() const
Definition: BasicBlock.h:262
static const SCEV * getStartForNegStride(const SCEV *Start, const SCEV *BECount, Type *IntPtr, unsigned StoreSize, ScalarEvolution *SE)
const SCEV * getBackedgeTakenCount(const Loop *L)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
The cost of a typical 'add' instruction.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:545
LLVM Value Representation.
Definition: Value.h:73
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:121
A vector that has set insertion semantics.
Definition: SetVector.h:41
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:532
#define DEBUG(X)
Definition: Debug.h:118
static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL)
block_iterator block_begin() const
Definition: LoopInfo.h:142
unsigned greater than
Definition: InstrTypes.h:883
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
This is the interface for LLVM's primary stateless and local alias analysis.
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"...
Definition: Value.cpp:438
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
This pass exposes codegen information to IR-level passes.
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.
int * Ptr
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...
Definition: BasicBlock.cpp:120
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:171
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...
bool isBigEndian() const
Definition: DataLayout.h:217
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count...
Value * getPointerOperand()
Definition: Instructions.h:398
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition: Constants.h:201
bool has(LibFunc F) const
Tests whether a library function is available.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
This class represents a constant integer value.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.