blob: 0ac1edfee930b766d599e02c193eeace50d6d63f [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
Wei Mi1cf58f82016-07-21 22:28:52 +000079#include "llvm/Transforms/Scalar/NaryReassociate.h"
Jingyue Wucf02ef32015-07-01 03:38:49 +000080#include "llvm/Analysis/ValueTracking.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000081#include "llvm/IR/Module.h"
82#include "llvm/IR/PatternMatch.h"
Jingyue Wucf02ef32015-07-01 03:38:49 +000083#include "llvm/Support/Debug.h"
84#include "llvm/Support/raw_ostream.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000085#include "llvm/Transforms/Scalar.h"
Jingyue Wu8579b812015-04-17 00:25:10 +000086#include "llvm/Transforms/Utils/Local.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000087using namespace llvm;
88using namespace PatternMatch;
89
90#define DEBUG_TYPE "nary-reassociate"
91
92namespace {
Wei Mi1cf58f82016-07-21 22:28:52 +000093class NaryReassociateLegacyPass : public FunctionPass {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000094public:
95 static char ID;
96
Wei Mi1cf58f82016-07-21 22:28:52 +000097 NaryReassociateLegacyPass() : FunctionPass(ID) {
98 initializeNaryReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000099 }
100
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000101 bool doInitialization(Module &M) override {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000102 return false;
103 }
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000104 bool runOnFunction(Function &F) override;
105
106 void getAnalysisUsage(AnalysisUsage &AU) const override {
107 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000108 AU.addPreserved<ScalarEvolutionWrapperPass>();
Jingyue Wu8579b812015-04-17 00:25:10 +0000109 AU.addPreserved<TargetLibraryInfoWrapperPass>();
Jingyue Wucf02ef32015-07-01 03:38:49 +0000110 AU.addRequired<AssumptionCacheTracker>();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000111 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000112 AU.addRequired<ScalarEvolutionWrapperPass>();
Jingyue Wu8579b812015-04-17 00:25:10 +0000113 AU.addRequired<TargetLibraryInfoWrapperPass>();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000114 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000115 AU.setPreservesCFG();
116 }
117
118private:
Wei Mi1cf58f82016-07-21 22:28:52 +0000119 NaryReassociatePass Impl;
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000120};
121} // anonymous namespace
122
Wei Mi1cf58f82016-07-21 22:28:52 +0000123char NaryReassociateLegacyPass::ID = 0;
124INITIALIZE_PASS_BEGIN(NaryReassociateLegacyPass, "nary-reassociate",
125 "Nary reassociation", false, false)
Jingyue Wucf02ef32015-07-01 03:38:49 +0000126INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000127INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000128INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Jingyue Wu8579b812015-04-17 00:25:10 +0000129INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000130INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Wei Mi1cf58f82016-07-21 22:28:52 +0000131INITIALIZE_PASS_END(NaryReassociateLegacyPass, "nary-reassociate",
132 "Nary reassociation", false, false)
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000133
134FunctionPass *llvm::createNaryReassociatePass() {
Wei Mi1cf58f82016-07-21 22:28:52 +0000135 return new NaryReassociateLegacyPass();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000136}
137
Wei Mi1cf58f82016-07-21 22:28:52 +0000138bool NaryReassociateLegacyPass::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000139 if (skipFunction(F))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000140 return false;
141
Wei Mi1cf58f82016-07-21 22:28:52 +0000142 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
143 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
144 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
145 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
146 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
147
148 return Impl.runImpl(F, AC, DT, SE, TLI, TTI);
149}
150
151PreservedAnalyses NaryReassociatePass::run(Function &F,
152 FunctionAnalysisManager &AM) {
153 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
154 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
155 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
156 auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
157 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
158
159 bool Changed = runImpl(F, AC, DT, SE, TLI, TTI);
Sean Silva7f21f4b2016-08-08 05:38:06 +0000160 AM.invalidate<ScalarEvolutionAnalysis>(F);
Wei Mi1cf58f82016-07-21 22:28:52 +0000161 if (!Changed)
162 return PreservedAnalyses::all();
163
164 // FIXME: This should also 'preserve the CFG'.
165 PreservedAnalyses PA;
166 PA.preserve<DominatorTreeAnalysis>();
167 PA.preserve<ScalarEvolutionAnalysis>();
168 PA.preserve<TargetLibraryAnalysis>();
169 return PA;
170}
171
172bool NaryReassociatePass::runImpl(Function &F, AssumptionCache *AC_,
173 DominatorTree *DT_, ScalarEvolution *SE_,
174 TargetLibraryInfo *TLI_,
175 TargetTransformInfo *TTI_) {
176 AC = AC_;
177 DT = DT_;
178 SE = SE_;
179 TLI = TLI_;
180 TTI = TTI_;
181 DL = &F.getParent()->getDataLayout();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000182
Jingyue Wu8579b812015-04-17 00:25:10 +0000183 bool Changed = false, ChangedInThisIteration;
184 do {
185 ChangedInThisIteration = doOneIteration(F);
186 Changed |= ChangedInThisIteration;
187 } while (ChangedInThisIteration);
188 return Changed;
189}
190
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000191// Whitelist the instruction types NaryReassociate handles for now.
192static bool isPotentiallyNaryReassociable(Instruction *I) {
193 switch (I->getOpcode()) {
194 case Instruction::Add:
195 case Instruction::GetElementPtr:
Marcello Maggioni454faa82015-09-15 17:22:52 +0000196 case Instruction::Mul:
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000197 return true;
198 default:
199 return false;
200 }
201}
202
Wei Mi1cf58f82016-07-21 22:28:52 +0000203bool NaryReassociatePass::doOneIteration(Function &F) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000204 bool Changed = false;
205 SeenExprs.clear();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000206 // Process the basic blocks in pre-order of the dominator tree. This order
207 // ensures that all bases of a candidate are in Candidates when we process it.
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000208 for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
209 Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
210 BasicBlock *BB = Node->getBlock();
211 for (auto I = BB->begin(); I != BB->end(); ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000212 if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(&*I)) {
213 const SCEV *OldSCEV = SE->getSCEV(&*I);
214 if (Instruction *NewI = tryReassociate(&*I)) {
Jingyue Wu8579b812015-04-17 00:25:10 +0000215 Changed = true;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000216 SE->forgetValue(&*I);
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000217 I->replaceAllUsesWith(NewI);
Jingyue Wudf1a1b12015-10-01 03:51:44 +0000218 // If SeenExprs constains I's WeakVH, that entry will be replaced with
219 // nullptr.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000220 RecursivelyDeleteTriviallyDeadInstructions(&*I, TLI);
221 I = NewI->getIterator();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000222 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000223 // Add the rewritten instruction to SeenExprs; the original instruction
224 // is deleted.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000225 const SCEV *NewSCEV = SE->getSCEV(&*I);
226 SeenExprs[NewSCEV].push_back(WeakVH(&*I));
Jingyue Wuc2a01462015-05-28 04:56:52 +0000227 // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
228 // is equivalent to I. However, ScalarEvolution::getSCEV may
229 // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose
230 // we reassociate
231 // I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
232 // to
233 // NewI = &a[sext(i)] + sext(j).
234 //
235 // ScalarEvolution computes
236 // getSCEV(I) = a + 4 * sext(i + j)
237 // getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
238 // which are different SCEVs.
239 //
240 // To alleviate this issue of ScalarEvolution not always capturing
241 // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
242 // map both SCEV before and after tryReassociate(I) to I.
243 //
244 // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
245 if (NewSCEV != OldSCEV)
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000246 SeenExprs[OldSCEV].push_back(WeakVH(&*I));
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000247 }
248 }
249 }
250 return Changed;
251}
252
Wei Mi1cf58f82016-07-21 22:28:52 +0000253Instruction *NaryReassociatePass::tryReassociate(Instruction *I) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000254 switch (I->getOpcode()) {
255 case Instruction::Add:
Marcello Maggioni454faa82015-09-15 17:22:52 +0000256 case Instruction::Mul:
257 return tryReassociateBinaryOp(cast<BinaryOperator>(I));
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000258 case Instruction::GetElementPtr:
259 return tryReassociateGEP(cast<GetElementPtrInst>(I));
260 default:
261 llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
262 }
263}
264
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000265static bool isGEPFoldable(GetElementPtrInst *GEP,
Jingyue Wu15f3e822016-07-08 21:48:05 +0000266 const TargetTransformInfo *TTI) {
267 SmallVector<const Value*, 4> Indices;
268 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
269 Indices.push_back(*I);
270 return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
271 Indices) == TargetTransformInfo::TCC_Free;
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000272}
273
Wei Mi1cf58f82016-07-21 22:28:52 +0000274Instruction *NaryReassociatePass::tryReassociateGEP(GetElementPtrInst *GEP) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000275 // Not worth reassociating GEP if it is foldable.
Jingyue Wu15f3e822016-07-08 21:48:05 +0000276 if (isGEPFoldable(GEP, TTI))
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000277 return nullptr;
278
279 gep_type_iterator GTI = gep_type_begin(*GEP);
280 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
281 if (isa<SequentialType>(*GTI++)) {
282 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1, *GTI)) {
283 return NewGEP;
284 }
285 }
286 }
287 return nullptr;
288}
289
Wei Mi1cf58f82016-07-21 22:28:52 +0000290bool NaryReassociatePass::requiresSignExtension(Value *Index,
291 GetElementPtrInst *GEP) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000292 unsigned PointerSizeInBits =
293 DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
294 return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
295}
296
297GetElementPtrInst *
Wei Mi1cf58f82016-07-21 22:28:52 +0000298NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
299 unsigned I, Type *IndexedType) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000300 Value *IndexToSplit = GEP->getOperand(I + 1);
Jingyue Wucf02ef32015-07-01 03:38:49 +0000301 if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000302 IndexToSplit = SExt->getOperand(0);
Jingyue Wucf02ef32015-07-01 03:38:49 +0000303 } else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(IndexToSplit)) {
304 // zext can be treated as sext if the source is non-negative.
Jingyue Wu10fcea52015-08-20 18:27:04 +0000305 if (isKnownNonNegative(ZExt->getOperand(0), *DL, 0, AC, GEP, DT))
Jingyue Wucf02ef32015-07-01 03:38:49 +0000306 IndexToSplit = ZExt->getOperand(0);
307 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000308
309 if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
310 // If the I-th index needs sext and the underlying add is not equipped with
311 // nsw, we cannot split the add because
312 // sext(LHS + RHS) != sext(LHS) + sext(RHS).
Jingyue Wu10fcea52015-08-20 18:27:04 +0000313 if (requiresSignExtension(IndexToSplit, GEP) &&
314 computeOverflowForSignedAdd(AO, *DL, AC, GEP, DT) !=
315 OverflowResult::NeverOverflows)
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000316 return nullptr;
Jingyue Wu10fcea52015-08-20 18:27:04 +0000317
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000318 Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
319 // IndexToSplit = LHS + RHS.
320 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
321 return NewGEP;
322 // Symmetrically, try IndexToSplit = RHS + LHS.
323 if (LHS != RHS) {
324 if (auto *NewGEP =
325 tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
326 return NewGEP;
327 }
328 }
329 return nullptr;
330}
331
Wei Mi1cf58f82016-07-21 22:28:52 +0000332GetElementPtrInst *
333NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
334 unsigned I, Value *LHS,
335 Value *RHS, Type *IndexedType) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000336 // Look for GEP's closest dominator that has the same SCEV as GEP except that
337 // the I-th index is replaced with LHS.
338 SmallVector<const SCEV *, 4> IndexExprs;
339 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
340 IndexExprs.push_back(SE->getSCEV(*Index));
341 // Replace the I-th index with LHS.
342 IndexExprs[I] = SE->getSCEV(LHS);
Jingyue Wu10fcea52015-08-20 18:27:04 +0000343 if (isKnownNonNegative(LHS, *DL, 0, AC, GEP, DT) &&
Jingyue Wucf02ef32015-07-01 03:38:49 +0000344 DL->getTypeSizeInBits(LHS->getType()) <
345 DL->getTypeSizeInBits(GEP->getOperand(I)->getType())) {
346 // Zero-extend LHS if it is non-negative. InstCombine canonicalizes sext to
347 // zext if the source operand is proved non-negative. We should do that
348 // consistently so that CandidateExpr more likely appears before. See
349 // @reassociate_gep_assume for an example of this canonicalization.
350 IndexExprs[I] =
351 SE->getZeroExtendExpr(IndexExprs[I], GEP->getOperand(I)->getType());
352 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000353 const SCEV *CandidateExpr = SE->getGEPExpr(
354 GEP->getSourceElementType(), SE->getSCEV(GEP->getPointerOperand()),
355 IndexExprs, GEP->isInBounds());
356
Jingyue Wuba3ca762015-12-18 21:36:30 +0000357 Value *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000358 if (Candidate == nullptr)
359 return nullptr;
360
Jingyue Wuba3ca762015-12-18 21:36:30 +0000361 IRBuilder<> Builder(GEP);
362 // Candidate does not necessarily have the same pointer type as GEP. Use
363 // bitcast or pointer cast to make sure they have the same type, so that the
364 // later RAUW doesn't complain.
365 Candidate = Builder.CreateBitOrPointerCast(Candidate, GEP->getType());
366 assert(Candidate->getType() == GEP->getType());
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000367
368 // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
369 uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000370 Type *ElementType = GEP->getResultElementType();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000371 uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
372 // Another less rare case: because I is not necessarily the last index of the
373 // GEP, the size of the type at the I-th index (IndexedSize) is not
374 // necessarily divisible by ElementSize. For example,
375 //
376 // #pragma pack(1)
377 // struct S {
378 // int a[3];
379 // int64 b[8];
380 // };
381 // #pragma pack()
382 //
383 // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
384 //
385 // TODO: bail out on this case for now. We could emit uglygep.
386 if (IndexedSize % ElementSize != 0)
387 return nullptr;
388
389 // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
Jingyue Wuba3ca762015-12-18 21:36:30 +0000390 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000391 if (RHS->getType() != IntPtrTy)
392 RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
393 if (IndexedSize != ElementSize) {
394 RHS = Builder.CreateMul(
395 RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
396 }
397 GetElementPtrInst *NewGEP =
398 cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS));
399 NewGEP->setIsInBounds(GEP->isInBounds());
400 NewGEP->takeName(GEP);
401 return NewGEP;
402}
403
Wei Mi1cf58f82016-07-21 22:28:52 +0000404Instruction *NaryReassociatePass::tryReassociateBinaryOp(BinaryOperator *I) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000405 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Marcello Maggioni454faa82015-09-15 17:22:52 +0000406 if (auto *NewI = tryReassociateBinaryOp(LHS, RHS, I))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000407 return NewI;
Marcello Maggioni454faa82015-09-15 17:22:52 +0000408 if (auto *NewI = tryReassociateBinaryOp(RHS, LHS, I))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000409 return NewI;
410 return nullptr;
411}
412
Wei Mi1cf58f82016-07-21 22:28:52 +0000413Instruction *NaryReassociatePass::tryReassociateBinaryOp(Value *LHS, Value *RHS,
414 BinaryOperator *I) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000415 Value *A = nullptr, *B = nullptr;
Marcello Maggioni454faa82015-09-15 17:22:52 +0000416 // To be conservative, we reassociate I only when it is the only user of (A op
417 // B).
418 if (LHS->hasOneUse() && matchTernaryOp(I, LHS, A, B)) {
419 // I = (A op B) op RHS
420 // = (A op RHS) op B or (B op RHS) op A
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000421 const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
422 const SCEV *RHSExpr = SE->getSCEV(RHS);
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000423 if (BExpr != RHSExpr) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000424 if (auto *NewI =
425 tryReassociatedBinaryOp(getBinarySCEV(I, AExpr, RHSExpr), B, I))
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000426 return NewI;
427 }
428 if (AExpr != RHSExpr) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000429 if (auto *NewI =
430 tryReassociatedBinaryOp(getBinarySCEV(I, BExpr, RHSExpr), A, I))
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000431 return NewI;
432 }
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000433 }
434 return nullptr;
435}
436
Wei Mi1cf58f82016-07-21 22:28:52 +0000437Instruction *NaryReassociatePass::tryReassociatedBinaryOp(const SCEV *LHSExpr,
438 Value *RHS,
439 BinaryOperator *I) {
Jingyue Wu771dfe92015-04-16 18:42:31 +0000440 // Look for the closest dominator LHS of I that computes LHSExpr, and replace
Marcello Maggioni454faa82015-09-15 17:22:52 +0000441 // I with LHS op RHS.
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000442 auto *LHS = findClosestMatchingDominator(LHSExpr, I);
443 if (LHS == nullptr)
444 return nullptr;
445
Marcello Maggioni454faa82015-09-15 17:22:52 +0000446 Instruction *NewI = nullptr;
447 switch (I->getOpcode()) {
448 case Instruction::Add:
449 NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
450 break;
451 case Instruction::Mul:
452 NewI = BinaryOperator::CreateMul(LHS, RHS, "", I);
453 break;
454 default:
455 llvm_unreachable("Unexpected instruction.");
456 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000457 NewI->takeName(I);
458 return NewI;
459}
460
Wei Mi1cf58f82016-07-21 22:28:52 +0000461bool NaryReassociatePass::matchTernaryOp(BinaryOperator *I, Value *V,
462 Value *&Op1, Value *&Op2) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000463 switch (I->getOpcode()) {
464 case Instruction::Add:
465 return match(V, m_Add(m_Value(Op1), m_Value(Op2)));
466 case Instruction::Mul:
467 return match(V, m_Mul(m_Value(Op1), m_Value(Op2)));
468 default:
469 llvm_unreachable("Unexpected instruction.");
470 }
471 return false;
472}
473
Wei Mi1cf58f82016-07-21 22:28:52 +0000474const SCEV *NaryReassociatePass::getBinarySCEV(BinaryOperator *I,
475 const SCEV *LHS,
476 const SCEV *RHS) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000477 switch (I->getOpcode()) {
478 case Instruction::Add:
479 return SE->getAddExpr(LHS, RHS);
480 case Instruction::Mul:
481 return SE->getMulExpr(LHS, RHS);
482 default:
483 llvm_unreachable("Unexpected instruction.");
484 }
485 return nullptr;
486}
487
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000488Instruction *
Wei Mi1cf58f82016-07-21 22:28:52 +0000489NaryReassociatePass::findClosestMatchingDominator(const SCEV *CandidateExpr,
490 Instruction *Dominatee) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000491 auto Pos = SeenExprs.find(CandidateExpr);
492 if (Pos == SeenExprs.end())
493 return nullptr;
494
495 auto &Candidates = Pos->second;
496 // Because we process the basic blocks in pre-order of the dominator tree, a
Jingyue Wu771dfe92015-04-16 18:42:31 +0000497 // candidate that doesn't dominate the current instruction won't dominate any
498 // future instruction either. Therefore, we pop it out of the stack. This
499 // optimization makes the algorithm O(n).
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000500 while (!Candidates.empty()) {
Jingyue Wudf1a1b12015-10-01 03:51:44 +0000501 // Candidates stores WeakVHs, so a candidate can be nullptr if it's removed
502 // during rewriting.
503 if (Value *Candidate = Candidates.back()) {
504 Instruction *CandidateInstruction = cast<Instruction>(Candidate);
505 if (DT->dominates(CandidateInstruction, Dominatee))
506 return CandidateInstruction;
507 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000508 Candidates.pop_back();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000509 }
510 return nullptr;
511}