LLVM  4.0.0
StraightLineStrengthReduce.cpp
Go to the documentation of this file.
1 //===-- StraightLineStrengthReduce.cpp - ------------------------*- C++ -*-===//
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 file implements straight-line strength reduction (SLSR). Unlike loop
11 // strength reduction, this algorithm is designed to reduce arithmetic
12 // redundancy in straight-line code instead of loops. It has proven to be
13 // effective in simplifying arithmetic statements derived from an unrolled loop.
14 // It can also simplify the logic of SeparateConstOffsetFromGEP.
15 //
16 // There are many optimizations we can perform in the domain of SLSR. This file
17 // for now contains only an initial step. Specifically, we look for strength
18 // reduction candidates in the following forms:
19 //
20 // Form 1: B + i * S
21 // Form 2: (B + i) * S
22 // Form 3: &B[i * S]
23 //
24 // where S is an integer variable, and i is a constant integer. If we found two
25 // candidates S1 and S2 in the same form and S1 dominates S2, we may rewrite S2
26 // in a simpler way with respect to S1. For example,
27 //
28 // S1: X = B + i * S
29 // S2: Y = B + i' * S => X + (i' - i) * S
30 //
31 // S1: X = (B + i) * S
32 // S2: Y = (B + i') * S => X + (i' - i) * S
33 //
34 // S1: X = &B[i * S]
35 // S2: Y = &B[i' * S] => &X[(i' - i) * S]
36 //
37 // Note: (i' - i) * S is folded to the extent possible.
38 //
39 // This rewriting is in general a good idea. The code patterns we focus on
40 // usually come from loop unrolling, so (i' - i) * S is likely the same
41 // across iterations and can be reused. When that happens, the optimized form
42 // takes only one add starting from the second iteration.
43 //
44 // When such rewriting is possible, we call S1 a "basis" of S2. When S2 has
45 // multiple bases, we choose to rewrite S2 with respect to its "immediate"
46 // basis, the basis that is the closest ancestor in the dominator tree.
47 //
48 // TODO:
49 //
50 // - Floating point arithmetics when fast math is enabled.
51 //
52 // - SLSR may decrease ILP at the architecture level. Targets that are very
53 // sensitive to ILP may want to disable it. Having SLSR to consider ILP is
54 // left as future work.
55 //
56 // - When (i' - i) is constant but i and i' are not, we could still perform
57 // SLSR.
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/Dominators.h"
63 #include "llvm/IR/IRBuilder.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/PatternMatch.h"
67 #include "llvm/Transforms/Scalar.h"
69 #include <list>
70 #include <vector>
71 
72 using namespace llvm;
73 using namespace PatternMatch;
74 
75 namespace {
76 
77 static const unsigned UnknownAddressSpace = ~0u;
78 
79 class StraightLineStrengthReduce : public FunctionPass {
80 public:
81  // SLSR candidate. Such a candidate must be in one of the forms described in
82  // the header comments.
83  struct Candidate {
84  enum Kind {
85  Invalid, // reserved for the default constructor
86  Add, // B + i * S
87  Mul, // (B + i) * S
88  GEP, // &B[..][i * S][..]
89  };
90 
91  Candidate()
92  : CandidateKind(Invalid), Base(nullptr), Index(nullptr),
93  Stride(nullptr), Ins(nullptr), Basis(nullptr) {}
94  Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
95  Instruction *I)
96  : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I),
97  Basis(nullptr) {}
98  Kind CandidateKind;
99  const SCEV *Base;
100  // Note that Index and Stride of a GEP candidate do not necessarily have the
101  // same integer type. In that case, during rewriting, Stride will be
102  // sign-extended or truncated to Index's type.
103  ConstantInt *Index;
104  Value *Stride;
105  // The instruction this candidate corresponds to. It helps us to rewrite a
106  // candidate with respect to its immediate basis. Note that one instruction
107  // can correspond to multiple candidates depending on how you associate the
108  // expression. For instance,
109  //
110  // (a + 1) * (b + 2)
111  //
112  // can be treated as
113  //
114  // <Base: a, Index: 1, Stride: b + 2>
115  //
116  // or
117  //
118  // <Base: b, Index: 2, Stride: a + 1>
119  Instruction *Ins;
120  // Points to the immediate basis of this candidate, or nullptr if we cannot
121  // find any basis for this candidate.
122  Candidate *Basis;
123  };
124 
125  static char ID;
126 
127  StraightLineStrengthReduce()
128  : FunctionPass(ID), DL(nullptr), DT(nullptr), TTI(nullptr) {
130  }
131 
132  void getAnalysisUsage(AnalysisUsage &AU) const override {
136  // We do not modify the shape of the CFG.
137  AU.setPreservesCFG();
138  }
139 
140  bool doInitialization(Module &M) override {
141  DL = &M.getDataLayout();
142  return false;
143  }
144 
145  bool runOnFunction(Function &F) override;
146 
147 private:
148  // Returns true if Basis is a basis for C, i.e., Basis dominates C and they
149  // share the same base and stride.
150  bool isBasisFor(const Candidate &Basis, const Candidate &C);
151  // Returns whether the candidate can be folded into an addressing mode.
152  bool isFoldable(const Candidate &C, TargetTransformInfo *TTI,
153  const DataLayout *DL);
154  // Returns true if C is already in a simplest form and not worth being
155  // rewritten.
156  bool isSimplestForm(const Candidate &C);
157  // Checks whether I is in a candidate form. If so, adds all the matching forms
158  // to Candidates, and tries to find the immediate basis for each of them.
159  void allocateCandidatesAndFindBasis(Instruction *I);
160  // Allocate candidates and find bases for Add instructions.
161  void allocateCandidatesAndFindBasisForAdd(Instruction *I);
162  // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
163  // candidate.
164  void allocateCandidatesAndFindBasisForAdd(Value *LHS, Value *RHS,
165  Instruction *I);
166  // Allocate candidates and find bases for Mul instructions.
167  void allocateCandidatesAndFindBasisForMul(Instruction *I);
168  // Splits LHS into Base + Index and, if succeeds, calls
169  // allocateCandidatesAndFindBasis.
170  void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS,
171  Instruction *I);
172  // Allocate candidates and find bases for GetElementPtr instructions.
173  void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP);
174  // A helper function that scales Idx with ElementSize before invoking
175  // allocateCandidatesAndFindBasis.
176  void allocateCandidatesAndFindBasisForGEP(const SCEV *B, ConstantInt *Idx,
177  Value *S, uint64_t ElementSize,
178  Instruction *I);
179  // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
180  // basis.
181  void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B,
182  ConstantInt *Idx, Value *S,
183  Instruction *I);
184  // Rewrites candidate C with respect to Basis.
185  void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
186  // A helper function that factors ArrayIdx to a product of a stride and a
187  // constant index, and invokes allocateCandidatesAndFindBasis with the
188  // factorings.
189  void factorArrayIndex(Value *ArrayIdx, const SCEV *Base, uint64_t ElementSize,
191  // Emit code that computes the "bump" from Basis to C. If the candidate is a
192  // GEP and the bump is not divisible by the element size of the GEP, this
193  // function sets the BumpWithUglyGEP flag to notify its caller to bump the
194  // basis using an ugly GEP.
195  static Value *emitBump(const Candidate &Basis, const Candidate &C,
196  IRBuilder<> &Builder, const DataLayout *DL,
197  bool &BumpWithUglyGEP);
198 
199  const DataLayout *DL;
200  DominatorTree *DT;
201  ScalarEvolution *SE;
202  TargetTransformInfo *TTI;
203  std::list<Candidate> Candidates;
204  // Temporarily holds all instructions that are unlinked (but not deleted) by
205  // rewriteCandidateWithBasis. These instructions will be actually removed
206  // after all rewriting finishes.
207  std::vector<Instruction *> UnlinkedInstructions;
208 };
209 } // anonymous namespace
210 
212 INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
213  "Straight line strength reduction", false, false)
217 INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
218  "Straight line strength reduction", false, false)
219 
221  return new StraightLineStrengthReduce();
222 }
223 
224 bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
225  const Candidate &C) {
226  return (Basis.Ins != C.Ins && // skip the same instruction
227  // They must have the same type too. Basis.Base == C.Base doesn't
228  // guarantee their types are the same (PR23975).
229  Basis.Ins->getType() == C.Ins->getType() &&
230  // Basis must dominate C in order to rewrite C with respect to Basis.
231  DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
232  // They share the same base, stride, and candidate kind.
233  Basis.Base == C.Base && Basis.Stride == C.Stride &&
234  Basis.CandidateKind == C.CandidateKind);
235 }
236 
238  const TargetTransformInfo *TTI) {
240  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
241  Indices.push_back(*I);
242  return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
243  Indices) == TargetTransformInfo::TCC_Free;
244 }
245 
246 // Returns whether (Base + Index * Stride) can be folded to an addressing mode.
247 static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
248  TargetTransformInfo *TTI) {
249  // Index->getSExtValue() may crash if Index is wider than 64-bit.
250  return Index->getBitWidth() <= 64 &&
251  TTI->isLegalAddressingMode(Base->getType(), nullptr, 0, true,
252  Index->getSExtValue(), UnknownAddressSpace);
253 }
254 
255 bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
256  TargetTransformInfo *TTI,
257  const DataLayout *DL) {
258  if (C.CandidateKind == Candidate::Add)
259  return isAddFoldable(C.Base, C.Index, C.Stride, TTI);
260  if (C.CandidateKind == Candidate::GEP)
261  return isGEPFoldable(cast<GetElementPtrInst>(C.Ins), TTI);
262  return false;
263 }
264 
265 // Returns true if GEP has zero or one non-zero index.
267  unsigned NumNonZeroIndices = 0;
268  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) {
269  ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
270  if (ConstIdx == nullptr || !ConstIdx->isZero())
271  ++NumNonZeroIndices;
272  }
273  return NumNonZeroIndices <= 1;
274 }
275 
276 bool StraightLineStrengthReduce::isSimplestForm(const Candidate &C) {
277  if (C.CandidateKind == Candidate::Add) {
278  // B + 1 * S or B + (-1) * S
279  return C.Index->isOne() || C.Index->isMinusOne();
280  }
281  if (C.CandidateKind == Candidate::Mul) {
282  // (B + 0) * S
283  return C.Index->isZero();
284  }
285  if (C.CandidateKind == Candidate::GEP) {
286  // (char*)B + S or (char*)B - S
287  return ((C.Index->isOne() || C.Index->isMinusOne()) &&
288  hasOnlyOneNonZeroIndex(cast<GetElementPtrInst>(C.Ins)));
289  }
290  return false;
291 }
292 
293 // TODO: We currently implement an algorithm whose time complexity is linear in
294 // the number of existing candidates. However, we could do better by using
295 // ScopedHashTable. Specifically, while traversing the dominator tree, we could
296 // maintain all the candidates that dominate the basic block being traversed in
297 // a ScopedHashTable. This hash table is indexed by the base and the stride of
298 // a candidate. Therefore, finding the immediate basis of a candidate boils down
299 // to one hash-table look up.
300 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
301  Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
302  Instruction *I) {
303  Candidate C(CT, B, Idx, S, I);
304  // SLSR can complicate an instruction in two cases:
305  //
306  // 1. If we can fold I into an addressing mode, computing I is likely free or
307  // takes only one instruction.
308  //
309  // 2. I is already in a simplest form. For example, when
310  // X = B + 8 * S
311  // Y = B + S,
312  // rewriting Y to X - 7 * S is probably a bad idea.
313  //
314  // In the above cases, we still add I to the candidate list so that I can be
315  // the basis of other candidates, but we leave I's basis blank so that I
316  // won't be rewritten.
317  if (!isFoldable(C, TTI, DL) && !isSimplestForm(C)) {
318  // Try to compute the immediate basis of C.
319  unsigned NumIterations = 0;
320  // Limit the scan radius to avoid running in quadratice time.
321  static const unsigned MaxNumIterations = 50;
322  for (auto Basis = Candidates.rbegin();
323  Basis != Candidates.rend() && NumIterations < MaxNumIterations;
324  ++Basis, ++NumIterations) {
325  if (isBasisFor(*Basis, C)) {
326  C.Basis = &(*Basis);
327  break;
328  }
329  }
330  }
331  // Regardless of whether we find a basis for C, we need to push C to the
332  // candidate list so that it can be the basis of other candidates.
333  Candidates.push_back(C);
334 }
335 
336 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
337  Instruction *I) {
338  switch (I->getOpcode()) {
339  case Instruction::Add:
340  allocateCandidatesAndFindBasisForAdd(I);
341  break;
342  case Instruction::Mul:
343  allocateCandidatesAndFindBasisForMul(I);
344  break;
345  case Instruction::GetElementPtr:
346  allocateCandidatesAndFindBasisForGEP(cast<GetElementPtrInst>(I));
347  break;
348  }
349 }
350 
351 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
352  Instruction *I) {
353  // Try matching B + i * S.
354  if (!isa<IntegerType>(I->getType()))
355  return;
356 
357  assert(I->getNumOperands() == 2 && "isn't I an add?");
358  Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
359  allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
360  if (LHS != RHS)
361  allocateCandidatesAndFindBasisForAdd(RHS, LHS, I);
362 }
363 
364 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
365  Value *LHS, Value *RHS, Instruction *I) {
366  Value *S = nullptr;
367  ConstantInt *Idx = nullptr;
368  if (match(RHS, m_Mul(m_Value(S), m_ConstantInt(Idx)))) {
369  // I = LHS + RHS = LHS + Idx * S
370  allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
371  } else if (match(RHS, m_Shl(m_Value(S), m_ConstantInt(Idx)))) {
372  // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
373  APInt One(Idx->getBitWidth(), 1);
374  Idx = ConstantInt::get(Idx->getContext(), One << Idx->getValue());
375  allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
376  } else {
377  // At least, I = LHS + 1 * RHS
378  ConstantInt *One = ConstantInt::get(cast<IntegerType>(I->getType()), 1);
379  allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), One, RHS,
380  I);
381  }
382 }
383 
384 // Returns true if A matches B + C where C is constant.
385 static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
386  return (match(A, m_Add(m_Value(B), m_ConstantInt(C))) ||
387  match(A, m_Add(m_ConstantInt(C), m_Value(B))));
388 }
389 
390 // Returns true if A matches B | C where C is constant.
391 static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
392  return (match(A, m_Or(m_Value(B), m_ConstantInt(C))) ||
393  match(A, m_Or(m_ConstantInt(C), m_Value(B))));
394 }
395 
396 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
397  Value *LHS, Value *RHS, Instruction *I) {
398  Value *B = nullptr;
399  ConstantInt *Idx = nullptr;
400  if (matchesAdd(LHS, B, Idx)) {
401  // If LHS is in the form of "Base + Index", then I is in the form of
402  // "(Base + Index) * RHS".
403  allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
404  } else if (matchesOr(LHS, B, Idx) && haveNoCommonBitsSet(B, Idx, *DL)) {
405  // If LHS is in the form of "Base | Index" and Base and Index have no common
406  // bits set, then
407  // Base | Index = Base + Index
408  // and I is thus in the form of "(Base + Index) * RHS".
409  allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
410  } else {
411  // Otherwise, at least try the form (LHS + 0) * RHS.
412  ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0);
413  allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS,
414  I);
415  }
416 }
417 
418 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
419  Instruction *I) {
420  // Try matching (B + i) * S.
421  // TODO: we could extend SLSR to float and vector types.
422  if (!isa<IntegerType>(I->getType()))
423  return;
424 
425  assert(I->getNumOperands() == 2 && "isn't I a mul?");
426  Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
427  allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
428  if (LHS != RHS) {
429  // Symmetrically, try to split RHS to Base + Index.
430  allocateCandidatesAndFindBasisForMul(RHS, LHS, I);
431  }
432 }
433 
434 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
435  const SCEV *B, ConstantInt *Idx, Value *S, uint64_t ElementSize,
436  Instruction *I) {
437  // I = B + sext(Idx *nsw S) * ElementSize
438  // = B + (sext(Idx) * sext(S)) * ElementSize
439  // = B + (sext(Idx) * ElementSize) * sext(S)
440  // Casting to IntegerType is safe because we skipped vector GEPs.
441  IntegerType *IntPtrTy = cast<IntegerType>(DL->getIntPtrType(I->getType()));
442  ConstantInt *ScaledIdx = ConstantInt::get(
443  IntPtrTy, Idx->getSExtValue() * (int64_t)ElementSize, true);
444  allocateCandidatesAndFindBasis(Candidate::GEP, B, ScaledIdx, S, I);
445 }
446 
447 void StraightLineStrengthReduce::factorArrayIndex(Value *ArrayIdx,
448  const SCEV *Base,
449  uint64_t ElementSize,
451  // At least, ArrayIdx = ArrayIdx *nsw 1.
452  allocateCandidatesAndFindBasisForGEP(
453  Base, ConstantInt::get(cast<IntegerType>(ArrayIdx->getType()), 1),
454  ArrayIdx, ElementSize, GEP);
455  Value *LHS = nullptr;
456  ConstantInt *RHS = nullptr;
457  // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
458  // itself. This would allow us to handle the shl case for free. However,
459  // matching SCEVs has two issues:
460  //
461  // 1. this would complicate rewriting because the rewriting procedure
462  // would have to translate SCEVs back to IR instructions. This translation
463  // is difficult when LHS is further evaluated to a composite SCEV.
464  //
465  // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
466  // to strip nsw/nuw flags which are critical for SLSR to trace into
467  // sext'ed multiplication.
468  if (match(ArrayIdx, m_NSWMul(m_Value(LHS), m_ConstantInt(RHS)))) {
469  // SLSR is currently unsafe if i * S may overflow.
470  // GEP = Base + sext(LHS *nsw RHS) * ElementSize
471  allocateCandidatesAndFindBasisForGEP(Base, RHS, LHS, ElementSize, GEP);
472  } else if (match(ArrayIdx, m_NSWShl(m_Value(LHS), m_ConstantInt(RHS)))) {
473  // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
474  // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
475  APInt One(RHS->getBitWidth(), 1);
476  ConstantInt *PowerOf2 =
477  ConstantInt::get(RHS->getContext(), One << RHS->getValue());
478  allocateCandidatesAndFindBasisForGEP(Base, PowerOf2, LHS, ElementSize, GEP);
479  }
480 }
481 
482 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
483  GetElementPtrInst *GEP) {
484  // TODO: handle vector GEPs
485  if (GEP->getType()->isVectorTy())
486  return;
487 
488  SmallVector<const SCEV *, 4> IndexExprs;
489  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
490  IndexExprs.push_back(SE->getSCEV(*I));
491 
493  for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
494  if (GTI.isStruct())
495  continue;
496 
497  const SCEV *OrigIndexExpr = IndexExprs[I - 1];
498  IndexExprs[I - 1] = SE->getZero(OrigIndexExpr->getType());
499 
500  // The base of this candidate is GEP's base plus the offsets of all
501  // indices except this current one.
502  const SCEV *BaseExpr = SE->getGEPExpr(cast<GEPOperator>(GEP), IndexExprs);
503  Value *ArrayIdx = GEP->getOperand(I);
504  uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
505  if (ArrayIdx->getType()->getIntegerBitWidth() <=
507  // Skip factoring if ArrayIdx is wider than the pointer size, because
508  // ArrayIdx is implicitly truncated to the pointer size.
509  factorArrayIndex(ArrayIdx, BaseExpr, ElementSize, GEP);
510  }
511  // When ArrayIdx is the sext of a value, we try to factor that value as
512  // well. Handling this case is important because array indices are
513  // typically sign-extended to the pointer size.
514  Value *TruncatedArrayIdx = nullptr;
515  if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))) &&
516  TruncatedArrayIdx->getType()->getIntegerBitWidth() <=
518  // Skip factoring if TruncatedArrayIdx is wider than the pointer size,
519  // because TruncatedArrayIdx is implicitly truncated to the pointer size.
520  factorArrayIndex(TruncatedArrayIdx, BaseExpr, ElementSize, GEP);
521  }
522 
523  IndexExprs[I - 1] = OrigIndexExpr;
524  }
525 }
526 
527 // A helper function that unifies the bitwidth of A and B.
528 static void unifyBitWidth(APInt &A, APInt &B) {
529  if (A.getBitWidth() < B.getBitWidth())
530  A = A.sext(B.getBitWidth());
531  else if (A.getBitWidth() > B.getBitWidth())
532  B = B.sext(A.getBitWidth());
533 }
534 
535 Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
536  const Candidate &C,
537  IRBuilder<> &Builder,
538  const DataLayout *DL,
539  bool &BumpWithUglyGEP) {
540  APInt Idx = C.Index->getValue(), BasisIdx = Basis.Index->getValue();
541  unifyBitWidth(Idx, BasisIdx);
542  APInt IndexOffset = Idx - BasisIdx;
543 
544  BumpWithUglyGEP = false;
545  if (Basis.CandidateKind == Candidate::GEP) {
546  APInt ElementSize(
547  IndexOffset.getBitWidth(),
548  DL->getTypeAllocSize(
549  cast<GetElementPtrInst>(Basis.Ins)->getResultElementType()));
550  APInt Q, R;
551  APInt::sdivrem(IndexOffset, ElementSize, Q, R);
552  if (R == 0)
553  IndexOffset = Q;
554  else
555  BumpWithUglyGEP = true;
556  }
557 
558  // Compute Bump = C - Basis = (i' - i) * S.
559  // Common case 1: if (i' - i) is 1, Bump = S.
560  if (IndexOffset == 1)
561  return C.Stride;
562  // Common case 2: if (i' - i) is -1, Bump = -S.
563  if (IndexOffset.isAllOnesValue())
564  return Builder.CreateNeg(C.Stride);
565 
566  // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may
567  // have different bit widths.
568  IntegerType *DeltaType =
569  IntegerType::get(Basis.Ins->getContext(), IndexOffset.getBitWidth());
570  Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, DeltaType);
571  if (IndexOffset.isPowerOf2()) {
572  // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i).
573  ConstantInt *Exponent = ConstantInt::get(DeltaType, IndexOffset.logBase2());
574  return Builder.CreateShl(ExtendedStride, Exponent);
575  }
576  if ((-IndexOffset).isPowerOf2()) {
577  // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i).
578  ConstantInt *Exponent =
579  ConstantInt::get(DeltaType, (-IndexOffset).logBase2());
580  return Builder.CreateNeg(Builder.CreateShl(ExtendedStride, Exponent));
581  }
582  Constant *Delta = ConstantInt::get(DeltaType, IndexOffset);
583  return Builder.CreateMul(ExtendedStride, Delta);
584 }
585 
586 void StraightLineStrengthReduce::rewriteCandidateWithBasis(
587  const Candidate &C, const Candidate &Basis) {
588  assert(C.CandidateKind == Basis.CandidateKind && C.Base == Basis.Base &&
589  C.Stride == Basis.Stride);
590  // We run rewriteCandidateWithBasis on all candidates in a post-order, so the
591  // basis of a candidate cannot be unlinked before the candidate.
592  assert(Basis.Ins->getParent() != nullptr && "the basis is unlinked");
593 
594  // An instruction can correspond to multiple candidates. Therefore, instead of
595  // simply deleting an instruction when we rewrite it, we mark its parent as
596  // nullptr (i.e. unlink it) so that we can skip the candidates whose
597  // instruction is already rewritten.
598  if (!C.Ins->getParent())
599  return;
600 
601  IRBuilder<> Builder(C.Ins);
602  bool BumpWithUglyGEP;
603  Value *Bump = emitBump(Basis, C, Builder, DL, BumpWithUglyGEP);
604  Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
605  switch (C.CandidateKind) {
606  case Candidate::Add:
607  case Candidate::Mul:
608  // C = Basis + Bump
609  if (BinaryOperator::isNeg(Bump)) {
610  // If Bump is a neg instruction, emit C = Basis - (-Bump).
611  Reduced =
612  Builder.CreateSub(Basis.Ins, BinaryOperator::getNegArgument(Bump));
613  // We only use the negative argument of Bump, and Bump itself may be
614  // trivially dead.
616  } else {
617  // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
618  // usually unsound, e.g.,
619  //
620  // X = (-2 +nsw 1) *nsw INT_MAX
621  // Y = (-2 +nsw 3) *nsw INT_MAX
622  // =>
623  // Y = X + 2 * INT_MAX
624  //
625  // Neither + and * in the resultant expression are nsw.
626  Reduced = Builder.CreateAdd(Basis.Ins, Bump);
627  }
628  break;
629  case Candidate::GEP:
630  {
631  Type *IntPtrTy = DL->getIntPtrType(C.Ins->getType());
632  bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds();
633  if (BumpWithUglyGEP) {
634  // C = (char *)Basis + Bump
635  unsigned AS = Basis.Ins->getType()->getPointerAddressSpace();
636  Type *CharTy = Type::getInt8PtrTy(Basis.Ins->getContext(), AS);
637  Reduced = Builder.CreateBitCast(Basis.Ins, CharTy);
638  if (InBounds)
639  Reduced =
640  Builder.CreateInBoundsGEP(Builder.getInt8Ty(), Reduced, Bump);
641  else
642  Reduced = Builder.CreateGEP(Builder.getInt8Ty(), Reduced, Bump);
643  Reduced = Builder.CreateBitCast(Reduced, C.Ins->getType());
644  } else {
645  // C = gep Basis, Bump
646  // Canonicalize bump to pointer size.
647  Bump = Builder.CreateSExtOrTrunc(Bump, IntPtrTy);
648  if (InBounds)
649  Reduced = Builder.CreateInBoundsGEP(nullptr, Basis.Ins, Bump);
650  else
651  Reduced = Builder.CreateGEP(nullptr, Basis.Ins, Bump);
652  }
653  }
654  break;
655  default:
656  llvm_unreachable("C.CandidateKind is invalid");
657  };
658  Reduced->takeName(C.Ins);
659  C.Ins->replaceAllUsesWith(Reduced);
660  // Unlink C.Ins so that we can skip other candidates also corresponding to
661  // C.Ins. The actual deletion is postponed to the end of runOnFunction.
662  C.Ins->removeFromParent();
663  UnlinkedInstructions.push_back(C.Ins);
664 }
665 
666 bool StraightLineStrengthReduce::runOnFunction(Function &F) {
667  if (skipFunction(F))
668  return false;
669 
670  TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
671  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
672  SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
673  // Traverse the dominator tree in the depth-first order. This order makes sure
674  // all bases of a candidate are in Candidates when we process it.
675  for (const auto Node : depth_first(DT))
676  for (auto &I : *(Node->getBlock()))
677  allocateCandidatesAndFindBasis(&I);
678 
679  // Rewrite candidates in the reverse depth-first order. This order makes sure
680  // a candidate being rewritten is not a basis for any other candidate.
681  while (!Candidates.empty()) {
682  const Candidate &C = Candidates.back();
683  if (C.Basis != nullptr) {
684  rewriteCandidateWithBasis(C, *C.Basis);
685  }
686  Candidates.pop_back();
687  }
688 
689  // Delete all unlink instructions.
690  for (auto *UnlinkedInst : UnlinkedInstructions) {
691  for (unsigned I = 0, E = UnlinkedInst->getNumOperands(); I != E; ++I) {
692  Value *Op = UnlinkedInst->getOperand(I);
693  UnlinkedInst->setOperand(I, nullptr);
695  }
696  delete UnlinkedInst;
697  }
698  bool Ret = !UnlinkedInstructions.empty();
699  UnlinkedInstructions.clear();
700  return Ret;
701 }
FunctionPass * createStraightLineStrengthReducePass()
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:102
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:64
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Type * getSourceElementType() const
Definition: Instructions.h:928
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
Definition: Constants.h:148
unsigned getNumOperands() const
Definition: User.h:167
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
Definition: PatternMatch.h:458
The main scalar evolution driver.
static void unifyBitWidth(APInt &A, APInt &B)
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition: APInt.cpp:1965
int getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands) const
Estimate the cost of a GEP operation when lowered.
static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C)
Hexagon Common GEP
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:41
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:53
static const Value * getNegArgument(const Value *BinOp)
Helper functions to extract the unary argument of a NEG, FNEG or NOT operation implemented via Sub...
static bool matchesOr(Value *A, Value *&B, ConstantInt *&C)
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:143
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:588
unsigned logBase2(const APInt &APIVal)
Returns the floor log base 2 of the specified APInt value.
Definition: APInt.h:1834
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:813
static bool hasOnlyOneNonZeroIndex(GetElementPtrInst *GEP)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
Definition: PatternMatch.h:434
void initializeStraightLineStrengthReducePass(PassRegistry &)
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1362
#define F(x, y, z)
Definition: MD5.cpp:51
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:1323
op_iterator idx_begin()
Definition: Instructions.h:956
static bool isGEPFoldable(GetElementPtrInst *GEP, const TargetTransformInfo *TTI)
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:75
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:835
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce,"slsr","Straight line strength reduction", false, false) INITIALIZE_PASS_END(StraightLineStrengthReduce
bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return true if LHS and RHS have no common bits set.
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1158
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:96
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:830
bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace=0) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
Wrapper pass for TargetTransformInfo.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Definition: PatternMatch.h:512
Type * getType() const
Return the LLVM type of this SCEV expression.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:219
This is an important base class in LLVM.
Definition: Constant.h:42
Straight line strength reduction
Expected to fold away in lowering.
APInt sext(unsigned width) const
Sign extend to a new width.
Definition: APInt.cpp:939
Represent the analysis usage information of a pass.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
Definition: PatternMatch.h:524
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1044
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1255
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
Value * getOperand(unsigned i) const
Definition: User.h:145
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:96
Class to represent integer types.
Definition: DerivedTypes.h:39
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
Definition: Local.cpp:355
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:654
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:213
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition: APInt.h:391
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:857
unsigned getAddressSpace() const
Returns the address space of this instruction's pointer type.
Definition: Instructions.h:940
CastClass_match< OpTy, Instruction::SExt > m_SExt(const OpTy &Op)
Matches SExt.
Definition: PatternMatch.h:807
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:709
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:234
This is the shared class of boolean and integer constants.
Definition: Constants.h:88
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:408
unsigned logBase2() const
Definition: APInt.h:1507
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
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:230
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:558
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:198
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:276
Straight line strength false
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
Value * CreateGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1141
static bool isNeg(const Value *V)
Check if the given Value is a NEG, FNeg, or NOT instruction.
Class for arbitrary precision integers.
Definition: APInt.h:77
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:337
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:932
bool isAllOnesValue() const
Determine if all bits are set.
Definition: APInt.h:342
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:384
This class represents an analyzed expression in the program.
#define I(x, y, z)
Definition: MD5.cpp:54
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
Definition: PatternMatch.h:593
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:349
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:287
static volatile int Zero
iterator_range< df_iterator< T > > depth_first(const T &G)
const unsigned Kind
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:71
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:111
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
Definition: PatternMatch.h:585
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:217
This pass exposes codegen information to IR-level passes.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:162
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride, TargetTransformInfo *TTI)
gep_type_iterator gep_type_begin(const User *GEP)