blob: 03de393ca7365001d3a217a3cdccbacd606c1e9c [file] [log] [blame]
Jingyue Wud7966ff2015-02-03 19:37:06 +00001//===-- 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
Jingyue Wu43885eb2015-04-15 16:46:13 +000018// reduction candidates in the following forms:
Jingyue Wud7966ff2015-02-03 19:37:06 +000019//
Jingyue Wu43885eb2015-04-15 16:46:13 +000020// Form 1: B + i * S
21// Form 2: (B + i) * S
22// Form 3: &B[i * S]
Jingyue Wud7966ff2015-02-03 19:37:06 +000023//
Jingyue Wu177a8152015-03-26 16:49:24 +000024// where S is an integer variable, and i is a constant integer. If we found two
Jingyue Wu43885eb2015-04-15 16:46:13 +000025// 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
Jingyue Wud7966ff2015-02-03 19:37:06 +000030//
Jingyue Wu177a8152015-03-26 16:49:24 +000031// S1: X = (B + i) * S
Jingyue Wu43885eb2015-04-15 16:46:13 +000032// S2: Y = (B + i') * S => X + (i' - i) * S
Jingyue Wu177a8152015-03-26 16:49:24 +000033//
34// S1: X = &B[i * S]
Jingyue Wu43885eb2015-04-15 16:46:13 +000035// S2: Y = &B[i' * S] => &X[(i' - i) * S]
Jingyue Wud7966ff2015-02-03 19:37:06 +000036//
Jingyue Wu43885eb2015-04-15 16:46:13 +000037// Note: (i' - i) * S is folded to the extent possible.
Jingyue Wud7966ff2015-02-03 19:37:06 +000038//
Jingyue Wu43885eb2015-04-15 16:46:13 +000039// 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.
Jingyue Wud7966ff2015-02-03 19:37:06 +000043//
Jingyue Wu43885eb2015-04-15 16:46:13 +000044// 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.
Jingyue Wud7966ff2015-02-03 19:37:06 +000047//
48// TODO:
49//
Jingyue Wud7966ff2015-02-03 19:37:06 +000050// - 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.
Jingyue Wu43885eb2015-04-15 16:46:13 +000055//
56// - When (i' - i) is constant but i and i' are not, we could still perform
57// SLSR.
Jingyue Wud7966ff2015-02-03 19:37:06 +000058#include <vector>
59
Jingyue Wu177a8152015-03-26 16:49:24 +000060#include "llvm/Analysis/ScalarEvolution.h"
61#include "llvm/Analysis/TargetTransformInfo.h"
Jingyue Wu80a96d292015-05-15 17:07:48 +000062#include "llvm/Analysis/ValueTracking.h"
Jingyue Wu177a8152015-03-26 16:49:24 +000063#include "llvm/IR/DataLayout.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000064#include "llvm/IR/Dominators.h"
65#include "llvm/IR/IRBuilder.h"
66#include "llvm/IR/Module.h"
67#include "llvm/IR/PatternMatch.h"
68#include "llvm/Support/raw_ostream.h"
69#include "llvm/Transforms/Scalar.h"
Jingyue Wuf1edf3e2015-04-21 19:56:18 +000070#include "llvm/Transforms/Utils/Local.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000071
72using namespace llvm;
73using namespace PatternMatch;
74
75namespace {
76
77class StraightLineStrengthReduce : public FunctionPass {
Jingyue Wu177a8152015-03-26 16:49:24 +000078public:
Jingyue Wu43885eb2015-04-15 16:46:13 +000079 // SLSR candidate. Such a candidate must be in one of the forms described in
80 // the header comments.
Jingyue Wud7966ff2015-02-03 19:37:06 +000081 struct Candidate : public ilist_node<Candidate> {
Jingyue Wu177a8152015-03-26 16:49:24 +000082 enum Kind {
83 Invalid, // reserved for the default constructor
Jingyue Wu43885eb2015-04-15 16:46:13 +000084 Add, // B + i * S
Jingyue Wu177a8152015-03-26 16:49:24 +000085 Mul, // (B + i) * S
86 GEP, // &B[..][i * S][..]
87 };
88
89 Candidate()
90 : CandidateKind(Invalid), Base(nullptr), Index(nullptr),
91 Stride(nullptr), Ins(nullptr), Basis(nullptr) {}
92 Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
93 Instruction *I)
94 : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I),
95 Basis(nullptr) {}
96 Kind CandidateKind;
97 const SCEV *Base;
Jingyue Wu43885eb2015-04-15 16:46:13 +000098 // Note that Index and Stride of a GEP candidate do not necessarily have the
99 // same integer type. In that case, during rewriting, Stride will be
Jingyue Wu177a8152015-03-26 16:49:24 +0000100 // sign-extended or truncated to Index's type.
Jingyue Wud7966ff2015-02-03 19:37:06 +0000101 ConstantInt *Index;
102 Value *Stride;
103 // The instruction this candidate corresponds to. It helps us to rewrite a
104 // candidate with respect to its immediate basis. Note that one instruction
Jingyue Wu43885eb2015-04-15 16:46:13 +0000105 // can correspond to multiple candidates depending on how you associate the
Jingyue Wud7966ff2015-02-03 19:37:06 +0000106 // expression. For instance,
107 //
108 // (a + 1) * (b + 2)
109 //
110 // can be treated as
111 //
112 // <Base: a, Index: 1, Stride: b + 2>
113 //
114 // or
115 //
116 // <Base: b, Index: 2, Stride: a + 1>
117 Instruction *Ins;
118 // Points to the immediate basis of this candidate, or nullptr if we cannot
119 // find any basis for this candidate.
120 Candidate *Basis;
121 };
122
123 static char ID;
124
Jingyue Wu177a8152015-03-26 16:49:24 +0000125 StraightLineStrengthReduce()
126 : FunctionPass(ID), DL(nullptr), DT(nullptr), TTI(nullptr) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000127 initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
128 }
129
130 void getAnalysisUsage(AnalysisUsage &AU) const override {
131 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000132 AU.addRequired<ScalarEvolutionWrapperPass>();
Jingyue Wu177a8152015-03-26 16:49:24 +0000133 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000134 // We do not modify the shape of the CFG.
135 AU.setPreservesCFG();
136 }
137
Jingyue Wu177a8152015-03-26 16:49:24 +0000138 bool doInitialization(Module &M) override {
139 DL = &M.getDataLayout();
140 return false;
141 }
142
Jingyue Wud7966ff2015-02-03 19:37:06 +0000143 bool runOnFunction(Function &F) override;
144
Jingyue Wu177a8152015-03-26 16:49:24 +0000145private:
Jingyue Wud7966ff2015-02-03 19:37:06 +0000146 // Returns true if Basis is a basis for C, i.e., Basis dominates C and they
147 // share the same base and stride.
148 bool isBasisFor(const Candidate &Basis, const Candidate &C);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000149 // Returns whether the candidate can be folded into an addressing mode.
150 bool isFoldable(const Candidate &C, TargetTransformInfo *TTI,
151 const DataLayout *DL);
152 // Returns true if C is already in a simplest form and not worth being
153 // rewritten.
154 bool isSimplestForm(const Candidate &C);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000155 // Checks whether I is in a candidate form. If so, adds all the matching forms
156 // to Candidates, and tries to find the immediate basis for each of them.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000157 void allocateCandidatesAndFindBasis(Instruction *I);
158 // Allocate candidates and find bases for Add instructions.
159 void allocateCandidatesAndFindBasisForAdd(Instruction *I);
160 // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
161 // candidate.
162 void allocateCandidatesAndFindBasisForAdd(Value *LHS, Value *RHS,
163 Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000164 // Allocate candidates and find bases for Mul instructions.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000165 void allocateCandidatesAndFindBasisForMul(Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000166 // Splits LHS into Base + Index and, if succeeds, calls
Jingyue Wu43885eb2015-04-15 16:46:13 +0000167 // allocateCandidatesAndFindBasis.
168 void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS,
169 Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000170 // Allocate candidates and find bases for GetElementPtr instructions.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000171 void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000172 // A helper function that scales Idx with ElementSize before invoking
Jingyue Wu43885eb2015-04-15 16:46:13 +0000173 // allocateCandidatesAndFindBasis.
174 void allocateCandidatesAndFindBasisForGEP(const SCEV *B, ConstantInt *Idx,
175 Value *S, uint64_t ElementSize,
176 Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000177 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
178 // basis.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000179 void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B,
180 ConstantInt *Idx, Value *S,
181 Instruction *I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000182 // Rewrites candidate C with respect to Basis.
183 void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
Jingyue Wu177a8152015-03-26 16:49:24 +0000184 // A helper function that factors ArrayIdx to a product of a stride and a
Jingyue Wu43885eb2015-04-15 16:46:13 +0000185 // constant index, and invokes allocateCandidatesAndFindBasis with the
Jingyue Wu177a8152015-03-26 16:49:24 +0000186 // factorings.
187 void factorArrayIndex(Value *ArrayIdx, const SCEV *Base, uint64_t ElementSize,
188 GetElementPtrInst *GEP);
189 // Emit code that computes the "bump" from Basis to C. If the candidate is a
190 // GEP and the bump is not divisible by the element size of the GEP, this
191 // function sets the BumpWithUglyGEP flag to notify its caller to bump the
192 // basis using an ugly GEP.
193 static Value *emitBump(const Candidate &Basis, const Candidate &C,
194 IRBuilder<> &Builder, const DataLayout *DL,
195 bool &BumpWithUglyGEP);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000196
Jingyue Wu177a8152015-03-26 16:49:24 +0000197 const DataLayout *DL;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000198 DominatorTree *DT;
Jingyue Wu177a8152015-03-26 16:49:24 +0000199 ScalarEvolution *SE;
200 TargetTransformInfo *TTI;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000201 ilist<Candidate> Candidates;
202 // Temporarily holds all instructions that are unlinked (but not deleted) by
203 // rewriteCandidateWithBasis. These instructions will be actually removed
204 // after all rewriting finishes.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000205 std::vector<Instruction *> UnlinkedInstructions;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000206};
207} // anonymous namespace
208
209char StraightLineStrengthReduce::ID = 0;
210INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
211 "Straight line strength reduction", false, false)
212INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000213INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Jingyue Wu177a8152015-03-26 16:49:24 +0000214INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Jingyue Wud7966ff2015-02-03 19:37:06 +0000215INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
216 "Straight line strength reduction", false, false)
217
218FunctionPass *llvm::createStraightLineStrengthReducePass() {
219 return new StraightLineStrengthReduce();
220}
221
222bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
223 const Candidate &C) {
224 return (Basis.Ins != C.Ins && // skip the same instruction
Jingyue Wu3abde7b2015-06-28 17:45:05 +0000225 // They must have the same type too. Basis.Base == C.Base doesn't
226 // guarantee their types are the same (PR23975).
227 Basis.Ins->getType() == C.Ins->getType() &&
Jingyue Wud7966ff2015-02-03 19:37:06 +0000228 // Basis must dominate C in order to rewrite C with respect to Basis.
229 DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000230 // They share the same base, stride, and candidate kind.
Jingyue Wu3abde7b2015-06-28 17:45:05 +0000231 Basis.Base == C.Base && Basis.Stride == C.Stride &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000232 Basis.CandidateKind == C.CandidateKind);
233}
234
Jingyue Wubfefff52015-07-26 19:10:03 +0000235// TODO: use TTI->getGEPCost.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000236static bool isGEPFoldable(GetElementPtrInst *GEP,
237 const TargetTransformInfo *TTI,
238 const DataLayout *DL) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000239 GlobalVariable *BaseGV = nullptr;
240 int64_t BaseOffset = 0;
241 bool HasBaseReg = false;
242 int64_t Scale = 0;
243
244 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
245 BaseGV = GV;
246 else
247 HasBaseReg = true;
248
249 gep_type_iterator GTI = gep_type_begin(GEP);
250 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) {
251 if (isa<SequentialType>(*GTI)) {
252 int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
253 if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
254 BaseOffset += ConstIdx->getSExtValue() * ElementSize;
255 } else {
256 // Needs scale register.
257 if (Scale != 0) {
258 // No addressing mode takes two scale registers.
259 return false;
260 }
261 Scale = ElementSize;
262 }
263 } else {
264 StructType *STy = cast<StructType>(*GTI);
265 uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
266 BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
267 }
268 }
Matt Arsenault91f90e62015-06-11 16:13:39 +0000269
270 unsigned AddrSpace = GEP->getPointerAddressSpace();
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000271 return TTI->isLegalAddressingMode(GEP->getResultElementType(), BaseGV,
Matt Arsenault91f90e62015-06-11 16:13:39 +0000272 BaseOffset, HasBaseReg, Scale, AddrSpace);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000273}
274
Jingyue Wu43885eb2015-04-15 16:46:13 +0000275// Returns whether (Base + Index * Stride) can be folded to an addressing mode.
276static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
277 TargetTransformInfo *TTI) {
278 return TTI->isLegalAddressingMode(Base->getType(), nullptr, 0, true,
279 Index->getSExtValue());
280}
281
282bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
283 TargetTransformInfo *TTI,
284 const DataLayout *DL) {
285 if (C.CandidateKind == Candidate::Add)
286 return isAddFoldable(C.Base, C.Index, C.Stride, TTI);
287 if (C.CandidateKind == Candidate::GEP)
288 return isGEPFoldable(cast<GetElementPtrInst>(C.Ins), TTI, DL);
289 return false;
290}
291
292// Returns true if GEP has zero or one non-zero index.
293static bool hasOnlyOneNonZeroIndex(GetElementPtrInst *GEP) {
294 unsigned NumNonZeroIndices = 0;
295 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) {
296 ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
297 if (ConstIdx == nullptr || !ConstIdx->isZero())
298 ++NumNonZeroIndices;
299 }
300 return NumNonZeroIndices <= 1;
301}
302
303bool StraightLineStrengthReduce::isSimplestForm(const Candidate &C) {
304 if (C.CandidateKind == Candidate::Add) {
305 // B + 1 * S or B + (-1) * S
306 return C.Index->isOne() || C.Index->isMinusOne();
307 }
308 if (C.CandidateKind == Candidate::Mul) {
309 // (B + 0) * S
310 return C.Index->isZero();
311 }
312 if (C.CandidateKind == Candidate::GEP) {
313 // (char*)B + S or (char*)B - S
314 return ((C.Index->isOne() || C.Index->isMinusOne()) &&
315 hasOnlyOneNonZeroIndex(cast<GetElementPtrInst>(C.Ins)));
316 }
317 return false;
318}
319
320// TODO: We currently implement an algorithm whose time complexity is linear in
321// the number of existing candidates. However, we could do better by using
322// ScopedHashTable. Specifically, while traversing the dominator tree, we could
323// maintain all the candidates that dominate the basic block being traversed in
324// a ScopedHashTable. This hash table is indexed by the base and the stride of
325// a candidate. Therefore, finding the immediate basis of a candidate boils down
326// to one hash-table look up.
327void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
Jingyue Wu177a8152015-03-26 16:49:24 +0000328 Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
329 Instruction *I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000330 Candidate C(CT, B, Idx, S, I);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000331 // SLSR can complicate an instruction in two cases:
332 //
333 // 1. If we can fold I into an addressing mode, computing I is likely free or
334 // takes only one instruction.
335 //
336 // 2. I is already in a simplest form. For example, when
337 // X = B + 8 * S
338 // Y = B + S,
339 // rewriting Y to X - 7 * S is probably a bad idea.
340 //
341 // In the above cases, we still add I to the candidate list so that I can be
342 // the basis of other candidates, but we leave I's basis blank so that I
343 // won't be rewritten.
344 if (!isFoldable(C, TTI, DL) && !isSimplestForm(C)) {
345 // Try to compute the immediate basis of C.
346 unsigned NumIterations = 0;
347 // Limit the scan radius to avoid running in quadratice time.
348 static const unsigned MaxNumIterations = 50;
349 for (auto Basis = Candidates.rbegin();
350 Basis != Candidates.rend() && NumIterations < MaxNumIterations;
351 ++Basis, ++NumIterations) {
352 if (isBasisFor(*Basis, C)) {
353 C.Basis = &(*Basis);
354 break;
355 }
Jingyue Wud7966ff2015-02-03 19:37:06 +0000356 }
357 }
358 // Regardless of whether we find a basis for C, we need to push C to the
Jingyue Wu43885eb2015-04-15 16:46:13 +0000359 // candidate list so that it can be the basis of other candidates.
Jingyue Wud7966ff2015-02-03 19:37:06 +0000360 Candidates.push_back(C);
361}
362
Jingyue Wu43885eb2015-04-15 16:46:13 +0000363void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
364 Instruction *I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000365 switch (I->getOpcode()) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000366 case Instruction::Add:
367 allocateCandidatesAndFindBasisForAdd(I);
368 break;
Jingyue Wu177a8152015-03-26 16:49:24 +0000369 case Instruction::Mul:
Jingyue Wu43885eb2015-04-15 16:46:13 +0000370 allocateCandidatesAndFindBasisForMul(I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000371 break;
372 case Instruction::GetElementPtr:
Jingyue Wu43885eb2015-04-15 16:46:13 +0000373 allocateCandidatesAndFindBasisForGEP(cast<GetElementPtrInst>(I));
Jingyue Wu177a8152015-03-26 16:49:24 +0000374 break;
375 }
376}
377
Jingyue Wu43885eb2015-04-15 16:46:13 +0000378void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
379 Instruction *I) {
380 // Try matching B + i * S.
381 if (!isa<IntegerType>(I->getType()))
382 return;
383
384 assert(I->getNumOperands() == 2 && "isn't I an add?");
385 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
386 allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
387 if (LHS != RHS)
388 allocateCandidatesAndFindBasisForAdd(RHS, LHS, I);
389}
390
391void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
392 Value *LHS, Value *RHS, Instruction *I) {
393 Value *S = nullptr;
394 ConstantInt *Idx = nullptr;
395 if (match(RHS, m_Mul(m_Value(S), m_ConstantInt(Idx)))) {
396 // I = LHS + RHS = LHS + Idx * S
397 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
398 } else if (match(RHS, m_Shl(m_Value(S), m_ConstantInt(Idx)))) {
399 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
400 APInt One(Idx->getBitWidth(), 1);
401 Idx = ConstantInt::get(Idx->getContext(), One << Idx->getValue());
402 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
403 } else {
404 // At least, I = LHS + 1 * RHS
405 ConstantInt *One = ConstantInt::get(cast<IntegerType>(I->getType()), 1);
406 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), One, RHS,
407 I);
408 }
409}
410
Jingyue Wu80a96d292015-05-15 17:07:48 +0000411// Returns true if A matches B + C where C is constant.
412static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
413 return (match(A, m_Add(m_Value(B), m_ConstantInt(C))) ||
414 match(A, m_Add(m_ConstantInt(C), m_Value(B))));
415}
416
417// Returns true if A matches B | C where C is constant.
418static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
419 return (match(A, m_Or(m_Value(B), m_ConstantInt(C))) ||
420 match(A, m_Or(m_ConstantInt(C), m_Value(B))));
421}
422
Jingyue Wu43885eb2015-04-15 16:46:13 +0000423void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
Jingyue Wu177a8152015-03-26 16:49:24 +0000424 Value *LHS, Value *RHS, Instruction *I) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000425 Value *B = nullptr;
426 ConstantInt *Idx = nullptr;
Jingyue Wu80a96d292015-05-15 17:07:48 +0000427 if (matchesAdd(LHS, B, Idx)) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000428 // If LHS is in the form of "Base + Index", then I is in the form of
429 // "(Base + Index) * RHS".
Jingyue Wu43885eb2015-04-15 16:46:13 +0000430 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
Jingyue Wu80a96d292015-05-15 17:07:48 +0000431 } else if (matchesOr(LHS, B, Idx) && haveNoCommonBitsSet(B, Idx, *DL)) {
432 // If LHS is in the form of "Base | Index" and Base and Index have no common
433 // bits set, then
434 // Base | Index = Base + Index
435 // and I is thus in the form of "(Base + Index) * RHS".
436 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000437 } else {
438 // Otherwise, at least try the form (LHS + 0) * RHS.
439 ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000440 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS,
Jingyue Wu80a96d292015-05-15 17:07:48 +0000441 I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000442 }
443}
444
Jingyue Wu43885eb2015-04-15 16:46:13 +0000445void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
Jingyue Wu177a8152015-03-26 16:49:24 +0000446 Instruction *I) {
447 // Try matching (B + i) * S.
448 // TODO: we could extend SLSR to float and vector types.
449 if (!isa<IntegerType>(I->getType()))
450 return;
451
Jingyue Wu43885eb2015-04-15 16:46:13 +0000452 assert(I->getNumOperands() == 2 && "isn't I a mul?");
Jingyue Wu177a8152015-03-26 16:49:24 +0000453 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000454 allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000455 if (LHS != RHS) {
456 // Symmetrically, try to split RHS to Base + Index.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000457 allocateCandidatesAndFindBasisForMul(RHS, LHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000458 }
459}
460
Jingyue Wu43885eb2015-04-15 16:46:13 +0000461void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000462 const SCEV *B, ConstantInt *Idx, Value *S, uint64_t ElementSize,
463 Instruction *I) {
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000464 // I = B + sext(Idx *nsw S) * ElementSize
465 // = B + (sext(Idx) * sext(S)) * ElementSize
Jingyue Wu177a8152015-03-26 16:49:24 +0000466 // = B + (sext(Idx) * ElementSize) * sext(S)
467 // Casting to IntegerType is safe because we skipped vector GEPs.
468 IntegerType *IntPtrTy = cast<IntegerType>(DL->getIntPtrType(I->getType()));
469 ConstantInt *ScaledIdx = ConstantInt::get(
470 IntPtrTy, Idx->getSExtValue() * (int64_t)ElementSize, true);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000471 allocateCandidatesAndFindBasis(Candidate::GEP, B, ScaledIdx, S, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000472}
473
474void StraightLineStrengthReduce::factorArrayIndex(Value *ArrayIdx,
475 const SCEV *Base,
476 uint64_t ElementSize,
477 GetElementPtrInst *GEP) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000478 // At least, ArrayIdx = ArrayIdx *nsw 1.
479 allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000480 Base, ConstantInt::get(cast<IntegerType>(ArrayIdx->getType()), 1),
481 ArrayIdx, ElementSize, GEP);
482 Value *LHS = nullptr;
483 ConstantInt *RHS = nullptr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000484 // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
485 // itself. This would allow us to handle the shl case for free. However,
486 // matching SCEVs has two issues:
487 //
488 // 1. this would complicate rewriting because the rewriting procedure
489 // would have to translate SCEVs back to IR instructions. This translation
490 // is difficult when LHS is further evaluated to a composite SCEV.
491 //
492 // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
493 // to strip nsw/nuw flags which are critical for SLSR to trace into
494 // sext'ed multiplication.
495 if (match(ArrayIdx, m_NSWMul(m_Value(LHS), m_ConstantInt(RHS)))) {
496 // SLSR is currently unsafe if i * S may overflow.
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000497 // GEP = Base + sext(LHS *nsw RHS) * ElementSize
Jingyue Wu43885eb2015-04-15 16:46:13 +0000498 allocateCandidatesAndFindBasisForGEP(Base, RHS, LHS, ElementSize, GEP);
Jingyue Wu96d74002015-04-06 17:15:48 +0000499 } else if (match(ArrayIdx, m_NSWShl(m_Value(LHS), m_ConstantInt(RHS)))) {
500 // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
501 // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
502 APInt One(RHS->getBitWidth(), 1);
503 ConstantInt *PowerOf2 =
504 ConstantInt::get(RHS->getContext(), One << RHS->getValue());
Jingyue Wu43885eb2015-04-15 16:46:13 +0000505 allocateCandidatesAndFindBasisForGEP(Base, PowerOf2, LHS, ElementSize, GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000506 }
507}
508
Jingyue Wu43885eb2015-04-15 16:46:13 +0000509void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000510 GetElementPtrInst *GEP) {
511 // TODO: handle vector GEPs
512 if (GEP->getType()->isVectorTy())
513 return;
514
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000515 SmallVector<const SCEV *, 4> IndexExprs;
516 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
517 IndexExprs.push_back(SE->getSCEV(*I));
Jingyue Wu177a8152015-03-26 16:49:24 +0000518
519 gep_type_iterator GTI = gep_type_begin(GEP);
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000520 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000521 if (!isa<SequentialType>(*GTI++))
522 continue;
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000523
524 const SCEV *OrigIndexExpr = IndexExprs[I - 1];
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000525 IndexExprs[I - 1] = SE->getZero(OrigIndexExpr->getType());
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000526
527 // The base of this candidate is GEP's base plus the offsets of all
528 // indices except this current one.
529 const SCEV *BaseExpr = SE->getGEPExpr(GEP->getSourceElementType(),
530 SE->getSCEV(GEP->getPointerOperand()),
531 IndexExprs, GEP->isInBounds());
532 Value *ArrayIdx = GEP->getOperand(I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000533 uint64_t ElementSize = DL->getTypeAllocSize(*GTI);
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000534 factorArrayIndex(ArrayIdx, BaseExpr, ElementSize, GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000535 // When ArrayIdx is the sext of a value, we try to factor that value as
536 // well. Handling this case is important because array indices are
537 // typically sign-extended to the pointer size.
538 Value *TruncatedArrayIdx = nullptr;
539 if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))))
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000540 factorArrayIndex(TruncatedArrayIdx, BaseExpr, ElementSize, GEP);
541
542 IndexExprs[I - 1] = OrigIndexExpr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000543 }
544}
545
546// A helper function that unifies the bitwidth of A and B.
547static void unifyBitWidth(APInt &A, APInt &B) {
548 if (A.getBitWidth() < B.getBitWidth())
549 A = A.sext(B.getBitWidth());
550 else if (A.getBitWidth() > B.getBitWidth())
551 B = B.sext(A.getBitWidth());
552}
553
554Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
555 const Candidate &C,
556 IRBuilder<> &Builder,
557 const DataLayout *DL,
558 bool &BumpWithUglyGEP) {
559 APInt Idx = C.Index->getValue(), BasisIdx = Basis.Index->getValue();
560 unifyBitWidth(Idx, BasisIdx);
561 APInt IndexOffset = Idx - BasisIdx;
562
563 BumpWithUglyGEP = false;
564 if (Basis.CandidateKind == Candidate::GEP) {
565 APInt ElementSize(
566 IndexOffset.getBitWidth(),
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000567 DL->getTypeAllocSize(cast<GetElementPtrInst>(Basis.Ins)->getResultElementType()));
Jingyue Wu177a8152015-03-26 16:49:24 +0000568 APInt Q, R;
569 APInt::sdivrem(IndexOffset, ElementSize, Q, R);
570 if (R.getSExtValue() == 0)
571 IndexOffset = Q;
572 else
573 BumpWithUglyGEP = true;
574 }
Jingyue Wu43885eb2015-04-15 16:46:13 +0000575
Jingyue Wu177a8152015-03-26 16:49:24 +0000576 // Compute Bump = C - Basis = (i' - i) * S.
577 // Common case 1: if (i' - i) is 1, Bump = S.
578 if (IndexOffset.getSExtValue() == 1)
579 return C.Stride;
580 // Common case 2: if (i' - i) is -1, Bump = -S.
581 if (IndexOffset.getSExtValue() == -1)
582 return Builder.CreateNeg(C.Stride);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000583
584 // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may
585 // have different bit widths.
586 IntegerType *DeltaType =
587 IntegerType::get(Basis.Ins->getContext(), IndexOffset.getBitWidth());
588 Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, DeltaType);
589 if (IndexOffset.isPowerOf2()) {
590 // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i).
591 ConstantInt *Exponent = ConstantInt::get(DeltaType, IndexOffset.logBase2());
592 return Builder.CreateShl(ExtendedStride, Exponent);
593 }
594 if ((-IndexOffset).isPowerOf2()) {
595 // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i).
596 ConstantInt *Exponent =
597 ConstantInt::get(DeltaType, (-IndexOffset).logBase2());
598 return Builder.CreateNeg(Builder.CreateShl(ExtendedStride, Exponent));
599 }
600 Constant *Delta = ConstantInt::get(DeltaType, IndexOffset);
Jingyue Wu177a8152015-03-26 16:49:24 +0000601 return Builder.CreateMul(ExtendedStride, Delta);
602}
603
Jingyue Wud7966ff2015-02-03 19:37:06 +0000604void StraightLineStrengthReduce::rewriteCandidateWithBasis(
605 const Candidate &C, const Candidate &Basis) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000606 assert(C.CandidateKind == Basis.CandidateKind && C.Base == Basis.Base &&
607 C.Stride == Basis.Stride);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000608 // We run rewriteCandidateWithBasis on all candidates in a post-order, so the
609 // basis of a candidate cannot be unlinked before the candidate.
610 assert(Basis.Ins->getParent() != nullptr && "the basis is unlinked");
Jingyue Wu177a8152015-03-26 16:49:24 +0000611
Jingyue Wud7966ff2015-02-03 19:37:06 +0000612 // An instruction can correspond to multiple candidates. Therefore, instead of
613 // simply deleting an instruction when we rewrite it, we mark its parent as
614 // nullptr (i.e. unlink it) so that we can skip the candidates whose
615 // instruction is already rewritten.
616 if (!C.Ins->getParent())
617 return;
Jingyue Wu177a8152015-03-26 16:49:24 +0000618
Jingyue Wud7966ff2015-02-03 19:37:06 +0000619 IRBuilder<> Builder(C.Ins);
Jingyue Wu177a8152015-03-26 16:49:24 +0000620 bool BumpWithUglyGEP;
621 Value *Bump = emitBump(Basis, C, Builder, DL, BumpWithUglyGEP);
622 Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
623 switch (C.CandidateKind) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000624 case Candidate::Add:
Jingyue Wu177a8152015-03-26 16:49:24 +0000625 case Candidate::Mul:
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000626 // C = Basis + Bump
Jingyue Wu43885eb2015-04-15 16:46:13 +0000627 if (BinaryOperator::isNeg(Bump)) {
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000628 // If Bump is a neg instruction, emit C = Basis - (-Bump).
Jingyue Wu43885eb2015-04-15 16:46:13 +0000629 Reduced =
630 Builder.CreateSub(Basis.Ins, BinaryOperator::getNegArgument(Bump));
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000631 // We only use the negative argument of Bump, and Bump itself may be
632 // trivially dead.
633 RecursivelyDeleteTriviallyDeadInstructions(Bump);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000634 } else {
Jingyue Wua9411292015-06-18 03:35:57 +0000635 // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
636 // usually unsound, e.g.,
637 //
638 // X = (-2 +nsw 1) *nsw INT_MAX
639 // Y = (-2 +nsw 3) *nsw INT_MAX
640 // =>
641 // Y = X + 2 * INT_MAX
642 //
643 // Neither + and * in the resultant expression are nsw.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000644 Reduced = Builder.CreateAdd(Basis.Ins, Bump);
645 }
Jingyue Wu177a8152015-03-26 16:49:24 +0000646 break;
647 case Candidate::GEP:
648 {
649 Type *IntPtrTy = DL->getIntPtrType(C.Ins->getType());
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000650 bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds();
Jingyue Wu177a8152015-03-26 16:49:24 +0000651 if (BumpWithUglyGEP) {
652 // C = (char *)Basis + Bump
653 unsigned AS = Basis.Ins->getType()->getPointerAddressSpace();
654 Type *CharTy = Type::getInt8PtrTy(Basis.Ins->getContext(), AS);
655 Reduced = Builder.CreateBitCast(Basis.Ins, CharTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000656 if (InBounds)
David Blaikieaa41cd52015-04-03 21:33:42 +0000657 Reduced =
658 Builder.CreateInBoundsGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000659 else
David Blaikie93c54442015-04-03 19:41:44 +0000660 Reduced = Builder.CreateGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000661 Reduced = Builder.CreateBitCast(Reduced, C.Ins->getType());
662 } else {
663 // C = gep Basis, Bump
664 // Canonicalize bump to pointer size.
665 Bump = Builder.CreateSExtOrTrunc(Bump, IntPtrTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000666 if (InBounds)
David Blaikieaa41cd52015-04-03 21:33:42 +0000667 Reduced = Builder.CreateInBoundsGEP(nullptr, Basis.Ins, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000668 else
David Blaikie93c54442015-04-03 19:41:44 +0000669 Reduced = Builder.CreateGEP(nullptr, Basis.Ins, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000670 }
671 }
672 break;
673 default:
674 llvm_unreachable("C.CandidateKind is invalid");
675 };
Jingyue Wud7966ff2015-02-03 19:37:06 +0000676 Reduced->takeName(C.Ins);
677 C.Ins->replaceAllUsesWith(Reduced);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000678 // Unlink C.Ins so that we can skip other candidates also corresponding to
679 // C.Ins. The actual deletion is postponed to the end of runOnFunction.
680 C.Ins->removeFromParent();
Jingyue Wu43885eb2015-04-15 16:46:13 +0000681 UnlinkedInstructions.push_back(C.Ins);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000682}
683
684bool StraightLineStrengthReduce::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000685 if (skipFunction(F))
Jingyue Wud7966ff2015-02-03 19:37:06 +0000686 return false;
687
Jingyue Wu177a8152015-03-26 16:49:24 +0000688 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000689 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000690 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000691 // Traverse the dominator tree in the depth-first order. This order makes sure
692 // all bases of a candidate are in Candidates when we process it.
693 for (auto node = GraphTraits<DominatorTree *>::nodes_begin(DT);
694 node != GraphTraits<DominatorTree *>::nodes_end(DT); ++node) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000695 for (auto &I : *node->getBlock())
Jingyue Wu43885eb2015-04-15 16:46:13 +0000696 allocateCandidatesAndFindBasis(&I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000697 }
698
699 // Rewrite candidates in the reverse depth-first order. This order makes sure
700 // a candidate being rewritten is not a basis for any other candidate.
701 while (!Candidates.empty()) {
702 const Candidate &C = Candidates.back();
703 if (C.Basis != nullptr) {
704 rewriteCandidateWithBasis(C, *C.Basis);
705 }
706 Candidates.pop_back();
707 }
708
709 // Delete all unlink instructions.
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000710 for (auto *UnlinkedInst : UnlinkedInstructions) {
711 for (unsigned I = 0, E = UnlinkedInst->getNumOperands(); I != E; ++I) {
712 Value *Op = UnlinkedInst->getOperand(I);
713 UnlinkedInst->setOperand(I, nullptr);
714 RecursivelyDeleteTriviallyDeadInstructions(Op);
715 }
716 delete UnlinkedInst;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000717 }
718 bool Ret = !UnlinkedInstructions.empty();
719 UnlinkedInstructions.clear();
720 return Ret;
721}