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