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