blob: 453503ab61da66a433d472a5475b087bb53a161c [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
60#include "llvm/ADT/DenseSet.h"
Jingyue Wu177a8152015-03-26 16:49:24 +000061#include "llvm/ADT/FoldingSet.h"
62#include "llvm/Analysis/ScalarEvolution.h"
63#include "llvm/Analysis/TargetTransformInfo.h"
Jingyue Wu80a96d292015-05-15 17:07:48 +000064#include "llvm/Analysis/ValueTracking.h"
Jingyue Wu177a8152015-03-26 16:49:24 +000065#include "llvm/IR/DataLayout.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000066#include "llvm/IR/Dominators.h"
67#include "llvm/IR/IRBuilder.h"
68#include "llvm/IR/Module.h"
69#include "llvm/IR/PatternMatch.h"
70#include "llvm/Support/raw_ostream.h"
71#include "llvm/Transforms/Scalar.h"
Jingyue Wuf1edf3e2015-04-21 19:56:18 +000072#include "llvm/Transforms/Utils/Local.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000073
74using namespace llvm;
75using namespace PatternMatch;
76
77namespace {
78
79class StraightLineStrengthReduce : public FunctionPass {
Jingyue Wu177a8152015-03-26 16:49:24 +000080public:
Jingyue Wu43885eb2015-04-15 16:46:13 +000081 // SLSR candidate. Such a candidate must be in one of the forms described in
82 // the header comments.
Jingyue Wud7966ff2015-02-03 19:37:06 +000083 struct Candidate : public ilist_node<Candidate> {
Jingyue Wu177a8152015-03-26 16:49:24 +000084 enum Kind {
85 Invalid, // reserved for the default constructor
Jingyue Wu43885eb2015-04-15 16:46:13 +000086 Add, // B + i * S
Jingyue Wu177a8152015-03-26 16:49:24 +000087 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;
Jingyue Wu43885eb2015-04-15 16:46:13 +0000100 // 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
Jingyue Wu177a8152015-03-26 16:49:24 +0000102 // sign-extended or truncated to Index's type.
Jingyue Wud7966ff2015-02-03 19:37:06 +0000103 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
Jingyue Wu43885eb2015-04-15 16:46:13 +0000107 // can correspond to multiple candidates depending on how you associate the
Jingyue Wud7966ff2015-02-03 19:37:06 +0000108 // 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
Jingyue Wu177a8152015-03-26 16:49:24 +0000127 StraightLineStrengthReduce()
128 : FunctionPass(ID), DL(nullptr), DT(nullptr), TTI(nullptr) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000129 initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
130 }
131
132 void getAnalysisUsage(AnalysisUsage &AU) const override {
133 AU.addRequired<DominatorTreeWrapperPass>();
Jingyue Wu177a8152015-03-26 16:49:24 +0000134 AU.addRequired<ScalarEvolution>();
135 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000136 // We do not modify the shape of the CFG.
137 AU.setPreservesCFG();
138 }
139
Jingyue Wu177a8152015-03-26 16:49:24 +0000140 bool doInitialization(Module &M) override {
141 DL = &M.getDataLayout();
142 return false;
143 }
144
Jingyue Wud7966ff2015-02-03 19:37:06 +0000145 bool runOnFunction(Function &F) override;
146
Jingyue Wu177a8152015-03-26 16:49:24 +0000147private:
Jingyue Wud7966ff2015-02-03 19:37:06 +0000148 // 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);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000151 // 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);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000157 // 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.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000159 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);
Jingyue Wu177a8152015-03-26 16:49:24 +0000166 // Allocate candidates and find bases for Mul instructions.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000167 void allocateCandidatesAndFindBasisForMul(Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000168 // Splits LHS into Base + Index and, if succeeds, calls
Jingyue Wu43885eb2015-04-15 16:46:13 +0000169 // allocateCandidatesAndFindBasis.
170 void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS,
171 Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000172 // Allocate candidates and find bases for GetElementPtr instructions.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000173 void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000174 // A helper function that scales Idx with ElementSize before invoking
Jingyue Wu43885eb2015-04-15 16:46:13 +0000175 // allocateCandidatesAndFindBasis.
176 void allocateCandidatesAndFindBasisForGEP(const SCEV *B, ConstantInt *Idx,
177 Value *S, uint64_t ElementSize,
178 Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000179 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
180 // basis.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000181 void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B,
182 ConstantInt *Idx, Value *S,
183 Instruction *I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000184 // Rewrites candidate C with respect to Basis.
185 void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
Jingyue Wu177a8152015-03-26 16:49:24 +0000186 // A helper function that factors ArrayIdx to a product of a stride and a
Jingyue Wu43885eb2015-04-15 16:46:13 +0000187 // constant index, and invokes allocateCandidatesAndFindBasis with the
Jingyue Wu177a8152015-03-26 16:49:24 +0000188 // factorings.
189 void factorArrayIndex(Value *ArrayIdx, const SCEV *Base, uint64_t ElementSize,
190 GetElementPtrInst *GEP);
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);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000198
Jingyue Wu177a8152015-03-26 16:49:24 +0000199 const DataLayout *DL;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000200 DominatorTree *DT;
Jingyue Wu177a8152015-03-26 16:49:24 +0000201 ScalarEvolution *SE;
202 TargetTransformInfo *TTI;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000203 ilist<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.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000207 std::vector<Instruction *> UnlinkedInstructions;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000208};
209} // anonymous namespace
210
211char StraightLineStrengthReduce::ID = 0;
212INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
213 "Straight line strength reduction", false, false)
214INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Jingyue Wu177a8152015-03-26 16:49:24 +0000215INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
216INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Jingyue Wud7966ff2015-02-03 19:37:06 +0000217INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
218 "Straight line strength reduction", false, false)
219
220FunctionPass *llvm::createStraightLineStrengthReducePass() {
221 return new StraightLineStrengthReduce();
222}
223
224bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
225 const Candidate &C) {
226 return (Basis.Ins != C.Ins && // skip the same instruction
227 // Basis must dominate C in order to rewrite C with respect to Basis.
228 DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000229 // They share the same base, stride, and candidate kind.
Jingyue Wud7966ff2015-02-03 19:37:06 +0000230 Basis.Base == C.Base &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000231 Basis.Stride == C.Stride &&
232 Basis.CandidateKind == C.CandidateKind);
233}
234
Jingyue Wu43885eb2015-04-15 16:46:13 +0000235static bool isGEPFoldable(GetElementPtrInst *GEP,
236 const TargetTransformInfo *TTI,
237 const DataLayout *DL) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000238 GlobalVariable *BaseGV = nullptr;
239 int64_t BaseOffset = 0;
240 bool HasBaseReg = false;
241 int64_t Scale = 0;
242
243 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
244 BaseGV = GV;
245 else
246 HasBaseReg = true;
247
248 gep_type_iterator GTI = gep_type_begin(GEP);
249 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) {
250 if (isa<SequentialType>(*GTI)) {
251 int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
252 if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
253 BaseOffset += ConstIdx->getSExtValue() * ElementSize;
254 } else {
255 // Needs scale register.
256 if (Scale != 0) {
257 // No addressing mode takes two scale registers.
258 return false;
259 }
260 Scale = ElementSize;
261 }
262 } else {
263 StructType *STy = cast<StructType>(*GTI);
264 uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
265 BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
266 }
267 }
268 return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV,
269 BaseOffset, HasBaseReg, Scale);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000270}
271
Jingyue Wu43885eb2015-04-15 16:46:13 +0000272// Returns whether (Base + Index * Stride) can be folded to an addressing mode.
273static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
274 TargetTransformInfo *TTI) {
275 return TTI->isLegalAddressingMode(Base->getType(), nullptr, 0, true,
276 Index->getSExtValue());
277}
278
279bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
280 TargetTransformInfo *TTI,
281 const DataLayout *DL) {
282 if (C.CandidateKind == Candidate::Add)
283 return isAddFoldable(C.Base, C.Index, C.Stride, TTI);
284 if (C.CandidateKind == Candidate::GEP)
285 return isGEPFoldable(cast<GetElementPtrInst>(C.Ins), TTI, DL);
286 return false;
287}
288
289// Returns true if GEP has zero or one non-zero index.
290static bool hasOnlyOneNonZeroIndex(GetElementPtrInst *GEP) {
291 unsigned NumNonZeroIndices = 0;
292 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) {
293 ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
294 if (ConstIdx == nullptr || !ConstIdx->isZero())
295 ++NumNonZeroIndices;
296 }
297 return NumNonZeroIndices <= 1;
298}
299
300bool StraightLineStrengthReduce::isSimplestForm(const Candidate &C) {
301 if (C.CandidateKind == Candidate::Add) {
302 // B + 1 * S or B + (-1) * S
303 return C.Index->isOne() || C.Index->isMinusOne();
304 }
305 if (C.CandidateKind == Candidate::Mul) {
306 // (B + 0) * S
307 return C.Index->isZero();
308 }
309 if (C.CandidateKind == Candidate::GEP) {
310 // (char*)B + S or (char*)B - S
311 return ((C.Index->isOne() || C.Index->isMinusOne()) &&
312 hasOnlyOneNonZeroIndex(cast<GetElementPtrInst>(C.Ins)));
313 }
314 return false;
315}
316
317// TODO: We currently implement an algorithm whose time complexity is linear in
318// the number of existing candidates. However, we could do better by using
319// ScopedHashTable. Specifically, while traversing the dominator tree, we could
320// maintain all the candidates that dominate the basic block being traversed in
321// a ScopedHashTable. This hash table is indexed by the base and the stride of
322// a candidate. Therefore, finding the immediate basis of a candidate boils down
323// to one hash-table look up.
324void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
Jingyue Wu177a8152015-03-26 16:49:24 +0000325 Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
326 Instruction *I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000327 Candidate C(CT, B, Idx, S, I);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000328 // SLSR can complicate an instruction in two cases:
329 //
330 // 1. If we can fold I into an addressing mode, computing I is likely free or
331 // takes only one instruction.
332 //
333 // 2. I is already in a simplest form. For example, when
334 // X = B + 8 * S
335 // Y = B + S,
336 // rewriting Y to X - 7 * S is probably a bad idea.
337 //
338 // In the above cases, we still add I to the candidate list so that I can be
339 // the basis of other candidates, but we leave I's basis blank so that I
340 // won't be rewritten.
341 if (!isFoldable(C, TTI, DL) && !isSimplestForm(C)) {
342 // Try to compute the immediate basis of C.
343 unsigned NumIterations = 0;
344 // Limit the scan radius to avoid running in quadratice time.
345 static const unsigned MaxNumIterations = 50;
346 for (auto Basis = Candidates.rbegin();
347 Basis != Candidates.rend() && NumIterations < MaxNumIterations;
348 ++Basis, ++NumIterations) {
349 if (isBasisFor(*Basis, C)) {
350 C.Basis = &(*Basis);
351 break;
352 }
Jingyue Wud7966ff2015-02-03 19:37:06 +0000353 }
354 }
355 // Regardless of whether we find a basis for C, we need to push C to the
Jingyue Wu43885eb2015-04-15 16:46:13 +0000356 // candidate list so that it can be the basis of other candidates.
Jingyue Wud7966ff2015-02-03 19:37:06 +0000357 Candidates.push_back(C);
358}
359
Jingyue Wu43885eb2015-04-15 16:46:13 +0000360void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
361 Instruction *I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000362 switch (I->getOpcode()) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000363 case Instruction::Add:
364 allocateCandidatesAndFindBasisForAdd(I);
365 break;
Jingyue Wu177a8152015-03-26 16:49:24 +0000366 case Instruction::Mul:
Jingyue Wu43885eb2015-04-15 16:46:13 +0000367 allocateCandidatesAndFindBasisForMul(I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000368 break;
369 case Instruction::GetElementPtr:
Jingyue Wu43885eb2015-04-15 16:46:13 +0000370 allocateCandidatesAndFindBasisForGEP(cast<GetElementPtrInst>(I));
Jingyue Wu177a8152015-03-26 16:49:24 +0000371 break;
372 }
373}
374
Jingyue Wu43885eb2015-04-15 16:46:13 +0000375void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
376 Instruction *I) {
377 // Try matching B + i * S.
378 if (!isa<IntegerType>(I->getType()))
379 return;
380
381 assert(I->getNumOperands() == 2 && "isn't I an add?");
382 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
383 allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
384 if (LHS != RHS)
385 allocateCandidatesAndFindBasisForAdd(RHS, LHS, I);
386}
387
388void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
389 Value *LHS, Value *RHS, Instruction *I) {
390 Value *S = nullptr;
391 ConstantInt *Idx = nullptr;
392 if (match(RHS, m_Mul(m_Value(S), m_ConstantInt(Idx)))) {
393 // I = LHS + RHS = LHS + Idx * S
394 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
395 } else if (match(RHS, m_Shl(m_Value(S), m_ConstantInt(Idx)))) {
396 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
397 APInt One(Idx->getBitWidth(), 1);
398 Idx = ConstantInt::get(Idx->getContext(), One << Idx->getValue());
399 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
400 } else {
401 // At least, I = LHS + 1 * RHS
402 ConstantInt *One = ConstantInt::get(cast<IntegerType>(I->getType()), 1);
403 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), One, RHS,
404 I);
405 }
406}
407
Jingyue Wu80a96d292015-05-15 17:07:48 +0000408// Returns true if A matches B + C where C is constant.
409static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
410 return (match(A, m_Add(m_Value(B), m_ConstantInt(C))) ||
411 match(A, m_Add(m_ConstantInt(C), m_Value(B))));
412}
413
414// Returns true if A matches B | C where C is constant.
415static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
416 return (match(A, m_Or(m_Value(B), m_ConstantInt(C))) ||
417 match(A, m_Or(m_ConstantInt(C), m_Value(B))));
418}
419
Jingyue Wu43885eb2015-04-15 16:46:13 +0000420void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
Jingyue Wu177a8152015-03-26 16:49:24 +0000421 Value *LHS, Value *RHS, Instruction *I) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000422 Value *B = nullptr;
423 ConstantInt *Idx = nullptr;
Jingyue Wu80a96d292015-05-15 17:07:48 +0000424 if (matchesAdd(LHS, B, Idx)) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000425 // If LHS is in the form of "Base + Index", then I is in the form of
426 // "(Base + Index) * RHS".
Jingyue Wu43885eb2015-04-15 16:46:13 +0000427 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
Jingyue Wu80a96d292015-05-15 17:07:48 +0000428 } else if (matchesOr(LHS, B, Idx) && haveNoCommonBitsSet(B, Idx, *DL)) {
429 // If LHS is in the form of "Base | Index" and Base and Index have no common
430 // bits set, then
431 // Base | Index = Base + Index
432 // and I is thus in the form of "(Base + Index) * RHS".
433 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000434 } else {
435 // Otherwise, at least try the form (LHS + 0) * RHS.
436 ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000437 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS,
Jingyue Wu80a96d292015-05-15 17:07:48 +0000438 I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000439 }
440}
441
Jingyue Wu43885eb2015-04-15 16:46:13 +0000442void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
Jingyue Wu177a8152015-03-26 16:49:24 +0000443 Instruction *I) {
444 // Try matching (B + i) * S.
445 // TODO: we could extend SLSR to float and vector types.
446 if (!isa<IntegerType>(I->getType()))
447 return;
448
Jingyue Wu43885eb2015-04-15 16:46:13 +0000449 assert(I->getNumOperands() == 2 && "isn't I a mul?");
Jingyue Wu177a8152015-03-26 16:49:24 +0000450 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000451 allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000452 if (LHS != RHS) {
453 // Symmetrically, try to split RHS to Base + Index.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000454 allocateCandidatesAndFindBasisForMul(RHS, LHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000455 }
456}
457
Jingyue Wu43885eb2015-04-15 16:46:13 +0000458void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000459 const SCEV *B, ConstantInt *Idx, Value *S, uint64_t ElementSize,
460 Instruction *I) {
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000461 // I = B + sext(Idx *nsw S) * ElementSize
462 // = B + (sext(Idx) * sext(S)) * ElementSize
Jingyue Wu177a8152015-03-26 16:49:24 +0000463 // = B + (sext(Idx) * ElementSize) * sext(S)
464 // Casting to IntegerType is safe because we skipped vector GEPs.
465 IntegerType *IntPtrTy = cast<IntegerType>(DL->getIntPtrType(I->getType()));
466 ConstantInt *ScaledIdx = ConstantInt::get(
467 IntPtrTy, Idx->getSExtValue() * (int64_t)ElementSize, true);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000468 allocateCandidatesAndFindBasis(Candidate::GEP, B, ScaledIdx, S, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000469}
470
471void StraightLineStrengthReduce::factorArrayIndex(Value *ArrayIdx,
472 const SCEV *Base,
473 uint64_t ElementSize,
474 GetElementPtrInst *GEP) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000475 // At least, ArrayIdx = ArrayIdx *nsw 1.
476 allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000477 Base, ConstantInt::get(cast<IntegerType>(ArrayIdx->getType()), 1),
478 ArrayIdx, ElementSize, GEP);
479 Value *LHS = nullptr;
480 ConstantInt *RHS = nullptr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000481 // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
482 // itself. This would allow us to handle the shl case for free. However,
483 // matching SCEVs has two issues:
484 //
485 // 1. this would complicate rewriting because the rewriting procedure
486 // would have to translate SCEVs back to IR instructions. This translation
487 // is difficult when LHS is further evaluated to a composite SCEV.
488 //
489 // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
490 // to strip nsw/nuw flags which are critical for SLSR to trace into
491 // sext'ed multiplication.
492 if (match(ArrayIdx, m_NSWMul(m_Value(LHS), m_ConstantInt(RHS)))) {
493 // SLSR is currently unsafe if i * S may overflow.
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000494 // GEP = Base + sext(LHS *nsw RHS) * ElementSize
Jingyue Wu43885eb2015-04-15 16:46:13 +0000495 allocateCandidatesAndFindBasisForGEP(Base, RHS, LHS, ElementSize, GEP);
Jingyue Wu96d74002015-04-06 17:15:48 +0000496 } else if (match(ArrayIdx, m_NSWShl(m_Value(LHS), m_ConstantInt(RHS)))) {
497 // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
498 // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
499 APInt One(RHS->getBitWidth(), 1);
500 ConstantInt *PowerOf2 =
501 ConstantInt::get(RHS->getContext(), One << RHS->getValue());
Jingyue Wu43885eb2015-04-15 16:46:13 +0000502 allocateCandidatesAndFindBasisForGEP(Base, PowerOf2, LHS, ElementSize, GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000503 }
504}
505
Jingyue Wu43885eb2015-04-15 16:46:13 +0000506void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000507 GetElementPtrInst *GEP) {
508 // TODO: handle vector GEPs
509 if (GEP->getType()->isVectorTy())
510 return;
511
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000512 SmallVector<const SCEV *, 4> IndexExprs;
513 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
514 IndexExprs.push_back(SE->getSCEV(*I));
Jingyue Wu177a8152015-03-26 16:49:24 +0000515
516 gep_type_iterator GTI = gep_type_begin(GEP);
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000517 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000518 if (!isa<SequentialType>(*GTI++))
519 continue;
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000520
521 const SCEV *OrigIndexExpr = IndexExprs[I - 1];
522 IndexExprs[I - 1] = SE->getConstant(OrigIndexExpr->getType(), 0);
523
524 // The base of this candidate is GEP's base plus the offsets of all
525 // indices except this current one.
526 const SCEV *BaseExpr = SE->getGEPExpr(GEP->getSourceElementType(),
527 SE->getSCEV(GEP->getPointerOperand()),
528 IndexExprs, GEP->isInBounds());
529 Value *ArrayIdx = GEP->getOperand(I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000530 uint64_t ElementSize = DL->getTypeAllocSize(*GTI);
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000531 factorArrayIndex(ArrayIdx, BaseExpr, ElementSize, GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000532 // When ArrayIdx is the sext of a value, we try to factor that value as
533 // well. Handling this case is important because array indices are
534 // typically sign-extended to the pointer size.
535 Value *TruncatedArrayIdx = nullptr;
536 if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))))
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000537 factorArrayIndex(TruncatedArrayIdx, BaseExpr, ElementSize, GEP);
538
539 IndexExprs[I - 1] = OrigIndexExpr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000540 }
541}
542
543// A helper function that unifies the bitwidth of A and B.
544static void unifyBitWidth(APInt &A, APInt &B) {
545 if (A.getBitWidth() < B.getBitWidth())
546 A = A.sext(B.getBitWidth());
547 else if (A.getBitWidth() > B.getBitWidth())
548 B = B.sext(A.getBitWidth());
549}
550
551Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
552 const Candidate &C,
553 IRBuilder<> &Builder,
554 const DataLayout *DL,
555 bool &BumpWithUglyGEP) {
556 APInt Idx = C.Index->getValue(), BasisIdx = Basis.Index->getValue();
557 unifyBitWidth(Idx, BasisIdx);
558 APInt IndexOffset = Idx - BasisIdx;
559
560 BumpWithUglyGEP = false;
561 if (Basis.CandidateKind == Candidate::GEP) {
562 APInt ElementSize(
563 IndexOffset.getBitWidth(),
564 DL->getTypeAllocSize(
565 cast<GetElementPtrInst>(Basis.Ins)->getType()->getElementType()));
566 APInt Q, R;
567 APInt::sdivrem(IndexOffset, ElementSize, Q, R);
568 if (R.getSExtValue() == 0)
569 IndexOffset = Q;
570 else
571 BumpWithUglyGEP = true;
572 }
Jingyue Wu43885eb2015-04-15 16:46:13 +0000573
Jingyue Wu177a8152015-03-26 16:49:24 +0000574 // Compute Bump = C - Basis = (i' - i) * S.
575 // Common case 1: if (i' - i) is 1, Bump = S.
576 if (IndexOffset.getSExtValue() == 1)
577 return C.Stride;
578 // Common case 2: if (i' - i) is -1, Bump = -S.
579 if (IndexOffset.getSExtValue() == -1)
580 return Builder.CreateNeg(C.Stride);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000581
582 // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may
583 // have different bit widths.
584 IntegerType *DeltaType =
585 IntegerType::get(Basis.Ins->getContext(), IndexOffset.getBitWidth());
586 Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, DeltaType);
587 if (IndexOffset.isPowerOf2()) {
588 // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i).
589 ConstantInt *Exponent = ConstantInt::get(DeltaType, IndexOffset.logBase2());
590 return Builder.CreateShl(ExtendedStride, Exponent);
591 }
592 if ((-IndexOffset).isPowerOf2()) {
593 // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i).
594 ConstantInt *Exponent =
595 ConstantInt::get(DeltaType, (-IndexOffset).logBase2());
596 return Builder.CreateNeg(Builder.CreateShl(ExtendedStride, Exponent));
597 }
598 Constant *Delta = ConstantInt::get(DeltaType, IndexOffset);
Jingyue Wu177a8152015-03-26 16:49:24 +0000599 return Builder.CreateMul(ExtendedStride, Delta);
600}
601
Jingyue Wud7966ff2015-02-03 19:37:06 +0000602void StraightLineStrengthReduce::rewriteCandidateWithBasis(
603 const Candidate &C, const Candidate &Basis) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000604 assert(C.CandidateKind == Basis.CandidateKind && C.Base == Basis.Base &&
605 C.Stride == Basis.Stride);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000606 // We run rewriteCandidateWithBasis on all candidates in a post-order, so the
607 // basis of a candidate cannot be unlinked before the candidate.
608 assert(Basis.Ins->getParent() != nullptr && "the basis is unlinked");
Jingyue Wu177a8152015-03-26 16:49:24 +0000609
Jingyue Wud7966ff2015-02-03 19:37:06 +0000610 // An instruction can correspond to multiple candidates. Therefore, instead of
611 // simply deleting an instruction when we rewrite it, we mark its parent as
612 // nullptr (i.e. unlink it) so that we can skip the candidates whose
613 // instruction is already rewritten.
614 if (!C.Ins->getParent())
615 return;
Jingyue Wu177a8152015-03-26 16:49:24 +0000616
Jingyue Wud7966ff2015-02-03 19:37:06 +0000617 IRBuilder<> Builder(C.Ins);
Jingyue Wu177a8152015-03-26 16:49:24 +0000618 bool BumpWithUglyGEP;
619 Value *Bump = emitBump(Basis, C, Builder, DL, BumpWithUglyGEP);
620 Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
621 switch (C.CandidateKind) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000622 case Candidate::Add:
Jingyue Wu177a8152015-03-26 16:49:24 +0000623 case Candidate::Mul:
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000624 // C = Basis + Bump
Jingyue Wu43885eb2015-04-15 16:46:13 +0000625 if (BinaryOperator::isNeg(Bump)) {
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000626 // If Bump is a neg instruction, emit C = Basis - (-Bump).
Jingyue Wu43885eb2015-04-15 16:46:13 +0000627 Reduced =
628 Builder.CreateSub(Basis.Ins, BinaryOperator::getNegArgument(Bump));
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000629 // We only use the negative argument of Bump, and Bump itself may be
630 // trivially dead.
631 RecursivelyDeleteTriviallyDeadInstructions(Bump);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000632 } else {
633 Reduced = Builder.CreateAdd(Basis.Ins, Bump);
634 }
Jingyue Wu177a8152015-03-26 16:49:24 +0000635 break;
636 case Candidate::GEP:
637 {
638 Type *IntPtrTy = DL->getIntPtrType(C.Ins->getType());
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000639 bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds();
Jingyue Wu177a8152015-03-26 16:49:24 +0000640 if (BumpWithUglyGEP) {
641 // C = (char *)Basis + Bump
642 unsigned AS = Basis.Ins->getType()->getPointerAddressSpace();
643 Type *CharTy = Type::getInt8PtrTy(Basis.Ins->getContext(), AS);
644 Reduced = Builder.CreateBitCast(Basis.Ins, CharTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000645 if (InBounds)
David Blaikieaa41cd52015-04-03 21:33:42 +0000646 Reduced =
647 Builder.CreateInBoundsGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000648 else
David Blaikie93c54442015-04-03 19:41:44 +0000649 Reduced = Builder.CreateGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000650 Reduced = Builder.CreateBitCast(Reduced, C.Ins->getType());
651 } else {
652 // C = gep Basis, Bump
653 // Canonicalize bump to pointer size.
654 Bump = Builder.CreateSExtOrTrunc(Bump, IntPtrTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000655 if (InBounds)
David Blaikieaa41cd52015-04-03 21:33:42 +0000656 Reduced = Builder.CreateInBoundsGEP(nullptr, Basis.Ins, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000657 else
David Blaikie93c54442015-04-03 19:41:44 +0000658 Reduced = Builder.CreateGEP(nullptr, Basis.Ins, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000659 }
660 }
661 break;
662 default:
663 llvm_unreachable("C.CandidateKind is invalid");
664 };
Jingyue Wud7966ff2015-02-03 19:37:06 +0000665 Reduced->takeName(C.Ins);
666 C.Ins->replaceAllUsesWith(Reduced);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000667 // Unlink C.Ins so that we can skip other candidates also corresponding to
668 // C.Ins. The actual deletion is postponed to the end of runOnFunction.
669 C.Ins->removeFromParent();
Jingyue Wu43885eb2015-04-15 16:46:13 +0000670 UnlinkedInstructions.push_back(C.Ins);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000671}
672
673bool StraightLineStrengthReduce::runOnFunction(Function &F) {
674 if (skipOptnoneFunction(F))
675 return false;
676
Jingyue Wu177a8152015-03-26 16:49:24 +0000677 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000678 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Jingyue Wu177a8152015-03-26 16:49:24 +0000679 SE = &getAnalysis<ScalarEvolution>();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000680 // Traverse the dominator tree in the depth-first order. This order makes sure
681 // all bases of a candidate are in Candidates when we process it.
682 for (auto node = GraphTraits<DominatorTree *>::nodes_begin(DT);
683 node != GraphTraits<DominatorTree *>::nodes_end(DT); ++node) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000684 for (auto &I : *node->getBlock())
Jingyue Wu43885eb2015-04-15 16:46:13 +0000685 allocateCandidatesAndFindBasis(&I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000686 }
687
688 // Rewrite candidates in the reverse depth-first order. This order makes sure
689 // a candidate being rewritten is not a basis for any other candidate.
690 while (!Candidates.empty()) {
691 const Candidate &C = Candidates.back();
692 if (C.Basis != nullptr) {
693 rewriteCandidateWithBasis(C, *C.Basis);
694 }
695 Candidates.pop_back();
696 }
697
698 // Delete all unlink instructions.
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000699 for (auto *UnlinkedInst : UnlinkedInstructions) {
700 for (unsigned I = 0, E = UnlinkedInst->getNumOperands(); I != E; ++I) {
701 Value *Op = UnlinkedInst->getOperand(I);
702 UnlinkedInst->setOperand(I, nullptr);
703 RecursivelyDeleteTriviallyDeadInstructions(Op);
704 }
705 delete UnlinkedInst;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000706 }
707 bool Ret = !UnlinkedInstructions.empty();
708 UnlinkedInstructions.clear();
709 return Ret;
710}