1249259Sdim//===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
2249259Sdim//
3249259Sdim//                     The LLVM Compiler Infrastructure
4249259Sdim//
5249259Sdim// This file is distributed under the University of Illinois Open Source
6249259Sdim// License. See LICENSE.TXT for details.
7249259Sdim//
8249259Sdim//===----------------------------------------------------------------------===//
9249259Sdim//
10249259Sdim// This file implements folding of constants for LLVM.  This implements the
11249259Sdim// (internal) ConstantFold.h interface, which is used by the
12249259Sdim// ConstantExpr::get* methods to automatically fold constants when possible.
13249259Sdim//
14249259Sdim// The current constant folding implementation is implemented in two pieces: the
15249259Sdim// pieces that don't need DataLayout, and the pieces that do. This is to avoid
16249259Sdim// a dependence in IR on Target.
17249259Sdim//
18249259Sdim//===----------------------------------------------------------------------===//
19249259Sdim
20249259Sdim#include "ConstantFold.h"
21249259Sdim#include "llvm/ADT/SmallVector.h"
22249259Sdim#include "llvm/IR/Constants.h"
23249259Sdim#include "llvm/IR/DerivedTypes.h"
24249259Sdim#include "llvm/IR/Function.h"
25249259Sdim#include "llvm/IR/GlobalAlias.h"
26249259Sdim#include "llvm/IR/GlobalVariable.h"
27249259Sdim#include "llvm/IR/Instructions.h"
28249259Sdim#include "llvm/IR/Operator.h"
29249259Sdim#include "llvm/Support/Compiler.h"
30249259Sdim#include "llvm/Support/ErrorHandling.h"
31249259Sdim#include "llvm/Support/GetElementPtrTypeIterator.h"
32249259Sdim#include "llvm/Support/ManagedStatic.h"
33249259Sdim#include "llvm/Support/MathExtras.h"
34249259Sdim#include <limits>
35249259Sdimusing namespace llvm;
36249259Sdim
37249259Sdim//===----------------------------------------------------------------------===//
38249259Sdim//                ConstantFold*Instruction Implementations
39249259Sdim//===----------------------------------------------------------------------===//
40249259Sdim
41249259Sdim/// BitCastConstantVector - Convert the specified vector Constant node to the
42249259Sdim/// specified vector type.  At this point, we know that the elements of the
43249259Sdim/// input vector constant are all simple integer or FP values.
44249259Sdimstatic Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
45249259Sdim
46249259Sdim  if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
47249259Sdim  if (CV->isNullValue()) return Constant::getNullValue(DstTy);
48249259Sdim
49249259Sdim  // If this cast changes element count then we can't handle it here:
50249259Sdim  // doing so requires endianness information.  This should be handled by
51249259Sdim  // Analysis/ConstantFolding.cpp
52249259Sdim  unsigned NumElts = DstTy->getNumElements();
53249259Sdim  if (NumElts != CV->getType()->getVectorNumElements())
54249259Sdim    return 0;
55249259Sdim
56249259Sdim  Type *DstEltTy = DstTy->getElementType();
57249259Sdim
58249259Sdim  SmallVector<Constant*, 16> Result;
59249259Sdim  Type *Ty = IntegerType::get(CV->getContext(), 32);
60249259Sdim  for (unsigned i = 0; i != NumElts; ++i) {
61249259Sdim    Constant *C =
62249259Sdim      ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
63249259Sdim    C = ConstantExpr::getBitCast(C, DstEltTy);
64249259Sdim    Result.push_back(C);
65249259Sdim  }
66249259Sdim
67249259Sdim  return ConstantVector::get(Result);
68249259Sdim}
69249259Sdim
70249259Sdim/// This function determines which opcode to use to fold two constant cast
71249259Sdim/// expressions together. It uses CastInst::isEliminableCastPair to determine
72249259Sdim/// the opcode. Consequently its just a wrapper around that function.
73249259Sdim/// @brief Determine if it is valid to fold a cast of a cast
74249259Sdimstatic unsigned
75249259SdimfoldConstantCastPair(
76249259Sdim  unsigned opc,          ///< opcode of the second cast constant expression
77249259Sdim  ConstantExpr *Op,      ///< the first cast constant expression
78249259Sdim  Type *DstTy      ///< desintation type of the first cast
79249259Sdim) {
80249259Sdim  assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
81249259Sdim  assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
82249259Sdim  assert(CastInst::isCast(opc) && "Invalid cast opcode");
83249259Sdim
84249259Sdim  // The the types and opcodes for the two Cast constant expressions
85249259Sdim  Type *SrcTy = Op->getOperand(0)->getType();
86249259Sdim  Type *MidTy = Op->getType();
87249259Sdim  Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
88249259Sdim  Instruction::CastOps secondOp = Instruction::CastOps(opc);
89249259Sdim
90249259Sdim  // Assume that pointers are never more than 64 bits wide.
91249259Sdim  IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
92249259Sdim
93249259Sdim  // Let CastInst::isEliminableCastPair do the heavy lifting.
94249259Sdim  return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
95249259Sdim                                        FakeIntPtrTy, FakeIntPtrTy,
96249259Sdim                                        FakeIntPtrTy);
97249259Sdim}
98249259Sdim
99249259Sdimstatic Constant *FoldBitCast(Constant *V, Type *DestTy) {
100249259Sdim  Type *SrcTy = V->getType();
101249259Sdim  if (SrcTy == DestTy)
102249259Sdim    return V; // no-op cast
103249259Sdim
104249259Sdim  // Check to see if we are casting a pointer to an aggregate to a pointer to
105249259Sdim  // the first element.  If so, return the appropriate GEP instruction.
106249259Sdim  if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
107249259Sdim    if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
108249259Sdim      if (PTy->getAddressSpace() == DPTy->getAddressSpace()
109249259Sdim          && DPTy->getElementType()->isSized()) {
110249259Sdim        SmallVector<Value*, 8> IdxList;
111249259Sdim        Value *Zero =
112249259Sdim          Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
113249259Sdim        IdxList.push_back(Zero);
114249259Sdim        Type *ElTy = PTy->getElementType();
115249259Sdim        while (ElTy != DPTy->getElementType()) {
116249259Sdim          if (StructType *STy = dyn_cast<StructType>(ElTy)) {
117249259Sdim            if (STy->getNumElements() == 0) break;
118249259Sdim            ElTy = STy->getElementType(0);
119249259Sdim            IdxList.push_back(Zero);
120249259Sdim          } else if (SequentialType *STy =
121249259Sdim                     dyn_cast<SequentialType>(ElTy)) {
122249259Sdim            if (ElTy->isPointerTy()) break;  // Can't index into pointers!
123249259Sdim            ElTy = STy->getElementType();
124249259Sdim            IdxList.push_back(Zero);
125249259Sdim          } else {
126249259Sdim            break;
127249259Sdim          }
128249259Sdim        }
129249259Sdim
130249259Sdim        if (ElTy == DPTy->getElementType())
131249259Sdim          // This GEP is inbounds because all indices are zero.
132249259Sdim          return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
133249259Sdim      }
134249259Sdim
135249259Sdim  // Handle casts from one vector constant to another.  We know that the src
136249259Sdim  // and dest type have the same size (otherwise its an illegal cast).
137249259Sdim  if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
138249259Sdim    if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
139249259Sdim      assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
140249259Sdim             "Not cast between same sized vectors!");
141249259Sdim      SrcTy = NULL;
142249259Sdim      // First, check for null.  Undef is already handled.
143249259Sdim      if (isa<ConstantAggregateZero>(V))
144249259Sdim        return Constant::getNullValue(DestTy);
145249259Sdim
146249259Sdim      // Handle ConstantVector and ConstantAggregateVector.
147249259Sdim      return BitCastConstantVector(V, DestPTy);
148249259Sdim    }
149249259Sdim
150249259Sdim    // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
151249259Sdim    // This allows for other simplifications (although some of them
152249259Sdim    // can only be handled by Analysis/ConstantFolding.cpp).
153249259Sdim    if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
154249259Sdim      return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
155249259Sdim  }
156249259Sdim
157249259Sdim  // Finally, implement bitcast folding now.   The code below doesn't handle
158249259Sdim  // bitcast right.
159249259Sdim  if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
160249259Sdim    return ConstantPointerNull::get(cast<PointerType>(DestTy));
161249259Sdim
162249259Sdim  // Handle integral constant input.
163249259Sdim  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
164249259Sdim    if (DestTy->isIntegerTy())
165249259Sdim      // Integral -> Integral. This is a no-op because the bit widths must
166249259Sdim      // be the same. Consequently, we just fold to V.
167249259Sdim      return V;
168249259Sdim
169249259Sdim    if (DestTy->isFloatingPointTy())
170249259Sdim      return ConstantFP::get(DestTy->getContext(),
171249259Sdim                             APFloat(DestTy->getFltSemantics(),
172249259Sdim                                     CI->getValue()));
173249259Sdim
174249259Sdim    // Otherwise, can't fold this (vector?)
175249259Sdim    return 0;
176249259Sdim  }
177249259Sdim
178249259Sdim  // Handle ConstantFP input: FP -> Integral.
179249259Sdim  if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
180249259Sdim    return ConstantInt::get(FP->getContext(),
181249259Sdim                            FP->getValueAPF().bitcastToAPInt());
182249259Sdim
183249259Sdim  return 0;
184249259Sdim}
185249259Sdim
186249259Sdim
187249259Sdim/// ExtractConstantBytes - V is an integer constant which only has a subset of
188249259Sdim/// its bytes used.  The bytes used are indicated by ByteStart (which is the
189249259Sdim/// first byte used, counting from the least significant byte) and ByteSize,
190249259Sdim/// which is the number of bytes used.
191249259Sdim///
192249259Sdim/// This function analyzes the specified constant to see if the specified byte
193249259Sdim/// range can be returned as a simplified constant.  If so, the constant is
194249259Sdim/// returned, otherwise null is returned.
195249259Sdim///
196249259Sdimstatic Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
197249259Sdim                                      unsigned ByteSize) {
198249259Sdim  assert(C->getType()->isIntegerTy() &&
199249259Sdim         (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
200249259Sdim         "Non-byte sized integer input");
201249259Sdim  unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
202249259Sdim  assert(ByteSize && "Must be accessing some piece");
203249259Sdim  assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
204249259Sdim  assert(ByteSize != CSize && "Should not extract everything");
205249259Sdim
206249259Sdim  // Constant Integers are simple.
207249259Sdim  if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
208249259Sdim    APInt V = CI->getValue();
209249259Sdim    if (ByteStart)
210249259Sdim      V = V.lshr(ByteStart*8);
211249259Sdim    V = V.trunc(ByteSize*8);
212249259Sdim    return ConstantInt::get(CI->getContext(), V);
213249259Sdim  }
214249259Sdim
215249259Sdim  // In the input is a constant expr, we might be able to recursively simplify.
216249259Sdim  // If not, we definitely can't do anything.
217249259Sdim  ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
218249259Sdim  if (CE == 0) return 0;
219249259Sdim
220249259Sdim  switch (CE->getOpcode()) {
221249259Sdim  default: return 0;
222249259Sdim  case Instruction::Or: {
223249259Sdim    Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
224249259Sdim    if (RHS == 0)
225249259Sdim      return 0;
226249259Sdim
227249259Sdim    // X | -1 -> -1.
228249259Sdim    if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
229249259Sdim      if (RHSC->isAllOnesValue())
230249259Sdim        return RHSC;
231249259Sdim
232249259Sdim    Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
233249259Sdim    if (LHS == 0)
234249259Sdim      return 0;
235249259Sdim    return ConstantExpr::getOr(LHS, RHS);
236249259Sdim  }
237249259Sdim  case Instruction::And: {
238249259Sdim    Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
239249259Sdim    if (RHS == 0)
240249259Sdim      return 0;
241249259Sdim
242249259Sdim    // X & 0 -> 0.
243249259Sdim    if (RHS->isNullValue())
244249259Sdim      return RHS;
245249259Sdim
246249259Sdim    Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
247249259Sdim    if (LHS == 0)
248249259Sdim      return 0;
249249259Sdim    return ConstantExpr::getAnd(LHS, RHS);
250249259Sdim  }
251249259Sdim  case Instruction::LShr: {
252249259Sdim    ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
253249259Sdim    if (Amt == 0)
254249259Sdim      return 0;
255249259Sdim    unsigned ShAmt = Amt->getZExtValue();
256249259Sdim    // Cannot analyze non-byte shifts.
257249259Sdim    if ((ShAmt & 7) != 0)
258249259Sdim      return 0;
259249259Sdim    ShAmt >>= 3;
260249259Sdim
261249259Sdim    // If the extract is known to be all zeros, return zero.
262249259Sdim    if (ByteStart >= CSize-ShAmt)
263249259Sdim      return Constant::getNullValue(IntegerType::get(CE->getContext(),
264249259Sdim                                                     ByteSize*8));
265249259Sdim    // If the extract is known to be fully in the input, extract it.
266249259Sdim    if (ByteStart+ByteSize+ShAmt <= CSize)
267249259Sdim      return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
268249259Sdim
269249259Sdim    // TODO: Handle the 'partially zero' case.
270249259Sdim    return 0;
271249259Sdim  }
272249259Sdim
273249259Sdim  case Instruction::Shl: {
274249259Sdim    ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
275249259Sdim    if (Amt == 0)
276249259Sdim      return 0;
277249259Sdim    unsigned ShAmt = Amt->getZExtValue();
278249259Sdim    // Cannot analyze non-byte shifts.
279249259Sdim    if ((ShAmt & 7) != 0)
280249259Sdim      return 0;
281249259Sdim    ShAmt >>= 3;
282249259Sdim
283249259Sdim    // If the extract is known to be all zeros, return zero.
284249259Sdim    if (ByteStart+ByteSize <= ShAmt)
285249259Sdim      return Constant::getNullValue(IntegerType::get(CE->getContext(),
286249259Sdim                                                     ByteSize*8));
287249259Sdim    // If the extract is known to be fully in the input, extract it.
288249259Sdim    if (ByteStart >= ShAmt)
289249259Sdim      return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
290249259Sdim
291249259Sdim    // TODO: Handle the 'partially zero' case.
292249259Sdim    return 0;
293249259Sdim  }
294249259Sdim
295249259Sdim  case Instruction::ZExt: {
296249259Sdim    unsigned SrcBitSize =
297249259Sdim      cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
298249259Sdim
299249259Sdim    // If extracting something that is completely zero, return 0.
300249259Sdim    if (ByteStart*8 >= SrcBitSize)
301249259Sdim      return Constant::getNullValue(IntegerType::get(CE->getContext(),
302249259Sdim                                                     ByteSize*8));
303249259Sdim
304249259Sdim    // If exactly extracting the input, return it.
305249259Sdim    if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
306249259Sdim      return CE->getOperand(0);
307249259Sdim
308249259Sdim    // If extracting something completely in the input, if if the input is a
309249259Sdim    // multiple of 8 bits, recurse.
310249259Sdim    if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
311249259Sdim      return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
312249259Sdim
313249259Sdim    // Otherwise, if extracting a subset of the input, which is not multiple of
314249259Sdim    // 8 bits, do a shift and trunc to get the bits.
315249259Sdim    if ((ByteStart+ByteSize)*8 < SrcBitSize) {
316249259Sdim      assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
317249259Sdim      Constant *Res = CE->getOperand(0);
318249259Sdim      if (ByteStart)
319249259Sdim        Res = ConstantExpr::getLShr(Res,
320249259Sdim                                 ConstantInt::get(Res->getType(), ByteStart*8));
321249259Sdim      return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
322249259Sdim                                                          ByteSize*8));
323249259Sdim    }
324249259Sdim
325249259Sdim    // TODO: Handle the 'partially zero' case.
326249259Sdim    return 0;
327249259Sdim  }
328249259Sdim  }
329249259Sdim}
330249259Sdim
331249259Sdim/// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
332249259Sdim/// on Ty, with any known factors factored out. If Folded is false,
333249259Sdim/// return null if no factoring was possible, to avoid endlessly
334249259Sdim/// bouncing an unfoldable expression back into the top-level folder.
335249259Sdim///
336249259Sdimstatic Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
337249259Sdim                                 bool Folded) {
338249259Sdim  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
339249259Sdim    Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
340249259Sdim    Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
341249259Sdim    return ConstantExpr::getNUWMul(E, N);
342249259Sdim  }
343249259Sdim
344249259Sdim  if (StructType *STy = dyn_cast<StructType>(Ty))
345249259Sdim    if (!STy->isPacked()) {
346249259Sdim      unsigned NumElems = STy->getNumElements();
347249259Sdim      // An empty struct has size zero.
348249259Sdim      if (NumElems == 0)
349249259Sdim        return ConstantExpr::getNullValue(DestTy);
350249259Sdim      // Check for a struct with all members having the same size.
351249259Sdim      Constant *MemberSize =
352249259Sdim        getFoldedSizeOf(STy->getElementType(0), DestTy, true);
353249259Sdim      bool AllSame = true;
354249259Sdim      for (unsigned i = 1; i != NumElems; ++i)
355249259Sdim        if (MemberSize !=
356249259Sdim            getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
357249259Sdim          AllSame = false;
358249259Sdim          break;
359249259Sdim        }
360249259Sdim      if (AllSame) {
361249259Sdim        Constant *N = ConstantInt::get(DestTy, NumElems);
362249259Sdim        return ConstantExpr::getNUWMul(MemberSize, N);
363249259Sdim      }
364249259Sdim    }
365249259Sdim
366249259Sdim  // Pointer size doesn't depend on the pointee type, so canonicalize them
367249259Sdim  // to an arbitrary pointee.
368249259Sdim  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
369249259Sdim    if (!PTy->getElementType()->isIntegerTy(1))
370249259Sdim      return
371249259Sdim        getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
372249259Sdim                                         PTy->getAddressSpace()),
373249259Sdim                        DestTy, true);
374249259Sdim
375249259Sdim  // If there's no interesting folding happening, bail so that we don't create
376249259Sdim  // a constant that looks like it needs folding but really doesn't.
377249259Sdim  if (!Folded)
378249259Sdim    return 0;
379249259Sdim
380249259Sdim  // Base case: Get a regular sizeof expression.
381249259Sdim  Constant *C = ConstantExpr::getSizeOf(Ty);
382249259Sdim  C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
383249259Sdim                                                    DestTy, false),
384249259Sdim                            C, DestTy);
385249259Sdim  return C;
386249259Sdim}
387249259Sdim
388249259Sdim/// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
389249259Sdim/// on Ty, with any known factors factored out. If Folded is false,
390249259Sdim/// return null if no factoring was possible, to avoid endlessly
391249259Sdim/// bouncing an unfoldable expression back into the top-level folder.
392249259Sdim///
393249259Sdimstatic Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
394249259Sdim                                  bool Folded) {
395249259Sdim  // The alignment of an array is equal to the alignment of the
396249259Sdim  // array element. Note that this is not always true for vectors.
397249259Sdim  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
398249259Sdim    Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
399249259Sdim    C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
400249259Sdim                                                      DestTy,
401249259Sdim                                                      false),
402249259Sdim                              C, DestTy);
403249259Sdim    return C;
404249259Sdim  }
405249259Sdim
406249259Sdim  if (StructType *STy = dyn_cast<StructType>(Ty)) {
407249259Sdim    // Packed structs always have an alignment of 1.
408249259Sdim    if (STy->isPacked())
409249259Sdim      return ConstantInt::get(DestTy, 1);
410249259Sdim
411249259Sdim    // Otherwise, struct alignment is the maximum alignment of any member.
412249259Sdim    // Without target data, we can't compare much, but we can check to see
413249259Sdim    // if all the members have the same alignment.
414249259Sdim    unsigned NumElems = STy->getNumElements();
415249259Sdim    // An empty struct has minimal alignment.
416249259Sdim    if (NumElems == 0)
417249259Sdim      return ConstantInt::get(DestTy, 1);
418249259Sdim    // Check for a struct with all members having the same alignment.
419249259Sdim    Constant *MemberAlign =
420249259Sdim      getFoldedAlignOf(STy->getElementType(0), DestTy, true);
421249259Sdim    bool AllSame = true;
422249259Sdim    for (unsigned i = 1; i != NumElems; ++i)
423249259Sdim      if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
424249259Sdim        AllSame = false;
425249259Sdim        break;
426249259Sdim      }
427249259Sdim    if (AllSame)
428249259Sdim      return MemberAlign;
429249259Sdim  }
430249259Sdim
431249259Sdim  // Pointer alignment doesn't depend on the pointee type, so canonicalize them
432249259Sdim  // to an arbitrary pointee.
433249259Sdim  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
434249259Sdim    if (!PTy->getElementType()->isIntegerTy(1))
435249259Sdim      return
436249259Sdim        getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
437249259Sdim                                                           1),
438249259Sdim                                          PTy->getAddressSpace()),
439249259Sdim                         DestTy, true);
440249259Sdim
441249259Sdim  // If there's no interesting folding happening, bail so that we don't create
442249259Sdim  // a constant that looks like it needs folding but really doesn't.
443249259Sdim  if (!Folded)
444249259Sdim    return 0;
445249259Sdim
446249259Sdim  // Base case: Get a regular alignof expression.
447249259Sdim  Constant *C = ConstantExpr::getAlignOf(Ty);
448249259Sdim  C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
449249259Sdim                                                    DestTy, false),
450249259Sdim                            C, DestTy);
451249259Sdim  return C;
452249259Sdim}
453249259Sdim
454249259Sdim/// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
455249259Sdim/// on Ty and FieldNo, with any known factors factored out. If Folded is false,
456249259Sdim/// return null if no factoring was possible, to avoid endlessly
457249259Sdim/// bouncing an unfoldable expression back into the top-level folder.
458249259Sdim///
459249259Sdimstatic Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
460249259Sdim                                   Type *DestTy,
461249259Sdim                                   bool Folded) {
462249259Sdim  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
463249259Sdim    Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
464249259Sdim                                                                DestTy, false),
465249259Sdim                                        FieldNo, DestTy);
466249259Sdim    Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
467249259Sdim    return ConstantExpr::getNUWMul(E, N);
468249259Sdim  }
469249259Sdim
470249259Sdim  if (StructType *STy = dyn_cast<StructType>(Ty))
471249259Sdim    if (!STy->isPacked()) {
472249259Sdim      unsigned NumElems = STy->getNumElements();
473249259Sdim      // An empty struct has no members.
474249259Sdim      if (NumElems == 0)
475249259Sdim        return 0;
476249259Sdim      // Check for a struct with all members having the same size.
477249259Sdim      Constant *MemberSize =
478249259Sdim        getFoldedSizeOf(STy->getElementType(0), DestTy, true);
479249259Sdim      bool AllSame = true;
480249259Sdim      for (unsigned i = 1; i != NumElems; ++i)
481249259Sdim        if (MemberSize !=
482249259Sdim            getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
483249259Sdim          AllSame = false;
484249259Sdim          break;
485249259Sdim        }
486249259Sdim      if (AllSame) {
487249259Sdim        Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
488249259Sdim                                                                    false,
489249259Sdim                                                                    DestTy,
490249259Sdim                                                                    false),
491249259Sdim                                            FieldNo, DestTy);
492249259Sdim        return ConstantExpr::getNUWMul(MemberSize, N);
493249259Sdim      }
494249259Sdim    }
495249259Sdim
496249259Sdim  // If there's no interesting folding happening, bail so that we don't create
497249259Sdim  // a constant that looks like it needs folding but really doesn't.
498249259Sdim  if (!Folded)
499249259Sdim    return 0;
500249259Sdim
501249259Sdim  // Base case: Get a regular offsetof expression.
502249259Sdim  Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
503249259Sdim  C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
504249259Sdim                                                    DestTy, false),
505249259Sdim                            C, DestTy);
506249259Sdim  return C;
507249259Sdim}
508249259Sdim
509249259SdimConstant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
510249259Sdim                                            Type *DestTy) {
511249259Sdim  if (isa<UndefValue>(V)) {
512249259Sdim    // zext(undef) = 0, because the top bits will be zero.
513249259Sdim    // sext(undef) = 0, because the top bits will all be the same.
514249259Sdim    // [us]itofp(undef) = 0, because the result value is bounded.
515249259Sdim    if (opc == Instruction::ZExt || opc == Instruction::SExt ||
516249259Sdim        opc == Instruction::UIToFP || opc == Instruction::SIToFP)
517249259Sdim      return Constant::getNullValue(DestTy);
518249259Sdim    return UndefValue::get(DestTy);
519249259Sdim  }
520249259Sdim
521249259Sdim  if (V->isNullValue() && !DestTy->isX86_MMXTy())
522249259Sdim    return Constant::getNullValue(DestTy);
523249259Sdim
524249259Sdim  // If the cast operand is a constant expression, there's a few things we can
525249259Sdim  // do to try to simplify it.
526249259Sdim  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
527249259Sdim    if (CE->isCast()) {
528249259Sdim      // Try hard to fold cast of cast because they are often eliminable.
529249259Sdim      if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
530249259Sdim        return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
531249259Sdim    } else if (CE->getOpcode() == Instruction::GetElementPtr) {
532249259Sdim      // If all of the indexes in the GEP are null values, there is no pointer
533249259Sdim      // adjustment going on.  We might as well cast the source pointer.
534249259Sdim      bool isAllNull = true;
535249259Sdim      for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
536249259Sdim        if (!CE->getOperand(i)->isNullValue()) {
537249259Sdim          isAllNull = false;
538249259Sdim          break;
539249259Sdim        }
540249259Sdim      if (isAllNull)
541249259Sdim        // This is casting one pointer type to another, always BitCast
542249259Sdim        return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
543249259Sdim    }
544249259Sdim  }
545249259Sdim
546249259Sdim  // If the cast operand is a constant vector, perform the cast by
547249259Sdim  // operating on each element. In the cast of bitcasts, the element
548249259Sdim  // count may be mismatched; don't attempt to handle that here.
549249259Sdim  if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
550249259Sdim      DestTy->isVectorTy() &&
551249259Sdim      DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
552249259Sdim    SmallVector<Constant*, 16> res;
553249259Sdim    VectorType *DestVecTy = cast<VectorType>(DestTy);
554249259Sdim    Type *DstEltTy = DestVecTy->getElementType();
555249259Sdim    Type *Ty = IntegerType::get(V->getContext(), 32);
556249259Sdim    for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
557249259Sdim      Constant *C =
558249259Sdim        ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
559249259Sdim      res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
560249259Sdim    }
561249259Sdim    return ConstantVector::get(res);
562249259Sdim  }
563249259Sdim
564249259Sdim  // We actually have to do a cast now. Perform the cast according to the
565249259Sdim  // opcode specified.
566249259Sdim  switch (opc) {
567249259Sdim  default:
568249259Sdim    llvm_unreachable("Failed to cast constant expression");
569249259Sdim  case Instruction::FPTrunc:
570249259Sdim  case Instruction::FPExt:
571249259Sdim    if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
572249259Sdim      bool ignored;
573249259Sdim      APFloat Val = FPC->getValueAPF();
574249259Sdim      Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
575249259Sdim                  DestTy->isFloatTy() ? APFloat::IEEEsingle :
576249259Sdim                  DestTy->isDoubleTy() ? APFloat::IEEEdouble :
577249259Sdim                  DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
578249259Sdim                  DestTy->isFP128Ty() ? APFloat::IEEEquad :
579249259Sdim                  DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
580249259Sdim                  APFloat::Bogus,
581249259Sdim                  APFloat::rmNearestTiesToEven, &ignored);
582249259Sdim      return ConstantFP::get(V->getContext(), Val);
583249259Sdim    }
584249259Sdim    return 0; // Can't fold.
585249259Sdim  case Instruction::FPToUI:
586249259Sdim  case Instruction::FPToSI:
587249259Sdim    if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
588249259Sdim      const APFloat &V = FPC->getValueAPF();
589249259Sdim      bool ignored;
590249259Sdim      uint64_t x[2];
591249259Sdim      uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
592249259Sdim      (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
593249259Sdim                                APFloat::rmTowardZero, &ignored);
594249259Sdim      APInt Val(DestBitWidth, x);
595249259Sdim      return ConstantInt::get(FPC->getContext(), Val);
596249259Sdim    }
597249259Sdim    return 0; // Can't fold.
598249259Sdim  case Instruction::IntToPtr:   //always treated as unsigned
599249259Sdim    if (V->isNullValue())       // Is it an integral null value?
600249259Sdim      return ConstantPointerNull::get(cast<PointerType>(DestTy));
601249259Sdim    return 0;                   // Other pointer types cannot be casted
602249259Sdim  case Instruction::PtrToInt:   // always treated as unsigned
603249259Sdim    // Is it a null pointer value?
604249259Sdim    if (V->isNullValue())
605249259Sdim      return ConstantInt::get(DestTy, 0);
606249259Sdim    // If this is a sizeof-like expression, pull out multiplications by
607249259Sdim    // known factors to expose them to subsequent folding. If it's an
608249259Sdim    // alignof-like expression, factor out known factors.
609249259Sdim    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
610249259Sdim      if (CE->getOpcode() == Instruction::GetElementPtr &&
611249259Sdim          CE->getOperand(0)->isNullValue()) {
612249259Sdim        Type *Ty =
613249259Sdim          cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
614249259Sdim        if (CE->getNumOperands() == 2) {
615249259Sdim          // Handle a sizeof-like expression.
616249259Sdim          Constant *Idx = CE->getOperand(1);
617249259Sdim          bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
618249259Sdim          if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
619249259Sdim            Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
620249259Sdim                                                                DestTy, false),
621249259Sdim                                        Idx, DestTy);
622249259Sdim            return ConstantExpr::getMul(C, Idx);
623249259Sdim          }
624249259Sdim        } else if (CE->getNumOperands() == 3 &&
625249259Sdim                   CE->getOperand(1)->isNullValue()) {
626249259Sdim          // Handle an alignof-like expression.
627249259Sdim          if (StructType *STy = dyn_cast<StructType>(Ty))
628249259Sdim            if (!STy->isPacked()) {
629249259Sdim              ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
630249259Sdim              if (CI->isOne() &&
631249259Sdim                  STy->getNumElements() == 2 &&
632249259Sdim                  STy->getElementType(0)->isIntegerTy(1)) {
633249259Sdim                return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
634249259Sdim              }
635249259Sdim            }
636249259Sdim          // Handle an offsetof-like expression.
637249259Sdim          if (Ty->isStructTy() || Ty->isArrayTy()) {
638249259Sdim            if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
639249259Sdim                                                DestTy, false))
640249259Sdim              return C;
641249259Sdim          }
642249259Sdim        }
643249259Sdim      }
644249259Sdim    // Other pointer types cannot be casted
645249259Sdim    return 0;
646249259Sdim  case Instruction::UIToFP:
647249259Sdim  case Instruction::SIToFP:
648249259Sdim    if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
649249259Sdim      APInt api = CI->getValue();
650249259Sdim      APFloat apf(DestTy->getFltSemantics(),
651249259Sdim                  APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
652249259Sdim      (void)apf.convertFromAPInt(api,
653249259Sdim                                 opc==Instruction::SIToFP,
654249259Sdim                                 APFloat::rmNearestTiesToEven);
655249259Sdim      return ConstantFP::get(V->getContext(), apf);
656249259Sdim    }
657249259Sdim    return 0;
658249259Sdim  case Instruction::ZExt:
659249259Sdim    if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
660249259Sdim      uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
661249259Sdim      return ConstantInt::get(V->getContext(),
662249259Sdim                              CI->getValue().zext(BitWidth));
663249259Sdim    }
664249259Sdim    return 0;
665249259Sdim  case Instruction::SExt:
666249259Sdim    if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
667249259Sdim      uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
668249259Sdim      return ConstantInt::get(V->getContext(),
669249259Sdim                              CI->getValue().sext(BitWidth));
670249259Sdim    }
671249259Sdim    return 0;
672249259Sdim  case Instruction::Trunc: {
673249259Sdim    uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
674249259Sdim    if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
675249259Sdim      return ConstantInt::get(V->getContext(),
676249259Sdim                              CI->getValue().trunc(DestBitWidth));
677249259Sdim    }
678249259Sdim
679249259Sdim    // The input must be a constantexpr.  See if we can simplify this based on
680249259Sdim    // the bytes we are demanding.  Only do this if the source and dest are an
681249259Sdim    // even multiple of a byte.
682249259Sdim    if ((DestBitWidth & 7) == 0 &&
683249259Sdim        (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
684249259Sdim      if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
685249259Sdim        return Res;
686249259Sdim
687249259Sdim    return 0;
688249259Sdim  }
689249259Sdim  case Instruction::BitCast:
690249259Sdim    return FoldBitCast(V, DestTy);
691249259Sdim  }
692249259Sdim}
693249259Sdim
694249259SdimConstant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
695249259Sdim                                              Constant *V1, Constant *V2) {
696249259Sdim  // Check for i1 and vector true/false conditions.
697249259Sdim  if (Cond->isNullValue()) return V2;
698249259Sdim  if (Cond->isAllOnesValue()) return V1;
699249259Sdim
700249259Sdim  // If the condition is a vector constant, fold the result elementwise.
701249259Sdim  if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
702249259Sdim    SmallVector<Constant*, 16> Result;
703249259Sdim    Type *Ty = IntegerType::get(CondV->getContext(), 32);
704249259Sdim    for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
705249259Sdim      ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
706249259Sdim      if (Cond == 0) break;
707249259Sdim
708249259Sdim      Constant *V = Cond->isNullValue() ? V2 : V1;
709249259Sdim      Constant *Res = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
710249259Sdim      Result.push_back(Res);
711249259Sdim    }
712249259Sdim
713249259Sdim    // If we were able to build the vector, return it.
714249259Sdim    if (Result.size() == V1->getType()->getVectorNumElements())
715249259Sdim      return ConstantVector::get(Result);
716249259Sdim  }
717249259Sdim
718249259Sdim  if (isa<UndefValue>(Cond)) {
719249259Sdim    if (isa<UndefValue>(V1)) return V1;
720249259Sdim    return V2;
721249259Sdim  }
722249259Sdim  if (isa<UndefValue>(V1)) return V2;
723249259Sdim  if (isa<UndefValue>(V2)) return V1;
724249259Sdim  if (V1 == V2) return V1;
725249259Sdim
726249259Sdim  if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
727249259Sdim    if (TrueVal->getOpcode() == Instruction::Select)
728249259Sdim      if (TrueVal->getOperand(0) == Cond)
729249259Sdim        return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
730249259Sdim  }
731249259Sdim  if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
732249259Sdim    if (FalseVal->getOpcode() == Instruction::Select)
733249259Sdim      if (FalseVal->getOperand(0) == Cond)
734249259Sdim        return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
735249259Sdim  }
736249259Sdim
737249259Sdim  return 0;
738249259Sdim}
739249259Sdim
740249259SdimConstant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
741249259Sdim                                                      Constant *Idx) {
742249259Sdim  if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
743249259Sdim    return UndefValue::get(Val->getType()->getVectorElementType());
744249259Sdim  if (Val->isNullValue())  // ee(zero, x) -> zero
745249259Sdim    return Constant::getNullValue(Val->getType()->getVectorElementType());
746249259Sdim  // ee({w,x,y,z}, undef) -> undef
747249259Sdim  if (isa<UndefValue>(Idx))
748249259Sdim    return UndefValue::get(Val->getType()->getVectorElementType());
749249259Sdim
750249259Sdim  if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
751249259Sdim    uint64_t Index = CIdx->getZExtValue();
752249259Sdim    // ee({w,x,y,z}, wrong_value) -> undef
753249259Sdim    if (Index >= Val->getType()->getVectorNumElements())
754249259Sdim      return UndefValue::get(Val->getType()->getVectorElementType());
755249259Sdim    return Val->getAggregateElement(Index);
756249259Sdim  }
757249259Sdim  return 0;
758249259Sdim}
759249259Sdim
760249259SdimConstant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
761249259Sdim                                                     Constant *Elt,
762249259Sdim                                                     Constant *Idx) {
763249259Sdim  ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
764249259Sdim  if (!CIdx) return 0;
765249259Sdim  const APInt &IdxVal = CIdx->getValue();
766249259Sdim
767249259Sdim  SmallVector<Constant*, 16> Result;
768249259Sdim  Type *Ty = IntegerType::get(Val->getContext(), 32);
769249259Sdim  for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
770249259Sdim    if (i == IdxVal) {
771249259Sdim      Result.push_back(Elt);
772249259Sdim      continue;
773249259Sdim    }
774249259Sdim
775249259Sdim    Constant *C =
776249259Sdim      ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
777249259Sdim    Result.push_back(C);
778249259Sdim  }
779249259Sdim
780249259Sdim  return ConstantVector::get(Result);
781249259Sdim}
782249259Sdim
783249259SdimConstant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
784249259Sdim                                                     Constant *V2,
785249259Sdim                                                     Constant *Mask) {
786249259Sdim  unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
787249259Sdim  Type *EltTy = V1->getType()->getVectorElementType();
788249259Sdim
789249259Sdim  // Undefined shuffle mask -> undefined value.
790249259Sdim  if (isa<UndefValue>(Mask))
791249259Sdim    return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
792249259Sdim
793249259Sdim  // Don't break the bitcode reader hack.
794249259Sdim  if (isa<ConstantExpr>(Mask)) return 0;
795249259Sdim
796249259Sdim  unsigned SrcNumElts = V1->getType()->getVectorNumElements();
797249259Sdim
798249259Sdim  // Loop over the shuffle mask, evaluating each element.
799249259Sdim  SmallVector<Constant*, 32> Result;
800249259Sdim  for (unsigned i = 0; i != MaskNumElts; ++i) {
801249259Sdim    int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
802249259Sdim    if (Elt == -1) {
803249259Sdim      Result.push_back(UndefValue::get(EltTy));
804249259Sdim      continue;
805249259Sdim    }
806249259Sdim    Constant *InElt;
807249259Sdim    if (unsigned(Elt) >= SrcNumElts*2)
808249259Sdim      InElt = UndefValue::get(EltTy);
809249259Sdim    else if (unsigned(Elt) >= SrcNumElts) {
810249259Sdim      Type *Ty = IntegerType::get(V2->getContext(), 32);
811249259Sdim      InElt =
812249259Sdim        ConstantExpr::getExtractElement(V2,
813249259Sdim                                        ConstantInt::get(Ty, Elt - SrcNumElts));
814249259Sdim    } else {
815249259Sdim      Type *Ty = IntegerType::get(V1->getContext(), 32);
816249259Sdim      InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
817249259Sdim    }
818249259Sdim    Result.push_back(InElt);
819249259Sdim  }
820249259Sdim
821249259Sdim  return ConstantVector::get(Result);
822249259Sdim}
823249259Sdim
824249259SdimConstant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
825249259Sdim                                                    ArrayRef<unsigned> Idxs) {
826249259Sdim  // Base case: no indices, so return the entire value.
827249259Sdim  if (Idxs.empty())
828249259Sdim    return Agg;
829249259Sdim
830249259Sdim  if (Constant *C = Agg->getAggregateElement(Idxs[0]))
831249259Sdim    return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
832249259Sdim
833249259Sdim  return 0;
834249259Sdim}
835249259Sdim
836249259SdimConstant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
837249259Sdim                                                   Constant *Val,
838249259Sdim                                                   ArrayRef<unsigned> Idxs) {
839249259Sdim  // Base case: no indices, so replace the entire value.
840249259Sdim  if (Idxs.empty())
841249259Sdim    return Val;
842249259Sdim
843249259Sdim  unsigned NumElts;
844249259Sdim  if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
845249259Sdim    NumElts = ST->getNumElements();
846249259Sdim  else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
847249259Sdim    NumElts = AT->getNumElements();
848249259Sdim  else
849249259Sdim    NumElts = Agg->getType()->getVectorNumElements();
850249259Sdim
851249259Sdim  SmallVector<Constant*, 32> Result;
852249259Sdim  for (unsigned i = 0; i != NumElts; ++i) {
853249259Sdim    Constant *C = Agg->getAggregateElement(i);
854249259Sdim    if (C == 0) return 0;
855249259Sdim
856249259Sdim    if (Idxs[0] == i)
857249259Sdim      C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
858249259Sdim
859249259Sdim    Result.push_back(C);
860249259Sdim  }
861249259Sdim
862249259Sdim  if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
863249259Sdim    return ConstantStruct::get(ST, Result);
864249259Sdim  if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
865249259Sdim    return ConstantArray::get(AT, Result);
866249259Sdim  return ConstantVector::get(Result);
867249259Sdim}
868249259Sdim
869249259Sdim
870249259SdimConstant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
871249259Sdim                                              Constant *C1, Constant *C2) {
872249259Sdim  // Handle UndefValue up front.
873249259Sdim  if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
874249259Sdim    switch (Opcode) {
875249259Sdim    case Instruction::Xor:
876249259Sdim      if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
877249259Sdim        // Handle undef ^ undef -> 0 special case. This is a common
878249259Sdim        // idiom (misuse).
879249259Sdim        return Constant::getNullValue(C1->getType());
880249259Sdim      // Fallthrough
881249259Sdim    case Instruction::Add:
882249259Sdim    case Instruction::Sub:
883249259Sdim      return UndefValue::get(C1->getType());
884249259Sdim    case Instruction::And:
885249259Sdim      if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
886249259Sdim        return C1;
887249259Sdim      return Constant::getNullValue(C1->getType());   // undef & X -> 0
888249259Sdim    case Instruction::Mul: {
889249259Sdim      ConstantInt *CI;
890249259Sdim      // X * undef -> undef   if X is odd or undef
891249259Sdim      if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
892249259Sdim          ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
893249259Sdim          (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
894249259Sdim        return UndefValue::get(C1->getType());
895249259Sdim
896249259Sdim      // X * undef -> 0       otherwise
897249259Sdim      return Constant::getNullValue(C1->getType());
898249259Sdim    }
899249259Sdim    case Instruction::UDiv:
900249259Sdim    case Instruction::SDiv:
901249259Sdim      // undef / 1 -> undef
902249259Sdim      if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
903249259Sdim        if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
904249259Sdim          if (CI2->isOne())
905249259Sdim            return C1;
906249259Sdim      // FALL THROUGH
907249259Sdim    case Instruction::URem:
908249259Sdim    case Instruction::SRem:
909249259Sdim      if (!isa<UndefValue>(C2))                    // undef / X -> 0
910249259Sdim        return Constant::getNullValue(C1->getType());
911249259Sdim      return C2;                                   // X / undef -> undef
912249259Sdim    case Instruction::Or:                          // X | undef -> -1
913249259Sdim      if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
914249259Sdim        return C1;
915249259Sdim      return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
916249259Sdim    case Instruction::LShr:
917249259Sdim      if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
918249259Sdim        return C1;                                  // undef lshr undef -> undef
919249259Sdim      return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
920249259Sdim                                                    // undef lshr X -> 0
921249259Sdim    case Instruction::AShr:
922249259Sdim      if (!isa<UndefValue>(C2))                     // undef ashr X --> all ones
923249259Sdim        return Constant::getAllOnesValue(C1->getType());
924249259Sdim      else if (isa<UndefValue>(C1))
925249259Sdim        return C1;                                  // undef ashr undef -> undef
926249259Sdim      else
927249259Sdim        return C1;                                  // X ashr undef --> X
928249259Sdim    case Instruction::Shl:
929249259Sdim      if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
930249259Sdim        return C1;                                  // undef shl undef -> undef
931249259Sdim      // undef << X -> 0   or   X << undef -> 0
932249259Sdim      return Constant::getNullValue(C1->getType());
933249259Sdim    }
934249259Sdim  }
935249259Sdim
936249259Sdim  // Handle simplifications when the RHS is a constant int.
937249259Sdim  if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
938249259Sdim    switch (Opcode) {
939249259Sdim    case Instruction::Add:
940249259Sdim      if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
941249259Sdim      break;
942249259Sdim    case Instruction::Sub:
943249259Sdim      if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
944249259Sdim      break;
945249259Sdim    case Instruction::Mul:
946249259Sdim      if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
947249259Sdim      if (CI2->equalsInt(1))
948249259Sdim        return C1;                                              // X * 1 == X
949249259Sdim      break;
950249259Sdim    case Instruction::UDiv:
951249259Sdim    case Instruction::SDiv:
952249259Sdim      if (CI2->equalsInt(1))
953249259Sdim        return C1;                                            // X / 1 == X
954249259Sdim      if (CI2->equalsInt(0))
955249259Sdim        return UndefValue::get(CI2->getType());               // X / 0 == undef
956249259Sdim      break;
957249259Sdim    case Instruction::URem:
958249259Sdim    case Instruction::SRem:
959249259Sdim      if (CI2->equalsInt(1))
960249259Sdim        return Constant::getNullValue(CI2->getType());        // X % 1 == 0
961249259Sdim      if (CI2->equalsInt(0))
962249259Sdim        return UndefValue::get(CI2->getType());               // X % 0 == undef
963249259Sdim      break;
964249259Sdim    case Instruction::And:
965249259Sdim      if (CI2->isZero()) return C2;                           // X & 0 == 0
966249259Sdim      if (CI2->isAllOnesValue())
967249259Sdim        return C1;                                            // X & -1 == X
968249259Sdim
969249259Sdim      if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
970249259Sdim        // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
971249259Sdim        if (CE1->getOpcode() == Instruction::ZExt) {
972249259Sdim          unsigned DstWidth = CI2->getType()->getBitWidth();
973249259Sdim          unsigned SrcWidth =
974249259Sdim            CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
975249259Sdim          APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
976249259Sdim          if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
977249259Sdim            return C1;
978249259Sdim        }
979249259Sdim
980249259Sdim        // If and'ing the address of a global with a constant, fold it.
981249259Sdim        if (CE1->getOpcode() == Instruction::PtrToInt &&
982249259Sdim            isa<GlobalValue>(CE1->getOperand(0))) {
983249259Sdim          GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
984249259Sdim
985249259Sdim          // Functions are at least 4-byte aligned.
986249259Sdim          unsigned GVAlign = GV->getAlignment();
987249259Sdim          if (isa<Function>(GV))
988249259Sdim            GVAlign = std::max(GVAlign, 4U);
989249259Sdim
990249259Sdim          if (GVAlign > 1) {
991249259Sdim            unsigned DstWidth = CI2->getType()->getBitWidth();
992249259Sdim            unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
993249259Sdim            APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
994249259Sdim
995249259Sdim            // If checking bits we know are clear, return zero.
996249259Sdim            if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
997249259Sdim              return Constant::getNullValue(CI2->getType());
998249259Sdim          }
999249259Sdim        }
1000249259Sdim      }
1001249259Sdim      break;
1002249259Sdim    case Instruction::Or:
1003249259Sdim      if (CI2->equalsInt(0)) return C1;    // X | 0 == X
1004249259Sdim      if (CI2->isAllOnesValue())
1005249259Sdim        return C2;                         // X | -1 == -1
1006249259Sdim      break;
1007249259Sdim    case Instruction::Xor:
1008249259Sdim      if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
1009249259Sdim
1010249259Sdim      if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1011249259Sdim        switch (CE1->getOpcode()) {
1012249259Sdim        default: break;
1013249259Sdim        case Instruction::ICmp:
1014249259Sdim        case Instruction::FCmp:
1015249259Sdim          // cmp pred ^ true -> cmp !pred
1016249259Sdim          assert(CI2->equalsInt(1));
1017249259Sdim          CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1018249259Sdim          pred = CmpInst::getInversePredicate(pred);
1019249259Sdim          return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1020249259Sdim                                          CE1->getOperand(1));
1021249259Sdim        }
1022249259Sdim      }
1023249259Sdim      break;
1024249259Sdim    case Instruction::AShr:
1025249259Sdim      // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1026249259Sdim      if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1027249259Sdim        if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1028249259Sdim          return ConstantExpr::getLShr(C1, C2);
1029249259Sdim      break;
1030249259Sdim    }
1031249259Sdim  } else if (isa<ConstantInt>(C1)) {
1032249259Sdim    // If C1 is a ConstantInt and C2 is not, swap the operands.
1033249259Sdim    if (Instruction::isCommutative(Opcode))
1034249259Sdim      return ConstantExpr::get(Opcode, C2, C1);
1035249259Sdim  }
1036249259Sdim
1037249259Sdim  // At this point we know neither constant is an UndefValue.
1038249259Sdim  if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1039249259Sdim    if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1040249259Sdim      const APInt &C1V = CI1->getValue();
1041249259Sdim      const APInt &C2V = CI2->getValue();
1042249259Sdim      switch (Opcode) {
1043249259Sdim      default:
1044249259Sdim        break;
1045249259Sdim      case Instruction::Add:
1046249259Sdim        return ConstantInt::get(CI1->getContext(), C1V + C2V);
1047249259Sdim      case Instruction::Sub:
1048249259Sdim        return ConstantInt::get(CI1->getContext(), C1V - C2V);
1049249259Sdim      case Instruction::Mul:
1050249259Sdim        return ConstantInt::get(CI1->getContext(), C1V * C2V);
1051249259Sdim      case Instruction::UDiv:
1052249259Sdim        assert(!CI2->isNullValue() && "Div by zero handled above");
1053249259Sdim        return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1054249259Sdim      case Instruction::SDiv:
1055249259Sdim        assert(!CI2->isNullValue() && "Div by zero handled above");
1056249259Sdim        if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1057249259Sdim          return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1058249259Sdim        return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1059249259Sdim      case Instruction::URem:
1060249259Sdim        assert(!CI2->isNullValue() && "Div by zero handled above");
1061249259Sdim        return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1062249259Sdim      case Instruction::SRem:
1063249259Sdim        assert(!CI2->isNullValue() && "Div by zero handled above");
1064249259Sdim        if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1065249259Sdim          return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1066249259Sdim        return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1067249259Sdim      case Instruction::And:
1068249259Sdim        return ConstantInt::get(CI1->getContext(), C1V & C2V);
1069249259Sdim      case Instruction::Or:
1070249259Sdim        return ConstantInt::get(CI1->getContext(), C1V | C2V);
1071249259Sdim      case Instruction::Xor:
1072249259Sdim        return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1073249259Sdim      case Instruction::Shl: {
1074249259Sdim        uint32_t shiftAmt = C2V.getZExtValue();
1075249259Sdim        if (shiftAmt < C1V.getBitWidth())
1076249259Sdim          return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1077249259Sdim        else
1078249259Sdim          return UndefValue::get(C1->getType()); // too big shift is undef
1079249259Sdim      }
1080249259Sdim      case Instruction::LShr: {
1081249259Sdim        uint32_t shiftAmt = C2V.getZExtValue();
1082249259Sdim        if (shiftAmt < C1V.getBitWidth())
1083249259Sdim          return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1084249259Sdim        else
1085249259Sdim          return UndefValue::get(C1->getType()); // too big shift is undef
1086249259Sdim      }
1087249259Sdim      case Instruction::AShr: {
1088249259Sdim        uint32_t shiftAmt = C2V.getZExtValue();
1089249259Sdim        if (shiftAmt < C1V.getBitWidth())
1090249259Sdim          return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1091249259Sdim        else
1092249259Sdim          return UndefValue::get(C1->getType()); // too big shift is undef
1093249259Sdim      }
1094249259Sdim      }
1095249259Sdim    }
1096249259Sdim
1097249259Sdim    switch (Opcode) {
1098249259Sdim    case Instruction::SDiv:
1099249259Sdim    case Instruction::UDiv:
1100249259Sdim    case Instruction::URem:
1101249259Sdim    case Instruction::SRem:
1102249259Sdim    case Instruction::LShr:
1103249259Sdim    case Instruction::AShr:
1104249259Sdim    case Instruction::Shl:
1105249259Sdim      if (CI1->equalsInt(0)) return C1;
1106249259Sdim      break;
1107249259Sdim    default:
1108249259Sdim      break;
1109249259Sdim    }
1110249259Sdim  } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1111249259Sdim    if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1112249259Sdim      APFloat C1V = CFP1->getValueAPF();
1113249259Sdim      APFloat C2V = CFP2->getValueAPF();
1114249259Sdim      APFloat C3V = C1V;  // copy for modification
1115249259Sdim      switch (Opcode) {
1116249259Sdim      default:
1117249259Sdim        break;
1118249259Sdim      case Instruction::FAdd:
1119249259Sdim        (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1120249259Sdim        return ConstantFP::get(C1->getContext(), C3V);
1121249259Sdim      case Instruction::FSub:
1122249259Sdim        (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1123249259Sdim        return ConstantFP::get(C1->getContext(), C3V);
1124249259Sdim      case Instruction::FMul:
1125249259Sdim        (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1126249259Sdim        return ConstantFP::get(C1->getContext(), C3V);
1127249259Sdim      case Instruction::FDiv:
1128249259Sdim        (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1129249259Sdim        return ConstantFP::get(C1->getContext(), C3V);
1130249259Sdim      case Instruction::FRem:
1131249259Sdim        (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1132249259Sdim        return ConstantFP::get(C1->getContext(), C3V);
1133249259Sdim      }
1134249259Sdim    }
1135249259Sdim  } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1136249259Sdim    // Perform elementwise folding.
1137249259Sdim    SmallVector<Constant*, 16> Result;
1138249259Sdim    Type *Ty = IntegerType::get(VTy->getContext(), 32);
1139249259Sdim    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1140249259Sdim      Constant *LHS =
1141249259Sdim        ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1142249259Sdim      Constant *RHS =
1143249259Sdim        ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1144249259Sdim
1145249259Sdim      Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1146249259Sdim    }
1147249259Sdim
1148249259Sdim    return ConstantVector::get(Result);
1149249259Sdim  }
1150249259Sdim
1151249259Sdim  if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1152249259Sdim    // There are many possible foldings we could do here.  We should probably
1153249259Sdim    // at least fold add of a pointer with an integer into the appropriate
1154249259Sdim    // getelementptr.  This will improve alias analysis a bit.
1155249259Sdim
1156249259Sdim    // Given ((a + b) + c), if (b + c) folds to something interesting, return
1157249259Sdim    // (a + (b + c)).
1158249259Sdim    if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1159249259Sdim      Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1160249259Sdim      if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1161249259Sdim        return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1162249259Sdim    }
1163249259Sdim  } else if (isa<ConstantExpr>(C2)) {
1164249259Sdim    // If C2 is a constant expr and C1 isn't, flop them around and fold the
1165249259Sdim    // other way if possible.
1166249259Sdim    if (Instruction::isCommutative(Opcode))
1167249259Sdim      return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1168249259Sdim  }
1169249259Sdim
1170249259Sdim  // i1 can be simplified in many cases.
1171249259Sdim  if (C1->getType()->isIntegerTy(1)) {
1172249259Sdim    switch (Opcode) {
1173249259Sdim    case Instruction::Add:
1174249259Sdim    case Instruction::Sub:
1175249259Sdim      return ConstantExpr::getXor(C1, C2);
1176249259Sdim    case Instruction::Mul:
1177249259Sdim      return ConstantExpr::getAnd(C1, C2);
1178249259Sdim    case Instruction::Shl:
1179249259Sdim    case Instruction::LShr:
1180249259Sdim    case Instruction::AShr:
1181249259Sdim      // We can assume that C2 == 0.  If it were one the result would be
1182249259Sdim      // undefined because the shift value is as large as the bitwidth.
1183249259Sdim      return C1;
1184249259Sdim    case Instruction::SDiv:
1185249259Sdim    case Instruction::UDiv:
1186249259Sdim      // We can assume that C2 == 1.  If it were zero the result would be
1187249259Sdim      // undefined through division by zero.
1188249259Sdim      return C1;
1189249259Sdim    case Instruction::URem:
1190249259Sdim    case Instruction::SRem:
1191249259Sdim      // We can assume that C2 == 1.  If it were zero the result would be
1192249259Sdim      // undefined through division by zero.
1193249259Sdim      return ConstantInt::getFalse(C1->getContext());
1194249259Sdim    default:
1195249259Sdim      break;
1196249259Sdim    }
1197249259Sdim  }
1198249259Sdim
1199249259Sdim  // We don't know how to fold this.
1200249259Sdim  return 0;
1201249259Sdim}
1202249259Sdim
1203249259Sdim/// isZeroSizedType - This type is zero sized if its an array or structure of
1204249259Sdim/// zero sized types.  The only leaf zero sized type is an empty structure.
1205249259Sdimstatic bool isMaybeZeroSizedType(Type *Ty) {
1206249259Sdim  if (StructType *STy = dyn_cast<StructType>(Ty)) {
1207249259Sdim    if (STy->isOpaque()) return true;  // Can't say.
1208249259Sdim
1209249259Sdim    // If all of elements have zero size, this does too.
1210249259Sdim    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1211249259Sdim      if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1212249259Sdim    return true;
1213249259Sdim
1214249259Sdim  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1215249259Sdim    return isMaybeZeroSizedType(ATy->getElementType());
1216249259Sdim  }
1217249259Sdim  return false;
1218249259Sdim}
1219249259Sdim
1220249259Sdim/// IdxCompare - Compare the two constants as though they were getelementptr
1221249259Sdim/// indices.  This allows coersion of the types to be the same thing.
1222249259Sdim///
1223249259Sdim/// If the two constants are the "same" (after coersion), return 0.  If the
1224249259Sdim/// first is less than the second, return -1, if the second is less than the
1225249259Sdim/// first, return 1.  If the constants are not integral, return -2.
1226249259Sdim///
1227249259Sdimstatic int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1228249259Sdim  if (C1 == C2) return 0;
1229249259Sdim
1230249259Sdim  // Ok, we found a different index.  If they are not ConstantInt, we can't do
1231249259Sdim  // anything with them.
1232249259Sdim  if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1233249259Sdim    return -2; // don't know!
1234249259Sdim
1235249259Sdim  // Ok, we have two differing integer indices.  Sign extend them to be the same
1236249259Sdim  // type.  Long is always big enough, so we use it.
1237249259Sdim  if (!C1->getType()->isIntegerTy(64))
1238249259Sdim    C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1239249259Sdim
1240249259Sdim  if (!C2->getType()->isIntegerTy(64))
1241249259Sdim    C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1242249259Sdim
1243249259Sdim  if (C1 == C2) return 0;  // They are equal
1244249259Sdim
1245249259Sdim  // If the type being indexed over is really just a zero sized type, there is
1246249259Sdim  // no pointer difference being made here.
1247249259Sdim  if (isMaybeZeroSizedType(ElTy))
1248249259Sdim    return -2; // dunno.
1249249259Sdim
1250249259Sdim  // If they are really different, now that they are the same type, then we
1251249259Sdim  // found a difference!
1252249259Sdim  if (cast<ConstantInt>(C1)->getSExtValue() <
1253249259Sdim      cast<ConstantInt>(C2)->getSExtValue())
1254249259Sdim    return -1;
1255249259Sdim  else
1256249259Sdim    return 1;
1257249259Sdim}
1258249259Sdim
1259249259Sdim/// evaluateFCmpRelation - This function determines if there is anything we can
1260249259Sdim/// decide about the two constants provided.  This doesn't need to handle simple
1261249259Sdim/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1262249259Sdim/// If we can determine that the two constants have a particular relation to
1263249259Sdim/// each other, we should return the corresponding FCmpInst predicate,
1264249259Sdim/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1265249259Sdim/// ConstantFoldCompareInstruction.
1266249259Sdim///
1267249259Sdim/// To simplify this code we canonicalize the relation so that the first
1268249259Sdim/// operand is always the most "complex" of the two.  We consider ConstantFP
1269249259Sdim/// to be the simplest, and ConstantExprs to be the most complex.
1270249259Sdimstatic FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1271249259Sdim  assert(V1->getType() == V2->getType() &&
1272249259Sdim         "Cannot compare values of different types!");
1273249259Sdim
1274249259Sdim  // Handle degenerate case quickly
1275249259Sdim  if (V1 == V2) return FCmpInst::FCMP_OEQ;
1276249259Sdim
1277249259Sdim  if (!isa<ConstantExpr>(V1)) {
1278249259Sdim    if (!isa<ConstantExpr>(V2)) {
1279249259Sdim      // We distilled thisUse the standard constant folder for a few cases
1280249259Sdim      ConstantInt *R = 0;
1281249259Sdim      R = dyn_cast<ConstantInt>(
1282249259Sdim                      ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1283249259Sdim      if (R && !R->isZero())
1284249259Sdim        return FCmpInst::FCMP_OEQ;
1285249259Sdim      R = dyn_cast<ConstantInt>(
1286249259Sdim                      ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1287249259Sdim      if (R && !R->isZero())
1288249259Sdim        return FCmpInst::FCMP_OLT;
1289249259Sdim      R = dyn_cast<ConstantInt>(
1290249259Sdim                      ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1291249259Sdim      if (R && !R->isZero())
1292249259Sdim        return FCmpInst::FCMP_OGT;
1293249259Sdim
1294249259Sdim      // Nothing more we can do
1295249259Sdim      return FCmpInst::BAD_FCMP_PREDICATE;
1296249259Sdim    }
1297249259Sdim
1298249259Sdim    // If the first operand is simple and second is ConstantExpr, swap operands.
1299249259Sdim    FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1300249259Sdim    if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1301249259Sdim      return FCmpInst::getSwappedPredicate(SwappedRelation);
1302249259Sdim  } else {
1303249259Sdim    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1304249259Sdim    // constantexpr or a simple constant.
1305249259Sdim    ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1306249259Sdim    switch (CE1->getOpcode()) {
1307249259Sdim    case Instruction::FPTrunc:
1308249259Sdim    case Instruction::FPExt:
1309249259Sdim    case Instruction::UIToFP:
1310249259Sdim    case Instruction::SIToFP:
1311249259Sdim      // We might be able to do something with these but we don't right now.
1312249259Sdim      break;
1313249259Sdim    default:
1314249259Sdim      break;
1315249259Sdim    }
1316249259Sdim  }
1317249259Sdim  // There are MANY other foldings that we could perform here.  They will
1318249259Sdim  // probably be added on demand, as they seem needed.
1319249259Sdim  return FCmpInst::BAD_FCMP_PREDICATE;
1320249259Sdim}
1321249259Sdim
1322249259Sdim/// evaluateICmpRelation - This function determines if there is anything we can
1323249259Sdim/// decide about the two constants provided.  This doesn't need to handle simple
1324249259Sdim/// things like integer comparisons, but should instead handle ConstantExprs
1325249259Sdim/// and GlobalValues.  If we can determine that the two constants have a
1326249259Sdim/// particular relation to each other, we should return the corresponding ICmp
1327249259Sdim/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1328249259Sdim///
1329249259Sdim/// To simplify this code we canonicalize the relation so that the first
1330249259Sdim/// operand is always the most "complex" of the two.  We consider simple
1331249259Sdim/// constants (like ConstantInt) to be the simplest, followed by
1332249259Sdim/// GlobalValues, followed by ConstantExpr's (the most complex).
1333249259Sdim///
1334249259Sdimstatic ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1335249259Sdim                                                bool isSigned) {
1336249259Sdim  assert(V1->getType() == V2->getType() &&
1337249259Sdim         "Cannot compare different types of values!");
1338249259Sdim  if (V1 == V2) return ICmpInst::ICMP_EQ;
1339249259Sdim
1340249259Sdim  if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1341249259Sdim      !isa<BlockAddress>(V1)) {
1342249259Sdim    if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1343249259Sdim        !isa<BlockAddress>(V2)) {
1344249259Sdim      // We distilled this down to a simple case, use the standard constant
1345249259Sdim      // folder.
1346249259Sdim      ConstantInt *R = 0;
1347249259Sdim      ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1348249259Sdim      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1349249259Sdim      if (R && !R->isZero())
1350249259Sdim        return pred;
1351249259Sdim      pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1352249259Sdim      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1353249259Sdim      if (R && !R->isZero())
1354249259Sdim        return pred;
1355249259Sdim      pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1356249259Sdim      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1357249259Sdim      if (R && !R->isZero())
1358249259Sdim        return pred;
1359249259Sdim
1360249259Sdim      // If we couldn't figure it out, bail.
1361249259Sdim      return ICmpInst::BAD_ICMP_PREDICATE;
1362249259Sdim    }
1363249259Sdim
1364249259Sdim    // If the first operand is simple, swap operands.
1365249259Sdim    ICmpInst::Predicate SwappedRelation =
1366249259Sdim      evaluateICmpRelation(V2, V1, isSigned);
1367249259Sdim    if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1368249259Sdim      return ICmpInst::getSwappedPredicate(SwappedRelation);
1369249259Sdim
1370249259Sdim  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1371249259Sdim    if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1372249259Sdim      ICmpInst::Predicate SwappedRelation =
1373249259Sdim        evaluateICmpRelation(V2, V1, isSigned);
1374249259Sdim      if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1375249259Sdim        return ICmpInst::getSwappedPredicate(SwappedRelation);
1376249259Sdim      return ICmpInst::BAD_ICMP_PREDICATE;
1377249259Sdim    }
1378249259Sdim
1379249259Sdim    // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1380249259Sdim    // constant (which, since the types must match, means that it's a
1381249259Sdim    // ConstantPointerNull).
1382249259Sdim    if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1383249259Sdim      // Don't try to decide equality of aliases.
1384249259Sdim      if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1385249259Sdim        if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1386249259Sdim          return ICmpInst::ICMP_NE;
1387249259Sdim    } else if (isa<BlockAddress>(V2)) {
1388249259Sdim      return ICmpInst::ICMP_NE; // Globals never equal labels.
1389249259Sdim    } else {
1390249259Sdim      assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1391249259Sdim      // GlobalVals can never be null unless they have external weak linkage.
1392249259Sdim      // We don't try to evaluate aliases here.
1393249259Sdim      if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1394249259Sdim        return ICmpInst::ICMP_NE;
1395249259Sdim    }
1396249259Sdim  } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1397249259Sdim    if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1398249259Sdim      ICmpInst::Predicate SwappedRelation =
1399249259Sdim        evaluateICmpRelation(V2, V1, isSigned);
1400249259Sdim      if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1401249259Sdim        return ICmpInst::getSwappedPredicate(SwappedRelation);
1402249259Sdim      return ICmpInst::BAD_ICMP_PREDICATE;
1403249259Sdim    }
1404249259Sdim
1405249259Sdim    // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1406249259Sdim    // constant (which, since the types must match, means that it is a
1407249259Sdim    // ConstantPointerNull).
1408249259Sdim    if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1409249259Sdim      // Block address in another function can't equal this one, but block
1410249259Sdim      // addresses in the current function might be the same if blocks are
1411249259Sdim      // empty.
1412249259Sdim      if (BA2->getFunction() != BA->getFunction())
1413249259Sdim        return ICmpInst::ICMP_NE;
1414249259Sdim    } else {
1415249259Sdim      // Block addresses aren't null, don't equal the address of globals.
1416249259Sdim      assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1417249259Sdim             "Canonicalization guarantee!");
1418249259Sdim      return ICmpInst::ICMP_NE;
1419249259Sdim    }
1420249259Sdim  } else {
1421249259Sdim    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1422249259Sdim    // constantexpr, a global, block address, or a simple constant.
1423249259Sdim    ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1424249259Sdim    Constant *CE1Op0 = CE1->getOperand(0);
1425249259Sdim
1426249259Sdim    switch (CE1->getOpcode()) {
1427249259Sdim    case Instruction::Trunc:
1428249259Sdim    case Instruction::FPTrunc:
1429249259Sdim    case Instruction::FPExt:
1430249259Sdim    case Instruction::FPToUI:
1431249259Sdim    case Instruction::FPToSI:
1432249259Sdim      break; // We can't evaluate floating point casts or truncations.
1433249259Sdim
1434249259Sdim    case Instruction::UIToFP:
1435249259Sdim    case Instruction::SIToFP:
1436249259Sdim    case Instruction::BitCast:
1437249259Sdim    case Instruction::ZExt:
1438249259Sdim    case Instruction::SExt:
1439249259Sdim      // If the cast is not actually changing bits, and the second operand is a
1440249259Sdim      // null pointer, do the comparison with the pre-casted value.
1441249259Sdim      if (V2->isNullValue() &&
1442249259Sdim          (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1443249259Sdim        if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1444249259Sdim        if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1445249259Sdim        return evaluateICmpRelation(CE1Op0,
1446249259Sdim                                    Constant::getNullValue(CE1Op0->getType()),
1447249259Sdim                                    isSigned);
1448249259Sdim      }
1449249259Sdim      break;
1450249259Sdim
1451249259Sdim    case Instruction::GetElementPtr:
1452249259Sdim      // Ok, since this is a getelementptr, we know that the constant has a
1453249259Sdim      // pointer type.  Check the various cases.
1454249259Sdim      if (isa<ConstantPointerNull>(V2)) {
1455249259Sdim        // If we are comparing a GEP to a null pointer, check to see if the base
1456249259Sdim        // of the GEP equals the null pointer.
1457249259Sdim        if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1458249259Sdim          if (GV->hasExternalWeakLinkage())
1459249259Sdim            // Weak linkage GVals could be zero or not. We're comparing that
1460249259Sdim            // to null pointer so its greater-or-equal
1461249259Sdim            return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1462249259Sdim          else
1463249259Sdim            // If its not weak linkage, the GVal must have a non-zero address
1464249259Sdim            // so the result is greater-than
1465249259Sdim            return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1466249259Sdim        } else if (isa<ConstantPointerNull>(CE1Op0)) {
1467249259Sdim          // If we are indexing from a null pointer, check to see if we have any
1468249259Sdim          // non-zero indices.
1469249259Sdim          for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1470249259Sdim            if (!CE1->getOperand(i)->isNullValue())
1471249259Sdim              // Offsetting from null, must not be equal.
1472249259Sdim              return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1473249259Sdim          // Only zero indexes from null, must still be zero.
1474249259Sdim          return ICmpInst::ICMP_EQ;
1475249259Sdim        }
1476249259Sdim        // Otherwise, we can't really say if the first operand is null or not.
1477249259Sdim      } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1478249259Sdim        if (isa<ConstantPointerNull>(CE1Op0)) {
1479249259Sdim          if (GV2->hasExternalWeakLinkage())
1480249259Sdim            // Weak linkage GVals could be zero or not. We're comparing it to
1481249259Sdim            // a null pointer, so its less-or-equal
1482249259Sdim            return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1483249259Sdim          else
1484249259Sdim            // If its not weak linkage, the GVal must have a non-zero address
1485249259Sdim            // so the result is less-than
1486249259Sdim            return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1487249259Sdim        } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1488249259Sdim          if (GV == GV2) {
1489249259Sdim            // If this is a getelementptr of the same global, then it must be
1490249259Sdim            // different.  Because the types must match, the getelementptr could
1491249259Sdim            // only have at most one index, and because we fold getelementptr's
1492249259Sdim            // with a single zero index, it must be nonzero.
1493249259Sdim            assert(CE1->getNumOperands() == 2 &&
1494249259Sdim                   !CE1->getOperand(1)->isNullValue() &&
1495249259Sdim                   "Surprising getelementptr!");
1496249259Sdim            return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1497249259Sdim          } else {
1498249259Sdim            // If they are different globals, we don't know what the value is.
1499249259Sdim            return ICmpInst::BAD_ICMP_PREDICATE;
1500249259Sdim          }
1501249259Sdim        }
1502249259Sdim      } else {
1503249259Sdim        ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1504249259Sdim        Constant *CE2Op0 = CE2->getOperand(0);
1505249259Sdim
1506249259Sdim        // There are MANY other foldings that we could perform here.  They will
1507249259Sdim        // probably be added on demand, as they seem needed.
1508249259Sdim        switch (CE2->getOpcode()) {
1509249259Sdim        default: break;
1510249259Sdim        case Instruction::GetElementPtr:
1511249259Sdim          // By far the most common case to handle is when the base pointers are
1512249259Sdim          // obviously to the same global.
1513249259Sdim          if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1514249259Sdim            if (CE1Op0 != CE2Op0) // Don't know relative ordering.
1515249259Sdim              return ICmpInst::BAD_ICMP_PREDICATE;
1516249259Sdim            // Ok, we know that both getelementptr instructions are based on the
1517249259Sdim            // same global.  From this, we can precisely determine the relative
1518249259Sdim            // ordering of the resultant pointers.
1519249259Sdim            unsigned i = 1;
1520249259Sdim
1521249259Sdim            // The logic below assumes that the result of the comparison
1522249259Sdim            // can be determined by finding the first index that differs.
1523249259Sdim            // This doesn't work if there is over-indexing in any
1524249259Sdim            // subsequent indices, so check for that case first.
1525249259Sdim            if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1526249259Sdim                !CE2->isGEPWithNoNotionalOverIndexing())
1527249259Sdim               return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1528249259Sdim
1529249259Sdim            // Compare all of the operands the GEP's have in common.
1530249259Sdim            gep_type_iterator GTI = gep_type_begin(CE1);
1531249259Sdim            for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1532249259Sdim                 ++i, ++GTI)
1533249259Sdim              switch (IdxCompare(CE1->getOperand(i),
1534249259Sdim                                 CE2->getOperand(i), GTI.getIndexedType())) {
1535249259Sdim              case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1536249259Sdim              case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1537249259Sdim              case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1538249259Sdim              }
1539249259Sdim
1540249259Sdim            // Ok, we ran out of things they have in common.  If any leftovers
1541249259Sdim            // are non-zero then we have a difference, otherwise we are equal.
1542249259Sdim            for (; i < CE1->getNumOperands(); ++i)
1543249259Sdim              if (!CE1->getOperand(i)->isNullValue()) {
1544249259Sdim                if (isa<ConstantInt>(CE1->getOperand(i)))
1545249259Sdim                  return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1546249259Sdim                else
1547249259Sdim                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1548249259Sdim              }
1549249259Sdim
1550249259Sdim            for (; i < CE2->getNumOperands(); ++i)
1551249259Sdim              if (!CE2->getOperand(i)->isNullValue()) {
1552249259Sdim                if (isa<ConstantInt>(CE2->getOperand(i)))
1553249259Sdim                  return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1554249259Sdim                else
1555249259Sdim                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1556249259Sdim              }
1557249259Sdim            return ICmpInst::ICMP_EQ;
1558249259Sdim          }
1559249259Sdim        }
1560249259Sdim      }
1561249259Sdim    default:
1562249259Sdim      break;
1563249259Sdim    }
1564249259Sdim  }
1565249259Sdim
1566249259Sdim  return ICmpInst::BAD_ICMP_PREDICATE;
1567249259Sdim}
1568249259Sdim
1569249259SdimConstant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1570249259Sdim                                               Constant *C1, Constant *C2) {
1571249259Sdim  Type *ResultTy;
1572249259Sdim  if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1573249259Sdim    ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1574249259Sdim                               VT->getNumElements());
1575249259Sdim  else
1576249259Sdim    ResultTy = Type::getInt1Ty(C1->getContext());
1577249259Sdim
1578249259Sdim  // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1579249259Sdim  if (pred == FCmpInst::FCMP_FALSE)
1580249259Sdim    return Constant::getNullValue(ResultTy);
1581249259Sdim
1582249259Sdim  if (pred == FCmpInst::FCMP_TRUE)
1583249259Sdim    return Constant::getAllOnesValue(ResultTy);
1584249259Sdim
1585249259Sdim  // Handle some degenerate cases first
1586249259Sdim  if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1587249259Sdim    // For EQ and NE, we can always pick a value for the undef to make the
1588249259Sdim    // predicate pass or fail, so we can return undef.
1589249259Sdim    // Also, if both operands are undef, we can return undef.
1590249259Sdim    if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1591249259Sdim        (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1592249259Sdim      return UndefValue::get(ResultTy);
1593249259Sdim    // Otherwise, pick the same value as the non-undef operand, and fold
1594249259Sdim    // it to true or false.
1595249259Sdim    return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1596249259Sdim  }
1597249259Sdim
1598249259Sdim  // icmp eq/ne(null,GV) -> false/true
1599249259Sdim  if (C1->isNullValue()) {
1600249259Sdim    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1601249259Sdim      // Don't try to evaluate aliases.  External weak GV can be null.
1602249259Sdim      if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1603249259Sdim        if (pred == ICmpInst::ICMP_EQ)
1604249259Sdim          return ConstantInt::getFalse(C1->getContext());
1605249259Sdim        else if (pred == ICmpInst::ICMP_NE)
1606249259Sdim          return ConstantInt::getTrue(C1->getContext());
1607249259Sdim      }
1608249259Sdim  // icmp eq/ne(GV,null) -> false/true
1609249259Sdim  } else if (C2->isNullValue()) {
1610249259Sdim    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1611249259Sdim      // Don't try to evaluate aliases.  External weak GV can be null.
1612249259Sdim      if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1613249259Sdim        if (pred == ICmpInst::ICMP_EQ)
1614249259Sdim          return ConstantInt::getFalse(C1->getContext());
1615249259Sdim        else if (pred == ICmpInst::ICMP_NE)
1616249259Sdim          return ConstantInt::getTrue(C1->getContext());
1617249259Sdim      }
1618249259Sdim  }
1619249259Sdim
1620249259Sdim  // If the comparison is a comparison between two i1's, simplify it.
1621249259Sdim  if (C1->getType()->isIntegerTy(1)) {
1622249259Sdim    switch(pred) {
1623249259Sdim    case ICmpInst::ICMP_EQ:
1624249259Sdim      if (isa<ConstantInt>(C2))
1625249259Sdim        return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1626249259Sdim      return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1627249259Sdim    case ICmpInst::ICMP_NE:
1628249259Sdim      return ConstantExpr::getXor(C1, C2);
1629249259Sdim    default:
1630249259Sdim      break;
1631249259Sdim    }
1632249259Sdim  }
1633249259Sdim
1634249259Sdim  if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1635249259Sdim    APInt V1 = cast<ConstantInt>(C1)->getValue();
1636249259Sdim    APInt V2 = cast<ConstantInt>(C2)->getValue();
1637249259Sdim    switch (pred) {
1638249259Sdim    default: llvm_unreachable("Invalid ICmp Predicate");
1639249259Sdim    case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1640249259Sdim    case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1641249259Sdim    case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1642249259Sdim    case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1643249259Sdim    case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1644249259Sdim    case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1645249259Sdim    case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1646249259Sdim    case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1647249259Sdim    case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1648249259Sdim    case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1649249259Sdim    }
1650249259Sdim  } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1651249259Sdim    APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1652249259Sdim    APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1653249259Sdim    APFloat::cmpResult R = C1V.compare(C2V);
1654249259Sdim    switch (pred) {
1655249259Sdim    default: llvm_unreachable("Invalid FCmp Predicate");
1656249259Sdim    case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1657249259Sdim    case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
1658249259Sdim    case FCmpInst::FCMP_UNO:
1659249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1660249259Sdim    case FCmpInst::FCMP_ORD:
1661249259Sdim      return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1662249259Sdim    case FCmpInst::FCMP_UEQ:
1663249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1664249259Sdim                                        R==APFloat::cmpEqual);
1665249259Sdim    case FCmpInst::FCMP_OEQ:
1666249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1667249259Sdim    case FCmpInst::FCMP_UNE:
1668249259Sdim      return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1669249259Sdim    case FCmpInst::FCMP_ONE:
1670249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1671249259Sdim                                        R==APFloat::cmpGreaterThan);
1672249259Sdim    case FCmpInst::FCMP_ULT:
1673249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1674249259Sdim                                        R==APFloat::cmpLessThan);
1675249259Sdim    case FCmpInst::FCMP_OLT:
1676249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1677249259Sdim    case FCmpInst::FCMP_UGT:
1678249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1679249259Sdim                                        R==APFloat::cmpGreaterThan);
1680249259Sdim    case FCmpInst::FCMP_OGT:
1681249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1682249259Sdim    case FCmpInst::FCMP_ULE:
1683249259Sdim      return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1684249259Sdim    case FCmpInst::FCMP_OLE:
1685249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1686249259Sdim                                        R==APFloat::cmpEqual);
1687249259Sdim    case FCmpInst::FCMP_UGE:
1688249259Sdim      return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1689249259Sdim    case FCmpInst::FCMP_OGE:
1690249259Sdim      return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1691249259Sdim                                        R==APFloat::cmpEqual);
1692249259Sdim    }
1693249259Sdim  } else if (C1->getType()->isVectorTy()) {
1694249259Sdim    // If we can constant fold the comparison of each element, constant fold
1695249259Sdim    // the whole vector comparison.
1696249259Sdim    SmallVector<Constant*, 4> ResElts;
1697249259Sdim    Type *Ty = IntegerType::get(C1->getContext(), 32);
1698249259Sdim    // Compare the elements, producing an i1 result or constant expr.
1699249259Sdim    for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1700249259Sdim      Constant *C1E =
1701249259Sdim        ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1702249259Sdim      Constant *C2E =
1703249259Sdim        ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1704249259Sdim
1705249259Sdim      ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1706249259Sdim    }
1707249259Sdim
1708249259Sdim    return ConstantVector::get(ResElts);
1709249259Sdim  }
1710249259Sdim
1711249259Sdim  if (C1->getType()->isFloatingPointTy()) {
1712249259Sdim    int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1713249259Sdim    switch (evaluateFCmpRelation(C1, C2)) {
1714249259Sdim    default: llvm_unreachable("Unknown relation!");
1715249259Sdim    case FCmpInst::FCMP_UNO:
1716249259Sdim    case FCmpInst::FCMP_ORD:
1717249259Sdim    case FCmpInst::FCMP_UEQ:
1718249259Sdim    case FCmpInst::FCMP_UNE:
1719249259Sdim    case FCmpInst::FCMP_ULT:
1720249259Sdim    case FCmpInst::FCMP_UGT:
1721249259Sdim    case FCmpInst::FCMP_ULE:
1722249259Sdim    case FCmpInst::FCMP_UGE:
1723249259Sdim    case FCmpInst::FCMP_TRUE:
1724249259Sdim    case FCmpInst::FCMP_FALSE:
1725249259Sdim    case FCmpInst::BAD_FCMP_PREDICATE:
1726249259Sdim      break; // Couldn't determine anything about these constants.
1727249259Sdim    case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1728249259Sdim      Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1729249259Sdim                pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1730249259Sdim                pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1731249259Sdim      break;
1732249259Sdim    case FCmpInst::FCMP_OLT: // We know that C1 < C2
1733249259Sdim      Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1734249259Sdim                pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1735249259Sdim                pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1736249259Sdim      break;
1737249259Sdim    case FCmpInst::FCMP_OGT: // We know that C1 > C2
1738249259Sdim      Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1739249259Sdim                pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1740249259Sdim                pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1741249259Sdim      break;
1742249259Sdim    case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1743249259Sdim      // We can only partially decide this relation.
1744249259Sdim      if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1745249259Sdim        Result = 0;
1746249259Sdim      else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1747249259Sdim        Result = 1;
1748249259Sdim      break;
1749249259Sdim    case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1750249259Sdim      // We can only partially decide this relation.
1751249259Sdim      if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1752249259Sdim        Result = 0;
1753249259Sdim      else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1754249259Sdim        Result = 1;
1755249259Sdim      break;
1756249259Sdim    case FCmpInst::FCMP_ONE: // We know that C1 != C2
1757249259Sdim      // We can only partially decide this relation.
1758249259Sdim      if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1759249259Sdim        Result = 0;
1760249259Sdim      else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1761249259Sdim        Result = 1;
1762249259Sdim      break;
1763249259Sdim    }
1764249259Sdim
1765249259Sdim    // If we evaluated the result, return it now.
1766249259Sdim    if (Result != -1)
1767249259Sdim      return ConstantInt::get(ResultTy, Result);
1768249259Sdim
1769249259Sdim  } else {
1770249259Sdim    // Evaluate the relation between the two constants, per the predicate.
1771249259Sdim    int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1772249259Sdim    switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1773249259Sdim    default: llvm_unreachable("Unknown relational!");
1774249259Sdim    case ICmpInst::BAD_ICMP_PREDICATE:
1775249259Sdim      break;  // Couldn't determine anything about these constants.
1776249259Sdim    case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1777249259Sdim      // If we know the constants are equal, we can decide the result of this
1778249259Sdim      // computation precisely.
1779249259Sdim      Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1780249259Sdim      break;
1781249259Sdim    case ICmpInst::ICMP_ULT:
1782249259Sdim      switch (pred) {
1783249259Sdim      case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1784249259Sdim        Result = 1; break;
1785249259Sdim      case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1786249259Sdim        Result = 0; break;
1787249259Sdim      }
1788249259Sdim      break;
1789249259Sdim    case ICmpInst::ICMP_SLT:
1790249259Sdim      switch (pred) {
1791249259Sdim      case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1792249259Sdim        Result = 1; break;
1793249259Sdim      case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1794249259Sdim        Result = 0; break;
1795249259Sdim      }
1796249259Sdim      break;
1797249259Sdim    case ICmpInst::ICMP_UGT:
1798249259Sdim      switch (pred) {
1799249259Sdim      case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1800249259Sdim        Result = 1; break;
1801249259Sdim      case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1802249259Sdim        Result = 0; break;
1803249259Sdim      }
1804249259Sdim      break;
1805249259Sdim    case ICmpInst::ICMP_SGT:
1806249259Sdim      switch (pred) {
1807249259Sdim      case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1808249259Sdim        Result = 1; break;
1809249259Sdim      case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1810249259Sdim        Result = 0; break;
1811249259Sdim      }
1812249259Sdim      break;
1813249259Sdim    case ICmpInst::ICMP_ULE:
1814249259Sdim      if (pred == ICmpInst::ICMP_UGT) Result = 0;
1815249259Sdim      if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1816249259Sdim      break;
1817249259Sdim    case ICmpInst::ICMP_SLE:
1818249259Sdim      if (pred == ICmpInst::ICMP_SGT) Result = 0;
1819249259Sdim      if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1820249259Sdim      break;
1821249259Sdim    case ICmpInst::ICMP_UGE:
1822249259Sdim      if (pred == ICmpInst::ICMP_ULT) Result = 0;
1823249259Sdim      if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1824249259Sdim      break;
1825249259Sdim    case ICmpInst::ICMP_SGE:
1826249259Sdim      if (pred == ICmpInst::ICMP_SLT) Result = 0;
1827249259Sdim      if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1828249259Sdim      break;
1829249259Sdim    case ICmpInst::ICMP_NE:
1830249259Sdim      if (pred == ICmpInst::ICMP_EQ) Result = 0;
1831249259Sdim      if (pred == ICmpInst::ICMP_NE) Result = 1;
1832249259Sdim      break;
1833249259Sdim    }
1834249259Sdim
1835249259Sdim    // If we evaluated the result, return it now.
1836249259Sdim    if (Result != -1)
1837249259Sdim      return ConstantInt::get(ResultTy, Result);
1838249259Sdim
1839249259Sdim    // If the right hand side is a bitcast, try using its inverse to simplify
1840249259Sdim    // it by moving it to the left hand side.  We can't do this if it would turn
1841249259Sdim    // a vector compare into a scalar compare or visa versa.
1842249259Sdim    if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1843249259Sdim      Constant *CE2Op0 = CE2->getOperand(0);
1844249259Sdim      if (CE2->getOpcode() == Instruction::BitCast &&
1845249259Sdim          CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1846249259Sdim        Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1847249259Sdim        return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1848249259Sdim      }
1849249259Sdim    }
1850249259Sdim
1851249259Sdim    // If the left hand side is an extension, try eliminating it.
1852249259Sdim    if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1853249259Sdim      if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1854249259Sdim          (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1855249259Sdim        Constant *CE1Op0 = CE1->getOperand(0);
1856249259Sdim        Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1857249259Sdim        if (CE1Inverse == CE1Op0) {
1858249259Sdim          // Check whether we can safely truncate the right hand side.
1859249259Sdim          Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1860249259Sdim          if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
1861249259Sdim            return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1862249259Sdim          }
1863249259Sdim        }
1864249259Sdim      }
1865249259Sdim    }
1866249259Sdim
1867249259Sdim    if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1868249259Sdim        (C1->isNullValue() && !C2->isNullValue())) {
1869249259Sdim      // If C2 is a constant expr and C1 isn't, flip them around and fold the
1870249259Sdim      // other way if possible.
1871249259Sdim      // Also, if C1 is null and C2 isn't, flip them around.
1872249259Sdim      pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1873249259Sdim      return ConstantExpr::getICmp(pred, C2, C1);
1874249259Sdim    }
1875249259Sdim  }
1876249259Sdim  return 0;
1877249259Sdim}
1878249259Sdim
1879249259Sdim/// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1880249259Sdim/// is "inbounds".
1881249259Sdimtemplate<typename IndexTy>
1882249259Sdimstatic bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1883249259Sdim  // No indices means nothing that could be out of bounds.
1884249259Sdim  if (Idxs.empty()) return true;
1885249259Sdim
1886249259Sdim  // If the first index is zero, it's in bounds.
1887249259Sdim  if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1888249259Sdim
1889249259Sdim  // If the first index is one and all the rest are zero, it's in bounds,
1890249259Sdim  // by the one-past-the-end rule.
1891249259Sdim  if (!cast<ConstantInt>(Idxs[0])->isOne())
1892249259Sdim    return false;
1893249259Sdim  for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1894249259Sdim    if (!cast<Constant>(Idxs[i])->isNullValue())
1895249259Sdim      return false;
1896249259Sdim  return true;
1897249259Sdim}
1898249259Sdim
1899249259Sdimtemplate<typename IndexTy>
1900249259Sdimstatic Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1901249259Sdim                                               bool inBounds,
1902249259Sdim                                               ArrayRef<IndexTy> Idxs) {
1903249259Sdim  if (Idxs.empty()) return C;
1904249259Sdim  Constant *Idx0 = cast<Constant>(Idxs[0]);
1905249259Sdim  if ((Idxs.size() == 1 && Idx0->isNullValue()))
1906249259Sdim    return C;
1907249259Sdim
1908249259Sdim  if (isa<UndefValue>(C)) {
1909249259Sdim    PointerType *Ptr = cast<PointerType>(C->getType());
1910249259Sdim    Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1911249259Sdim    assert(Ty != 0 && "Invalid indices for GEP!");
1912249259Sdim    return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1913249259Sdim  }
1914249259Sdim
1915249259Sdim  if (C->isNullValue()) {
1916249259Sdim    bool isNull = true;
1917249259Sdim    for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1918249259Sdim      if (!cast<Constant>(Idxs[i])->isNullValue()) {
1919249259Sdim        isNull = false;
1920249259Sdim        break;
1921249259Sdim      }
1922249259Sdim    if (isNull) {
1923249259Sdim      PointerType *Ptr = cast<PointerType>(C->getType());
1924249259Sdim      Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1925249259Sdim      assert(Ty != 0 && "Invalid indices for GEP!");
1926249259Sdim      return ConstantPointerNull::get(PointerType::get(Ty,
1927249259Sdim                                                       Ptr->getAddressSpace()));
1928249259Sdim    }
1929249259Sdim  }
1930249259Sdim
1931249259Sdim  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1932249259Sdim    // Combine Indices - If the source pointer to this getelementptr instruction
1933249259Sdim    // is a getelementptr instruction, combine the indices of the two
1934249259Sdim    // getelementptr instructions into a single instruction.
1935249259Sdim    //
1936249259Sdim    if (CE->getOpcode() == Instruction::GetElementPtr) {
1937249259Sdim      Type *LastTy = 0;
1938249259Sdim      for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1939249259Sdim           I != E; ++I)
1940249259Sdim        LastTy = *I;
1941249259Sdim
1942249259Sdim      if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
1943249259Sdim        SmallVector<Value*, 16> NewIndices;
1944249259Sdim        NewIndices.reserve(Idxs.size() + CE->getNumOperands());
1945249259Sdim        for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1946249259Sdim          NewIndices.push_back(CE->getOperand(i));
1947249259Sdim
1948249259Sdim        // Add the last index of the source with the first index of the new GEP.
1949249259Sdim        // Make sure to handle the case when they are actually different types.
1950249259Sdim        Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1951249259Sdim        // Otherwise it must be an array.
1952249259Sdim        if (!Idx0->isNullValue()) {
1953249259Sdim          Type *IdxTy = Combined->getType();
1954249259Sdim          if (IdxTy != Idx0->getType()) {
1955249259Sdim            Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
1956249259Sdim            Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
1957249259Sdim            Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
1958249259Sdim            Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1959249259Sdim          } else {
1960249259Sdim            Combined =
1961249259Sdim              ConstantExpr::get(Instruction::Add, Idx0, Combined);
1962249259Sdim          }
1963249259Sdim        }
1964249259Sdim
1965249259Sdim        NewIndices.push_back(Combined);
1966249259Sdim        NewIndices.append(Idxs.begin() + 1, Idxs.end());
1967249259Sdim        return
1968249259Sdim          ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
1969249259Sdim                                         inBounds &&
1970249259Sdim                                           cast<GEPOperator>(CE)->isInBounds());
1971249259Sdim      }
1972249259Sdim    }
1973249259Sdim
1974249259Sdim    // Attempt to fold casts to the same type away.  For example, folding:
1975249259Sdim    //
1976249259Sdim    //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
1977249259Sdim    //                       i64 0, i64 0)
1978249259Sdim    // into:
1979249259Sdim    //
1980249259Sdim    //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
1981249259Sdim    //
1982249259Sdim    // Don't fold if the cast is changing address spaces.
1983249259Sdim    if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
1984249259Sdim      PointerType *SrcPtrTy =
1985249259Sdim        dyn_cast<PointerType>(CE->getOperand(0)->getType());
1986249259Sdim      PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
1987249259Sdim      if (SrcPtrTy && DstPtrTy) {
1988249259Sdim        ArrayType *SrcArrayTy =
1989249259Sdim          dyn_cast<ArrayType>(SrcPtrTy->getElementType());
1990249259Sdim        ArrayType *DstArrayTy =
1991249259Sdim          dyn_cast<ArrayType>(DstPtrTy->getElementType());
1992249259Sdim        if (SrcArrayTy && DstArrayTy
1993249259Sdim            && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
1994249259Sdim            && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
1995249259Sdim          return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
1996249259Sdim                                                Idxs, inBounds);
1997249259Sdim      }
1998249259Sdim    }
1999249259Sdim  }
2000249259Sdim
2001249259Sdim  // Check to see if any array indices are not within the corresponding
2002249259Sdim  // notional array bounds. If so, try to determine if they can be factored
2003249259Sdim  // out into preceding dimensions.
2004249259Sdim  bool Unknown = false;
2005249259Sdim  SmallVector<Constant *, 8> NewIdxs;
2006249259Sdim  Type *Ty = C->getType();
2007249259Sdim  Type *Prev = 0;
2008249259Sdim  for (unsigned i = 0, e = Idxs.size(); i != e;
2009249259Sdim       Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2010249259Sdim    if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2011249259Sdim      if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2012249259Sdim        if (ATy->getNumElements() <= INT64_MAX &&
2013249259Sdim            ATy->getNumElements() != 0 &&
2014249259Sdim            CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2015249259Sdim          if (isa<SequentialType>(Prev)) {
2016249259Sdim            // It's out of range, but we can factor it into the prior
2017249259Sdim            // dimension.
2018249259Sdim            NewIdxs.resize(Idxs.size());
2019249259Sdim            ConstantInt *Factor = ConstantInt::get(CI->getType(),
2020249259Sdim                                                   ATy->getNumElements());
2021249259Sdim            NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2022249259Sdim
2023249259Sdim            Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2024249259Sdim            Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2025249259Sdim
2026249259Sdim            // Before adding, extend both operands to i64 to avoid
2027249259Sdim            // overflow trouble.
2028249259Sdim            if (!PrevIdx->getType()->isIntegerTy(64))
2029249259Sdim              PrevIdx = ConstantExpr::getSExt(PrevIdx,
2030249259Sdim                                           Type::getInt64Ty(Div->getContext()));
2031249259Sdim            if (!Div->getType()->isIntegerTy(64))
2032249259Sdim              Div = ConstantExpr::getSExt(Div,
2033249259Sdim                                          Type::getInt64Ty(Div->getContext()));
2034249259Sdim
2035249259Sdim            NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2036249259Sdim          } else {
2037249259Sdim            // It's out of range, but the prior dimension is a struct
2038249259Sdim            // so we can't do anything about it.
2039249259Sdim            Unknown = true;
2040249259Sdim          }
2041249259Sdim        }
2042249259Sdim    } else {
2043249259Sdim      // We don't know if it's in range or not.
2044249259Sdim      Unknown = true;
2045249259Sdim    }
2046249259Sdim  }
2047249259Sdim
2048249259Sdim  // If we did any factoring, start over with the adjusted indices.
2049249259Sdim  if (!NewIdxs.empty()) {
2050249259Sdim    for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2051249259Sdim      if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2052249259Sdim    return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2053249259Sdim  }
2054249259Sdim
2055249259Sdim  // If all indices are known integers and normalized, we can do a simple
2056249259Sdim  // check for the "inbounds" property.
2057249259Sdim  if (!Unknown && !inBounds &&
2058249259Sdim      isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
2059249259Sdim    return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2060249259Sdim
2061249259Sdim  return 0;
2062249259Sdim}
2063249259Sdim
2064249259SdimConstant *llvm::ConstantFoldGetElementPtr(Constant *C,
2065249259Sdim                                          bool inBounds,
2066249259Sdim                                          ArrayRef<Constant *> Idxs) {
2067249259Sdim  return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2068249259Sdim}
2069249259Sdim
2070249259SdimConstant *llvm::ConstantFoldGetElementPtr(Constant *C,
2071249259Sdim                                          bool inBounds,
2072249259Sdim                                          ArrayRef<Value *> Idxs) {
2073249259Sdim  return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2074249259Sdim}
2075