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