<div dir="ltr">I've seen the bot failures now - working on it.</div><div class="gmail_extra"><br><br><div class="gmail_quote">On Thu, May 1, 2014 at 11:38 AM, Eli Bendersky <span dir="ltr"><<a href="mailto:eliben@google.com" target="_blank">eliben@google.com</a>></span> wrote:<br>

<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Author: eliben<br>
Date: Thu May  1 13:38:36 2014<br>
New Revision: 207783<br>
<br>
URL: <a href="http://llvm.org/viewvc/llvm-project?rev=207783&view=rev" target="_blank">http://llvm.org/viewvc/llvm-project?rev=207783&view=rev</a><br>
Log:<br>
Add an optimization that does CSE in a group of similar GEPs.<br>
<br>
This optimization merges the common part of a group of GEPs, so we can compute<br>
each pointer address by adding a simple offset to the common part.<br>
<br>
The optimization is currently only enabled for the NVPTX backend, where it has<br>
a large payoff on some benchmarks.<br>
<br>
Review: <a href="http://reviews.llvm.org/D3462" target="_blank">http://reviews.llvm.org/D3462</a><br>
<br>
Patch by Jingyue Wu.<br>
<br>
<br>
<br>
Added:<br>
    llvm/trunk/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp<br>
    llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/<br>
    llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/<br>
    llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/lit.local.cfg<br>
    llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep-and-gvn.ll<br>
    llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep.ll<br>
Modified:<br>
    llvm/trunk/include/llvm/InitializePasses.h<br>
    llvm/trunk/include/llvm/LinkAllPasses.h<br>
    llvm/trunk/include/llvm/Transforms/Scalar.h<br>
    llvm/trunk/lib/Target/NVPTX/NVPTXTargetMachine.cpp<br>
    llvm/trunk/lib/Transforms/Scalar/Scalar.cpp<br>
<br>
Modified: llvm/trunk/include/llvm/InitializePasses.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/InitializePasses.h?rev=207783&r1=207782&r2=207783&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/InitializePasses.h?rev=207783&r1=207782&r2=207783&view=diff</a><br>


