[NaryReassociate] Run EarlyCSE after NaryReassociate
[oota-llvm.git] / lib / Transforms / Scalar / NaryReassociate.cpp
1 //===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===//
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 pass reassociates n-ary add expressions and eliminates the redundancy
11 // exposed by the reassociation.
12 //
13 // A motivating example:
14 //
15 //   void foo(int a, int b) {
16 //     bar(a + b);
17 //     bar((a + 2) + b);
18 //   }
19 //
20 // An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify
21 // the above code to
22 //
23 //   int t = a + b;
24 //   bar(t);
25 //   bar(t + 2);
26 //
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.
30 //
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.
35 //
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 and removes the redundancy accordingly. To efficiently look up whether
40 // an expression is computed before, we store each instruction seen and its SCEV
41 // into an SCEV-to-instruction map.
42 //
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
46 //
47 //   (a + c) + d
48 //   ((a + b) + c) + d
49 //
50 // NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites
51 // ((a + c) + b) + d into ((a + c) + d) + b.
52 //
53 // Finally, the above dominator-based algorithm may need to be run multiple
54 // iterations before emitting optimal code. One source of this need is that we
55 // only split an operand when it is used only once. The above algorithm can
56 // eliminate an instruction and decrease the usage count of its operands. As a
57 // result, an instruction that previously had multiple uses may become a
58 // single-use instruction and thus eligible for split consideration. For
59 // example,
60 //
61 //   ac = a + c
62 //   ab = a + b
63 //   abc = ab + c
64 //   ab2 = ab + b
65 //   ab2c = ab2 + c
66 //
67 // In the first iteration, we cannot reassociate abc to ac+b because ab is used
68 // twice. However, we can reassociate ab2c to abc+b in the first iteration. As a
69 // result, ab2 becomes dead and ab will be used only once in the second
70 // iteration.
71 //
72 // Limitations and TODO items:
73 //
74 // 1) We only considers n-ary adds for now. This should be extended and
75 // generalized.
76 //
77 // 2) Besides arithmetic operations, similar reassociation can be applied to
78 // GEPs. For example, if
79 //   X = &arr[a]
80 // dominates
81 //   Y = &arr[a + b]
82 // we may rewrite Y into X + b.
83 //
84 //===----------------------------------------------------------------------===//
85
86 #include "llvm/Analysis/ScalarEvolution.h"
87 #include "llvm/Analysis/TargetLibraryInfo.h"
88 #include "llvm/Analysis/TargetTransformInfo.h"
89 #include "llvm/IR/Dominators.h"
90 #include "llvm/IR/Module.h"
91 #include "llvm/IR/PatternMatch.h"
92 #include "llvm/Transforms/Scalar.h"
93 #include "llvm/Transforms/Utils/Local.h"
94 using namespace llvm;
95 using namespace PatternMatch;
96
97 #define DEBUG_TYPE "nary-reassociate"
98
99 namespace {
100 class NaryReassociate : public FunctionPass {
101 public:
102   static char ID;
103
104   NaryReassociate(): FunctionPass(ID) {
105     initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
106   }
107
108   bool doInitialization(Module &M) override {
109     DL = &M.getDataLayout();
110     return false;
111   }
112   bool runOnFunction(Function &F) override;
113
114   void getAnalysisUsage(AnalysisUsage &AU) const override {
115     AU.addPreserved<DominatorTreeWrapperPass>();
116     AU.addPreserved<ScalarEvolution>();
117     AU.addPreserved<TargetLibraryInfoWrapperPass>();
118     AU.addRequired<DominatorTreeWrapperPass>();
119     AU.addRequired<ScalarEvolution>();
120     AU.addRequired<TargetLibraryInfoWrapperPass>();
121     AU.addRequired<TargetTransformInfoWrapperPass>();
122     AU.setPreservesCFG();
123   }
124
125 private:
126   // Runs only one iteration of the dominator-based algorithm. See the header
127   // comments for why we need multiple iterations.
128   bool doOneIteration(Function &F);
129
130   // Reassociates I for better CSE.
131   Instruction *tryReassociate(Instruction *I);
132
133   // Reassociate GEP for better CSE.
134   Instruction *tryReassociateGEP(GetElementPtrInst *GEP);
135   // Try splitting GEP at the I-th index and see whether either part can be
136   // CSE'ed. This is a helper function for tryReassociateGEP.
137   //
138   // \p IndexedType The element type indexed by GEP's I-th index. This is
139   //                equivalent to
140   //                  GEP->getIndexedType(GEP->getPointerOperand(), 0-th index,
141   //                                      ..., i-th index).
142   GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
143                                               unsigned I, Type *IndexedType);
144   // Given GEP's I-th index = LHS + RHS, see whether &Base[..][LHS][..] or
145   // &Base[..][RHS][..] can be CSE'ed and rewrite GEP accordingly.
146   GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
147                                               unsigned I, Value *LHS,
148                                               Value *RHS, Type *IndexedType);
149
150   // Reassociate Add for better CSE.
151   Instruction *tryReassociateAdd(BinaryOperator *I);
152   // A helper function for tryReassociateAdd. LHS and RHS are explicitly passed.
153   Instruction *tryReassociateAdd(Value *LHS, Value *RHS, Instruction *I);
154   // Rewrites I to LHS + RHS if LHS is computed already.
155   Instruction *tryReassociatedAdd(const SCEV *LHS, Value *RHS, Instruction *I);
156
157   // Returns the closest dominator of \c Dominatee that computes
158   // \c CandidateExpr. Returns null if not found.
159   Instruction *findClosestMatchingDominator(const SCEV *CandidateExpr,
160                                             Instruction *Dominatee);
161   // GetElementPtrInst implicitly sign-extends an index if the index is shorter
162   // than the pointer size. This function returns whether Index is shorter than
163   // GEP's pointer size, i.e., whether Index needs to be sign-extended in order
164   // to be an index of GEP.
165   bool requiresSignExtension(Value *Index, GetElementPtrInst *GEP);
166
167   DominatorTree *DT;
168   ScalarEvolution *SE;
169   TargetLibraryInfo *TLI;
170   TargetTransformInfo *TTI;
171   const DataLayout *DL;
172   // A lookup table quickly telling which instructions compute the given SCEV.
173   // Note that there can be multiple instructions at different locations
174   // computing to the same SCEV, so we map a SCEV to an instruction list.  For
175   // example,
176   //
177   //   if (p1)
178   //     foo(a + b);
179   //   if (p2)
180   //     bar(a + b);
181   DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs;
182 };
183 } // anonymous namespace
184
185 char NaryReassociate::ID = 0;
186 INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
187                       false, false)
188 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
189 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
190 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
191 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
192 INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation",
193                     false, false)
194
195 FunctionPass *llvm::createNaryReassociatePass() {
196   return new NaryReassociate();
197 }
198
199 bool NaryReassociate::runOnFunction(Function &F) {
200   if (skipOptnoneFunction(F))
201     return false;
202
203   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
204   SE = &getAnalysis<ScalarEvolution>();
205   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
206   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
207
208   bool Changed = false, ChangedInThisIteration;
209   do {
210     ChangedInThisIteration = doOneIteration(F);
211     Changed |= ChangedInThisIteration;
212   } while (ChangedInThisIteration);
213   return Changed;
214 }
215
216 // Whitelist the instruction types NaryReassociate handles for now.
217 static bool isPotentiallyNaryReassociable(Instruction *I) {
218   switch (I->getOpcode()) {
219   case Instruction::Add:
220   case Instruction::GetElementPtr:
221     return true;
222   default:
223     return false;
224   }
225 }
226
227 bool NaryReassociate::doOneIteration(Function &F) {
228   bool Changed = false;
229   SeenExprs.clear();
230   // Process the basic blocks in pre-order of the dominator tree. This order
231   // ensures that all bases of a candidate are in Candidates when we process it.
232   for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
233        Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
234     BasicBlock *BB = Node->getBlock();
235     for (auto I = BB->begin(); I != BB->end(); ++I) {
236       if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(I)) {
237         const SCEV *OldSCEV = SE->getSCEV(I);
238         if (Instruction *NewI = tryReassociate(I)) {
239           Changed = true;
240           SE->forgetValue(I);
241           I->replaceAllUsesWith(NewI);
242           RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
243           I = NewI;
244         }
245         // Add the rewritten instruction to SeenExprs; the original instruction
246         // is deleted.
247         const SCEV *NewSCEV = SE->getSCEV(I);
248         SeenExprs[NewSCEV].push_back(I);
249         // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
250         // is equivalent to I. However, ScalarEvolution::getSCEV may
251         // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose
252         // we reassociate
253         //   I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
254         // to
255         //   NewI = &a[sext(i)] + sext(j).
256         //
257         // ScalarEvolution computes
258         //   getSCEV(I)    = a + 4 * sext(i + j)
259         //   getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
260         // which are different SCEVs.
261         //
262         // To alleviate this issue of ScalarEvolution not always capturing
263         // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
264         // map both SCEV before and after tryReassociate(I) to I.
265         //
266         // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
267         if (NewSCEV != OldSCEV)
268           SeenExprs[OldSCEV].push_back(I);
269       }
270     }
271   }
272   return Changed;
273 }
274
275 Instruction *NaryReassociate::tryReassociate(Instruction *I) {
276   switch (I->getOpcode()) {
277   case Instruction::Add:
278     return tryReassociateAdd(cast<BinaryOperator>(I));
279   case Instruction::GetElementPtr:
280     return tryReassociateGEP(cast<GetElementPtrInst>(I));
281   default:
282     llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
283   }
284 }
285
286 // FIXME: extract this method into TTI->getGEPCost.
287 static bool isGEPFoldable(GetElementPtrInst *GEP,
288                           const TargetTransformInfo *TTI,
289                           const DataLayout *DL) {
290   GlobalVariable *BaseGV = nullptr;
291   int64_t BaseOffset = 0;
292   bool HasBaseReg = false;
293   int64_t Scale = 0;
294
295   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
296     BaseGV = GV;
297   else
298     HasBaseReg = true;
299
300   gep_type_iterator GTI = gep_type_begin(GEP);
301   for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) {
302     if (isa<SequentialType>(*GTI)) {
303       int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
304       if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
305         BaseOffset += ConstIdx->getSExtValue() * ElementSize;
306       } else {
307         // Needs scale register.
308         if (Scale != 0) {
309           // No addressing mode takes two scale registers.
310           return false;
311         }
312         Scale = ElementSize;
313       }
314     } else {
315       StructType *STy = cast<StructType>(*GTI);
316       uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
317       BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
318     }
319   }
320   return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV,
321                                     BaseOffset, HasBaseReg, Scale);
322 }
323
324 Instruction *NaryReassociate::tryReassociateGEP(GetElementPtrInst *GEP) {
325   // Not worth reassociating GEP if it is foldable.
326   if (isGEPFoldable(GEP, TTI, DL))
327     return nullptr;
328
329   gep_type_iterator GTI = gep_type_begin(*GEP);
330   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
331     if (isa<SequentialType>(*GTI++)) {
332       if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1, *GTI)) {
333         return NewGEP;
334       }
335     }
336   }
337   return nullptr;
338 }
339
340 bool NaryReassociate::requiresSignExtension(Value *Index,
341                                             GetElementPtrInst *GEP) {
342   unsigned PointerSizeInBits =
343       DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
344   return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
345 }
346
347 GetElementPtrInst *
348 NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I,
349                                           Type *IndexedType) {
350   Value *IndexToSplit = GEP->getOperand(I + 1);
351   if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit))
352     IndexToSplit = SExt->getOperand(0);
353
354   if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
355     // If the I-th index needs sext and the underlying add is not equipped with
356     // nsw, we cannot split the add because
357     //   sext(LHS + RHS) != sext(LHS) + sext(RHS).
358     if (requiresSignExtension(IndexToSplit, GEP) && !AO->hasNoSignedWrap())
359       return nullptr;
360     Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
361     // IndexToSplit = LHS + RHS.
362     if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
363       return NewGEP;
364     // Symmetrically, try IndexToSplit = RHS + LHS.
365     if (LHS != RHS) {
366       if (auto *NewGEP =
367               tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
368         return NewGEP;
369     }
370   }
371   return nullptr;
372 }
373
374 GetElementPtrInst *
375 NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I,
376                                           Value *LHS, Value *RHS,
377                                           Type *IndexedType) {
378   // Look for GEP's closest dominator that has the same SCEV as GEP except that
379   // the I-th index is replaced with LHS.
380   SmallVector<const SCEV *, 4> IndexExprs;
381   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
382     IndexExprs.push_back(SE->getSCEV(*Index));
383   // Replace the I-th index with LHS.
384   IndexExprs[I] = SE->getSCEV(LHS);
385   const SCEV *CandidateExpr = SE->getGEPExpr(
386       GEP->getSourceElementType(), SE->getSCEV(GEP->getPointerOperand()),
387       IndexExprs, GEP->isInBounds());
388
389   auto *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
390   if (Candidate == nullptr)
391     return nullptr;
392
393   PointerType *TypeOfCandidate = dyn_cast<PointerType>(Candidate->getType());
394   // Pretty rare but theoretically possible when a numeric value happens to
395   // share CandidateExpr.
396   if (TypeOfCandidate == nullptr)
397     return nullptr;
398
399   // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
400   uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
401   Type *ElementType = TypeOfCandidate->getElementType();
402   uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
403   // Another less rare case: because I is not necessarily the last index of the
404   // GEP, the size of the type at the I-th index (IndexedSize) is not
405   // necessarily divisible by ElementSize. For example,
406   //
407   // #pragma pack(1)
408   // struct S {
409   //   int a[3];
410   //   int64 b[8];
411   // };
412   // #pragma pack()
413   //
414   // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
415   //
416   // TODO: bail out on this case for now. We could emit uglygep.
417   if (IndexedSize % ElementSize != 0)
418     return nullptr;
419
420   // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
421   IRBuilder<> Builder(GEP);
422   Type *IntPtrTy = DL->getIntPtrType(TypeOfCandidate);
423   if (RHS->getType() != IntPtrTy)
424     RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
425   if (IndexedSize != ElementSize) {
426     RHS = Builder.CreateMul(
427         RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
428   }
429   GetElementPtrInst *NewGEP =
430       cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS));
431   NewGEP->setIsInBounds(GEP->isInBounds());
432   NewGEP->takeName(GEP);
433   return NewGEP;
434 }
435
436 Instruction *NaryReassociate::tryReassociateAdd(BinaryOperator *I) {
437   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
438   if (auto *NewI = tryReassociateAdd(LHS, RHS, I))
439     return NewI;
440   if (auto *NewI = tryReassociateAdd(RHS, LHS, I))
441     return NewI;
442   return nullptr;
443 }
444
445 Instruction *NaryReassociate::tryReassociateAdd(Value *LHS, Value *RHS,
446                                                 Instruction *I) {
447   Value *A = nullptr, *B = nullptr;
448   // To be conservative, we reassociate I only when it is the only user of A+B.
449   if (LHS->hasOneUse() && match(LHS, m_Add(m_Value(A), m_Value(B)))) {
450     // I = (A + B) + RHS
451     //   = (A + RHS) + B or (B + RHS) + A
452     const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
453     const SCEV *RHSExpr = SE->getSCEV(RHS);
454     if (BExpr != RHSExpr) {
455       if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(AExpr, RHSExpr), B, I))
456         return NewI;
457     }
458     if (AExpr != RHSExpr) {
459       if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(BExpr, RHSExpr), A, I))
460         return NewI;
461     }
462   }
463   return nullptr;
464 }
465
466 Instruction *NaryReassociate::tryReassociatedAdd(const SCEV *LHSExpr,
467                                                  Value *RHS, Instruction *I) {
468   auto Pos = SeenExprs.find(LHSExpr);
469   // Bail out if LHSExpr is not previously seen.
470   if (Pos == SeenExprs.end())
471     return nullptr;
472
473   // Look for the closest dominator LHS of I that computes LHSExpr, and replace
474   // I with LHS + RHS.
475   auto *LHS = findClosestMatchingDominator(LHSExpr, I);
476   if (LHS == nullptr)
477     return nullptr;
478
479   Instruction *NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
480   NewI->takeName(I);
481   return NewI;
482 }
483
484 Instruction *
485 NaryReassociate::findClosestMatchingDominator(const SCEV *CandidateExpr,
486                                               Instruction *Dominatee) {
487   auto Pos = SeenExprs.find(CandidateExpr);
488   if (Pos == SeenExprs.end())
489     return nullptr;
490
491   auto &Candidates = Pos->second;
492   // Because we process the basic blocks in pre-order of the dominator tree, a
493   // candidate that doesn't dominate the current instruction won't dominate any
494   // future instruction either. Therefore, we pop it out of the stack. This
495   // optimization makes the algorithm O(n).
496   while (!Candidates.empty()) {
497     Instruction *Candidate = Candidates.back();
498     if (DT->dominates(Candidate, Dominatee))
499       return Candidate;
500     Candidates.pop_back();
501   }
502   return nullptr;
503 }