xref: /aosp_15_r20/external/llvm/lib/Transforms/Scalar/NaryReassociate.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass reassociates n-ary add expressions and eliminates the redundancy
11*9880d681SAndroid Build Coastguard Worker // exposed by the reassociation.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker // A motivating example:
14*9880d681SAndroid Build Coastguard Worker //
15*9880d681SAndroid Build Coastguard Worker //   void foo(int a, int b) {
16*9880d681SAndroid Build Coastguard Worker //     bar(a + b);
17*9880d681SAndroid Build Coastguard Worker //     bar((a + 2) + b);
18*9880d681SAndroid Build Coastguard Worker //   }
19*9880d681SAndroid Build Coastguard Worker //
20*9880d681SAndroid Build Coastguard Worker // An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify
21*9880d681SAndroid Build Coastguard Worker // the above code to
22*9880d681SAndroid Build Coastguard Worker //
23*9880d681SAndroid Build Coastguard Worker //   int t = a + b;
24*9880d681SAndroid Build Coastguard Worker //   bar(t);
25*9880d681SAndroid Build Coastguard Worker //   bar(t + 2);
26*9880d681SAndroid Build Coastguard Worker //
27*9880d681SAndroid Build Coastguard Worker // However, the Reassociate pass is unable to do that because it processes each
28*9880d681SAndroid Build Coastguard Worker // instruction individually and believes (a + 2) + b is the best form according
29*9880d681SAndroid Build Coastguard Worker // to its rank system.
30*9880d681SAndroid Build Coastguard Worker //
31*9880d681SAndroid Build Coastguard Worker // To address this limitation, NaryReassociate reassociates an expression in a
32*9880d681SAndroid Build Coastguard Worker // form that reuses existing instructions. As a result, NaryReassociate can
33*9880d681SAndroid Build Coastguard Worker // reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that
34*9880d681SAndroid Build Coastguard Worker // (a + b) is computed before.
35*9880d681SAndroid Build Coastguard Worker //
36*9880d681SAndroid Build Coastguard Worker // NaryReassociate works as follows. For every instruction in the form of (a +
37*9880d681SAndroid Build Coastguard Worker // b) + c, it checks whether a + c or b + c is already computed by a dominating
38*9880d681SAndroid Build Coastguard Worker // instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b +
39*9880d681SAndroid Build Coastguard Worker // c) + a and removes the redundancy accordingly. To efficiently look up whether
40*9880d681SAndroid Build Coastguard Worker // an expression is computed before, we store each instruction seen and its SCEV
41*9880d681SAndroid Build Coastguard Worker // into an SCEV-to-instruction map.
42*9880d681SAndroid Build Coastguard Worker //
43*9880d681SAndroid Build Coastguard Worker // Although the algorithm pattern-matches only ternary additions, it
44*9880d681SAndroid Build Coastguard Worker // automatically handles many >3-ary expressions by walking through the function
45*9880d681SAndroid Build Coastguard Worker // in the depth-first order. For example, given
46*9880d681SAndroid Build Coastguard Worker //
47*9880d681SAndroid Build Coastguard Worker //   (a + c) + d
48*9880d681SAndroid Build Coastguard Worker //   ((a + b) + c) + d
49*9880d681SAndroid Build Coastguard Worker //
50*9880d681SAndroid Build Coastguard Worker // NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites
51*9880d681SAndroid Build Coastguard Worker // ((a + c) + b) + d into ((a + c) + d) + b.
52*9880d681SAndroid Build Coastguard Worker //
53*9880d681SAndroid Build Coastguard Worker // Finally, the above dominator-based algorithm may need to be run multiple
54*9880d681SAndroid Build Coastguard Worker // iterations before emitting optimal code. One source of this need is that we
55*9880d681SAndroid Build Coastguard Worker // only split an operand when it is used only once. The above algorithm can
56*9880d681SAndroid Build Coastguard Worker // eliminate an instruction and decrease the usage count of its operands. As a
57*9880d681SAndroid Build Coastguard Worker // result, an instruction that previously had multiple uses may become a
58*9880d681SAndroid Build Coastguard Worker // single-use instruction and thus eligible for split consideration. For
59*9880d681SAndroid Build Coastguard Worker // example,
60*9880d681SAndroid Build Coastguard Worker //
61*9880d681SAndroid Build Coastguard Worker //   ac = a + c
62*9880d681SAndroid Build Coastguard Worker //   ab = a + b
63*9880d681SAndroid Build Coastguard Worker //   abc = ab + c
64*9880d681SAndroid Build Coastguard Worker //   ab2 = ab + b
65*9880d681SAndroid Build Coastguard Worker //   ab2c = ab2 + c
66*9880d681SAndroid Build Coastguard Worker //
67*9880d681SAndroid Build Coastguard Worker // In the first iteration, we cannot reassociate abc to ac+b because ab is used
68*9880d681SAndroid Build Coastguard Worker // twice. However, we can reassociate ab2c to abc+b in the first iteration. As a
69*9880d681SAndroid Build Coastguard Worker // result, ab2 becomes dead and ab will be used only once in the second
70*9880d681SAndroid Build Coastguard Worker // iteration.
71*9880d681SAndroid Build Coastguard Worker //
72*9880d681SAndroid Build Coastguard Worker // Limitations and TODO items:
73*9880d681SAndroid Build Coastguard Worker //
74*9880d681SAndroid Build Coastguard Worker // 1) We only considers n-ary adds and muls for now. This should be extended
75*9880d681SAndroid Build Coastguard Worker // and generalized.
76*9880d681SAndroid Build Coastguard Worker //
77*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
78*9880d681SAndroid Build Coastguard Worker 
79*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
80*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolution.h"
81*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
82*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
83*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
84*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
85*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
86*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
87*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
88*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
89*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
90*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
91*9880d681SAndroid Build Coastguard Worker using namespace llvm;
92*9880d681SAndroid Build Coastguard Worker using namespace PatternMatch;
93*9880d681SAndroid Build Coastguard Worker 
94*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "nary-reassociate"
95*9880d681SAndroid Build Coastguard Worker 
96*9880d681SAndroid Build Coastguard Worker namespace {
97*9880d681SAndroid Build Coastguard Worker class NaryReassociate : public FunctionPass {
98*9880d681SAndroid Build Coastguard Worker public:
99*9880d681SAndroid Build Coastguard Worker   static char ID;
100*9880d681SAndroid Build Coastguard Worker 
NaryReassociate()101*9880d681SAndroid Build Coastguard Worker   NaryReassociate(): FunctionPass(ID) {
102*9880d681SAndroid Build Coastguard Worker     initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
103*9880d681SAndroid Build Coastguard Worker   }
104*9880d681SAndroid Build Coastguard Worker 
doInitialization(Module & M)105*9880d681SAndroid Build Coastguard Worker   bool doInitialization(Module &M) override {
106*9880d681SAndroid Build Coastguard Worker     DL = &M.getDataLayout();
107*9880d681SAndroid Build Coastguard Worker     return false;
108*9880d681SAndroid Build Coastguard Worker   }
109*9880d681SAndroid Build Coastguard Worker   bool runOnFunction(Function &F) override;
110*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const111*9880d681SAndroid Build Coastguard Worker   void getAnalysisUsage(AnalysisUsage &AU) const override {
112*9880d681SAndroid Build Coastguard Worker     AU.addPreserved<DominatorTreeWrapperPass>();
113*9880d681SAndroid Build Coastguard Worker     AU.addPreserved<ScalarEvolutionWrapperPass>();
114*9880d681SAndroid Build Coastguard Worker     AU.addPreserved<TargetLibraryInfoWrapperPass>();
115*9880d681SAndroid Build Coastguard Worker     AU.addRequired<AssumptionCacheTracker>();
116*9880d681SAndroid Build Coastguard Worker     AU.addRequired<DominatorTreeWrapperPass>();
117*9880d681SAndroid Build Coastguard Worker     AU.addRequired<ScalarEvolutionWrapperPass>();
118*9880d681SAndroid Build Coastguard Worker     AU.addRequired<TargetLibraryInfoWrapperPass>();
119*9880d681SAndroid Build Coastguard Worker     AU.addRequired<TargetTransformInfoWrapperPass>();
120*9880d681SAndroid Build Coastguard Worker     AU.setPreservesCFG();
121*9880d681SAndroid Build Coastguard Worker   }
122*9880d681SAndroid Build Coastguard Worker 
123*9880d681SAndroid Build Coastguard Worker private:
124*9880d681SAndroid Build Coastguard Worker   // Runs only one iteration of the dominator-based algorithm. See the header
125*9880d681SAndroid Build Coastguard Worker   // comments for why we need multiple iterations.
126*9880d681SAndroid Build Coastguard Worker   bool doOneIteration(Function &F);
127*9880d681SAndroid Build Coastguard Worker 
128*9880d681SAndroid Build Coastguard Worker   // Reassociates I for better CSE.
129*9880d681SAndroid Build Coastguard Worker   Instruction *tryReassociate(Instruction *I);
130*9880d681SAndroid Build Coastguard Worker 
131*9880d681SAndroid Build Coastguard Worker   // Reassociate GEP for better CSE.
132*9880d681SAndroid Build Coastguard Worker   Instruction *tryReassociateGEP(GetElementPtrInst *GEP);
133*9880d681SAndroid Build Coastguard Worker   // Try splitting GEP at the I-th index and see whether either part can be
134*9880d681SAndroid Build Coastguard Worker   // CSE'ed. This is a helper function for tryReassociateGEP.
135*9880d681SAndroid Build Coastguard Worker   //
136*9880d681SAndroid Build Coastguard Worker   // \p IndexedType The element type indexed by GEP's I-th index. This is
137*9880d681SAndroid Build Coastguard Worker   //                equivalent to
138*9880d681SAndroid Build Coastguard Worker   //                  GEP->getIndexedType(GEP->getPointerOperand(), 0-th index,
139*9880d681SAndroid Build Coastguard Worker   //                                      ..., i-th index).
140*9880d681SAndroid Build Coastguard Worker   GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
141*9880d681SAndroid Build Coastguard Worker                                               unsigned I, Type *IndexedType);
142*9880d681SAndroid Build Coastguard Worker   // Given GEP's I-th index = LHS + RHS, see whether &Base[..][LHS][..] or
143*9880d681SAndroid Build Coastguard Worker   // &Base[..][RHS][..] can be CSE'ed and rewrite GEP accordingly.
144*9880d681SAndroid Build Coastguard Worker   GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
145*9880d681SAndroid Build Coastguard Worker                                               unsigned I, Value *LHS,
146*9880d681SAndroid Build Coastguard Worker                                               Value *RHS, Type *IndexedType);
147*9880d681SAndroid Build Coastguard Worker 
148*9880d681SAndroid Build Coastguard Worker   // Reassociate binary operators for better CSE.
149*9880d681SAndroid Build Coastguard Worker   Instruction *tryReassociateBinaryOp(BinaryOperator *I);
150*9880d681SAndroid Build Coastguard Worker 
151*9880d681SAndroid Build Coastguard Worker   // A helper function for tryReassociateBinaryOp. LHS and RHS are explicitly
152*9880d681SAndroid Build Coastguard Worker   // passed.
153*9880d681SAndroid Build Coastguard Worker   Instruction *tryReassociateBinaryOp(Value *LHS, Value *RHS,
154*9880d681SAndroid Build Coastguard Worker                                       BinaryOperator *I);
155*9880d681SAndroid Build Coastguard Worker   // Rewrites I to (LHS op RHS) if LHS is computed already.
156*9880d681SAndroid Build Coastguard Worker   Instruction *tryReassociatedBinaryOp(const SCEV *LHS, Value *RHS,
157*9880d681SAndroid Build Coastguard Worker                                        BinaryOperator *I);
158*9880d681SAndroid Build Coastguard Worker 
159*9880d681SAndroid Build Coastguard Worker   // Tries to match Op1 and Op2 by using V.
160*9880d681SAndroid Build Coastguard Worker   bool matchTernaryOp(BinaryOperator *I, Value *V, Value *&Op1, Value *&Op2);
161*9880d681SAndroid Build Coastguard Worker 
162*9880d681SAndroid Build Coastguard Worker   // Gets SCEV for (LHS op RHS).
163*9880d681SAndroid Build Coastguard Worker   const SCEV *getBinarySCEV(BinaryOperator *I, const SCEV *LHS,
164*9880d681SAndroid Build Coastguard Worker                             const SCEV *RHS);
165*9880d681SAndroid Build Coastguard Worker 
166*9880d681SAndroid Build Coastguard Worker   // Returns the closest dominator of \c Dominatee that computes
167*9880d681SAndroid Build Coastguard Worker   // \c CandidateExpr. Returns null if not found.
168*9880d681SAndroid Build Coastguard Worker   Instruction *findClosestMatchingDominator(const SCEV *CandidateExpr,
169*9880d681SAndroid Build Coastguard Worker                                             Instruction *Dominatee);
170*9880d681SAndroid Build Coastguard Worker   // GetElementPtrInst implicitly sign-extends an index if the index is shorter
171*9880d681SAndroid Build Coastguard Worker   // than the pointer size. This function returns whether Index is shorter than
172*9880d681SAndroid Build Coastguard Worker   // GEP's pointer size, i.e., whether Index needs to be sign-extended in order
173*9880d681SAndroid Build Coastguard Worker   // to be an index of GEP.
174*9880d681SAndroid Build Coastguard Worker   bool requiresSignExtension(Value *Index, GetElementPtrInst *GEP);
175*9880d681SAndroid Build Coastguard Worker 
176*9880d681SAndroid Build Coastguard Worker   AssumptionCache *AC;
177*9880d681SAndroid Build Coastguard Worker   const DataLayout *DL;
178*9880d681SAndroid Build Coastguard Worker   DominatorTree *DT;
179*9880d681SAndroid Build Coastguard Worker   ScalarEvolution *SE;
180*9880d681SAndroid Build Coastguard Worker   TargetLibraryInfo *TLI;
181*9880d681SAndroid Build Coastguard Worker   TargetTransformInfo *TTI;
182*9880d681SAndroid Build Coastguard Worker   // A lookup table quickly telling which instructions compute the given SCEV.
183*9880d681SAndroid Build Coastguard Worker   // Note that there can be multiple instructions at different locations
184*9880d681SAndroid Build Coastguard Worker   // computing to the same SCEV, so we map a SCEV to an instruction list.  For
185*9880d681SAndroid Build Coastguard Worker   // example,
186*9880d681SAndroid Build Coastguard Worker   //
187*9880d681SAndroid Build Coastguard Worker   //   if (p1)
188*9880d681SAndroid Build Coastguard Worker   //     foo(a + b);
189*9880d681SAndroid Build Coastguard Worker   //   if (p2)
190*9880d681SAndroid Build Coastguard Worker   //     bar(a + b);
191*9880d681SAndroid Build Coastguard Worker   DenseMap<const SCEV *, SmallVector<WeakVH, 2>> SeenExprs;
192*9880d681SAndroid Build Coastguard Worker };
193*9880d681SAndroid Build Coastguard Worker } // anonymous namespace
194*9880d681SAndroid Build Coastguard Worker 
195*9880d681SAndroid Build Coastguard Worker char NaryReassociate::ID = 0;
196*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
197*9880d681SAndroid Build Coastguard Worker                       false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)198*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
199*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
200*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
201*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
202*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
203*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation",
204*9880d681SAndroid Build Coastguard Worker                     false, false)
205*9880d681SAndroid Build Coastguard Worker 
206*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createNaryReassociatePass() {
207*9880d681SAndroid Build Coastguard Worker   return new NaryReassociate();
208*9880d681SAndroid Build Coastguard Worker }
209*9880d681SAndroid Build Coastguard Worker 
runOnFunction(Function & F)210*9880d681SAndroid Build Coastguard Worker bool NaryReassociate::runOnFunction(Function &F) {
211*9880d681SAndroid Build Coastguard Worker   if (skipFunction(F))
212*9880d681SAndroid Build Coastguard Worker     return false;
213*9880d681SAndroid Build Coastguard Worker 
214*9880d681SAndroid Build Coastguard Worker   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
215*9880d681SAndroid Build Coastguard Worker   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
216*9880d681SAndroid Build Coastguard Worker   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
217*9880d681SAndroid Build Coastguard Worker   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
218*9880d681SAndroid Build Coastguard Worker   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
219*9880d681SAndroid Build Coastguard Worker 
220*9880d681SAndroid Build Coastguard Worker   bool Changed = false, ChangedInThisIteration;
221*9880d681SAndroid Build Coastguard Worker   do {
222*9880d681SAndroid Build Coastguard Worker     ChangedInThisIteration = doOneIteration(F);
223*9880d681SAndroid Build Coastguard Worker     Changed |= ChangedInThisIteration;
224*9880d681SAndroid Build Coastguard Worker   } while (ChangedInThisIteration);
225*9880d681SAndroid Build Coastguard Worker   return Changed;
226*9880d681SAndroid Build Coastguard Worker }
227*9880d681SAndroid Build Coastguard Worker 
228*9880d681SAndroid Build Coastguard Worker // Whitelist the instruction types NaryReassociate handles for now.
isPotentiallyNaryReassociable(Instruction * I)229*9880d681SAndroid Build Coastguard Worker static bool isPotentiallyNaryReassociable(Instruction *I) {
230*9880d681SAndroid Build Coastguard Worker   switch (I->getOpcode()) {
231*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
232*9880d681SAndroid Build Coastguard Worker   case Instruction::GetElementPtr:
233*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:
234*9880d681SAndroid Build Coastguard Worker     return true;
235*9880d681SAndroid Build Coastguard Worker   default:
236*9880d681SAndroid Build Coastguard Worker     return false;
237*9880d681SAndroid Build Coastguard Worker   }
238*9880d681SAndroid Build Coastguard Worker }
239*9880d681SAndroid Build Coastguard Worker 
doOneIteration(Function & F)240*9880d681SAndroid Build Coastguard Worker bool NaryReassociate::doOneIteration(Function &F) {
241*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
242*9880d681SAndroid Build Coastguard Worker   SeenExprs.clear();
243*9880d681SAndroid Build Coastguard Worker   // Process the basic blocks in pre-order of the dominator tree. This order
244*9880d681SAndroid Build Coastguard Worker   // ensures that all bases of a candidate are in Candidates when we process it.
245*9880d681SAndroid Build Coastguard Worker   for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
246*9880d681SAndroid Build Coastguard Worker        Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
247*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB = Node->getBlock();
248*9880d681SAndroid Build Coastguard Worker     for (auto I = BB->begin(); I != BB->end(); ++I) {
249*9880d681SAndroid Build Coastguard Worker       if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(&*I)) {
250*9880d681SAndroid Build Coastguard Worker         const SCEV *OldSCEV = SE->getSCEV(&*I);
251*9880d681SAndroid Build Coastguard Worker         if (Instruction *NewI = tryReassociate(&*I)) {
252*9880d681SAndroid Build Coastguard Worker           Changed = true;
253*9880d681SAndroid Build Coastguard Worker           SE->forgetValue(&*I);
254*9880d681SAndroid Build Coastguard Worker           I->replaceAllUsesWith(NewI);
255*9880d681SAndroid Build Coastguard Worker           // If SeenExprs constains I's WeakVH, that entry will be replaced with
256*9880d681SAndroid Build Coastguard Worker           // nullptr.
257*9880d681SAndroid Build Coastguard Worker           RecursivelyDeleteTriviallyDeadInstructions(&*I, TLI);
258*9880d681SAndroid Build Coastguard Worker           I = NewI->getIterator();
259*9880d681SAndroid Build Coastguard Worker         }
260*9880d681SAndroid Build Coastguard Worker         // Add the rewritten instruction to SeenExprs; the original instruction
261*9880d681SAndroid Build Coastguard Worker         // is deleted.
262*9880d681SAndroid Build Coastguard Worker         const SCEV *NewSCEV = SE->getSCEV(&*I);
263*9880d681SAndroid Build Coastguard Worker         SeenExprs[NewSCEV].push_back(WeakVH(&*I));
264*9880d681SAndroid Build Coastguard Worker         // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
265*9880d681SAndroid Build Coastguard Worker         // is equivalent to I. However, ScalarEvolution::getSCEV may
266*9880d681SAndroid Build Coastguard Worker         // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose
267*9880d681SAndroid Build Coastguard Worker         // we reassociate
268*9880d681SAndroid Build Coastguard Worker         //   I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
269*9880d681SAndroid Build Coastguard Worker         // to
270*9880d681SAndroid Build Coastguard Worker         //   NewI = &a[sext(i)] + sext(j).
271*9880d681SAndroid Build Coastguard Worker         //
272*9880d681SAndroid Build Coastguard Worker         // ScalarEvolution computes
273*9880d681SAndroid Build Coastguard Worker         //   getSCEV(I)    = a + 4 * sext(i + j)
274*9880d681SAndroid Build Coastguard Worker         //   getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
275*9880d681SAndroid Build Coastguard Worker         // which are different SCEVs.
276*9880d681SAndroid Build Coastguard Worker         //
277*9880d681SAndroid Build Coastguard Worker         // To alleviate this issue of ScalarEvolution not always capturing
278*9880d681SAndroid Build Coastguard Worker         // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
279*9880d681SAndroid Build Coastguard Worker         // map both SCEV before and after tryReassociate(I) to I.
280*9880d681SAndroid Build Coastguard Worker         //
281*9880d681SAndroid Build Coastguard Worker         // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
282*9880d681SAndroid Build Coastguard Worker         if (NewSCEV != OldSCEV)
283*9880d681SAndroid Build Coastguard Worker           SeenExprs[OldSCEV].push_back(WeakVH(&*I));
284*9880d681SAndroid Build Coastguard Worker       }
285*9880d681SAndroid Build Coastguard Worker     }
286*9880d681SAndroid Build Coastguard Worker   }
287*9880d681SAndroid Build Coastguard Worker   return Changed;
288*9880d681SAndroid Build Coastguard Worker }
289*9880d681SAndroid Build Coastguard Worker 
tryReassociate(Instruction * I)290*9880d681SAndroid Build Coastguard Worker Instruction *NaryReassociate::tryReassociate(Instruction *I) {
291*9880d681SAndroid Build Coastguard Worker   switch (I->getOpcode()) {
292*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
293*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:
294*9880d681SAndroid Build Coastguard Worker     return tryReassociateBinaryOp(cast<BinaryOperator>(I));
295*9880d681SAndroid Build Coastguard Worker   case Instruction::GetElementPtr:
296*9880d681SAndroid Build Coastguard Worker     return tryReassociateGEP(cast<GetElementPtrInst>(I));
297*9880d681SAndroid Build Coastguard Worker   default:
298*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
299*9880d681SAndroid Build Coastguard Worker   }
300*9880d681SAndroid Build Coastguard Worker }
301*9880d681SAndroid Build Coastguard Worker 
isGEPFoldable(GetElementPtrInst * GEP,const TargetTransformInfo * TTI)302*9880d681SAndroid Build Coastguard Worker static bool isGEPFoldable(GetElementPtrInst *GEP,
303*9880d681SAndroid Build Coastguard Worker                           const TargetTransformInfo *TTI) {
304*9880d681SAndroid Build Coastguard Worker   SmallVector<const Value*, 4> Indices;
305*9880d681SAndroid Build Coastguard Worker   for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
306*9880d681SAndroid Build Coastguard Worker     Indices.push_back(*I);
307*9880d681SAndroid Build Coastguard Worker   return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
308*9880d681SAndroid Build Coastguard Worker                          Indices) == TargetTransformInfo::TCC_Free;
309*9880d681SAndroid Build Coastguard Worker }
310*9880d681SAndroid Build Coastguard Worker 
tryReassociateGEP(GetElementPtrInst * GEP)311*9880d681SAndroid Build Coastguard Worker Instruction *NaryReassociate::tryReassociateGEP(GetElementPtrInst *GEP) {
312*9880d681SAndroid Build Coastguard Worker   // Not worth reassociating GEP if it is foldable.
313*9880d681SAndroid Build Coastguard Worker   if (isGEPFoldable(GEP, TTI))
314*9880d681SAndroid Build Coastguard Worker     return nullptr;
315*9880d681SAndroid Build Coastguard Worker 
316*9880d681SAndroid Build Coastguard Worker   gep_type_iterator GTI = gep_type_begin(*GEP);
317*9880d681SAndroid Build Coastguard Worker   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
318*9880d681SAndroid Build Coastguard Worker     if (isa<SequentialType>(*GTI++)) {
319*9880d681SAndroid Build Coastguard Worker       if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1, *GTI)) {
320*9880d681SAndroid Build Coastguard Worker         return NewGEP;
321*9880d681SAndroid Build Coastguard Worker       }
322*9880d681SAndroid Build Coastguard Worker     }
323*9880d681SAndroid Build Coastguard Worker   }
324*9880d681SAndroid Build Coastguard Worker   return nullptr;
325*9880d681SAndroid Build Coastguard Worker }
326*9880d681SAndroid Build Coastguard Worker 
requiresSignExtension(Value * Index,GetElementPtrInst * GEP)327*9880d681SAndroid Build Coastguard Worker bool NaryReassociate::requiresSignExtension(Value *Index,
328*9880d681SAndroid Build Coastguard Worker                                             GetElementPtrInst *GEP) {
329*9880d681SAndroid Build Coastguard Worker   unsigned PointerSizeInBits =
330*9880d681SAndroid Build Coastguard Worker       DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
331*9880d681SAndroid Build Coastguard Worker   return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
332*9880d681SAndroid Build Coastguard Worker }
333*9880d681SAndroid Build Coastguard Worker 
334*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *
tryReassociateGEPAtIndex(GetElementPtrInst * GEP,unsigned I,Type * IndexedType)335*9880d681SAndroid Build Coastguard Worker NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I,
336*9880d681SAndroid Build Coastguard Worker                                           Type *IndexedType) {
337*9880d681SAndroid Build Coastguard Worker   Value *IndexToSplit = GEP->getOperand(I + 1);
338*9880d681SAndroid Build Coastguard Worker   if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) {
339*9880d681SAndroid Build Coastguard Worker     IndexToSplit = SExt->getOperand(0);
340*9880d681SAndroid Build Coastguard Worker   } else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(IndexToSplit)) {
341*9880d681SAndroid Build Coastguard Worker     // zext can be treated as sext if the source is non-negative.
342*9880d681SAndroid Build Coastguard Worker     if (isKnownNonNegative(ZExt->getOperand(0), *DL, 0, AC, GEP, DT))
343*9880d681SAndroid Build Coastguard Worker       IndexToSplit = ZExt->getOperand(0);
344*9880d681SAndroid Build Coastguard Worker   }
345*9880d681SAndroid Build Coastguard Worker 
346*9880d681SAndroid Build Coastguard Worker   if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
347*9880d681SAndroid Build Coastguard Worker     // If the I-th index needs sext and the underlying add is not equipped with
348*9880d681SAndroid Build Coastguard Worker     // nsw, we cannot split the add because
349*9880d681SAndroid Build Coastguard Worker     //   sext(LHS + RHS) != sext(LHS) + sext(RHS).
350*9880d681SAndroid Build Coastguard Worker     if (requiresSignExtension(IndexToSplit, GEP) &&
351*9880d681SAndroid Build Coastguard Worker         computeOverflowForSignedAdd(AO, *DL, AC, GEP, DT) !=
352*9880d681SAndroid Build Coastguard Worker             OverflowResult::NeverOverflows)
353*9880d681SAndroid Build Coastguard Worker       return nullptr;
354*9880d681SAndroid Build Coastguard Worker 
355*9880d681SAndroid Build Coastguard Worker     Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
356*9880d681SAndroid Build Coastguard Worker     // IndexToSplit = LHS + RHS.
357*9880d681SAndroid Build Coastguard Worker     if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
358*9880d681SAndroid Build Coastguard Worker       return NewGEP;
359*9880d681SAndroid Build Coastguard Worker     // Symmetrically, try IndexToSplit = RHS + LHS.
360*9880d681SAndroid Build Coastguard Worker     if (LHS != RHS) {
361*9880d681SAndroid Build Coastguard Worker       if (auto *NewGEP =
362*9880d681SAndroid Build Coastguard Worker               tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
363*9880d681SAndroid Build Coastguard Worker         return NewGEP;
364*9880d681SAndroid Build Coastguard Worker     }
365*9880d681SAndroid Build Coastguard Worker   }
366*9880d681SAndroid Build Coastguard Worker   return nullptr;
367*9880d681SAndroid Build Coastguard Worker }
368*9880d681SAndroid Build Coastguard Worker 
tryReassociateGEPAtIndex(GetElementPtrInst * GEP,unsigned I,Value * LHS,Value * RHS,Type * IndexedType)369*9880d681SAndroid Build Coastguard Worker GetElementPtrInst *NaryReassociate::tryReassociateGEPAtIndex(
370*9880d681SAndroid Build Coastguard Worker     GetElementPtrInst *GEP, unsigned I, Value *LHS, Value *RHS,
371*9880d681SAndroid Build Coastguard Worker     Type *IndexedType) {
372*9880d681SAndroid Build Coastguard Worker   // Look for GEP's closest dominator that has the same SCEV as GEP except that
373*9880d681SAndroid Build Coastguard Worker   // the I-th index is replaced with LHS.
374*9880d681SAndroid Build Coastguard Worker   SmallVector<const SCEV *, 4> IndexExprs;
375*9880d681SAndroid Build Coastguard Worker   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
376*9880d681SAndroid Build Coastguard Worker     IndexExprs.push_back(SE->getSCEV(*Index));
377*9880d681SAndroid Build Coastguard Worker   // Replace the I-th index with LHS.
378*9880d681SAndroid Build Coastguard Worker   IndexExprs[I] = SE->getSCEV(LHS);
379*9880d681SAndroid Build Coastguard Worker   if (isKnownNonNegative(LHS, *DL, 0, AC, GEP, DT) &&
380*9880d681SAndroid Build Coastguard Worker       DL->getTypeSizeInBits(LHS->getType()) <
381*9880d681SAndroid Build Coastguard Worker           DL->getTypeSizeInBits(GEP->getOperand(I)->getType())) {
382*9880d681SAndroid Build Coastguard Worker     // Zero-extend LHS if it is non-negative. InstCombine canonicalizes sext to
383*9880d681SAndroid Build Coastguard Worker     // zext if the source operand is proved non-negative. We should do that
384*9880d681SAndroid Build Coastguard Worker     // consistently so that CandidateExpr more likely appears before. See
385*9880d681SAndroid Build Coastguard Worker     // @reassociate_gep_assume for an example of this canonicalization.
386*9880d681SAndroid Build Coastguard Worker     IndexExprs[I] =
387*9880d681SAndroid Build Coastguard Worker         SE->getZeroExtendExpr(IndexExprs[I], GEP->getOperand(I)->getType());
388*9880d681SAndroid Build Coastguard Worker   }
389*9880d681SAndroid Build Coastguard Worker   const SCEV *CandidateExpr = SE->getGEPExpr(
390*9880d681SAndroid Build Coastguard Worker       GEP->getSourceElementType(), SE->getSCEV(GEP->getPointerOperand()),
391*9880d681SAndroid Build Coastguard Worker       IndexExprs, GEP->isInBounds());
392*9880d681SAndroid Build Coastguard Worker 
393*9880d681SAndroid Build Coastguard Worker   Value *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
394*9880d681SAndroid Build Coastguard Worker   if (Candidate == nullptr)
395*9880d681SAndroid Build Coastguard Worker     return nullptr;
396*9880d681SAndroid Build Coastguard Worker 
397*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(GEP);
398*9880d681SAndroid Build Coastguard Worker   // Candidate does not necessarily have the same pointer type as GEP. Use
399*9880d681SAndroid Build Coastguard Worker   // bitcast or pointer cast to make sure they have the same type, so that the
400*9880d681SAndroid Build Coastguard Worker   // later RAUW doesn't complain.
401*9880d681SAndroid Build Coastguard Worker   Candidate = Builder.CreateBitOrPointerCast(Candidate, GEP->getType());
402*9880d681SAndroid Build Coastguard Worker   assert(Candidate->getType() == GEP->getType());
403*9880d681SAndroid Build Coastguard Worker 
404*9880d681SAndroid Build Coastguard Worker   // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
405*9880d681SAndroid Build Coastguard Worker   uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
406*9880d681SAndroid Build Coastguard Worker   Type *ElementType = GEP->getResultElementType();
407*9880d681SAndroid Build Coastguard Worker   uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
408*9880d681SAndroid Build Coastguard Worker   // Another less rare case: because I is not necessarily the last index of the
409*9880d681SAndroid Build Coastguard Worker   // GEP, the size of the type at the I-th index (IndexedSize) is not
410*9880d681SAndroid Build Coastguard Worker   // necessarily divisible by ElementSize. For example,
411*9880d681SAndroid Build Coastguard Worker   //
412*9880d681SAndroid Build Coastguard Worker   // #pragma pack(1)
413*9880d681SAndroid Build Coastguard Worker   // struct S {
414*9880d681SAndroid Build Coastguard Worker   //   int a[3];
415*9880d681SAndroid Build Coastguard Worker   //   int64 b[8];
416*9880d681SAndroid Build Coastguard Worker   // };
417*9880d681SAndroid Build Coastguard Worker   // #pragma pack()
418*9880d681SAndroid Build Coastguard Worker   //
419*9880d681SAndroid Build Coastguard Worker   // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
420*9880d681SAndroid Build Coastguard Worker   //
421*9880d681SAndroid Build Coastguard Worker   // TODO: bail out on this case for now. We could emit uglygep.
422*9880d681SAndroid Build Coastguard Worker   if (IndexedSize % ElementSize != 0)
423*9880d681SAndroid Build Coastguard Worker     return nullptr;
424*9880d681SAndroid Build Coastguard Worker 
425*9880d681SAndroid Build Coastguard Worker   // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
426*9880d681SAndroid Build Coastguard Worker   Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
427*9880d681SAndroid Build Coastguard Worker   if (RHS->getType() != IntPtrTy)
428*9880d681SAndroid Build Coastguard Worker     RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
429*9880d681SAndroid Build Coastguard Worker   if (IndexedSize != ElementSize) {
430*9880d681SAndroid Build Coastguard Worker     RHS = Builder.CreateMul(
431*9880d681SAndroid Build Coastguard Worker         RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
432*9880d681SAndroid Build Coastguard Worker   }
433*9880d681SAndroid Build Coastguard Worker   GetElementPtrInst *NewGEP =
434*9880d681SAndroid Build Coastguard Worker       cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS));
435*9880d681SAndroid Build Coastguard Worker   NewGEP->setIsInBounds(GEP->isInBounds());
436*9880d681SAndroid Build Coastguard Worker   NewGEP->takeName(GEP);
437*9880d681SAndroid Build Coastguard Worker   return NewGEP;
438*9880d681SAndroid Build Coastguard Worker }
439*9880d681SAndroid Build Coastguard Worker 
tryReassociateBinaryOp(BinaryOperator * I)440*9880d681SAndroid Build Coastguard Worker Instruction *NaryReassociate::tryReassociateBinaryOp(BinaryOperator *I) {
441*9880d681SAndroid Build Coastguard Worker   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
442*9880d681SAndroid Build Coastguard Worker   if (auto *NewI = tryReassociateBinaryOp(LHS, RHS, I))
443*9880d681SAndroid Build Coastguard Worker     return NewI;
444*9880d681SAndroid Build Coastguard Worker   if (auto *NewI = tryReassociateBinaryOp(RHS, LHS, I))
445*9880d681SAndroid Build Coastguard Worker     return NewI;
446*9880d681SAndroid Build Coastguard Worker   return nullptr;
447*9880d681SAndroid Build Coastguard Worker }
448*9880d681SAndroid Build Coastguard Worker 
tryReassociateBinaryOp(Value * LHS,Value * RHS,BinaryOperator * I)449*9880d681SAndroid Build Coastguard Worker Instruction *NaryReassociate::tryReassociateBinaryOp(Value *LHS, Value *RHS,
450*9880d681SAndroid Build Coastguard Worker                                                      BinaryOperator *I) {
451*9880d681SAndroid Build Coastguard Worker   Value *A = nullptr, *B = nullptr;
452*9880d681SAndroid Build Coastguard Worker   // To be conservative, we reassociate I only when it is the only user of (A op
453*9880d681SAndroid Build Coastguard Worker   // B).
454*9880d681SAndroid Build Coastguard Worker   if (LHS->hasOneUse() && matchTernaryOp(I, LHS, A, B)) {
455*9880d681SAndroid Build Coastguard Worker     // I = (A op B) op RHS
456*9880d681SAndroid Build Coastguard Worker     //   = (A op RHS) op B or (B op RHS) op A
457*9880d681SAndroid Build Coastguard Worker     const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
458*9880d681SAndroid Build Coastguard Worker     const SCEV *RHSExpr = SE->getSCEV(RHS);
459*9880d681SAndroid Build Coastguard Worker     if (BExpr != RHSExpr) {
460*9880d681SAndroid Build Coastguard Worker       if (auto *NewI =
461*9880d681SAndroid Build Coastguard Worker               tryReassociatedBinaryOp(getBinarySCEV(I, AExpr, RHSExpr), B, I))
462*9880d681SAndroid Build Coastguard Worker         return NewI;
463*9880d681SAndroid Build Coastguard Worker     }
464*9880d681SAndroid Build Coastguard Worker     if (AExpr != RHSExpr) {
465*9880d681SAndroid Build Coastguard Worker       if (auto *NewI =
466*9880d681SAndroid Build Coastguard Worker               tryReassociatedBinaryOp(getBinarySCEV(I, BExpr, RHSExpr), A, I))
467*9880d681SAndroid Build Coastguard Worker         return NewI;
468*9880d681SAndroid Build Coastguard Worker     }
469*9880d681SAndroid Build Coastguard Worker   }
470*9880d681SAndroid Build Coastguard Worker   return nullptr;
471*9880d681SAndroid Build Coastguard Worker }
472*9880d681SAndroid Build Coastguard Worker 
tryReassociatedBinaryOp(const SCEV * LHSExpr,Value * RHS,BinaryOperator * I)473*9880d681SAndroid Build Coastguard Worker Instruction *NaryReassociate::tryReassociatedBinaryOp(const SCEV *LHSExpr,
474*9880d681SAndroid Build Coastguard Worker                                                       Value *RHS,
475*9880d681SAndroid Build Coastguard Worker                                                       BinaryOperator *I) {
476*9880d681SAndroid Build Coastguard Worker   // Look for the closest dominator LHS of I that computes LHSExpr, and replace
477*9880d681SAndroid Build Coastguard Worker   // I with LHS op RHS.
478*9880d681SAndroid Build Coastguard Worker   auto *LHS = findClosestMatchingDominator(LHSExpr, I);
479*9880d681SAndroid Build Coastguard Worker   if (LHS == nullptr)
480*9880d681SAndroid Build Coastguard Worker     return nullptr;
481*9880d681SAndroid Build Coastguard Worker 
482*9880d681SAndroid Build Coastguard Worker   Instruction *NewI = nullptr;
483*9880d681SAndroid Build Coastguard Worker   switch (I->getOpcode()) {
484*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
485*9880d681SAndroid Build Coastguard Worker     NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
486*9880d681SAndroid Build Coastguard Worker     break;
487*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:
488*9880d681SAndroid Build Coastguard Worker     NewI = BinaryOperator::CreateMul(LHS, RHS, "", I);
489*9880d681SAndroid Build Coastguard Worker     break;
490*9880d681SAndroid Build Coastguard Worker   default:
491*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unexpected instruction.");
492*9880d681SAndroid Build Coastguard Worker   }
493*9880d681SAndroid Build Coastguard Worker   NewI->takeName(I);
494*9880d681SAndroid Build Coastguard Worker   return NewI;
495*9880d681SAndroid Build Coastguard Worker }
496*9880d681SAndroid Build Coastguard Worker 
matchTernaryOp(BinaryOperator * I,Value * V,Value * & Op1,Value * & Op2)497*9880d681SAndroid Build Coastguard Worker bool NaryReassociate::matchTernaryOp(BinaryOperator *I, Value *V, Value *&Op1,
498*9880d681SAndroid Build Coastguard Worker                                      Value *&Op2) {
499*9880d681SAndroid Build Coastguard Worker   switch (I->getOpcode()) {
500*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
501*9880d681SAndroid Build Coastguard Worker     return match(V, m_Add(m_Value(Op1), m_Value(Op2)));
502*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:
503*9880d681SAndroid Build Coastguard Worker     return match(V, m_Mul(m_Value(Op1), m_Value(Op2)));
504*9880d681SAndroid Build Coastguard Worker   default:
505*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unexpected instruction.");
506*9880d681SAndroid Build Coastguard Worker   }
507*9880d681SAndroid Build Coastguard Worker   return false;
508*9880d681SAndroid Build Coastguard Worker }
509*9880d681SAndroid Build Coastguard Worker 
getBinarySCEV(BinaryOperator * I,const SCEV * LHS,const SCEV * RHS)510*9880d681SAndroid Build Coastguard Worker const SCEV *NaryReassociate::getBinarySCEV(BinaryOperator *I, const SCEV *LHS,
511*9880d681SAndroid Build Coastguard Worker                                            const SCEV *RHS) {
512*9880d681SAndroid Build Coastguard Worker   switch (I->getOpcode()) {
513*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
514*9880d681SAndroid Build Coastguard Worker     return SE->getAddExpr(LHS, RHS);
515*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:
516*9880d681SAndroid Build Coastguard Worker     return SE->getMulExpr(LHS, RHS);
517*9880d681SAndroid Build Coastguard Worker   default:
518*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unexpected instruction.");
519*9880d681SAndroid Build Coastguard Worker   }
520*9880d681SAndroid Build Coastguard Worker   return nullptr;
521*9880d681SAndroid Build Coastguard Worker }
522*9880d681SAndroid Build Coastguard Worker 
523*9880d681SAndroid Build Coastguard Worker Instruction *
findClosestMatchingDominator(const SCEV * CandidateExpr,Instruction * Dominatee)524*9880d681SAndroid Build Coastguard Worker NaryReassociate::findClosestMatchingDominator(const SCEV *CandidateExpr,
525*9880d681SAndroid Build Coastguard Worker                                               Instruction *Dominatee) {
526*9880d681SAndroid Build Coastguard Worker   auto Pos = SeenExprs.find(CandidateExpr);
527*9880d681SAndroid Build Coastguard Worker   if (Pos == SeenExprs.end())
528*9880d681SAndroid Build Coastguard Worker     return nullptr;
529*9880d681SAndroid Build Coastguard Worker 
530*9880d681SAndroid Build Coastguard Worker   auto &Candidates = Pos->second;
531*9880d681SAndroid Build Coastguard Worker   // Because we process the basic blocks in pre-order of the dominator tree, a
532*9880d681SAndroid Build Coastguard Worker   // candidate that doesn't dominate the current instruction won't dominate any
533*9880d681SAndroid Build Coastguard Worker   // future instruction either. Therefore, we pop it out of the stack. This
534*9880d681SAndroid Build Coastguard Worker   // optimization makes the algorithm O(n).
535*9880d681SAndroid Build Coastguard Worker   while (!Candidates.empty()) {
536*9880d681SAndroid Build Coastguard Worker     // Candidates stores WeakVHs, so a candidate can be nullptr if it's removed
537*9880d681SAndroid Build Coastguard Worker     // during rewriting.
538*9880d681SAndroid Build Coastguard Worker     if (Value *Candidate = Candidates.back()) {
539*9880d681SAndroid Build Coastguard Worker       Instruction *CandidateInstruction = cast<Instruction>(Candidate);
540*9880d681SAndroid Build Coastguard Worker       if (DT->dominates(CandidateInstruction, Dominatee))
541*9880d681SAndroid Build Coastguard Worker         return CandidateInstruction;
542*9880d681SAndroid Build Coastguard Worker     }
543*9880d681SAndroid Build Coastguard Worker     Candidates.pop_back();
544*9880d681SAndroid Build Coastguard Worker   }
545*9880d681SAndroid Build Coastguard Worker   return nullptr;
546*9880d681SAndroid Build Coastguard Worker }
547