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