continue making the world safe for ConstantDataVector. At this point,
[oota-llvm.git] / lib / VMCore / ConstantFold.cpp
1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // 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 // pieces that don't need TargetData, and the pieces that do. This is to avoid
16 // a dependence in VMCore on Target.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "ConstantFold.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Operator.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include <limits>
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 //                ConstantFold*Instruction Implementations
39 //===----------------------------------------------------------------------===//
40
41 /// BitCastConstantVector - Convert the specified vector Constant node to the
42 /// specified vector type.  At this point, we know that the elements of the
43 /// input vector constant are all simple integer or FP values.
44 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
45
46   if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
47   if (CV->isNullValue()) return Constant::getNullValue(DstTy);
48
49   // If this cast changes element count then we can't handle it here:
50   // doing so requires endianness information.  This should be handled by
51   // Analysis/ConstantFolding.cpp
52   unsigned NumElts = DstTy->getNumElements();
53   if (NumElts != CV->getType()->getVectorNumElements())
54     return 0;
55   
56   Type *DstEltTy = DstTy->getElementType();
57
58   // Check to verify that all elements of the input are simple.
59   SmallVector<Constant*, 16> Result;
60   for (unsigned i = 0; i != NumElts; ++i) {
61     Constant *C = CV->getAggregateElement(i);
62     if (C == 0) return 0;
63     C = ConstantExpr::getBitCast(C, DstEltTy);
64     if (isa<ConstantExpr>(C)) return 0;
65     Result.push_back(C);
66   }
67
68   return ConstantVector::get(Result);
69 }
70
71 /// This function determines which opcode to use to fold two constant cast 
72 /// expressions together. It uses CastInst::isEliminableCastPair to determine
73 /// the opcode. Consequently its just a wrapper around that function.
74 /// @brief Determine if it is valid to fold a cast of a cast
75 static unsigned
76 foldConstantCastPair(
77   unsigned opc,          ///< opcode of the second cast constant expression
78   ConstantExpr *Op,      ///< the first cast constant expression
79   Type *DstTy      ///< desintation type of the first cast
80 ) {
81   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
82   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
83   assert(CastInst::isCast(opc) && "Invalid cast opcode");
84
85   // The the types and opcodes for the two Cast constant expressions
86   Type *SrcTy = Op->getOperand(0)->getType();
87   Type *MidTy = Op->getType();
88   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
89   Instruction::CastOps secondOp = Instruction::CastOps(opc);
90
91   // Let CastInst::isEliminableCastPair do the heavy lifting.
92   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
93                                         Type::getInt64Ty(DstTy->getContext()));
94 }
95
96 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
97   Type *SrcTy = V->getType();
98   if (SrcTy == DestTy)
99     return V; // no-op cast
100
101   // Check to see if we are casting a pointer to an aggregate to a pointer to
102   // the first element.  If so, return the appropriate GEP instruction.
103   if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
104     if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
105       if (PTy->getAddressSpace() == DPTy->getAddressSpace()
106           && DPTy->getElementType()->isSized()) {
107         SmallVector<Value*, 8> IdxList;
108         Value *Zero =
109           Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
110         IdxList.push_back(Zero);
111         Type *ElTy = PTy->getElementType();
112         while (ElTy != DPTy->getElementType()) {
113           if (StructType *STy = dyn_cast<StructType>(ElTy)) {
114             if (STy->getNumElements() == 0) break;
115             ElTy = STy->getElementType(0);
116             IdxList.push_back(Zero);
117           } else if (SequentialType *STy = 
118                      dyn_cast<SequentialType>(ElTy)) {
119             if (ElTy->isPointerTy()) break;  // Can't index into pointers!
120             ElTy = STy->getElementType();
121             IdxList.push_back(Zero);
122           } else {
123             break;
124           }
125         }
126
127         if (ElTy == DPTy->getElementType())
128           // This GEP is inbounds because all indices are zero.
129           return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
130       }
131
132   // Handle casts from one vector constant to another.  We know that the src 
133   // and dest type have the same size (otherwise its an illegal cast).
134   if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
135     if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
136       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
137              "Not cast between same sized vectors!");
138       SrcTy = NULL;
139       // First, check for null.  Undef is already handled.
140       if (isa<ConstantAggregateZero>(V))
141         return Constant::getNullValue(DestTy);
142
143       // Handle ConstantVector and ConstantAggregateVector.
144       return BitCastConstantVector(V, DestPTy);
145     }
146
147     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
148     // This allows for other simplifications (although some of them
149     // can only be handled by Analysis/ConstantFolding.cpp).
150     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
151       return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
152   }
153
154   // Finally, implement bitcast folding now.   The code below doesn't handle
155   // bitcast right.
156   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
157     return ConstantPointerNull::get(cast<PointerType>(DestTy));
158
159   // Handle integral constant input.
160   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
161     if (DestTy->isIntegerTy())
162       // Integral -> Integral. This is a no-op because the bit widths must
163       // be the same. Consequently, we just fold to V.
164       return V;
165
166     if (DestTy->isFloatingPointTy())
167       return ConstantFP::get(DestTy->getContext(),
168                              APFloat(CI->getValue(),
169                                      !DestTy->isPPC_FP128Ty()));
170
171     // Otherwise, can't fold this (vector?)
172     return 0;
173   }
174
175   // Handle ConstantFP input: FP -> Integral.
176   if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
177     return ConstantInt::get(FP->getContext(),
178                             FP->getValueAPF().bitcastToAPInt());
179
180   return 0;
181 }
182
183
184 /// ExtractConstantBytes - V is an integer constant which only has a subset of
185 /// its bytes used.  The bytes used are indicated by ByteStart (which is the
186 /// first byte used, counting from the least significant byte) and ByteSize,
187 /// which is the number of bytes used.
188 ///
189 /// This function analyzes the specified constant to see if the specified byte
190 /// range can be returned as a simplified constant.  If so, the constant is
191 /// returned, otherwise null is returned.
192 /// 
193 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
194                                       unsigned ByteSize) {
195   assert(C->getType()->isIntegerTy() &&
196          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
197          "Non-byte sized integer input");
198   unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
199   assert(ByteSize && "Must be accessing some piece");
200   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
201   assert(ByteSize != CSize && "Should not extract everything");
202   
203   // Constant Integers are simple.
204   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
205     APInt V = CI->getValue();
206     if (ByteStart)
207       V = V.lshr(ByteStart*8);
208     V = V.trunc(ByteSize*8);
209     return ConstantInt::get(CI->getContext(), V);
210   }
211   
212   // In the input is a constant expr, we might be able to recursively simplify.
213   // If not, we definitely can't do anything.
214   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
215   if (CE == 0) return 0;
216   
217   switch (CE->getOpcode()) {
218   default: return 0;
219   case Instruction::Or: {
220     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
221     if (RHS == 0)
222       return 0;
223     
224     // X | -1 -> -1.
225     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
226       if (RHSC->isAllOnesValue())
227         return RHSC;
228     
229     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
230     if (LHS == 0)
231       return 0;
232     return ConstantExpr::getOr(LHS, RHS);
233   }
234   case Instruction::And: {
235     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
236     if (RHS == 0)
237       return 0;
238     
239     // X & 0 -> 0.
240     if (RHS->isNullValue())
241       return RHS;
242     
243     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
244     if (LHS == 0)
245       return 0;
246     return ConstantExpr::getAnd(LHS, RHS);
247   }
248   case Instruction::LShr: {
249     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
250     if (Amt == 0)
251       return 0;
252     unsigned ShAmt = Amt->getZExtValue();
253     // Cannot analyze non-byte shifts.
254     if ((ShAmt & 7) != 0)
255       return 0;
256     ShAmt >>= 3;
257     
258     // If the extract is known to be all zeros, return zero.
259     if (ByteStart >= CSize-ShAmt)
260       return Constant::getNullValue(IntegerType::get(CE->getContext(),
261                                                      ByteSize*8));
262     // If the extract is known to be fully in the input, extract it.
263     if (ByteStart+ByteSize+ShAmt <= CSize)
264       return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
265     
266     // TODO: Handle the 'partially zero' case.
267     return 0;
268   }
269     
270   case Instruction::Shl: {
271     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
272     if (Amt == 0)
273       return 0;
274     unsigned ShAmt = Amt->getZExtValue();
275     // Cannot analyze non-byte shifts.
276     if ((ShAmt & 7) != 0)
277       return 0;
278     ShAmt >>= 3;
279     
280     // If the extract is known to be all zeros, return zero.
281     if (ByteStart+ByteSize <= ShAmt)
282       return Constant::getNullValue(IntegerType::get(CE->getContext(),
283                                                      ByteSize*8));
284     // If the extract is known to be fully in the input, extract it.
285     if (ByteStart >= ShAmt)
286       return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
287     
288     // TODO: Handle the 'partially zero' case.
289     return 0;
290   }
291       
292   case Instruction::ZExt: {
293     unsigned SrcBitSize =
294       cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
295     
296     // If extracting something that is completely zero, return 0.
297     if (ByteStart*8 >= SrcBitSize)
298       return Constant::getNullValue(IntegerType::get(CE->getContext(),
299                                                      ByteSize*8));
300
301     // If exactly extracting the input, return it.
302     if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
303       return CE->getOperand(0);
304     
305     // If extracting something completely in the input, if if the input is a
306     // multiple of 8 bits, recurse.
307     if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
308       return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
309       
310     // Otherwise, if extracting a subset of the input, which is not multiple of
311     // 8 bits, do a shift and trunc to get the bits.
312     if ((ByteStart+ByteSize)*8 < SrcBitSize) {
313       assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
314       Constant *Res = CE->getOperand(0);
315       if (ByteStart)
316         Res = ConstantExpr::getLShr(Res, 
317                                  ConstantInt::get(Res->getType(), ByteStart*8));
318       return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
319                                                           ByteSize*8));
320     }
321     
322     // TODO: Handle the 'partially zero' case.
323     return 0;
324   }
325   }
326 }
327
328 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
329 /// on Ty, with any known factors factored out. If Folded is false,
330 /// return null if no factoring was possible, to avoid endlessly
331 /// bouncing an unfoldable expression back into the top-level folder.
332 ///
333 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
334                                  bool Folded) {
335   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
336     Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
337     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
338     return ConstantExpr::getNUWMul(E, N);
339   }
340
341   if (StructType *STy = dyn_cast<StructType>(Ty))
342     if (!STy->isPacked()) {
343       unsigned NumElems = STy->getNumElements();
344       // An empty struct has size zero.
345       if (NumElems == 0)
346         return ConstantExpr::getNullValue(DestTy);
347       // Check for a struct with all members having the same size.
348       Constant *MemberSize =
349         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
350       bool AllSame = true;
351       for (unsigned i = 1; i != NumElems; ++i)
352         if (MemberSize !=
353             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
354           AllSame = false;
355           break;
356         }
357       if (AllSame) {
358         Constant *N = ConstantInt::get(DestTy, NumElems);
359         return ConstantExpr::getNUWMul(MemberSize, N);
360       }
361     }
362
363   // Pointer size doesn't depend on the pointee type, so canonicalize them
364   // to an arbitrary pointee.
365   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
366     if (!PTy->getElementType()->isIntegerTy(1))
367       return
368         getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
369                                          PTy->getAddressSpace()),
370                         DestTy, true);
371
372   // If there's no interesting folding happening, bail so that we don't create
373   // a constant that looks like it needs folding but really doesn't.
374   if (!Folded)
375     return 0;
376
377   // Base case: Get a regular sizeof expression.
378   Constant *C = ConstantExpr::getSizeOf(Ty);
379   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
380                                                     DestTy, false),
381                             C, DestTy);
382   return C;
383 }
384
385 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
386 /// on Ty, with any known factors factored out. If Folded is false,
387 /// return null if no factoring was possible, to avoid endlessly
388 /// bouncing an unfoldable expression back into the top-level folder.
389 ///
390 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
391                                   bool Folded) {
392   // The alignment of an array is equal to the alignment of the
393   // array element. Note that this is not always true for vectors.
394   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
395     Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
396     C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
397                                                       DestTy,
398                                                       false),
399                               C, DestTy);
400     return C;
401   }
402
403   if (StructType *STy = dyn_cast<StructType>(Ty)) {
404     // Packed structs always have an alignment of 1.
405     if (STy->isPacked())
406       return ConstantInt::get(DestTy, 1);
407
408     // Otherwise, struct alignment is the maximum alignment of any member.
409     // Without target data, we can't compare much, but we can check to see
410     // if all the members have the same alignment.
411     unsigned NumElems = STy->getNumElements();
412     // An empty struct has minimal alignment.
413     if (NumElems == 0)
414       return ConstantInt::get(DestTy, 1);
415     // Check for a struct with all members having the same alignment.
416     Constant *MemberAlign =
417       getFoldedAlignOf(STy->getElementType(0), DestTy, true);
418     bool AllSame = true;
419     for (unsigned i = 1; i != NumElems; ++i)
420       if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
421         AllSame = false;
422         break;
423       }
424     if (AllSame)
425       return MemberAlign;
426   }
427
428   // Pointer alignment doesn't depend on the pointee type, so canonicalize them
429   // to an arbitrary pointee.
430   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
431     if (!PTy->getElementType()->isIntegerTy(1))
432       return
433         getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
434                                                            1),
435                                           PTy->getAddressSpace()),
436                          DestTy, true);
437
438   // If there's no interesting folding happening, bail so that we don't create
439   // a constant that looks like it needs folding but really doesn't.
440   if (!Folded)
441     return 0;
442
443   // Base case: Get a regular alignof expression.
444   Constant *C = ConstantExpr::getAlignOf(Ty);
445   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
446                                                     DestTy, false),
447                             C, DestTy);
448   return C;
449 }
450
451 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
452 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
453 /// return null if no factoring was possible, to avoid endlessly
454 /// bouncing an unfoldable expression back into the top-level folder.
455 ///
456 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
457                                    Type *DestTy,
458                                    bool Folded) {
459   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
460     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
461                                                                 DestTy, false),
462                                         FieldNo, DestTy);
463     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
464     return ConstantExpr::getNUWMul(E, N);
465   }
466
467   if (StructType *STy = dyn_cast<StructType>(Ty))
468     if (!STy->isPacked()) {
469       unsigned NumElems = STy->getNumElements();
470       // An empty struct has no members.
471       if (NumElems == 0)
472         return 0;
473       // Check for a struct with all members having the same size.
474       Constant *MemberSize =
475         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
476       bool AllSame = true;
477       for (unsigned i = 1; i != NumElems; ++i)
478         if (MemberSize !=
479             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
480           AllSame = false;
481           break;
482         }
483       if (AllSame) {
484         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
485                                                                     false,
486                                                                     DestTy,
487                                                                     false),
488                                             FieldNo, DestTy);
489         return ConstantExpr::getNUWMul(MemberSize, N);
490       }
491     }
492
493   // If there's no interesting folding happening, bail so that we don't create
494   // a constant that looks like it needs folding but really doesn't.
495   if (!Folded)
496     return 0;
497
498   // Base case: Get a regular offsetof expression.
499   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
500   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
501                                                     DestTy, false),
502                             C, DestTy);
503   return C;
504 }
505
506 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
507                                             Type *DestTy) {
508   if (isa<UndefValue>(V)) {
509     // zext(undef) = 0, because the top bits will be zero.
510     // sext(undef) = 0, because the top bits will all be the same.
511     // [us]itofp(undef) = 0, because the result value is bounded.
512     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
513         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
514       return Constant::getNullValue(DestTy);
515     return UndefValue::get(DestTy);
516   }
517
518   // No compile-time operations on this type yet.
519   if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
520     return 0;
521
522   if (V->isNullValue() && !DestTy->isX86_MMXTy())
523     return Constant::getNullValue(DestTy);
524
525   // If the cast operand is a constant expression, there's a few things we can
526   // do to try to simplify it.
527   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
528     if (CE->isCast()) {
529       // Try hard to fold cast of cast because they are often eliminable.
530       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
531         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
532     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
533       // If all of the indexes in the GEP are null values, there is no pointer
534       // adjustment going on.  We might as well cast the source pointer.
535       bool isAllNull = true;
536       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
537         if (!CE->getOperand(i)->isNullValue()) {
538           isAllNull = false;
539           break;
540         }
541       if (isAllNull)
542         // This is casting one pointer type to another, always BitCast
543         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
544     }
545   }
546
547   // If the cast operand is a constant vector, perform the cast by
548   // operating on each element. In the cast of bitcasts, the element
549   // count may be mismatched; don't attempt to handle that here.
550   if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
551       DestTy->isVectorTy() &&
552       DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
553     SmallVector<Constant*, 16> res;
554     VectorType *DestVecTy = cast<VectorType>(DestTy);
555     Type *DstEltTy = DestVecTy->getElementType();
556     for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i)
557       res.push_back(ConstantExpr::getCast(opc,
558                                           V->getAggregateElement(i), DstEltTy));
559     return ConstantVector::get(res);
560   }
561
562   // We actually have to do a cast now. Perform the cast according to the
563   // opcode specified.
564   switch (opc) {
565   default:
566     llvm_unreachable("Failed to cast constant expression");
567   case Instruction::FPTrunc:
568   case Instruction::FPExt:
569     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
570       bool ignored;
571       APFloat Val = FPC->getValueAPF();
572       Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
573                   DestTy->isFloatTy() ? APFloat::IEEEsingle :
574                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
575                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
576                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
577                   APFloat::Bogus,
578                   APFloat::rmNearestTiesToEven, &ignored);
579       return ConstantFP::get(V->getContext(), Val);
580     }
581     return 0; // Can't fold.
582   case Instruction::FPToUI: 
583   case Instruction::FPToSI:
584     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
585       const APFloat &V = FPC->getValueAPF();
586       bool ignored;
587       uint64_t x[2]; 
588       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
589       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
590                                 APFloat::rmTowardZero, &ignored);
591       APInt Val(DestBitWidth, x);
592       return ConstantInt::get(FPC->getContext(), Val);
593     }
594     return 0; // Can't fold.
595   case Instruction::IntToPtr:   //always treated as unsigned
596     if (V->isNullValue())       // Is it an integral null value?
597       return ConstantPointerNull::get(cast<PointerType>(DestTy));
598     return 0;                   // Other pointer types cannot be casted
599   case Instruction::PtrToInt:   // always treated as unsigned
600     // Is it a null pointer value?
601     if (V->isNullValue())
602       return ConstantInt::get(DestTy, 0);
603     // If this is a sizeof-like expression, pull out multiplications by
604     // known factors to expose them to subsequent folding. If it's an
605     // alignof-like expression, factor out known factors.
606     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607       if (CE->getOpcode() == Instruction::GetElementPtr &&
608           CE->getOperand(0)->isNullValue()) {
609         Type *Ty =
610           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
611         if (CE->getNumOperands() == 2) {
612           // Handle a sizeof-like expression.
613           Constant *Idx = CE->getOperand(1);
614           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
615           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
616             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
617                                                                 DestTy, false),
618                                         Idx, DestTy);
619             return ConstantExpr::getMul(C, Idx);
620           }
621         } else if (CE->getNumOperands() == 3 &&
622                    CE->getOperand(1)->isNullValue()) {
623           // Handle an alignof-like expression.
624           if (StructType *STy = dyn_cast<StructType>(Ty))
625             if (!STy->isPacked()) {
626               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
627               if (CI->isOne() &&
628                   STy->getNumElements() == 2 &&
629                   STy->getElementType(0)->isIntegerTy(1)) {
630                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
631               }
632             }
633           // Handle an offsetof-like expression.
634           if (Ty->isStructTy() || Ty->isArrayTy()) {
635             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
636                                                 DestTy, false))
637               return C;
638           }
639         }
640       }
641     // Other pointer types cannot be casted
642     return 0;
643   case Instruction::UIToFP:
644   case Instruction::SIToFP:
645     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
646       APInt api = CI->getValue();
647       APFloat apf(APInt::getNullValue(DestTy->getPrimitiveSizeInBits()), true);
648       (void)apf.convertFromAPInt(api, 
649                                  opc==Instruction::SIToFP,
650                                  APFloat::rmNearestTiesToEven);
651       return ConstantFP::get(V->getContext(), apf);
652     }
653     return 0;
654   case Instruction::ZExt:
655     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
656       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
657       return ConstantInt::get(V->getContext(),
658                               CI->getValue().zext(BitWidth));
659     }
660     return 0;
661   case Instruction::SExt:
662     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
663       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
664       return ConstantInt::get(V->getContext(),
665                               CI->getValue().sext(BitWidth));
666     }
667     return 0;
668   case Instruction::Trunc: {
669     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
670     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
671       return ConstantInt::get(V->getContext(),
672                               CI->getValue().trunc(DestBitWidth));
673     }
674     
675     // The input must be a constantexpr.  See if we can simplify this based on
676     // the bytes we are demanding.  Only do this if the source and dest are an
677     // even multiple of a byte.
678     if ((DestBitWidth & 7) == 0 &&
679         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
680       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
681         return Res;
682       
683     return 0;
684   }
685   case Instruction::BitCast:
686     return FoldBitCast(V, DestTy);
687   }
688 }
689
690 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
691                                               Constant *V1, Constant *V2) {
692   // Check for i1 and vector true/false conditions.
693   if (Cond->isNullValue()) return V2;
694   if (Cond->isAllOnesValue()) return V1;
695
696   // FIXME: Remove ConstantVector
697   // If the condition is a vector constant, fold the result elementwise.
698   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
699     SmallVector<Constant*, 16> Result;
700     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
701       ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
702       if (Cond == 0) break;
703       
704       Constant *Res = (Cond->getZExtValue() ? V2 : V1)->getAggregateElement(i);
705       if (Res == 0) break;
706       Result.push_back(Res);
707     }
708     
709     // If we were able to build the vector, return it.
710     if (Result.size() == V1->getType()->getVectorNumElements())
711       return ConstantVector::get(Result);
712   }
713   if (ConstantDataVector *CondV = dyn_cast<ConstantDataVector>(Cond)) {
714     SmallVector<Constant*, 16> Result;
715     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
716       uint64_t Cond = CondV->getElementAsInteger(i);
717       
718       Constant *Res = (Cond ? V2 : V1)->getAggregateElement(i);
719       if (Res == 0) break;
720       Result.push_back(Res);
721     }
722     
723     // If we were able to build the vector, return it.
724     if (Result.size() == V1->getType()->getVectorNumElements())
725       return ConstantVector::get(Result);
726   }
727
728
729   if (isa<UndefValue>(Cond)) {
730     if (isa<UndefValue>(V1)) return V1;
731     return V2;
732   }
733   if (isa<UndefValue>(V1)) return V2;
734   if (isa<UndefValue>(V2)) return V1;
735   if (V1 == V2) return V1;
736
737   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
738     if (TrueVal->getOpcode() == Instruction::Select)
739       if (TrueVal->getOperand(0) == Cond)
740         return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
741   }
742   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
743     if (FalseVal->getOpcode() == Instruction::Select)
744       if (FalseVal->getOperand(0) == Cond)
745         return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
746   }
747
748   return 0;
749 }
750
751 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
752                                                       Constant *Idx) {
753   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
754     return UndefValue::get(Val->getType()->getVectorElementType());
755   if (Val->isNullValue())  // ee(zero, x) -> zero
756     return Constant::getNullValue(Val->getType()->getVectorElementType());
757   // ee({w,x,y,z}, undef) -> undef
758   if (isa<UndefValue>(Idx))
759     return UndefValue::get(Val->getType()->getVectorElementType());
760
761   if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
762     uint64_t Index = CIdx->getZExtValue();
763     // ee({w,x,y,z}, wrong_value) -> undef
764     if (Index >= Val->getType()->getVectorNumElements())
765       return UndefValue::get(Val->getType()->getVectorElementType());
766     return Val->getAggregateElement(Index);
767   }
768   return 0;
769 }
770
771 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
772                                                      Constant *Elt,
773                                                      Constant *Idx) {
774   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
775   if (!CIdx) return 0;
776   const APInt &IdxVal = CIdx->getValue();
777   
778   SmallVector<Constant*, 16> Result;
779   for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
780     if (i == IdxVal) {
781       Result.push_back(Elt);
782       continue;
783     }
784     
785     if (Constant *C = Val->getAggregateElement(i))
786       Result.push_back(C);
787     else
788       return 0;
789   }
790   
791   return ConstantVector::get(Result);
792 }
793
794 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
795                                                      Constant *V2,
796                                                      Constant *Mask) {
797   // Undefined shuffle mask -> undefined value.
798   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
799
800   // Don't break the bitcode reader hack.
801   if (isa<ConstantExpr>(Mask)) return 0;
802   
803   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
804   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
805   Type *EltTy = V1->getType()->getVectorElementType();
806
807   // Loop over the shuffle mask, evaluating each element.
808   SmallVector<Constant*, 32> Result;
809   for (unsigned i = 0; i != MaskNumElts; ++i) {
810     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
811     if (Elt == -1) {
812       Result.push_back(UndefValue::get(EltTy));
813       continue;
814     }
815     Constant *InElt;
816     if (unsigned(Elt) >= SrcNumElts*2)
817       InElt = UndefValue::get(EltTy);
818     else if (unsigned(Elt) >= SrcNumElts)
819       InElt = V2->getAggregateElement(Elt - SrcNumElts);
820     else
821       InElt = V1->getAggregateElement(Elt);
822     if (InElt == 0) return 0;
823     Result.push_back(InElt);
824   }
825
826   return ConstantVector::get(Result);
827 }
828
829 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
830                                                     ArrayRef<unsigned> Idxs) {
831   // Base case: no indices, so return the entire value.
832   if (Idxs.empty())
833     return Agg;
834
835   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
836     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
837
838   return 0;
839 }
840
841 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
842                                                    Constant *Val,
843                                                    ArrayRef<unsigned> Idxs) {
844   // Base case: no indices, so replace the entire value.
845   if (Idxs.empty())
846     return Val;
847
848   unsigned NumElts;
849   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
850     NumElts = ST->getNumElements();
851   else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
852     NumElts = AT->getNumElements();
853   else
854     NumElts = AT->getVectorNumElements();
855   
856   SmallVector<Constant*, 32> Result;
857   for (unsigned i = 0; i != NumElts; ++i) {
858     Constant *C = Agg->getAggregateElement(i);
859     if (C == 0) return 0;
860     
861     if (Idxs[0] == i)
862       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
863     
864     Result.push_back(C);
865   }
866   
867   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
868     return ConstantStruct::get(ST, Result);
869   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
870     return ConstantArray::get(AT, Result);
871   return ConstantVector::get(Result);
872 }
873
874
875 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
876                                               Constant *C1, Constant *C2) {
877   // No compile-time operations on this type yet.
878   if (C1->getType()->isPPC_FP128Ty())
879     return 0;
880
881   // Handle UndefValue up front.
882   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
883     switch (Opcode) {
884     case Instruction::Xor:
885       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
886         // Handle undef ^ undef -> 0 special case. This is a common
887         // idiom (misuse).
888         return Constant::getNullValue(C1->getType());
889       // Fallthrough
890     case Instruction::Add:
891     case Instruction::Sub:
892       return UndefValue::get(C1->getType());
893     case Instruction::And:
894       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
895         return C1;
896       return Constant::getNullValue(C1->getType());   // undef & X -> 0
897     case Instruction::Mul: {
898       ConstantInt *CI;
899       // X * undef -> undef   if X is odd or undef
900       if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
901           ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
902           (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
903         return UndefValue::get(C1->getType());
904
905       // X * undef -> 0       otherwise
906       return Constant::getNullValue(C1->getType());
907     }
908     case Instruction::UDiv:
909     case Instruction::SDiv:
910       // undef / 1 -> undef
911       if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
912         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
913           if (CI2->isOne())
914             return C1;
915       // FALL THROUGH
916     case Instruction::URem:
917     case Instruction::SRem:
918       if (!isa<UndefValue>(C2))                    // undef / X -> 0
919         return Constant::getNullValue(C1->getType());
920       return C2;                                   // X / undef -> undef
921     case Instruction::Or:                          // X | undef -> -1
922       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
923         return C1;
924       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
925     case Instruction::LShr:
926       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
927         return C1;                                  // undef lshr undef -> undef
928       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
929                                                     // undef lshr X -> 0
930     case Instruction::AShr:
931       if (!isa<UndefValue>(C2))                     // undef ashr X --> all ones
932         return Constant::getAllOnesValue(C1->getType());
933       else if (isa<UndefValue>(C1)) 
934         return C1;                                  // undef ashr undef -> undef
935       else
936         return C1;                                  // X ashr undef --> X
937     case Instruction::Shl:
938       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
939         return C1;                                  // undef shl undef -> undef
940       // undef << X -> 0   or   X << undef -> 0
941       return Constant::getNullValue(C1->getType());
942     }
943   }
944
945   // Handle simplifications when the RHS is a constant int.
946   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
947     switch (Opcode) {
948     case Instruction::Add:
949       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
950       break;
951     case Instruction::Sub:
952       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
953       break;
954     case Instruction::Mul:
955       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
956       if (CI2->equalsInt(1))
957         return C1;                                              // X * 1 == X
958       break;
959     case Instruction::UDiv:
960     case Instruction::SDiv:
961       if (CI2->equalsInt(1))
962         return C1;                                            // X / 1 == X
963       if (CI2->equalsInt(0))
964         return UndefValue::get(CI2->getType());               // X / 0 == undef
965       break;
966     case Instruction::URem:
967     case Instruction::SRem:
968       if (CI2->equalsInt(1))
969         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
970       if (CI2->equalsInt(0))
971         return UndefValue::get(CI2->getType());               // X % 0 == undef
972       break;
973     case Instruction::And:
974       if (CI2->isZero()) return C2;                           // X & 0 == 0
975       if (CI2->isAllOnesValue())
976         return C1;                                            // X & -1 == X
977
978       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
979         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
980         if (CE1->getOpcode() == Instruction::ZExt) {
981           unsigned DstWidth = CI2->getType()->getBitWidth();
982           unsigned SrcWidth =
983             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
984           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
985           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
986             return C1;
987         }
988
989         // If and'ing the address of a global with a constant, fold it.
990         if (CE1->getOpcode() == Instruction::PtrToInt && 
991             isa<GlobalValue>(CE1->getOperand(0))) {
992           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
993
994           // Functions are at least 4-byte aligned.
995           unsigned GVAlign = GV->getAlignment();
996           if (isa<Function>(GV))
997             GVAlign = std::max(GVAlign, 4U);
998
999           if (GVAlign > 1) {
1000             unsigned DstWidth = CI2->getType()->getBitWidth();
1001             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1002             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1003
1004             // If checking bits we know are clear, return zero.
1005             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1006               return Constant::getNullValue(CI2->getType());
1007           }
1008         }
1009       }
1010       break;
1011     case Instruction::Or:
1012       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
1013       if (CI2->isAllOnesValue())
1014         return C2;                         // X | -1 == -1
1015       break;
1016     case Instruction::Xor:
1017       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
1018
1019       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1020         switch (CE1->getOpcode()) {
1021         default: break;
1022         case Instruction::ICmp:
1023         case Instruction::FCmp:
1024           // cmp pred ^ true -> cmp !pred
1025           assert(CI2->equalsInt(1));
1026           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1027           pred = CmpInst::getInversePredicate(pred);
1028           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1029                                           CE1->getOperand(1));
1030         }
1031       }
1032       break;
1033     case Instruction::AShr:
1034       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1035       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1036         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1037           return ConstantExpr::getLShr(C1, C2);
1038       break;
1039     }
1040   } else if (isa<ConstantInt>(C1)) {
1041     // If C1 is a ConstantInt and C2 is not, swap the operands.
1042     if (Instruction::isCommutative(Opcode))
1043       return ConstantExpr::get(Opcode, C2, C1);
1044   }
1045
1046   // At this point we know neither constant is an UndefValue.
1047   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1048     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1049       const APInt &C1V = CI1->getValue();
1050       const APInt &C2V = CI2->getValue();
1051       switch (Opcode) {
1052       default:
1053         break;
1054       case Instruction::Add:     
1055         return ConstantInt::get(CI1->getContext(), C1V + C2V);
1056       case Instruction::Sub:     
1057         return ConstantInt::get(CI1->getContext(), C1V - C2V);
1058       case Instruction::Mul:     
1059         return ConstantInt::get(CI1->getContext(), C1V * C2V);
1060       case Instruction::UDiv:
1061         assert(!CI2->isNullValue() && "Div by zero handled above");
1062         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1063       case Instruction::SDiv:
1064         assert(!CI2->isNullValue() && "Div by zero handled above");
1065         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1066           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1067         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1068       case Instruction::URem:
1069         assert(!CI2->isNullValue() && "Div by zero handled above");
1070         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1071       case Instruction::SRem:
1072         assert(!CI2->isNullValue() && "Div by zero handled above");
1073         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1074           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1075         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1076       case Instruction::And:
1077         return ConstantInt::get(CI1->getContext(), C1V & C2V);
1078       case Instruction::Or:
1079         return ConstantInt::get(CI1->getContext(), C1V | C2V);
1080       case Instruction::Xor:
1081         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1082       case Instruction::Shl: {
1083         uint32_t shiftAmt = C2V.getZExtValue();
1084         if (shiftAmt < C1V.getBitWidth())
1085           return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1086         else
1087           return UndefValue::get(C1->getType()); // too big shift is undef
1088       }
1089       case Instruction::LShr: {
1090         uint32_t shiftAmt = C2V.getZExtValue();
1091         if (shiftAmt < C1V.getBitWidth())
1092           return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1093         else
1094           return UndefValue::get(C1->getType()); // too big shift is undef
1095       }
1096       case Instruction::AShr: {
1097         uint32_t shiftAmt = C2V.getZExtValue();
1098         if (shiftAmt < C1V.getBitWidth())
1099           return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1100         else
1101           return UndefValue::get(C1->getType()); // too big shift is undef
1102       }
1103       }
1104     }
1105
1106     switch (Opcode) {
1107     case Instruction::SDiv:
1108     case Instruction::UDiv:
1109     case Instruction::URem:
1110     case Instruction::SRem:
1111     case Instruction::LShr:
1112     case Instruction::AShr:
1113     case Instruction::Shl:
1114       if (CI1->equalsInt(0)) return C1;
1115       break;
1116     default:
1117       break;
1118     }
1119   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1120     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1121       APFloat C1V = CFP1->getValueAPF();
1122       APFloat C2V = CFP2->getValueAPF();
1123       APFloat C3V = C1V;  // copy for modification
1124       switch (Opcode) {
1125       default:                   
1126         break;
1127       case Instruction::FAdd:
1128         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1129         return ConstantFP::get(C1->getContext(), C3V);
1130       case Instruction::FSub:
1131         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1132         return ConstantFP::get(C1->getContext(), C3V);
1133       case Instruction::FMul:
1134         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1135         return ConstantFP::get(C1->getContext(), C3V);
1136       case Instruction::FDiv:
1137         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1138         return ConstantFP::get(C1->getContext(), C3V);
1139       case Instruction::FRem:
1140         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1141         return ConstantFP::get(C1->getContext(), C3V);
1142       }
1143     }
1144   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1145     // Perform elementwise folding.
1146     SmallVector<Constant*, 16> Result;
1147     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1148       Constant *LHS = C1->getAggregateElement(i);
1149       Constant *RHS = C2->getAggregateElement(i);
1150       if (LHS == 0 || RHS == 0) break;
1151       
1152       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1153     }
1154     
1155     if (Result.size() == VTy->getNumElements())
1156       return ConstantVector::get(Result);
1157   }
1158
1159   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1160     // There are many possible foldings we could do here.  We should probably
1161     // at least fold add of a pointer with an integer into the appropriate
1162     // getelementptr.  This will improve alias analysis a bit.
1163
1164     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1165     // (a + (b + c)).
1166     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1167       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1168       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1169         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1170     }
1171   } else if (isa<ConstantExpr>(C2)) {
1172     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1173     // other way if possible.
1174     if (Instruction::isCommutative(Opcode))
1175       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1176   }
1177
1178   // i1 can be simplified in many cases.
1179   if (C1->getType()->isIntegerTy(1)) {
1180     switch (Opcode) {
1181     case Instruction::Add:
1182     case Instruction::Sub:
1183       return ConstantExpr::getXor(C1, C2);
1184     case Instruction::Mul:
1185       return ConstantExpr::getAnd(C1, C2);
1186     case Instruction::Shl:
1187     case Instruction::LShr:
1188     case Instruction::AShr:
1189       // We can assume that C2 == 0.  If it were one the result would be
1190       // undefined because the shift value is as large as the bitwidth.
1191       return C1;
1192     case Instruction::SDiv:
1193     case Instruction::UDiv:
1194       // We can assume that C2 == 1.  If it were zero the result would be
1195       // undefined through division by zero.
1196       return C1;
1197     case Instruction::URem:
1198     case Instruction::SRem:
1199       // We can assume that C2 == 1.  If it were zero the result would be
1200       // undefined through division by zero.
1201       return ConstantInt::getFalse(C1->getContext());
1202     default:
1203       break;
1204     }
1205   }
1206
1207   // We don't know how to fold this.
1208   return 0;
1209 }
1210
1211 /// isZeroSizedType - This type is zero sized if its an array or structure of
1212 /// zero sized types.  The only leaf zero sized type is an empty structure.
1213 static bool isMaybeZeroSizedType(Type *Ty) {
1214   if (StructType *STy = dyn_cast<StructType>(Ty)) {
1215     if (STy->isOpaque()) return true;  // Can't say.
1216
1217     // If all of elements have zero size, this does too.
1218     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1219       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1220     return true;
1221
1222   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1223     return isMaybeZeroSizedType(ATy->getElementType());
1224   }
1225   return false;
1226 }
1227
1228 /// IdxCompare - Compare the two constants as though they were getelementptr
1229 /// indices.  This allows coersion of the types to be the same thing.
1230 ///
1231 /// If the two constants are the "same" (after coersion), return 0.  If the
1232 /// first is less than the second, return -1, if the second is less than the
1233 /// first, return 1.  If the constants are not integral, return -2.
1234 ///
1235 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1236   if (C1 == C2) return 0;
1237
1238   // Ok, we found a different index.  If they are not ConstantInt, we can't do
1239   // anything with them.
1240   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1241     return -2; // don't know!
1242
1243   // Ok, we have two differing integer indices.  Sign extend them to be the same
1244   // type.  Long is always big enough, so we use it.
1245   if (!C1->getType()->isIntegerTy(64))
1246     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1247
1248   if (!C2->getType()->isIntegerTy(64))
1249     C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1250
1251   if (C1 == C2) return 0;  // They are equal
1252
1253   // If the type being indexed over is really just a zero sized type, there is
1254   // no pointer difference being made here.
1255   if (isMaybeZeroSizedType(ElTy))
1256     return -2; // dunno.
1257
1258   // If they are really different, now that they are the same type, then we
1259   // found a difference!
1260   if (cast<ConstantInt>(C1)->getSExtValue() < 
1261       cast<ConstantInt>(C2)->getSExtValue())
1262     return -1;
1263   else
1264     return 1;
1265 }
1266
1267 /// evaluateFCmpRelation - This function determines if there is anything we can
1268 /// decide about the two constants provided.  This doesn't need to handle simple
1269 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1270 /// If we can determine that the two constants have a particular relation to 
1271 /// each other, we should return the corresponding FCmpInst predicate, 
1272 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1273 /// ConstantFoldCompareInstruction.
1274 ///
1275 /// To simplify this code we canonicalize the relation so that the first
1276 /// operand is always the most "complex" of the two.  We consider ConstantFP
1277 /// to be the simplest, and ConstantExprs to be the most complex.
1278 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1279   assert(V1->getType() == V2->getType() &&
1280          "Cannot compare values of different types!");
1281
1282   // No compile-time operations on this type yet.
1283   if (V1->getType()->isPPC_FP128Ty())
1284     return FCmpInst::BAD_FCMP_PREDICATE;
1285
1286   // Handle degenerate case quickly
1287   if (V1 == V2) return FCmpInst::FCMP_OEQ;
1288
1289   if (!isa<ConstantExpr>(V1)) {
1290     if (!isa<ConstantExpr>(V2)) {
1291       // We distilled thisUse the standard constant folder for a few cases
1292       ConstantInt *R = 0;
1293       R = dyn_cast<ConstantInt>(
1294                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1295       if (R && !R->isZero()) 
1296         return FCmpInst::FCMP_OEQ;
1297       R = dyn_cast<ConstantInt>(
1298                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1299       if (R && !R->isZero()) 
1300         return FCmpInst::FCMP_OLT;
1301       R = dyn_cast<ConstantInt>(
1302                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1303       if (R && !R->isZero()) 
1304         return FCmpInst::FCMP_OGT;
1305
1306       // Nothing more we can do
1307       return FCmpInst::BAD_FCMP_PREDICATE;
1308     }
1309
1310     // If the first operand is simple and second is ConstantExpr, swap operands.
1311     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1312     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1313       return FCmpInst::getSwappedPredicate(SwappedRelation);
1314   } else {
1315     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1316     // constantexpr or a simple constant.
1317     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1318     switch (CE1->getOpcode()) {
1319     case Instruction::FPTrunc:
1320     case Instruction::FPExt:
1321     case Instruction::UIToFP:
1322     case Instruction::SIToFP:
1323       // We might be able to do something with these but we don't right now.
1324       break;
1325     default:
1326       break;
1327     }
1328   }
1329   // There are MANY other foldings that we could perform here.  They will
1330   // probably be added on demand, as they seem needed.
1331   return FCmpInst::BAD_FCMP_PREDICATE;
1332 }
1333
1334 /// evaluateICmpRelation - This function determines if there is anything we can
1335 /// decide about the two constants provided.  This doesn't need to handle simple
1336 /// things like integer comparisons, but should instead handle ConstantExprs
1337 /// and GlobalValues.  If we can determine that the two constants have a
1338 /// particular relation to each other, we should return the corresponding ICmp
1339 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1340 ///
1341 /// To simplify this code we canonicalize the relation so that the first
1342 /// operand is always the most "complex" of the two.  We consider simple
1343 /// constants (like ConstantInt) to be the simplest, followed by
1344 /// GlobalValues, followed by ConstantExpr's (the most complex).
1345 ///
1346 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1347                                                 bool isSigned) {
1348   assert(V1->getType() == V2->getType() &&
1349          "Cannot compare different types of values!");
1350   if (V1 == V2) return ICmpInst::ICMP_EQ;
1351
1352   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1353       !isa<BlockAddress>(V1)) {
1354     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1355         !isa<BlockAddress>(V2)) {
1356       // We distilled this down to a simple case, use the standard constant
1357       // folder.
1358       ConstantInt *R = 0;
1359       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1360       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1361       if (R && !R->isZero()) 
1362         return pred;
1363       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1364       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1365       if (R && !R->isZero())
1366         return pred;
1367       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1368       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1369       if (R && !R->isZero())
1370         return pred;
1371
1372       // If we couldn't figure it out, bail.
1373       return ICmpInst::BAD_ICMP_PREDICATE;
1374     }
1375
1376     // If the first operand is simple, swap operands.
1377     ICmpInst::Predicate SwappedRelation = 
1378       evaluateICmpRelation(V2, V1, isSigned);
1379     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1380       return ICmpInst::getSwappedPredicate(SwappedRelation);
1381
1382   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1383     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1384       ICmpInst::Predicate SwappedRelation = 
1385         evaluateICmpRelation(V2, V1, isSigned);
1386       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1387         return ICmpInst::getSwappedPredicate(SwappedRelation);
1388       return ICmpInst::BAD_ICMP_PREDICATE;
1389     }
1390
1391     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1392     // constant (which, since the types must match, means that it's a
1393     // ConstantPointerNull).
1394     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1395       // Don't try to decide equality of aliases.
1396       if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1397         if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1398           return ICmpInst::ICMP_NE;
1399     } else if (isa<BlockAddress>(V2)) {
1400       return ICmpInst::ICMP_NE; // Globals never equal labels.
1401     } else {
1402       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1403       // GlobalVals can never be null unless they have external weak linkage.
1404       // We don't try to evaluate aliases here.
1405       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1406         return ICmpInst::ICMP_NE;
1407     }
1408   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1409     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1410       ICmpInst::Predicate SwappedRelation = 
1411         evaluateICmpRelation(V2, V1, isSigned);
1412       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1413         return ICmpInst::getSwappedPredicate(SwappedRelation);
1414       return ICmpInst::BAD_ICMP_PREDICATE;
1415     }
1416     
1417     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1418     // constant (which, since the types must match, means that it is a
1419     // ConstantPointerNull).
1420     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1421       // Block address in another function can't equal this one, but block
1422       // addresses in the current function might be the same if blocks are
1423       // empty.
1424       if (BA2->getFunction() != BA->getFunction())
1425         return ICmpInst::ICMP_NE;
1426     } else {
1427       // Block addresses aren't null, don't equal the address of globals.
1428       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1429              "Canonicalization guarantee!");
1430       return ICmpInst::ICMP_NE;
1431     }
1432   } else {
1433     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1434     // constantexpr, a global, block address, or a simple constant.
1435     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1436     Constant *CE1Op0 = CE1->getOperand(0);
1437
1438     switch (CE1->getOpcode()) {
1439     case Instruction::Trunc:
1440     case Instruction::FPTrunc:
1441     case Instruction::FPExt:
1442     case Instruction::FPToUI:
1443     case Instruction::FPToSI:
1444       break; // We can't evaluate floating point casts or truncations.
1445
1446     case Instruction::UIToFP:
1447     case Instruction::SIToFP:
1448     case Instruction::BitCast:
1449     case Instruction::ZExt:
1450     case Instruction::SExt:
1451       // If the cast is not actually changing bits, and the second operand is a
1452       // null pointer, do the comparison with the pre-casted value.
1453       if (V2->isNullValue() &&
1454           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1455         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1456         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1457         return evaluateICmpRelation(CE1Op0,
1458                                     Constant::getNullValue(CE1Op0->getType()), 
1459                                     isSigned);
1460       }
1461       break;
1462
1463     case Instruction::GetElementPtr:
1464       // Ok, since this is a getelementptr, we know that the constant has a
1465       // pointer type.  Check the various cases.
1466       if (isa<ConstantPointerNull>(V2)) {
1467         // If we are comparing a GEP to a null pointer, check to see if the base
1468         // of the GEP equals the null pointer.
1469         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1470           if (GV->hasExternalWeakLinkage())
1471             // Weak linkage GVals could be zero or not. We're comparing that
1472             // to null pointer so its greater-or-equal
1473             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1474           else 
1475             // If its not weak linkage, the GVal must have a non-zero address
1476             // so the result is greater-than
1477             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1478         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1479           // If we are indexing from a null pointer, check to see if we have any
1480           // non-zero indices.
1481           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1482             if (!CE1->getOperand(i)->isNullValue())
1483               // Offsetting from null, must not be equal.
1484               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1485           // Only zero indexes from null, must still be zero.
1486           return ICmpInst::ICMP_EQ;
1487         }
1488         // Otherwise, we can't really say if the first operand is null or not.
1489       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1490         if (isa<ConstantPointerNull>(CE1Op0)) {
1491           if (GV2->hasExternalWeakLinkage())
1492             // Weak linkage GVals could be zero or not. We're comparing it to
1493             // a null pointer, so its less-or-equal
1494             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1495           else
1496             // If its not weak linkage, the GVal must have a non-zero address
1497             // so the result is less-than
1498             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1499         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1500           if (GV == GV2) {
1501             // If this is a getelementptr of the same global, then it must be
1502             // different.  Because the types must match, the getelementptr could
1503             // only have at most one index, and because we fold getelementptr's
1504             // with a single zero index, it must be nonzero.
1505             assert(CE1->getNumOperands() == 2 &&
1506                    !CE1->getOperand(1)->isNullValue() &&
1507                    "Surprising getelementptr!");
1508             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1509           } else {
1510             // If they are different globals, we don't know what the value is,
1511             // but they can't be equal.
1512             return ICmpInst::ICMP_NE;
1513           }
1514         }
1515       } else {
1516         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1517         Constant *CE2Op0 = CE2->getOperand(0);
1518
1519         // There are MANY other foldings that we could perform here.  They will
1520         // probably be added on demand, as they seem needed.
1521         switch (CE2->getOpcode()) {
1522         default: break;
1523         case Instruction::GetElementPtr:
1524           // By far the most common case to handle is when the base pointers are
1525           // obviously to the same or different globals.
1526           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1527             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1528               return ICmpInst::ICMP_NE;
1529             // Ok, we know that both getelementptr instructions are based on the
1530             // same global.  From this, we can precisely determine the relative
1531             // ordering of the resultant pointers.
1532             unsigned i = 1;
1533
1534             // The logic below assumes that the result of the comparison
1535             // can be determined by finding the first index that differs.
1536             // This doesn't work if there is over-indexing in any
1537             // subsequent indices, so check for that case first.
1538             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1539                 !CE2->isGEPWithNoNotionalOverIndexing())
1540                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1541
1542             // Compare all of the operands the GEP's have in common.
1543             gep_type_iterator GTI = gep_type_begin(CE1);
1544             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1545                  ++i, ++GTI)
1546               switch (IdxCompare(CE1->getOperand(i),
1547                                  CE2->getOperand(i), GTI.getIndexedType())) {
1548               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1549               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1550               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1551               }
1552
1553             // Ok, we ran out of things they have in common.  If any leftovers
1554             // are non-zero then we have a difference, otherwise we are equal.
1555             for (; i < CE1->getNumOperands(); ++i)
1556               if (!CE1->getOperand(i)->isNullValue()) {
1557                 if (isa<ConstantInt>(CE1->getOperand(i)))
1558                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1559                 else
1560                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1561               }
1562
1563             for (; i < CE2->getNumOperands(); ++i)
1564               if (!CE2->getOperand(i)->isNullValue()) {
1565                 if (isa<ConstantInt>(CE2->getOperand(i)))
1566                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1567                 else
1568                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1569               }
1570             return ICmpInst::ICMP_EQ;
1571           }
1572         }
1573       }
1574     default:
1575       break;
1576     }
1577   }
1578
1579   return ICmpInst::BAD_ICMP_PREDICATE;
1580 }
1581
1582 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
1583                                                Constant *C1, Constant *C2) {
1584   Type *ResultTy;
1585   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1586     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1587                                VT->getNumElements());
1588   else
1589     ResultTy = Type::getInt1Ty(C1->getContext());
1590
1591   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1592   if (pred == FCmpInst::FCMP_FALSE)
1593     return Constant::getNullValue(ResultTy);
1594
1595   if (pred == FCmpInst::FCMP_TRUE)
1596     return Constant::getAllOnesValue(ResultTy);
1597
1598   // Handle some degenerate cases first
1599   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1600     // For EQ and NE, we can always pick a value for the undef to make the
1601     // predicate pass or fail, so we can return undef.
1602     // Also, if both operands are undef, we can return undef.
1603     if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1604         (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1605       return UndefValue::get(ResultTy);
1606     // Otherwise, pick the same value as the non-undef operand, and fold
1607     // it to true or false.
1608     return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1609   }
1610
1611   // No compile-time operations on this type yet.
1612   if (C1->getType()->isPPC_FP128Ty())
1613     return 0;
1614
1615   // icmp eq/ne(null,GV) -> false/true
1616   if (C1->isNullValue()) {
1617     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1618       // Don't try to evaluate aliases.  External weak GV can be null.
1619       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1620         if (pred == ICmpInst::ICMP_EQ)
1621           return ConstantInt::getFalse(C1->getContext());
1622         else if (pred == ICmpInst::ICMP_NE)
1623           return ConstantInt::getTrue(C1->getContext());
1624       }
1625   // icmp eq/ne(GV,null) -> false/true
1626   } else if (C2->isNullValue()) {
1627     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1628       // Don't try to evaluate aliases.  External weak GV can be null.
1629       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1630         if (pred == ICmpInst::ICMP_EQ)
1631           return ConstantInt::getFalse(C1->getContext());
1632         else if (pred == ICmpInst::ICMP_NE)
1633           return ConstantInt::getTrue(C1->getContext());
1634       }
1635   }
1636
1637   // If the comparison is a comparison between two i1's, simplify it.
1638   if (C1->getType()->isIntegerTy(1)) {
1639     switch(pred) {
1640     case ICmpInst::ICMP_EQ:
1641       if (isa<ConstantInt>(C2))
1642         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1643       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1644     case ICmpInst::ICMP_NE:
1645       return ConstantExpr::getXor(C1, C2);
1646     default:
1647       break;
1648     }
1649   }
1650
1651   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1652     APInt V1 = cast<ConstantInt>(C1)->getValue();
1653     APInt V2 = cast<ConstantInt>(C2)->getValue();
1654     switch (pred) {
1655     default: llvm_unreachable("Invalid ICmp Predicate");
1656     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1657     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1658     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1659     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1660     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1661     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1662     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1663     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1664     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1665     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1666     }
1667   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1668     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1669     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1670     APFloat::cmpResult R = C1V.compare(C2V);
1671     switch (pred) {
1672     default: llvm_unreachable("Invalid FCmp Predicate");
1673     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1674     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
1675     case FCmpInst::FCMP_UNO:
1676       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1677     case FCmpInst::FCMP_ORD:
1678       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1679     case FCmpInst::FCMP_UEQ:
1680       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1681                                         R==APFloat::cmpEqual);
1682     case FCmpInst::FCMP_OEQ:   
1683       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1684     case FCmpInst::FCMP_UNE:
1685       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1686     case FCmpInst::FCMP_ONE:   
1687       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1688                                         R==APFloat::cmpGreaterThan);
1689     case FCmpInst::FCMP_ULT: 
1690       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1691                                         R==APFloat::cmpLessThan);
1692     case FCmpInst::FCMP_OLT:   
1693       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1694     case FCmpInst::FCMP_UGT:
1695       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1696                                         R==APFloat::cmpGreaterThan);
1697     case FCmpInst::FCMP_OGT:
1698       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1699     case FCmpInst::FCMP_ULE:
1700       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1701     case FCmpInst::FCMP_OLE: 
1702       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1703                                         R==APFloat::cmpEqual);
1704     case FCmpInst::FCMP_UGE:
1705       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1706     case FCmpInst::FCMP_OGE: 
1707       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1708                                         R==APFloat::cmpEqual);
1709     }
1710   } else if (C1->getType()->isVectorTy()) {
1711     // If we can constant fold the comparison of each element, constant fold
1712     // the whole vector comparison.
1713     SmallVector<Constant*, 4> ResElts;
1714     // Compare the elements, producing an i1 result or constant expr.
1715     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1716       Constant *C1E = C1->getAggregateElement(i);
1717       Constant *C2E = C2->getAggregateElement(i);
1718       if (C1E == 0 || C2E == 0) break;
1719       
1720       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1721     }
1722     
1723     if (ResElts.size() == C1->getType()->getVectorNumElements())
1724       return ConstantVector::get(ResElts);
1725   }
1726
1727   if (C1->getType()->isFloatingPointTy()) {
1728     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1729     switch (evaluateFCmpRelation(C1, C2)) {
1730     default: llvm_unreachable("Unknown relation!");
1731     case FCmpInst::FCMP_UNO:
1732     case FCmpInst::FCMP_ORD:
1733     case FCmpInst::FCMP_UEQ:
1734     case FCmpInst::FCMP_UNE:
1735     case FCmpInst::FCMP_ULT:
1736     case FCmpInst::FCMP_UGT:
1737     case FCmpInst::FCMP_ULE:
1738     case FCmpInst::FCMP_UGE:
1739     case FCmpInst::FCMP_TRUE:
1740     case FCmpInst::FCMP_FALSE:
1741     case FCmpInst::BAD_FCMP_PREDICATE:
1742       break; // Couldn't determine anything about these constants.
1743     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1744       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1745                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1746                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1747       break;
1748     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1749       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1750                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1751                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1752       break;
1753     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1754       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1755                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1756                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1757       break;
1758     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1759       // We can only partially decide this relation.
1760       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1761         Result = 0;
1762       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1763         Result = 1;
1764       break;
1765     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1766       // We can only partially decide this relation.
1767       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1768         Result = 0;
1769       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1770         Result = 1;
1771       break;
1772     case FCmpInst::FCMP_ONE: // We know that C1 != C2
1773       // We can only partially decide this relation.
1774       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1775         Result = 0;
1776       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1777         Result = 1;
1778       break;
1779     }
1780
1781     // If we evaluated the result, return it now.
1782     if (Result != -1)
1783       return ConstantInt::get(ResultTy, Result);
1784
1785   } else {
1786     // Evaluate the relation between the two constants, per the predicate.
1787     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1788     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1789     default: llvm_unreachable("Unknown relational!");
1790     case ICmpInst::BAD_ICMP_PREDICATE:
1791       break;  // Couldn't determine anything about these constants.
1792     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1793       // If we know the constants are equal, we can decide the result of this
1794       // computation precisely.
1795       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1796       break;
1797     case ICmpInst::ICMP_ULT:
1798       switch (pred) {
1799       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1800         Result = 1; break;
1801       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1802         Result = 0; break;
1803       }
1804       break;
1805     case ICmpInst::ICMP_SLT:
1806       switch (pred) {
1807       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1808         Result = 1; break;
1809       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1810         Result = 0; break;
1811       }
1812       break;
1813     case ICmpInst::ICMP_UGT:
1814       switch (pred) {
1815       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1816         Result = 1; break;
1817       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1818         Result = 0; break;
1819       }
1820       break;
1821     case ICmpInst::ICMP_SGT:
1822       switch (pred) {
1823       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1824         Result = 1; break;
1825       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1826         Result = 0; break;
1827       }
1828       break;
1829     case ICmpInst::ICMP_ULE:
1830       if (pred == ICmpInst::ICMP_UGT) Result = 0;
1831       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1832       break;
1833     case ICmpInst::ICMP_SLE:
1834       if (pred == ICmpInst::ICMP_SGT) Result = 0;
1835       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1836       break;
1837     case ICmpInst::ICMP_UGE:
1838       if (pred == ICmpInst::ICMP_ULT) Result = 0;
1839       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1840       break;
1841     case ICmpInst::ICMP_SGE:
1842       if (pred == ICmpInst::ICMP_SLT) Result = 0;
1843       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1844       break;
1845     case ICmpInst::ICMP_NE:
1846       if (pred == ICmpInst::ICMP_EQ) Result = 0;
1847       if (pred == ICmpInst::ICMP_NE) Result = 1;
1848       break;
1849     }
1850
1851     // If we evaluated the result, return it now.
1852     if (Result != -1)
1853       return ConstantInt::get(ResultTy, Result);
1854
1855     // If the right hand side is a bitcast, try using its inverse to simplify
1856     // it by moving it to the left hand side.  We can't do this if it would turn
1857     // a vector compare into a scalar compare or visa versa.
1858     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1859       Constant *CE2Op0 = CE2->getOperand(0);
1860       if (CE2->getOpcode() == Instruction::BitCast &&
1861           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1862         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1863         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1864       }
1865     }
1866
1867     // If the left hand side is an extension, try eliminating it.
1868     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1869       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1870           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1871         Constant *CE1Op0 = CE1->getOperand(0);
1872         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1873         if (CE1Inverse == CE1Op0) {
1874           // Check whether we can safely truncate the right hand side.
1875           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1876           if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
1877             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1878           }
1879         }
1880       }
1881     }
1882
1883     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1884         (C1->isNullValue() && !C2->isNullValue())) {
1885       // If C2 is a constant expr and C1 isn't, flip them around and fold the
1886       // other way if possible.
1887       // Also, if C1 is null and C2 isn't, flip them around.
1888       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1889       return ConstantExpr::getICmp(pred, C2, C1);
1890     }
1891   }
1892   return 0;
1893 }
1894
1895 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1896 /// is "inbounds".
1897 template<typename IndexTy>
1898 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1899   // No indices means nothing that could be out of bounds.
1900   if (Idxs.empty()) return true;
1901
1902   // If the first index is zero, it's in bounds.
1903   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1904
1905   // If the first index is one and all the rest are zero, it's in bounds,
1906   // by the one-past-the-end rule.
1907   if (!cast<ConstantInt>(Idxs[0])->isOne())
1908     return false;
1909   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1910     if (!cast<Constant>(Idxs[i])->isNullValue())
1911       return false;
1912   return true;
1913 }
1914
1915 template<typename IndexTy>
1916 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1917                                                bool inBounds,
1918                                                ArrayRef<IndexTy> Idxs) {
1919   if (Idxs.empty()) return C;
1920   Constant *Idx0 = cast<Constant>(Idxs[0]);
1921   if ((Idxs.size() == 1 && Idx0->isNullValue()))
1922     return C;
1923
1924   if (isa<UndefValue>(C)) {
1925     PointerType *Ptr = cast<PointerType>(C->getType());
1926     Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1927     assert(Ty != 0 && "Invalid indices for GEP!");
1928     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1929   }
1930
1931   if (C->isNullValue()) {
1932     bool isNull = true;
1933     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1934       if (!cast<Constant>(Idxs[i])->isNullValue()) {
1935         isNull = false;
1936         break;
1937       }
1938     if (isNull) {
1939       PointerType *Ptr = cast<PointerType>(C->getType());
1940       Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1941       assert(Ty != 0 && "Invalid indices for GEP!");
1942       return ConstantPointerNull::get(PointerType::get(Ty,
1943                                                        Ptr->getAddressSpace()));
1944     }
1945   }
1946
1947   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1948     // Combine Indices - If the source pointer to this getelementptr instruction
1949     // is a getelementptr instruction, combine the indices of the two
1950     // getelementptr instructions into a single instruction.
1951     //
1952     if (CE->getOpcode() == Instruction::GetElementPtr) {
1953       Type *LastTy = 0;
1954       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1955            I != E; ++I)
1956         LastTy = *I;
1957
1958       if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
1959         SmallVector<Value*, 16> NewIndices;
1960         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
1961         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1962           NewIndices.push_back(CE->getOperand(i));
1963
1964         // Add the last index of the source with the first index of the new GEP.
1965         // Make sure to handle the case when they are actually different types.
1966         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1967         // Otherwise it must be an array.
1968         if (!Idx0->isNullValue()) {
1969           Type *IdxTy = Combined->getType();
1970           if (IdxTy != Idx0->getType()) {
1971             Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
1972             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
1973             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
1974             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1975           } else {
1976             Combined =
1977               ConstantExpr::get(Instruction::Add, Idx0, Combined);
1978           }
1979         }
1980
1981         NewIndices.push_back(Combined);
1982         NewIndices.append(Idxs.begin() + 1, Idxs.end());
1983         return
1984           ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
1985                                          inBounds &&
1986                                            cast<GEPOperator>(CE)->isInBounds());
1987       }
1988     }
1989
1990     // Implement folding of:
1991     //    i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
1992     //                        i64 0, i64 0)
1993     // To: i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
1994     //
1995     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
1996       if (PointerType *SPT =
1997           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1998         if (ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1999           if (ArrayType *CAT =
2000         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
2001             if (CAT->getElementType() == SAT->getElementType())
2002               return
2003                 ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
2004                                                Idxs, inBounds);
2005     }
2006   }
2007
2008   // Check to see if any array indices are not within the corresponding
2009   // notional array bounds. If so, try to determine if they can be factored
2010   // out into preceding dimensions.
2011   bool Unknown = false;
2012   SmallVector<Constant *, 8> NewIdxs;
2013   Type *Ty = C->getType();
2014   Type *Prev = 0;
2015   for (unsigned i = 0, e = Idxs.size(); i != e;
2016        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2017     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2018       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2019         if (ATy->getNumElements() <= INT64_MAX &&
2020             ATy->getNumElements() != 0 &&
2021             CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2022           if (isa<SequentialType>(Prev)) {
2023             // It's out of range, but we can factor it into the prior
2024             // dimension.
2025             NewIdxs.resize(Idxs.size());
2026             ConstantInt *Factor = ConstantInt::get(CI->getType(),
2027                                                    ATy->getNumElements());
2028             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2029
2030             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2031             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2032
2033             // Before adding, extend both operands to i64 to avoid
2034             // overflow trouble.
2035             if (!PrevIdx->getType()->isIntegerTy(64))
2036               PrevIdx = ConstantExpr::getSExt(PrevIdx,
2037                                            Type::getInt64Ty(Div->getContext()));
2038             if (!Div->getType()->isIntegerTy(64))
2039               Div = ConstantExpr::getSExt(Div,
2040                                           Type::getInt64Ty(Div->getContext()));
2041
2042             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2043           } else {
2044             // It's out of range, but the prior dimension is a struct
2045             // so we can't do anything about it.
2046             Unknown = true;
2047           }
2048         }
2049     } else {
2050       // We don't know if it's in range or not.
2051       Unknown = true;
2052     }
2053   }
2054
2055   // If we did any factoring, start over with the adjusted indices.
2056   if (!NewIdxs.empty()) {
2057     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2058       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2059     return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2060   }
2061
2062   // If all indices are known integers and normalized, we can do a simple
2063   // check for the "inbounds" property.
2064   if (!Unknown && !inBounds &&
2065       isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
2066     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2067
2068   return 0;
2069 }
2070
2071 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2072                                           bool inBounds,
2073                                           ArrayRef<Constant *> Idxs) {
2074   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2075 }
2076
2077 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2078                                           bool inBounds,
2079                                           ArrayRef<Value *> Idxs) {
2080   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2081 }