blob: c6cb12f77fa0a3476aee35a03f53c7ed4335e167 [file] [log] [blame]
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +00001//===- 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 +
Jingyue Wu8579b812015-04-17 00:25:10 +000039// 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.
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000042//
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//
Jingyue Wu8579b812015-04-17 00:25:10 +000053// 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//
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000072// Limitations and TODO items:
73//
Marcello Maggioni454faa82015-09-15 17:22:52 +000074// 1) We only considers n-ary adds and muls for now. This should be extended
75// and generalized.
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000076//
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000077//===----------------------------------------------------------------------===//
78
Jingyue Wucf02ef32015-07-01 03:38:49 +000079#include "llvm/Analysis/AssumptionCache.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000080#include "llvm/Analysis/ScalarEvolution.h"
Jingyue Wu8579b812015-04-17 00:25:10 +000081#include "llvm/Analysis/TargetLibraryInfo.h"
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +000082#include "llvm/Analysis/TargetTransformInfo.h"
Jingyue Wucf02ef32015-07-01 03:38:49 +000083#include "llvm/Analysis/ValueTracking.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000084#include "llvm/IR/Dominators.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/PatternMatch.h"
Jingyue Wucf02ef32015-07-01 03:38:49 +000087#include "llvm/Support/Debug.h"
88#include "llvm/Support/raw_ostream.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000089#include "llvm/Transforms/Scalar.h"
Jingyue Wu8579b812015-04-17 00:25:10 +000090#include "llvm/Transforms/Utils/Local.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000091using namespace llvm;
92using namespace PatternMatch;
93
94#define DEBUG_TYPE "nary-reassociate"
95
96namespace {
97class NaryReassociate : public FunctionPass {
98public:
99 static char ID;
100
101 NaryReassociate(): FunctionPass(ID) {
102 initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
103 }
104
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000105 bool doInitialization(Module &M) override {
106 DL = &M.getDataLayout();
107 return false;
108 }
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000109 bool runOnFunction(Function &F) override;
110
111 void getAnalysisUsage(AnalysisUsage &AU) const override {
112 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000113 AU.addPreserved<ScalarEvolutionWrapperPass>();
Jingyue Wu8579b812015-04-17 00:25:10 +0000114 AU.addPreserved<TargetLibraryInfoWrapperPass>();
Jingyue Wucf02ef32015-07-01 03:38:49 +0000115 AU.addRequired<AssumptionCacheTracker>();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000116 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000117 AU.addRequired<ScalarEvolutionWrapperPass>();
Jingyue Wu8579b812015-04-17 00:25:10 +0000118 AU.addRequired<TargetLibraryInfoWrapperPass>();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000119 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000120 AU.setPreservesCFG();
121 }
122
123private:
Jingyue Wu8579b812015-04-17 00:25:10 +0000124 // 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);
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000127
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
Marcello Maggioni454faa82015-09-15 17:22:52 +0000148 // Reassociate binary operators for better CSE.
149 Instruction *tryReassociateBinaryOp(BinaryOperator *I);
150
151 // A helper function for tryReassociateBinaryOp. LHS and RHS are explicitly
152 // passed.
153 Instruction *tryReassociateBinaryOp(Value *LHS, Value *RHS,
154 BinaryOperator *I);
155 // Rewrites I to (LHS op RHS) if LHS is computed already.
156 Instruction *tryReassociatedBinaryOp(const SCEV *LHS, Value *RHS,
157 BinaryOperator *I);
158
159 // Tries to match Op1 and Op2 by using V.
160 bool matchTernaryOp(BinaryOperator *I, Value *V, Value *&Op1, Value *&Op2);
161
162 // Gets SCEV for (LHS op RHS).
163 const SCEV *getBinarySCEV(BinaryOperator *I, const SCEV *LHS,
164 const SCEV *RHS);
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000165
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000166 // Returns the closest dominator of \c Dominatee that computes
167 // \c CandidateExpr. Returns null if not found.
168 Instruction *findClosestMatchingDominator(const SCEV *CandidateExpr,
169 Instruction *Dominatee);
170 // GetElementPtrInst implicitly sign-extends an index if the index is shorter
171 // than the pointer size. This function returns whether Index is shorter than
172 // GEP's pointer size, i.e., whether Index needs to be sign-extended in order
173 // to be an index of GEP.
174 bool requiresSignExtension(Value *Index, GetElementPtrInst *GEP);
175
Jingyue Wucf02ef32015-07-01 03:38:49 +0000176 AssumptionCache *AC;
177 const DataLayout *DL;
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000178 DominatorTree *DT;
179 ScalarEvolution *SE;
Jingyue Wu8579b812015-04-17 00:25:10 +0000180 TargetLibraryInfo *TLI;
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000181 TargetTransformInfo *TTI;
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000182 // A lookup table quickly telling which instructions compute the given SCEV.
183 // Note that there can be multiple instructions at different locations
Jingyue Wu771dfe92015-04-16 18:42:31 +0000184 // computing to the same SCEV, so we map a SCEV to an instruction list. For
185 // example,
186 //
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000187 // if (p1)
188 // foo(a + b);
189 // if (p2)
190 // bar(a + b);
191 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs;
192};
193} // anonymous namespace
194
195char NaryReassociate::ID = 0;
196INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
197 false, false)
Jingyue Wucf02ef32015-07-01 03:38:49 +0000198INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000199INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000200INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Jingyue Wu8579b812015-04-17 00:25:10 +0000201INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000202INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000203INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation",
204 false, false)
205
206FunctionPass *llvm::createNaryReassociatePass() {
207 return new NaryReassociate();
208}
209
210bool NaryReassociate::runOnFunction(Function &F) {
211 if (skipOptnoneFunction(F))
212 return false;
213
Jingyue Wucf02ef32015-07-01 03:38:49 +0000214 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000215 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000216 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Jingyue Wu8579b812015-04-17 00:25:10 +0000217 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000218 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000219
Jingyue Wu8579b812015-04-17 00:25:10 +0000220 bool Changed = false, ChangedInThisIteration;
221 do {
222 ChangedInThisIteration = doOneIteration(F);
223 Changed |= ChangedInThisIteration;
224 } while (ChangedInThisIteration);
225 return Changed;
226}
227
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000228// Whitelist the instruction types NaryReassociate handles for now.
229static bool isPotentiallyNaryReassociable(Instruction *I) {
230 switch (I->getOpcode()) {
231 case Instruction::Add:
232 case Instruction::GetElementPtr:
Marcello Maggioni454faa82015-09-15 17:22:52 +0000233 case Instruction::Mul:
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000234 return true;
235 default:
236 return false;
237 }
238}
239
Jingyue Wu8579b812015-04-17 00:25:10 +0000240bool NaryReassociate::doOneIteration(Function &F) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000241 bool Changed = false;
242 SeenExprs.clear();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000243 // Process the basic blocks in pre-order of the dominator tree. This order
244 // ensures that all bases of a candidate are in Candidates when we process it.
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000245 for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
246 Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
247 BasicBlock *BB = Node->getBlock();
248 for (auto I = BB->begin(); I != BB->end(); ++I) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000249 if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(I)) {
Jingyue Wuc2a01462015-05-28 04:56:52 +0000250 const SCEV *OldSCEV = SE->getSCEV(I);
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000251 if (Instruction *NewI = tryReassociate(I)) {
Jingyue Wu8579b812015-04-17 00:25:10 +0000252 Changed = true;
253 SE->forgetValue(I);
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000254 I->replaceAllUsesWith(NewI);
Jingyue Wu8579b812015-04-17 00:25:10 +0000255 RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000256 I = NewI;
257 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000258 // Add the rewritten instruction to SeenExprs; the original instruction
259 // is deleted.
Jingyue Wuc2a01462015-05-28 04:56:52 +0000260 const SCEV *NewSCEV = SE->getSCEV(I);
261 SeenExprs[NewSCEV].push_back(I);
262 // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
263 // is equivalent to I. However, ScalarEvolution::getSCEV may
264 // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose
265 // we reassociate
266 // I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
267 // to
268 // NewI = &a[sext(i)] + sext(j).
269 //
270 // ScalarEvolution computes
271 // getSCEV(I) = a + 4 * sext(i + j)
272 // getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
273 // which are different SCEVs.
274 //
275 // To alleviate this issue of ScalarEvolution not always capturing
276 // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
277 // map both SCEV before and after tryReassociate(I) to I.
278 //
279 // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
280 if (NewSCEV != OldSCEV)
281 SeenExprs[OldSCEV].push_back(I);
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000282 }
283 }
284 }
285 return Changed;
286}
287
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000288Instruction *NaryReassociate::tryReassociate(Instruction *I) {
289 switch (I->getOpcode()) {
290 case Instruction::Add:
Marcello Maggioni454faa82015-09-15 17:22:52 +0000291 case Instruction::Mul:
292 return tryReassociateBinaryOp(cast<BinaryOperator>(I));
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000293 case Instruction::GetElementPtr:
294 return tryReassociateGEP(cast<GetElementPtrInst>(I));
295 default:
296 llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
297 }
298}
299
300// FIXME: extract this method into TTI->getGEPCost.
301static bool isGEPFoldable(GetElementPtrInst *GEP,
302 const TargetTransformInfo *TTI,
303 const DataLayout *DL) {
304 GlobalVariable *BaseGV = nullptr;
305 int64_t BaseOffset = 0;
306 bool HasBaseReg = false;
307 int64_t Scale = 0;
308
309 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
310 BaseGV = GV;
311 else
312 HasBaseReg = true;
313
314 gep_type_iterator GTI = gep_type_begin(GEP);
315 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) {
316 if (isa<SequentialType>(*GTI)) {
317 int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
318 if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
319 BaseOffset += ConstIdx->getSExtValue() * ElementSize;
320 } else {
321 // Needs scale register.
322 if (Scale != 0) {
323 // No addressing mode takes two scale registers.
324 return false;
325 }
326 Scale = ElementSize;
327 }
328 } else {
329 StructType *STy = cast<StructType>(*GTI);
330 uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
331 BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
332 }
333 }
Matt Arsenaultfb88aca2015-06-07 20:17:42 +0000334
335 unsigned AddrSpace = GEP->getPointerAddressSpace();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000336 return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV,
Matt Arsenaultfb88aca2015-06-07 20:17:42 +0000337 BaseOffset, HasBaseReg, Scale, AddrSpace);
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000338}
339
340Instruction *NaryReassociate::tryReassociateGEP(GetElementPtrInst *GEP) {
341 // Not worth reassociating GEP if it is foldable.
342 if (isGEPFoldable(GEP, TTI, DL))
343 return nullptr;
344
345 gep_type_iterator GTI = gep_type_begin(*GEP);
346 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
347 if (isa<SequentialType>(*GTI++)) {
348 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1, *GTI)) {
349 return NewGEP;
350 }
351 }
352 }
353 return nullptr;
354}
355
356bool NaryReassociate::requiresSignExtension(Value *Index,
357 GetElementPtrInst *GEP) {
358 unsigned PointerSizeInBits =
359 DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
360 return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
361}
362
363GetElementPtrInst *
364NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I,
365 Type *IndexedType) {
366 Value *IndexToSplit = GEP->getOperand(I + 1);
Jingyue Wucf02ef32015-07-01 03:38:49 +0000367 if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000368 IndexToSplit = SExt->getOperand(0);
Jingyue Wucf02ef32015-07-01 03:38:49 +0000369 } else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(IndexToSplit)) {
370 // zext can be treated as sext if the source is non-negative.
Jingyue Wu10fcea52015-08-20 18:27:04 +0000371 if (isKnownNonNegative(ZExt->getOperand(0), *DL, 0, AC, GEP, DT))
Jingyue Wucf02ef32015-07-01 03:38:49 +0000372 IndexToSplit = ZExt->getOperand(0);
373 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000374
375 if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
376 // If the I-th index needs sext and the underlying add is not equipped with
377 // nsw, we cannot split the add because
378 // sext(LHS + RHS) != sext(LHS) + sext(RHS).
Jingyue Wu10fcea52015-08-20 18:27:04 +0000379 if (requiresSignExtension(IndexToSplit, GEP) &&
380 computeOverflowForSignedAdd(AO, *DL, AC, GEP, DT) !=
381 OverflowResult::NeverOverflows)
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000382 return nullptr;
Jingyue Wu10fcea52015-08-20 18:27:04 +0000383
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000384 Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
385 // IndexToSplit = LHS + RHS.
386 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
387 return NewGEP;
388 // Symmetrically, try IndexToSplit = RHS + LHS.
389 if (LHS != RHS) {
390 if (auto *NewGEP =
391 tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
392 return NewGEP;
393 }
394 }
395 return nullptr;
396}
397
Jingyue Wucf02ef32015-07-01 03:38:49 +0000398GetElementPtrInst *NaryReassociate::tryReassociateGEPAtIndex(
399 GetElementPtrInst *GEP, unsigned I, Value *LHS, Value *RHS,
400 Type *IndexedType) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000401 // Look for GEP's closest dominator that has the same SCEV as GEP except that
402 // the I-th index is replaced with LHS.
403 SmallVector<const SCEV *, 4> IndexExprs;
404 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
405 IndexExprs.push_back(SE->getSCEV(*Index));
406 // Replace the I-th index with LHS.
407 IndexExprs[I] = SE->getSCEV(LHS);
Jingyue Wu10fcea52015-08-20 18:27:04 +0000408 if (isKnownNonNegative(LHS, *DL, 0, AC, GEP, DT) &&
Jingyue Wucf02ef32015-07-01 03:38:49 +0000409 DL->getTypeSizeInBits(LHS->getType()) <
410 DL->getTypeSizeInBits(GEP->getOperand(I)->getType())) {
411 // Zero-extend LHS if it is non-negative. InstCombine canonicalizes sext to
412 // zext if the source operand is proved non-negative. We should do that
413 // consistently so that CandidateExpr more likely appears before. See
414 // @reassociate_gep_assume for an example of this canonicalization.
415 IndexExprs[I] =
416 SE->getZeroExtendExpr(IndexExprs[I], GEP->getOperand(I)->getType());
417 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000418 const SCEV *CandidateExpr = SE->getGEPExpr(
419 GEP->getSourceElementType(), SE->getSCEV(GEP->getPointerOperand()),
420 IndexExprs, GEP->isInBounds());
421
422 auto *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
423 if (Candidate == nullptr)
424 return nullptr;
425
426 PointerType *TypeOfCandidate = dyn_cast<PointerType>(Candidate->getType());
427 // Pretty rare but theoretically possible when a numeric value happens to
428 // share CandidateExpr.
429 if (TypeOfCandidate == nullptr)
430 return nullptr;
431
432 // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
433 uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
434 Type *ElementType = TypeOfCandidate->getElementType();
435 uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
436 // Another less rare case: because I is not necessarily the last index of the
437 // GEP, the size of the type at the I-th index (IndexedSize) is not
438 // necessarily divisible by ElementSize. For example,
439 //
440 // #pragma pack(1)
441 // struct S {
442 // int a[3];
443 // int64 b[8];
444 // };
445 // #pragma pack()
446 //
447 // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
448 //
449 // TODO: bail out on this case for now. We could emit uglygep.
450 if (IndexedSize % ElementSize != 0)
451 return nullptr;
452
453 // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
454 IRBuilder<> Builder(GEP);
455 Type *IntPtrTy = DL->getIntPtrType(TypeOfCandidate);
456 if (RHS->getType() != IntPtrTy)
457 RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
458 if (IndexedSize != ElementSize) {
459 RHS = Builder.CreateMul(
460 RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
461 }
462 GetElementPtrInst *NewGEP =
463 cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS));
464 NewGEP->setIsInBounds(GEP->isInBounds());
465 NewGEP->takeName(GEP);
466 return NewGEP;
467}
468
Marcello Maggioni454faa82015-09-15 17:22:52 +0000469Instruction *NaryReassociate::tryReassociateBinaryOp(BinaryOperator *I) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000470 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Marcello Maggioni454faa82015-09-15 17:22:52 +0000471 if (auto *NewI = tryReassociateBinaryOp(LHS, RHS, I))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000472 return NewI;
Marcello Maggioni454faa82015-09-15 17:22:52 +0000473 if (auto *NewI = tryReassociateBinaryOp(RHS, LHS, I))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000474 return NewI;
475 return nullptr;
476}
477
Marcello Maggioni454faa82015-09-15 17:22:52 +0000478Instruction *NaryReassociate::tryReassociateBinaryOp(Value *LHS, Value *RHS,
479 BinaryOperator *I) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000480 Value *A = nullptr, *B = nullptr;
Marcello Maggioni454faa82015-09-15 17:22:52 +0000481 // To be conservative, we reassociate I only when it is the only user of (A op
482 // B).
483 if (LHS->hasOneUse() && matchTernaryOp(I, LHS, A, B)) {
484 // I = (A op B) op RHS
485 // = (A op RHS) op B or (B op RHS) op A
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000486 const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
487 const SCEV *RHSExpr = SE->getSCEV(RHS);
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000488 if (BExpr != RHSExpr) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000489 if (auto *NewI =
490 tryReassociatedBinaryOp(getBinarySCEV(I, AExpr, RHSExpr), B, I))
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000491 return NewI;
492 }
493 if (AExpr != RHSExpr) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000494 if (auto *NewI =
495 tryReassociatedBinaryOp(getBinarySCEV(I, BExpr, RHSExpr), A, I))
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000496 return NewI;
497 }
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000498 }
499 return nullptr;
500}
501
Marcello Maggioni454faa82015-09-15 17:22:52 +0000502Instruction *NaryReassociate::tryReassociatedBinaryOp(const SCEV *LHSExpr,
503 Value *RHS,
504 BinaryOperator *I) {
Jingyue Wu771dfe92015-04-16 18:42:31 +0000505 // Look for the closest dominator LHS of I that computes LHSExpr, and replace
Marcello Maggioni454faa82015-09-15 17:22:52 +0000506 // I with LHS op RHS.
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000507 auto *LHS = findClosestMatchingDominator(LHSExpr, I);
508 if (LHS == nullptr)
509 return nullptr;
510
Marcello Maggioni454faa82015-09-15 17:22:52 +0000511 Instruction *NewI = nullptr;
512 switch (I->getOpcode()) {
513 case Instruction::Add:
514 NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
515 break;
516 case Instruction::Mul:
517 NewI = BinaryOperator::CreateMul(LHS, RHS, "", I);
518 break;
519 default:
520 llvm_unreachable("Unexpected instruction.");
521 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000522 NewI->takeName(I);
523 return NewI;
524}
525
Marcello Maggioni454faa82015-09-15 17:22:52 +0000526bool NaryReassociate::matchTernaryOp(BinaryOperator *I, Value *V, Value *&Op1,
527 Value *&Op2) {
528 switch (I->getOpcode()) {
529 case Instruction::Add:
530 return match(V, m_Add(m_Value(Op1), m_Value(Op2)));
531 case Instruction::Mul:
532 return match(V, m_Mul(m_Value(Op1), m_Value(Op2)));
533 default:
534 llvm_unreachable("Unexpected instruction.");
535 }
536 return false;
537}
538
539const SCEV *NaryReassociate::getBinarySCEV(BinaryOperator *I, const SCEV *LHS,
540 const SCEV *RHS) {
541 switch (I->getOpcode()) {
542 case Instruction::Add:
543 return SE->getAddExpr(LHS, RHS);
544 case Instruction::Mul:
545 return SE->getMulExpr(LHS, RHS);
546 default:
547 llvm_unreachable("Unexpected instruction.");
548 }
549 return nullptr;
550}
551
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000552Instruction *
553NaryReassociate::findClosestMatchingDominator(const SCEV *CandidateExpr,
554 Instruction *Dominatee) {
555 auto Pos = SeenExprs.find(CandidateExpr);
556 if (Pos == SeenExprs.end())
557 return nullptr;
558
559 auto &Candidates = Pos->second;
560 // Because we process the basic blocks in pre-order of the dominator tree, a
Jingyue Wu771dfe92015-04-16 18:42:31 +0000561 // candidate that doesn't dominate the current instruction won't dominate any
562 // future instruction either. Therefore, we pop it out of the stack. This
563 // optimization makes the algorithm O(n).
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000564 while (!Candidates.empty()) {
565 Instruction *Candidate = Candidates.back();
566 if (DT->dominates(Candidate, Dominatee))
567 return Candidate;
568 Candidates.pop_back();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000569 }
570 return nullptr;
571}