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