StraightLineStrengthReduce.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. //===-- StraightLineStrengthReduce.cpp - ------------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements straight-line strength reduction (SLSR). Unlike loop
  11. // strength reduction, this algorithm is designed to reduce arithmetic
  12. // redundancy in straight-line code instead of loops. It has proven to be
  13. // effective in simplifying arithmetic statements derived from an unrolled loop.
  14. // It can also simplify the logic of SeparateConstOffsetFromGEP.
  15. //
  16. // There are many optimizations we can perform in the domain of SLSR. This file
  17. // for now contains only an initial step. Specifically, we look for strength
  18. // reduction candidates in the following forms:
  19. //
  20. // Form 1: B + i * S
  21. // Form 2: (B + i) * S
  22. // Form 3: &B[i * S]
  23. //
  24. // where S is an integer variable, and i is a constant integer. If we found two
  25. // candidates S1 and S2 in the same form and S1 dominates S2, we may rewrite S2
  26. // in a simpler way with respect to S1. For example,
  27. //
  28. // S1: X = B + i * S
  29. // S2: Y = B + i' * S => X + (i' - i) * S
  30. //
  31. // S1: X = (B + i) * S
  32. // S2: Y = (B + i') * S => X + (i' - i) * S
  33. //
  34. // S1: X = &B[i * S]
  35. // S2: Y = &B[i' * S] => &X[(i' - i) * S]
  36. //
  37. // Note: (i' - i) * S is folded to the extent possible.
  38. //
  39. // This rewriting is in general a good idea. The code patterns we focus on
  40. // usually come from loop unrolling, so (i' - i) * S is likely the same
  41. // across iterations and can be reused. When that happens, the optimized form
  42. // takes only one add starting from the second iteration.
  43. //
  44. // When such rewriting is possible, we call S1 a "basis" of S2. When S2 has
  45. // multiple bases, we choose to rewrite S2 with respect to its "immediate"
  46. // basis, the basis that is the closest ancestor in the dominator tree.
  47. //
  48. // TODO:
  49. //
  50. // - Floating point arithmetics when fast math is enabled.
  51. //
  52. // - SLSR may decrease ILP at the architecture level. Targets that are very
  53. // sensitive to ILP may want to disable it. Having SLSR to consider ILP is
  54. // left as future work.
  55. //
  56. // - When (i' - i) is constant but i and i' are not, we could still perform
  57. // SLSR.
  58. #include <vector>
  59. // //
  60. ///////////////////////////////////////////////////////////////////////////////
  61. #include "llvm/ADT/DenseSet.h"
  62. #include "llvm/ADT/FoldingSet.h"
  63. #include "llvm/Analysis/ScalarEvolution.h"
  64. #include "llvm/Analysis/TargetTransformInfo.h"
  65. #include "llvm/Analysis/ValueTracking.h"
  66. #include "llvm/IR/DataLayout.h"
  67. #include "llvm/IR/Dominators.h"
  68. #include "llvm/IR/IRBuilder.h"
  69. #include "llvm/IR/Module.h"
  70. #include "llvm/IR/PatternMatch.h"
  71. #include "llvm/Support/raw_ostream.h"
  72. #include "llvm/Transforms/Scalar.h"
  73. #include "llvm/Transforms/Utils/Local.h"
  74. using namespace llvm;
  75. using namespace PatternMatch;
  76. namespace {
  77. class StraightLineStrengthReduce : public FunctionPass {
  78. public:
  79. // SLSR candidate. Such a candidate must be in one of the forms described in
  80. // the header comments.
  81. struct Candidate : public ilist_node<Candidate> {
  82. enum Kind {
  83. Invalid, // reserved for the default constructor
  84. Add, // B + i * S
  85. Mul, // (B + i) * S
  86. GEP, // &B[..][i * S][..]
  87. };
  88. Candidate()
  89. : CandidateKind(Invalid), Base(nullptr), Index(nullptr),
  90. Stride(nullptr), Ins(nullptr), Basis(nullptr) {}
  91. Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
  92. Instruction *I)
  93. : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I),
  94. Basis(nullptr) {}
  95. Kind CandidateKind;
  96. const SCEV *Base;
  97. // Note that Index and Stride of a GEP candidate do not necessarily have the
  98. // same integer type. In that case, during rewriting, Stride will be
  99. // sign-extended or truncated to Index's type.
  100. ConstantInt *Index;
  101. Value *Stride;
  102. // The instruction this candidate corresponds to. It helps us to rewrite a
  103. // candidate with respect to its immediate basis. Note that one instruction
  104. // can correspond to multiple candidates depending on how you associate the
  105. // expression. For instance,
  106. //
  107. // (a + 1) * (b + 2)
  108. //
  109. // can be treated as
  110. //
  111. // <Base: a, Index: 1, Stride: b + 2>
  112. //
  113. // or
  114. //
  115. // <Base: b, Index: 2, Stride: a + 1>
  116. Instruction *Ins;
  117. // Points to the immediate basis of this candidate, or nullptr if we cannot
  118. // find any basis for this candidate.
  119. Candidate *Basis;
  120. };
  121. static char ID;
  122. StraightLineStrengthReduce()
  123. : FunctionPass(ID), DL(nullptr), DT(nullptr), TTI(nullptr) {
  124. initializeStraightLineStrengthReducePass(*PassRegistry::getPassRegistry());
  125. }
  126. void getAnalysisUsage(AnalysisUsage &AU) const override {
  127. AU.addRequired<DominatorTreeWrapperPass>();
  128. AU.addRequired<ScalarEvolution>();
  129. AU.addRequired<TargetTransformInfoWrapperPass>();
  130. // We do not modify the shape of the CFG.
  131. AU.setPreservesCFG();
  132. }
  133. bool doInitialization(Module &M) override {
  134. DL = &M.getDataLayout();
  135. return false;
  136. }
  137. bool runOnFunction(Function &F) override;
  138. private:
  139. // Returns true if Basis is a basis for C, i.e., Basis dominates C and they
  140. // share the same base and stride.
  141. bool isBasisFor(const Candidate &Basis, const Candidate &C);
  142. // Returns whether the candidate can be folded into an addressing mode.
  143. bool isFoldable(const Candidate &C, TargetTransformInfo *TTI,
  144. const DataLayout *DL);
  145. // Returns true if C is already in a simplest form and not worth being
  146. // rewritten.
  147. bool isSimplestForm(const Candidate &C);
  148. // Checks whether I is in a candidate form. If so, adds all the matching forms
  149. // to Candidates, and tries to find the immediate basis for each of them.
  150. void allocateCandidatesAndFindBasis(Instruction *I);
  151. // Allocate candidates and find bases for Add instructions.
  152. void allocateCandidatesAndFindBasisForAdd(Instruction *I);
  153. // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a
  154. // candidate.
  155. void allocateCandidatesAndFindBasisForAdd(Value *LHS, Value *RHS,
  156. Instruction *I);
  157. // Allocate candidates and find bases for Mul instructions.
  158. void allocateCandidatesAndFindBasisForMul(Instruction *I);
  159. // Splits LHS into Base + Index and, if succeeds, calls
  160. // allocateCandidatesAndFindBasis.
  161. void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS,
  162. Instruction *I);
  163. // Allocate candidates and find bases for GetElementPtr instructions.
  164. void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP);
  165. // A helper function that scales Idx with ElementSize before invoking
  166. // allocateCandidatesAndFindBasis.
  167. void allocateCandidatesAndFindBasisForGEP(const SCEV *B, ConstantInt *Idx,
  168. Value *S, uint64_t ElementSize,
  169. Instruction *I);
  170. // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate
  171. // basis.
  172. void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B,
  173. ConstantInt *Idx, Value *S,
  174. Instruction *I);
  175. // Rewrites candidate C with respect to Basis.
  176. void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis);
  177. // A helper function that factors ArrayIdx to a product of a stride and a
  178. // constant index, and invokes allocateCandidatesAndFindBasis with the
  179. // factorings.
  180. void factorArrayIndex(Value *ArrayIdx, const SCEV *Base, uint64_t ElementSize,
  181. GetElementPtrInst *GEP);
  182. // Emit code that computes the "bump" from Basis to C. If the candidate is a
  183. // GEP and the bump is not divisible by the element size of the GEP, this
  184. // function sets the BumpWithUglyGEP flag to notify its caller to bump the
  185. // basis using an ugly GEP.
  186. static Value *emitBump(const Candidate &Basis, const Candidate &C,
  187. IRBuilder<> &Builder, const DataLayout *DL,
  188. bool &BumpWithUglyGEP);
  189. const DataLayout *DL;
  190. DominatorTree *DT;
  191. ScalarEvolution *SE;
  192. TargetTransformInfo *TTI;
  193. ilist<Candidate> Candidates;
  194. // Temporarily holds all instructions that are unlinked (but not deleted) by
  195. // rewriteCandidateWithBasis. These instructions will be actually removed
  196. // after all rewriting finishes.
  197. std::vector<Instruction *> UnlinkedInstructions;
  198. };
  199. } // anonymous namespace
  200. char StraightLineStrengthReduce::ID = 0;
  201. INITIALIZE_PASS_BEGIN(StraightLineStrengthReduce, "slsr",
  202. "Straight line strength reduction", false, false)
  203. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  204. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  205. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  206. INITIALIZE_PASS_END(StraightLineStrengthReduce, "slsr",
  207. "Straight line strength reduction", false, false)
  208. FunctionPass *llvm::createStraightLineStrengthReducePass() {
  209. return new StraightLineStrengthReduce();
  210. }
  211. bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis,
  212. const Candidate &C) {
  213. return (Basis.Ins != C.Ins && // skip the same instruction
  214. // They must have the same type too. Basis.Base == C.Base doesn't
  215. // guarantee their types are the same (PR23975).
  216. Basis.Ins->getType() == C.Ins->getType() &&
  217. // Basis must dominate C in order to rewrite C with respect to Basis.
  218. DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) &&
  219. // They share the same base, stride, and candidate kind.
  220. Basis.Base == C.Base && Basis.Stride == C.Stride &&
  221. Basis.CandidateKind == C.CandidateKind);
  222. }
  223. static bool isGEPFoldable(GetElementPtrInst *GEP,
  224. const TargetTransformInfo *TTI,
  225. const DataLayout *DL) {
  226. GlobalVariable *BaseGV = nullptr;
  227. int64_t BaseOffset = 0;
  228. bool HasBaseReg = false;
  229. int64_t Scale = 0;
  230. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
  231. BaseGV = GV;
  232. else
  233. HasBaseReg = true;
  234. gep_type_iterator GTI = gep_type_begin(GEP);
  235. for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) {
  236. if (isa<SequentialType>(*GTI)) {
  237. int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
  238. if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
  239. BaseOffset += ConstIdx->getSExtValue() * ElementSize;
  240. } else {
  241. // Needs scale register.
  242. if (Scale != 0) {
  243. // No addressing mode takes two scale registers.
  244. return false;
  245. }
  246. Scale = ElementSize;
  247. }
  248. } else {
  249. StructType *STy = cast<StructType>(*GTI);
  250. uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
  251. BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
  252. }
  253. }
  254. unsigned AddrSpace = GEP->getPointerAddressSpace();
  255. return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV,
  256. BaseOffset, HasBaseReg, Scale, AddrSpace);
  257. }
  258. // Returns whether (Base + Index * Stride) can be folded to an addressing mode.
  259. static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride,
  260. TargetTransformInfo *TTI) {
  261. return TTI->isLegalAddressingMode(Base->getType(), nullptr, 0, true,
  262. Index->getSExtValue());
  263. }
  264. bool StraightLineStrengthReduce::isFoldable(const Candidate &C,
  265. TargetTransformInfo *TTI,
  266. const DataLayout *DL) {
  267. if (C.CandidateKind == Candidate::Add)
  268. return isAddFoldable(C.Base, C.Index, C.Stride, TTI);
  269. if (C.CandidateKind == Candidate::GEP)
  270. return isGEPFoldable(cast<GetElementPtrInst>(C.Ins), TTI, DL);
  271. return false;
  272. }
  273. // Returns true if GEP has zero or one non-zero index.
  274. static bool hasOnlyOneNonZeroIndex(GetElementPtrInst *GEP) {
  275. unsigned NumNonZeroIndices = 0;
  276. for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) {
  277. ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
  278. if (ConstIdx == nullptr || !ConstIdx->isZero())
  279. ++NumNonZeroIndices;
  280. }
  281. return NumNonZeroIndices <= 1;
  282. }
  283. bool StraightLineStrengthReduce::isSimplestForm(const Candidate &C) {
  284. if (C.CandidateKind == Candidate::Add) {
  285. // B + 1 * S or B + (-1) * S
  286. return C.Index->isOne() || C.Index->isMinusOne();
  287. }
  288. if (C.CandidateKind == Candidate::Mul) {
  289. // (B + 0) * S
  290. return C.Index->isZero();
  291. }
  292. if (C.CandidateKind == Candidate::GEP) {
  293. // (char*)B + S or (char*)B - S
  294. return ((C.Index->isOne() || C.Index->isMinusOne()) &&
  295. hasOnlyOneNonZeroIndex(cast<GetElementPtrInst>(C.Ins)));
  296. }
  297. return false;
  298. }
  299. // TODO: We currently implement an algorithm whose time complexity is linear in
  300. // the number of existing candidates. However, we could do better by using
  301. // ScopedHashTable. Specifically, while traversing the dominator tree, we could
  302. // maintain all the candidates that dominate the basic block being traversed in
  303. // a ScopedHashTable. This hash table is indexed by the base and the stride of
  304. // a candidate. Therefore, finding the immediate basis of a candidate boils down
  305. // to one hash-table look up.
  306. void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
  307. Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S,
  308. Instruction *I) {
  309. Candidate C(CT, B, Idx, S, I);
  310. // SLSR can complicate an instruction in two cases:
  311. //
  312. // 1. If we can fold I into an addressing mode, computing I is likely free or
  313. // takes only one instruction.
  314. //
  315. // 2. I is already in a simplest form. For example, when
  316. // X = B + 8 * S
  317. // Y = B + S,
  318. // rewriting Y to X - 7 * S is probably a bad idea.
  319. //
  320. // In the above cases, we still add I to the candidate list so that I can be
  321. // the basis of other candidates, but we leave I's basis blank so that I
  322. // won't be rewritten.
  323. if (!isFoldable(C, TTI, DL) && !isSimplestForm(C)) {
  324. // Try to compute the immediate basis of C.
  325. unsigned NumIterations = 0;
  326. // Limit the scan radius to avoid running in quadratice time.
  327. static const unsigned MaxNumIterations = 50;
  328. for (auto Basis = Candidates.rbegin();
  329. Basis != Candidates.rend() && NumIterations < MaxNumIterations;
  330. ++Basis, ++NumIterations) {
  331. if (isBasisFor(*Basis, C)) {
  332. C.Basis = &(*Basis);
  333. break;
  334. }
  335. }
  336. }
  337. // Regardless of whether we find a basis for C, we need to push C to the
  338. // candidate list so that it can be the basis of other candidates.
  339. Candidates.push_back(C);
  340. }
  341. void StraightLineStrengthReduce::allocateCandidatesAndFindBasis(
  342. Instruction *I) {
  343. switch (I->getOpcode()) {
  344. case Instruction::Add:
  345. allocateCandidatesAndFindBasisForAdd(I);
  346. break;
  347. case Instruction::Mul:
  348. allocateCandidatesAndFindBasisForMul(I);
  349. break;
  350. case Instruction::GetElementPtr:
  351. allocateCandidatesAndFindBasisForGEP(cast<GetElementPtrInst>(I));
  352. break;
  353. }
  354. }
  355. void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
  356. Instruction *I) {
  357. // Try matching B + i * S.
  358. if (!isa<IntegerType>(I->getType()))
  359. return;
  360. assert(I->getNumOperands() == 2 && "isn't I an add?");
  361. Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
  362. allocateCandidatesAndFindBasisForAdd(LHS, RHS, I);
  363. if (LHS != RHS)
  364. allocateCandidatesAndFindBasisForAdd(RHS, LHS, I);
  365. }
  366. void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd(
  367. Value *LHS, Value *RHS, Instruction *I) {
  368. Value *S = nullptr;
  369. ConstantInt *Idx = nullptr;
  370. if (match(RHS, m_Mul(m_Value(S), m_ConstantInt(Idx)))) {
  371. // I = LHS + RHS = LHS + Idx * S
  372. allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
  373. } else if (match(RHS, m_Shl(m_Value(S), m_ConstantInt(Idx)))) {
  374. // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx)
  375. APInt One(Idx->getBitWidth(), 1);
  376. Idx = ConstantInt::get(Idx->getContext(), One << Idx->getValue());
  377. allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I);
  378. } else {
  379. // At least, I = LHS + 1 * RHS
  380. ConstantInt *One = ConstantInt::get(cast<IntegerType>(I->getType()), 1);
  381. allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), One, RHS,
  382. I);
  383. }
  384. }
  385. // Returns true if A matches B + C where C is constant.
  386. static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) {
  387. return (match(A, m_Add(m_Value(B), m_ConstantInt(C))) ||
  388. match(A, m_Add(m_ConstantInt(C), m_Value(B))));
  389. }
  390. // Returns true if A matches B | C where C is constant.
  391. static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) {
  392. return (match(A, m_Or(m_Value(B), m_ConstantInt(C))) ||
  393. match(A, m_Or(m_ConstantInt(C), m_Value(B))));
  394. }
  395. void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
  396. Value *LHS, Value *RHS, Instruction *I) {
  397. Value *B = nullptr;
  398. ConstantInt *Idx = nullptr;
  399. if (matchesAdd(LHS, B, Idx)) {
  400. // If LHS is in the form of "Base + Index", then I is in the form of
  401. // "(Base + Index) * RHS".
  402. allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
  403. } else if (matchesOr(LHS, B, Idx) && haveNoCommonBitsSet(B, Idx, *DL)) {
  404. // If LHS is in the form of "Base | Index" and Base and Index have no common
  405. // bits set, then
  406. // Base | Index = Base + Index
  407. // and I is thus in the form of "(Base + Index) * RHS".
  408. allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I);
  409. } else {
  410. // Otherwise, at least try the form (LHS + 0) * RHS.
  411. ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0);
  412. allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS,
  413. I);
  414. }
  415. }
  416. void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul(
  417. Instruction *I) {
  418. // Try matching (B + i) * S.
  419. // TODO: we could extend SLSR to float and vector types.
  420. if (!isa<IntegerType>(I->getType()))
  421. return;
  422. assert(I->getNumOperands() == 2 && "isn't I a mul?");
  423. Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
  424. allocateCandidatesAndFindBasisForMul(LHS, RHS, I);
  425. if (LHS != RHS) {
  426. // Symmetrically, try to split RHS to Base + Index.
  427. allocateCandidatesAndFindBasisForMul(RHS, LHS, I);
  428. }
  429. }
  430. void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
  431. const SCEV *B, ConstantInt *Idx, Value *S, uint64_t ElementSize,
  432. Instruction *I) {
  433. // I = B + sext(Idx *nsw S) * ElementSize
  434. // = B + (sext(Idx) * sext(S)) * ElementSize
  435. // = B + (sext(Idx) * ElementSize) * sext(S)
  436. // Casting to IntegerType is safe because we skipped vector GEPs.
  437. IntegerType *IntPtrTy = cast<IntegerType>(DL->getIntPtrType(I->getType()));
  438. ConstantInt *ScaledIdx = ConstantInt::get(
  439. IntPtrTy, Idx->getSExtValue() * (int64_t)ElementSize, true);
  440. allocateCandidatesAndFindBasis(Candidate::GEP, B, ScaledIdx, S, I);
  441. }
  442. void StraightLineStrengthReduce::factorArrayIndex(Value *ArrayIdx,
  443. const SCEV *Base,
  444. uint64_t ElementSize,
  445. GetElementPtrInst *GEP) {
  446. // At least, ArrayIdx = ArrayIdx *nsw 1.
  447. allocateCandidatesAndFindBasisForGEP(
  448. Base, ConstantInt::get(cast<IntegerType>(ArrayIdx->getType()), 1),
  449. ArrayIdx, ElementSize, GEP);
  450. Value *LHS = nullptr;
  451. ConstantInt *RHS = nullptr;
  452. // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx
  453. // itself. This would allow us to handle the shl case for free. However,
  454. // matching SCEVs has two issues:
  455. //
  456. // 1. this would complicate rewriting because the rewriting procedure
  457. // would have to translate SCEVs back to IR instructions. This translation
  458. // is difficult when LHS is further evaluated to a composite SCEV.
  459. //
  460. // 2. ScalarEvolution is designed to be control-flow oblivious. It tends
  461. // to strip nsw/nuw flags which are critical for SLSR to trace into
  462. // sext'ed multiplication.
  463. if (match(ArrayIdx, m_NSWMul(m_Value(LHS), m_ConstantInt(RHS)))) {
  464. // SLSR is currently unsafe if i * S may overflow.
  465. // GEP = Base + sext(LHS *nsw RHS) * ElementSize
  466. allocateCandidatesAndFindBasisForGEP(Base, RHS, LHS, ElementSize, GEP);
  467. } else if (match(ArrayIdx, m_NSWShl(m_Value(LHS), m_ConstantInt(RHS)))) {
  468. // GEP = Base + sext(LHS <<nsw RHS) * ElementSize
  469. // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize
  470. APInt One(RHS->getBitWidth(), 1);
  471. ConstantInt *PowerOf2 =
  472. ConstantInt::get(RHS->getContext(), One << RHS->getValue());
  473. allocateCandidatesAndFindBasisForGEP(Base, PowerOf2, LHS, ElementSize, GEP);
  474. }
  475. }
  476. void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP(
  477. GetElementPtrInst *GEP) {
  478. // TODO: handle vector GEPs
  479. if (GEP->getType()->isVectorTy())
  480. return;
  481. SmallVector<const SCEV *, 4> IndexExprs;
  482. for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
  483. IndexExprs.push_back(SE->getSCEV(*I));
  484. gep_type_iterator GTI = gep_type_begin(GEP);
  485. for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
  486. if (!isa<SequentialType>(*GTI++))
  487. continue;
  488. const SCEV *OrigIndexExpr = IndexExprs[I - 1];
  489. IndexExprs[I - 1] = SE->getConstant(OrigIndexExpr->getType(), 0);
  490. // The base of this candidate is GEP's base plus the offsets of all
  491. // indices except this current one.
  492. const SCEV *BaseExpr = SE->getGEPExpr(GEP->getSourceElementType(),
  493. SE->getSCEV(GEP->getPointerOperand()),
  494. IndexExprs, GEP->isInBounds());
  495. Value *ArrayIdx = GEP->getOperand(I);
  496. uint64_t ElementSize = DL->getTypeAllocSize(*GTI);
  497. factorArrayIndex(ArrayIdx, BaseExpr, ElementSize, GEP);
  498. // When ArrayIdx is the sext of a value, we try to factor that value as
  499. // well. Handling this case is important because array indices are
  500. // typically sign-extended to the pointer size.
  501. Value *TruncatedArrayIdx = nullptr;
  502. if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))))
  503. factorArrayIndex(TruncatedArrayIdx, BaseExpr, ElementSize, GEP);
  504. IndexExprs[I - 1] = OrigIndexExpr;
  505. }
  506. }
  507. // A helper function that unifies the bitwidth of A and B.
  508. static void unifyBitWidth(APInt &A, APInt &B) {
  509. if (A.getBitWidth() < B.getBitWidth())
  510. A = A.sext(B.getBitWidth());
  511. else if (A.getBitWidth() > B.getBitWidth())
  512. B = B.sext(A.getBitWidth());
  513. }
  514. Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis,
  515. const Candidate &C,
  516. IRBuilder<> &Builder,
  517. const DataLayout *DL,
  518. bool &BumpWithUglyGEP) {
  519. APInt Idx = C.Index->getValue(), BasisIdx = Basis.Index->getValue();
  520. unifyBitWidth(Idx, BasisIdx);
  521. APInt IndexOffset = Idx - BasisIdx;
  522. BumpWithUglyGEP = false;
  523. if (Basis.CandidateKind == Candidate::GEP) {
  524. APInt ElementSize(
  525. IndexOffset.getBitWidth(),
  526. DL->getTypeAllocSize(
  527. cast<GetElementPtrInst>(Basis.Ins)->getType()->getElementType()));
  528. APInt Q, R;
  529. APInt::sdivrem(IndexOffset, ElementSize, Q, R);
  530. if (R.getSExtValue() == 0)
  531. IndexOffset = Q;
  532. else
  533. BumpWithUglyGEP = true;
  534. }
  535. // Compute Bump = C - Basis = (i' - i) * S.
  536. // Common case 1: if (i' - i) is 1, Bump = S.
  537. if (IndexOffset.getSExtValue() == 1)
  538. return C.Stride;
  539. // Common case 2: if (i' - i) is -1, Bump = -S.
  540. if (IndexOffset.getSExtValue() == -1)
  541. return Builder.CreateNeg(C.Stride);
  542. // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may
  543. // have different bit widths.
  544. IntegerType *DeltaType =
  545. IntegerType::get(Basis.Ins->getContext(), IndexOffset.getBitWidth());
  546. Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, DeltaType);
  547. if (IndexOffset.isPowerOf2()) {
  548. // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i).
  549. ConstantInt *Exponent = ConstantInt::get(DeltaType, IndexOffset.logBase2());
  550. return Builder.CreateShl(ExtendedStride, Exponent);
  551. }
  552. if ((-IndexOffset).isPowerOf2()) {
  553. // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i).
  554. ConstantInt *Exponent =
  555. ConstantInt::get(DeltaType, (-IndexOffset).logBase2());
  556. return Builder.CreateNeg(Builder.CreateShl(ExtendedStride, Exponent));
  557. }
  558. Constant *Delta = ConstantInt::get(DeltaType, IndexOffset);
  559. return Builder.CreateMul(ExtendedStride, Delta);
  560. }
  561. void StraightLineStrengthReduce::rewriteCandidateWithBasis(
  562. const Candidate &C, const Candidate &Basis) {
  563. assert(C.CandidateKind == Basis.CandidateKind && C.Base == Basis.Base &&
  564. C.Stride == Basis.Stride);
  565. // We run rewriteCandidateWithBasis on all candidates in a post-order, so the
  566. // basis of a candidate cannot be unlinked before the candidate.
  567. assert(Basis.Ins->getParent() != nullptr && "the basis is unlinked");
  568. // An instruction can correspond to multiple candidates. Therefore, instead of
  569. // simply deleting an instruction when we rewrite it, we mark its parent as
  570. // nullptr (i.e. unlink it) so that we can skip the candidates whose
  571. // instruction is already rewritten.
  572. if (!C.Ins->getParent())
  573. return;
  574. IRBuilder<> Builder(C.Ins);
  575. bool BumpWithUglyGEP;
  576. Value *Bump = emitBump(Basis, C, Builder, DL, BumpWithUglyGEP);
  577. Value *Reduced = nullptr; // equivalent to but weaker than C.Ins
  578. switch (C.CandidateKind) {
  579. case Candidate::Add:
  580. case Candidate::Mul:
  581. // C = Basis + Bump
  582. if (BinaryOperator::isNeg(Bump)) {
  583. // If Bump is a neg instruction, emit C = Basis - (-Bump).
  584. Reduced =
  585. Builder.CreateSub(Basis.Ins, BinaryOperator::getNegArgument(Bump));
  586. // We only use the negative argument of Bump, and Bump itself may be
  587. // trivially dead.
  588. RecursivelyDeleteTriviallyDeadInstructions(Bump);
  589. } else {
  590. // It's tempting to preserve nsw on Bump and/or Reduced. However, it's
  591. // usually unsound, e.g.,
  592. //
  593. // X = (-2 +nsw 1) *nsw INT_MAX
  594. // Y = (-2 +nsw 3) *nsw INT_MAX
  595. // =>
  596. // Y = X + 2 * INT_MAX
  597. //
  598. // Neither + and * in the resultant expression are nsw.
  599. Reduced = Builder.CreateAdd(Basis.Ins, Bump);
  600. }
  601. break;
  602. case Candidate::GEP:
  603. {
  604. Type *IntPtrTy = DL->getIntPtrType(C.Ins->getType());
  605. bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds();
  606. if (BumpWithUglyGEP) {
  607. // C = (char *)Basis + Bump
  608. unsigned AS = Basis.Ins->getType()->getPointerAddressSpace();
  609. Type *CharTy = Type::getInt8PtrTy(Basis.Ins->getContext(), AS);
  610. Reduced = Builder.CreateBitCast(Basis.Ins, CharTy);
  611. if (InBounds)
  612. Reduced =
  613. Builder.CreateInBoundsGEP(Builder.getInt8Ty(), Reduced, Bump);
  614. else
  615. Reduced = Builder.CreateGEP(Builder.getInt8Ty(), Reduced, Bump);
  616. Reduced = Builder.CreateBitCast(Reduced, C.Ins->getType());
  617. } else {
  618. // C = gep Basis, Bump
  619. // Canonicalize bump to pointer size.
  620. Bump = Builder.CreateSExtOrTrunc(Bump, IntPtrTy);
  621. if (InBounds)
  622. Reduced = Builder.CreateInBoundsGEP(nullptr, Basis.Ins, Bump);
  623. else
  624. Reduced = Builder.CreateGEP(nullptr, Basis.Ins, Bump);
  625. }
  626. }
  627. break;
  628. default:
  629. llvm_unreachable("C.CandidateKind is invalid");
  630. };
  631. Reduced->takeName(C.Ins);
  632. C.Ins->replaceAllUsesWith(Reduced);
  633. // Unlink C.Ins so that we can skip other candidates also corresponding to
  634. // C.Ins. The actual deletion is postponed to the end of runOnFunction.
  635. C.Ins->removeFromParent();
  636. UnlinkedInstructions.push_back(C.Ins);
  637. }
  638. bool StraightLineStrengthReduce::runOnFunction(Function &F) {
  639. if (skipOptnoneFunction(F))
  640. return false;
  641. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  642. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  643. SE = &getAnalysis<ScalarEvolution>();
  644. // Traverse the dominator tree in the depth-first order. This order makes sure
  645. // all bases of a candidate are in Candidates when we process it.
  646. for (auto node = GraphTraits<DominatorTree *>::nodes_begin(DT);
  647. node != GraphTraits<DominatorTree *>::nodes_end(DT); ++node) {
  648. for (auto &I : *node->getBlock())
  649. allocateCandidatesAndFindBasis(&I);
  650. }
  651. // Rewrite candidates in the reverse depth-first order. This order makes sure
  652. // a candidate being rewritten is not a basis for any other candidate.
  653. while (!Candidates.empty()) {
  654. const Candidate &C = Candidates.back();
  655. if (C.Basis != nullptr) {
  656. rewriteCandidateWithBasis(C, *C.Basis);
  657. }
  658. Candidates.pop_back();
  659. }
  660. // Delete all unlink instructions.
  661. for (auto *UnlinkedInst : UnlinkedInstructions) {
  662. for (unsigned I = 0, E = UnlinkedInst->getNumOperands(); I != E; ++I) {
  663. Value *Op = UnlinkedInst->getOperand(I);
  664. UnlinkedInst->setOperand(I, nullptr);
  665. RecursivelyDeleteTriviallyDeadInstructions(Op);
  666. }
  667. delete UnlinkedInst;
  668. }
  669. bool Ret = !UnlinkedInstructions.empty();
  670. UnlinkedInstructions.clear();
  671. return Ret;
  672. }