1 //===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass reassociates n-ary add expressions and eliminates the redundancy
11 // exposed by the reassociation.
13 // A motivating example:
15 // void foo(int a, int b) {
20 // An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify
27 // However, the Reassociate pass is unable to do that because it processes each
28 // instruction individually and believes (a + 2) + b is the best form according
29 // to its rank system.
31 // To address this limitation, NaryReassociate reassociates an expression in a
32 // form that reuses existing instructions. As a result, NaryReassociate can
33 // reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that
34 // (a + b) is computed before.
36 // NaryReassociate works as follows. For every instruction in the form of (a +
37 // b) + c, it checks whether a + c or b + c is already computed by a dominating
38 // instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b +
39 // c) + a respectively. To efficiently look up whether an expression is
40 // computed before, we store each instruction seen and its SCEV into an
41 // SCEV-to-instruction map.
43 // Although the algorithm pattern-matches only ternary additions, it
44 // automatically handles many >3-ary expressions by walking through the function
45 // in the depth-first order. For example, given
50 // NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites
51 // ((a + c) + b) + d into ((a + c) + d) + b.
53 // Limitations and TODO items:
55 // 1) We only considers n-ary adds for now. This should be extended and
58 // 2) Besides arithmetic operations, similar reassociation can be applied to
59 // GEPs. For example, if
63 // we may rewrite Y into X + b.
65 //===----------------------------------------------------------------------===//
67 #include "llvm/Analysis/ScalarEvolution.h"
68 #include "llvm/IR/Dominators.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/PatternMatch.h"
71 #include "llvm/Transforms/Scalar.h"
73 using namespace PatternMatch;
75 #define DEBUG_TYPE "nary-reassociate"
78 class NaryReassociate : public FunctionPass {
82 NaryReassociate(): FunctionPass(ID) {
83 initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
86 bool runOnFunction(Function &F) override;
88 void getAnalysisUsage(AnalysisUsage &AU) const override {
89 AU.addPreserved<DominatorTreeWrapperPass>();
90 AU.addRequired<DominatorTreeWrapperPass>();
91 // TODO: can we preserve ScalarEvolution?
92 AU.addRequired<ScalarEvolution>();
97 // Reasssociates I to a better form.
98 Instruction *tryReassociateAdd(Instruction *I);
99 // A helper function for tryReassociateAdd. LHS and RHS are explicitly passed.
100 Instruction *tryReassociateAdd(Value *LHS, Value *RHS, Instruction *I);
101 // Rewrites I to LHS + RHS if LHS is computed already.
102 Instruction *tryReassociatedAdd(const SCEV *LHS, Value *RHS, Instruction *I);
106 // A lookup table quickly telling which instructions compute the given SCEV.
107 // Note that there can be multiple instructions at different locations
108 // computing to the same SCEV. For example,
113 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs;
115 } // anonymous namespace
117 char NaryReassociate::ID = 0;
118 INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
120 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
121 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
122 INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation",
125 FunctionPass *llvm::createNaryReassociatePass() {
126 return new NaryReassociate();
129 bool NaryReassociate::runOnFunction(Function &F) {
130 if (skipOptnoneFunction(F))
133 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
134 SE = &getAnalysis<ScalarEvolution>();
136 // Traverse the dominator tree in the depth-first order. This order makes sure
137 // all bases of a candidate are in Candidates when we process it.
138 bool Changed = false;
140 for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
141 Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
142 BasicBlock *BB = Node->getBlock();
143 for (auto I = BB->begin(); I != BB->end(); ++I) {
144 if (I->getOpcode() == Instruction::Add) {
145 if (Instruction *NewI = tryReassociateAdd(I)) {
146 I->replaceAllUsesWith(NewI);
147 I->eraseFromParent();
150 // We should add the rewritten instruction because tryReassociateAdd may
151 // have invalidated the original one.
152 SeenExprs[SE->getSCEV(I)].push_back(I);
159 Instruction *NaryReassociate::tryReassociateAdd(Instruction *I) {
160 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
161 if (auto *NewI = tryReassociateAdd(LHS, RHS, I))
163 if (auto *NewI = tryReassociateAdd(RHS, LHS, I))
168 Instruction *NaryReassociate::tryReassociateAdd(Value *LHS, Value *RHS,
170 Value *A = nullptr, *B = nullptr;
171 // To be conservative, we reassociate I only when it is the only user of A+B.
172 if (LHS->hasOneUse() && match(LHS, m_Add(m_Value(A), m_Value(B)))) {
174 // = (A + RHS) + B or (B + RHS) + A
175 const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
176 const SCEV *RHSExpr = SE->getSCEV(RHS);
177 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(AExpr, RHSExpr), B, I))
179 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(BExpr, RHSExpr), A, I))
185 Instruction *NaryReassociate::tryReassociatedAdd(const SCEV *LHSExpr,
186 Value *RHS, Instruction *I) {
187 auto Pos = SeenExprs.find(LHSExpr);
188 // Bail out if LHSExpr is not previously seen.
189 if (Pos == SeenExprs.end())
192 auto &LHSCandidates = Pos->second;
193 unsigned NumIterations = 0;
194 // Search at most 10 items to avoid running quadratically.
195 static const unsigned MaxNumIterations = 10;
196 for (auto LHS = LHSCandidates.rbegin();
197 LHS != LHSCandidates.rend() && NumIterations < MaxNumIterations;
198 ++LHS, ++NumIterations) {
199 if (DT->dominates(*LHS, I)) {
200 Instruction *NewI = BinaryOperator::CreateAdd(*LHS, RHS, "", I);