==============================================================================<br>
--- llvm/trunk/include/llvm/InitializePasses.h (original)<br>
+++ llvm/trunk/include/llvm/InitializePasses.h Thu May  1 13:38:36 2014<br>
@@ -238,6 +238,7 @@ void initializeSimpleInlinerPass(PassReg<br>
 void initializeRegisterCoalescerPass(PassRegistry&);<br>
 void initializeSingleLoopExtractorPass(PassRegistry&);<br>
 void initializeSinkingPass(PassRegistry&);<br>
+void initializeSeparateConstOffsetFromGEPPass(PassRegistry &);<br>
 void initializeSlotIndexesPass(PassRegistry&);<br>
 void initializeSpillPlacementPass(PassRegistry&);<br>
 void initializeStackProtectorPass(PassRegistry&);<br>
<br>
Modified: llvm/trunk/include/llvm/LinkAllPasses.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/LinkAllPasses.h?rev=207783&r1=207782&r2=207783&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/LinkAllPasses.h?rev=207783&r1=207782&r2=207783&view=diff</a><br>


==============================================================================<br>
--- llvm/trunk/include/llvm/LinkAllPasses.h (original)<br>
+++ llvm/trunk/include/llvm/LinkAllPasses.h Thu May  1 13:38:36 2014<br>
@@ -156,6 +156,7 @@ namespace {<br>
       (void) llvm::createBBVectorizePass();<br>
       (void) llvm::createPartiallyInlineLibCallsPass();<br>
       (void) llvm::createScalarizerPass();<br>
+      (void) llvm::createSeparateConstOffsetFromGEPPass();<br>
<br>
       (void)new llvm::IntervalPartition();<br>
       (void)new llvm::FindUsedTypes();<br>
<br>
Modified: llvm/trunk/include/llvm/Transforms/Scalar.h<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Transforms/Scalar.h?rev=207783&r1=207782&r2=207783&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Transforms/Scalar.h?rev=207783&r1=207782&r2=207783&view=diff</a><br>


==============================================================================<br>
--- llvm/trunk/include/llvm/Transforms/Scalar.h (original)<br>
+++ llvm/trunk/include/llvm/Transforms/Scalar.h Thu May  1 13:38:36 2014<br>
@@ -377,6 +377,12 @@ FunctionPass *createScalarizerPass();<br>
 // AddDiscriminators - Add DWARF path discriminators to the IR.<br>
 FunctionPass *createAddDiscriminatorsPass();<br>
<br>
+//===----------------------------------------------------------------------===//<br>
+//<br>
+// SeparateConstOffsetFromGEP - Split GEPs for better CSE<br>
+//<br>
+FunctionPass *createSeparateConstOffsetFromGEPPass();<br>
+<br>
 } // End llvm namespace<br>
<br>
 #endif<br>
<br>
Modified: llvm/trunk/lib/Target/NVPTX/NVPTXTargetMachine.cpp<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/NVPTX/NVPTXTargetMachine.cpp?rev=207783&r1=207782&r2=207783&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/NVPTX/NVPTXTargetMachine.cpp?rev=207783&r1=207782&r2=207783&view=diff</a><br>


==============================================================================<br>
--- llvm/trunk/lib/Target/NVPTX/NVPTXTargetMachine.cpp (original)<br>
+++ llvm/trunk/lib/Target/NVPTX/NVPTXTargetMachine.cpp Thu May  1 13:38:36 2014<br>
@@ -147,10 +147,23 @@ void NVPTXPassConfig::addIRPasses() {<br>
   addPass(createNVPTXAssignValidGlobalNamesPass());<br>
   addPass(createGenericToNVVMPass());<br>
   addPass(createNVPTXFavorNonGenericAddrSpacesPass());<br>
-  // The FavorNonGenericAddrSpaces pass may remove instructions and leave some<br>
-  // values unused. Therefore, we run a DCE pass right afterwards. We could<br>
-  // remove unused values in an ad-hoc manner, but it requires manual work and<br>
-  // might be error-prone.<br>
+  addPass(createSeparateConstOffsetFromGEPPass());<br>
+  // The SeparateConstOffsetFromGEP pass creates variadic bases that can be used<br>
+  // by multiple GEPs. Run GVN or EarlyCSE to really reuse them. GVN generates<br>
+  // significantly better code than EarlyCSE for some of our benchmarks.<br>
+  if (getOptLevel() == CodeGenOpt::Aggressive)<br>
+    addPass(createGVNPass());<br>
+  else<br>
+    addPass(createEarlyCSEPass());<br>
+  // Both FavorNonGenericAddrSpaces and SeparateConstOffsetFromGEP may leave<br>
+  // some dead code.  We could remove dead code in an ad-hoc manner, but that<br>
+  // requires manual work and might be error-prone.<br>
+  //<br>
+  // The FavorNonGenericAddrSpaces pass shortcuts unnecessary addrspacecasts,<br>
+  // and leave them unused.<br>
+  //<br>
+  // SeparateConstOffsetFromGEP rebuilds a new index from the old index, and the<br>
+  // old index and some of its intermediate results may become unused.<br>
   addPass(createDeadCodeEliminationPass());<br>
 }<br>
<br>
<br>
Modified: llvm/trunk/lib/Transforms/Scalar/Scalar.cpp<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Scalar.cpp?rev=207783&r1=207782&r2=207783&view=diff" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Scalar.cpp?rev=207783&r1=207782&r2=207783&view=diff</a><br>


==============================================================================<br>
--- llvm/trunk/lib/Transforms/Scalar/Scalar.cpp (original)<br>
+++ llvm/trunk/lib/Transforms/Scalar/Scalar.cpp Thu May  1 13:38:36 2014<br>
@@ -64,6 +64,7 @@ void llvm::initializeScalarOpts(PassRegi<br>
   initializeStructurizeCFGPass(Registry);<br>
   initializeSinkingPass(Registry);<br>
   initializeTailCallElimPass(Registry);<br>
+  initializeSeparateConstOffsetFromGEPPass(Registry);<br>
 }<br>
<br>
 void LLVMInitializeScalarOpts(LLVMPassRegistryRef R) {<br>
<br>
Added: llvm/trunk/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp?rev=207783&view=auto" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp?rev=207783&view=auto</a><br>


==============================================================================<br>
--- llvm/trunk/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp (added)<br>
+++ llvm/trunk/lib/Transforms/Scalar/SeparateConstOffsetFromGEP.cpp Thu May  1 13:38:36 2014<br>
@@ -0,0 +1,583 @@<br>
+//===-- SeparateConstOffsetFromGEP.cpp - ------------------------*- C++ -*-===//<br>
+//<br>
+//                     The LLVM Compiler Infrastructure<br>
+//<br>
+// This file is distributed under the University of Illinois Open Source<br>
+// License. See LICENSE.TXT for details.<br>
+//<br>
+//===----------------------------------------------------------------------===//<br>
+//<br>
+// Loop unrolling may create many similar GEPs for array accesses.<br>
+// e.g., a 2-level loop<br>
+//<br>
+// float a[32][32]; // global variable<br>
+//<br>
+// for (int i = 0; i < 2; ++i) {<br>
+//   for (int j = 0; j < 2; ++j) {<br>
+//     ...<br>
+//     ... = a[x + i][y + j];<br>
+//     ...<br>
+//   }<br>
+// }<br>
+//<br>
+// will probably be unrolled to:<br>
+//<br>
+// gep %a, 0, %x, %y; load<br>
+// gep %a, 0, %x, %y + 1; load<br>
+// gep %a, 0, %x + 1, %y; load<br>
+// gep %a, 0, %x + 1, %y + 1; load<br>
+//<br>
+// LLVM's GVN does not use partial redundancy elimination yet, and is thus<br>
+// unable to reuse (gep %a, 0, %x, %y). As a result, this misoptimization incurs<br>
+// significant slowdown in targets with limited addressing modes. For instance,<br>
+// because the PTX target does not support the reg+reg addressing mode, the<br>
+// NVPTX backend emits PTX code that literally computes the pointer address of<br>
+// each GEP, wasting tons of registers. It emits the following PTX for the<br>
+// first load and similar PTX for other loads.<br>
+//<br>
+// mov.u32         %r1, %x;<br>
+// mov.u32         %r2, %y;<br>
+// mul.wide.u32    %rl2, %r1, 128;<br>
+// mov.u64         %rl3, a;<br>
+// add.s64         %rl4, %rl3, %rl2;<br>
+// mul.wide.u32    %rl5, %r2, 4;<br>
+// add.s64         %rl6, %rl4, %rl5;<br>
+// ld.global.f32   %f1, [%rl6];<br>
+//<br>
+// To reduce the register pressure, the optimization implemented in this file<br>
+// merges the common part of a group of GEPs, so we can compute each pointer<br>
+// address by adding a simple offset to the common part, saving many registers.<br>
+//<br>
+// It works by splitting each GEP into a variadic base and a constant offset.<br>
+// The variadic base can be computed once and reused by multiple GEPs, and the<br>
+// constant offsets can be nicely folded into the reg+immediate addressing mode<br>
+// (supported by most targets) without using any extra register.<br>
+//<br>
+// For instance, we transform the four GEPs and four loads in the above example<br>
+// into:<br>
+//<br>
+// base = gep a, 0, x, y<br>
+// load base<br>
+// laod base + 1  * sizeof(float)<br>
+// load base + 32 * sizeof(float)<br>
+// load base + 33 * sizeof(float)<br>
+//<br>
+// Given the transformed IR, a backend that supports the reg+immediate<br>
+// addressing mode can easily fold the pointer arithmetics into the loads. For<br>
+// example, the NVPTX backend can easily fold the pointer arithmetics into the<br>
+// ld.global.f32 instructions, and the resultant PTX uses much fewer registers.<br>
+//<br>
+// mov.u32         %r1, %tid.x;<br>
+// mov.u32         %r2, %tid.y;<br>
+// mul.wide.u32    %rl2, %r1, 128;<br>
+// mov.u64         %rl3, a;<br>
+// add.s64         %rl4, %rl3, %rl2;<br>
+// mul.wide.u32    %rl5, %r2, 4;<br>
+// add.s64         %rl6, %rl4, %rl5;<br>
+// ld.global.f32   %f1, [%rl6]; // so far the same as unoptimized PTX<br>
+// ld.global.f32   %f2, [%rl6+4]; // much better<br>
+// ld.global.f32   %f3, [%rl6+128]; // much better<br>
+// ld.global.f32   %f4, [%rl6+132]; // much better<br>
+//<br>
+//===----------------------------------------------------------------------===//<br>
+<br>
+#include "llvm/Analysis/TargetTransformInfo.h"<br>
+#include "llvm/Analysis/ValueTracking.h"<br>
+#include "llvm/IR/Constants.h"<br>
+#include "llvm/IR/DataLayout.h"<br>
+#include "llvm/IR/Instructions.h"<br>
+#include "llvm/IR/LLVMContext.h"<br>
+#include "llvm/IR/Module.h"<br>
+#include "llvm/IR/Operator.h"<br>
+#include "llvm/Support/CommandLine.h"<br>
+#include "llvm/Support/raw_ostream.h"<br>
+#include "llvm/Transforms/Scalar.h"<br>
+<br>
+using namespace llvm;<br>
+<br>
+static cl::opt<bool> DisableSeparateConstOffsetFromGEP(<br>
+    "disable-separate-const-offset-from-gep", cl::init(false),<br>
+    cl::desc("Do not separate the constant offset from a GEP instruction"),<br>
+    cl::Hidden);<br>
+<br>
+namespace {<br>
+<br>
+/// \brief A helper class for separating a constant offset from a GEP index.<br>
+///<br>
+/// In real programs, a GEP index may be more complicated than a simple addition<br>
+/// of something and a constant integer which can be trivially splitted. For<br>
+/// example, to split ((a << 3) | 5) + b, we need to search deeper for the<br>
+/// constant offset, so that we can seperate the index to (a << 3) + b and 5.<br>
+///<br>
+/// Therefore, this class looks into the expression that computes a given GEP<br>
+/// index, and tries to find a constant integer that can be hoisted to the<br>
+/// outermost level of the expression as an addition. Not every constant in an<br>
+/// expression can jump out. e.g., we cannot transform (b * (a + 5)) to (b * a +<br>
+/// 5); nor can we transform (3 * (a + 5)) to (3 * a + 5), however in this case,<br>
+/// -instcombine probably already optimized (3 * (a + 5)) to (3 * a + 15).<br>
+class ConstantOffsetExtractor {<br>
+ public:<br>
+  /// Extracts a constant offset from the given GEP index. It outputs the<br>
+  /// numeric value of the extracted constant offset (0 if failed), and a<br>
+  /// new index representing the remainder (equal to the original index minus<br>
+  /// the constant offset).<br>
+  /// \p Idx The given GEP index<br>
+  /// \p NewIdx The new index to replace<br>
+  /// \p DL The datalayout of the module<br>
+  /// \p IP Calculating the new index requires new instructions. IP indicates<br>
+  /// where to insert them (typically right before the GEP).<br>
+  static int64_t Extract(Value *Idx, Value *&NewIdx, const DataLayout *DL,<br>
+                         Instruction *IP);<br>
+  /// Looks for a constant offset without extracting it. The meaning of the<br>
+  /// arguments and the return value are the same as Extract.<br>
+  static int64_t Find(Value *Idx, const DataLayout *DL);<br>
+<br>
+ private:<br>
+  ConstantOffsetExtractor(const DataLayout *Layout, Instruction *InsertionPt)<br>
+      : DL(Layout), IP(InsertionPt) {}<br>
+  /// Searches the expression that computes V for a constant offset. If the<br>
+  /// searching is successful, update UserChain as a path from V to the constant<br>
+  /// offset.<br>
+  int64_t find(Value *V);<br>
+  /// A helper function to look into both operands of a binary operator U.<br>
+  /// \p IsSub Whether U is a sub operator. If so, we need to negate the<br>
+  /// constant offset at some point.<br>
+  int64_t findInEitherOperand(User *U, bool IsSub);<br>
+  /// After finding the constant offset and how it is reached from the GEP<br>
+  /// index, we build a new index which is a clone of the old one except the<br>
+  /// constant offset is removed. For example, given (a + (b + 5)) and knowning<br>
+  /// the constant offset is 5, this function returns (a + b).<br>
+  ///<br>
+  /// We cannot simply change the constant to zero because the expression that<br>
+  /// computes the index or its intermediate result may be used by others.<br>
+  Value *rebuildWithoutConstantOffset();<br>
+  // A helper function for rebuildWithoutConstantOffset that rebuilds the direct<br>
+  // user (U) of the constant offset (C).<br>
+  Value *rebuildLeafWithoutConstantOffset(User *U, Value *C);<br>
+  /// Returns a clone of U except the first occurrence of From with To.<br>
+  Value *cloneAndReplace(User *U, Value *From, Value *To);<br>
+<br>
+  /// Returns true if LHS and RHS have no bits in common, i.e., LHS | RHS == 0.<br>
+  bool NoCommonBits(Value *LHS, Value *RHS) const;<br>
+  /// Computes which bits are known to be one or zero.<br>
+  /// \p KnownOne Mask of all bits that are known to be one.<br>
+  /// \p KnownZero Mask of all bits that are known to be zero.<br>
+  void ComputeKnownBits(Value *V, APInt &KnownOne, APInt &KnownZero) const;<br>
+  /// Finds the first use of Used in U. Returns -1 if not found.<br>
+  static unsigned FindFirstUse(User *U, Value *Used);<br>
+<br>
+  /// The path from the constant offset to the old GEP index. e.g., if the GEP<br>
+  /// index is "a * b + (c + 5)". After running function find, UserChain[0] will<br>
+  /// be the constant 5, UserChain[1] will be the subexpression "c + 5", and<br>
+  /// UserChain[2] will be the entire expression "a * b + (c + 5)".<br>
+  ///<br>
+  /// This path helps rebuildWithoutConstantOffset rebuild the new GEP index.<br>
+  SmallVector<User *, 8> UserChain;<br>
+  /// The data layout of the module. Used in ComputeKnownBits.<br>
+  const DataLayout *DL;<br>
+  Instruction *IP;  /// Insertion position of cloned instructions.<br>
+};<br>
+<br>
+/// \brief A pass that tries to split every GEP in the function into a variadic<br>
+/// base and a constant offset. It is a FuntionPass because searching for the<br>
+/// constant offset may inspect other basic blocks.<br>
+class SeparateConstOffsetFromGEP : public FunctionPass {<br>
+ public:<br>
+  static char ID;<br>
+  SeparateConstOffsetFromGEP() : FunctionPass(ID) {<br>
+    initializeSeparateConstOffsetFromGEPPass(*PassRegistry::getPassRegistry());<br>
+  }<br>
+<br>
+  void getAnalysisUsage(AnalysisUsage &AU) const override {<br>
+    AU.addRequired<DataLayoutPass>();<br>
+    AU.addRequired<TargetTransformInfo>();<br>
+  }<br>
+  bool runOnFunction(Function &F) override;<br>
+<br>
+ private:<br>
+  /// Tries to split the given GEP into a variadic base and a constant offset,<br>
+  /// and returns true if the splitting succeeds.<br>
+  bool splitGEP(GetElementPtrInst *GEP);<br>
+  /// Finds the constant offset within each index, and accumulates them. This<br>
+  /// function only inspects the GEP without changing it. The output<br>
+  /// NeedsExtraction indicates whether we can extract a non-zero constant<br>
+  /// offset from any index.<br>
+  int64_t accumulateByteOffset(GetElementPtrInst *GEP, const DataLayout *DL,<br>
+                               bool &NeedsExtraction);<br>
+};<br>
+}  // anonymous namespace<br>
+<br>
+char SeparateConstOffsetFromGEP::ID = 0;<br>
+INITIALIZE_PASS_BEGIN(<br>
+    SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",<br>
+    "Split GEPs to a variadic base and a constant offset for better CSE", false,<br>
+    false)<br>
+INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)<br>
+INITIALIZE_PASS_DEPENDENCY(DataLayoutPass)<br>
+INITIALIZE_PASS_END(<br>
+    SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",<br>
+    "Split GEPs to a variadic base and a constant offset for better CSE", false,<br>
+    false)<br>
+<br>
+FunctionPass *llvm::createSeparateConstOffsetFromGEPPass() {<br>
+  return new SeparateConstOffsetFromGEP();<br>
+}<br>
+<br>
+int64_t ConstantOffsetExtractor::findInEitherOperand(User *U, bool IsSub) {<br>
+  assert(U->getNumOperands() == 2);<br>
+  int64_t ConstantOffset = find(U->getOperand(0));<br>
+  // If we found a constant offset in the left operand, stop and return that.<br>
+  // This shortcut might cause us to miss opportunities of combining the<br>
+  // constant offsets in both operands, e.g., (a + 4) + (b + 5) => (a + b) + 9.<br>
+  // However, such cases are probably already handled by -instcombine,<br>
+  // given this pass runs after the standard optimizations.<br>
+  if (ConstantOffset != 0) return ConstantOffset;<br>
+  ConstantOffset = find(U->getOperand(1));<br>
+  // If U is a sub operator, negate the constant offset found in the right<br>
+  // operand.<br>
+  return IsSub ? -ConstantOffset : ConstantOffset;<br>
+}<br>
+<br>
+int64_t ConstantOffsetExtractor::find(Value *V) {<br>
+  // TODO(jingyue): We can even trace into integer/pointer casts, such as<br>
+  // inttoptr, ptrtoint, bitcast, and addrspacecast. We choose to handle only<br>
+  // integers because it gives good enough results for our benchmarks.<br>
+  assert(V->getType()->isIntegerTy());<br>
+<br>
+  User *U = dyn_cast<User>(V);<br>
+  // We cannot do much with Values that are not a User, such as BasicBlock and<br>
+  // MDNode.<br>
+  if (U == nullptr) return 0;<br>
+<br>
+  int64_t ConstantOffset = 0;<br>
+  if (ConstantInt *CI = dyn_cast<ConstantInt>(U)) {<br>
+    // Hooray, we found it!<br>
+    ConstantOffset = CI->getSExtValue();<br>
+  } else if (Operator *O = dyn_cast<Operator>(U)) {<br>
+    // The GEP index may be more complicated than a simple addition of a<br>
+    // varaible and a constant. Therefore, we trace into subexpressions for more<br>
+    // hoisting opportunities.<br>
+    switch (O->getOpcode()) {<br>
+      case Instruction::Add: {<br>
+        ConstantOffset = findInEitherOperand(U, false);<br>
+        break;<br>
+      }<br>
+      case Instruction::Sub: {<br>
+        ConstantOffset = findInEitherOperand(U, true);<br>
+        break;<br>
+      }<br>
+      case Instruction::Or: {<br>
+        // If LHS and RHS don't have common bits, (LHS | RHS) is equivalent to<br>
+        // (LHS + RHS).<br>
+        if (NoCommonBits(U->getOperand(0), U->getOperand(1)))<br>
+          ConstantOffset = findInEitherOperand(U, false);<br>
+        break;<br>
+      }<br>
+      case Instruction::SExt: {<br>
+        // For safety, we trace into sext only when its operand is marked<br>
+        // "nsw" because xxx.nsw guarantees no signed wrap. e.g., we can safely<br>
+        // transform "sext (add nsw a, 5)" into "add nsw (sext a), 5".<br>
+        if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) {<br>
+          if (BO->hasNoSignedWrap())<br>
+            ConstantOffset = find(U->getOperand(0));<br>
+        }<br>
+        break;<br>
+      }<br>
+      case Instruction::ZExt: {<br>
+        // Similarly, we trace into zext only when its operand is marked with<br>
+        // "nuw" because zext (add nuw a, b) == add nuw (zext a), (zext b).<br>
+        if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0))) {<br>
+          if (BO->hasNoUnsignedWrap())<br>
+            ConstantOffset = find(U->getOperand(0));<br>
+        }<br>
+        break;<br>
+      }<br>
+    }<br>
+  }<br>
+  // If we found a non-zero constant offset, adds it to the path for future<br>
+  // transformation (rebuildWithoutConstantOffset). Zero is a valid constant<br>
+  // offset, but doesn't help this optimization.<br>
+  if (ConstantOffset != 0)<br>
+    UserChain.push_back(U);<br>
+  return ConstantOffset;<br>
+}<br>
+<br>
+unsigned ConstantOffsetExtractor::FindFirstUse(User *U, Value *Used) {<br>
+  for (unsigned I = 0, E = U->getNumOperands(); I < E; ++I) {<br>
+    if (U->getOperand(I) == Used)<br>
+      return I;<br>
+  }<br>
+  return -1;<br>
+}<br>
+<br>
+Value *ConstantOffsetExtractor::cloneAndReplace(User *U, Value *From,<br>
+                                                Value *To) {<br>
+  // Finds in U the first use of From. It is safe to ignore future occurrences<br>
+  // of From, because findInEitherOperand similarly stops searching the right<br>
+  // operand when the first operand has a non-zero constant offset.<br>
+  unsigned OpNo = FindFirstUse(U, From);<br>
+  assert(OpNo != (unsigned)-1 && "UserChain wasn't built correctly");<br>
+<br>
+  // ConstantOffsetExtractor::find only follows Operators (i.e., Instructions<br>
+  // and ConstantExprs). Therefore, U is either an Instruction or a<br>
+  // ConstantExpr.<br>
+  if (Instruction *I = dyn_cast<Instruction>(U)) {<br>
+    Instruction *Clone = I->clone();<br>
+    Clone->setOperand(OpNo, To);<br>
+    Clone->insertBefore(IP);<br>
+    return Clone;<br>
+  }<br>
+  // cast<Constant>(To) is safe because a ConstantExpr only uses Constants.<br>
+  return cast<ConstantExpr>(U)<br>
+      ->getWithOperandReplaced(OpNo, cast<Constant>(To));<br>
+}<br>
+<br>
+Value *ConstantOffsetExtractor::rebuildLeafWithoutConstantOffset(User *U,<br>
+                                                                 Value *C) {<br>
+  assert(U->getNumOperands() <= 2 &&<br>
+         "We didn't trace into any operator with more than 2 operands");<br>
+  // If U has only one operand which is the constant offset, removing the<br>
+  // constant offset leaves U as a null value.<br>
+  if (U->getNumOperands() == 1)<br>
+    return Constant::getNullValue(U->getType());<br>
+<br>
+  // U->getNumOperands() == 2<br>
+  unsigned OpNo = FindFirstUse(U, C); // U->getOperand(OpNo) == C<br>
+  assert(OpNo < 2 && "UserChain wasn't built correctly");<br>
+  Value *TheOther = U->getOperand(1 - OpNo); // The other operand of U<br>
+  // If U = C - X, removing C makes U = -X; otherwise U will simply be X.<br>
+  if (!isa<SubOperator>(U) || OpNo == 1)<br>
+    return TheOther;<br>
+  if (isa<ConstantExpr>(U))<br>
+    return ConstantExpr::getNeg(cast<Constant>(TheOther));<br>
+  return BinaryOperator::CreateNeg(TheOther, "", IP);<br>
+}<br>
+<br>
+Value *ConstantOffsetExtractor::rebuildWithoutConstantOffset() {<br>
+  assert(UserChain.size() > 0 && "you at least found a constant, right?");<br>
+  // Start with the constant and go up through UserChain, each time building a<br>
+  // clone of the subexpression but with the constant removed.<br>
+  // e.g., to build a clone of (a + (b + (c + 5)) but with the 5 removed, we<br>
+  // first c, then (b + c), and finally (a + (b + c)).<br>
+  //<br>
+  // Fast path: if the GEP index is a constant, simply returns 0.<br>
+  if (UserChain.size() == 1)<br>
+    return ConstantInt::get(UserChain[0]->getType(), 0);<br>
+<br>
+  Value *Remainder =<br>
+      rebuildLeafWithoutConstantOffset(UserChain[1], UserChain[0]);<br>
+  for (size_t I = 2; I < UserChain.size(); ++I)<br>
+    Remainder = cloneAndReplace(UserChain[I], UserChain[I - 1], Remainder);<br>
+  return Remainder;<br>
+}<br>
+<br>
+int64_t ConstantOffsetExtractor::Extract(Value *Idx, Value *&NewIdx,<br>
+                                         const DataLayout *DL,<br>
+                                         Instruction *IP) {<br>
+  ConstantOffsetExtractor Extractor(DL, IP);<br>
+  // Find a non-zero constant offset first.<br>
+  int64_t ConstantOffset = Extractor.find(Idx);<br>
+  if (ConstantOffset == 0)<br>
+    return 0;<br>
+  // Then rebuild a new index with the constant removed.<br>
+  NewIdx = Extractor.rebuildWithoutConstantOffset();<br>
+  return ConstantOffset;<br>
+}<br>
+<br>
+int64_t ConstantOffsetExtractor::Find(Value *Idx, const DataLayout *DL) {<br>
+  return ConstantOffsetExtractor(DL, nullptr).find(Idx);<br>
+}<br>
+<br>
+void ConstantOffsetExtractor::ComputeKnownBits(Value *V, APInt &KnownOne,<br>
+                                               APInt &KnownZero) const {<br>
+  IntegerType *IT = cast<IntegerType>(V->getType());<br>
+  KnownOne = APInt(IT->getBitWidth(), 0);<br>
+  KnownZero = APInt(IT->getBitWidth(), 0);<br>
+  llvm::ComputeMaskedBits(V, KnownZero, KnownOne, DL, 0);<br>
+}<br>
+<br>
+bool ConstantOffsetExtractor::NoCommonBits(Value *LHS, Value *RHS) const {<br>
+  assert(LHS->getType() == RHS->getType() &&<br>
+         "LHS and RHS should have the same type");<br>
+  APInt LHSKnownOne, LHSKnownZero, RHSKnownOne, RHSKnownZero;<br>
+  ComputeKnownBits(LHS, LHSKnownOne, LHSKnownZero);<br>
+  ComputeKnownBits(RHS, RHSKnownOne, RHSKnownZero);<br>
+  return (LHSKnownZero | RHSKnownZero).isAllOnesValue();<br>
+}<br>
+<br>
+int64_t SeparateConstOffsetFromGEP::accumulateByteOffset(<br>
+    GetElementPtrInst *GEP, const DataLayout *DL, bool &NeedsExtraction) {<br>
+  NeedsExtraction = false;<br>
+  int64_t AccumulativeByteOffset = 0;<br>
+  gep_type_iterator GTI = gep_type_begin(*GEP);<br>
+  for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {<br>
+    if (isa<SequentialType>(*GTI)) {<br>
+      // Tries to extract a constant offset from this GEP index.<br>
+      int64_t ConstantOffset =<br>
+          ConstantOffsetExtractor::Find(GEP->getOperand(I), DL);<br>
+      if (ConstantOffset != 0) {<br>
+        NeedsExtraction = true;<br>
+        // A GEP may have multiple indices.  We accumulate the extracted<br>
+        // constant offset to a byte offset, and later offset the remainder of<br>
+        // the original GEP with this byte offset.<br>
+        AccumulativeByteOffset +=<br>
+            ConstantOffset * DL->getTypeAllocSize(GTI.getIndexedType());<br>
+      }<br>
+    }<br>
+  }<br>
+  return AccumulativeByteOffset;<br>
+}<br>
+<br>
+bool SeparateConstOffsetFromGEP::splitGEP(GetElementPtrInst *GEP) {<br>
+  // Skip vector GEPs.<br>
+  if (GEP->getType()->isVectorTy())<br>
+    return false;<br>
+<br>
+  // The backend can already nicely handle the case where all indices are<br>
+  // constant.<br>
+  if (GEP->hasAllConstantIndices())<br>
+    return false;<br>
+<br>
+  bool Changed = false;<br>
+<br>
+  // Shortcuts integer casts. Eliminating these explicit casts can make<br>
+  // subsequent optimizations more obvious: ConstantOffsetExtractor needn't<br>
+  // trace into these casts.<br>
+  if (GEP->isInBounds()) {<br>
+    // Doing this to inbounds GEPs is safe because their indices are guaranteed<br>
+    // to be non-negative and in bounds.<br>
+    gep_type_iterator GTI = gep_type_begin(*GEP);<br>
+    for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {<br>
+      if (isa<SequentialType>(*GTI)) {<br>
+        if (Operator *O = dyn_cast<Operator>(GEP->getOperand(I))) {<br>
+          if (O->getOpcode() == Instruction::SExt ||<br>
+              O->getOpcode() == Instruction::ZExt) {<br>
+            GEP->setOperand(I, O->getOperand(0));<br>
+            Changed = true;<br>
+          }<br>
+        }<br>
+      }<br>
+    }<br>
+  }<br>
+<br>
+  const DataLayout *DL = &getAnalysis<DataLayoutPass>().getDataLayout();<br>
+  bool NeedsExtraction;<br>
+  int64_t AccumulativeByteOffset =<br>
+      accumulateByteOffset(GEP, DL, NeedsExtraction);<br>
+<br>
+  if (!NeedsExtraction)<br>
+    return Changed;<br>
+  // Before really splitting the GEP, check whether the backend supports the<br>
+  // addressing mode we are about to produce. If no, this splitting probably<br>
+  // won't be beneficial.<br>
+  TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();<br>
+  if (!TTI.isLegalAddressingMode(GEP->getType()->getElementType(),<br>
+                                 /*BaseGV=*/nullptr, AccumulativeByteOffset,<br>
+                                 /*HasBaseReg=*/true, /*Scale=*/0)) {<br>
+    return Changed;<br>
+  }<br>
+<br>
+  // Remove the constant offset in each GEP index. The resultant GEP computes<br>
+  // the variadic base.<br>
+  gep_type_iterator GTI = gep_type_begin(*GEP);<br>
+  for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) {<br>
+    if (isa<SequentialType>(*GTI)) {<br>
+      Value *NewIdx = nullptr;<br>
+      // Tries to extract a constant offset from this GEP index.<br>
+      int64_t ConstantOffset =<br>
+          ConstantOffsetExtractor::Extract(GEP->getOperand(I), NewIdx, DL, GEP);<br>
+      if (ConstantOffset != 0) {<br>
+        assert(NewIdx && "ConstantOffset != 0 implies NewIdx is set");<br>
+        GEP->setOperand(I, NewIdx);<br>
+        // Clear the inbounds attribute because the new index may be off-bound.<br>
+        // e.g.,<br>
+        //<br>
+        // b = add i64 a, 5<br>
+        // addr = gep inbounds float* p, i64 b<br>
+        //<br>
+        // is transformed to:<br>
+        //<br>
+        // addr2 = gep float* p, i64 a<br>
+        // addr = gep float* addr2, i64 5<br>
+        //<br>
+        // If a is -4, although the old index b is in bounds, the new index a is<br>
+        // off-bound. <a href="http://llvm.org/docs/LangRef.html#id181" target="_blank">http://llvm.org/docs/LangRef.html#id181</a> says "if the<br>
+        // inbounds keyword is not present, the offsets are added to the base<br>
+        // address with silently-wrapping two's complement arithmetic".<br>
+        // Therefore, the final code will be a semantically equivalent.<br>
+        //<br>
+        // TODO(jingyue): do some range analysis to keep as many inbounds as<br>
+        // possible. GEPs with inbounds are more friendly to alias analysis.<br>
+        GEP->setIsInBounds(false);<br>
+        Changed = true;<br>
+      }<br>
+    }<br>
+  }<br>
+<br>
+  // Offsets the base with the accumulative byte offset.<br>
+  //<br>
+  //   %gep                        ; the base<br>
+  //   ... %gep ...<br>
+  //<br>
+  // => add the offset<br>
+  //<br>
+  //   %gep2                       ; clone of %gep<br>
+  //   %0       = ptrtoint %gep2<br>
+  //   %1       = add %0, <offset><br>
+  //   %new.gep = inttoptr %1<br>
+  //   %gep                        ; will be removed<br>
+  //   ... %gep ...<br>
+  //<br>
+  // => replace all uses of %gep with %new.gep and remove %gep<br>
+  //<br>
+  //   %gep2                       ; clone of %gep<br>
+  //   %0       = ptrtoint %gep2<br>
+  //   %1       = add %0, <offset><br>
+  //   %new.gep = inttoptr %1<br>
+  //   ... %new.gep ...<br>
+  //<br>
+  // TODO(jingyue): Emit a GEP instead of an "uglygep"<br>
+  // (<a href="http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep" target="_blank">http://llvm.org/docs/GetElementPtr.html#what-s-an-uglygep</a>) to make the IR<br>
+  // prettier and more alias analysis friendly. One caveat: if the original GEP<br>
+  // ends with a StructType, we need to split the GEP at the last<br>
+  // SequentialType. For instance, consider the following IR:<br>
+  //<br>
+  //   %struct.S = type { float, double }<br>
+  //   @array = global [1024 x %struct.S]<br>
+  //   %p = getelementptr %array, 0, %i + 5, 1<br>
+  //<br>
+  // To separate the constant 5 from %p, we would need to split %p at the last<br>
+  // array index so that we have:<br>
+  //<br>
+  //   %addr = gep %array, 0, %i<br>
+  //   %p = gep %addr, 5, 1<br>
+  Instruction *NewGEP = GEP->clone();<br>
+  NewGEP->insertBefore(GEP);<br>
+  Type *IntPtrTy = DL->getIntPtrType(GEP->getType());<br>
+  Value *Addr = new PtrToIntInst(NewGEP, IntPtrTy, "", GEP);<br>
+  Addr = BinaryOperator::CreateAdd(<br>
+      Addr, ConstantInt::get(IntPtrTy, AccumulativeByteOffset, true), "", GEP);<br>
+  Addr = new IntToPtrInst(Addr, GEP->getType(), "", GEP);<br>
+<br>
+  GEP->replaceAllUsesWith(Addr);<br>
+  GEP->eraseFromParent();<br>
+<br>
+  return true;<br>
+}<br>
+<br>
+bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {<br>
+  if (DisableSeparateConstOffsetFromGEP)<br>
+    return false;<br>
+<br>
+  bool Changed = false;<br>
+  for (Function::iterator B = F.begin(), BE = F.end(); B != BE; ++B) {<br>
+    for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ) {<br>
+      if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++)) {<br>
+        Changed |= splitGEP(GEP);<br>
+      }<br>
+      // No need to split GEP ConstantExprs because all its indices are constant<br>
+      // already.<br>
+    }<br>
+  }<br>
+  return Changed;<br>
+}<br>
<br>
Added: llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/lit.local.cfg<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/lit.local.cfg?rev=207783&view=auto" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/lit.local.cfg?rev=207783&view=auto</a><br>


