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