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