blob: a58c32cc58943f3fc6071183eb18b7080cded890 [file] [log] [blame]
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001//===- StraightLineStrengthReduce.cpp - -----------------------------------===//
Jingyue Wud7966ff2015-02-03 19:37:06 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jingyue Wud7966ff2015-02-03 19:37:06 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements straight-line strength reduction (SLSR). Unlike loop
10// strength reduction, this algorithm is designed to reduce arithmetic
11// redundancy in straight-line code instead of loops. It has proven to be
12// effective in simplifying arithmetic statements derived from an unrolled loop.
13// It can also simplify the logic of SeparateConstOffsetFromGEP.
14//
15// There are many optimizations we can perform in the domain of SLSR. This file
16// for now contains only an initial step. Specifically, we look for strength
Jingyue Wu43885eb2015-04-15 16:46:13 +000017// reduction candidates in the following forms:
Jingyue Wud7966ff2015-02-03 19:37:06 +000018//
Jingyue Wu43885eb2015-04-15 16:46:13 +000019// Form 1: B + i * S
20// Form 2: (B + i) * S
21// Form 3: &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
Jingyue Wu43885eb2015-04-15 16:46:13 +000024// candidates S1 and S2 in the same form and S1 dominates S2, we may rewrite S2
25// in a simpler way with respect to S1. For example,
26//
27// S1: X = B + i * S
28// S2: Y = B + i' * S => X + (i' - i) * S
Jingyue Wud7966ff2015-02-03 19:37:06 +000029//
Jingyue Wu177a8152015-03-26 16:49:24 +000030// S1: X = (B + i) * S
Jingyue Wu43885eb2015-04-15 16:46:13 +000031// S2: Y = (B + i') * S => X + (i' - i) * S
Jingyue Wu177a8152015-03-26 16:49:24 +000032//
33// S1: X = &B[i * S]
Jingyue Wu43885eb2015-04-15 16:46:13 +000034// S2: Y = &B[i' * S] => &X[(i' - i) * S]
Jingyue Wud7966ff2015-02-03 19:37:06 +000035//
Jingyue Wu43885eb2015-04-15 16:46:13 +000036// Note: (i' - i) * S is folded to the extent possible.
Jingyue Wud7966ff2015-02-03 19:37:06 +000037//
Jingyue Wu43885eb2015-04-15 16:46:13 +000038// This rewriting is in general a good idea. The code patterns we focus on
39// usually come from loop unrolling, so (i' - i) * S is likely the same
40// across iterations and can be reused. When that happens, the optimized form
41// takes only one add starting from the second iteration.
Jingyue Wud7966ff2015-02-03 19:37:06 +000042//
Jingyue Wu43885eb2015-04-15 16:46:13 +000043// When such rewriting is possible, we call S1 a "basis" of S2. When S2 has
44// multiple bases, we choose to rewrite S2 with respect to its "immediate"
45// basis, the basis that is the closest ancestor in the dominator tree.
Jingyue Wud7966ff2015-02-03 19:37:06 +000046//
47// TODO:
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.
Jingyue Wu43885eb2015-04-15 16:46:13 +000054//
55// - When (i' - i) is constant but i and i' are not, we could still perform
56// SLSR.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000057
58#include "llvm/ADT/APInt.h"
59#include "llvm/ADT/DepthFirstIterator.h"
60#include "llvm/ADT/SmallVector.h"
Jingyue Wu177a8152015-03-26 16:49:24 +000061#include "llvm/Analysis/ScalarEvolution.h"
62#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000063#include "llvm/Transforms/Utils/Local.h"
Jingyue Wu80a96d292015-05-15 17:07:48 +000064#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000065#include "llvm/IR/Constants.h"
Jingyue Wu177a8152015-03-26 16:49:24 +000066#include "llvm/IR/DataLayout.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000067#include "llvm/IR/DerivedTypes.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000068#include "llvm/IR/Dominators.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000069#include "llvm/IR/GetElementPtrTypeIterator.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000070#include "llvm/IR/IRBuilder.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000071#include "llvm/IR/InstrTypes.h"
72#include "llvm/IR/Instruction.h"
73#include "llvm/IR/Instructions.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000074#include "llvm/IR/Module.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000075#include "llvm/IR/Operator.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000076#include "llvm/IR/PatternMatch.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000077#include "llvm/IR/Type.h"
78#include "llvm/IR/Value.h"
79#include "llvm/Pass.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/ErrorHandling.h"
Jingyue Wud7966ff2015-02-03 19:37:06 +000082#include "llvm/Transforms/Scalar.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000083#include <cassert>
84#include <cstdint>
85#include <limits>
Duncan P. N. Exon Smith8b4e4af2016-09-11 21:29:34 +000086#include <list>
Duncan P. N. Exon Smith077f5b42016-09-11 21:04:36 +000087#include <vector>
Jingyue Wud7966ff2015-02-03 19:37:06 +000088
89using namespace llvm;
90using namespace PatternMatch;
91
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000092static const unsigned UnknownAddressSpace =
93 std::numeric_limits<unsigned>::max();
Jingyue Wud7966ff2015-02-03 19:37:06 +000094
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000095namespace {
Matt Arsenaultba437c62016-04-27 00:32:09 +000096
Jingyue Wud7966ff2015-02-03 19:37:06 +000097class StraightLineStrengthReduce : public FunctionPass {
Jingyue Wu177a8152015-03-26 16:49:24 +000098public:
Jingyue Wu43885eb2015-04-15 16:46:13 +000099 // SLSR candidate. Such a candidate must be in one of the forms described in
100 // the header comments.
Duncan P. N. Exon Smith8b4e4af2016-09-11 21:29:34 +0000101 struct Candidate {
Jingyue Wu177a8152015-03-26 16:49:24 +0000102 enum Kind {
103 Invalid, // reserved for the default constructor
Jingyue Wu43885eb2015-04-15 16:46:13 +0000104 Add, // B + i * S
Jingyue Wu177a8152015-03-26 16:49:24 +0000105 Mul, // (B + i) * S
106 GEP, // &B[..][i * S][..]
107 };
108
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000109 Candidate() = default;
Jingyue Wu177a8152015-03-26 16:49:24 +0000110 Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
111 Instruction *I)
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000112 : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I) {}
113
114 Kind CandidateKind = Invalid;
115
116 const SCEV *Base = nullptr;
117
Jingyue Wu43885eb2015-04-15 16:46:13 +0000118 // Note that Index and Stride of a GEP candidate do not necessarily have the
119 // same integer type. In that case, during rewriting, Stride will be
Jingyue Wu177a8152015-03-26 16:49:24 +0000120 // sign-extended or truncated to Index's type.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000121 ConstantInt *Index = nullptr;
122
123 Value *Stride = nullptr;
124
Jingyue Wud7966ff2015-02-03 19:37:06 +0000125 // The instruction this candidate corresponds to. It helps us to rewrite a
126 // candidate with respect to its immediate basis. Note that one instruction
Jingyue Wu43885eb2015-04-15 16:46:13 +0000127 // can correspond to multiple candidates depending on how you associate the
Jingyue Wud7966ff2015-02-03 19:37:06 +0000128 // expression. For instance,
129 //
130 // (a + 1) * (b + 2)
131 //
132 // can be treated as
133 //
134 // <Base: a, Index: 1, Stride: b + 2>
135 //
136 // or
137 //
138 // <Base: b, Index: 2, Stride: a + 1>
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000139 Instruction *Ins = nullptr;
140
Jingyue Wud7966ff2015-02-03 19:37:06 +0000141 // Points to the immediate basis of this candidate, or nullptr if we cannot
142 // find any basis for this candidate.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000143 Candidate *Basis = nullptr;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000144 };
145
146 static char ID;
147
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000148 StraightLineStrengthReduce() : FunctionPass(ID) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000149 initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
150 }
151
152 void getAnalysisUsage(AnalysisUsage &AU) const override {
153 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000154 AU.addRequired<ScalarEvolutionWrapperPass>();
Jingyue Wu177a8152015-03-26 16:49:24 +0000155 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000156 // We do not modify the shape of the CFG.
157 AU.setPreservesCFG();
158 }
159
Jingyue Wu177a8152015-03-26 16:49:24 +0000160 bool doInitialization(Module &M) override {
161 DL = &M.getDataLayout();
162 return false;
163 }
164
Jingyue Wud7966ff2015-02-03 19:37:06 +0000165 bool runOnFunction(Function &F) override;
166
Jingyue Wu177a8152015-03-26 16:49:24 +0000167private:
Jingyue Wud7966ff2015-02-03 19:37:06 +0000168 // Returns true if Basis is a basis for C, i.e., Basis dominates C and they
169 // share the same base and stride.
170 bool isBasisFor(const Candidate &Basis, const Candidate &C);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000171
Jingyue Wu43885eb2015-04-15 16:46:13 +0000172 // Returns whether the candidate can be folded into an addressing mode.
173 bool isFoldable(const Candidate &C, TargetTransformInfo *TTI,
174 const DataLayout *DL);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000175
Jingyue Wu43885eb2015-04-15 16:46:13 +0000176 // Returns true if C is already in a simplest form and not worth being
177 // rewritten.
178 bool isSimplestForm(const Candidate &C);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000179
Jingyue Wud7966ff2015-02-03 19:37:06 +0000180 // Checks whether I is in a candidate form. If so, adds all the matching forms
181 // to Candidates, and tries to find the immediate basis for each of them.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000182 void allocateCandidatesAndFindBasis(Instruction *I);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000183
Jingyue Wu43885eb2015-04-15 16:46:13 +0000184 // Allocate candidates and find bases for Add instructions.
185 void allocateCandidatesAndFindBasisForAdd(Instruction *I);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000186
Jingyue Wu43885eb2015-04-15 16:46:13 +0000187 // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
188 // candidate.
189 void allocateCandidatesAndFindBasisForAdd(Value *LHS, Value *RHS,
190 Instruction *I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000191 // Allocate candidates and find bases for Mul instructions.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000192 void allocateCandidatesAndFindBasisForMul(Instruction *I);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000193
Jingyue Wu177a8152015-03-26 16:49:24 +0000194 // Splits LHS into Base + Index and, if succeeds, calls
Jingyue Wu43885eb2015-04-15 16:46:13 +0000195 // allocateCandidatesAndFindBasis.
196 void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS,
197 Instruction *I);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000198
Jingyue Wu177a8152015-03-26 16:49:24 +0000199 // Allocate candidates and find bases for GetElementPtr instructions.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000200 void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000201
Jingyue Wu177a8152015-03-26 16:49:24 +0000202 // A helper function that scales Idx with ElementSize before invoking
Jingyue Wu43885eb2015-04-15 16:46:13 +0000203 // allocateCandidatesAndFindBasis.
204 void allocateCandidatesAndFindBasisForGEP(const SCEV *B, ConstantInt *Idx,
205 Value *S, uint64_t ElementSize,
206 Instruction *I);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000207
Jingyue Wu177a8152015-03-26 16:49:24 +0000208 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
209 // basis.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000210 void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B,
211 ConstantInt *Idx, Value *S,
212 Instruction *I);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000213
Jingyue Wud7966ff2015-02-03 19:37:06 +0000214 // Rewrites candidate C with respect to Basis.
215 void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000216
Jingyue Wu177a8152015-03-26 16:49:24 +0000217 // A helper function that factors ArrayIdx to a product of a stride and a
Jingyue Wu43885eb2015-04-15 16:46:13 +0000218 // constant index, and invokes allocateCandidatesAndFindBasis with the
Jingyue Wu177a8152015-03-26 16:49:24 +0000219 // factorings.
220 void factorArrayIndex(Value *ArrayIdx, const SCEV *Base, uint64_t ElementSize,
221 GetElementPtrInst *GEP);
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000222
Jingyue Wu177a8152015-03-26 16:49:24 +0000223 // Emit code that computes the "bump" from Basis to C. If the candidate is a
224 // GEP and the bump is not divisible by the element size of the GEP, this
225 // function sets the BumpWithUglyGEP flag to notify its caller to bump the
226 // basis using an ugly GEP.
227 static Value *emitBump(const Candidate &Basis, const Candidate &C,
228 IRBuilder<> &Builder, const DataLayout *DL,
229 bool &BumpWithUglyGEP);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000230
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000231 const DataLayout *DL = nullptr;
232 DominatorTree *DT = nullptr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000233 ScalarEvolution *SE;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000234 TargetTransformInfo *TTI = nullptr;
Duncan P. N. Exon Smith8b4e4af2016-09-11 21:29:34 +0000235 std::list<Candidate> Candidates;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000236
Jingyue Wud7966ff2015-02-03 19:37:06 +0000237 // Temporarily holds all instructions that are unlinked (but not deleted) by
238 // rewriteCandidateWithBasis. These instructions will be actually removed
239 // after all rewriting finishes.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000240 std::vector<Instruction *> UnlinkedInstructions;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000241};
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000242
243} // end anonymous namespace
Jingyue Wud7966ff2015-02-03 19:37:06 +0000244
245char StraightLineStrengthReduce::ID = 0;
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000246
Jingyue Wud7966ff2015-02-03 19:37:06 +0000247INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
248 "Straight line strength reduction", false, false)
249INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000250INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Jingyue Wu177a8152015-03-26 16:49:24 +0000251INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Jingyue Wud7966ff2015-02-03 19:37:06 +0000252INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
253 "Straight line strength reduction", false, false)
254
255FunctionPass *llvm::createStraightLineStrengthReducePass() {
256 return new StraightLineStrengthReduce();
257}
258
259bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
260 const Candidate &C) {
261 return (Basis.Ins != C.Ins && // skip the same instruction
Jingyue Wu3abde7b2015-06-28 17:45:05 +0000262 // They must have the same type too. Basis.Base == C.Base doesn't
263 // guarantee their types are the same (PR23975).
264 Basis.Ins->getType() == C.Ins->getType() &&
Jingyue Wud7966ff2015-02-03 19:37:06 +0000265 // Basis must dominate C in order to rewrite C with respect to Basis.
266 DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000267 // They share the same base, stride, and candidate kind.
Jingyue Wu3abde7b2015-06-28 17:45:05 +0000268 Basis.Base == C.Base && Basis.Stride == C.Stride &&
Jingyue Wu177a8152015-03-26 16:49:24 +0000269 Basis.CandidateKind == C.CandidateKind);
270}
271
Jingyue Wu43885eb2015-04-15 16:46:13 +0000272static bool isGEPFoldable(GetElementPtrInst *GEP,
Jingyue Wu15f3e822016-07-08 21:48:05 +0000273 const TargetTransformInfo *TTI) {
274 SmallVector<const Value*, 4> Indices;
275 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
276 Indices.push_back(*I);
Daniel Jasper3344a212017-10-13 14:04:21 +0000277 return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
Jingyue Wu15f3e822016-07-08 21:48:05 +0000278 Indices) == TargetTransformInfo::TCC_Free;
Jingyue Wud7966ff2015-02-03 19:37:06 +0000279}
280
Jingyue Wu43885eb2015-04-15 16:46:13 +0000281// Returns whether (Base + Index * Stride) can be folded to an addressing mode.
282static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
283 TargetTransformInfo *TTI) {
Jingyue Wudebce552016-07-09 19:13:18 +0000284 // Index->getSExtValue() may crash if Index is wider than 64-bit.
285 return Index->getBitWidth() <= 64 &&
286 TTI->isLegalAddressingMode(Base->getType(), nullptr, 0, true,
Matt Arsenaultba437c62016-04-27 00:32:09 +0000287 Index->getSExtValue(), UnknownAddressSpace);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000288}
289
290bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
291 TargetTransformInfo *TTI,
292 const DataLayout *DL) {
293 if (C.CandidateKind == Candidate::Add)
294 return isAddFoldable(C.Base, C.Index, C.Stride, TTI);
295 if (C.CandidateKind == Candidate::GEP)
Jingyue Wu15f3e822016-07-08 21:48:05 +0000296 return isGEPFoldable(cast<GetElementPtrInst>(C.Ins), TTI);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000297 return false;
298}
299
300// Returns true if GEP has zero or one non-zero index.
301static bool hasOnlyOneNonZeroIndex(GetElementPtrInst *GEP) {
302 unsigned NumNonZeroIndices = 0;
303 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) {
304 ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
305 if (ConstIdx == nullptr || !ConstIdx->isZero())
306 ++NumNonZeroIndices;
307 }
308 return NumNonZeroIndices <= 1;
309}
310
311bool StraightLineStrengthReduce::isSimplestForm(const Candidate &C) {
312 if (C.CandidateKind == Candidate::Add) {
313 // B + 1 * S or B + (-1) * S
314 return C.Index->isOne() || C.Index->isMinusOne();
315 }
316 if (C.CandidateKind == Candidate::Mul) {
317 // (B + 0) * S
318 return C.Index->isZero();
319 }
320 if (C.CandidateKind == Candidate::GEP) {
321 // (char*)B + S or (char*)B - S
322 return ((C.Index->isOne() || C.Index->isMinusOne()) &&
323 hasOnlyOneNonZeroIndex(cast<GetElementPtrInst>(C.Ins)));
324 }
325 return false;
326}
327
328// TODO: We currently implement an algorithm whose time complexity is linear in
329// the number of existing candidates. However, we could do better by using
330// ScopedHashTable. Specifically, while traversing the dominator tree, we could
331// maintain all the candidates that dominate the basic block being traversed in
332// a ScopedHashTable. This hash table is indexed by the base and the stride of
333// a candidate. Therefore, finding the immediate basis of a candidate boils down
334// to one hash-table look up.
335void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
Jingyue Wu177a8152015-03-26 16:49:24 +0000336 Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
337 Instruction *I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000338 Candidate C(CT, B, Idx, S, I);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000339 // SLSR can complicate an instruction in two cases:
340 //
341 // 1. If we can fold I into an addressing mode, computing I is likely free or
342 // takes only one instruction.
343 //
344 // 2. I is already in a simplest form. For example, when
345 // X = B + 8 * S
346 // Y = B + S,
347 // rewriting Y to X - 7 * S is probably a bad idea.
348 //
349 // In the above cases, we still add I to the candidate list so that I can be
350 // the basis of other candidates, but we leave I's basis blank so that I
351 // won't be rewritten.
352 if (!isFoldable(C, TTI, DL) && !isSimplestForm(C)) {
353 // Try to compute the immediate basis of C.
354 unsigned NumIterations = 0;
355 // Limit the scan radius to avoid running in quadratice time.
356 static const unsigned MaxNumIterations = 50;
357 for (auto Basis = Candidates.rbegin();
358 Basis != Candidates.rend() && NumIterations < MaxNumIterations;
359 ++Basis, ++NumIterations) {
360 if (isBasisFor(*Basis, C)) {
361 C.Basis = &(*Basis);
362 break;
363 }
Jingyue Wud7966ff2015-02-03 19:37:06 +0000364 }
365 }
366 // Regardless of whether we find a basis for C, we need to push C to the
Jingyue Wu43885eb2015-04-15 16:46:13 +0000367 // candidate list so that it can be the basis of other candidates.
Jingyue Wud7966ff2015-02-03 19:37:06 +0000368 Candidates.push_back(C);
369}
370
Jingyue Wu43885eb2015-04-15 16:46:13 +0000371void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
372 Instruction *I) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000373 switch (I->getOpcode()) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000374 case Instruction::Add:
375 allocateCandidatesAndFindBasisForAdd(I);
376 break;
Jingyue Wu177a8152015-03-26 16:49:24 +0000377 case Instruction::Mul:
Jingyue Wu43885eb2015-04-15 16:46:13 +0000378 allocateCandidatesAndFindBasisForMul(I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000379 break;
380 case Instruction::GetElementPtr:
Jingyue Wu43885eb2015-04-15 16:46:13 +0000381 allocateCandidatesAndFindBasisForGEP(cast<GetElementPtrInst>(I));
Jingyue Wu177a8152015-03-26 16:49:24 +0000382 break;
383 }
384}
385
Jingyue Wu43885eb2015-04-15 16:46:13 +0000386void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
387 Instruction *I) {
388 // Try matching B + i * S.
389 if (!isa<IntegerType>(I->getType()))
390 return;
391
392 assert(I->getNumOperands() == 2 && "isn't I an add?");
393 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
394 allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
395 if (LHS != RHS)
396 allocateCandidatesAndFindBasisForAdd(RHS, LHS, I);
397}
398
399void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
400 Value *LHS, Value *RHS, Instruction *I) {
401 Value *S = nullptr;
402 ConstantInt *Idx = nullptr;
403 if (match(RHS, m_Mul(m_Value(S), m_ConstantInt(Idx)))) {
404 // I = LHS + RHS = LHS + Idx * S
405 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
406 } else if (match(RHS, m_Shl(m_Value(S), m_ConstantInt(Idx)))) {
407 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
408 APInt One(Idx->getBitWidth(), 1);
409 Idx = ConstantInt::get(Idx->getContext(), One << Idx->getValue());
410 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
411 } else {
412 // At least, I = LHS + 1 * RHS
413 ConstantInt *One = ConstantInt::get(cast<IntegerType>(I->getType()), 1);
414 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), One, RHS,
415 I);
416 }
417}
418
Jingyue Wu80a96d292015-05-15 17:07:48 +0000419// Returns true if A matches B + C where C is constant.
420static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
421 return (match(A, m_Add(m_Value(B), m_ConstantInt(C))) ||
422 match(A, m_Add(m_ConstantInt(C), m_Value(B))));
423}
424
425// Returns true if A matches B | C where C is constant.
426static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
427 return (match(A, m_Or(m_Value(B), m_ConstantInt(C))) ||
428 match(A, m_Or(m_ConstantInt(C), m_Value(B))));
429}
430
Jingyue Wu43885eb2015-04-15 16:46:13 +0000431void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
Jingyue Wu177a8152015-03-26 16:49:24 +0000432 Value *LHS, Value *RHS, Instruction *I) {
Jingyue Wud7966ff2015-02-03 19:37:06 +0000433 Value *B = nullptr;
434 ConstantInt *Idx = nullptr;
Jingyue Wu80a96d292015-05-15 17:07:48 +0000435 if (matchesAdd(LHS, B, Idx)) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000436 // If LHS is in the form of "Base + Index", then I is in the form of
437 // "(Base + Index) * RHS".
Jingyue Wu43885eb2015-04-15 16:46:13 +0000438 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
Jingyue Wu80a96d292015-05-15 17:07:48 +0000439 } else if (matchesOr(LHS, B, Idx) && haveNoCommonBitsSet(B, Idx, *DL)) {
440 // If LHS is in the form of "Base | Index" and Base and Index have no common
441 // bits set, then
442 // Base | Index = Base + Index
443 // and I is thus in the form of "(Base + Index) * RHS".
444 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000445 } else {
446 // Otherwise, at least try the form (LHS + 0) * RHS.
447 ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000448 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS,
Jingyue Wu80a96d292015-05-15 17:07:48 +0000449 I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000450 }
451}
452
Jingyue Wu43885eb2015-04-15 16:46:13 +0000453void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
Jingyue Wu177a8152015-03-26 16:49:24 +0000454 Instruction *I) {
455 // Try matching (B + i) * S.
456 // TODO: we could extend SLSR to float and vector types.
457 if (!isa<IntegerType>(I->getType()))
458 return;
459
Jingyue Wu43885eb2015-04-15 16:46:13 +0000460 assert(I->getNumOperands() == 2 && "isn't I a mul?");
Jingyue Wu177a8152015-03-26 16:49:24 +0000461 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000462 allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000463 if (LHS != RHS) {
464 // Symmetrically, try to split RHS to Base + Index.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000465 allocateCandidatesAndFindBasisForMul(RHS, LHS, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000466 }
467}
468
Jingyue Wu43885eb2015-04-15 16:46:13 +0000469void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000470 const SCEV *B, ConstantInt *Idx, Value *S, uint64_t ElementSize,
471 Instruction *I) {
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000472 // I = B + sext(Idx *nsw S) * ElementSize
473 // = B + (sext(Idx) * sext(S)) * ElementSize
Jingyue Wu177a8152015-03-26 16:49:24 +0000474 // = B + (sext(Idx) * ElementSize) * sext(S)
475 // Casting to IntegerType is safe because we skipped vector GEPs.
476 IntegerType *IntPtrTy = cast<IntegerType>(DL->getIntPtrType(I->getType()));
477 ConstantInt *ScaledIdx = ConstantInt::get(
478 IntPtrTy, Idx->getSExtValue() * (int64_t)ElementSize, true);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000479 allocateCandidatesAndFindBasis(Candidate::GEP, B, ScaledIdx, S, I);
Jingyue Wu177a8152015-03-26 16:49:24 +0000480}
481
482void StraightLineStrengthReduce::factorArrayIndex(Value *ArrayIdx,
483 const SCEV *Base,
484 uint64_t ElementSize,
485 GetElementPtrInst *GEP) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000486 // At least, ArrayIdx = ArrayIdx *nsw 1.
487 allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000488 Base, ConstantInt::get(cast<IntegerType>(ArrayIdx->getType()), 1),
489 ArrayIdx, ElementSize, GEP);
490 Value *LHS = nullptr;
491 ConstantInt *RHS = nullptr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000492 // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
493 // itself. This would allow us to handle the shl case for free. However,
494 // matching SCEVs has two issues:
495 //
496 // 1. this would complicate rewriting because the rewriting procedure
497 // would have to translate SCEVs back to IR instructions. This translation
498 // is difficult when LHS is further evaluated to a composite SCEV.
499 //
500 // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
501 // to strip nsw/nuw flags which are critical for SLSR to trace into
502 // sext'ed multiplication.
503 if (match(ArrayIdx, m_NSWMul(m_Value(LHS), m_ConstantInt(RHS)))) {
504 // SLSR is currently unsafe if i * S may overflow.
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000505 // GEP = Base + sext(LHS *nsw RHS) * ElementSize
Jingyue Wu43885eb2015-04-15 16:46:13 +0000506 allocateCandidatesAndFindBasisForGEP(Base, RHS, LHS, ElementSize, GEP);
Jingyue Wu96d74002015-04-06 17:15:48 +0000507 } else if (match(ArrayIdx, m_NSWShl(m_Value(LHS), m_ConstantInt(RHS)))) {
508 // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
509 // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
510 APInt One(RHS->getBitWidth(), 1);
511 ConstantInt *PowerOf2 =
512 ConstantInt::get(RHS->getContext(), One << RHS->getValue());
Jingyue Wu43885eb2015-04-15 16:46:13 +0000513 allocateCandidatesAndFindBasisForGEP(Base, PowerOf2, LHS, ElementSize, GEP);
Jingyue Wu177a8152015-03-26 16:49:24 +0000514 }
515}
516
Jingyue Wu43885eb2015-04-15 16:46:13 +0000517void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
Jingyue Wu177a8152015-03-26 16:49:24 +0000518 GetElementPtrInst *GEP) {
519 // TODO: handle vector GEPs
520 if (GEP->getType()->isVectorTy())
521 return;
522
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000523 SmallVector<const SCEV *, 4> IndexExprs;
524 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
525 IndexExprs.push_back(SE->getSCEV(*I));
Jingyue Wu177a8152015-03-26 16:49:24 +0000526
527 gep_type_iterator GTI = gep_type_begin(GEP);
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000528 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
529 if (GTI.isStruct())
Jingyue Wu177a8152015-03-26 16:49:24 +0000530 continue;
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000531
532 const SCEV *OrigIndexExpr = IndexExprs[I - 1];
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000533 IndexExprs[I - 1] = SE->getZero(OrigIndexExpr->getType());
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000534
535 // The base of this candidate is GEP's base plus the offsets of all
536 // indices except this current one.
Peter Collingbourne8dff0392016-11-13 06:59:50 +0000537 const SCEV *BaseExpr = SE->getGEPExpr(cast<GEPOperator>(GEP), IndexExprs);
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000538 Value *ArrayIdx = GEP->getOperand(I);
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000539 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
Jingyue Wudebce552016-07-09 19:13:18 +0000540 if (ArrayIdx->getType()->getIntegerBitWidth() <=
Jingyue Wu641cfee2016-07-11 18:13:28 +0000541 DL->getPointerSizeInBits(GEP->getAddressSpace())) {
Jingyue Wudebce552016-07-09 19:13:18 +0000542 // Skip factoring if ArrayIdx is wider than the pointer size, because
543 // ArrayIdx is implicitly truncated to the pointer size.
544 factorArrayIndex(ArrayIdx, BaseExpr, ElementSize, GEP);
545 }
Jingyue Wu177a8152015-03-26 16:49:24 +0000546 // When ArrayIdx is the sext of a value, we try to factor that value as
547 // well. Handling this case is important because array indices are
548 // typically sign-extended to the pointer size.
549 Value *TruncatedArrayIdx = nullptr;
Jingyue Wudebce552016-07-09 19:13:18 +0000550 if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))) &&
551 TruncatedArrayIdx->getType()->getIntegerBitWidth() <=
Jingyue Wu641cfee2016-07-11 18:13:28 +0000552 DL->getPointerSizeInBits(GEP->getAddressSpace())) {
Jingyue Wudebce552016-07-09 19:13:18 +0000553 // Skip factoring if TruncatedArrayIdx is wider than the pointer size,
554 // because TruncatedArrayIdx is implicitly truncated to the pointer size.
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000555 factorArrayIndex(TruncatedArrayIdx, BaseExpr, ElementSize, GEP);
Jingyue Wudebce552016-07-09 19:13:18 +0000556 }
Jingyue Wu2982d4d2015-05-18 17:03:25 +0000557
558 IndexExprs[I - 1] = OrigIndexExpr;
Jingyue Wu177a8152015-03-26 16:49:24 +0000559 }
560}
561
562// A helper function that unifies the bitwidth of A and B.
563static void unifyBitWidth(APInt &A, APInt &B) {
564 if (A.getBitWidth() < B.getBitWidth())
565 A = A.sext(B.getBitWidth());
566 else if (A.getBitWidth() > B.getBitWidth())
567 B = B.sext(A.getBitWidth());
568}
569
570Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
571 const Candidate &C,
572 IRBuilder<> &Builder,
573 const DataLayout *DL,
574 bool &BumpWithUglyGEP) {
575 APInt Idx = C.Index->getValue(), BasisIdx = Basis.Index->getValue();
576 unifyBitWidth(Idx, BasisIdx);
577 APInt IndexOffset = Idx - BasisIdx;
578
579 BumpWithUglyGEP = false;
580 if (Basis.CandidateKind == Candidate::GEP) {
581 APInt ElementSize(
582 IndexOffset.getBitWidth(),
Jingyue Wudebce552016-07-09 19:13:18 +0000583 DL->getTypeAllocSize(
584 cast<GetElementPtrInst>(Basis.Ins)->getResultElementType()));
Jingyue Wu177a8152015-03-26 16:49:24 +0000585 APInt Q, R;
586 APInt::sdivrem(IndexOffset, ElementSize, Q, R);
Jingyue Wudebce552016-07-09 19:13:18 +0000587 if (R == 0)
Jingyue Wu177a8152015-03-26 16:49:24 +0000588 IndexOffset = Q;
589 else
590 BumpWithUglyGEP = true;
591 }
Jingyue Wu43885eb2015-04-15 16:46:13 +0000592
Jingyue Wu177a8152015-03-26 16:49:24 +0000593 // Compute Bump = C - Basis = (i' - i) * S.
594 // Common case 1: if (i' - i) is 1, Bump = S.
Jingyue Wudebce552016-07-09 19:13:18 +0000595 if (IndexOffset == 1)
Jingyue Wu177a8152015-03-26 16:49:24 +0000596 return C.Stride;
597 // Common case 2: if (i' - i) is -1, Bump = -S.
Jingyue Wudebce552016-07-09 19:13:18 +0000598 if (IndexOffset.isAllOnesValue())
Jingyue Wu177a8152015-03-26 16:49:24 +0000599 return Builder.CreateNeg(C.Stride);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000600
601 // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may
602 // have different bit widths.
603 IntegerType *DeltaType =
604 IntegerType::get(Basis.Ins->getContext(), IndexOffset.getBitWidth());
605 Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, DeltaType);
606 if (IndexOffset.isPowerOf2()) {
607 // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i).
608 ConstantInt *Exponent = ConstantInt::get(DeltaType, IndexOffset.logBase2());
609 return Builder.CreateShl(ExtendedStride, Exponent);
610 }
611 if ((-IndexOffset).isPowerOf2()) {
612 // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i).
613 ConstantInt *Exponent =
614 ConstantInt::get(DeltaType, (-IndexOffset).logBase2());
615 return Builder.CreateNeg(Builder.CreateShl(ExtendedStride, Exponent));
616 }
617 Constant *Delta = ConstantInt::get(DeltaType, IndexOffset);
Jingyue Wu177a8152015-03-26 16:49:24 +0000618 return Builder.CreateMul(ExtendedStride, Delta);
619}
620
Jingyue Wud7966ff2015-02-03 19:37:06 +0000621void StraightLineStrengthReduce::rewriteCandidateWithBasis(
622 const Candidate &C, const Candidate &Basis) {
Jingyue Wu177a8152015-03-26 16:49:24 +0000623 assert(C.CandidateKind == Basis.CandidateKind && C.Base == Basis.Base &&
624 C.Stride == Basis.Stride);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000625 // We run rewriteCandidateWithBasis on all candidates in a post-order, so the
626 // basis of a candidate cannot be unlinked before the candidate.
627 assert(Basis.Ins->getParent() != nullptr && "the basis is unlinked");
Jingyue Wu177a8152015-03-26 16:49:24 +0000628
Jingyue Wud7966ff2015-02-03 19:37:06 +0000629 // An instruction can correspond to multiple candidates. Therefore, instead of
630 // simply deleting an instruction when we rewrite it, we mark its parent as
631 // nullptr (i.e. unlink it) so that we can skip the candidates whose
632 // instruction is already rewritten.
633 if (!C.Ins->getParent())
634 return;
Jingyue Wu177a8152015-03-26 16:49:24 +0000635
Jingyue Wud7966ff2015-02-03 19:37:06 +0000636 IRBuilder<> Builder(C.Ins);
Jingyue Wu177a8152015-03-26 16:49:24 +0000637 bool BumpWithUglyGEP;
638 Value *Bump = emitBump(Basis, C, Builder, DL, BumpWithUglyGEP);
639 Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
640 switch (C.CandidateKind) {
Jingyue Wu43885eb2015-04-15 16:46:13 +0000641 case Candidate::Add:
Sanjay Patel51414352018-10-23 14:07:39 +0000642 case Candidate::Mul: {
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000643 // C = Basis + Bump
Sanjay Patel51414352018-10-23 14:07:39 +0000644 Value *NegBump;
645 if (match(Bump, m_Neg(m_Value(NegBump)))) {
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000646 // If Bump is a neg instruction, emit C = Basis - (-Bump).
Sanjay Patel51414352018-10-23 14:07:39 +0000647 Reduced = Builder.CreateSub(Basis.Ins, NegBump);
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000648 // We only use the negative argument of Bump, and Bump itself may be
649 // trivially dead.
650 RecursivelyDeleteTriviallyDeadInstructions(Bump);
Jingyue Wu43885eb2015-04-15 16:46:13 +0000651 } else {
Jingyue Wua9411292015-06-18 03:35:57 +0000652 // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
653 // usually unsound, e.g.,
654 //
655 // X = (-2 +nsw 1) *nsw INT_MAX
656 // Y = (-2 +nsw 3) *nsw INT_MAX
657 // =>
658 // Y = X + 2 * INT_MAX
659 //
660 // Neither + and * in the resultant expression are nsw.
Jingyue Wu43885eb2015-04-15 16:46:13 +0000661 Reduced = Builder.CreateAdd(Basis.Ins, Bump);
662 }
Jingyue Wu177a8152015-03-26 16:49:24 +0000663 break;
Sanjay Patel51414352018-10-23 14:07:39 +0000664 }
Jingyue Wu177a8152015-03-26 16:49:24 +0000665 case Candidate::GEP:
666 {
667 Type *IntPtrTy = DL->getIntPtrType(C.Ins->getType());
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000668 bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds();
Jingyue Wu177a8152015-03-26 16:49:24 +0000669 if (BumpWithUglyGEP) {
670 // C = (char *)Basis + Bump
671 unsigned AS = Basis.Ins->getType()->getPointerAddressSpace();
672 Type *CharTy = Type::getInt8PtrTy(Basis.Ins->getContext(), AS);
673 Reduced = Builder.CreateBitCast(Basis.Ins, CharTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000674 if (InBounds)
David Blaikieaa41cd52015-04-03 21:33:42 +0000675 Reduced =
676 Builder.CreateInBoundsGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000677 else
David Blaikie93c54442015-04-03 19:41:44 +0000678 Reduced = Builder.CreateGEP(Builder.getInt8Ty(), Reduced, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000679 Reduced = Builder.CreateBitCast(Reduced, C.Ins->getType());
680 } else {
681 // C = gep Basis, Bump
682 // Canonicalize bump to pointer size.
683 Bump = Builder.CreateSExtOrTrunc(Bump, IntPtrTy);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000684 if (InBounds)
James Y Knight77160752019-02-01 20:44:47 +0000685 Reduced = Builder.CreateInBoundsGEP(
686 cast<GetElementPtrInst>(Basis.Ins)->getResultElementType(),
687 Basis.Ins, Bump);
Jingyue Wu99a6bed2015-04-02 21:18:32 +0000688 else
James Y Knight77160752019-02-01 20:44:47 +0000689 Reduced = Builder.CreateGEP(
690 cast<GetElementPtrInst>(Basis.Ins)->getResultElementType(),
691 Basis.Ins, Bump);
Jingyue Wu177a8152015-03-26 16:49:24 +0000692 }
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000693 break;
Jingyue Wu177a8152015-03-26 16:49:24 +0000694 }
Jingyue Wu177a8152015-03-26 16:49:24 +0000695 default:
696 llvm_unreachable("C.CandidateKind is invalid");
697 };
Jingyue Wud7966ff2015-02-03 19:37:06 +0000698 Reduced->takeName(C.Ins);
699 C.Ins->replaceAllUsesWith(Reduced);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000700 // Unlink C.Ins so that we can skip other candidates also corresponding to
701 // C.Ins. The actual deletion is postponed to the end of runOnFunction.
702 C.Ins->removeFromParent();
Jingyue Wu43885eb2015-04-15 16:46:13 +0000703 UnlinkedInstructions.push_back(C.Ins);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000704}
705
706bool StraightLineStrengthReduce::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000707 if (skipFunction(F))
Jingyue Wud7966ff2015-02-03 19:37:06 +0000708 return false;
709
Jingyue Wu177a8152015-03-26 16:49:24 +0000710 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000711 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000712 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000713 // Traverse the dominator tree in the depth-first order. This order makes sure
714 // all bases of a candidate are in Candidates when we process it.
Daniel Berlina36f4632016-08-19 22:06:23 +0000715 for (const auto Node : depth_first(DT))
716 for (auto &I : *(Node->getBlock()))
Jingyue Wu43885eb2015-04-15 16:46:13 +0000717 allocateCandidatesAndFindBasis(&I);
Jingyue Wud7966ff2015-02-03 19:37:06 +0000718
719 // Rewrite candidates in the reverse depth-first order. This order makes sure
720 // a candidate being rewritten is not a basis for any other candidate.
721 while (!Candidates.empty()) {
722 const Candidate &C = Candidates.back();
723 if (C.Basis != nullptr) {
724 rewriteCandidateWithBasis(C, *C.Basis);
725 }
726 Candidates.pop_back();
727 }
728
729 // Delete all unlink instructions.
Jingyue Wuf1edf3e2015-04-21 19:56:18 +0000730 for (auto *UnlinkedInst : UnlinkedInstructions) {
731 for (unsigned I = 0, E = UnlinkedInst->getNumOperands(); I != E; ++I) {
732 Value *Op = UnlinkedInst->getOperand(I);
733 UnlinkedInst->setOperand(I, nullptr);
734 RecursivelyDeleteTriviallyDeadInstructions(Op);
735 }
Reid Kleckner96ab8722017-05-18 17:24:10 +0000736 UnlinkedInst->deleteValue();
Jingyue Wud7966ff2015-02-03 19:37:06 +0000737 }
738 bool Ret = !UnlinkedInstructions.empty();
739 UnlinkedInstructions.clear();
740 return Ret;
741}