==============================================================================<br>
--- llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/lit.local.cfg (added)<br>
+++ llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/lit.local.cfg Thu May  1 13:38:36 2014<br>
@@ -0,0 +1,4 @@<br>
+targets = set(config.root.targets_to_build.split())<br>
+if not 'NVPTX' in targets:<br>
+    config.unsupported = True<br>
+<br>
<br>
Added: llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep-and-gvn.ll<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep-and-gvn.ll?rev=207783&view=auto" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep-and-gvn.ll?rev=207783&view=auto</a><br>


==============================================================================<br>
--- llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep-and-gvn.ll (added)<br>
+++ llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep-and-gvn.ll Thu May  1 13:38:36 2014<br>
@@ -0,0 +1,60 @@<br>
+; RUN: llc < %s -march=nvptx -mcpu=sm_20 | FileCheck %s --check-prefix=PTX<br>
+; RUN: llc < %s -march=nvptx64 -mcpu=sm_20 | FileCheck %s --check-prefix=PTX<br>
+; RUN: opt < %s -S -separate-const-offset-from-gep -gvn -dce | FileCheck %s --check-prefix=IR<br>
+<br>
+; Verifies the SeparateConstOffsetFromGEP pass.<br>
+; The following code computes<br>
+; *output = array[x][y] + array[x][y+1] + array[x+1][y] + array[x+1][y+1]<br>
+;<br>
+; We expect SeparateConstOffsetFromGEP to transform it to<br>
+;<br>
+; float *base = &a[x][y];<br>
+; *output = base[0] + base[1] + base[32] + base[33];<br>
+;<br>
+; so the backend can emit PTX that uses fewer virtual registers.<br>
+<br>
+target datalayout = "e-i64:64-v16:16-v32:32-n16:32:64"<br>
+target triple = "nvptx64-unknown-unknown"<br>
+<br>
+@array = internal addrspace(3) constant [32 x [32 x float]] zeroinitializer, align 4<br>
+<br>
+define void @sum_of_array(i32 %x, i32 %y, float* nocapture %output) {<br>
+.preheader:<br>
+  %0 = zext i32 %y to i64<br>
+  %1 = zext i32 %x to i64<br>
+  %2 = getelementptr inbounds [32 x [32 x float]] addrspace(3)* @array, i64 0, i64 %1, i64 %0<br>
+  %3 = addrspacecast float addrspace(3)* %2 to float*<br>
+  %4 = load float* %3, align 4<br>
+  %5 = fadd float %4, 0.000000e+00<br>
+  %6 = add i32 %y, 1<br>
+  %7 = zext i32 %6 to i64<br>
+  %8 = getelementptr inbounds [32 x [32 x float]] addrspace(3)* @array, i64 0, i64 %1, i64 %7<br>
+  %9 = addrspacecast float addrspace(3)* %8 to float*<br>
+  %10 = load float* %9, align 4<br>
+  %11 = fadd float %5, %10<br>
+  %12 = add i32 %x, 1<br>
+  %13 = zext i32 %12 to i64<br>
+  %14 = getelementptr inbounds [32 x [32 x float]] addrspace(3)* @array, i64 0, i64 %13, i64 %0<br>
+  %15 = addrspacecast float addrspace(3)* %14 to float*<br>
+  %16 = load float* %15, align 4<br>
+  %17 = fadd float %11, %16<br>
+  %18 = getelementptr inbounds [32 x [32 x float]] addrspace(3)* @array, i64 0, i64 %13, i64 %7<br>
+  %19 = addrspacecast float addrspace(3)* %18 to float*<br>
+  %20 = load float* %19, align 4<br>
+  %21 = fadd float %17, %20<br>
+  store float %21, float* %output, align 4<br>
+  ret void<br>
+}<br>
+<br>
+; PTX-LABEL: sum_of_array(<br>
+; PTX: ld.shared.f32 {{%f[0-9]+}}, {{\[}}[[BASE_REG:%(rl|r)[0-9]+]]{{\]}}<br>
+; PTX: ld.shared.f32 {{%f[0-9]+}}, {{\[}}[[BASE_REG]]+4{{\]}}<br>
+; PTX: ld.shared.f32 {{%f[0-9]+}}, {{\[}}[[BASE_REG]]+128{{\]}}<br>
+; PTX: ld.shared.f32 {{%f[0-9]+}}, {{\[}}[[BASE_REG]]+132{{\]}}<br>
+<br>
+; IR-LABEL: @sum_of_array(<br>
+; IR: [[BASE_PTR:%[0-9]+]] = getelementptr inbounds [32 x [32 x float]] addrspace(3)* @array, i64 0, i32 %x, i32 %y<br>
+; IR: [[BASE_INT:%[0-9]+]] = ptrtoint float addrspace(3)* [[BASE_PTR]] to i64<br>
+; IR: %5 = add i64 [[BASE_INT]], 4<br>
+; IR: %10 = add i64 [[BASE_INT]], 128<br>
+; IR: %15 = add i64 [[BASE_INT]], 132<br>
<br>
Added: llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep.ll<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep.ll?rev=207783&view=auto" target="_blank">http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep.ll?rev=207783&view=auto</a><br>


==============================================================================<br>
--- llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep.ll (added)<br>
+++ llvm/trunk/test/Transforms/SeparateConstOffsetFromGEP/NVPTX/split-gep.ll Thu May  1 13:38:36 2014<br>
@@ -0,0 +1,101 @@<br>
+; RUN: opt < %s -separate-const-offset-from-gep -dce -S | FileCheck %s<br>
+<br>
+; Several unit tests for -separate-const-offset-from-gep. The transformation<br>
+; heavily relies on TargetTransformInfo, so we put these tests under<br>
+; target-specific folders.<br>
+<br>
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
+; target triple is necessary; otherwise TargetTransformInfo rejects any<br>
+; addressing mode.<br>
+target triple = "nvptx64-unknown-unknown"<br>
+<br>
+%struct.S = type { float, double }<br>
+<br>
+@struct_array = global [1024 x %struct.S] zeroinitializer, align 16<br>
+@float_2d_array = global [32 x [32 x float]] zeroinitializer, align 4<br>
+<br>
+; We should not extract any struct field indices, because fields in a struct<br>
+; may have different types.<br>
+define double* @struct(i32 %i) {<br>
+entry:<br>
+  %add = add nsw i32 %i, 5<br>
+  %idxprom = sext i32 %add to i64<br>
+  %p = getelementptr inbounds [1024 x %struct.S]* @struct_array, i64 0, i64 %idxprom, i32 1<br>
+  ret double* %p<br>
+}<br>
+; CHECK-LABEL: @struct<br>
+; CHECK: getelementptr [1024 x %struct.S]* @struct_array, i64 0, i32 %i, i32 1<br>
+<br>
+; We should be able to trace into sext/zext if it's directly used as a GEP<br>
+; index.<br>
+define float* @sext_zext(i32 %i, i32 %j) {<br>
+entry:<br>
+  %i1 = add i32 %i, 1<br>
+  %j2 = add i32 %j, 2<br>
+  %i1.ext = sext i32 %i1 to i64<br>
+  %j2.ext = zext i32 %j2 to i64<br>
+  %p = getelementptr inbounds [32 x [32 x float]]* @float_2d_array, i64 0, i64 %i1.ext, i64 %j2.ext<br>
+  ret float* %p<br>
+}<br>
+; CHECK-LABEL: @sext_zext<br>
+; CHECK: getelementptr [32 x [32 x float]]* @float_2d_array, i64 0, i32 %i, i32 %j<br>
+; CHECK: add i64 %{{[0-9]+}}, 136<br>
+<br>
+; We should be able to trace into sext/zext if it can be distributed to both<br>
+; operands, e.g., sext (add nsw a, b) == add nsw (sext a), (sext b)<br>
+define float* @ext_add_no_overflow(i64 %a, i32 %b, i64 %c, i32 %d) {<br>
+  %b1 = add nsw i32 %b, 1<br>
+  %b2 = sext i32 %b1 to i64<br>
+  %i = add i64 %a, %b2<br>
+  %d1 = add nuw i32 %d, 1<br>
+  %d2 = zext i32 %d1 to i64<br>
+  %j = add i64 %c, %d2<br>
+  %p = getelementptr inbounds [32 x [32 x float]]* @float_2d_array, i64 0, i64 %i, i64 %j<br>
+  ret float* %p<br>
+}<br>
+; CHECK-LABEL: @ext_add_no_overflow<br>
+; CHECK: [[BASE_PTR:%[0-9]+]] = getelementptr [32 x [32 x float]]* @float_2d_array, i64 0, i64 %{{[0-9]+}}, i64 %{{[0-9]+}}<br>
+; CHECK: [[BASE_INT:%[0-9]+]] = ptrtoint float* [[BASE_PTR]] to i64<br>
+; CHECK: add i64 [[BASE_INT]], 132<br>
+<br>
+; We should treat "or" with no common bits (%k) as "add", and leave "or" with<br>
+; potentially common bits (%l) as is.<br>
+define float* @or(i64 %i) {<br>
+entry:<br>
+  %j = shl i64 %i, 2<br>
+  %k = or i64 %j, 3 ; no common bits<br>
+  %l = or i64 %j, 4 ; potentially common bits<br>
+  %p = getelementptr inbounds [32 x [32 x float]]* @float_2d_array, i64 0, i64 %k, i64 %l<br>
+  ret float* %p<br>
+}<br>
+; CHECK-LABEL: @or<br>
+; CHECK: getelementptr [32 x [32 x float]]* @float_2d_array, i64 0, i64 %j, i64 %l<br>
+; CHECK: add i64 %{{[0-9]+}}, 384<br>
+<br>
+; The subexpression (b + 5) is used in both "i = a + (b + 5)" and "*out = b +<br>
+; 5". When extracting the constant offset 5, make sure "*out = b + 5" isn't<br>
+; affected.<br>
+define float* @expr(i64 %a, i64 %b, i64* %out) {<br>
+entry:<br>
+  %b5 = add i64 %b, 5<br>
+  %i = add i64 %b5, %a<br>
+  %p = getelementptr inbounds [32 x [32 x float]]* @float_2d_array, i64 0, i64 %i, i64 0<br>
+  store i64 %b5, i64* %out<br>
+  ret float* %p<br>
+}<br>
+; CHECK-LABEL: @expr<br>
+; CHECK: getelementptr [32 x [32 x float]]* @float_2d_array, i64 0, i64 %0, i64 0<br>
+; CHECK: add i64 %{{[0-9]+}}, 640<br>
+; CHECK: store i64 %b5, i64* %out<br>
+<br>
+; Verifies we handle "sub" correctly.<br>
+define float* @sub(i64 %i, i64 %j) {<br>
+  %i2 = sub i64 %i, 5 ; i - 5<br>
+  %j2 = sub i64 5, %j ; 5 - i<br>
+  %p = getelementptr inbounds [32 x [32 x float]]* @float_2d_array, i64 0, i64 %i2, i64 %j2<br>
+  ret float* %p<br>
+}<br>
+; CHECK-LABEL: @sub<br>
+; CHECK: %[[j2:[0-9]+]] = sub i64 0, %j<br>
+; CHECK: getelementptr [32 x [32 x float]]* @float_2d_array, i64 0, i64 %i, i64 %[[j2]]<br>
+; CHECK: add i64 %{{[0-9]+}}, -620<br>
<br>
<br>
_______________________________________________<br>
llvm-commits mailing list<br>
<a href="mailto:llvm-commits@cs.uiuc.edu">llvm-commits@cs.uiuc.edu</a><br>
<a href="http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits" target="_blank">http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits</a><br>
</blockquote></div><br></div>