[LVer] Fix FIXME: hide addPHINodes, NFC
[oota-llvm.git] / lib / Transforms / Scalar / SeparateConstOffsetFromGEP.cpp
1 //===-- SeparateConstOffsetFromGEP.cpp - ------------------------*- C++ -*-===//
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 // Loop unrolling may create many similar GEPs for array accesses.
11 // e.g., a 2-level loop
12 //
13 // float a[32][32]; // global variable
14 //
15 // for (int i = 0; i < 2; ++i) {
16 //   for (int j = 0; j < 2; ++j) {
17 //     ...
18 //     ... = a[x + i][y + j];
19 //     ...
20 //   }
21 // }
22 //
23 // will probably be unrolled to:
24 //
25 // gep %a, 0, %x, %y; load
26 // gep %a, 0, %x, %y + 1; load
27 // gep %a, 0, %x + 1, %y; load
28 // gep %a, 0, %x + 1, %y + 1; load
29 //
30 // LLVM's GVN does not use partial redundancy elimination yet, and is thus
31 // unable to reuse (gep %a, 0, %x, %y). As a result, this misoptimization incurs
32 // significant slowdown in targets with limited addressing modes. For instance,
33 // because the PTX target does not support the reg+reg addressing mode, the
34 // NVPTX backend emits PTX code that literally computes the pointer address of
35 // each GEP, wasting tons of registers. It emits the following PTX for the
36 // first load and similar PTX for other loads.
37 //
38 // mov.u32         %r1, %x;
39 // mov.u32         %r2, %y;
40 // mul.wide.u32    %rl2, %r1, 128;
41 // mov.u64         %rl3, a;
42 // add.s64         %rl4, %rl3, %rl2;
43 // mul.wide.u32    %rl5, %r2, 4;
44 // add.s64         %rl6, %rl4, %rl5;
45 // ld.global.f32   %f1, [%rl6];
46 //
47 // To reduce the register pressure, the optimization implemented in this file
48 // merges the common part of a group of GEPs, so we can compute each pointer
49 // address by adding a simple offset to the common part, saving many registers.
50 //
51 // It works by splitting each GEP into a variadic base and a constant offset.
52 // The variadic base can be computed once and reused by multiple GEPs, and the
53 // constant offsets can be nicely folded into the reg+immediate addressing mode
54 // (supported by most targets) without using any extra register.
55 //
56 // For instance, we transform the four GEPs and four loads in the above example
57 // into:
58 //
59 // base = gep a, 0, x, y
60 // load base
61 // laod base + 1  * sizeof(float)
62 // load base + 32 * sizeof(float)
63 // load base + 33 * sizeof(float)
64 //
65 // Given the transformed IR, a backend that supports the reg+immediate
66 // addressing mode can easily fold the pointer arithmetics into the loads. For
67 // example, the NVPTX backend can easily fold the pointer arithmetics into the
68 // ld.global.f32 instructions, and the resultant PTX uses much fewer registers.
69 //
70 // mov.u32         %r1, %tid.x;
71 // mov.u32         %r2, %tid.y;
72 // mul.wide.u32    %rl2, %r1, 128;
73 // mov.u64         %rl3, a;
74 // add.s64         %rl4, %rl3, %rl2;
75 // mul.wide.u32    %rl5, %r2, 4;
76 // add.s64         %rl6, %rl4, %rl5;
77 // ld.global.f32   %f1, [%rl6]; // so far the same as unoptimized PTX
78 // ld.global.f32   %f2, [%rl6+4]; // much better
79 // ld.global.f32   %f3, [%rl6+128]; // much better
80 // ld.global.f32   %f4, [%rl6+132]; // much better
81 //
82 // Another improvement enabled by the LowerGEP flag is to lower a GEP with
83 // multiple indices to either multiple GEPs with a single index or arithmetic
84 // operations (depending on whether the target uses alias analysis in codegen).
85 // Such transformation can have following benefits:
86 // (1) It can always extract constants in the indices of structure type.
87 // (2) After such Lowering, there are more optimization opportunities such as
88 //     CSE, LICM and CGP.
89 //
90 // E.g. The following GEPs have multiple indices:
91 //  BB1:
92 //    %p = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 3
93 //    load %p
94 //    ...
95 //  BB2:
96 //    %p2 = getelementptr [10 x %struct]* %ptr, i64 %i, i64 %j1, i32 2
97 //    load %p2
98 //    ...
99 //
100 // We can not do CSE for to the common part related to index "i64 %i". Lowering
101 // GEPs can achieve such goals.
102 // If the target does not use alias analysis in codegen, this pass will
103 // lower a GEP with multiple indices into arithmetic operations:
104 //  BB1:
105 //    %1 = ptrtoint [10 x %struct]* %ptr to i64    ; CSE opportunity
106 //    %2 = mul i64 %i, length_of_10xstruct         ; CSE opportunity
107 //    %3 = add i64 %1, %2                          ; CSE opportunity
108 //    %4 = mul i64 %j1, length_of_struct
109 //    %5 = add i64 %3, %4
110 //    %6 = add i64 %3, struct_field_3              ; Constant offset
111 //    %p = inttoptr i64 %6 to i32*
112 //    load %p
113 //    ...
114 //  BB2:
115 //    %7 = ptrtoint [10 x %struct]* %ptr to i64    ; CSE opportunity
116 //    %8 = mul i64 %i, length_of_10xstruct         ; CSE opportunity
117 //    %9 = add i64 %7, %8                          ; CSE opportunity
118 //    %10 = mul i64 %j2, length_of_struct
119 //    %11 = add i64 %9, %10
120 //    %12 = add i64 %11, struct_field_2            ; Constant offset
121 //    %p = inttoptr i64 %12 to i32*
122 //    load %p2
123 //    ...
124 //
125 // If the target uses alias analysis in codegen, this pass will lower a GEP
126 // with multiple indices into multiple GEPs with a single index:
127 //  BB1:
128 //    %1 = bitcast [10 x %struct]* %ptr to i8*     ; CSE opportunity
129 //    %2 = mul i64 %i, length_of_10xstruct         ; CSE opportunity
130 //    %3 = getelementptr i8* %1, i64 %2            ; CSE opportunity
131 //    %4 = mul i64 %j1, length_of_struct
132 //    %5 = getelementptr i8* %3, i64 %4
133 //    %6 = getelementptr i8* %5, struct_field_3    ; Constant offset
134 //    %p = bitcast i8* %6 to i32*
135 //    load %p
136 //    ...
137 //  BB2:
138 //    %7 = bitcast [10 x %struct]* %ptr to i8*     ; CSE opportunity
139 //    %8 = mul i64 %i, length_of_10xstruct         ; CSE opportunity
140 //    %9 = getelementptr i8* %7, i64 %8            ; CSE opportunity
141 //    %10 = mul i64 %j2, length_of_struct
142 //    %11 = getelementptr i8* %9, i64 %10
143 //    %12 = getelementptr i8* %11, struct_field_2  ; Constant offset
144 //    %p2 = bitcast i8* %12 to i32*
145 //    load %p2
146 //    ...
147 //
148 // Lowering GEPs can also benefit other passes such as LICM and CGP.
149 // LICM (Loop Invariant Code Motion) can not hoist/sink a GEP of multiple
150 // indices if one of the index is variant. If we lower such GEP into invariant
151 // parts and variant parts, LICM can hoist/sink those invariant parts.
152 // CGP (CodeGen Prepare) tries to sink address calculations that match the
153 // target's addressing modes. A GEP with multiple indices may not match and will
154 // not be sunk. If we lower such GEP into smaller parts, CGP may sink some of
155 // them. So we end up with a better addressing mode.
156 //
157 //===----------------------------------------------------------------------===//
158
159 #include "llvm/Analysis/ScalarEvolution.h"
160 #include "llvm/Analysis/TargetTransformInfo.h"
161 #include "llvm/Analysis/ValueTracking.h"
162 #include "llvm/IR/Constants.h"
163 #include "llvm/IR/DataLayout.h"
164 #include "llvm/IR/Dominators.h"
165 #include "llvm/IR/Instructions.h"
166 #include "llvm/IR/LLVMContext.h"
167 #include "llvm/IR/Module.h"
168 #include "llvm/IR/PatternMatch.h"
169 #include "llvm/IR/Operator.h"
170 #include "llvm/Support/CommandLine.h"
171 #include "llvm/Support/raw_ostream.h"
172 #include "llvm/Transforms/Scalar.h"
173 #include "llvm/Transforms/Utils/Local.h"
174 #include "llvm/Target/TargetMachine.h"
175 #include "llvm/Target/TargetSubtargetInfo.h"
176 #include "llvm/IR/IRBuilder.h"
177
178 using namespace llvm;
179 using namespace llvm::PatternMatch;
180
181 static cl::opt<bool> DisableSeparateConstOffsetFromGEP(
182     "disable-separate-const-offset-from-gep", cl::init(false),
183     cl::desc("Do not separate the constant offset from a GEP instruction"),
184     cl::Hidden);
185 // Setting this flag may emit false positives when the input module already
186 // contains dead instructions. Therefore, we set it only in unit tests that are
187 // free of dead code.
188 static cl::opt<bool>
189     VerifyNoDeadCode("reassociate-geps-verify-no-dead-code", cl::init(false),
190                      cl::desc("Verify this pass produces no dead code"),
191                      cl::Hidden);
192
193 namespace {
194
195 /// \brief A helper class for separating a constant offset from a GEP index.
196 ///
197 /// In real programs, a GEP index may be more complicated than a simple addition
198 /// of something and a constant integer which can be trivially splitted. For
199 /// example, to split ((a << 3) | 5) + b, we need to search deeper for the
200 /// constant offset, so that we can separate the index to (a << 3) + b and 5.
201 ///
202 /// Therefore, this class looks into the expression that computes a given GEP
203 /// index, and tries to find a constant integer that can be hoisted to the
204 /// outermost level of the expression as an addition. Not every constant in an
205 /// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a +
206 /// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case,
207 /// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15).
208 class ConstantOffsetExtractor {
209 public:
210   /// Extracts a constant offset from the given GEP index. It returns the
211   /// new index representing the remainder (equal to the original index minus
212   /// the constant offset), or nullptr if we cannot extract a constant offset.
213   /// \p Idx The given GEP index
214   /// \p GEP The given GEP
215   /// \p UserChainTail Outputs the tail of UserChain so that we can
216   ///                  garbage-collect unused instructions in UserChain.
217   static Value *Extract(Value *Idx, GetElementPtrInst *GEP,
218                         User *&UserChainTail, const DominatorTree *DT);
219   /// Looks for a constant offset from the given GEP index without extracting
220   /// it. It returns the numeric value of the extracted constant offset (0 if
221   /// failed). The meaning of the arguments are the same as Extract.
222   static int64_t Find(Value *Idx, GetElementPtrInst *GEP,
223                       const DominatorTree *DT);
224
225 private:
226   ConstantOffsetExtractor(Instruction *InsertionPt, const DominatorTree *DT)
227       : IP(InsertionPt), DL(InsertionPt->getModule()->getDataLayout()), DT(DT) {
228   }
229   /// Searches the expression that computes V for a non-zero constant C s.t.
230   /// V can be reassociated into the form V' + C. If the searching is
231   /// successful, returns C and update UserChain as a def-use chain from C to V;
232   /// otherwise, UserChain is empty.
233   ///
234   /// \p V            The given expression
235   /// \p SignExtended Whether V will be sign-extended in the computation of the
236   ///                 GEP index
237   /// \p ZeroExtended Whether V will be zero-extended in the computation of the
238   ///                 GEP index
239   /// \p NonNegative  Whether V is guaranteed to be non-negative. For example,
240   ///                 an index of an inbounds GEP is guaranteed to be
241   ///                 non-negative. Levaraging this, we can better split
242   ///                 inbounds GEPs.
243   APInt find(Value *V, bool SignExtended, bool ZeroExtended, bool NonNegative);
244   /// A helper function to look into both operands of a binary operator.
245   APInt findInEitherOperand(BinaryOperator *BO, bool SignExtended,
246                             bool ZeroExtended);
247   /// After finding the constant offset C from the GEP index I, we build a new
248   /// index I' s.t. I' + C = I. This function builds and returns the new
249   /// index I' according to UserChain produced by function "find".
250   ///
251   /// The building conceptually takes two steps:
252   /// 1) iteratively distribute s/zext towards the leaves of the expression tree
253   /// that computes I
254   /// 2) reassociate the expression tree to the form I' + C.
255   ///
256   /// For example, to extract the 5 from sext(a + (b + 5)), we first distribute
257   /// sext to a, b and 5 so that we have
258   ///   sext(a) + (sext(b) + 5).
259   /// Then, we reassociate it to
260   ///   (sext(a) + sext(b)) + 5.
261   /// Given this form, we know I' is sext(a) + sext(b).
262   Value *rebuildWithoutConstOffset();
263   /// After the first step of rebuilding the GEP index without the constant
264   /// offset, distribute s/zext to the operands of all operators in UserChain.
265   /// e.g., zext(sext(a + (b + 5)) (assuming no overflow) =>
266   /// zext(sext(a)) + (zext(sext(b)) + zext(sext(5))).
267   ///
268   /// The function also updates UserChain to point to new subexpressions after
269   /// distributing s/zext. e.g., the old UserChain of the above example is
270   /// 5 -> b + 5 -> a + (b + 5) -> sext(...) -> zext(sext(...)),
271   /// and the new UserChain is
272   /// zext(sext(5)) -> zext(sext(b)) + zext(sext(5)) ->
273   ///   zext(sext(a)) + (zext(sext(b)) + zext(sext(5))
274   ///
275   /// \p ChainIndex The index to UserChain. ChainIndex is initially
276   ///               UserChain.size() - 1, and is decremented during
277   ///               the recursion.
278   Value *distributeExtsAndCloneChain(unsigned ChainIndex);
279   /// Reassociates the GEP index to the form I' + C and returns I'.
280   Value *removeConstOffset(unsigned ChainIndex);
281   /// A helper function to apply ExtInsts, a list of s/zext, to value V.
282   /// e.g., if ExtInsts = [sext i32 to i64, zext i16 to i32], this function
283   /// returns "sext i32 (zext i16 V to i32) to i64".
284   Value *applyExts(Value *V);
285
286   /// A helper function that returns whether we can trace into the operands
287   /// of binary operator BO for a constant offset.
288   ///
289   /// \p SignExtended Whether BO is surrounded by sext
290   /// \p ZeroExtended Whether BO is surrounded by zext
291   /// \p NonNegative Whether BO is known to be non-negative, e.g., an in-bound
292   ///                array index.
293   bool CanTraceInto(bool SignExtended, bool ZeroExtended, BinaryOperator *BO,
294                     bool NonNegative);
295
296   /// The path from the constant offset to the old GEP index. e.g., if the GEP
297   /// index is "a * b + (c + 5)". After running function find, UserChain[0] will
298   /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and
299   /// UserChain[2] will be the entire expression "a * b + (c + 5)".
300   ///
301   /// This path helps to rebuild the new GEP index.
302   SmallVector<User *, 8> UserChain;
303   /// A data structure used in rebuildWithoutConstOffset. Contains all
304   /// sext/zext instructions along UserChain.
305   SmallVector<CastInst *, 16> ExtInsts;
306   Instruction *IP;  /// Insertion position of cloned instructions.
307   const DataLayout &DL;
308   const DominatorTree *DT;
309 };
310
311 /// \brief A pass that tries to split every GEP in the function into a variadic
312 /// base and a constant offset. It is a FunctionPass because searching for the
313 /// constant offset may inspect other basic blocks.
314 class SeparateConstOffsetFromGEP : public FunctionPass {
315 public:
316   static char ID;
317   SeparateConstOffsetFromGEP(const TargetMachine *TM = nullptr,
318                              bool LowerGEP = false)
319       : FunctionPass(ID), DL(nullptr), DT(nullptr), TM(TM), LowerGEP(LowerGEP) {
320     initializeSeparateConstOffsetFromGEPPass(*PassRegistry::getPassRegistry());
321   }
322
323   void getAnalysisUsage(AnalysisUsage &AU) const override {
324     AU.addRequired<DominatorTreeWrapperPass>();
325     AU.addRequired<ScalarEvolutionWrapperPass>();
326     AU.addRequired<TargetTransformInfoWrapperPass>();
327     AU.setPreservesCFG();
328   }
329
330   bool doInitialization(Module &M) override {
331     DL = &M.getDataLayout();
332     return false;
333   }
334   bool runOnFunction(Function &F) override;
335
336 private:
337   /// Tries to split the given GEP into a variadic base and a constant offset,
338   /// and returns true if the splitting succeeds.
339   bool splitGEP(GetElementPtrInst *GEP);
340   /// Lower a GEP with multiple indices into multiple GEPs with a single index.
341   /// Function splitGEP already split the original GEP into a variadic part and
342   /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
343   /// variadic part into a set of GEPs with a single index and applies
344   /// AccumulativeByteOffset to it.
345   /// \p Variadic                  The variadic part of the original GEP.
346   /// \p AccumulativeByteOffset    The constant offset.
347   void lowerToSingleIndexGEPs(GetElementPtrInst *Variadic,
348                               int64_t AccumulativeByteOffset);
349   /// Lower a GEP with multiple indices into ptrtoint+arithmetics+inttoptr form.
350   /// Function splitGEP already split the original GEP into a variadic part and
351   /// a constant offset (i.e., AccumulativeByteOffset). This function lowers the
352   /// variadic part into a set of arithmetic operations and applies
353   /// AccumulativeByteOffset to it.
354   /// \p Variadic                  The variadic part of the original GEP.
355   /// \p AccumulativeByteOffset    The constant offset.
356   void lowerToArithmetics(GetElementPtrInst *Variadic,
357                           int64_t AccumulativeByteOffset);
358   /// Finds the constant offset within each index and accumulates them. If
359   /// LowerGEP is true, it finds in indices of both sequential and structure
360   /// types, otherwise it only finds in sequential indices. The output
361   /// NeedsExtraction indicates whether we successfully find a non-zero constant
362   /// offset.
363   int64_t accumulateByteOffset(GetElementPtrInst *GEP, bool &NeedsExtraction);
364   /// Canonicalize array indices to pointer-size integers. This helps to
365   /// simplify the logic of splitting a GEP. For example, if a + b is a
366   /// pointer-size integer, we have
367   ///   gep base, a + b = gep (gep base, a), b
368   /// However, this equality may not hold if the size of a + b is smaller than
369   /// the pointer size, because LLVM conceptually sign-extends GEP indices to
370   /// pointer size before computing the address
371   /// (http://llvm.org/docs/LangRef.html#id181).
372   ///
373   /// This canonicalization is very likely already done in clang and
374   /// instcombine. Therefore, the program will probably remain the same.
375   ///
376   /// Returns true if the module changes.
377   ///
378   /// Verified in @i32_add in split-gep.ll
379   bool canonicalizeArrayIndicesToPointerSize(GetElementPtrInst *GEP);
380   /// Optimize sext(a)+sext(b) to sext(a+b) when a+b can't sign overflow.
381   /// SeparateConstOffsetFromGEP distributes a sext to leaves before extracting
382   /// the constant offset. After extraction, it becomes desirable to reunion the
383   /// distributed sexts. For example,
384   ///
385   ///                              &a[sext(i +nsw (j +nsw 5)]
386   ///   => distribute              &a[sext(i) +nsw (sext(j) +nsw 5)]
387   ///   => constant extraction     &a[sext(i) + sext(j)] + 5
388   ///   => reunion                 &a[sext(i +nsw j)] + 5
389   bool reuniteExts(Function &F);
390   /// A helper that reunites sexts in an instruction.
391   bool reuniteExts(Instruction *I);
392   /// Find the closest dominator of <Dominatee> that is equivalent to <Key>.
393   Instruction *findClosestMatchingDominator(const SCEV *Key,
394                                             Instruction *Dominatee);
395   /// Verify F is free of dead code.
396   void verifyNoDeadCode(Function &F);
397
398   const DataLayout *DL;
399   DominatorTree *DT;
400   ScalarEvolution *SE;
401   const TargetMachine *TM;
402   /// Whether to lower a GEP with multiple indices into arithmetic operations or
403   /// multiple GEPs with a single index.
404   bool LowerGEP;
405   DenseMap<const SCEV *, SmallVector<Instruction *, 2>> DominatingExprs;
406 };
407 }  // anonymous namespace
408
409 char SeparateConstOffsetFromGEP::ID = 0;
410 INITIALIZE_PASS_BEGIN(
411     SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
412     "Split GEPs to a variadic base and a constant offset for better CSE", false,
413     false)
414 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
415 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
416 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
417 INITIALIZE_PASS_END(
418     SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
419     "Split GEPs to a variadic base and a constant offset for better CSE", false,
420     false)
421
422 FunctionPass *
423 llvm::createSeparateConstOffsetFromGEPPass(const TargetMachine *TM,
424                                            bool LowerGEP) {
425   return new SeparateConstOffsetFromGEP(TM, LowerGEP);
426 }
427
428 bool ConstantOffsetExtractor::CanTraceInto(bool SignExtended,
429                                             bool ZeroExtended,
430                                             BinaryOperator *BO,
431                                             bool NonNegative) {
432   // We only consider ADD, SUB and OR, because a non-zero constant found in
433   // expressions composed of these operations can be easily hoisted as a
434   // constant offset by reassociation.
435   if (BO->getOpcode() != Instruction::Add &&
436       BO->getOpcode() != Instruction::Sub &&
437       BO->getOpcode() != Instruction::Or) {
438     return false;
439   }
440
441   Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
442   // Do not trace into "or" unless it is equivalent to "add". If LHS and RHS
443   // don't have common bits, (LHS | RHS) is equivalent to (LHS + RHS).
444   if (BO->getOpcode() == Instruction::Or &&
445       !haveNoCommonBitsSet(LHS, RHS, DL, nullptr, BO, DT))
446     return false;
447
448   // In addition, tracing into BO requires that its surrounding s/zext (if
449   // any) is distributable to both operands.
450   //
451   // Suppose BO = A op B.
452   //  SignExtended | ZeroExtended | Distributable?
453   // --------------+--------------+----------------------------------
454   //       0       |      0       | true because no s/zext exists
455   //       0       |      1       | zext(BO) == zext(A) op zext(B)
456   //       1       |      0       | sext(BO) == sext(A) op sext(B)
457   //       1       |      1       | zext(sext(BO)) ==
458   //               |              |     zext(sext(A)) op zext(sext(B))
459   if (BO->getOpcode() == Instruction::Add && !ZeroExtended && NonNegative) {
460     // If a + b >= 0 and (a >= 0 or b >= 0), then
461     //   sext(a + b) = sext(a) + sext(b)
462     // even if the addition is not marked nsw.
463     //
464     // Leveraging this invarient, we can trace into an sext'ed inbound GEP
465     // index if the constant offset is non-negative.
466     //
467     // Verified in @sext_add in split-gep.ll.
468     if (ConstantInt *ConstLHS = dyn_cast<ConstantInt>(LHS)) {
469       if (!ConstLHS->isNegative())
470         return true;
471     }
472     if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(RHS)) {
473       if (!ConstRHS->isNegative())
474         return true;
475     }
476   }
477
478   // sext (add/sub nsw A, B) == add/sub nsw (sext A), (sext B)
479   // zext (add/sub nuw A, B) == add/sub nuw (zext A), (zext B)
480   if (BO->getOpcode() == Instruction::Add ||
481       BO->getOpcode() == Instruction::Sub) {
482     if (SignExtended && !BO->hasNoSignedWrap())
483       return false;
484     if (ZeroExtended && !BO->hasNoUnsignedWrap())
485       return false;
486   }
487
488   return true;
489 }
490
491 APInt ConstantOffsetExtractor::findInEitherOperand(BinaryOperator *BO,
492                                                    bool SignExtended,
493                                                    bool ZeroExtended) {
494   // BO being non-negative does not shed light on whether its operands are
495   // non-negative. Clear the NonNegative flag here.
496   APInt ConstantOffset = find(BO->getOperand(0), SignExtended, ZeroExtended,
497                               /* NonNegative */ false);
498   // If we found a constant offset in the left operand, stop and return that.
499   // This shortcut might cause us to miss opportunities of combining the
500   // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.
501   // However, such cases are probably already handled by -instcombine,
502   // given this pass runs after the standard optimizations.
503   if (ConstantOffset != 0) return ConstantOffset;
504   ConstantOffset = find(BO->getOperand(1), SignExtended, ZeroExtended,
505                         /* NonNegative */ false);
506   // If U is a sub operator, negate the constant offset found in the right
507   // operand.
508   if (BO->getOpcode() == Instruction::Sub)
509     ConstantOffset = -ConstantOffset;
510   return ConstantOffset;
511 }
512
513 APInt ConstantOffsetExtractor::find(Value *V, bool SignExtended,
514                                     bool ZeroExtended, bool NonNegative) {
515   // TODO(jingyue): We could trace into integer/pointer casts, such as
516   // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only
517   // integers because it gives good enough results for our benchmarks.
518   unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
519
520   // We cannot do much with Values that are not a User, such as an Argument.
521   User *U = dyn_cast<User>(V);
522   if (U == nullptr) return APInt(BitWidth, 0);
523
524   APInt ConstantOffset(BitWidth, 0);
525   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
526     // Hooray, we found it!
527     ConstantOffset = CI->getValue();
528   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
529     // Trace into subexpressions for more hoisting opportunities.
530     if (CanTraceInto(SignExtended, ZeroExtended, BO, NonNegative))
531       ConstantOffset = findInEitherOperand(BO, SignExtended, ZeroExtended);
532   } else if (isa<SExtInst>(V)) {
533     ConstantOffset = find(U->getOperand(0), /* SignExtended */ true,
534                           ZeroExtended, NonNegative).sext(BitWidth);
535   } else if (isa<ZExtInst>(V)) {
536     // As an optimization, we can clear the SignExtended flag because
537     // sext(zext(a)) = zext(a). Verified in @sext_zext in split-gep.ll.
538     //
539     // Clear the NonNegative flag, because zext(a) >= 0 does not imply a >= 0.
540     ConstantOffset =
541         find(U->getOperand(0), /* SignExtended */ false,
542              /* ZeroExtended */ true, /* NonNegative */ false).zext(BitWidth);
543   }
544
545   // If we found a non-zero constant offset, add it to the path for
546   // rebuildWithoutConstOffset. Zero is a valid constant offset, but doesn't
547   // help this optimization.
548   if (ConstantOffset != 0)
549     UserChain.push_back(U);
550   return ConstantOffset;
551 }
552
553 Value *ConstantOffsetExtractor::applyExts(Value *V) {
554   Value *Current = V;
555   // ExtInsts is built in the use-def order. Therefore, we apply them to V
556   // in the reversed order.
557   for (auto I = ExtInsts.rbegin(), E = ExtInsts.rend(); I != E; ++I) {
558     if (Constant *C = dyn_cast<Constant>(Current)) {
559       // If Current is a constant, apply s/zext using ConstantExpr::getCast.
560       // ConstantExpr::getCast emits a ConstantInt if C is a ConstantInt.
561       Current = ConstantExpr::getCast((*I)->getOpcode(), C, (*I)->getType());
562     } else {
563       Instruction *Ext = (*I)->clone();
564       Ext->setOperand(0, Current);
565       Ext->insertBefore(IP);
566       Current = Ext;
567     }
568   }
569   return Current;
570 }
571
572 Value *ConstantOffsetExtractor::rebuildWithoutConstOffset() {
573   distributeExtsAndCloneChain(UserChain.size() - 1);
574   // Remove all nullptrs (used to be s/zext) from UserChain.
575   unsigned NewSize = 0;
576   for (auto I = UserChain.begin(), E = UserChain.end(); I != E; ++I) {
577     if (*I != nullptr) {
578       UserChain[NewSize] = *I;
579       NewSize++;
580     }
581   }
582   UserChain.resize(NewSize);
583   return removeConstOffset(UserChain.size() - 1);
584 }
585
586 Value *
587 ConstantOffsetExtractor::distributeExtsAndCloneChain(unsigned ChainIndex) {
588   User *U = UserChain[ChainIndex];
589   if (ChainIndex == 0) {
590     assert(isa<ConstantInt>(U));
591     // If U is a ConstantInt, applyExts will return a ConstantInt as well.
592     return UserChain[ChainIndex] = cast<ConstantInt>(applyExts(U));
593   }
594
595   if (CastInst *Cast = dyn_cast<CastInst>(U)) {
596     assert((isa<SExtInst>(Cast) || isa<ZExtInst>(Cast)) &&
597            "We only traced into two types of CastInst: sext and zext");
598     ExtInsts.push_back(Cast);
599     UserChain[ChainIndex] = nullptr;
600     return distributeExtsAndCloneChain(ChainIndex - 1);
601   }
602
603   // Function find only trace into BinaryOperator and CastInst.
604   BinaryOperator *BO = cast<BinaryOperator>(U);
605   // OpNo = which operand of BO is UserChain[ChainIndex - 1]
606   unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
607   Value *TheOther = applyExts(BO->getOperand(1 - OpNo));
608   Value *NextInChain = distributeExtsAndCloneChain(ChainIndex - 1);
609
610   BinaryOperator *NewBO = nullptr;
611   if (OpNo == 0) {
612     NewBO = BinaryOperator::Create(BO->getOpcode(), NextInChain, TheOther,
613                                    BO->getName(), IP);
614   } else {
615     NewBO = BinaryOperator::Create(BO->getOpcode(), TheOther, NextInChain,
616                                    BO->getName(), IP);
617   }
618   return UserChain[ChainIndex] = NewBO;
619 }
620
621 Value *ConstantOffsetExtractor::removeConstOffset(unsigned ChainIndex) {
622   if (ChainIndex == 0) {
623     assert(isa<ConstantInt>(UserChain[ChainIndex]));
624     return ConstantInt::getNullValue(UserChain[ChainIndex]->getType());
625   }
626
627   BinaryOperator *BO = cast<BinaryOperator>(UserChain[ChainIndex]);
628   assert(BO->getNumUses() <= 1 &&
629          "distributeExtsAndCloneChain clones each BinaryOperator in "
630          "UserChain, so no one should be used more than "
631          "once");
632
633   unsigned OpNo = (BO->getOperand(0) == UserChain[ChainIndex - 1] ? 0 : 1);
634   assert(BO->getOperand(OpNo) == UserChain[ChainIndex - 1]);
635   Value *NextInChain = removeConstOffset(ChainIndex - 1);
636   Value *TheOther = BO->getOperand(1 - OpNo);
637
638   // If NextInChain is 0 and not the LHS of a sub, we can simplify the
639   // sub-expression to be just TheOther.
640   if (ConstantInt *CI = dyn_cast<ConstantInt>(NextInChain)) {
641     if (CI->isZero() && !(BO->getOpcode() == Instruction::Sub && OpNo == 0))
642       return TheOther;
643   }
644
645   BinaryOperator::BinaryOps NewOp = BO->getOpcode();
646   if (BO->getOpcode() == Instruction::Or) {
647     // Rebuild "or" as "add", because "or" may be invalid for the new
648     // epxression.
649     //
650     // For instance, given
651     //   a | (b + 5) where a and b + 5 have no common bits,
652     // we can extract 5 as the constant offset.
653     //
654     // However, reusing the "or" in the new index would give us
655     //   (a | b) + 5
656     // which does not equal a | (b + 5).
657     //
658     // Replacing the "or" with "add" is fine, because
659     //   a | (b + 5) = a + (b + 5) = (a + b) + 5
660     NewOp = Instruction::Add;
661   }
662
663   BinaryOperator *NewBO;
664   if (OpNo == 0) {
665     NewBO = BinaryOperator::Create(NewOp, NextInChain, TheOther, "", IP);
666   } else {
667     NewBO = BinaryOperator::Create(NewOp, TheOther, NextInChain, "", IP);
668   }
669   NewBO->takeName(BO);
670   return NewBO;
671 }
672
673 Value *ConstantOffsetExtractor::Extract(Value *Idx, GetElementPtrInst *GEP,
674                                         User *&UserChainTail,
675                                         const DominatorTree *DT) {
676   ConstantOffsetExtractor Extractor(GEP, DT);
677   // Find a non-zero constant offset first.
678   APInt ConstantOffset =
679       Extractor.find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
680                      GEP->isInBounds());
681   if (ConstantOffset == 0) {
682     UserChainTail = nullptr;
683     return nullptr;
684   }
685   // Separates the constant offset from the GEP index.
686   Value *IdxWithoutConstOffset = Extractor.rebuildWithoutConstOffset();
687   UserChainTail = Extractor.UserChain.back();
688   return IdxWithoutConstOffset;
689 }
690
691 int64_t ConstantOffsetExtractor::Find(Value *Idx, GetElementPtrInst *GEP,
692                                       const DominatorTree *DT) {
693   // If Idx is an index of an inbound GEP, Idx is guaranteed to be non-negative.
694   return ConstantOffsetExtractor(GEP, DT)
695       .find(Idx, /* SignExtended */ false, /* ZeroExtended */ false,
696             GEP->isInBounds())
697       .getSExtValue();
698 }
699
700 bool SeparateConstOffsetFromGEP::canonicalizeArrayIndicesToPointerSize(
701     GetElementPtrInst *GEP) {
702   bool Changed = false;
703   Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
704   gep_type_iterator GTI = gep_type_begin(*GEP);
705   for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end();
706        I != E; ++I, ++GTI) {
707     // Skip struct member indices which must be i32.
708     if (isa<SequentialType>(*GTI)) {
709       if ((*I)->getType() != IntPtrTy) {
710         *I = CastInst::CreateIntegerCast(*I, IntPtrTy, true, "idxprom", GEP);
711         Changed = true;
712       }
713     }
714   }
715   return Changed;
716 }
717
718 int64_t
719 SeparateConstOffsetFromGEP::accumulateByteOffset(GetElementPtrInst *GEP,
720                                                  bool &NeedsExtraction) {
721   NeedsExtraction = false;
722   int64_t AccumulativeByteOffset = 0;
723   gep_type_iterator GTI = gep_type_begin(*GEP);
724   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
725     if (isa<SequentialType>(*GTI)) {
726       // Tries to extract a constant offset from this GEP index.
727       int64_t ConstantOffset =
728           ConstantOffsetExtractor::Find(GEP->getOperand(I), GEP, DT);
729       if (ConstantOffset != 0) {
730         NeedsExtraction = true;
731         // A GEP may have multiple indices.  We accumulate the extracted
732         // constant offset to a byte offset, and later offset the remainder of
733         // the original GEP with this byte offset.
734         AccumulativeByteOffset +=
735             ConstantOffset * DL->getTypeAllocSize(GTI.getIndexedType());
736       }
737     } else if (LowerGEP) {
738       StructType *StTy = cast<StructType>(*GTI);
739       uint64_t Field = cast<ConstantInt>(GEP->getOperand(I))->getZExtValue();
740       // Skip field 0 as the offset is always 0.
741       if (Field != 0) {
742         NeedsExtraction = true;
743         AccumulativeByteOffset +=
744             DL->getStructLayout(StTy)->getElementOffset(Field);
745       }
746     }
747   }
748   return AccumulativeByteOffset;
749 }
750
751 void SeparateConstOffsetFromGEP::lowerToSingleIndexGEPs(
752     GetElementPtrInst *Variadic, int64_t AccumulativeByteOffset) {
753   IRBuilder<> Builder(Variadic);
754   Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
755
756   Type *I8PtrTy =
757       Builder.getInt8PtrTy(Variadic->getType()->getPointerAddressSpace());
758   Value *ResultPtr = Variadic->getOperand(0);
759   if (ResultPtr->getType() != I8PtrTy)
760     ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
761
762   gep_type_iterator GTI = gep_type_begin(*Variadic);
763   // Create an ugly GEP for each sequential index. We don't create GEPs for
764   // structure indices, as they are accumulated in the constant offset index.
765   for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
766     if (isa<SequentialType>(*GTI)) {
767       Value *Idx = Variadic->getOperand(I);
768       // Skip zero indices.
769       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
770         if (CI->isZero())
771           continue;
772
773       APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
774                                 DL->getTypeAllocSize(GTI.getIndexedType()));
775       // Scale the index by element size.
776       if (ElementSize != 1) {
777         if (ElementSize.isPowerOf2()) {
778           Idx = Builder.CreateShl(
779               Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
780         } else {
781           Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
782         }
783       }
784       // Create an ugly GEP with a single index for each index.
785       ResultPtr =
786           Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Idx, "uglygep");
787     }
788   }
789
790   // Create a GEP with the constant offset index.
791   if (AccumulativeByteOffset != 0) {
792     Value *Offset = ConstantInt::get(IntPtrTy, AccumulativeByteOffset);
793     ResultPtr =
794         Builder.CreateGEP(Builder.getInt8Ty(), ResultPtr, Offset, "uglygep");
795   }
796   if (ResultPtr->getType() != Variadic->getType())
797     ResultPtr = Builder.CreateBitCast(ResultPtr, Variadic->getType());
798
799   Variadic->replaceAllUsesWith(ResultPtr);
800   Variadic->eraseFromParent();
801 }
802
803 void
804 SeparateConstOffsetFromGEP::lowerToArithmetics(GetElementPtrInst *Variadic,
805                                                int64_t AccumulativeByteOffset) {
806   IRBuilder<> Builder(Variadic);
807   Type *IntPtrTy = DL->getIntPtrType(Variadic->getType());
808
809   Value *ResultPtr = Builder.CreatePtrToInt(Variadic->getOperand(0), IntPtrTy);
810   gep_type_iterator GTI = gep_type_begin(*Variadic);
811   // Create ADD/SHL/MUL arithmetic operations for each sequential indices. We
812   // don't create arithmetics for structure indices, as they are accumulated
813   // in the constant offset index.
814   for (unsigned I = 1, E = Variadic->getNumOperands(); I != E; ++I, ++GTI) {
815     if (isa<SequentialType>(*GTI)) {
816       Value *Idx = Variadic->getOperand(I);
817       // Skip zero indices.
818       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx))
819         if (CI->isZero())
820           continue;
821
822       APInt ElementSize = APInt(IntPtrTy->getIntegerBitWidth(),
823                                 DL->getTypeAllocSize(GTI.getIndexedType()));
824       // Scale the index by element size.
825       if (ElementSize != 1) {
826         if (ElementSize.isPowerOf2()) {
827           Idx = Builder.CreateShl(
828               Idx, ConstantInt::get(IntPtrTy, ElementSize.logBase2()));
829         } else {
830           Idx = Builder.CreateMul(Idx, ConstantInt::get(IntPtrTy, ElementSize));
831         }
832       }
833       // Create an ADD for each index.
834       ResultPtr = Builder.CreateAdd(ResultPtr, Idx);
835     }
836   }
837
838   // Create an ADD for the constant offset index.
839   if (AccumulativeByteOffset != 0) {
840     ResultPtr = Builder.CreateAdd(
841         ResultPtr, ConstantInt::get(IntPtrTy, AccumulativeByteOffset));
842   }
843
844   ResultPtr = Builder.CreateIntToPtr(ResultPtr, Variadic->getType());
845   Variadic->replaceAllUsesWith(ResultPtr);
846   Variadic->eraseFromParent();
847 }
848
849 bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {
850   // Skip vector GEPs.
851   if (GEP->getType()->isVectorTy())
852     return false;
853
854   // The backend can already nicely handle the case where all indices are
855   // constant.
856   if (GEP->hasAllConstantIndices())
857     return false;
858
859   bool Changed = canonicalizeArrayIndicesToPointerSize(GEP);
860
861   bool NeedsExtraction;
862   int64_t AccumulativeByteOffset = accumulateByteOffset(GEP, NeedsExtraction);
863
864   if (!NeedsExtraction)
865     return Changed;
866   // If LowerGEP is disabled, before really splitting the GEP, check whether the
867   // backend supports the addressing mode we are about to produce. If no, this
868   // splitting probably won't be beneficial.
869   // If LowerGEP is enabled, even the extracted constant offset can not match
870   // the addressing mode, we can still do optimizations to other lowered parts
871   // of variable indices. Therefore, we don't check for addressing modes in that
872   // case.
873   if (!LowerGEP) {
874     TargetTransformInfo &TTI =
875         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
876             *GEP->getParent()->getParent());
877     unsigned AddrSpace = GEP->getPointerAddressSpace();
878     if (!TTI.isLegalAddressingMode(GEP->getType()->getElementType(),
879                                    /*BaseGV=*/nullptr, AccumulativeByteOffset,
880                                    /*HasBaseReg=*/true, /*Scale=*/0,
881                                    AddrSpace)) {
882       return Changed;
883     }
884   }
885
886   // Remove the constant offset in each sequential index. The resultant GEP
887   // computes the variadic base.
888   // Notice that we don't remove struct field indices here. If LowerGEP is
889   // disabled, a structure index is not accumulated and we still use the old
890   // one. If LowerGEP is enabled, a structure index is accumulated in the
891   // constant offset. LowerToSingleIndexGEPs or lowerToArithmetics will later
892   // handle the constant offset and won't need a new structure index.
893   gep_type_iterator GTI = gep_type_begin(*GEP);
894   for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {
895     if (isa<SequentialType>(*GTI)) {
896       // Splits this GEP index into a variadic part and a constant offset, and
897       // uses the variadic part as the new index.
898       Value *OldIdx = GEP->getOperand(I);
899       User *UserChainTail;
900       Value *NewIdx =
901           ConstantOffsetExtractor::Extract(OldIdx, GEP, UserChainTail, DT);
902       if (NewIdx != nullptr) {
903         // Switches to the index with the constant offset removed.
904         GEP->setOperand(I, NewIdx);
905         // After switching to the new index, we can garbage-collect UserChain
906         // and the old index if they are not used.
907         RecursivelyDeleteTriviallyDeadInstructions(UserChainTail);
908         RecursivelyDeleteTriviallyDeadInstructions(OldIdx);
909       }
910     }
911   }
912
913   // Clear the inbounds attribute because the new index may be off-bound.
914   // e.g.,
915   //
916   //   b     = add i64 a, 5
917   //   addr  = gep inbounds float, float* p, i64 b
918   //
919   // is transformed to:
920   //
921   //   addr2 = gep float, float* p, i64 a ; inbounds removed
922   //   addr  = gep inbounds float, float* addr2, i64 5
923   //
924   // If a is -4, although the old index b is in bounds, the new index a is
925   // off-bound. http://llvm.org/docs/LangRef.html#id181 says "if the
926   // inbounds keyword is not present, the offsets are added to the base
927   // address with silently-wrapping two's complement arithmetic".
928   // Therefore, the final code will be a semantically equivalent.
929   //
930   // TODO(jingyue): do some range analysis to keep as many inbounds as
931   // possible. GEPs with inbounds are more friendly to alias analysis.
932   bool GEPWasInBounds = GEP->isInBounds();
933   GEP->setIsInBounds(false);
934
935   // Lowers a GEP to either GEPs with a single index or arithmetic operations.
936   if (LowerGEP) {
937     // As currently BasicAA does not analyze ptrtoint/inttoptr, do not lower to
938     // arithmetic operations if the target uses alias analysis in codegen.
939     if (TM && TM->getSubtargetImpl(*GEP->getParent()->getParent())->useAA())
940       lowerToSingleIndexGEPs(GEP, AccumulativeByteOffset);
941     else
942       lowerToArithmetics(GEP, AccumulativeByteOffset);
943     return true;
944   }
945
946   // No need to create another GEP if the accumulative byte offset is 0.
947   if (AccumulativeByteOffset == 0)
948     return true;
949
950   // Offsets the base with the accumulative byte offset.
951   //
952   //   %gep                        ; the base
953   //   ... %gep ...
954   //
955   // => add the offset
956   //
957   //   %gep2                       ; clone of %gep
958   //   %new.gep = gep %gep2, <offset / sizeof(*%gep)>
959   //   %gep                        ; will be removed
960   //   ... %gep ...
961   //
962   // => replace all uses of %gep with %new.gep and remove %gep
963   //
964   //   %gep2                       ; clone of %gep
965   //   %new.gep = gep %gep2, <offset / sizeof(*%gep)>
966   //   ... %new.gep ...
967   //
968   // If AccumulativeByteOffset is not a multiple of sizeof(*%gep), we emit an
969   // uglygep (http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep):
970   // bitcast %gep2 to i8*, add the offset, and bitcast the result back to the
971   // type of %gep.
972   //
973   //   %gep2                       ; clone of %gep
974   //   %0       = bitcast %gep2 to i8*
975   //   %uglygep = gep %0, <offset>
976   //   %new.gep = bitcast %uglygep to <type of %gep>
977   //   ... %new.gep ...
978   Instruction *NewGEP = GEP->clone();
979   NewGEP->insertBefore(GEP);
980
981   // Per ANSI C standard, signed / unsigned = unsigned and signed % unsigned =
982   // unsigned.. Therefore, we cast ElementTypeSizeOfGEP to signed because it is
983   // used with unsigned integers later.
984   int64_t ElementTypeSizeOfGEP = static_cast<int64_t>(
985       DL->getTypeAllocSize(GEP->getType()->getElementType()));
986   Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
987   if (AccumulativeByteOffset % ElementTypeSizeOfGEP == 0) {
988     // Very likely. As long as %gep is natually aligned, the byte offset we
989     // extracted should be a multiple of sizeof(*%gep).
990     int64_t Index = AccumulativeByteOffset / ElementTypeSizeOfGEP;
991     NewGEP = GetElementPtrInst::Create(GEP->getResultElementType(), NewGEP,
992                                        ConstantInt::get(IntPtrTy, Index, true),
993                                        GEP->getName(), GEP);
994     // Inherit the inbounds attribute of the original GEP.
995     cast<GetElementPtrInst>(NewGEP)->setIsInBounds(GEPWasInBounds);
996   } else {
997     // Unlikely but possible. For example,
998     // #pragma pack(1)
999     // struct S {
1000     //   int a[3];
1001     //   int64 b[8];
1002     // };
1003     // #pragma pack()
1004     //
1005     // Suppose the gep before extraction is &s[i + 1].b[j + 3]. After
1006     // extraction, it becomes &s[i].b[j] and AccumulativeByteOffset is
1007     // sizeof(S) + 3 * sizeof(int64) = 100, which is not a multiple of
1008     // sizeof(int64).
1009     //
1010     // Emit an uglygep in this case.
1011     Type *I8PtrTy = Type::getInt8PtrTy(GEP->getContext(),
1012                                        GEP->getPointerAddressSpace());
1013     NewGEP = new BitCastInst(NewGEP, I8PtrTy, "", GEP);
1014     NewGEP = GetElementPtrInst::Create(
1015         Type::getInt8Ty(GEP->getContext()), NewGEP,
1016         ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true), "uglygep",
1017         GEP);
1018     // Inherit the inbounds attribute of the original GEP.
1019     cast<GetElementPtrInst>(NewGEP)->setIsInBounds(GEPWasInBounds);
1020     if (GEP->getType() != I8PtrTy)
1021       NewGEP = new BitCastInst(NewGEP, GEP->getType(), GEP->getName(), GEP);
1022   }
1023
1024   GEP->replaceAllUsesWith(NewGEP);
1025   GEP->eraseFromParent();
1026
1027   return true;
1028 }
1029
1030 bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {
1031   if (skipOptnoneFunction(F))
1032     return false;
1033
1034   if (DisableSeparateConstOffsetFromGEP)
1035     return false;
1036
1037   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1038   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1039
1040   bool Changed = false;
1041   for (Function::iterator B = F.begin(), BE = F.end(); B != BE; ++B) {
1042     for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ) {
1043       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++)) {
1044         Changed |= splitGEP(GEP);
1045       }
1046       // No need to split GEP ConstantExprs because all its indices are constant
1047       // already.
1048     }
1049   }
1050
1051   Changed |= reuniteExts(F);
1052
1053   if (VerifyNoDeadCode)
1054     verifyNoDeadCode(F);
1055
1056   return Changed;
1057 }
1058
1059 Instruction *SeparateConstOffsetFromGEP::findClosestMatchingDominator(
1060     const SCEV *Key, Instruction *Dominatee) {
1061   auto Pos = DominatingExprs.find(Key);
1062   if (Pos == DominatingExprs.end())
1063     return nullptr;
1064
1065   auto &Candidates = Pos->second;
1066   // Because we process the basic blocks in pre-order of the dominator tree, a
1067   // candidate that doesn't dominate the current instruction won't dominate any
1068   // future instruction either. Therefore, we pop it out of the stack. This
1069   // optimization makes the algorithm O(n).
1070   while (!Candidates.empty()) {
1071     Instruction *Candidate = Candidates.back();
1072     if (DT->dominates(Candidate, Dominatee))
1073       return Candidate;
1074     Candidates.pop_back();
1075   }
1076   return nullptr;
1077 }
1078
1079 bool SeparateConstOffsetFromGEP::reuniteExts(Instruction *I) {
1080   if (!SE->isSCEVable(I->getType()))
1081     return false;
1082
1083   //   Dom: LHS+RHS
1084   //   I: sext(LHS)+sext(RHS)
1085   // If Dom can't sign overflow and Dom dominates I, optimize I to sext(Dom).
1086   // TODO: handle zext
1087   Value *LHS = nullptr, *RHS = nullptr;
1088   if (match(I, m_Add(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS)))) ||
1089       match(I, m_Sub(m_SExt(m_Value(LHS)), m_SExt(m_Value(RHS))))) {
1090     if (LHS->getType() == RHS->getType()) {
1091       const SCEV *Key =
1092           SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
1093       if (auto *Dom = findClosestMatchingDominator(Key, I)) {
1094         Instruction *NewSExt = new SExtInst(Dom, I->getType(), "", I);
1095         NewSExt->takeName(I);
1096         I->replaceAllUsesWith(NewSExt);
1097         RecursivelyDeleteTriviallyDeadInstructions(I);
1098         return true;
1099       }
1100     }
1101   }
1102
1103   // Add I to DominatingExprs if it's an add/sub that can't sign overflow.
1104   if (match(I, m_NSWAdd(m_Value(LHS), m_Value(RHS))) ||
1105       match(I, m_NSWSub(m_Value(LHS), m_Value(RHS)))) {
1106     if (isKnownNotFullPoison(I)) {
1107       const SCEV *Key =
1108           SE->getAddExpr(SE->getUnknown(LHS), SE->getUnknown(RHS));
1109       DominatingExprs[Key].push_back(I);
1110     }
1111   }
1112   return false;
1113 }
1114
1115 bool SeparateConstOffsetFromGEP::reuniteExts(Function &F) {
1116   bool Changed = false;
1117   DominatingExprs.clear();
1118   for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
1119        Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
1120     BasicBlock *BB = Node->getBlock();
1121     for (auto I = BB->begin(); I != BB->end(); ) {
1122       Instruction *Cur = I++;
1123       Changed |= reuniteExts(Cur);
1124     }
1125   }
1126   return Changed;
1127 }
1128
1129 void SeparateConstOffsetFromGEP::verifyNoDeadCode(Function &F) {
1130   for (auto &B : F) {
1131     for (auto &I : B) {
1132       if (isInstructionTriviallyDead(&I)) {
1133         std::string ErrMessage;
1134         raw_string_ostream RSO(ErrMessage);
1135         RSO << "Dead instruction detected!\n" << I << "\n";
1136         llvm_unreachable(RSO.str().c_str());
1137       }
1138     }
1139   }
1140 }