blob: 7106ea216ad6f282a8b7bdd56c5e418d2e1a05f2 [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"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000080#include "llvm/ADT/DepthFirstIterator.h"
81#include "llvm/ADT/SmallVector.h"
82#include "llvm/Analysis/AssumptionCache.h"
83#include "llvm/Analysis/ScalarEvolution.h"
84#include "llvm/Analysis/TargetLibraryInfo.h"
85#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000086#include "llvm/Transforms/Utils/Local.h"
Jingyue Wucf02ef32015-07-01 03:38:49 +000087#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000088#include "llvm/IR/BasicBlock.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
91#include "llvm/IR/DerivedTypes.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GetElementPtrTypeIterator.h"
95#include "llvm/IR/IRBuilder.h"
96#include "llvm/IR/InstrTypes.h"
97#include "llvm/IR/Instruction.h"
98#include "llvm/IR/Instructions.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +000099#include "llvm/IR/Module.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000100#include "llvm/IR/Operator.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000101#include "llvm/IR/PatternMatch.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000102#include "llvm/IR/Type.h"
103#include "llvm/IR/Value.h"
104#include "llvm/IR/ValueHandle.h"
105#include "llvm/Pass.h"
106#include "llvm/Support/Casting.h"
107#include "llvm/Support/ErrorHandling.h"
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000108#include "llvm/Transforms/Scalar.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000109#include <cassert>
110#include <cstdint>
111
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000112using namespace llvm;
113using namespace PatternMatch;
114
115#define DEBUG_TYPE "nary-reassociate"
116
117namespace {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000118
Wei Mi1cf58f82016-07-21 22:28:52 +0000119class NaryReassociateLegacyPass : public FunctionPass {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000120public:
121 static char ID;
122
Wei Mi1cf58f82016-07-21 22:28:52 +0000123 NaryReassociateLegacyPass() : FunctionPass(ID) {
124 initializeNaryReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000125 }
126
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000127 bool doInitialization(Module &M) override {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000128 return false;
129 }
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000130
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000131 bool runOnFunction(Function &F) override;
132
133 void getAnalysisUsage(AnalysisUsage &AU) const override {
134 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000135 AU.addPreserved<ScalarEvolutionWrapperPass>();
Jingyue Wu8579b812015-04-17 00:25:10 +0000136 AU.addPreserved<TargetLibraryInfoWrapperPass>();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000137 AU.addRequired<AssumptionCacheTracker>();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000138 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000139 AU.addRequired<ScalarEvolutionWrapperPass>();
Jingyue Wu8579b812015-04-17 00:25:10 +0000140 AU.addRequired<TargetLibraryInfoWrapperPass>();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000141 AU.addRequired<TargetTransformInfoWrapperPass>();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000142 AU.setPreservesCFG();
143 }
144
145private:
Wei Mi1cf58f82016-07-21 22:28:52 +0000146 NaryReassociatePass Impl;
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000147};
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000148
149} // end anonymous namespace
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000150
Wei Mi1cf58f82016-07-21 22:28:52 +0000151char NaryReassociateLegacyPass::ID = 0;
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000152
Wei Mi1cf58f82016-07-21 22:28:52 +0000153INITIALIZE_PASS_BEGIN(NaryReassociateLegacyPass, "nary-reassociate",
154 "Nary reassociation", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000155INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000156INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000157INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Jingyue Wu8579b812015-04-17 00:25:10 +0000158INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000159INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Wei Mi1cf58f82016-07-21 22:28:52 +0000160INITIALIZE_PASS_END(NaryReassociateLegacyPass, "nary-reassociate",
161 "Nary reassociation", false, false)
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000162
163FunctionPass *llvm::createNaryReassociatePass() {
Wei Mi1cf58f82016-07-21 22:28:52 +0000164 return new NaryReassociateLegacyPass();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000165}
166
Wei Mi1cf58f82016-07-21 22:28:52 +0000167bool NaryReassociateLegacyPass::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000168 if (skipFunction(F))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000169 return false;
170
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000171 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Wei Mi1cf58f82016-07-21 22:28:52 +0000172 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
173 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
174 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
175 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
176
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000177 return Impl.runImpl(F, AC, DT, SE, TLI, TTI);
Wei Mi1cf58f82016-07-21 22:28:52 +0000178}
179
180PreservedAnalyses NaryReassociatePass::run(Function &F,
181 FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000182 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
Wei Mi1cf58f82016-07-21 22:28:52 +0000183 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
Chandler Carruth6acdca72017-01-24 12:55:57 +0000188 if (!runImpl(F, AC, DT, SE, TLI, TTI))
Wei Mi1cf58f82016-07-21 22:28:52 +0000189 return PreservedAnalyses::all();
190
Wei Mi1cf58f82016-07-21 22:28:52 +0000191 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000192 PA.preserveSet<CFGAnalyses>();
Wei Mi1cf58f82016-07-21 22:28:52 +0000193 PA.preserve<ScalarEvolutionAnalysis>();
Wei Mi1cf58f82016-07-21 22:28:52 +0000194 return PA;
195}
196
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000197bool NaryReassociatePass::runImpl(Function &F, AssumptionCache *AC_,
198 DominatorTree *DT_, ScalarEvolution *SE_,
Wei Mi1cf58f82016-07-21 22:28:52 +0000199 TargetLibraryInfo *TLI_,
200 TargetTransformInfo *TTI_) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000201 AC = AC_;
Wei Mi1cf58f82016-07-21 22:28:52 +0000202 DT = DT_;
203 SE = SE_;
204 TLI = TLI_;
205 TTI = TTI_;
206 DL = &F.getParent()->getDataLayout();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000207
Jingyue Wu8579b812015-04-17 00:25:10 +0000208 bool Changed = false, ChangedInThisIteration;
209 do {
210 ChangedInThisIteration = doOneIteration(F);
211 Changed |= ChangedInThisIteration;
212 } while (ChangedInThisIteration);
213 return Changed;
214}
215
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000216// Whitelist the instruction types NaryReassociate handles for now.
217static bool isPotentiallyNaryReassociable(Instruction *I) {
218 switch (I->getOpcode()) {
219 case Instruction::Add:
220 case Instruction::GetElementPtr:
Marcello Maggioni454faa82015-09-15 17:22:52 +0000221 case Instruction::Mul:
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000222 return true;
223 default:
224 return false;
225 }
226}
227
Wei Mi1cf58f82016-07-21 22:28:52 +0000228bool NaryReassociatePass::doOneIteration(Function &F) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000229 bool Changed = false;
230 SeenExprs.clear();
Daniel Berlina36f4632016-08-19 22:06:23 +0000231 // Process the basic blocks in a depth first traversal of the dominator
232 // tree. This order ensures that all bases of a candidate are in Candidates
233 // when we process it.
234 for (const auto Node : depth_first(DT)) {
235 BasicBlock *BB = Node->getBlock();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000236 for (auto I = BB->begin(); I != BB->end(); ++I) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000237 if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(&*I)) {
238 const SCEV *OldSCEV = SE->getSCEV(&*I);
239 if (Instruction *NewI = tryReassociate(&*I)) {
Jingyue Wu8579b812015-04-17 00:25:10 +0000240 Changed = true;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000241 SE->forgetValue(&*I);
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000242 I->replaceAllUsesWith(NewI);
Karl-Johan Karlsson478232d2018-05-24 06:09:02 +0000243 WeakVH NewIExist = NewI;
244 // If SeenExprs/NewIExist contains I's WeakTrackingVH/WeakVH, that
245 // entry will be replaced with nullptr if deleted.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000246 RecursivelyDeleteTriviallyDeadInstructions(&*I, TLI);
Karl-Johan Karlsson478232d2018-05-24 06:09:02 +0000247 if (!NewIExist) {
248 // Rare occation where the new instruction (NewI) have been removed,
249 // probably due to parts of the input code was dead from the
250 // beginning, reset the iterator and start over from the beginning
251 I = BB->begin();
252 continue;
253 }
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000254 I = NewI->getIterator();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000255 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000256 // Add the rewritten instruction to SeenExprs; the original instruction
257 // is deleted.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000258 const SCEV *NewSCEV = SE->getSCEV(&*I);
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000259 SeenExprs[NewSCEV].push_back(WeakTrackingVH(&*I));
Jingyue Wuc2a01462015-05-28 04:56:52 +0000260 // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
261 // is equivalent to I. However, ScalarEvolution::getSCEV may
262 // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose
263 // we reassociate
264 // I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
265 // to
266 // NewI = &a[sext(i)] + sext(j).
267 //
268 // ScalarEvolution computes
269 // getSCEV(I) = a + 4 * sext(i + j)
270 // getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
271 // which are different SCEVs.
272 //
273 // To alleviate this issue of ScalarEvolution not always capturing
274 // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
275 // map both SCEV before and after tryReassociate(I) to I.
276 //
277 // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
278 if (NewSCEV != OldSCEV)
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000279 SeenExprs[OldSCEV].push_back(WeakTrackingVH(&*I));
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000280 }
281 }
282 }
283 return Changed;
284}
285
Wei Mi1cf58f82016-07-21 22:28:52 +0000286Instruction *NaryReassociatePass::tryReassociate(Instruction *I) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000287 switch (I->getOpcode()) {
288 case Instruction::Add:
Marcello Maggioni454faa82015-09-15 17:22:52 +0000289 case Instruction::Mul:
290 return tryReassociateBinaryOp(cast<BinaryOperator>(I));
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000291 case Instruction::GetElementPtr:
292 return tryReassociateGEP(cast<GetElementPtrInst>(I));
293 default:
294 llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
295 }
296}
297
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000298static bool isGEPFoldable(GetElementPtrInst *GEP,
Jingyue Wu15f3e822016-07-08 21:48:05 +0000299 const TargetTransformInfo *TTI) {
300 SmallVector<const Value*, 4> Indices;
301 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
302 Indices.push_back(*I);
Daniel Jasper3344a212017-10-13 14:04:21 +0000303 return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(),
Jingyue Wu15f3e822016-07-08 21:48:05 +0000304 Indices) == TargetTransformInfo::TCC_Free;
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000305}
306
Wei Mi1cf58f82016-07-21 22:28:52 +0000307Instruction *NaryReassociatePass::tryReassociateGEP(GetElementPtrInst *GEP) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000308 // Not worth reassociating GEP if it is foldable.
Jingyue Wu15f3e822016-07-08 21:48:05 +0000309 if (isGEPFoldable(GEP, TTI))
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000310 return nullptr;
311
312 gep_type_iterator GTI = gep_type_begin(*GEP);
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000313 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
314 if (GTI.isSequential()) {
315 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1,
316 GTI.getIndexedType())) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000317 return NewGEP;
318 }
319 }
320 }
321 return nullptr;
322}
323
Wei Mi1cf58f82016-07-21 22:28:52 +0000324bool NaryReassociatePass::requiresSignExtension(Value *Index,
325 GetElementPtrInst *GEP) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000326 unsigned PointerSizeInBits =
327 DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
328 return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
329}
330
331GetElementPtrInst *
Wei Mi1cf58f82016-07-21 22:28:52 +0000332NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
333 unsigned I, Type *IndexedType) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000334 Value *IndexToSplit = GEP->getOperand(I + 1);
Jingyue Wucf02ef32015-07-01 03:38:49 +0000335 if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000336 IndexToSplit = SExt->getOperand(0);
Jingyue Wucf02ef32015-07-01 03:38:49 +0000337 } else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(IndexToSplit)) {
338 // zext can be treated as sext if the source is non-negative.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000339 if (isKnownNonNegative(ZExt->getOperand(0), *DL, 0, AC, GEP, DT))
Jingyue Wucf02ef32015-07-01 03:38:49 +0000340 IndexToSplit = ZExt->getOperand(0);
341 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000342
343 if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
344 // If the I-th index needs sext and the underlying add is not equipped with
345 // nsw, we cannot split the add because
346 // sext(LHS + RHS) != sext(LHS) + sext(RHS).
Jingyue Wu10fcea52015-08-20 18:27:04 +0000347 if (requiresSignExtension(IndexToSplit, GEP) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000348 computeOverflowForSignedAdd(AO, *DL, AC, GEP, DT) !=
Jingyue Wu10fcea52015-08-20 18:27:04 +0000349 OverflowResult::NeverOverflows)
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000350 return nullptr;
Jingyue Wu10fcea52015-08-20 18:27:04 +0000351
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000352 Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
353 // IndexToSplit = LHS + RHS.
354 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
355 return NewGEP;
356 // Symmetrically, try IndexToSplit = RHS + LHS.
357 if (LHS != RHS) {
358 if (auto *NewGEP =
359 tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
360 return NewGEP;
361 }
362 }
363 return nullptr;
364}
365
Wei Mi1cf58f82016-07-21 22:28:52 +0000366GetElementPtrInst *
367NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
368 unsigned I, Value *LHS,
369 Value *RHS, Type *IndexedType) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000370 // Look for GEP's closest dominator that has the same SCEV as GEP except that
371 // the I-th index is replaced with LHS.
372 SmallVector<const SCEV *, 4> IndexExprs;
373 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
374 IndexExprs.push_back(SE->getSCEV(*Index));
375 // Replace the I-th index with LHS.
376 IndexExprs[I] = SE->getSCEV(LHS);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000377 if (isKnownNonNegative(LHS, *DL, 0, AC, GEP, DT) &&
Jingyue Wucf02ef32015-07-01 03:38:49 +0000378 DL->getTypeSizeInBits(LHS->getType()) <
379 DL->getTypeSizeInBits(GEP->getOperand(I)->getType())) {
380 // Zero-extend LHS if it is non-negative. InstCombine canonicalizes sext to
381 // zext if the source operand is proved non-negative. We should do that
382 // consistently so that CandidateExpr more likely appears before. See
383 // @reassociate_gep_assume for an example of this canonicalization.
384 IndexExprs[I] =
385 SE->getZeroExtendExpr(IndexExprs[I], GEP->getOperand(I)->getType());
386 }
Peter Collingbourne8dff0392016-11-13 06:59:50 +0000387 const SCEV *CandidateExpr = SE->getGEPExpr(cast<GEPOperator>(GEP),
388 IndexExprs);
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000389
Jingyue Wuba3ca762015-12-18 21:36:30 +0000390 Value *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000391 if (Candidate == nullptr)
392 return nullptr;
393
Jingyue Wuba3ca762015-12-18 21:36:30 +0000394 IRBuilder<> Builder(GEP);
395 // Candidate does not necessarily have the same pointer type as GEP. Use
396 // bitcast or pointer cast to make sure they have the same type, so that the
397 // later RAUW doesn't complain.
398 Candidate = Builder.CreateBitOrPointerCast(Candidate, GEP->getType());
399 assert(Candidate->getType() == GEP->getType());
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000400
401 // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType)
402 uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000403 Type *ElementType = GEP->getResultElementType();
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000404 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,
408 //
409 // #pragma pack(1)
410 // struct S {
411 // int a[3];
412 // int64 b[8];
413 // };
414 // #pragma pack()
415 //
416 // sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
417 //
418 // TODO: bail out on this case for now. We could emit uglygep.
419 if (IndexedSize % ElementSize != 0)
420 return nullptr;
421
422 // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
Jingyue Wuba3ca762015-12-18 21:36:30 +0000423 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000424 if (RHS->getType() != IntPtrTy)
425 RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
426 if (IndexedSize != ElementSize) {
427 RHS = Builder.CreateMul(
428 RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
429 }
430 GetElementPtrInst *NewGEP =
431 cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS));
432 NewGEP->setIsInBounds(GEP->isInBounds());
433 NewGEP->takeName(GEP);
434 return NewGEP;
435}
436
Wei Mi1cf58f82016-07-21 22:28:52 +0000437Instruction *NaryReassociatePass::tryReassociateBinaryOp(BinaryOperator *I) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000438 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Evgeny Stupachenko204ade42018-03-07 02:17:08 +0000439 // There is no need to reassociate 0.
440 if (SE->getSCEV(I)->isZero())
441 return nullptr;
Marcello Maggioni454faa82015-09-15 17:22:52 +0000442 if (auto *NewI = tryReassociateBinaryOp(LHS, RHS, I))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000443 return NewI;
Marcello Maggioni454faa82015-09-15 17:22:52 +0000444 if (auto *NewI = tryReassociateBinaryOp(RHS, LHS, I))
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000445 return NewI;
446 return nullptr;
447}
448
Wei Mi1cf58f82016-07-21 22:28:52 +0000449Instruction *NaryReassociatePass::tryReassociateBinaryOp(Value *LHS, Value *RHS,
450 BinaryOperator *I) {
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000451 Value *A = nullptr, *B = nullptr;
Marcello Maggioni454faa82015-09-15 17:22:52 +0000452 // To be conservative, we reassociate I only when it is the only user of (A op
453 // B).
454 if (LHS->hasOneUse() && matchTernaryOp(I, LHS, A, B)) {
455 // I = (A op B) op RHS
456 // = (A op RHS) op B or (B op RHS) op A
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000457 const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
458 const SCEV *RHSExpr = SE->getSCEV(RHS);
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000459 if (BExpr != RHSExpr) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000460 if (auto *NewI =
461 tryReassociatedBinaryOp(getBinarySCEV(I, AExpr, RHSExpr), B, I))
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000462 return NewI;
463 }
464 if (AExpr != RHSExpr) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000465 if (auto *NewI =
466 tryReassociatedBinaryOp(getBinarySCEV(I, BExpr, RHSExpr), A, I))
Jingyue Wuc74e33b2015-05-13 18:12:24 +0000467 return NewI;
468 }
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000469 }
470 return nullptr;
471}
472
Wei Mi1cf58f82016-07-21 22:28:52 +0000473Instruction *NaryReassociatePass::tryReassociatedBinaryOp(const SCEV *LHSExpr,
474 Value *RHS,
475 BinaryOperator *I) {
Jingyue Wu771dfe92015-04-16 18:42:31 +0000476 // Look for the closest dominator LHS of I that computes LHSExpr, and replace
Marcello Maggioni454faa82015-09-15 17:22:52 +0000477 // I with LHS op RHS.
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000478 auto *LHS = findClosestMatchingDominator(LHSExpr, I);
479 if (LHS == nullptr)
480 return nullptr;
481
Marcello Maggioni454faa82015-09-15 17:22:52 +0000482 Instruction *NewI = nullptr;
483 switch (I->getOpcode()) {
484 case Instruction::Add:
485 NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
486 break;
487 case Instruction::Mul:
488 NewI = BinaryOperator::CreateMul(LHS, RHS, "", I);
489 break;
490 default:
491 llvm_unreachable("Unexpected instruction.");
492 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000493 NewI->takeName(I);
494 return NewI;
495}
496
Wei Mi1cf58f82016-07-21 22:28:52 +0000497bool NaryReassociatePass::matchTernaryOp(BinaryOperator *I, Value *V,
498 Value *&Op1, Value *&Op2) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000499 switch (I->getOpcode()) {
500 case Instruction::Add:
501 return match(V, m_Add(m_Value(Op1), m_Value(Op2)));
502 case Instruction::Mul:
503 return match(V, m_Mul(m_Value(Op1), m_Value(Op2)));
504 default:
505 llvm_unreachable("Unexpected instruction.");
506 }
507 return false;
508}
509
Wei Mi1cf58f82016-07-21 22:28:52 +0000510const SCEV *NaryReassociatePass::getBinarySCEV(BinaryOperator *I,
511 const SCEV *LHS,
512 const SCEV *RHS) {
Marcello Maggioni454faa82015-09-15 17:22:52 +0000513 switch (I->getOpcode()) {
514 case Instruction::Add:
515 return SE->getAddExpr(LHS, RHS);
516 case Instruction::Mul:
517 return SE->getMulExpr(LHS, RHS);
518 default:
519 llvm_unreachable("Unexpected instruction.");
520 }
521 return nullptr;
522}
523
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000524Instruction *
Wei Mi1cf58f82016-07-21 22:28:52 +0000525NaryReassociatePass::findClosestMatchingDominator(const SCEV *CandidateExpr,
526 Instruction *Dominatee) {
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000527 auto Pos = SeenExprs.find(CandidateExpr);
528 if (Pos == SeenExprs.end())
529 return nullptr;
530
531 auto &Candidates = Pos->second;
532 // Because we process the basic blocks in pre-order of the dominator tree, a
Jingyue Wu771dfe92015-04-16 18:42:31 +0000533 // candidate that doesn't dominate the current instruction won't dominate any
534 // future instruction either. Therefore, we pop it out of the stack. This
535 // optimization makes the algorithm O(n).
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000536 while (!Candidates.empty()) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000537 // Candidates stores WeakTrackingVHs, so a candidate can be nullptr if it's
538 // removed
Sanjoy Das2cbeb002017-04-26 16:37:05 +0000539 // during rewriting.
Jingyue Wudf1a1b12015-10-01 03:51:44 +0000540 if (Value *Candidate = Candidates.back()) {
541 Instruction *CandidateInstruction = cast<Instruction>(Candidate);
542 if (DT->dominates(CandidateInstruction, Dominatee))
543 return CandidateInstruction;
544 }
Jingyue Wu4fc97f6d2015-05-21 23:17:30 +0000545 Candidates.pop_back();
Jingyue Wu8cb6b2a2015-04-14 04:59:22 +0000546 }
547 return nullptr;
548}