f1b97dfce13b0de976d1659cc9ec134a6137cec9
[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 (ConstantVector *CV = dyn_cast<ConstantVector>(V))
551     if (DestTy->isVectorTy() &&
552         cast<VectorType>(DestTy)->getNumElements() ==
553         CV->getType()->getNumElements()) {
554       std::vector<Constant*> res;
555       VectorType *DestVecTy = cast<VectorType>(DestTy);
556       Type *DstEltTy = DestVecTy->getElementType();
557       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
558         res.push_back(ConstantExpr::getCast(opc,
559                                             CV->getOperand(i), DstEltTy));
560       return ConstantVector::get(res);
561     }
562
563   // We actually have to do a cast now. Perform the cast according to the
564   // opcode specified.
565   switch (opc) {
566   default:
567     llvm_unreachable("Failed to cast constant expression");
568   case Instruction::FPTrunc:
569   case Instruction::FPExt:
570     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
571       bool ignored;
572       APFloat Val = FPC->getValueAPF();
573       Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
574                   DestTy->isFloatTy() ? APFloat::IEEEsingle :
575                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
576                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
577                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
578                   APFloat::Bogus,
579                   APFloat::rmNearestTiesToEven, &ignored);
580       return ConstantFP::get(V->getContext(), Val);
581     }
582     return 0; // Can't fold.
583   case Instruction::FPToUI: 
584   case Instruction::FPToSI:
585     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
586       const APFloat &V = FPC->getValueAPF();
587       bool ignored;
588       uint64_t x[2]; 
589       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
590       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
591                                 APFloat::rmTowardZero, &ignored);
592       APInt Val(DestBitWidth, x);
593       return ConstantInt::get(FPC->getContext(), Val);
594     }
595     return 0; // Can't fold.
596   case Instruction::IntToPtr:   //always treated as unsigned
597     if (V->isNullValue())       // Is it an integral null value?
598       return ConstantPointerNull::get(cast<PointerType>(DestTy));
599     return 0;                   // Other pointer types cannot be casted
600   case Instruction::PtrToInt:   // always treated as unsigned
601     // Is it a null pointer value?
602     if (V->isNullValue())
603       return ConstantInt::get(DestTy, 0);
604     // If this is a sizeof-like expression, pull out multiplications by
605     // known factors to expose them to subsequent folding. If it's an
606     // alignof-like expression, factor out known factors.
607     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
608       if (CE->getOpcode() == Instruction::GetElementPtr &&
609           CE->getOperand(0)->isNullValue()) {
610         Type *Ty =
611           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
612         if (CE->getNumOperands() == 2) {
613           // Handle a sizeof-like expression.
614           Constant *Idx = CE->getOperand(1);
615           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
616           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
617             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
618                                                                 DestTy, false),
619                                         Idx, DestTy);
620             return ConstantExpr::getMul(C, Idx);
621           }
622         } else if (CE->getNumOperands() == 3 &&
623                    CE->getOperand(1)->isNullValue()) {
624           // Handle an alignof-like expression.
625           if (StructType *STy = dyn_cast<StructType>(Ty))
626             if (!STy->isPacked()) {
627               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
628               if (CI->isOne() &&
629                   STy->getNumElements() == 2 &&
630                   STy->getElementType(0)->isIntegerTy(1)) {
631                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
632               }
633             }
634           // Handle an offsetof-like expression.
635           if (Ty->isStructTy() || Ty->isArrayTy()) {
636             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
637                                                 DestTy, false))
638               return C;
639           }
640         }
641       }
642     // Other pointer types cannot be casted
643     return 0;
644   case Instruction::UIToFP:
645   case Instruction::SIToFP:
646     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
647       APInt api = CI->getValue();
648       APFloat apf(APInt::getNullValue(DestTy->getPrimitiveSizeInBits()), true);
649       (void)apf.convertFromAPInt(api, 
650                                  opc==Instruction::SIToFP,
651                                  APFloat::rmNearestTiesToEven);
652       return ConstantFP::get(V->getContext(), apf);
653     }
654     return 0;
655   case Instruction::ZExt:
656     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
657       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
658       return ConstantInt::get(V->getContext(),
659                               CI->getValue().zext(BitWidth));
660     }
661     return 0;
662   case Instruction::SExt:
663     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
664       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
665       return ConstantInt::get(V->getContext(),
666                               CI->getValue().sext(BitWidth));
667     }
668     return 0;
669   case Instruction::Trunc: {
670     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
671     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
672       return ConstantInt::get(V->getContext(),
673                               CI->getValue().trunc(DestBitWidth));
674     }
675     
676     // The input must be a constantexpr.  See if we can simplify this based on
677     // the bytes we are demanding.  Only do this if the source and dest are an
678     // even multiple of a byte.
679     if ((DestBitWidth & 7) == 0 &&
680         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
681       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
682         return Res;
683       
684     return 0;
685   }
686   case Instruction::BitCast:
687     return FoldBitCast(V, DestTy);
688   }
689 }
690
691 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
692                                               Constant *V1, Constant *V2) {
693   // Check for i1 and vector true/false conditions.
694   if (Cond->isNullValue()) return V2;
695   if (Cond->isAllOnesValue()) return V1;
696
697   // FIXME: CDV Condition.
698   // If the condition is a vector constant, fold the result elementwise.
699   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
700     SmallVector<Constant*, 16> Result;
701     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
702       ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
703       if (Cond == 0) break;
704       
705       Constant *Res = (Cond->getZExtValue() ? V2 : V1)->getAggregateElement(i);
706       if (Res == 0) break;
707       Result.push_back(Res);
708     }
709     
710     // If we were able to build the vector, return it.
711     if (Result.size() == V1->getType()->getVectorNumElements())
712       return ConstantVector::get(Result);
713   }
714
715
716   if (isa<UndefValue>(Cond)) {
717     if (isa<UndefValue>(V1)) return V1;
718     return V2;
719   }
720   if (isa<UndefValue>(V1)) return V2;
721   if (isa<UndefValue>(V2)) return V1;
722   if (V1 == V2) return V1;
723
724   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
725     if (TrueVal->getOpcode() == Instruction::Select)
726       if (TrueVal->getOperand(0) == Cond)
727         return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
728   }
729   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
730     if (FalseVal->getOpcode() == Instruction::Select)
731       if (FalseVal->getOperand(0) == Cond)
732         return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
733   }
734
735   return 0;
736 }
737
738 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
739                                                       Constant *Idx) {
740   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
741     return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
742   if (Val->isNullValue())  // ee(zero, x) -> zero
743     return Constant::getNullValue(
744                           cast<VectorType>(Val->getType())->getElementType());
745
746   if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
747     if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
748       uint64_t Index = CIdx->getZExtValue();
749       if (Index >= CVal->getNumOperands())
750         // ee({w,x,y,z}, wrong_value) -> undef
751         return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
752       return CVal->getOperand(CIdx->getZExtValue());
753     } else if (isa<UndefValue>(Idx)) {
754       // ee({w,x,y,z}, undef) -> undef
755       return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
756     }
757   }
758   return 0;
759 }
760
761 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
762                                                      Constant *Elt,
763                                                      Constant *Idx) {
764   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
765   if (!CIdx) return 0;
766   const APInt &IdxVal = CIdx->getValue();
767   
768   SmallVector<Constant*, 16> Result;
769   for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
770     if (i == IdxVal) {
771       Result.push_back(Elt);
772       continue;
773     }
774     
775     if (Constant *C = Val->getAggregateElement(i))
776       Result.push_back(C);
777     else
778       return 0;
779   }
780   
781   return ConstantVector::get(Result);
782 }
783
784 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
785                                                      Constant *V2,
786                                                      Constant *Mask) {
787   // Undefined shuffle mask -> undefined value.
788   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
789
790   // Don't break the bitcode reader hack.
791   if (isa<ConstantExpr>(Mask)) return 0;
792   
793   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
794   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
795   Type *EltTy = V1->getType()->getVectorElementType();
796
797   // Loop over the shuffle mask, evaluating each element.
798   SmallVector<Constant*, 32> Result;
799   for (unsigned i = 0; i != MaskNumElts; ++i) {
800     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
801     if (Elt == -1) {
802       Result.push_back(UndefValue::get(EltTy));
803       continue;
804     }
805     Constant *InElt;
806     if (unsigned(Elt) >= SrcNumElts*2)
807       InElt = UndefValue::get(EltTy);
808     else if (unsigned(Elt) >= SrcNumElts)
809       InElt = V2->getAggregateElement(Elt - SrcNumElts);
810     else
811       InElt = V1->getAggregateElement(Elt);
812     if (InElt == 0) return 0;
813     Result.push_back(InElt);
814   }
815
816   return ConstantVector::get(Result);
817 }
818
819 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
820                                                     ArrayRef<unsigned> Idxs) {
821   // Base case: no indices, so return the entire value.
822   if (Idxs.empty())
823     return Agg;
824
825   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
826     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
827
828   return 0;
829 }
830
831 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
832                                                    Constant *Val,
833                                                    ArrayRef<unsigned> Idxs) {
834   // Base case: no indices, so replace the entire value.
835   if (Idxs.empty())
836     return Val;
837
838   unsigned NumElts;
839   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
840     NumElts = ST->getNumElements();
841   else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
842     NumElts = AT->getNumElements();
843   else
844     NumElts = AT->getVectorNumElements();
845   
846   SmallVector<Constant*, 32> Result;
847   for (unsigned i = 0; i != NumElts; ++i) {
848     Constant *C = Agg->getAggregateElement(i);
849     if (C == 0) return 0;
850     
851     if (Idxs[0] == i)
852       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
853     
854     Result.push_back(C);
855   }
856   
857   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
858     return ConstantStruct::get(ST, Result);
859   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
860     return ConstantArray::get(AT, Result);
861   return ConstantVector::get(Result);
862 }
863
864
865 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
866                                               Constant *C1, Constant *C2) {
867   // No compile-time operations on this type yet.
868   if (C1->getType()->isPPC_FP128Ty())
869     return 0;
870
871   // Handle UndefValue up front.
872   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
873     switch (Opcode) {
874     case Instruction::Xor:
875       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
876         // Handle undef ^ undef -> 0 special case. This is a common
877         // idiom (misuse).
878         return Constant::getNullValue(C1->getType());
879       // Fallthrough
880     case Instruction::Add:
881     case Instruction::Sub:
882       return UndefValue::get(C1->getType());
883     case Instruction::And:
884       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
885         return C1;
886       return Constant::getNullValue(C1->getType());   // undef & X -> 0
887     case Instruction::Mul: {
888       ConstantInt *CI;
889       // X * undef -> undef   if X is odd or undef
890       if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
891           ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
892           (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
893         return UndefValue::get(C1->getType());
894
895       // X * undef -> 0       otherwise
896       return Constant::getNullValue(C1->getType());
897     }
898     case Instruction::UDiv:
899     case Instruction::SDiv:
900       // undef / 1 -> undef
901       if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
902         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
903           if (CI2->isOne())
904             return C1;
905       // FALL THROUGH
906     case Instruction::URem:
907     case Instruction::SRem:
908       if (!isa<UndefValue>(C2))                    // undef / X -> 0
909         return Constant::getNullValue(C1->getType());
910       return C2;                                   // X / undef -> undef
911     case Instruction::Or:                          // X | undef -> -1
912       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
913         return C1;
914       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
915     case Instruction::LShr:
916       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
917         return C1;                                  // undef lshr undef -> undef
918       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
919                                                     // undef lshr X -> 0
920     case Instruction::AShr:
921       if (!isa<UndefValue>(C2))                     // undef ashr X --> all ones
922         return Constant::getAllOnesValue(C1->getType());
923       else if (isa<UndefValue>(C1)) 
924         return C1;                                  // undef ashr undef -> undef
925       else
926         return C1;                                  // X ashr undef --> X
927     case Instruction::Shl:
928       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
929         return C1;                                  // undef shl undef -> undef
930       // undef << X -> 0   or   X << undef -> 0
931       return Constant::getNullValue(C1->getType());
932     }
933   }
934
935   // Handle simplifications when the RHS is a constant int.
936   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
937     switch (Opcode) {
938     case Instruction::Add:
939       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
940       break;
941     case Instruction::Sub:
942       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
943       break;
944     case Instruction::Mul:
945       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
946       if (CI2->equalsInt(1))
947         return C1;                                              // X * 1 == X
948       break;
949     case Instruction::UDiv:
950     case Instruction::SDiv:
951       if (CI2->equalsInt(1))
952         return C1;                                            // X / 1 == X
953       if (CI2->equalsInt(0))
954         return UndefValue::get(CI2->getType());               // X / 0 == undef
955       break;
956     case Instruction::URem:
957     case Instruction::SRem:
958       if (CI2->equalsInt(1))
959         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
960       if (CI2->equalsInt(0))
961         return UndefValue::get(CI2->getType());               // X % 0 == undef
962       break;
963     case Instruction::And:
964       if (CI2->isZero()) return C2;                           // X & 0 == 0
965       if (CI2->isAllOnesValue())
966         return C1;                                            // X & -1 == X
967
968       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
969         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
970         if (CE1->getOpcode() == Instruction::ZExt) {
971           unsigned DstWidth = CI2->getType()->getBitWidth();
972           unsigned SrcWidth =
973             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
974           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
975           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
976             return C1;
977         }
978
979         // If and'ing the address of a global with a constant, fold it.
980         if (CE1->getOpcode() == Instruction::PtrToInt && 
981             isa<GlobalValue>(CE1->getOperand(0))) {
982           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
983
984           // Functions are at least 4-byte aligned.
985           unsigned GVAlign = GV->getAlignment();
986           if (isa<Function>(GV))
987             GVAlign = std::max(GVAlign, 4U);
988
989           if (GVAlign > 1) {
990             unsigned DstWidth = CI2->getType()->getBitWidth();
991             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
992             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
993
994             // If checking bits we know are clear, return zero.
995             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
996               return Constant::getNullValue(CI2->getType());
997           }
998         }
999       }
1000       break;
1001     case Instruction::Or:
1002       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
1003       if (CI2->isAllOnesValue())
1004         return C2;                         // X | -1 == -1
1005       break;
1006     case Instruction::Xor:
1007       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
1008
1009       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1010         switch (CE1->getOpcode()) {
1011         default: break;
1012         case Instruction::ICmp:
1013         case Instruction::FCmp:
1014           // cmp pred ^ true -> cmp !pred
1015           assert(CI2->equalsInt(1));
1016           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1017           pred = CmpInst::getInversePredicate(pred);
1018           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1019                                           CE1->getOperand(1));
1020         }
1021       }
1022       break;
1023     case Instruction::AShr:
1024       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1025       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1026         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1027           return ConstantExpr::getLShr(C1, C2);
1028       break;
1029     }
1030   } else if (isa<ConstantInt>(C1)) {
1031     // If C1 is a ConstantInt and C2 is not, swap the operands.
1032     if (Instruction::isCommutative(Opcode))
1033       return ConstantExpr::get(Opcode, C2, C1);
1034   }
1035
1036   // At this point we know neither constant is an UndefValue.
1037   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1038     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1039       const APInt &C1V = CI1->getValue();
1040       const APInt &C2V = CI2->getValue();
1041       switch (Opcode) {
1042       default:
1043         break;
1044       case Instruction::Add:     
1045         return ConstantInt::get(CI1->getContext(), C1V + C2V);
1046       case Instruction::Sub:     
1047         return ConstantInt::get(CI1->getContext(), C1V - C2V);
1048       case Instruction::Mul:     
1049         return ConstantInt::get(CI1->getContext(), C1V * C2V);
1050       case Instruction::UDiv:
1051         assert(!CI2->isNullValue() && "Div by zero handled above");
1052         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1053       case Instruction::SDiv:
1054         assert(!CI2->isNullValue() && "Div by zero handled above");
1055         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1056           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1057         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1058       case Instruction::URem:
1059         assert(!CI2->isNullValue() && "Div by zero handled above");
1060         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1061       case Instruction::SRem:
1062         assert(!CI2->isNullValue() && "Div by zero handled above");
1063         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1064           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1065         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1066       case Instruction::And:
1067         return ConstantInt::get(CI1->getContext(), C1V & C2V);
1068       case Instruction::Or:
1069         return ConstantInt::get(CI1->getContext(), C1V | C2V);
1070       case Instruction::Xor:
1071         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1072       case Instruction::Shl: {
1073         uint32_t shiftAmt = C2V.getZExtValue();
1074         if (shiftAmt < C1V.getBitWidth())
1075           return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1076         else
1077           return UndefValue::get(C1->getType()); // too big shift is undef
1078       }
1079       case Instruction::LShr: {
1080         uint32_t shiftAmt = C2V.getZExtValue();
1081         if (shiftAmt < C1V.getBitWidth())
1082           return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1083         else
1084           return UndefValue::get(C1->getType()); // too big shift is undef
1085       }
1086       case Instruction::AShr: {
1087         uint32_t shiftAmt = C2V.getZExtValue();
1088         if (shiftAmt < C1V.getBitWidth())
1089           return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1090         else
1091           return UndefValue::get(C1->getType()); // too big shift is undef
1092       }
1093       }
1094     }
1095
1096     switch (Opcode) {
1097     case Instruction::SDiv:
1098     case Instruction::UDiv:
1099     case Instruction::URem:
1100     case Instruction::SRem:
1101     case Instruction::LShr:
1102     case Instruction::AShr:
1103     case Instruction::Shl:
1104       if (CI1->equalsInt(0)) return C1;
1105       break;
1106     default:
1107       break;
1108     }
1109   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1110     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1111       APFloat C1V = CFP1->getValueAPF();
1112       APFloat C2V = CFP2->getValueAPF();
1113       APFloat C3V = C1V;  // copy for modification
1114       switch (Opcode) {
1115       default:                   
1116         break;
1117       case Instruction::FAdd:
1118         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1119         return ConstantFP::get(C1->getContext(), C3V);
1120       case Instruction::FSub:
1121         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1122         return ConstantFP::get(C1->getContext(), C3V);
1123       case Instruction::FMul:
1124         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1125         return ConstantFP::get(C1->getContext(), C3V);
1126       case Instruction::FDiv:
1127         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1128         return ConstantFP::get(C1->getContext(), C3V);
1129       case Instruction::FRem:
1130         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1131         return ConstantFP::get(C1->getContext(), C3V);
1132       }
1133     }
1134   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1135     // Perform elementwise folding.
1136     SmallVector<Constant*, 16> Result;
1137     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1138       Constant *LHS = C1->getAggregateElement(i);
1139       Constant *RHS = C2->getAggregateElement(i);
1140       if (LHS == 0 || RHS == 0) break;
1141       
1142       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1143     }
1144     
1145     if (Result.size() == VTy->getNumElements())
1146       return ConstantVector::get(Result);
1147   }
1148
1149   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1150     // There are many possible foldings we could do here.  We should probably
1151     // at least fold add of a pointer with an integer into the appropriate
1152     // getelementptr.  This will improve alias analysis a bit.
1153
1154     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1155     // (a + (b + c)).
1156     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1157       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1158       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1159         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1160     }
1161   } else if (isa<ConstantExpr>(C2)) {
1162     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1163     // other way if possible.
1164     if (Instruction::isCommutative(Opcode))
1165       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1166   }
1167
1168   // i1 can be simplified in many cases.
1169   if (C1->getType()->isIntegerTy(1)) {
1170     switch (Opcode) {
1171     case Instruction::Add:
1172     case Instruction::Sub:
1173       return ConstantExpr::getXor(C1, C2);
1174     case Instruction::Mul:
1175       return ConstantExpr::getAnd(C1, C2);
1176     case Instruction::Shl:
1177     case Instruction::LShr:
1178     case Instruction::AShr:
1179       // We can assume that C2 == 0.  If it were one the result would be
1180       // undefined because the shift value is as large as the bitwidth.
1181       return C1;
1182     case Instruction::SDiv:
1183     case Instruction::UDiv:
1184       // We can assume that C2 == 1.  If it were zero the result would be
1185       // undefined through division by zero.
1186       return C1;
1187     case Instruction::URem:
1188     case Instruction::SRem:
1189       // We can assume that C2 == 1.  If it were zero the result would be
1190       // undefined through division by zero.
1191       return ConstantInt::getFalse(C1->getContext());
1192     default:
1193       break;
1194     }
1195   }
1196
1197   // We don't know how to fold this.
1198   return 0;
1199 }
1200
1201 /// isZeroSizedType - This type is zero sized if its an array or structure of
1202 /// zero sized types.  The only leaf zero sized type is an empty structure.
1203 static bool isMaybeZeroSizedType(Type *Ty) {
1204   if (StructType *STy = dyn_cast<StructType>(Ty)) {
1205     if (STy->isOpaque()) return true;  // Can't say.
1206
1207     // If all of elements have zero size, this does too.
1208     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1209       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1210     return true;
1211
1212   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1213     return isMaybeZeroSizedType(ATy->getElementType());
1214   }
1215   return false;
1216 }
1217
1218 /// IdxCompare - Compare the two constants as though they were getelementptr
1219 /// indices.  This allows coersion of the types to be the same thing.
1220 ///
1221 /// If the two constants are the "same" (after coersion), return 0.  If the
1222 /// first is less than the second, return -1, if the second is less than the
1223 /// first, return 1.  If the constants are not integral, return -2.
1224 ///
1225 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1226   if (C1 == C2) return 0;
1227
1228   // Ok, we found a different index.  If they are not ConstantInt, we can't do
1229   // anything with them.
1230   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1231     return -2; // don't know!
1232
1233   // Ok, we have two differing integer indices.  Sign extend them to be the same
1234   // type.  Long is always big enough, so we use it.
1235   if (!C1->getType()->isIntegerTy(64))
1236     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1237
1238   if (!C2->getType()->isIntegerTy(64))
1239     C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1240
1241   if (C1 == C2) return 0;  // They are equal
1242
1243   // If the type being indexed over is really just a zero sized type, there is
1244   // no pointer difference being made here.
1245   if (isMaybeZeroSizedType(ElTy))
1246     return -2; // dunno.
1247
1248   // If they are really different, now that they are the same type, then we
1249   // found a difference!
1250   if (cast<ConstantInt>(C1)->getSExtValue() < 
1251       cast<ConstantInt>(C2)->getSExtValue())
1252     return -1;
1253   else
1254     return 1;
1255 }
1256
1257 /// evaluateFCmpRelation - This function determines if there is anything we can
1258 /// decide about the two constants provided.  This doesn't need to handle simple
1259 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1260 /// If we can determine that the two constants have a particular relation to 
1261 /// each other, we should return the corresponding FCmpInst predicate, 
1262 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1263 /// ConstantFoldCompareInstruction.
1264 ///
1265 /// To simplify this code we canonicalize the relation so that the first
1266 /// operand is always the most "complex" of the two.  We consider ConstantFP
1267 /// to be the simplest, and ConstantExprs to be the most complex.
1268 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1269   assert(V1->getType() == V2->getType() &&
1270          "Cannot compare values of different types!");
1271
1272   // No compile-time operations on this type yet.
1273   if (V1->getType()->isPPC_FP128Ty())
1274     return FCmpInst::BAD_FCMP_PREDICATE;
1275
1276   // Handle degenerate case quickly
1277   if (V1 == V2) return FCmpInst::FCMP_OEQ;
1278
1279   if (!isa<ConstantExpr>(V1)) {
1280     if (!isa<ConstantExpr>(V2)) {
1281       // We distilled thisUse the standard constant folder for a few cases
1282       ConstantInt *R = 0;
1283       R = dyn_cast<ConstantInt>(
1284                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1285       if (R && !R->isZero()) 
1286         return FCmpInst::FCMP_OEQ;
1287       R = dyn_cast<ConstantInt>(
1288                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1289       if (R && !R->isZero()) 
1290         return FCmpInst::FCMP_OLT;
1291       R = dyn_cast<ConstantInt>(
1292                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1293       if (R && !R->isZero()) 
1294         return FCmpInst::FCMP_OGT;
1295
1296       // Nothing more we can do
1297       return FCmpInst::BAD_FCMP_PREDICATE;
1298     }
1299
1300     // If the first operand is simple and second is ConstantExpr, swap operands.
1301     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1302     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1303       return FCmpInst::getSwappedPredicate(SwappedRelation);
1304   } else {
1305     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1306     // constantexpr or a simple constant.
1307     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1308     switch (CE1->getOpcode()) {
1309     case Instruction::FPTrunc:
1310     case Instruction::FPExt:
1311     case Instruction::UIToFP:
1312     case Instruction::SIToFP:
1313       // We might be able to do something with these but we don't right now.
1314       break;
1315     default:
1316       break;
1317     }
1318   }
1319   // There are MANY other foldings that we could perform here.  They will
1320   // probably be added on demand, as they seem needed.
1321   return FCmpInst::BAD_FCMP_PREDICATE;
1322 }
1323
1324 /// evaluateICmpRelation - This function determines if there is anything we can
1325 /// decide about the two constants provided.  This doesn't need to handle simple
1326 /// things like integer comparisons, but should instead handle ConstantExprs
1327 /// and GlobalValues.  If we can determine that the two constants have a
1328 /// particular relation to each other, we should return the corresponding ICmp
1329 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1330 ///
1331 /// To simplify this code we canonicalize the relation so that the first
1332 /// operand is always the most "complex" of the two.  We consider simple
1333 /// constants (like ConstantInt) to be the simplest, followed by
1334 /// GlobalValues, followed by ConstantExpr's (the most complex).
1335 ///
1336 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1337                                                 bool isSigned) {
1338   assert(V1->getType() == V2->getType() &&
1339          "Cannot compare different types of values!");
1340   if (V1 == V2) return ICmpInst::ICMP_EQ;
1341
1342   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1343       !isa<BlockAddress>(V1)) {
1344     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1345         !isa<BlockAddress>(V2)) {
1346       // We distilled this down to a simple case, use the standard constant
1347       // folder.
1348       ConstantInt *R = 0;
1349       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1350       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1351       if (R && !R->isZero()) 
1352         return pred;
1353       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1354       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1355       if (R && !R->isZero())
1356         return pred;
1357       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1358       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1359       if (R && !R->isZero())
1360         return pred;
1361
1362       // If we couldn't figure it out, bail.
1363       return ICmpInst::BAD_ICMP_PREDICATE;
1364     }
1365
1366     // If the first operand is simple, swap operands.
1367     ICmpInst::Predicate SwappedRelation = 
1368       evaluateICmpRelation(V2, V1, isSigned);
1369     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1370       return ICmpInst::getSwappedPredicate(SwappedRelation);
1371
1372   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1373     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1374       ICmpInst::Predicate SwappedRelation = 
1375         evaluateICmpRelation(V2, V1, isSigned);
1376       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1377         return ICmpInst::getSwappedPredicate(SwappedRelation);
1378       return ICmpInst::BAD_ICMP_PREDICATE;
1379     }
1380
1381     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1382     // constant (which, since the types must match, means that it's a
1383     // ConstantPointerNull).
1384     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1385       // Don't try to decide equality of aliases.
1386       if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1387         if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1388           return ICmpInst::ICMP_NE;
1389     } else if (isa<BlockAddress>(V2)) {
1390       return ICmpInst::ICMP_NE; // Globals never equal labels.
1391     } else {
1392       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1393       // GlobalVals can never be null unless they have external weak linkage.
1394       // We don't try to evaluate aliases here.
1395       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1396         return ICmpInst::ICMP_NE;
1397     }
1398   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1399     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1400       ICmpInst::Predicate SwappedRelation = 
1401         evaluateICmpRelation(V2, V1, isSigned);
1402       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1403         return ICmpInst::getSwappedPredicate(SwappedRelation);
1404       return ICmpInst::BAD_ICMP_PREDICATE;
1405     }
1406     
1407     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1408     // constant (which, since the types must match, means that it is a
1409     // ConstantPointerNull).
1410     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1411       // Block address in another function can't equal this one, but block
1412       // addresses in the current function might be the same if blocks are
1413       // empty.
1414       if (BA2->getFunction() != BA->getFunction())
1415         return ICmpInst::ICMP_NE;
1416     } else {
1417       // Block addresses aren't null, don't equal the address of globals.
1418       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1419              "Canonicalization guarantee!");
1420       return ICmpInst::ICMP_NE;
1421     }
1422   } else {
1423     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1424     // constantexpr, a global, block address, or a simple constant.
1425     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1426     Constant *CE1Op0 = CE1->getOperand(0);
1427
1428     switch (CE1->getOpcode()) {
1429     case Instruction::Trunc:
1430     case Instruction::FPTrunc:
1431     case Instruction::FPExt:
1432     case Instruction::FPToUI:
1433     case Instruction::FPToSI:
1434       break; // We can't evaluate floating point casts or truncations.
1435
1436     case Instruction::UIToFP:
1437     case Instruction::SIToFP:
1438     case Instruction::BitCast:
1439     case Instruction::ZExt:
1440     case Instruction::SExt:
1441       // If the cast is not actually changing bits, and the second operand is a
1442       // null pointer, do the comparison with the pre-casted value.
1443       if (V2->isNullValue() &&
1444           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1445         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1446         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1447         return evaluateICmpRelation(CE1Op0,
1448                                     Constant::getNullValue(CE1Op0->getType()), 
1449                                     isSigned);
1450       }
1451       break;
1452
1453     case Instruction::GetElementPtr:
1454       // Ok, since this is a getelementptr, we know that the constant has a
1455       // pointer type.  Check the various cases.
1456       if (isa<ConstantPointerNull>(V2)) {
1457         // If we are comparing a GEP to a null pointer, check to see if the base
1458         // of the GEP equals the null pointer.
1459         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1460           if (GV->hasExternalWeakLinkage())
1461             // Weak linkage GVals could be zero or not. We're comparing that
1462             // to null pointer so its greater-or-equal
1463             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1464           else 
1465             // If its not weak linkage, the GVal must have a non-zero address
1466             // so the result is greater-than
1467             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1468         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1469           // If we are indexing from a null pointer, check to see if we have any
1470           // non-zero indices.
1471           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1472             if (!CE1->getOperand(i)->isNullValue())
1473               // Offsetting from null, must not be equal.
1474               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1475           // Only zero indexes from null, must still be zero.
1476           return ICmpInst::ICMP_EQ;
1477         }
1478         // Otherwise, we can't really say if the first operand is null or not.
1479       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1480         if (isa<ConstantPointerNull>(CE1Op0)) {
1481           if (GV2->hasExternalWeakLinkage())
1482             // Weak linkage GVals could be zero or not. We're comparing it to
1483             // a null pointer, so its less-or-equal
1484             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1485           else
1486             // If its not weak linkage, the GVal must have a non-zero address
1487             // so the result is less-than
1488             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1489         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1490           if (GV == GV2) {
1491             // If this is a getelementptr of the same global, then it must be
1492             // different.  Because the types must match, the getelementptr could
1493             // only have at most one index, and because we fold getelementptr's
1494             // with a single zero index, it must be nonzero.
1495             assert(CE1->getNumOperands() == 2 &&
1496                    !CE1->getOperand(1)->isNullValue() &&
1497                    "Surprising getelementptr!");
1498             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1499           } else {
1500             // If they are different globals, we don't know what the value is,
1501             // but they can't be equal.
1502             return ICmpInst::ICMP_NE;
1503           }
1504         }
1505       } else {
1506         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1507         Constant *CE2Op0 = CE2->getOperand(0);
1508
1509         // There are MANY other foldings that we could perform here.  They will
1510         // probably be added on demand, as they seem needed.
1511         switch (CE2->getOpcode()) {
1512         default: break;
1513         case Instruction::GetElementPtr:
1514           // By far the most common case to handle is when the base pointers are
1515           // obviously to the same or different globals.
1516           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1517             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1518               return ICmpInst::ICMP_NE;
1519             // Ok, we know that both getelementptr instructions are based on the
1520             // same global.  From this, we can precisely determine the relative
1521             // ordering of the resultant pointers.
1522             unsigned i = 1;
1523
1524             // The logic below assumes that the result of the comparison
1525             // can be determined by finding the first index that differs.
1526             // This doesn't work if there is over-indexing in any
1527             // subsequent indices, so check for that case first.
1528             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1529                 !CE2->isGEPWithNoNotionalOverIndexing())
1530                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1531
1532             // Compare all of the operands the GEP's have in common.
1533             gep_type_iterator GTI = gep_type_begin(CE1);
1534             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1535                  ++i, ++GTI)
1536               switch (IdxCompare(CE1->getOperand(i),
1537                                  CE2->getOperand(i), GTI.getIndexedType())) {
1538               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1539               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1540               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1541               }
1542
1543             // Ok, we ran out of things they have in common.  If any leftovers
1544             // are non-zero then we have a difference, otherwise we are equal.
1545             for (; i < CE1->getNumOperands(); ++i)
1546               if (!CE1->getOperand(i)->isNullValue()) {
1547                 if (isa<ConstantInt>(CE1->getOperand(i)))
1548                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1549                 else
1550                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1551               }
1552
1553             for (; i < CE2->getNumOperands(); ++i)
1554               if (!CE2->getOperand(i)->isNullValue()) {
1555                 if (isa<ConstantInt>(CE2->getOperand(i)))
1556                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1557                 else
1558                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1559               }
1560             return ICmpInst::ICMP_EQ;
1561           }
1562         }
1563       }
1564     default:
1565       break;
1566     }
1567   }
1568
1569   return ICmpInst::BAD_ICMP_PREDICATE;
1570 }
1571
1572 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
1573                                                Constant *C1, Constant *C2) {
1574   Type *ResultTy;
1575   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1576     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1577                                VT->getNumElements());
1578   else
1579     ResultTy = Type::getInt1Ty(C1->getContext());
1580
1581   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1582   if (pred == FCmpInst::FCMP_FALSE)
1583     return Constant::getNullValue(ResultTy);
1584
1585   if (pred == FCmpInst::FCMP_TRUE)
1586     return Constant::getAllOnesValue(ResultTy);
1587
1588   // Handle some degenerate cases first
1589   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1590     // For EQ and NE, we can always pick a value for the undef to make the
1591     // predicate pass or fail, so we can return undef.
1592     // Also, if both operands are undef, we can return undef.
1593     if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1594         (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1595       return UndefValue::get(ResultTy);
1596     // Otherwise, pick the same value as the non-undef operand, and fold
1597     // it to true or false.
1598     return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1599   }
1600
1601   // No compile-time operations on this type yet.
1602   if (C1->getType()->isPPC_FP128Ty())
1603     return 0;
1604
1605   // icmp eq/ne(null,GV) -> false/true
1606   if (C1->isNullValue()) {
1607     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1608       // Don't try to evaluate aliases.  External weak GV can be null.
1609       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1610         if (pred == ICmpInst::ICMP_EQ)
1611           return ConstantInt::getFalse(C1->getContext());
1612         else if (pred == ICmpInst::ICMP_NE)
1613           return ConstantInt::getTrue(C1->getContext());
1614       }
1615   // icmp eq/ne(GV,null) -> false/true
1616   } else if (C2->isNullValue()) {
1617     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
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   }
1626
1627   // If the comparison is a comparison between two i1's, simplify it.
1628   if (C1->getType()->isIntegerTy(1)) {
1629     switch(pred) {
1630     case ICmpInst::ICMP_EQ:
1631       if (isa<ConstantInt>(C2))
1632         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1633       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1634     case ICmpInst::ICMP_NE:
1635       return ConstantExpr::getXor(C1, C2);
1636     default:
1637       break;
1638     }
1639   }
1640
1641   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1642     APInt V1 = cast<ConstantInt>(C1)->getValue();
1643     APInt V2 = cast<ConstantInt>(C2)->getValue();
1644     switch (pred) {
1645     default: llvm_unreachable("Invalid ICmp Predicate");
1646     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1647     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1648     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1649     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1650     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1651     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1652     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1653     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1654     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1655     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1656     }
1657   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1658     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1659     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1660     APFloat::cmpResult R = C1V.compare(C2V);
1661     switch (pred) {
1662     default: llvm_unreachable("Invalid FCmp Predicate");
1663     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1664     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
1665     case FCmpInst::FCMP_UNO:
1666       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1667     case FCmpInst::FCMP_ORD:
1668       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1669     case FCmpInst::FCMP_UEQ:
1670       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1671                                         R==APFloat::cmpEqual);
1672     case FCmpInst::FCMP_OEQ:   
1673       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1674     case FCmpInst::FCMP_UNE:
1675       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1676     case FCmpInst::FCMP_ONE:   
1677       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1678                                         R==APFloat::cmpGreaterThan);
1679     case FCmpInst::FCMP_ULT: 
1680       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1681                                         R==APFloat::cmpLessThan);
1682     case FCmpInst::FCMP_OLT:   
1683       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1684     case FCmpInst::FCMP_UGT:
1685       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1686                                         R==APFloat::cmpGreaterThan);
1687     case FCmpInst::FCMP_OGT:
1688       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1689     case FCmpInst::FCMP_ULE:
1690       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1691     case FCmpInst::FCMP_OLE: 
1692       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1693                                         R==APFloat::cmpEqual);
1694     case FCmpInst::FCMP_UGE:
1695       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1696     case FCmpInst::FCMP_OGE: 
1697       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1698                                         R==APFloat::cmpEqual);
1699     }
1700   } else if (C1->getType()->isVectorTy()) {
1701     // If we can constant fold the comparison of each element, constant fold
1702     // the whole vector comparison.
1703     SmallVector<Constant*, 4> ResElts;
1704     // Compare the elements, producing an i1 result or constant expr.
1705     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1706       Constant *C1E = C1->getAggregateElement(i);
1707       Constant *C2E = C2->getAggregateElement(i);
1708       if (C1E == 0 || C2E == 0) break;
1709       
1710       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1711     }
1712     
1713     if (ResElts.size() == C1->getType()->getVectorNumElements())
1714       return ConstantVector::get(ResElts);
1715   }
1716
1717   if (C1->getType()->isFloatingPointTy()) {
1718     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1719     switch (evaluateFCmpRelation(C1, C2)) {
1720     default: llvm_unreachable("Unknown relation!");
1721     case FCmpInst::FCMP_UNO:
1722     case FCmpInst::FCMP_ORD:
1723     case FCmpInst::FCMP_UEQ:
1724     case FCmpInst::FCMP_UNE:
1725     case FCmpInst::FCMP_ULT:
1726     case FCmpInst::FCMP_UGT:
1727     case FCmpInst::FCMP_ULE:
1728     case FCmpInst::FCMP_UGE:
1729     case FCmpInst::FCMP_TRUE:
1730     case FCmpInst::FCMP_FALSE:
1731     case FCmpInst::BAD_FCMP_PREDICATE:
1732       break; // Couldn't determine anything about these constants.
1733     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1734       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1735                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1736                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1737       break;
1738     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1739       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1740                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1741                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1742       break;
1743     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1744       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1745                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1746                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1747       break;
1748     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1749       // We can only partially decide this relation.
1750       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1751         Result = 0;
1752       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1753         Result = 1;
1754       break;
1755     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1756       // We can only partially decide this relation.
1757       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1758         Result = 0;
1759       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1760         Result = 1;
1761       break;
1762     case FCmpInst::FCMP_ONE: // We know that C1 != C2
1763       // We can only partially decide this relation.
1764       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1765         Result = 0;
1766       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1767         Result = 1;
1768       break;
1769     }
1770
1771     // If we evaluated the result, return it now.
1772     if (Result != -1)
1773       return ConstantInt::get(ResultTy, Result);
1774
1775   } else {
1776     // Evaluate the relation between the two constants, per the predicate.
1777     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1778     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1779     default: llvm_unreachable("Unknown relational!");
1780     case ICmpInst::BAD_ICMP_PREDICATE:
1781       break;  // Couldn't determine anything about these constants.
1782     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1783       // If we know the constants are equal, we can decide the result of this
1784       // computation precisely.
1785       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1786       break;
1787     case ICmpInst::ICMP_ULT:
1788       switch (pred) {
1789       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1790         Result = 1; break;
1791       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1792         Result = 0; break;
1793       }
1794       break;
1795     case ICmpInst::ICMP_SLT:
1796       switch (pred) {
1797       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1798         Result = 1; break;
1799       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1800         Result = 0; break;
1801       }
1802       break;
1803     case ICmpInst::ICMP_UGT:
1804       switch (pred) {
1805       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1806         Result = 1; break;
1807       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1808         Result = 0; break;
1809       }
1810       break;
1811     case ICmpInst::ICMP_SGT:
1812       switch (pred) {
1813       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1814         Result = 1; break;
1815       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1816         Result = 0; break;
1817       }
1818       break;
1819     case ICmpInst::ICMP_ULE:
1820       if (pred == ICmpInst::ICMP_UGT) Result = 0;
1821       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1822       break;
1823     case ICmpInst::ICMP_SLE:
1824       if (pred == ICmpInst::ICMP_SGT) Result = 0;
1825       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1826       break;
1827     case ICmpInst::ICMP_UGE:
1828       if (pred == ICmpInst::ICMP_ULT) Result = 0;
1829       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1830       break;
1831     case ICmpInst::ICMP_SGE:
1832       if (pred == ICmpInst::ICMP_SLT) Result = 0;
1833       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1834       break;
1835     case ICmpInst::ICMP_NE:
1836       if (pred == ICmpInst::ICMP_EQ) Result = 0;
1837       if (pred == ICmpInst::ICMP_NE) Result = 1;
1838       break;
1839     }
1840
1841     // If we evaluated the result, return it now.
1842     if (Result != -1)
1843       return ConstantInt::get(ResultTy, Result);
1844
1845     // If the right hand side is a bitcast, try using its inverse to simplify
1846     // it by moving it to the left hand side.  We can't do this if it would turn
1847     // a vector compare into a scalar compare or visa versa.
1848     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1849       Constant *CE2Op0 = CE2->getOperand(0);
1850       if (CE2->getOpcode() == Instruction::BitCast &&
1851           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1852         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1853         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1854       }
1855     }
1856
1857     // If the left hand side is an extension, try eliminating it.
1858     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1859       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1860           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1861         Constant *CE1Op0 = CE1->getOperand(0);
1862         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1863         if (CE1Inverse == CE1Op0) {
1864           // Check whether we can safely truncate the right hand side.
1865           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1866           if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
1867             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1868           }
1869         }
1870       }
1871     }
1872
1873     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1874         (C1->isNullValue() && !C2->isNullValue())) {
1875       // If C2 is a constant expr and C1 isn't, flip them around and fold the
1876       // other way if possible.
1877       // Also, if C1 is null and C2 isn't, flip them around.
1878       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1879       return ConstantExpr::getICmp(pred, C2, C1);
1880     }
1881   }
1882   return 0;
1883 }
1884
1885 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1886 /// is "inbounds".
1887 template<typename IndexTy>
1888 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1889   // No indices means nothing that could be out of bounds.
1890   if (Idxs.empty()) return true;
1891
1892   // If the first index is zero, it's in bounds.
1893   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1894
1895   // If the first index is one and all the rest are zero, it's in bounds,
1896   // by the one-past-the-end rule.
1897   if (!cast<ConstantInt>(Idxs[0])->isOne())
1898     return false;
1899   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1900     if (!cast<Constant>(Idxs[i])->isNullValue())
1901       return false;
1902   return true;
1903 }
1904
1905 template<typename IndexTy>
1906 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1907                                                bool inBounds,
1908                                                ArrayRef<IndexTy> Idxs) {
1909   if (Idxs.empty()) return C;
1910   Constant *Idx0 = cast<Constant>(Idxs[0]);
1911   if ((Idxs.size() == 1 && Idx0->isNullValue()))
1912     return C;
1913
1914   if (isa<UndefValue>(C)) {
1915     PointerType *Ptr = cast<PointerType>(C->getType());
1916     Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1917     assert(Ty != 0 && "Invalid indices for GEP!");
1918     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1919   }
1920
1921   if (C->isNullValue()) {
1922     bool isNull = true;
1923     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1924       if (!cast<Constant>(Idxs[i])->isNullValue()) {
1925         isNull = false;
1926         break;
1927       }
1928     if (isNull) {
1929       PointerType *Ptr = cast<PointerType>(C->getType());
1930       Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1931       assert(Ty != 0 && "Invalid indices for GEP!");
1932       return ConstantPointerNull::get(PointerType::get(Ty,
1933                                                        Ptr->getAddressSpace()));
1934     }
1935   }
1936
1937   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1938     // Combine Indices - If the source pointer to this getelementptr instruction
1939     // is a getelementptr instruction, combine the indices of the two
1940     // getelementptr instructions into a single instruction.
1941     //
1942     if (CE->getOpcode() == Instruction::GetElementPtr) {
1943       Type *LastTy = 0;
1944       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1945            I != E; ++I)
1946         LastTy = *I;
1947
1948       if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
1949         SmallVector<Value*, 16> NewIndices;
1950         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
1951         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1952           NewIndices.push_back(CE->getOperand(i));
1953
1954         // Add the last index of the source with the first index of the new GEP.
1955         // Make sure to handle the case when they are actually different types.
1956         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1957         // Otherwise it must be an array.
1958         if (!Idx0->isNullValue()) {
1959           Type *IdxTy = Combined->getType();
1960           if (IdxTy != Idx0->getType()) {
1961             Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
1962             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
1963             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
1964             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1965           } else {
1966             Combined =
1967               ConstantExpr::get(Instruction::Add, Idx0, Combined);
1968           }
1969         }
1970
1971         NewIndices.push_back(Combined);
1972         NewIndices.append(Idxs.begin() + 1, Idxs.end());
1973         return
1974           ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
1975                                          inBounds &&
1976                                            cast<GEPOperator>(CE)->isInBounds());
1977       }
1978     }
1979
1980     // Implement folding of:
1981     //    i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
1982     //                        i64 0, i64 0)
1983     // To: i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
1984     //
1985     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
1986       if (PointerType *SPT =
1987           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1988         if (ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1989           if (ArrayType *CAT =
1990         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1991             if (CAT->getElementType() == SAT->getElementType())
1992               return
1993                 ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
1994                                                Idxs, inBounds);
1995     }
1996   }
1997
1998   // Check to see if any array indices are not within the corresponding
1999   // notional array bounds. If so, try to determine if they can be factored
2000   // out into preceding dimensions.
2001   bool Unknown = false;
2002   SmallVector<Constant *, 8> NewIdxs;
2003   Type *Ty = C->getType();
2004   Type *Prev = 0;
2005   for (unsigned i = 0, e = Idxs.size(); i != e;
2006        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2007     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2008       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2009         if (ATy->getNumElements() <= INT64_MAX &&
2010             ATy->getNumElements() != 0 &&
2011             CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2012           if (isa<SequentialType>(Prev)) {
2013             // It's out of range, but we can factor it into the prior
2014             // dimension.
2015             NewIdxs.resize(Idxs.size());
2016             ConstantInt *Factor = ConstantInt::get(CI->getType(),
2017                                                    ATy->getNumElements());
2018             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2019
2020             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2021             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2022
2023             // Before adding, extend both operands to i64 to avoid
2024             // overflow trouble.
2025             if (!PrevIdx->getType()->isIntegerTy(64))
2026               PrevIdx = ConstantExpr::getSExt(PrevIdx,
2027                                            Type::getInt64Ty(Div->getContext()));
2028             if (!Div->getType()->isIntegerTy(64))
2029               Div = ConstantExpr::getSExt(Div,
2030                                           Type::getInt64Ty(Div->getContext()));
2031
2032             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2033           } else {
2034             // It's out of range, but the prior dimension is a struct
2035             // so we can't do anything about it.
2036             Unknown = true;
2037           }
2038         }
2039     } else {
2040       // We don't know if it's in range or not.
2041       Unknown = true;
2042     }
2043   }
2044
2045   // If we did any factoring, start over with the adjusted indices.
2046   if (!NewIdxs.empty()) {
2047     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2048       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2049     return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2050   }
2051
2052   // If all indices are known integers and normalized, we can do a simple
2053   // check for the "inbounds" property.
2054   if (!Unknown && !inBounds &&
2055       isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
2056     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2057
2058   return 0;
2059 }
2060
2061 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2062                                           bool inBounds,
2063                                           ArrayRef<Constant *> Idxs) {
2064   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2065 }
2066
2067 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2068                                           bool inBounds,
2069                                           ArrayRef<Value *> Idxs) {
2070   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2071 }