1 //===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass reassociates n-ary add expressions and eliminates the redundancy
11 // exposed by the reassociation.
13 // A motivating example:
15 // void foo(int a, int b) {
20 // An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify
27 // However, the Reassociate pass is unable to do that because it processes each
28 // instruction individually and believes (a + 2) + b is the best form according
29 // to its rank system.
31 // To address this limitation, NaryReassociate reassociates an expression in a
32 // form that reuses existing instructions. As a result, NaryReassociate can
33 // reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that
34 // (a + b) is computed before.
36 // NaryReassociate works as follows. For every instruction in the form of (a +
37 // b) + c, it checks whether a + c or b + c is already computed by a dominating
38 // instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b +
39 // c) + a 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.
43 // Although the algorithm pattern-matches only ternary additions, it
44 // automatically handles many >3-ary expressions by walking through the function
45 // in the depth-first order. For example, given
50 // NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites
51 // ((a + c) + b) + d into ((a + c) + d) + b.
53 // 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
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
72 // Limitations and TODO items:
74 // 1) We only considers n-ary adds for now. This should be extended and
77 // 2) Besides arithmetic operations, similar reassociation can be applied to
78 // GEPs. For example, if
82 // we may rewrite Y into X + b.
84 //===----------------------------------------------------------------------===//
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"
95 using namespace PatternMatch;
97 #define DEBUG_TYPE "nary-reassociate"
100 class NaryReassociate : public FunctionPass {
104 NaryReassociate(): FunctionPass(ID) {
105 initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
108 bool doInitialization(Module &M) override {
109 DL = &M.getDataLayout();
112 bool runOnFunction(Function &F) override;
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();
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);
130 // Reassociates I for better CSE.
131 Instruction *tryReassociate(Instruction *I);
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.
138 // \p IndexedType The element type indexed by GEP's I-th index. This is
140 // GEP->getIndexedType(GEP->getPointerOperand(), 0-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);
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);
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);
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
181 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs;
183 } // anonymous namespace
185 char NaryReassociate::ID = 0;
186 INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
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",
195 FunctionPass *llvm::createNaryReassociatePass() {
196 return new NaryReassociate();
199 bool NaryReassociate::runOnFunction(Function &F) {
200 if (skipOptnoneFunction(F))
203 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
204 SE = &getAnalysis<ScalarEvolution>();
205 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
206 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
208 bool Changed = false, ChangedInThisIteration;
210 ChangedInThisIteration = doOneIteration(F);
211 Changed |= ChangedInThisIteration;
212 } while (ChangedInThisIteration);
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:
227 bool NaryReassociate::doOneIteration(Function &F) {
228 bool Changed = false;
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)) {
241 I->replaceAllUsesWith(NewI);
242 RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
245 // Add the rewritten instruction to SeenExprs; the original instruction
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
253 // I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
255 // NewI = &a[sext(i)] + sext(j).
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.
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.
266 // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
267 if (NewSCEV != OldSCEV)
268 SeenExprs[OldSCEV].push_back(I);
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));
282 llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
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;
295 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
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;
307 // Needs scale register.
309 // No addressing mode takes two scale registers.
315 StructType *STy = cast<StructType>(*GTI);
316 uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
317 BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
321 unsigned AddrSpace = GEP->getPointerAddressSpace();
322 return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV,
323 BaseOffset, HasBaseReg, Scale, AddrSpace);
326 Instruction *NaryReassociate::tryReassociateGEP(GetElementPtrInst *GEP) {
327 // Not worth reassociating GEP if it is foldable.
328 if (isGEPFoldable(GEP, TTI, DL))
331 gep_type_iterator GTI = gep_type_begin(*GEP);
332 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
333 if (isa<SequentialType>(*GTI++)) {
334 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1, *GTI)) {
342 bool NaryReassociate::requiresSignExtension(Value *Index,
343 GetElementPtrInst *GEP) {
344 unsigned PointerSizeInBits =
345 DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
346 return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
350 NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I,
352 Value *IndexToSplit = GEP->getOperand(I + 1);
353 if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit))
354 IndexToSplit = SExt->getOperand(0);
356 if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
357 // If the I-th index needs sext and the underlying add is not equipped with
358 // nsw, we cannot split the add because
359 // sext(LHS + RHS) != sext(LHS) + sext(RHS).
360 if (requiresSignExtension(IndexToSplit, GEP) && !AO->hasNoSignedWrap())
362 Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
363 // IndexToSplit = LHS + RHS.
364 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
366 // Symmetrically, try IndexToSplit = RHS + LHS.
369 tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
377 NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I,
378 Value *LHS, Value *RHS,
380 // Look for GEP's closest dominator that has the same SCEV as GEP except that
381 // the I-th index is replaced with LHS.
382 SmallVector<const SCEV *, 4> IndexExprs;
383 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
384 IndexExprs.push_back(SE->getSCEV(*Index));
385 // Replace the I-th index with LHS.
386 IndexExprs[I] = SE->getSCEV(LHS);
387 const SCEV *CandidateExpr = SE->getGEPExpr(
388 GEP->getSourceElementType(), SE->getSCEV(GEP->getPointerOperand()),
389 IndexExprs, GEP->isInBounds());
391 auto *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
392 if (Candidate == nullptr)
395 PointerType *TypeOfCandidate = dyn_cast<PointerType>(Candidate->getType());
396 // Pretty rare but theoretically possible when a numeric value happens to
397 // share CandidateExpr.
398 if (TypeOfCandidate == nullptr)
401 // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
402 uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
403 Type *ElementType = TypeOfCandidate->getElementType();
404 uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
405 // Another less rare case: because I is not necessarily the last index of the
406 // GEP, the size of the type at the I-th index (IndexedSize) is not
407 // necessarily divisible by ElementSize. For example,
416 // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
418 // TODO: bail out on this case for now. We could emit uglygep.
419 if (IndexedSize % ElementSize != 0)
422 // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
423 IRBuilder<> Builder(GEP);
424 Type *IntPtrTy = DL->getIntPtrType(TypeOfCandidate);
425 if (RHS->getType() != IntPtrTy)
426 RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
427 if (IndexedSize != ElementSize) {
428 RHS = Builder.CreateMul(
429 RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
431 GetElementPtrInst *NewGEP =
432 cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS));
433 NewGEP->setIsInBounds(GEP->isInBounds());
434 NewGEP->takeName(GEP);
438 Instruction *NaryReassociate::tryReassociateAdd(BinaryOperator *I) {
439 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
440 if (auto *NewI = tryReassociateAdd(LHS, RHS, I))
442 if (auto *NewI = tryReassociateAdd(RHS, LHS, I))
447 Instruction *NaryReassociate::tryReassociateAdd(Value *LHS, Value *RHS,
449 Value *A = nullptr, *B = nullptr;
450 // To be conservative, we reassociate I only when it is the only user of A+B.
451 if (LHS->hasOneUse() && match(LHS, m_Add(m_Value(A), m_Value(B)))) {
453 // = (A + RHS) + B or (B + RHS) + A
454 const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
455 const SCEV *RHSExpr = SE->getSCEV(RHS);
456 if (BExpr != RHSExpr) {
457 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(AExpr, RHSExpr), B, I))
460 if (AExpr != RHSExpr) {
461 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(BExpr, RHSExpr), A, I))
468 Instruction *NaryReassociate::tryReassociatedAdd(const SCEV *LHSExpr,
469 Value *RHS, Instruction *I) {
470 auto Pos = SeenExprs.find(LHSExpr);
471 // Bail out if LHSExpr is not previously seen.
472 if (Pos == SeenExprs.end())
475 // Look for the closest dominator LHS of I that computes LHSExpr, and replace
477 auto *LHS = findClosestMatchingDominator(LHSExpr, I);
481 Instruction *NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
487 NaryReassociate::findClosestMatchingDominator(const SCEV *CandidateExpr,
488 Instruction *Dominatee) {
489 auto Pos = SeenExprs.find(CandidateExpr);
490 if (Pos == SeenExprs.end())
493 auto &Candidates = Pos->second;
494 // Because we process the basic blocks in pre-order of the dominator tree, a
495 // candidate that doesn't dominate the current instruction won't dominate any
496 // future instruction either. Therefore, we pop it out of the stack. This
497 // optimization makes the algorithm O(n).
498 while (!Candidates.empty()) {
499 Instruction *Candidate = Candidates.back();
500 if (DT->dominates(Candidate, Dominatee))
502 Candidates.pop_back();