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