ConstantFold.cpp revision 43ad6b3e0d6ada51e9b23aab3e061187f1f5710c
1//===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements folding of constants for LLVM.  This implements the
11// (internal) ConstantFold.h interface, which is used by the
12// ConstantExpr::get* methods to automatically fold constants when possible.
13//
14// The current constant folding implementation is implemented in two pieces: the
15// template-based folder for simple primitive constants like ConstantInt, and
16// the special case hackery that we use to symbolically evaluate expressions
17// that use ConstantExprs.
18//
19//===----------------------------------------------------------------------===//
20
21#include "ConstantFold.h"
22#include "llvm/Constants.h"
23#include "llvm/Instructions.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Function.h"
26#include "llvm/GlobalAlias.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Support/Compiler.h"
29#include "llvm/Support/GetElementPtrTypeIterator.h"
30#include "llvm/Support/ManagedStatic.h"
31#include "llvm/Support/MathExtras.h"
32#include <limits>
33using namespace llvm;
34
35//===----------------------------------------------------------------------===//
36//                ConstantFold*Instruction Implementations
37//===----------------------------------------------------------------------===//
38
39/// BitCastConstantVector - Convert the specified ConstantVector node to the
40/// specified vector type.  At this point, we know that the elements of the
41/// input vector constant are all simple integer or FP values.
42static Constant *BitCastConstantVector(ConstantVector *CV,
43                                       const VectorType *DstTy) {
44  // If this cast changes element count then we can't handle it here:
45  // doing so requires endianness information.  This should be handled by
46  // Analysis/ConstantFolding.cpp
47  unsigned NumElts = DstTy->getNumElements();
48  if (NumElts != CV->getNumOperands())
49    return 0;
50
51  // Check to verify that all elements of the input are simple.
52  for (unsigned i = 0; i != NumElts; ++i) {
53    if (!isa<ConstantInt>(CV->getOperand(i)) &&
54        !isa<ConstantFP>(CV->getOperand(i)))
55      return 0;
56  }
57
58  // Bitcast each element now.
59  std::vector<Constant*> Result;
60  const Type *DstEltTy = DstTy->getElementType();
61  for (unsigned i = 0; i != NumElts; ++i)
62    Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
63  return ConstantVector::get(Result);
64}
65
66/// This function determines which opcode to use to fold two constant cast
67/// expressions together. It uses CastInst::isEliminableCastPair to determine
68/// the opcode. Consequently its just a wrapper around that function.
69/// @brief Determine if it is valid to fold a cast of a cast
70static unsigned
71foldConstantCastPair(
72  unsigned opc,          ///< opcode of the second cast constant expression
73  const ConstantExpr*Op, ///< the first cast constant expression
74  const Type *DstTy      ///< desintation type of the first cast
75) {
76  assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
77  assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
78  assert(CastInst::isCast(opc) && "Invalid cast opcode");
79
80  // The the types and opcodes for the two Cast constant expressions
81  const Type *SrcTy = Op->getOperand(0)->getType();
82  const Type *MidTy = Op->getType();
83  Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
84  Instruction::CastOps secondOp = Instruction::CastOps(opc);
85
86  // Let CastInst::isEliminableCastPair do the heavy lifting.
87  return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
88                                        Type::Int64Ty);
89}
90
91static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
92  const Type *SrcTy = V->getType();
93  if (SrcTy == DestTy)
94    return V; // no-op cast
95
96  // Check to see if we are casting a pointer to an aggregate to a pointer to
97  // the first element.  If so, return the appropriate GEP instruction.
98  if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
99    if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
100      SmallVector<Value*, 8> IdxList;
101      IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
102      const Type *ElTy = PTy->getElementType();
103      while (ElTy != DPTy->getElementType()) {
104        if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
105          if (STy->getNumElements() == 0) break;
106          ElTy = STy->getElementType(0);
107          IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
108        } else if (const SequentialType *STy = dyn_cast<SequentialType>(ElTy)) {
109          if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
110          ElTy = STy->getElementType();
111          IdxList.push_back(IdxList[0]);
112        } else {
113          break;
114        }
115      }
116
117      if (ElTy == DPTy->getElementType())
118        return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
119    }
120
121  // Handle casts from one vector constant to another.  We know that the src
122  // and dest type have the same size (otherwise its an illegal cast).
123  if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
124    if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
125      assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
126             "Not cast between same sized vectors!");
127      // First, check for null.  Undef is already handled.
128      if (isa<ConstantAggregateZero>(V))
129        return Constant::getNullValue(DestTy);
130
131      if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
132        return BitCastConstantVector(CV, DestPTy);
133    }
134  }
135
136  // Finally, implement bitcast folding now.   The code below doesn't handle
137  // bitcast right.
138  if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
139    return ConstantPointerNull::get(cast<PointerType>(DestTy));
140
141  // Handle integral constant input.
142  if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
143    if (DestTy->isInteger())
144      // Integral -> Integral. This is a no-op because the bit widths must
145      // be the same. Consequently, we just fold to V.
146      return V;
147
148    if (DestTy->isFloatingPoint()) {
149      assert((DestTy == Type::DoubleTy || DestTy == Type::FloatTy) &&
150             "Unknown FP type!");
151      return ConstantFP::get(DestTy, APFloat(CI->getValue()));
152    }
153    // Otherwise, can't fold this (vector?)
154    return 0;
155  }
156
157  // Handle ConstantFP input.
158  if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
159    // FP -> Integral.
160    if (DestTy == Type::Int32Ty) {
161      return ConstantInt::get(FP->getValueAPF().convertToAPInt());
162    } else {
163      assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
164      return ConstantInt::get(FP->getValueAPF().convertToAPInt());
165    }
166  }
167  return 0;
168}
169
170
171Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
172                                            const Type *DestTy) {
173  const Type *SrcTy = V->getType();
174
175  if (isa<UndefValue>(V)) {
176    // zext(undef) = 0, because the top bits will be zero.
177    // sext(undef) = 0, because the top bits will all be the same.
178    if (opc == Instruction::ZExt || opc == Instruction::SExt)
179      return Constant::getNullValue(DestTy);
180    return UndefValue::get(DestTy);
181  }
182  // No compile-time operations on this type yet.
183  if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
184    return 0;
185
186  // If the cast operand is a constant expression, there's a few things we can
187  // do to try to simplify it.
188  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
189    if (CE->isCast()) {
190      // Try hard to fold cast of cast because they are often eliminable.
191      if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
192        return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
193    } else if (CE->getOpcode() == Instruction::GetElementPtr) {
194      // If all of the indexes in the GEP are null values, there is no pointer
195      // adjustment going on.  We might as well cast the source pointer.
196      bool isAllNull = true;
197      for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
198        if (!CE->getOperand(i)->isNullValue()) {
199          isAllNull = false;
200          break;
201        }
202      if (isAllNull)
203        // This is casting one pointer type to another, always BitCast
204        return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
205    }
206  }
207
208  // We actually have to do a cast now. Perform the cast according to the
209  // opcode specified.
210  switch (opc) {
211  case Instruction::FPTrunc:
212  case Instruction::FPExt:
213    if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
214      APFloat Val = FPC->getValueAPF();
215      Val.convert(DestTy == Type::FloatTy ? APFloat::IEEEsingle :
216                  DestTy == Type::DoubleTy ? APFloat::IEEEdouble :
217                  DestTy == Type::X86_FP80Ty ? APFloat::x87DoubleExtended :
218                  DestTy == Type::FP128Ty ? APFloat::IEEEquad :
219                  APFloat::Bogus,
220                  APFloat::rmNearestTiesToEven);
221      return ConstantFP::get(DestTy, Val);
222    }
223    return 0; // Can't fold.
224  case Instruction::FPToUI:
225  case Instruction::FPToSI:
226    if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
227      const APFloat &V = FPC->getValueAPF();
228      uint64_t x[2];
229      uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
230      (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
231                                APFloat::rmTowardZero);
232      APInt Val(DestBitWidth, 2, x);
233      return ConstantInt::get(Val);
234    }
235    if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
236      std::vector<Constant*> res;
237      const VectorType *DestVecTy = cast<VectorType>(DestTy);
238      const Type *DstEltTy = DestVecTy->getElementType();
239      for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
240        res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
241                                                  DstEltTy));
242      return ConstantVector::get(DestVecTy, res);
243    }
244    return 0; // Can't fold.
245  case Instruction::IntToPtr:   //always treated as unsigned
246    if (V->isNullValue())       // Is it an integral null value?
247      return ConstantPointerNull::get(cast<PointerType>(DestTy));
248    return 0;                   // Other pointer types cannot be casted
249  case Instruction::PtrToInt:   // always treated as unsigned
250    if (V->isNullValue())       // is it a null pointer value?
251      return ConstantInt::get(DestTy, 0);
252    return 0;                   // Other pointer types cannot be casted
253  case Instruction::UIToFP:
254  case Instruction::SIToFP:
255    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
256      APInt api = CI->getValue();
257      const uint64_t zero[] = {0, 0};
258      uint32_t BitWidth = cast<IntegerType>(SrcTy)->getBitWidth();
259      APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
260                                  2, zero));
261      (void)apf.convertFromZeroExtendedInteger(api.getRawData(), BitWidth,
262                                   opc==Instruction::SIToFP,
263                                   APFloat::rmNearestTiesToEven);
264      return ConstantFP::get(DestTy, apf);
265    }
266    if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
267      std::vector<Constant*> res;
268      const VectorType *DestVecTy = cast<VectorType>(DestTy);
269      const Type *DstEltTy = DestVecTy->getElementType();
270      for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
271        res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
272                                                  DstEltTy));
273      return ConstantVector::get(DestVecTy, res);
274    }
275    return 0;
276  case Instruction::ZExt:
277    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
278      uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
279      APInt Result(CI->getValue());
280      Result.zext(BitWidth);
281      return ConstantInt::get(Result);
282    }
283    return 0;
284  case Instruction::SExt:
285    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
286      uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
287      APInt Result(CI->getValue());
288      Result.sext(BitWidth);
289      return ConstantInt::get(Result);
290    }
291    return 0;
292  case Instruction::Trunc:
293    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
294      uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
295      APInt Result(CI->getValue());
296      Result.trunc(BitWidth);
297      return ConstantInt::get(Result);
298    }
299    return 0;
300  case Instruction::BitCast:
301    return FoldBitCast(const_cast<Constant*>(V), DestTy);
302  default:
303    assert(!"Invalid CE CastInst opcode");
304    break;
305  }
306
307  assert(0 && "Failed to cast constant expression");
308  return 0;
309}
310
311Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
312                                              const Constant *V1,
313                                              const Constant *V2) {
314  if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
315    return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
316
317  if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
318  if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
319  if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
320  if (V1 == V2) return const_cast<Constant*>(V1);
321  return 0;
322}
323
324Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
325                                                      const Constant *Idx) {
326  if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
327    return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
328  if (Val->isNullValue())  // ee(zero, x) -> zero
329    return Constant::getNullValue(
330                          cast<VectorType>(Val->getType())->getElementType());
331
332  if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
333    if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
334      return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
335    } else if (isa<UndefValue>(Idx)) {
336      // ee({w,x,y,z}, undef) -> w (an arbitrary value).
337      return const_cast<Constant*>(CVal->getOperand(0));
338    }
339  }
340  return 0;
341}
342
343Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
344                                                     const Constant *Elt,
345                                                     const Constant *Idx) {
346  const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
347  if (!CIdx) return 0;
348  APInt idxVal = CIdx->getValue();
349  if (isa<UndefValue>(Val)) {
350    // Insertion of scalar constant into vector undef
351    // Optimize away insertion of undef
352    if (isa<UndefValue>(Elt))
353      return const_cast<Constant*>(Val);
354    // Otherwise break the aggregate undef into multiple undefs and do
355    // the insertion
356    unsigned numOps =
357      cast<VectorType>(Val->getType())->getNumElements();
358    std::vector<Constant*> Ops;
359    Ops.reserve(numOps);
360    for (unsigned i = 0; i < numOps; ++i) {
361      const Constant *Op =
362        (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
363      Ops.push_back(const_cast<Constant*>(Op));
364    }
365    return ConstantVector::get(Ops);
366  }
367  if (isa<ConstantAggregateZero>(Val)) {
368    // Insertion of scalar constant into vector aggregate zero
369    // Optimize away insertion of zero
370    if (Elt->isNullValue())
371      return const_cast<Constant*>(Val);
372    // Otherwise break the aggregate zero into multiple zeros and do
373    // the insertion
374    unsigned numOps =
375      cast<VectorType>(Val->getType())->getNumElements();
376    std::vector<Constant*> Ops;
377    Ops.reserve(numOps);
378    for (unsigned i = 0; i < numOps; ++i) {
379      const Constant *Op =
380        (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
381      Ops.push_back(const_cast<Constant*>(Op));
382    }
383    return ConstantVector::get(Ops);
384  }
385  if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
386    // Insertion of scalar constant into vector constant
387    std::vector<Constant*> Ops;
388    Ops.reserve(CVal->getNumOperands());
389    for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
390      const Constant *Op =
391        (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
392      Ops.push_back(const_cast<Constant*>(Op));
393    }
394    return ConstantVector::get(Ops);
395  }
396  return 0;
397}
398
399/// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
400/// return the specified element value.  Otherwise return null.
401static Constant *GetVectorElement(const Constant *C, unsigned EltNo) {
402  if (const ConstantVector *CV = dyn_cast<ConstantVector>(C))
403    return const_cast<Constant*>(CV->getOperand(EltNo));
404
405  const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
406  if (isa<ConstantAggregateZero>(C))
407    return Constant::getNullValue(EltTy);
408  if (isa<UndefValue>(C))
409    return UndefValue::get(EltTy);
410  return 0;
411}
412
413Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
414                                                     const Constant *V2,
415                                                     const Constant *Mask) {
416  // Undefined shuffle mask -> undefined value.
417  if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
418
419  unsigned NumElts = cast<VectorType>(V1->getType())->getNumElements();
420  const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
421
422  // Loop over the shuffle mask, evaluating each element.
423  SmallVector<Constant*, 32> Result;
424  for (unsigned i = 0; i != NumElts; ++i) {
425    Constant *InElt = GetVectorElement(Mask, i);
426    if (InElt == 0) return 0;
427
428    if (isa<UndefValue>(InElt))
429      InElt = UndefValue::get(EltTy);
430    else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
431      unsigned Elt = CI->getZExtValue();
432      if (Elt >= NumElts*2)
433        InElt = UndefValue::get(EltTy);
434      else if (Elt >= NumElts)
435        InElt = GetVectorElement(V2, Elt-NumElts);
436      else
437        InElt = GetVectorElement(V1, Elt);
438      if (InElt == 0) return 0;
439    } else {
440      // Unknown value.
441      return 0;
442    }
443    Result.push_back(InElt);
444  }
445
446  return ConstantVector::get(&Result[0], Result.size());
447}
448
449/// EvalVectorOp - Given two vector constants and a function pointer, apply the
450/// function pointer to each element pair, producing a new ConstantVector
451/// constant. Either or both of V1 and V2 may be NULL, meaning a
452/// ConstantAggregateZero operand.
453static Constant *EvalVectorOp(const ConstantVector *V1,
454                              const ConstantVector *V2,
455                              const VectorType *VTy,
456                              Constant *(*FP)(Constant*, Constant*)) {
457  std::vector<Constant*> Res;
458  const Type *EltTy = VTy->getElementType();
459  for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
460    const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
461    const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
462    Res.push_back(FP(const_cast<Constant*>(C1),
463                     const_cast<Constant*>(C2)));
464  }
465  return ConstantVector::get(Res);
466}
467
468Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
469                                              const Constant *C1,
470                                              const Constant *C2) {
471  // No compile-time operations on this type yet.
472  if (C1->getType() == Type::PPC_FP128Ty)
473    return 0;
474
475  // Handle UndefValue up front
476  if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
477    switch (Opcode) {
478    case Instruction::Add:
479    case Instruction::Sub:
480    case Instruction::Xor:
481      return UndefValue::get(C1->getType());
482    case Instruction::Mul:
483    case Instruction::And:
484      return Constant::getNullValue(C1->getType());
485    case Instruction::UDiv:
486    case Instruction::SDiv:
487    case Instruction::FDiv:
488    case Instruction::URem:
489    case Instruction::SRem:
490    case Instruction::FRem:
491      if (!isa<UndefValue>(C2))                    // undef / X -> 0
492        return Constant::getNullValue(C1->getType());
493      return const_cast<Constant*>(C2);            // X / undef -> undef
494    case Instruction::Or:                          // X | undef -> -1
495      if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
496        return ConstantVector::getAllOnesValue(PTy);
497      return ConstantInt::getAllOnesValue(C1->getType());
498    case Instruction::LShr:
499      if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
500        return const_cast<Constant*>(C1);           // undef lshr undef -> undef
501      return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
502                                                    // undef lshr X -> 0
503    case Instruction::AShr:
504      if (!isa<UndefValue>(C2))
505        return const_cast<Constant*>(C1);           // undef ashr X --> undef
506      else if (isa<UndefValue>(C1))
507        return const_cast<Constant*>(C1);           // undef ashr undef -> undef
508      else
509        return const_cast<Constant*>(C1);           // X ashr undef --> X
510    case Instruction::Shl:
511      // undef << X -> 0   or   X << undef -> 0
512      return Constant::getNullValue(C1->getType());
513    }
514  }
515
516  if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
517    if (isa<ConstantExpr>(C2)) {
518      // There are many possible foldings we could do here.  We should probably
519      // at least fold add of a pointer with an integer into the appropriate
520      // getelementptr.  This will improve alias analysis a bit.
521    } else {
522      // Just implement a couple of simple identities.
523      switch (Opcode) {
524      case Instruction::Add:
525        if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X + 0 == X
526        break;
527      case Instruction::Sub:
528        if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X - 0 == X
529        break;
530      case Instruction::Mul:
531        if (C2->isNullValue()) return const_cast<Constant*>(C2);  // X * 0 == 0
532        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
533          if (CI->equalsInt(1))
534            return const_cast<Constant*>(C1);                     // X * 1 == X
535        break;
536      case Instruction::UDiv:
537      case Instruction::SDiv:
538        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
539          if (CI->equalsInt(1))
540            return const_cast<Constant*>(C1);                     // X / 1 == X
541        break;
542      case Instruction::URem:
543      case Instruction::SRem:
544        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
545          if (CI->equalsInt(1))
546            return Constant::getNullValue(CI->getType());         // X % 1 == 0
547        break;
548      case Instruction::And:
549        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2)) {
550          if (CI->isZero()) return const_cast<Constant*>(C2);     // X & 0 == 0
551          if (CI->isAllOnesValue())
552            return const_cast<Constant*>(C1);                     // X & -1 == X
553
554          // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
555          if (CE1->getOpcode() == Instruction::ZExt) {
556            APInt PossiblySetBits
557              = cast<IntegerType>(CE1->getOperand(0)->getType())->getMask();
558            PossiblySetBits.zext(C1->getType()->getPrimitiveSizeInBits());
559            if ((PossiblySetBits & CI->getValue()) == PossiblySetBits)
560              return const_cast<Constant*>(C1);
561          }
562        }
563        if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
564          GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
565
566          // Functions are at least 4-byte aligned.  If and'ing the address of a
567          // function with a constant < 4, fold it to zero.
568          if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
569            if (CI->getValue().ult(APInt(CI->getType()->getBitWidth(),4)) &&
570                isa<Function>(CPR))
571              return Constant::getNullValue(CI->getType());
572        }
573        break;
574      case Instruction::Or:
575        if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X | 0 == X
576        if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
577          if (CI->isAllOnesValue())
578            return const_cast<Constant*>(C2);  // X | -1 == -1
579        break;
580      case Instruction::Xor:
581        if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X ^ 0 == X
582        break;
583      case Instruction::AShr:
584        // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
585        if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
586          return ConstantExpr::getLShr(const_cast<Constant*>(C1),
587                                       const_cast<Constant*>(C2));
588        break;
589      }
590    }
591  } else if (isa<ConstantExpr>(C2)) {
592    // If C2 is a constant expr and C1 isn't, flop them around and fold the
593    // other way if possible.
594    switch (Opcode) {
595    case Instruction::Add:
596    case Instruction::Mul:
597    case Instruction::And:
598    case Instruction::Or:
599    case Instruction::Xor:
600      // No change of opcode required.
601      return ConstantFoldBinaryInstruction(Opcode, C2, C1);
602
603    case Instruction::Shl:
604    case Instruction::LShr:
605    case Instruction::AShr:
606    case Instruction::Sub:
607    case Instruction::SDiv:
608    case Instruction::UDiv:
609    case Instruction::FDiv:
610    case Instruction::URem:
611    case Instruction::SRem:
612    case Instruction::FRem:
613    default:  // These instructions cannot be flopped around.
614      return 0;
615    }
616  }
617
618  // At this point we know neither constant is an UndefValue nor a ConstantExpr
619  // so look at directly computing the value.
620  if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
621    if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
622      using namespace APIntOps;
623      APInt C1V = CI1->getValue();
624      APInt C2V = CI2->getValue();
625      switch (Opcode) {
626      default:
627        break;
628      case Instruction::Add:
629        return ConstantInt::get(C1V + C2V);
630      case Instruction::Sub:
631        return ConstantInt::get(C1V - C2V);
632      case Instruction::Mul:
633        return ConstantInt::get(C1V * C2V);
634      case Instruction::UDiv:
635        if (CI2->isNullValue())
636          return 0;        // X / 0 -> can't fold
637        return ConstantInt::get(C1V.udiv(C2V));
638      case Instruction::SDiv:
639        if (CI2->isNullValue())
640          return 0;        // X / 0 -> can't fold
641        if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
642          return 0;        // MIN_INT / -1 -> overflow
643        return ConstantInt::get(C1V.sdiv(C2V));
644      case Instruction::URem:
645        if (C2->isNullValue())
646          return 0;        // X / 0 -> can't fold
647        return ConstantInt::get(C1V.urem(C2V));
648      case Instruction::SRem:
649        if (CI2->isNullValue())
650          return 0;        // X % 0 -> can't fold
651        if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
652          return 0;        // MIN_INT % -1 -> overflow
653        return ConstantInt::get(C1V.srem(C2V));
654      case Instruction::And:
655        return ConstantInt::get(C1V & C2V);
656      case Instruction::Or:
657        return ConstantInt::get(C1V | C2V);
658      case Instruction::Xor:
659        return ConstantInt::get(C1V ^ C2V);
660      case Instruction::Shl:
661        if (uint32_t shiftAmt = C2V.getZExtValue())
662          if (shiftAmt < C1V.getBitWidth())
663            return ConstantInt::get(C1V.shl(shiftAmt));
664          else
665            return UndefValue::get(C1->getType()); // too big shift is undef
666        return const_cast<ConstantInt*>(CI1); // Zero shift is identity
667      case Instruction::LShr:
668        if (uint32_t shiftAmt = C2V.getZExtValue())
669          if (shiftAmt < C1V.getBitWidth())
670            return ConstantInt::get(C1V.lshr(shiftAmt));
671          else
672            return UndefValue::get(C1->getType()); // too big shift is undef
673        return const_cast<ConstantInt*>(CI1); // Zero shift is identity
674      case Instruction::AShr:
675        if (uint32_t shiftAmt = C2V.getZExtValue())
676          if (shiftAmt < C1V.getBitWidth())
677            return ConstantInt::get(C1V.ashr(shiftAmt));
678          else
679            return UndefValue::get(C1->getType()); // too big shift is undef
680        return const_cast<ConstantInt*>(CI1); // Zero shift is identity
681      }
682    }
683  } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
684    if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
685      APFloat C1V = CFP1->getValueAPF();
686      APFloat C2V = CFP2->getValueAPF();
687      APFloat C3V = C1V;  // copy for modification
688      bool isDouble = CFP1->getType()==Type::DoubleTy;
689      switch (Opcode) {
690      default:
691        break;
692      case Instruction::Add:
693        (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
694        return ConstantFP::get(CFP1->getType(), C3V);
695      case Instruction::Sub:
696        (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
697        return ConstantFP::get(CFP1->getType(), C3V);
698      case Instruction::Mul:
699        (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
700        return ConstantFP::get(CFP1->getType(), C3V);
701      case Instruction::FDiv:
702        (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
703        return ConstantFP::get(CFP1->getType(), C3V);
704      case Instruction::FRem:
705        if (C2V.isZero())
706          // IEEE 754, Section 7.1, #5
707          return ConstantFP::get(CFP1->getType(), isDouble ?
708                            APFloat(std::numeric_limits<double>::quiet_NaN()) :
709                            APFloat(std::numeric_limits<float>::quiet_NaN()));
710        (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
711        return ConstantFP::get(CFP1->getType(), C3V);
712      }
713    }
714  } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
715    const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
716    const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
717    if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
718        (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
719      switch (Opcode) {
720        default:
721          break;
722        case Instruction::Add:
723        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
724        case Instruction::Sub:
725        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
726        case Instruction::Mul:
727        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
728        case Instruction::UDiv:
729        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
730        case Instruction::SDiv:
731        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
732        case Instruction::FDiv:
733        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
734        case Instruction::URem:
735        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
736        case Instruction::SRem:
737        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
738        case Instruction::FRem:
739        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
740        case Instruction::And:
741        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
742        case Instruction::Or:
743        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
744        case Instruction::Xor:
745        return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
746      }
747    }
748  }
749
750  // We don't know how to fold this
751  return 0;
752}
753
754/// isZeroSizedType - This type is zero sized if its an array or structure of
755/// zero sized types.  The only leaf zero sized type is an empty structure.
756static bool isMaybeZeroSizedType(const Type *Ty) {
757  if (isa<OpaqueType>(Ty)) return true;  // Can't say.
758  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
759
760    // If all of elements have zero size, this does too.
761    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
762      if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
763    return true;
764
765  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
766    return isMaybeZeroSizedType(ATy->getElementType());
767  }
768  return false;
769}
770
771/// IdxCompare - Compare the two constants as though they were getelementptr
772/// indices.  This allows coersion of the types to be the same thing.
773///
774/// If the two constants are the "same" (after coersion), return 0.  If the
775/// first is less than the second, return -1, if the second is less than the
776/// first, return 1.  If the constants are not integral, return -2.
777///
778static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
779  if (C1 == C2) return 0;
780
781  // Ok, we found a different index.  If they are not ConstantInt, we can't do
782  // anything with them.
783  if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
784    return -2; // don't know!
785
786  // Ok, we have two differing integer indices.  Sign extend them to be the same
787  // type.  Long is always big enough, so we use it.
788  if (C1->getType() != Type::Int64Ty)
789    C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
790
791  if (C2->getType() != Type::Int64Ty)
792    C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
793
794  if (C1 == C2) return 0;  // They are equal
795
796  // If the type being indexed over is really just a zero sized type, there is
797  // no pointer difference being made here.
798  if (isMaybeZeroSizedType(ElTy))
799    return -2; // dunno.
800
801  // If they are really different, now that they are the same type, then we
802  // found a difference!
803  if (cast<ConstantInt>(C1)->getSExtValue() <
804      cast<ConstantInt>(C2)->getSExtValue())
805    return -1;
806  else
807    return 1;
808}
809
810/// evaluateFCmpRelation - This function determines if there is anything we can
811/// decide about the two constants provided.  This doesn't need to handle simple
812/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
813/// If we can determine that the two constants have a particular relation to
814/// each other, we should return the corresponding FCmpInst predicate,
815/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
816/// ConstantFoldCompareInstruction.
817///
818/// To simplify this code we canonicalize the relation so that the first
819/// operand is always the most "complex" of the two.  We consider ConstantFP
820/// to be the simplest, and ConstantExprs to be the most complex.
821static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
822                                                const Constant *V2) {
823  assert(V1->getType() == V2->getType() &&
824         "Cannot compare values of different types!");
825
826  // No compile-time operations on this type yet.
827  if (V1->getType() == Type::PPC_FP128Ty)
828    return FCmpInst::BAD_FCMP_PREDICATE;
829
830  // Handle degenerate case quickly
831  if (V1 == V2) return FCmpInst::FCMP_OEQ;
832
833  if (!isa<ConstantExpr>(V1)) {
834    if (!isa<ConstantExpr>(V2)) {
835      // We distilled thisUse the standard constant folder for a few cases
836      ConstantInt *R = 0;
837      Constant *C1 = const_cast<Constant*>(V1);
838      Constant *C2 = const_cast<Constant*>(V2);
839      R = dyn_cast<ConstantInt>(
840                             ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
841      if (R && !R->isZero())
842        return FCmpInst::FCMP_OEQ;
843      R = dyn_cast<ConstantInt>(
844                             ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
845      if (R && !R->isZero())
846        return FCmpInst::FCMP_OLT;
847      R = dyn_cast<ConstantInt>(
848                             ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
849      if (R && !R->isZero())
850        return FCmpInst::FCMP_OGT;
851
852      // Nothing more we can do
853      return FCmpInst::BAD_FCMP_PREDICATE;
854    }
855
856    // If the first operand is simple and second is ConstantExpr, swap operands.
857    FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
858    if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
859      return FCmpInst::getSwappedPredicate(SwappedRelation);
860  } else {
861    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
862    // constantexpr or a simple constant.
863    const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
864    switch (CE1->getOpcode()) {
865    case Instruction::FPTrunc:
866    case Instruction::FPExt:
867    case Instruction::UIToFP:
868    case Instruction::SIToFP:
869      // We might be able to do something with these but we don't right now.
870      break;
871    default:
872      break;
873    }
874  }
875  // There are MANY other foldings that we could perform here.  They will
876  // probably be added on demand, as they seem needed.
877  return FCmpInst::BAD_FCMP_PREDICATE;
878}
879
880/// evaluateICmpRelation - This function determines if there is anything we can
881/// decide about the two constants provided.  This doesn't need to handle simple
882/// things like integer comparisons, but should instead handle ConstantExprs
883/// and GlobalValues.  If we can determine that the two constants have a
884/// particular relation to each other, we should return the corresponding ICmp
885/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
886///
887/// To simplify this code we canonicalize the relation so that the first
888/// operand is always the most "complex" of the two.  We consider simple
889/// constants (like ConstantInt) to be the simplest, followed by
890/// GlobalValues, followed by ConstantExpr's (the most complex).
891///
892static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
893                                                const Constant *V2,
894                                                bool isSigned) {
895  assert(V1->getType() == V2->getType() &&
896         "Cannot compare different types of values!");
897  if (V1 == V2) return ICmpInst::ICMP_EQ;
898
899  if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
900    if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
901      // We distilled this down to a simple case, use the standard constant
902      // folder.
903      ConstantInt *R = 0;
904      Constant *C1 = const_cast<Constant*>(V1);
905      Constant *C2 = const_cast<Constant*>(V2);
906      ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
907      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
908      if (R && !R->isZero())
909        return pred;
910      pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
911      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
912      if (R && !R->isZero())
913        return pred;
914      pred = isSigned ?  ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
915      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
916      if (R && !R->isZero())
917        return pred;
918
919      // If we couldn't figure it out, bail.
920      return ICmpInst::BAD_ICMP_PREDICATE;
921    }
922
923    // If the first operand is simple, swap operands.
924    ICmpInst::Predicate SwappedRelation =
925      evaluateICmpRelation(V2, V1, isSigned);
926    if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
927      return ICmpInst::getSwappedPredicate(SwappedRelation);
928
929  } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
930    if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
931      ICmpInst::Predicate SwappedRelation =
932        evaluateICmpRelation(V2, V1, isSigned);
933      if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
934        return ICmpInst::getSwappedPredicate(SwappedRelation);
935      else
936        return ICmpInst::BAD_ICMP_PREDICATE;
937    }
938
939    // Now we know that the RHS is a GlobalValue or simple constant,
940    // which (since the types must match) means that it's a ConstantPointerNull.
941    if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
942      // Don't try to decide equality of aliases.
943      if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
944        if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
945          return ICmpInst::ICMP_NE;
946    } else {
947      assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
948      // GlobalVals can never be null.  Don't try to evaluate aliases.
949      if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
950        return ICmpInst::ICMP_NE;
951    }
952  } else {
953    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
954    // constantexpr, a CPR, or a simple constant.
955    const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
956    const Constant *CE1Op0 = CE1->getOperand(0);
957
958    switch (CE1->getOpcode()) {
959    case Instruction::Trunc:
960    case Instruction::FPTrunc:
961    case Instruction::FPExt:
962    case Instruction::FPToUI:
963    case Instruction::FPToSI:
964      break; // We can't evaluate floating point casts or truncations.
965
966    case Instruction::UIToFP:
967    case Instruction::SIToFP:
968    case Instruction::BitCast:
969    case Instruction::ZExt:
970    case Instruction::SExt:
971      // If the cast is not actually changing bits, and the second operand is a
972      // null pointer, do the comparison with the pre-casted value.
973      if (V2->isNullValue() &&
974          (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
975        bool sgnd = isSigned;
976        if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
977        if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
978        return evaluateICmpRelation(CE1Op0,
979                                    Constant::getNullValue(CE1Op0->getType()),
980                                    sgnd);
981      }
982
983      // If the dest type is a pointer type, and the RHS is a constantexpr cast
984      // from the same type as the src of the LHS, evaluate the inputs.  This is
985      // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
986      // which happens a lot in compilers with tagged integers.
987      if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
988        if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
989            CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
990            CE1->getOperand(0)->getType()->isInteger()) {
991          bool sgnd = isSigned;
992          if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
993          if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
994          return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
995                                      sgnd);
996        }
997      break;
998
999    case Instruction::GetElementPtr:
1000      // Ok, since this is a getelementptr, we know that the constant has a
1001      // pointer type.  Check the various cases.
1002      if (isa<ConstantPointerNull>(V2)) {
1003        // If we are comparing a GEP to a null pointer, check to see if the base
1004        // of the GEP equals the null pointer.
1005        if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1006          if (GV->hasExternalWeakLinkage())
1007            // Weak linkage GVals could be zero or not. We're comparing that
1008            // to null pointer so its greater-or-equal
1009            return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1010          else
1011            // If its not weak linkage, the GVal must have a non-zero address
1012            // so the result is greater-than
1013            return isSigned ? ICmpInst::ICMP_SGT :  ICmpInst::ICMP_UGT;
1014        } else if (isa<ConstantPointerNull>(CE1Op0)) {
1015          // If we are indexing from a null pointer, check to see if we have any
1016          // non-zero indices.
1017          for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1018            if (!CE1->getOperand(i)->isNullValue())
1019              // Offsetting from null, must not be equal.
1020              return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1021          // Only zero indexes from null, must still be zero.
1022          return ICmpInst::ICMP_EQ;
1023        }
1024        // Otherwise, we can't really say if the first operand is null or not.
1025      } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1026        if (isa<ConstantPointerNull>(CE1Op0)) {
1027          if (CPR2->hasExternalWeakLinkage())
1028            // Weak linkage GVals could be zero or not. We're comparing it to
1029            // a null pointer, so its less-or-equal
1030            return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1031          else
1032            // If its not weak linkage, the GVal must have a non-zero address
1033            // so the result is less-than
1034            return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1035        } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1036          if (CPR1 == CPR2) {
1037            // If this is a getelementptr of the same global, then it must be
1038            // different.  Because the types must match, the getelementptr could
1039            // only have at most one index, and because we fold getelementptr's
1040            // with a single zero index, it must be nonzero.
1041            assert(CE1->getNumOperands() == 2 &&
1042                   !CE1->getOperand(1)->isNullValue() &&
1043                   "Suprising getelementptr!");
1044            return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1045          } else {
1046            // If they are different globals, we don't know what the value is,
1047            // but they can't be equal.
1048            return ICmpInst::ICMP_NE;
1049          }
1050        }
1051      } else {
1052        const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1053        const Constant *CE2Op0 = CE2->getOperand(0);
1054
1055        // There are MANY other foldings that we could perform here.  They will
1056        // probably be added on demand, as they seem needed.
1057        switch (CE2->getOpcode()) {
1058        default: break;
1059        case Instruction::GetElementPtr:
1060          // By far the most common case to handle is when the base pointers are
1061          // obviously to the same or different globals.
1062          if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1063            if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1064              return ICmpInst::ICMP_NE;
1065            // Ok, we know that both getelementptr instructions are based on the
1066            // same global.  From this, we can precisely determine the relative
1067            // ordering of the resultant pointers.
1068            unsigned i = 1;
1069
1070            // Compare all of the operands the GEP's have in common.
1071            gep_type_iterator GTI = gep_type_begin(CE1);
1072            for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1073                 ++i, ++GTI)
1074              switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1075                                 GTI.getIndexedType())) {
1076              case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1077              case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1078              case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1079              }
1080
1081            // Ok, we ran out of things they have in common.  If any leftovers
1082            // are non-zero then we have a difference, otherwise we are equal.
1083            for (; i < CE1->getNumOperands(); ++i)
1084              if (!CE1->getOperand(i)->isNullValue())
1085                if (isa<ConstantInt>(CE1->getOperand(i)))
1086                  return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1087                else
1088                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1089
1090            for (; i < CE2->getNumOperands(); ++i)
1091              if (!CE2->getOperand(i)->isNullValue())
1092                if (isa<ConstantInt>(CE2->getOperand(i)))
1093                  return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1094                else
1095                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1096            return ICmpInst::ICMP_EQ;
1097          }
1098        }
1099      }
1100    default:
1101      break;
1102    }
1103  }
1104
1105  return ICmpInst::BAD_ICMP_PREDICATE;
1106}
1107
1108Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1109                                               const Constant *C1,
1110                                               const Constant *C2) {
1111
1112  // Handle some degenerate cases first
1113  if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1114    return UndefValue::get(Type::Int1Ty);
1115
1116  // No compile-time operations on this type yet.
1117  if (C1->getType() == Type::PPC_FP128Ty)
1118    return 0;
1119
1120  // icmp eq/ne(null,GV) -> false/true
1121  if (C1->isNullValue()) {
1122    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1123      // Don't try to evaluate aliases.  External weak GV can be null.
1124      if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage())
1125        if (pred == ICmpInst::ICMP_EQ)
1126          return ConstantInt::getFalse();
1127        else if (pred == ICmpInst::ICMP_NE)
1128          return ConstantInt::getTrue();
1129  // icmp eq/ne(GV,null) -> false/true
1130  } else if (C2->isNullValue()) {
1131    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1132      // Don't try to evaluate aliases.  External weak GV can be null.
1133      if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage())
1134        if (pred == ICmpInst::ICMP_EQ)
1135          return ConstantInt::getFalse();
1136        else if (pred == ICmpInst::ICMP_NE)
1137          return ConstantInt::getTrue();
1138  }
1139
1140  if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1141    APInt V1 = cast<ConstantInt>(C1)->getValue();
1142    APInt V2 = cast<ConstantInt>(C2)->getValue();
1143    switch (pred) {
1144    default: assert(0 && "Invalid ICmp Predicate"); return 0;
1145    case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1146    case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1147    case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1148    case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1149    case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1150    case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1151    case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1152    case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1153    case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1154    case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1155    }
1156  } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1157    APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1158    APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1159    APFloat::cmpResult R = C1V.compare(C2V);
1160    switch (pred) {
1161    default: assert(0 && "Invalid FCmp Predicate"); return 0;
1162    case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1163    case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue();
1164    case FCmpInst::FCMP_UNO:
1165      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
1166    case FCmpInst::FCMP_ORD:
1167      return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
1168    case FCmpInst::FCMP_UEQ:
1169      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1170                                            R==APFloat::cmpEqual);
1171    case FCmpInst::FCMP_OEQ:
1172      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
1173    case FCmpInst::FCMP_UNE:
1174      return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
1175    case FCmpInst::FCMP_ONE:
1176      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1177                                            R==APFloat::cmpGreaterThan);
1178    case FCmpInst::FCMP_ULT:
1179      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1180                                            R==APFloat::cmpLessThan);
1181    case FCmpInst::FCMP_OLT:
1182      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
1183    case FCmpInst::FCMP_UGT:
1184      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1185                                            R==APFloat::cmpGreaterThan);
1186    case FCmpInst::FCMP_OGT:
1187      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
1188    case FCmpInst::FCMP_ULE:
1189      return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
1190    case FCmpInst::FCMP_OLE:
1191      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1192                                            R==APFloat::cmpEqual);
1193    case FCmpInst::FCMP_UGE:
1194      return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
1195    case FCmpInst::FCMP_OGE:
1196      return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1197                                            R==APFloat::cmpEqual);
1198    }
1199  } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1200    if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1201      if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1202        for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1203          Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1204              const_cast<Constant*>(CP1->getOperand(i)),
1205              const_cast<Constant*>(CP2->getOperand(i)));
1206          if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1207            return CB;
1208        }
1209        // Otherwise, could not decide from any element pairs.
1210        return 0;
1211      } else if (pred == ICmpInst::ICMP_EQ) {
1212        for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1213          Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1214              const_cast<Constant*>(CP1->getOperand(i)),
1215              const_cast<Constant*>(CP2->getOperand(i)));
1216          if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1217            return CB;
1218        }
1219        // Otherwise, could not decide from any element pairs.
1220        return 0;
1221      }
1222    }
1223  }
1224
1225  if (C1->getType()->isFloatingPoint()) {
1226    switch (evaluateFCmpRelation(C1, C2)) {
1227    default: assert(0 && "Unknown relation!");
1228    case FCmpInst::FCMP_UNO:
1229    case FCmpInst::FCMP_ORD:
1230    case FCmpInst::FCMP_UEQ:
1231    case FCmpInst::FCMP_UNE:
1232    case FCmpInst::FCMP_ULT:
1233    case FCmpInst::FCMP_UGT:
1234    case FCmpInst::FCMP_ULE:
1235    case FCmpInst::FCMP_UGE:
1236    case FCmpInst::FCMP_TRUE:
1237    case FCmpInst::FCMP_FALSE:
1238    case FCmpInst::BAD_FCMP_PREDICATE:
1239      break; // Couldn't determine anything about these constants.
1240    case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1241      return ConstantInt::get(Type::Int1Ty,
1242          pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1243          pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1244          pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1245    case FCmpInst::FCMP_OLT: // We know that C1 < C2
1246      return ConstantInt::get(Type::Int1Ty,
1247          pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1248          pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1249          pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1250    case FCmpInst::FCMP_OGT: // We know that C1 > C2
1251      return ConstantInt::get(Type::Int1Ty,
1252          pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1253          pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1254          pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1255    case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1256      // We can only partially decide this relation.
1257      if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1258        return ConstantInt::getFalse();
1259      if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1260        return ConstantInt::getTrue();
1261      break;
1262    case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1263      // We can only partially decide this relation.
1264      if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1265        return ConstantInt::getFalse();
1266      if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1267        return ConstantInt::getTrue();
1268      break;
1269    case ICmpInst::ICMP_NE: // We know that C1 != C2
1270      // We can only partially decide this relation.
1271      if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1272        return ConstantInt::getFalse();
1273      if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1274        return ConstantInt::getTrue();
1275      break;
1276    }
1277  } else {
1278    // Evaluate the relation between the two constants, per the predicate.
1279    switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1280    default: assert(0 && "Unknown relational!");
1281    case ICmpInst::BAD_ICMP_PREDICATE:
1282      break;  // Couldn't determine anything about these constants.
1283    case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1284      // If we know the constants are equal, we can decide the result of this
1285      // computation precisely.
1286      return ConstantInt::get(Type::Int1Ty,
1287                              pred == ICmpInst::ICMP_EQ  ||
1288                              pred == ICmpInst::ICMP_ULE ||
1289                              pred == ICmpInst::ICMP_SLE ||
1290                              pred == ICmpInst::ICMP_UGE ||
1291                              pred == ICmpInst::ICMP_SGE);
1292    case ICmpInst::ICMP_ULT:
1293      // If we know that C1 < C2, we can decide the result of this computation
1294      // precisely.
1295      return ConstantInt::get(Type::Int1Ty,
1296                              pred == ICmpInst::ICMP_ULT ||
1297                              pred == ICmpInst::ICMP_NE  ||
1298                              pred == ICmpInst::ICMP_ULE);
1299    case ICmpInst::ICMP_SLT:
1300      // If we know that C1 < C2, we can decide the result of this computation
1301      // precisely.
1302      return ConstantInt::get(Type::Int1Ty,
1303                              pred == ICmpInst::ICMP_SLT ||
1304                              pred == ICmpInst::ICMP_NE  ||
1305                              pred == ICmpInst::ICMP_SLE);
1306    case ICmpInst::ICMP_UGT:
1307      // If we know that C1 > C2, we can decide the result of this computation
1308      // precisely.
1309      return ConstantInt::get(Type::Int1Ty,
1310                              pred == ICmpInst::ICMP_UGT ||
1311                              pred == ICmpInst::ICMP_NE  ||
1312                              pred == ICmpInst::ICMP_UGE);
1313    case ICmpInst::ICMP_SGT:
1314      // If we know that C1 > C2, we can decide the result of this computation
1315      // precisely.
1316      return ConstantInt::get(Type::Int1Ty,
1317                              pred == ICmpInst::ICMP_SGT ||
1318                              pred == ICmpInst::ICMP_NE  ||
1319                              pred == ICmpInst::ICMP_SGE);
1320    case ICmpInst::ICMP_ULE:
1321      // If we know that C1 <= C2, we can only partially decide this relation.
1322      if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1323      if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1324      break;
1325    case ICmpInst::ICMP_SLE:
1326      // If we know that C1 <= C2, we can only partially decide this relation.
1327      if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1328      if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1329      break;
1330
1331    case ICmpInst::ICMP_UGE:
1332      // If we know that C1 >= C2, we can only partially decide this relation.
1333      if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1334      if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1335      break;
1336    case ICmpInst::ICMP_SGE:
1337      // If we know that C1 >= C2, we can only partially decide this relation.
1338      if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1339      if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1340      break;
1341
1342    case ICmpInst::ICMP_NE:
1343      // If we know that C1 != C2, we can only partially decide this relation.
1344      if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1345      if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1346      break;
1347    }
1348
1349    if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1350      // If C2 is a constant expr and C1 isn't, flop them around and fold the
1351      // other way if possible.
1352      switch (pred) {
1353      case ICmpInst::ICMP_EQ:
1354      case ICmpInst::ICMP_NE:
1355        // No change of predicate required.
1356        return ConstantFoldCompareInstruction(pred, C2, C1);
1357
1358      case ICmpInst::ICMP_ULT:
1359      case ICmpInst::ICMP_SLT:
1360      case ICmpInst::ICMP_UGT:
1361      case ICmpInst::ICMP_SGT:
1362      case ICmpInst::ICMP_ULE:
1363      case ICmpInst::ICMP_SLE:
1364      case ICmpInst::ICMP_UGE:
1365      case ICmpInst::ICMP_SGE:
1366        // Change the predicate as necessary to swap the operands.
1367        pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1368        return ConstantFoldCompareInstruction(pred, C2, C1);
1369
1370      default:  // These predicates cannot be flopped around.
1371        break;
1372      }
1373    }
1374  }
1375  return 0;
1376}
1377
1378Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1379                                          Constant* const *Idxs,
1380                                          unsigned NumIdx) {
1381  if (NumIdx == 0 ||
1382      (NumIdx == 1 && Idxs[0]->isNullValue()))
1383    return const_cast<Constant*>(C);
1384
1385  if (isa<UndefValue>(C)) {
1386    const PointerType *Ptr = cast<PointerType>(C->getType());
1387    const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1388                                                       (Value **)Idxs,
1389                                                       (Value **)Idxs+NumIdx,
1390                                                       true);
1391    assert(Ty != 0 && "Invalid indices for GEP!");
1392    return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1393  }
1394
1395  Constant *Idx0 = Idxs[0];
1396  if (C->isNullValue()) {
1397    bool isNull = true;
1398    for (unsigned i = 0, e = NumIdx; i != e; ++i)
1399      if (!Idxs[i]->isNullValue()) {
1400        isNull = false;
1401        break;
1402      }
1403    if (isNull) {
1404      const PointerType *Ptr = cast<PointerType>(C->getType());
1405      const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1406                                                         (Value**)Idxs,
1407                                                         (Value**)Idxs+NumIdx,
1408                                                         true);
1409      assert(Ty != 0 && "Invalid indices for GEP!");
1410      return
1411        ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
1412    }
1413  }
1414
1415  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1416    // Combine Indices - If the source pointer to this getelementptr instruction
1417    // is a getelementptr instruction, combine the indices of the two
1418    // getelementptr instructions into a single instruction.
1419    //
1420    if (CE->getOpcode() == Instruction::GetElementPtr) {
1421      const Type *LastTy = 0;
1422      for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1423           I != E; ++I)
1424        LastTy = *I;
1425
1426      if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1427        SmallVector<Value*, 16> NewIndices;
1428        NewIndices.reserve(NumIdx + CE->getNumOperands());
1429        for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1430          NewIndices.push_back(CE->getOperand(i));
1431
1432        // Add the last index of the source with the first index of the new GEP.
1433        // Make sure to handle the case when they are actually different types.
1434        Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1435        // Otherwise it must be an array.
1436        if (!Idx0->isNullValue()) {
1437          const Type *IdxTy = Combined->getType();
1438          if (IdxTy != Idx0->getType()) {
1439            Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1440            Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1441                                                          Type::Int64Ty);
1442            Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1443          } else {
1444            Combined =
1445              ConstantExpr::get(Instruction::Add, Idx0, Combined);
1446          }
1447        }
1448
1449        NewIndices.push_back(Combined);
1450        NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1451        return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1452                                              NewIndices.size());
1453      }
1454    }
1455
1456    // Implement folding of:
1457    //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1458    //                        long 0, long 0)
1459    // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1460    //
1461    if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1462      if (const PointerType *SPT =
1463          dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1464        if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1465          if (const ArrayType *CAT =
1466        dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1467            if (CAT->getElementType() == SAT->getElementType())
1468              return ConstantExpr::getGetElementPtr(
1469                      (Constant*)CE->getOperand(0), Idxs, NumIdx);
1470    }
1471
1472    // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1473    // Into: inttoptr (i64 0 to i8*)
1474    // This happens with pointers to member functions in C++.
1475    if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1476        isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1477        cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1478      Constant *Base = CE->getOperand(0);
1479      Constant *Offset = Idxs[0];
1480
1481      // Convert the smaller integer to the larger type.
1482      if (Offset->getType()->getPrimitiveSizeInBits() <
1483          Base->getType()->getPrimitiveSizeInBits())
1484        Offset = ConstantExpr::getSExt(Offset, Base->getType());
1485      else if (Base->getType()->getPrimitiveSizeInBits() <
1486               Offset->getType()->getPrimitiveSizeInBits())
1487        Base = ConstantExpr::getZExt(Base, Base->getType());
1488
1489      Base = ConstantExpr::getAdd(Base, Offset);
1490      return ConstantExpr::getIntToPtr(Base, CE->getType());
1491    }
1492  }
1493  return 0;
1494}
1495
1496