blob: 681a70c517d37735b245e01513d63d3eadb91e44 [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 Wu177a8152015-03-26 16:49:24 +000018// reduction candidates in two forms:
Jingyue Wud7966ff2015-02-03 19:37:06 +000019//
Jingyue Wu177a8152015-03-26 16:49:24 +000020// Form 1: (B + i) * S
21// Form 2: &B[i * S]
Jingyue Wud7966ff2015-02-03 19:37:06 +000022//
Jingyue Wu177a8152015-03-26 16:49:24 +000023// where S is an integer variable, and i is a constant integer. If we found two
24// candidates
Jingyue Wud7966ff2015-02-03 19:37:06 +000025//
Jingyue Wu177a8152015-03-26 16:49:24 +000026// S1: X = (B + i) * S
27// S2: Y = (B + i') * S
28//
29// or
30//
31// S1: X = &B[i * S]
32// S2: Y = &B[i' * S]
Jingyue Wud7966ff2015-02-03 19:37:06 +000033//
34// and S1 dominates S2, we call S1 a basis of S2, and can replace S2 with
35//
36// Y = X + (i' - i) * S
37//
Jingyue Wu177a8152015-03-26 16:49:24 +000038// or
39//
40// Y = &X[(i' - i) * S]
41//
Jingyue Wud7966ff2015-02-03 19:37:06 +000042// where (i' - i) * S is folded to the extent possible. When S2 has multiple
43// bases, we pick the one that is closest to S2, or S2's "immediate" basis.
44//
45// TODO:
46//
47// - Handle candidates in the form of B + i * S
48//
Jingyue Wud7966ff2015-02-03 19:37:06 +000049// - Floating point arithmetics when fast math is enabled.
50//
51// - SLSR may decrease ILP at the architecture level. Targets that are very
52// sensitive to ILP may want to disable it. Having SLSR to consider ILP is
53// left as future work.
54#include <vector>
55
56#include "llvm/ADT/DenseSet.h"
Jingyue Wu177a8152015-03-26 16:49:24 +000057#include "llvm/ADT/FoldingSet.h"
58#include "llvm/Analysis/ScalarEvolution.h"
59#include "llvm/Analysis/TargetTransformInfo.h"
60#include "llvm/IR/DataLayout.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000061#include "llvm/IR/Dominators.h"
62#include "llvm/IR/IRBuilder.h"
63#include "llvm/IR/Module.h"
64#include "llvm/IR/PatternMatch.h"
65#include "llvm/Support/raw_ostream.h"
66#include "llvm/Transforms/Scalar.h"
67
68using namespace llvm;
69using namespace PatternMatch;
70
71namespace {
72
73class StraightLineStrengthReduce : public FunctionPass {
Jingyue Wu177a8152015-03-26 16:49:24 +000074public:
Jingyue Wud7966ff2015-02-03 19:37:06 +000075 // SLSR candidate. Such a candidate must be in the form of
76 // (Base + Index) * Stride
Jingyue Wu177a8152015-03-26 16:49:24 +000077 // or
78 // Base[..][Index * Stride][..]
Jingyue Wud7966ff2015-02-03 19:37:06 +000079 struct Candidate : public ilist_node<Candidate> {
Jingyue Wu177a8152015-03-26 16:49:24 +000080 enum Kind {
81 Invalid, // reserved for the default constructor
82 Mul, // (B + i) * S
83 GEP, // &B[..][i * S][..]
84 };
85
86 Candidate()
87 : CandidateKind(Invalid), Base(nullptr), Index(nullptr),
88 Stride(nullptr), Ins(nullptr), Basis(nullptr) {}
89 Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
90 Instruction *I)
91 : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I),
92 Basis(nullptr) {}
93 Kind CandidateKind;
94 const SCEV *Base;
95 // Note that Index and Stride of a GEP candidate may not have the same
96 // integer type. In that case, during rewriting, Stride will be
97 // sign-extended or truncated to Index's type.
Jingyue Wud7966ff2015-02-03 19:37:06 +000098 ConstantInt *Index;
99 Value *Stride;
100 // The instruction this candidate corresponds to. It helps us to rewrite a
101 // candidate with respect to its immediate basis. Note that one instruction
102 // can corresponds to multiple candidates depending on how you associate the
103 // expression. For instance,
104 //
105 // (a + 1) * (b + 2)
106 //
107 // can be treated as
108 //
109 // <Base: a, Index: 1, Stride: b + 2>
110 //
111 // or
112 //
113 // <Base: b, Index: 2, Stride: a + 1>
114 Instruction *Ins;
115 // Points to the immediate basis of this candidate, or nullptr if we cannot
116 // find any basis for this candidate.
117 Candidate *Basis;
118 };
119
120 static char ID;
121
Jingyue Wu177a8152015-03-26 16:49:24 +0000122 StraightLineStrengthReduce()
123 : FunctionPass(ID), DL(nullptr), DT(nullptr), TTI(nullptr) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000124 initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
125 }
126
127 void getAnalysisUsage(AnalysisUsage &AU) const override {
128 AU.addRequired<DominatorTreeWrapperPass>();
Jingyue Wu177a8152015-03-26 16:49:24 +0000129 AU.addRequired<ScalarEvolution>();
130 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000131 // We do not modify the shape of the CFG.
132 AU.setPreservesCFG();
133 }
134
Jingyue Wu177a8152015-03-26 16:49:24 +0000135 bool doInitialization(Module &M) override {
136 DL = &M.getDataLayout();
137 return false;
138 }
139
Jingyue Wud7966ff2015-02-03 19:37:06 +0000140 bool runOnFunction(Function &F) override;
141
Jingyue Wu177a8152015-03-26 16:49:24 +0000142private:
Jingyue Wud7966ff2015-02-03 19:37:06 +0000143 // Returns true if Basis is a basis for C, i.e., Basis dominates C and they
144 // share the same base and stride.
145 bool isBasisFor(const Candidate &Basis, const Candidate &C);
146 // Checks whether I is in a candidate form. If so, adds all the matching forms
147 // to Candidates, and tries to find the immediate basis for each of them.
148 void allocateCandidateAndFindBasis(Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000149 // Allocate candidates and find bases for Mul instructions.
150 void allocateCandidateAndFindBasisForMul(Instruction *I);
151 // Splits LHS into Base + Index and, if succeeds, calls
152 // allocateCandidateAndFindBasis.
153 void allocateCandidateAndFindBasisForMul(Value *LHS, Value *RHS,
154 Instruction *I);
155 // Allocate candidates and find bases for GetElementPtr instructions.
156 void allocateCandidateAndFindBasisForGEP(GetElementPtrInst *GEP);
157 // A helper function that scales Idx with ElementSize before invoking
158 // allocateCandidateAndFindBasis.
159 void allocateCandidateAndFindBasisForGEP(const SCEV *B, ConstantInt *Idx,
160 Value *S, uint64_t ElementSize,
161 Instruction *I);
162 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
163 // basis.
164 void allocateCandidateAndFindBasis(Candidate::Kind CT, const SCEV *B,
165 ConstantInt *Idx, Value *S,
Jingyue Wud7966ff2015-02-03 19:37:06 +0000166 Instruction *I);
167 // Rewrites candidate C with respect to Basis.
168 void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
Jingyue Wu177a8152015-03-26 16:49:24 +0000169 // A helper function that factors ArrayIdx to a product of a stride and a
170 // constant index, and invokes allocateCandidateAndFindBasis with the
171 // factorings.
172 void factorArrayIndex(Value *ArrayIdx, const SCEV *Base, uint64_t ElementSize,
173 GetElementPtrInst *GEP);
174 // Emit code that computes the "bump" from Basis to C. If the candidate is a
175 // GEP and the bump is not divisible by the element size of the GEP, this
176 // function sets the BumpWithUglyGEP flag to notify its caller to bump the
177 // basis using an ugly GEP.
178 static Value *emitBump(const Candidate &Basis, const Candidate &C,
179 IRBuilder<> &Builder, const DataLayout *DL,
180 bool &BumpWithUglyGEP);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000181
Jingyue Wu177a8152015-03-26 16:49:24 +0000182 const DataLayout *DL;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000183 DominatorTree *DT;
Jingyue Wu177a8152015-03-26 16:49:24 +0000184 ScalarEvolution *SE;
185 TargetTransformInfo *TTI;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000186 ilist<Candidate> Candidates;
187 // Temporarily holds all instructions that are unlinked (but not deleted) by
188 // rewriteCandidateWithBasis. These instructions will be actually removed
189 // after all rewriting finishes.
190 DenseSet<Instruction *> UnlinkedInstructions;
191};
192} // anonymous namespace
193
194char StraightLineStrengthReduce::ID = 0;
195INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
196 "Straight line strength reduction", false, false)
197INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Jingyue Wu177a8152015-03-26 16:49:24 +0000198INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
199INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Jingyue Wud7966ff2015-02-03 19:37:06 +0000200INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
201 "Straight line strength reduction", false, false)
202
203FunctionPass *llvm::createStraightLineStrengthReducePass() {
204 return new StraightLineStrengthReduce();
205}
206
207bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
208 const Candidate &C) {
209 return (Basis.Ins != C.Ins && // skip the same instruction
210 // Basis must dominate C in order to rewrite C with respect to Basis.
211 DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000212 // They share the same base, stride, and candidate kind.
Jingyue Wud7966ff2015-02-03 19:37:06 +0000213 Basis.Base == C.Base &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000214 Basis.Stride == C.Stride &&
215 Basis.CandidateKind == C.CandidateKind);
216}
217
218static bool isCompletelyFoldable(GetElementPtrInst *GEP,
219 const TargetTransformInfo *TTI,
220 const DataLayout *DL) {
221 GlobalVariable *BaseGV = nullptr;
222 int64_t BaseOffset = 0;
223 bool HasBaseReg = false;
224 int64_t Scale = 0;
225
226 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
227 BaseGV = GV;
228 else
229 HasBaseReg = true;
230
231 gep_type_iterator GTI = gep_type_begin(GEP);
232 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) {
233 if (isa<SequentialType>(*GTI)) {
234 int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
235 if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
236 BaseOffset += ConstIdx->getSExtValue() * ElementSize;
237 } else {
238 // Needs scale register.
239 if (Scale != 0) {
240 // No addressing mode takes two scale registers.
241 return false;
242 }
243 Scale = ElementSize;
244 }
245 } else {
246 StructType *STy = cast<StructType>(*GTI);
247 uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
248 BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
249 }
250 }
251 return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV,
252 BaseOffset, HasBaseReg, Scale);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000253}
254
255// TODO: We currently implement an algorithm whose time complexity is linear to
256// the number of existing candidates. However, a better algorithm exists. We
257// could depth-first search the dominator tree, and maintain a hash table that
258// contains all candidates that dominate the node being traversed. This hash
259// table is indexed by the base and the stride of a candidate. Therefore,
260// finding the immediate basis of a candidate boils down to one hash-table look
261// up.
Jingyue Wu177a8152015-03-26 16:49:24 +0000262void StraightLineStrengthReduce::allocateCandidateAndFindBasis(
263 Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
264 Instruction *I) {
265 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
266 // If &B[Idx * S] fits into an addressing mode, do not turn it into
267 // non-free computation.
268 if (isCompletelyFoldable(GEP, TTI, DL))
269 return;
270 }
271
272 Candidate C(CT, B, Idx, S, I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000273 // Try to compute the immediate basis of C.
274 unsigned NumIterations = 0;
275 // Limit the scan radius to avoid running forever.
Aaron Ballman34c325e2015-02-04 14:01:08 +0000276 static const unsigned MaxNumIterations = 50;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000277 for (auto Basis = Candidates.rbegin();
278 Basis != Candidates.rend() && NumIterations < MaxNumIterations;
279 ++Basis, ++NumIterations) {
280 if (isBasisFor(*Basis, C)) {
281 C.Basis = &(*Basis);
282 break;
283 }
284 }
285 // Regardless of whether we find a basis for C, we need to push C to the
286 // candidate list.
287 Candidates.push_back(C);
288}
289
290void StraightLineStrengthReduce::allocateCandidateAndFindBasis(Instruction *I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000291 switch (I->getOpcode()) {
292 case Instruction::Mul:
293 allocateCandidateAndFindBasisForMul(I);
294 break;
295 case Instruction::GetElementPtr:
296 allocateCandidateAndFindBasisForGEP(cast<GetElementPtrInst>(I));
297 break;
298 }
299}
300
301void StraightLineStrengthReduce::allocateCandidateAndFindBasisForMul(
302 Value *LHS, Value *RHS, Instruction *I) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000303 Value *B = nullptr;
304 ConstantInt *Idx = nullptr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000305 // Only handle the canonical operand ordering.
306 if (match(LHS, m_Add(m_Value(B), m_ConstantInt(Idx)))) {
307 // If LHS is in the form of "Base + Index", then I is in the form of
308 // "(Base + Index) * RHS".
309 allocateCandidateAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
310 } else {
311 // Otherwise, at least try the form (LHS + 0) * RHS.
312 ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0);
313 allocateCandidateAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS,
314 I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000315 }
316}
317
Jingyue Wu177a8152015-03-26 16:49:24 +0000318void StraightLineStrengthReduce::allocateCandidateAndFindBasisForMul(
319 Instruction *I) {
320 // Try matching (B + i) * S.
321 // TODO: we could extend SLSR to float and vector types.
322 if (!isa<IntegerType>(I->getType()))
323 return;
324
325 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
326 allocateCandidateAndFindBasisForMul(LHS, RHS, I);
327 if (LHS != RHS) {
328 // Symmetrically, try to split RHS to Base + Index.
329 allocateCandidateAndFindBasisForMul(RHS, LHS, I);
330 }
331}
332
333void StraightLineStrengthReduce::allocateCandidateAndFindBasisForGEP(
334 const SCEV *B, ConstantInt *Idx, Value *S, uint64_t ElementSize,
335 Instruction *I) {
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000336 // I = B + sext(Idx *nsw S) * ElementSize
337 // = B + (sext(Idx) * sext(S)) * ElementSize
Jingyue Wu177a8152015-03-26 16:49:24 +0000338 // = B + (sext(Idx) * ElementSize) * sext(S)
339 // Casting to IntegerType is safe because we skipped vector GEPs.
340 IntegerType *IntPtrTy = cast<IntegerType>(DL->getIntPtrType(I->getType()));
341 ConstantInt *ScaledIdx = ConstantInt::get(
342 IntPtrTy, Idx->getSExtValue() * (int64_t)ElementSize, true);
343 allocateCandidateAndFindBasis(Candidate::GEP, B, ScaledIdx, S, I);
344}
345
346void StraightLineStrengthReduce::factorArrayIndex(Value *ArrayIdx,
347 const SCEV *Base,
348 uint64_t ElementSize,
349 GetElementPtrInst *GEP) {
350 // At least, ArrayIdx = ArrayIdx *s 1.
351 allocateCandidateAndFindBasisForGEP(
352 Base, ConstantInt::get(cast<IntegerType>(ArrayIdx->getType()), 1),
353 ArrayIdx, ElementSize, GEP);
354 Value *LHS = nullptr;
355 ConstantInt *RHS = nullptr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000356 // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
357 // itself. This would allow us to handle the shl case for free. However,
358 // matching SCEVs has two issues:
359 //
360 // 1. this would complicate rewriting because the rewriting procedure
361 // would have to translate SCEVs back to IR instructions. This translation
362 // is difficult when LHS is further evaluated to a composite SCEV.
363 //
364 // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
365 // to strip nsw/nuw flags which are critical for SLSR to trace into
366 // sext'ed multiplication.
367 if (match(ArrayIdx, m_NSWMul(m_Value(LHS), m_ConstantInt(RHS)))) {
368 // SLSR is currently unsafe if i * S may overflow.
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000369 // GEP = Base + sext(LHS *nsw RHS) * ElementSize
Jingyue Wu177a8152015-03-26 16:49:24 +0000370 allocateCandidateAndFindBasisForGEP(Base, RHS, LHS, ElementSize, GEP);
Jingyue Wu96d74002015-04-06 17:15:48 +0000371 } else if (match(ArrayIdx, m_NSWShl(m_Value(LHS), m_ConstantInt(RHS)))) {
372 // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
373 // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
374 APInt One(RHS->getBitWidth(), 1);
375 ConstantInt *PowerOf2 =
376 ConstantInt::get(RHS->getContext(), One << RHS->getValue());
377 allocateCandidateAndFindBasisForGEP(Base, PowerOf2, LHS, ElementSize, GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000378 }
379}
380
381void StraightLineStrengthReduce::allocateCandidateAndFindBasisForGEP(
382 GetElementPtrInst *GEP) {
383 // TODO: handle vector GEPs
384 if (GEP->getType()->isVectorTy())
385 return;
386
387 const SCEV *GEPExpr = SE->getSCEV(GEP);
388 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
389
390 gep_type_iterator GTI = gep_type_begin(GEP);
391 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) {
392 if (!isa<SequentialType>(*GTI++))
393 continue;
394 Value *ArrayIdx = *I;
395 // Compute the byte offset of this index.
396 uint64_t ElementSize = DL->getTypeAllocSize(*GTI);
397 const SCEV *ElementSizeExpr = SE->getSizeOfExpr(IntPtrTy, *GTI);
398 const SCEV *ArrayIdxExpr = SE->getSCEV(ArrayIdx);
399 ArrayIdxExpr = SE->getTruncateOrSignExtend(ArrayIdxExpr, IntPtrTy);
400 const SCEV *LocalOffset =
401 SE->getMulExpr(ArrayIdxExpr, ElementSizeExpr, SCEV::FlagNSW);
402 // The base of this candidate equals GEPExpr less the byte offset of this
403 // index.
404 const SCEV *Base = SE->getMinusSCEV(GEPExpr, LocalOffset);
405 factorArrayIndex(ArrayIdx, Base, ElementSize, GEP);
406 // When ArrayIdx is the sext of a value, we try to factor that value as
407 // well. Handling this case is important because array indices are
408 // typically sign-extended to the pointer size.
409 Value *TruncatedArrayIdx = nullptr;
410 if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))))
411 factorArrayIndex(TruncatedArrayIdx, Base, ElementSize, GEP);
412 }
413}
414
415// A helper function that unifies the bitwidth of A and B.
416static void unifyBitWidth(APInt &A, APInt &B) {
417 if (A.getBitWidth() < B.getBitWidth())
418 A = A.sext(B.getBitWidth());
419 else if (A.getBitWidth() > B.getBitWidth())
420 B = B.sext(A.getBitWidth());
421}
422
423Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
424 const Candidate &C,
425 IRBuilder<> &Builder,
426 const DataLayout *DL,
427 bool &BumpWithUglyGEP) {
428 APInt Idx = C.Index->getValue(), BasisIdx = Basis.Index->getValue();
429 unifyBitWidth(Idx, BasisIdx);
430 APInt IndexOffset = Idx - BasisIdx;
431
432 BumpWithUglyGEP = false;
433 if (Basis.CandidateKind == Candidate::GEP) {
434 APInt ElementSize(
435 IndexOffset.getBitWidth(),
436 DL->getTypeAllocSize(
437 cast<GetElementPtrInst>(Basis.Ins)->getType()->getElementType()));
438 APInt Q, R;
439 APInt::sdivrem(IndexOffset, ElementSize, Q, R);
440 if (R.getSExtValue() == 0)
441 IndexOffset = Q;
442 else
443 BumpWithUglyGEP = true;
444 }
445 // Compute Bump = C - Basis = (i' - i) * S.
446 // Common case 1: if (i' - i) is 1, Bump = S.
447 if (IndexOffset.getSExtValue() == 1)
448 return C.Stride;
449 // Common case 2: if (i' - i) is -1, Bump = -S.
450 if (IndexOffset.getSExtValue() == -1)
451 return Builder.CreateNeg(C.Stride);
452 // Otherwise, Bump = (i' - i) * sext/trunc(S).
453 ConstantInt *Delta = ConstantInt::get(Basis.Ins->getContext(), IndexOffset);
454 Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, Delta->getType());
455 return Builder.CreateMul(ExtendedStride, Delta);
456}
457
Jingyue Wud7966ff2015-02-03 19:37:06 +0000458void StraightLineStrengthReduce::rewriteCandidateWithBasis(
459 const Candidate &C, const Candidate &Basis) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000460 assert(C.CandidateKind == Basis.CandidateKind && C.Base == Basis.Base &&
461 C.Stride == Basis.Stride);
462
Jingyue Wud7966ff2015-02-03 19:37:06 +0000463 // An instruction can correspond to multiple candidates. Therefore, instead of
464 // simply deleting an instruction when we rewrite it, we mark its parent as
465 // nullptr (i.e. unlink it) so that we can skip the candidates whose
466 // instruction is already rewritten.
467 if (!C.Ins->getParent())
468 return;
Jingyue Wu177a8152015-03-26 16:49:24 +0000469
Jingyue Wud7966ff2015-02-03 19:37:06 +0000470 IRBuilder<> Builder(C.Ins);
Jingyue Wu177a8152015-03-26 16:49:24 +0000471 bool BumpWithUglyGEP;
472 Value *Bump = emitBump(Basis, C, Builder, DL, BumpWithUglyGEP);
473 Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
474 switch (C.CandidateKind) {
475 case Candidate::Mul:
Jingyue Wud7966ff2015-02-03 19:37:06 +0000476 Reduced = Builder.CreateAdd(Basis.Ins, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000477 break;
478 case Candidate::GEP:
479 {
480 Type *IntPtrTy = DL->getIntPtrType(C.Ins->getType());
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000481 bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds();
Jingyue Wu177a8152015-03-26 16:49:24 +0000482 if (BumpWithUglyGEP) {
483 // C = (char *)Basis + Bump
484 unsigned AS = Basis.Ins->getType()->getPointerAddressSpace();
485 Type *CharTy = Type::getInt8PtrTy(Basis.Ins->getContext(), AS);
486 Reduced = Builder.CreateBitCast(Basis.Ins, CharTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000487 if (InBounds)
David Blaikieaa41cd52015-04-03 21:33:42 +0000488 Reduced =
489 Builder.CreateInBoundsGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000490 else
David Blaikie93c54442015-04-03 19:41:44 +0000491 Reduced = Builder.CreateGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000492 Reduced = Builder.CreateBitCast(Reduced, C.Ins->getType());
493 } else {
494 // C = gep Basis, Bump
495 // Canonicalize bump to pointer size.
496 Bump = Builder.CreateSExtOrTrunc(Bump, IntPtrTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000497 if (InBounds)
David Blaikieaa41cd52015-04-03 21:33:42 +0000498 Reduced = Builder.CreateInBoundsGEP(nullptr, Basis.Ins, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000499 else
David Blaikie93c54442015-04-03 19:41:44 +0000500 Reduced = Builder.CreateGEP(nullptr, Basis.Ins, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000501 }
502 }
503 break;
504 default:
505 llvm_unreachable("C.CandidateKind is invalid");
506 };
Jingyue Wud7966ff2015-02-03 19:37:06 +0000507 Reduced->takeName(C.Ins);
508 C.Ins->replaceAllUsesWith(Reduced);
509 C.Ins->dropAllReferences();
510 // Unlink C.Ins so that we can skip other candidates also corresponding to
511 // C.Ins. The actual deletion is postponed to the end of runOnFunction.
512 C.Ins->removeFromParent();
513 UnlinkedInstructions.insert(C.Ins);
514}
515
516bool StraightLineStrengthReduce::runOnFunction(Function &F) {
517 if (skipOptnoneFunction(F))
518 return false;
519
Jingyue Wu177a8152015-03-26 16:49:24 +0000520 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000521 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Jingyue Wu177a8152015-03-26 16:49:24 +0000522 SE = &getAnalysis<ScalarEvolution>();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000523 // Traverse the dominator tree in the depth-first order. This order makes sure
524 // all bases of a candidate are in Candidates when we process it.
525 for (auto node = GraphTraits<DominatorTree *>::nodes_begin(DT);
526 node != GraphTraits<DominatorTree *>::nodes_end(DT); ++node) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000527 for (auto &I : *node->getBlock())
528 allocateCandidateAndFindBasis(&I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000529 }
530
531 // Rewrite candidates in the reverse depth-first order. This order makes sure
532 // a candidate being rewritten is not a basis for any other candidate.
533 while (!Candidates.empty()) {
534 const Candidate &C = Candidates.back();
535 if (C.Basis != nullptr) {
536 rewriteCandidateWithBasis(C, *C.Basis);
537 }
538 Candidates.pop_back();
539 }
540
541 // Delete all unlink instructions.
542 for (auto I : UnlinkedInstructions) {
543 delete I;
544 }
545 bool Ret = !UnlinkedInstructions.empty();
546 UnlinkedInstructions.clear();
547 return Ret;
548}