1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
18 //===----------------------------------------------------------------------===//
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"
37 //===----------------------------------------------------------------------===//
38 // ConstantFold*Instruction Implementations
39 //===----------------------------------------------------------------------===//
41 /// BitCastConstantVector - Convert the specified vector Constant node to the
42 /// specified vector type. At this point, we know that the elements of the
43 /// input vector constant are all simple integer or FP values.
44 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
46 if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
47 if (CV->isNullValue()) return Constant::getNullValue(DstTy);
49 // If this cast changes element count then we can't handle it here:
50 // doing so requires endianness information. This should be handled by
51 // Analysis/ConstantFolding.cpp
52 unsigned NumElts = DstTy->getNumElements();
53 if (NumElts != CV->getType()->getVectorNumElements())
56 Type *DstEltTy = DstTy->getElementType();
58 // Check to verify that all elements of the input are simple.
59 SmallVector<Constant*, 16> Result;
60 for (unsigned i = 0; i != NumElts; ++i) {
61 Constant *C = CV->getAggregateElement(i);
63 C = ConstantExpr::getBitCast(C, DstEltTy);
64 if (isa<ConstantExpr>(C)) return 0;
68 return ConstantVector::get(Result);
71 /// This function determines which opcode to use to fold two constant cast
72 /// expressions together. It uses CastInst::isEliminableCastPair to determine
73 /// the opcode. Consequently its just a wrapper around that function.
74 /// @brief Determine if it is valid to fold a cast of a cast
77 unsigned opc, ///< opcode of the second cast constant expression
78 ConstantExpr *Op, ///< the first cast constant expression
79 Type *DstTy ///< desintation type of the first cast
81 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
82 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
83 assert(CastInst::isCast(opc) && "Invalid cast opcode");
85 // The the types and opcodes for the two Cast constant expressions
86 Type *SrcTy = Op->getOperand(0)->getType();
87 Type *MidTy = Op->getType();
88 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
89 Instruction::CastOps secondOp = Instruction::CastOps(opc);
91 // Let CastInst::isEliminableCastPair do the heavy lifting.
92 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
93 Type::getInt64Ty(DstTy->getContext()));
96 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
97 Type *SrcTy = V->getType();
99 return V; // no-op cast
101 // Check to see if we are casting a pointer to an aggregate to a pointer to
102 // the first element. If so, return the appropriate GEP instruction.
103 if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
104 if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
105 if (PTy->getAddressSpace() == DPTy->getAddressSpace()
106 && DPTy->getElementType()->isSized()) {
107 SmallVector<Value*, 8> IdxList;
109 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
110 IdxList.push_back(Zero);
111 Type *ElTy = PTy->getElementType();
112 while (ElTy != DPTy->getElementType()) {
113 if (StructType *STy = dyn_cast<StructType>(ElTy)) {
114 if (STy->getNumElements() == 0) break;
115 ElTy = STy->getElementType(0);
116 IdxList.push_back(Zero);
117 } else if (SequentialType *STy =
118 dyn_cast<SequentialType>(ElTy)) {
119 if (ElTy->isPointerTy()) break; // Can't index into pointers!
120 ElTy = STy->getElementType();
121 IdxList.push_back(Zero);
127 if (ElTy == DPTy->getElementType())
128 // This GEP is inbounds because all indices are zero.
129 return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
132 // Handle casts from one vector constant to another. We know that the src
133 // and dest type have the same size (otherwise its an illegal cast).
134 if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
135 if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
136 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
137 "Not cast between same sized vectors!");
139 // First, check for null. Undef is already handled.
140 if (isa<ConstantAggregateZero>(V))
141 return Constant::getNullValue(DestTy);
143 // Handle ConstantVector and ConstantAggregateVector.
144 return BitCastConstantVector(V, DestPTy);
147 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
148 // This allows for other simplifications (although some of them
149 // can only be handled by Analysis/ConstantFolding.cpp).
150 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
151 return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
154 // Finally, implement bitcast folding now. The code below doesn't handle
156 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
157 return ConstantPointerNull::get(cast<PointerType>(DestTy));
159 // Handle integral constant input.
160 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
161 if (DestTy->isIntegerTy())
162 // Integral -> Integral. This is a no-op because the bit widths must
163 // be the same. Consequently, we just fold to V.
166 if (DestTy->isFloatingPointTy())
167 return ConstantFP::get(DestTy->getContext(),
168 APFloat(CI->getValue(),
169 !DestTy->isPPC_FP128Ty()));
171 // Otherwise, can't fold this (vector?)
175 // Handle ConstantFP input: FP -> Integral.
176 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
177 return ConstantInt::get(FP->getContext(),
178 FP->getValueAPF().bitcastToAPInt());
184 /// ExtractConstantBytes - V is an integer constant which only has a subset of
185 /// its bytes used. The bytes used are indicated by ByteStart (which is the
186 /// first byte used, counting from the least significant byte) and ByteSize,
187 /// which is the number of bytes used.
189 /// This function analyzes the specified constant to see if the specified byte
190 /// range can be returned as a simplified constant. If so, the constant is
191 /// returned, otherwise null is returned.
193 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
195 assert(C->getType()->isIntegerTy() &&
196 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
197 "Non-byte sized integer input");
198 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
199 assert(ByteSize && "Must be accessing some piece");
200 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
201 assert(ByteSize != CSize && "Should not extract everything");
203 // Constant Integers are simple.
204 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
205 APInt V = CI->getValue();
207 V = V.lshr(ByteStart*8);
208 V = V.trunc(ByteSize*8);
209 return ConstantInt::get(CI->getContext(), V);
212 // In the input is a constant expr, we might be able to recursively simplify.
213 // If not, we definitely can't do anything.
214 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
215 if (CE == 0) return 0;
217 switch (CE->getOpcode()) {
219 case Instruction::Or: {
220 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
225 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
226 if (RHSC->isAllOnesValue())
229 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
232 return ConstantExpr::getOr(LHS, RHS);
234 case Instruction::And: {
235 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
240 if (RHS->isNullValue())
243 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
246 return ConstantExpr::getAnd(LHS, RHS);
248 case Instruction::LShr: {
249 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
252 unsigned ShAmt = Amt->getZExtValue();
253 // Cannot analyze non-byte shifts.
254 if ((ShAmt & 7) != 0)
258 // If the extract is known to be all zeros, return zero.
259 if (ByteStart >= CSize-ShAmt)
260 return Constant::getNullValue(IntegerType::get(CE->getContext(),
262 // If the extract is known to be fully in the input, extract it.
263 if (ByteStart+ByteSize+ShAmt <= CSize)
264 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
266 // TODO: Handle the 'partially zero' case.
270 case Instruction::Shl: {
271 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
274 unsigned ShAmt = Amt->getZExtValue();
275 // Cannot analyze non-byte shifts.
276 if ((ShAmt & 7) != 0)
280 // If the extract is known to be all zeros, return zero.
281 if (ByteStart+ByteSize <= ShAmt)
282 return Constant::getNullValue(IntegerType::get(CE->getContext(),
284 // If the extract is known to be fully in the input, extract it.
285 if (ByteStart >= ShAmt)
286 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
288 // TODO: Handle the 'partially zero' case.
292 case Instruction::ZExt: {
293 unsigned SrcBitSize =
294 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
296 // If extracting something that is completely zero, return 0.
297 if (ByteStart*8 >= SrcBitSize)
298 return Constant::getNullValue(IntegerType::get(CE->getContext(),
301 // If exactly extracting the input, return it.
302 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
303 return CE->getOperand(0);
305 // If extracting something completely in the input, if if the input is a
306 // multiple of 8 bits, recurse.
307 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
308 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
310 // Otherwise, if extracting a subset of the input, which is not multiple of
311 // 8 bits, do a shift and trunc to get the bits.
312 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
313 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
314 Constant *Res = CE->getOperand(0);
316 Res = ConstantExpr::getLShr(Res,
317 ConstantInt::get(Res->getType(), ByteStart*8));
318 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
322 // TODO: Handle the 'partially zero' case.
328 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
329 /// on Ty, with any known factors factored out. If Folded is false,
330 /// return null if no factoring was possible, to avoid endlessly
331 /// bouncing an unfoldable expression back into the top-level folder.
333 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
335 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
336 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
337 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
338 return ConstantExpr::getNUWMul(E, N);
341 if (StructType *STy = dyn_cast<StructType>(Ty))
342 if (!STy->isPacked()) {
343 unsigned NumElems = STy->getNumElements();
344 // An empty struct has size zero.
346 return ConstantExpr::getNullValue(DestTy);
347 // Check for a struct with all members having the same size.
348 Constant *MemberSize =
349 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
351 for (unsigned i = 1; i != NumElems; ++i)
353 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
358 Constant *N = ConstantInt::get(DestTy, NumElems);
359 return ConstantExpr::getNUWMul(MemberSize, N);
363 // Pointer size doesn't depend on the pointee type, so canonicalize them
364 // to an arbitrary pointee.
365 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
366 if (!PTy->getElementType()->isIntegerTy(1))
368 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
369 PTy->getAddressSpace()),
372 // If there's no interesting folding happening, bail so that we don't create
373 // a constant that looks like it needs folding but really doesn't.
377 // Base case: Get a regular sizeof expression.
378 Constant *C = ConstantExpr::getSizeOf(Ty);
379 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
385 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
386 /// on Ty, with any known factors factored out. If Folded is false,
387 /// return null if no factoring was possible, to avoid endlessly
388 /// bouncing an unfoldable expression back into the top-level folder.
390 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
392 // The alignment of an array is equal to the alignment of the
393 // array element. Note that this is not always true for vectors.
394 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
395 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
396 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
403 if (StructType *STy = dyn_cast<StructType>(Ty)) {
404 // Packed structs always have an alignment of 1.
406 return ConstantInt::get(DestTy, 1);
408 // Otherwise, struct alignment is the maximum alignment of any member.
409 // Without target data, we can't compare much, but we can check to see
410 // if all the members have the same alignment.
411 unsigned NumElems = STy->getNumElements();
412 // An empty struct has minimal alignment.
414 return ConstantInt::get(DestTy, 1);
415 // Check for a struct with all members having the same alignment.
416 Constant *MemberAlign =
417 getFoldedAlignOf(STy->getElementType(0), DestTy, true);
419 for (unsigned i = 1; i != NumElems; ++i)
420 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
428 // Pointer alignment doesn't depend on the pointee type, so canonicalize them
429 // to an arbitrary pointee.
430 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
431 if (!PTy->getElementType()->isIntegerTy(1))
433 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
435 PTy->getAddressSpace()),
438 // If there's no interesting folding happening, bail so that we don't create
439 // a constant that looks like it needs folding but really doesn't.
443 // Base case: Get a regular alignof expression.
444 Constant *C = ConstantExpr::getAlignOf(Ty);
445 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
451 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
452 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
453 /// return null if no factoring was possible, to avoid endlessly
454 /// bouncing an unfoldable expression back into the top-level folder.
456 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
459 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
460 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
463 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
464 return ConstantExpr::getNUWMul(E, N);
467 if (StructType *STy = dyn_cast<StructType>(Ty))
468 if (!STy->isPacked()) {
469 unsigned NumElems = STy->getNumElements();
470 // An empty struct has no members.
473 // Check for a struct with all members having the same size.
474 Constant *MemberSize =
475 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
477 for (unsigned i = 1; i != NumElems; ++i)
479 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
484 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
489 return ConstantExpr::getNUWMul(MemberSize, N);
493 // If there's no interesting folding happening, bail so that we don't create
494 // a constant that looks like it needs folding but really doesn't.
498 // Base case: Get a regular offsetof expression.
499 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
500 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
506 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
508 if (isa<UndefValue>(V)) {
509 // zext(undef) = 0, because the top bits will be zero.
510 // sext(undef) = 0, because the top bits will all be the same.
511 // [us]itofp(undef) = 0, because the result value is bounded.
512 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
513 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
514 return Constant::getNullValue(DestTy);
515 return UndefValue::get(DestTy);
518 // No compile-time operations on this type yet.
519 if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
522 if (V->isNullValue() && !DestTy->isX86_MMXTy())
523 return Constant::getNullValue(DestTy);
525 // If the cast operand is a constant expression, there's a few things we can
526 // do to try to simplify it.
527 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
529 // Try hard to fold cast of cast because they are often eliminable.
530 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
531 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
532 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
533 // If all of the indexes in the GEP are null values, there is no pointer
534 // adjustment going on. We might as well cast the source pointer.
535 bool isAllNull = true;
536 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
537 if (!CE->getOperand(i)->isNullValue()) {
542 // This is casting one pointer type to another, always BitCast
543 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
547 // If the cast operand is a constant vector, perform the cast by
548 // operating on each element. In the cast of bitcasts, the element
549 // count may be mismatched; don't attempt to handle that here.
550 if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
551 DestTy->isVectorTy() &&
552 DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
553 SmallVector<Constant*, 16> res;
554 VectorType *DestVecTy = cast<VectorType>(DestTy);
555 Type *DstEltTy = DestVecTy->getElementType();
556 for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i)
557 res.push_back(ConstantExpr::getCast(opc,
558 V->getAggregateElement(i), DstEltTy));
559 return ConstantVector::get(res);
562 // We actually have to do a cast now. Perform the cast according to the
566 llvm_unreachable("Failed to cast constant expression");
567 case Instruction::FPTrunc:
568 case Instruction::FPExt:
569 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
571 APFloat Val = FPC->getValueAPF();
572 Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
573 DestTy->isFloatTy() ? APFloat::IEEEsingle :
574 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
575 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
576 DestTy->isFP128Ty() ? APFloat::IEEEquad :
578 APFloat::rmNearestTiesToEven, &ignored);
579 return ConstantFP::get(V->getContext(), Val);
581 return 0; // Can't fold.
582 case Instruction::FPToUI:
583 case Instruction::FPToSI:
584 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
585 const APFloat &V = FPC->getValueAPF();
588 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
589 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
590 APFloat::rmTowardZero, &ignored);
591 APInt Val(DestBitWidth, x);
592 return ConstantInt::get(FPC->getContext(), Val);
594 return 0; // Can't fold.
595 case Instruction::IntToPtr: //always treated as unsigned
596 if (V->isNullValue()) // Is it an integral null value?
597 return ConstantPointerNull::get(cast<PointerType>(DestTy));
598 return 0; // Other pointer types cannot be casted
599 case Instruction::PtrToInt: // always treated as unsigned
600 // Is it a null pointer value?
601 if (V->isNullValue())
602 return ConstantInt::get(DestTy, 0);
603 // If this is a sizeof-like expression, pull out multiplications by
604 // known factors to expose them to subsequent folding. If it's an
605 // alignof-like expression, factor out known factors.
606 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607 if (CE->getOpcode() == Instruction::GetElementPtr &&
608 CE->getOperand(0)->isNullValue()) {
610 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
611 if (CE->getNumOperands() == 2) {
612 // Handle a sizeof-like expression.
613 Constant *Idx = CE->getOperand(1);
614 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
615 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
616 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
619 return ConstantExpr::getMul(C, Idx);
621 } else if (CE->getNumOperands() == 3 &&
622 CE->getOperand(1)->isNullValue()) {
623 // Handle an alignof-like expression.
624 if (StructType *STy = dyn_cast<StructType>(Ty))
625 if (!STy->isPacked()) {
626 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
628 STy->getNumElements() == 2 &&
629 STy->getElementType(0)->isIntegerTy(1)) {
630 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
633 // Handle an offsetof-like expression.
634 if (Ty->isStructTy() || Ty->isArrayTy()) {
635 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
641 // Other pointer types cannot be casted
643 case Instruction::UIToFP:
644 case Instruction::SIToFP:
645 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
646 APInt api = CI->getValue();
647 APFloat apf(APInt::getNullValue(DestTy->getPrimitiveSizeInBits()), true);
648 (void)apf.convertFromAPInt(api,
649 opc==Instruction::SIToFP,
650 APFloat::rmNearestTiesToEven);
651 return ConstantFP::get(V->getContext(), apf);
654 case Instruction::ZExt:
655 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
656 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
657 return ConstantInt::get(V->getContext(),
658 CI->getValue().zext(BitWidth));
661 case Instruction::SExt:
662 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
663 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
664 return ConstantInt::get(V->getContext(),
665 CI->getValue().sext(BitWidth));
668 case Instruction::Trunc: {
669 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
670 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
671 return ConstantInt::get(V->getContext(),
672 CI->getValue().trunc(DestBitWidth));
675 // The input must be a constantexpr. See if we can simplify this based on
676 // the bytes we are demanding. Only do this if the source and dest are an
677 // even multiple of a byte.
678 if ((DestBitWidth & 7) == 0 &&
679 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
680 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
685 case Instruction::BitCast:
686 return FoldBitCast(V, DestTy);
690 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
691 Constant *V1, Constant *V2) {
692 // Check for i1 and vector true/false conditions.
693 if (Cond->isNullValue()) return V2;
694 if (Cond->isAllOnesValue()) return V1;
696 // If the condition is a vector constant, fold the result elementwise.
697 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
698 SmallVector<Constant*, 16> Result;
699 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
700 ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
701 if (Cond == 0) break;
703 Constant *Res = (Cond->getZExtValue() ? V2 : V1)->getAggregateElement(i);
705 Result.push_back(Res);
708 // If we were able to build the vector, return it.
709 if (Result.size() == V1->getType()->getVectorNumElements())
710 return ConstantVector::get(Result);
713 if (isa<UndefValue>(Cond)) {
714 if (isa<UndefValue>(V1)) return V1;
717 if (isa<UndefValue>(V1)) return V2;
718 if (isa<UndefValue>(V2)) return V1;
719 if (V1 == V2) return V1;
721 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
722 if (TrueVal->getOpcode() == Instruction::Select)
723 if (TrueVal->getOperand(0) == Cond)
724 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
726 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
727 if (FalseVal->getOpcode() == Instruction::Select)
728 if (FalseVal->getOperand(0) == Cond)
729 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
735 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
737 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
738 return UndefValue::get(Val->getType()->getVectorElementType());
739 if (Val->isNullValue()) // ee(zero, x) -> zero
740 return Constant::getNullValue(Val->getType()->getVectorElementType());
741 // ee({w,x,y,z}, undef) -> undef
742 if (isa<UndefValue>(Idx))
743 return UndefValue::get(Val->getType()->getVectorElementType());
745 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
746 uint64_t Index = CIdx->getZExtValue();
747 // ee({w,x,y,z}, wrong_value) -> undef
748 if (Index >= Val->getType()->getVectorNumElements())
749 return UndefValue::get(Val->getType()->getVectorElementType());
750 return Val->getAggregateElement(Index);
755 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
758 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
760 const APInt &IdxVal = CIdx->getValue();
762 SmallVector<Constant*, 16> Result;
763 for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
765 Result.push_back(Elt);
769 if (Constant *C = Val->getAggregateElement(i))
775 return ConstantVector::get(Result);
778 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
781 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
782 Type *EltTy = V1->getType()->getVectorElementType();
784 // Undefined shuffle mask -> undefined value.
785 if (isa<UndefValue>(Mask))
786 return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
788 // Don't break the bitcode reader hack.
789 if (isa<ConstantExpr>(Mask)) return 0;
791 unsigned SrcNumElts = V1->getType()->getVectorNumElements();
793 // Loop over the shuffle mask, evaluating each element.
794 SmallVector<Constant*, 32> Result;
795 for (unsigned i = 0; i != MaskNumElts; ++i) {
796 int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
798 Result.push_back(UndefValue::get(EltTy));
802 if (unsigned(Elt) >= SrcNumElts*2)
803 InElt = UndefValue::get(EltTy);
804 else if (unsigned(Elt) >= SrcNumElts)
805 InElt = V2->getAggregateElement(Elt - SrcNumElts);
807 InElt = V1->getAggregateElement(Elt);
808 if (InElt == 0) return 0;
809 Result.push_back(InElt);
812 return ConstantVector::get(Result);
815 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
816 ArrayRef<unsigned> Idxs) {
817 // Base case: no indices, so return the entire value.
821 if (Constant *C = Agg->getAggregateElement(Idxs[0]))
822 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
827 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
829 ArrayRef<unsigned> Idxs) {
830 // Base case: no indices, so replace the entire value.
835 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
836 NumElts = ST->getNumElements();
837 else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
838 NumElts = AT->getNumElements();
840 NumElts = AT->getVectorNumElements();
842 SmallVector<Constant*, 32> Result;
843 for (unsigned i = 0; i != NumElts; ++i) {
844 Constant *C = Agg->getAggregateElement(i);
845 if (C == 0) return 0;
848 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
853 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
854 return ConstantStruct::get(ST, Result);
855 if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
856 return ConstantArray::get(AT, Result);
857 return ConstantVector::get(Result);
861 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
862 Constant *C1, Constant *C2) {
863 // No compile-time operations on this type yet.
864 if (C1->getType()->isPPC_FP128Ty())
867 // Handle UndefValue up front.
868 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
870 case Instruction::Xor:
871 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
872 // Handle undef ^ undef -> 0 special case. This is a common
874 return Constant::getNullValue(C1->getType());
876 case Instruction::Add:
877 case Instruction::Sub:
878 return UndefValue::get(C1->getType());
879 case Instruction::And:
880 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
882 return Constant::getNullValue(C1->getType()); // undef & X -> 0
883 case Instruction::Mul: {
885 // X * undef -> undef if X is odd or undef
886 if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
887 ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
888 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
889 return UndefValue::get(C1->getType());
891 // X * undef -> 0 otherwise
892 return Constant::getNullValue(C1->getType());
894 case Instruction::UDiv:
895 case Instruction::SDiv:
896 // undef / 1 -> undef
897 if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
898 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
902 case Instruction::URem:
903 case Instruction::SRem:
904 if (!isa<UndefValue>(C2)) // undef / X -> 0
905 return Constant::getNullValue(C1->getType());
906 return C2; // X / undef -> undef
907 case Instruction::Or: // X | undef -> -1
908 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
910 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
911 case Instruction::LShr:
912 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
913 return C1; // undef lshr undef -> undef
914 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
916 case Instruction::AShr:
917 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones
918 return Constant::getAllOnesValue(C1->getType());
919 else if (isa<UndefValue>(C1))
920 return C1; // undef ashr undef -> undef
922 return C1; // X ashr undef --> X
923 case Instruction::Shl:
924 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
925 return C1; // undef shl undef -> undef
926 // undef << X -> 0 or X << undef -> 0
927 return Constant::getNullValue(C1->getType());
931 // Handle simplifications when the RHS is a constant int.
932 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
934 case Instruction::Add:
935 if (CI2->equalsInt(0)) return C1; // X + 0 == X
937 case Instruction::Sub:
938 if (CI2->equalsInt(0)) return C1; // X - 0 == X
940 case Instruction::Mul:
941 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
942 if (CI2->equalsInt(1))
943 return C1; // X * 1 == X
945 case Instruction::UDiv:
946 case Instruction::SDiv:
947 if (CI2->equalsInt(1))
948 return C1; // X / 1 == X
949 if (CI2->equalsInt(0))
950 return UndefValue::get(CI2->getType()); // X / 0 == undef
952 case Instruction::URem:
953 case Instruction::SRem:
954 if (CI2->equalsInt(1))
955 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
956 if (CI2->equalsInt(0))
957 return UndefValue::get(CI2->getType()); // X % 0 == undef
959 case Instruction::And:
960 if (CI2->isZero()) return C2; // X & 0 == 0
961 if (CI2->isAllOnesValue())
962 return C1; // X & -1 == X
964 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
965 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
966 if (CE1->getOpcode() == Instruction::ZExt) {
967 unsigned DstWidth = CI2->getType()->getBitWidth();
969 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
970 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
971 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
975 // If and'ing the address of a global with a constant, fold it.
976 if (CE1->getOpcode() == Instruction::PtrToInt &&
977 isa<GlobalValue>(CE1->getOperand(0))) {
978 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
980 // Functions are at least 4-byte aligned.
981 unsigned GVAlign = GV->getAlignment();
982 if (isa<Function>(GV))
983 GVAlign = std::max(GVAlign, 4U);
986 unsigned DstWidth = CI2->getType()->getBitWidth();
987 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
988 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
990 // If checking bits we know are clear, return zero.
991 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
992 return Constant::getNullValue(CI2->getType());
997 case Instruction::Or:
998 if (CI2->equalsInt(0)) return C1; // X | 0 == X
999 if (CI2->isAllOnesValue())
1000 return C2; // X | -1 == -1
1002 case Instruction::Xor:
1003 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
1005 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1006 switch (CE1->getOpcode()) {
1008 case Instruction::ICmp:
1009 case Instruction::FCmp:
1010 // cmp pred ^ true -> cmp !pred
1011 assert(CI2->equalsInt(1));
1012 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1013 pred = CmpInst::getInversePredicate(pred);
1014 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1015 CE1->getOperand(1));
1019 case Instruction::AShr:
1020 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1021 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1022 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1023 return ConstantExpr::getLShr(C1, C2);
1026 } else if (isa<ConstantInt>(C1)) {
1027 // If C1 is a ConstantInt and C2 is not, swap the operands.
1028 if (Instruction::isCommutative(Opcode))
1029 return ConstantExpr::get(Opcode, C2, C1);
1032 // At this point we know neither constant is an UndefValue.
1033 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1034 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1035 const APInt &C1V = CI1->getValue();
1036 const APInt &C2V = CI2->getValue();
1040 case Instruction::Add:
1041 return ConstantInt::get(CI1->getContext(), C1V + C2V);
1042 case Instruction::Sub:
1043 return ConstantInt::get(CI1->getContext(), C1V - C2V);
1044 case Instruction::Mul:
1045 return ConstantInt::get(CI1->getContext(), C1V * C2V);
1046 case Instruction::UDiv:
1047 assert(!CI2->isNullValue() && "Div by zero handled above");
1048 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1049 case Instruction::SDiv:
1050 assert(!CI2->isNullValue() && "Div by zero handled above");
1051 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1052 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
1053 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1054 case Instruction::URem:
1055 assert(!CI2->isNullValue() && "Div by zero handled above");
1056 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1057 case Instruction::SRem:
1058 assert(!CI2->isNullValue() && "Div by zero handled above");
1059 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1060 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
1061 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1062 case Instruction::And:
1063 return ConstantInt::get(CI1->getContext(), C1V & C2V);
1064 case Instruction::Or:
1065 return ConstantInt::get(CI1->getContext(), C1V | C2V);
1066 case Instruction::Xor:
1067 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1068 case Instruction::Shl: {
1069 uint32_t shiftAmt = C2V.getZExtValue();
1070 if (shiftAmt < C1V.getBitWidth())
1071 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1073 return UndefValue::get(C1->getType()); // too big shift is undef
1075 case Instruction::LShr: {
1076 uint32_t shiftAmt = C2V.getZExtValue();
1077 if (shiftAmt < C1V.getBitWidth())
1078 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1080 return UndefValue::get(C1->getType()); // too big shift is undef
1082 case Instruction::AShr: {
1083 uint32_t shiftAmt = C2V.getZExtValue();
1084 if (shiftAmt < C1V.getBitWidth())
1085 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1087 return UndefValue::get(C1->getType()); // too big shift is undef
1093 case Instruction::SDiv:
1094 case Instruction::UDiv:
1095 case Instruction::URem:
1096 case Instruction::SRem:
1097 case Instruction::LShr:
1098 case Instruction::AShr:
1099 case Instruction::Shl:
1100 if (CI1->equalsInt(0)) return C1;
1105 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1106 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1107 APFloat C1V = CFP1->getValueAPF();
1108 APFloat C2V = CFP2->getValueAPF();
1109 APFloat C3V = C1V; // copy for modification
1113 case Instruction::FAdd:
1114 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1115 return ConstantFP::get(C1->getContext(), C3V);
1116 case Instruction::FSub:
1117 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1118 return ConstantFP::get(C1->getContext(), C3V);
1119 case Instruction::FMul:
1120 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1121 return ConstantFP::get(C1->getContext(), C3V);
1122 case Instruction::FDiv:
1123 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1124 return ConstantFP::get(C1->getContext(), C3V);
1125 case Instruction::FRem:
1126 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1127 return ConstantFP::get(C1->getContext(), C3V);
1130 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1131 // Perform elementwise folding.
1132 SmallVector<Constant*, 16> Result;
1133 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1134 Constant *LHS = C1->getAggregateElement(i);
1135 Constant *RHS = C2->getAggregateElement(i);
1136 if (LHS == 0 || RHS == 0) break;
1138 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1141 if (Result.size() == VTy->getNumElements())
1142 return ConstantVector::get(Result);
1145 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1146 // There are many possible foldings we could do here. We should probably
1147 // at least fold add of a pointer with an integer into the appropriate
1148 // getelementptr. This will improve alias analysis a bit.
1150 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1152 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1153 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1154 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1155 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1157 } else if (isa<ConstantExpr>(C2)) {
1158 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1159 // other way if possible.
1160 if (Instruction::isCommutative(Opcode))
1161 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1164 // i1 can be simplified in many cases.
1165 if (C1->getType()->isIntegerTy(1)) {
1167 case Instruction::Add:
1168 case Instruction::Sub:
1169 return ConstantExpr::getXor(C1, C2);
1170 case Instruction::Mul:
1171 return ConstantExpr::getAnd(C1, C2);
1172 case Instruction::Shl:
1173 case Instruction::LShr:
1174 case Instruction::AShr:
1175 // We can assume that C2 == 0. If it were one the result would be
1176 // undefined because the shift value is as large as the bitwidth.
1178 case Instruction::SDiv:
1179 case Instruction::UDiv:
1180 // We can assume that C2 == 1. If it were zero the result would be
1181 // undefined through division by zero.
1183 case Instruction::URem:
1184 case Instruction::SRem:
1185 // We can assume that C2 == 1. If it were zero the result would be
1186 // undefined through division by zero.
1187 return ConstantInt::getFalse(C1->getContext());
1193 // We don't know how to fold this.
1197 /// isZeroSizedType - This type is zero sized if its an array or structure of
1198 /// zero sized types. The only leaf zero sized type is an empty structure.
1199 static bool isMaybeZeroSizedType(Type *Ty) {
1200 if (StructType *STy = dyn_cast<StructType>(Ty)) {
1201 if (STy->isOpaque()) return true; // Can't say.
1203 // If all of elements have zero size, this does too.
1204 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1205 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1208 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1209 return isMaybeZeroSizedType(ATy->getElementType());
1214 /// IdxCompare - Compare the two constants as though they were getelementptr
1215 /// indices. This allows coersion of the types to be the same thing.
1217 /// If the two constants are the "same" (after coersion), return 0. If the
1218 /// first is less than the second, return -1, if the second is less than the
1219 /// first, return 1. If the constants are not integral, return -2.
1221 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1222 if (C1 == C2) return 0;
1224 // Ok, we found a different index. If they are not ConstantInt, we can't do
1225 // anything with them.
1226 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1227 return -2; // don't know!
1229 // Ok, we have two differing integer indices. Sign extend them to be the same
1230 // type. Long is always big enough, so we use it.
1231 if (!C1->getType()->isIntegerTy(64))
1232 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1234 if (!C2->getType()->isIntegerTy(64))
1235 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1237 if (C1 == C2) return 0; // They are equal
1239 // If the type being indexed over is really just a zero sized type, there is
1240 // no pointer difference being made here.
1241 if (isMaybeZeroSizedType(ElTy))
1242 return -2; // dunno.
1244 // If they are really different, now that they are the same type, then we
1245 // found a difference!
1246 if (cast<ConstantInt>(C1)->getSExtValue() <
1247 cast<ConstantInt>(C2)->getSExtValue())
1253 /// evaluateFCmpRelation - This function determines if there is anything we can
1254 /// decide about the two constants provided. This doesn't need to handle simple
1255 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1256 /// If we can determine that the two constants have a particular relation to
1257 /// each other, we should return the corresponding FCmpInst predicate,
1258 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1259 /// ConstantFoldCompareInstruction.
1261 /// To simplify this code we canonicalize the relation so that the first
1262 /// operand is always the most "complex" of the two. We consider ConstantFP
1263 /// to be the simplest, and ConstantExprs to be the most complex.
1264 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1265 assert(V1->getType() == V2->getType() &&
1266 "Cannot compare values of different types!");
1268 // No compile-time operations on this type yet.
1269 if (V1->getType()->isPPC_FP128Ty())
1270 return FCmpInst::BAD_FCMP_PREDICATE;
1272 // Handle degenerate case quickly
1273 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1275 if (!isa<ConstantExpr>(V1)) {
1276 if (!isa<ConstantExpr>(V2)) {
1277 // We distilled thisUse the standard constant folder for a few cases
1279 R = dyn_cast<ConstantInt>(
1280 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1281 if (R && !R->isZero())
1282 return FCmpInst::FCMP_OEQ;
1283 R = dyn_cast<ConstantInt>(
1284 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1285 if (R && !R->isZero())
1286 return FCmpInst::FCMP_OLT;
1287 R = dyn_cast<ConstantInt>(
1288 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1289 if (R && !R->isZero())
1290 return FCmpInst::FCMP_OGT;
1292 // Nothing more we can do
1293 return FCmpInst::BAD_FCMP_PREDICATE;
1296 // If the first operand is simple and second is ConstantExpr, swap operands.
1297 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1298 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1299 return FCmpInst::getSwappedPredicate(SwappedRelation);
1301 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1302 // constantexpr or a simple constant.
1303 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1304 switch (CE1->getOpcode()) {
1305 case Instruction::FPTrunc:
1306 case Instruction::FPExt:
1307 case Instruction::UIToFP:
1308 case Instruction::SIToFP:
1309 // We might be able to do something with these but we don't right now.
1315 // There are MANY other foldings that we could perform here. They will
1316 // probably be added on demand, as they seem needed.
1317 return FCmpInst::BAD_FCMP_PREDICATE;
1320 /// evaluateICmpRelation - This function determines if there is anything we can
1321 /// decide about the two constants provided. This doesn't need to handle simple
1322 /// things like integer comparisons, but should instead handle ConstantExprs
1323 /// and GlobalValues. If we can determine that the two constants have a
1324 /// particular relation to each other, we should return the corresponding ICmp
1325 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1327 /// To simplify this code we canonicalize the relation so that the first
1328 /// operand is always the most "complex" of the two. We consider simple
1329 /// constants (like ConstantInt) to be the simplest, followed by
1330 /// GlobalValues, followed by ConstantExpr's (the most complex).
1332 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1334 assert(V1->getType() == V2->getType() &&
1335 "Cannot compare different types of values!");
1336 if (V1 == V2) return ICmpInst::ICMP_EQ;
1338 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1339 !isa<BlockAddress>(V1)) {
1340 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1341 !isa<BlockAddress>(V2)) {
1342 // We distilled this down to a simple case, use the standard constant
1345 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1346 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1347 if (R && !R->isZero())
1349 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1350 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1351 if (R && !R->isZero())
1353 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1354 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1355 if (R && !R->isZero())
1358 // If we couldn't figure it out, bail.
1359 return ICmpInst::BAD_ICMP_PREDICATE;
1362 // If the first operand is simple, swap operands.
1363 ICmpInst::Predicate SwappedRelation =
1364 evaluateICmpRelation(V2, V1, isSigned);
1365 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1366 return ICmpInst::getSwappedPredicate(SwappedRelation);
1368 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1369 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1370 ICmpInst::Predicate SwappedRelation =
1371 evaluateICmpRelation(V2, V1, isSigned);
1372 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1373 return ICmpInst::getSwappedPredicate(SwappedRelation);
1374 return ICmpInst::BAD_ICMP_PREDICATE;
1377 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1378 // constant (which, since the types must match, means that it's a
1379 // ConstantPointerNull).
1380 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1381 // Don't try to decide equality of aliases.
1382 if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1383 if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1384 return ICmpInst::ICMP_NE;
1385 } else if (isa<BlockAddress>(V2)) {
1386 return ICmpInst::ICMP_NE; // Globals never equal labels.
1388 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1389 // GlobalVals can never be null unless they have external weak linkage.
1390 // We don't try to evaluate aliases here.
1391 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1392 return ICmpInst::ICMP_NE;
1394 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1395 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1396 ICmpInst::Predicate SwappedRelation =
1397 evaluateICmpRelation(V2, V1, isSigned);
1398 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1399 return ICmpInst::getSwappedPredicate(SwappedRelation);
1400 return ICmpInst::BAD_ICMP_PREDICATE;
1403 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1404 // constant (which, since the types must match, means that it is a
1405 // ConstantPointerNull).
1406 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1407 // Block address in another function can't equal this one, but block
1408 // addresses in the current function might be the same if blocks are
1410 if (BA2->getFunction() != BA->getFunction())
1411 return ICmpInst::ICMP_NE;
1413 // Block addresses aren't null, don't equal the address of globals.
1414 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1415 "Canonicalization guarantee!");
1416 return ICmpInst::ICMP_NE;
1419 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1420 // constantexpr, a global, block address, or a simple constant.
1421 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1422 Constant *CE1Op0 = CE1->getOperand(0);
1424 switch (CE1->getOpcode()) {
1425 case Instruction::Trunc:
1426 case Instruction::FPTrunc:
1427 case Instruction::FPExt:
1428 case Instruction::FPToUI:
1429 case Instruction::FPToSI:
1430 break; // We can't evaluate floating point casts or truncations.
1432 case Instruction::UIToFP:
1433 case Instruction::SIToFP:
1434 case Instruction::BitCast:
1435 case Instruction::ZExt:
1436 case Instruction::SExt:
1437 // If the cast is not actually changing bits, and the second operand is a
1438 // null pointer, do the comparison with the pre-casted value.
1439 if (V2->isNullValue() &&
1440 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1441 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1442 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1443 return evaluateICmpRelation(CE1Op0,
1444 Constant::getNullValue(CE1Op0->getType()),
1449 case Instruction::GetElementPtr:
1450 // Ok, since this is a getelementptr, we know that the constant has a
1451 // pointer type. Check the various cases.
1452 if (isa<ConstantPointerNull>(V2)) {
1453 // If we are comparing a GEP to a null pointer, check to see if the base
1454 // of the GEP equals the null pointer.
1455 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1456 if (GV->hasExternalWeakLinkage())
1457 // Weak linkage GVals could be zero or not. We're comparing that
1458 // to null pointer so its greater-or-equal
1459 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1461 // If its not weak linkage, the GVal must have a non-zero address
1462 // so the result is greater-than
1463 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1464 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1465 // If we are indexing from a null pointer, check to see if we have any
1466 // non-zero indices.
1467 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1468 if (!CE1->getOperand(i)->isNullValue())
1469 // Offsetting from null, must not be equal.
1470 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1471 // Only zero indexes from null, must still be zero.
1472 return ICmpInst::ICMP_EQ;
1474 // Otherwise, we can't really say if the first operand is null or not.
1475 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1476 if (isa<ConstantPointerNull>(CE1Op0)) {
1477 if (GV2->hasExternalWeakLinkage())
1478 // Weak linkage GVals could be zero or not. We're comparing it to
1479 // a null pointer, so its less-or-equal
1480 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1482 // If its not weak linkage, the GVal must have a non-zero address
1483 // so the result is less-than
1484 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1485 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1487 // If this is a getelementptr of the same global, then it must be
1488 // different. Because the types must match, the getelementptr could
1489 // only have at most one index, and because we fold getelementptr's
1490 // with a single zero index, it must be nonzero.
1491 assert(CE1->getNumOperands() == 2 &&
1492 !CE1->getOperand(1)->isNullValue() &&
1493 "Surprising getelementptr!");
1494 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1496 // If they are different globals, we don't know what the value is,
1497 // but they can't be equal.
1498 return ICmpInst::ICMP_NE;
1502 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1503 Constant *CE2Op0 = CE2->getOperand(0);
1505 // There are MANY other foldings that we could perform here. They will
1506 // probably be added on demand, as they seem needed.
1507 switch (CE2->getOpcode()) {
1509 case Instruction::GetElementPtr:
1510 // By far the most common case to handle is when the base pointers are
1511 // obviously to the same or different globals.
1512 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1513 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1514 return ICmpInst::ICMP_NE;
1515 // Ok, we know that both getelementptr instructions are based on the
1516 // same global. From this, we can precisely determine the relative
1517 // ordering of the resultant pointers.
1520 // The logic below assumes that the result of the comparison
1521 // can be determined by finding the first index that differs.
1522 // This doesn't work if there is over-indexing in any
1523 // subsequent indices, so check for that case first.
1524 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1525 !CE2->isGEPWithNoNotionalOverIndexing())
1526 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1528 // Compare all of the operands the GEP's have in common.
1529 gep_type_iterator GTI = gep_type_begin(CE1);
1530 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1532 switch (IdxCompare(CE1->getOperand(i),
1533 CE2->getOperand(i), GTI.getIndexedType())) {
1534 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1535 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1536 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1539 // Ok, we ran out of things they have in common. If any leftovers
1540 // are non-zero then we have a difference, otherwise we are equal.
1541 for (; i < CE1->getNumOperands(); ++i)
1542 if (!CE1->getOperand(i)->isNullValue()) {
1543 if (isa<ConstantInt>(CE1->getOperand(i)))
1544 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1546 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1549 for (; i < CE2->getNumOperands(); ++i)
1550 if (!CE2->getOperand(i)->isNullValue()) {
1551 if (isa<ConstantInt>(CE2->getOperand(i)))
1552 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1554 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1556 return ICmpInst::ICMP_EQ;
1565 return ICmpInst::BAD_ICMP_PREDICATE;
1568 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1569 Constant *C1, Constant *C2) {
1571 if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1572 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1573 VT->getNumElements());
1575 ResultTy = Type::getInt1Ty(C1->getContext());
1577 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1578 if (pred == FCmpInst::FCMP_FALSE)
1579 return Constant::getNullValue(ResultTy);
1581 if (pred == FCmpInst::FCMP_TRUE)
1582 return Constant::getAllOnesValue(ResultTy);
1584 // Handle some degenerate cases first
1585 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1586 // For EQ and NE, we can always pick a value for the undef to make the
1587 // predicate pass or fail, so we can return undef.
1588 // Also, if both operands are undef, we can return undef.
1589 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1590 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1591 return UndefValue::get(ResultTy);
1592 // Otherwise, pick the same value as the non-undef operand, and fold
1593 // it to true or false.
1594 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1597 // No compile-time operations on this type yet.
1598 if (C1->getType()->isPPC_FP128Ty())
1601 // icmp eq/ne(null,GV) -> false/true
1602 if (C1->isNullValue()) {
1603 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1604 // Don't try to evaluate aliases. External weak GV can be null.
1605 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1606 if (pred == ICmpInst::ICMP_EQ)
1607 return ConstantInt::getFalse(C1->getContext());
1608 else if (pred == ICmpInst::ICMP_NE)
1609 return ConstantInt::getTrue(C1->getContext());
1611 // icmp eq/ne(GV,null) -> false/true
1612 } else if (C2->isNullValue()) {
1613 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1614 // Don't try to evaluate aliases. External weak GV can be null.
1615 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1616 if (pred == ICmpInst::ICMP_EQ)
1617 return ConstantInt::getFalse(C1->getContext());
1618 else if (pred == ICmpInst::ICMP_NE)
1619 return ConstantInt::getTrue(C1->getContext());
1623 // If the comparison is a comparison between two i1's, simplify it.
1624 if (C1->getType()->isIntegerTy(1)) {
1626 case ICmpInst::ICMP_EQ:
1627 if (isa<ConstantInt>(C2))
1628 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1629 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1630 case ICmpInst::ICMP_NE:
1631 return ConstantExpr::getXor(C1, C2);
1637 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1638 APInt V1 = cast<ConstantInt>(C1)->getValue();
1639 APInt V2 = cast<ConstantInt>(C2)->getValue();
1641 default: llvm_unreachable("Invalid ICmp Predicate");
1642 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
1643 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
1644 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1645 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1646 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1647 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1648 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1649 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1650 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1651 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1653 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1654 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1655 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1656 APFloat::cmpResult R = C1V.compare(C2V);
1658 default: llvm_unreachable("Invalid FCmp Predicate");
1659 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1660 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
1661 case FCmpInst::FCMP_UNO:
1662 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1663 case FCmpInst::FCMP_ORD:
1664 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1665 case FCmpInst::FCMP_UEQ:
1666 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1667 R==APFloat::cmpEqual);
1668 case FCmpInst::FCMP_OEQ:
1669 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1670 case FCmpInst::FCMP_UNE:
1671 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1672 case FCmpInst::FCMP_ONE:
1673 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1674 R==APFloat::cmpGreaterThan);
1675 case FCmpInst::FCMP_ULT:
1676 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1677 R==APFloat::cmpLessThan);
1678 case FCmpInst::FCMP_OLT:
1679 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1680 case FCmpInst::FCMP_UGT:
1681 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1682 R==APFloat::cmpGreaterThan);
1683 case FCmpInst::FCMP_OGT:
1684 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1685 case FCmpInst::FCMP_ULE:
1686 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1687 case FCmpInst::FCMP_OLE:
1688 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1689 R==APFloat::cmpEqual);
1690 case FCmpInst::FCMP_UGE:
1691 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1692 case FCmpInst::FCMP_OGE:
1693 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1694 R==APFloat::cmpEqual);
1696 } else if (C1->getType()->isVectorTy()) {
1697 // If we can constant fold the comparison of each element, constant fold
1698 // the whole vector comparison.
1699 SmallVector<Constant*, 4> ResElts;
1700 // Compare the elements, producing an i1 result or constant expr.
1701 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1702 Constant *C1E = C1->getAggregateElement(i);
1703 Constant *C2E = C2->getAggregateElement(i);
1704 if (C1E == 0 || C2E == 0) break;
1706 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1709 if (ResElts.size() == C1->getType()->getVectorNumElements())
1710 return ConstantVector::get(ResElts);
1713 if (C1->getType()->isFloatingPointTy()) {
1714 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1715 switch (evaluateFCmpRelation(C1, C2)) {
1716 default: llvm_unreachable("Unknown relation!");
1717 case FCmpInst::FCMP_UNO:
1718 case FCmpInst::FCMP_ORD:
1719 case FCmpInst::FCMP_UEQ:
1720 case FCmpInst::FCMP_UNE:
1721 case FCmpInst::FCMP_ULT:
1722 case FCmpInst::FCMP_UGT:
1723 case FCmpInst::FCMP_ULE:
1724 case FCmpInst::FCMP_UGE:
1725 case FCmpInst::FCMP_TRUE:
1726 case FCmpInst::FCMP_FALSE:
1727 case FCmpInst::BAD_FCMP_PREDICATE:
1728 break; // Couldn't determine anything about these constants.
1729 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1730 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1731 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1732 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1734 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1735 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1736 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1737 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1739 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1740 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1741 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1742 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1744 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1745 // We can only partially decide this relation.
1746 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1748 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1751 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1752 // We can only partially decide this relation.
1753 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1755 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1758 case FCmpInst::FCMP_ONE: // We know that C1 != C2
1759 // We can only partially decide this relation.
1760 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1762 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1767 // If we evaluated the result, return it now.
1769 return ConstantInt::get(ResultTy, Result);
1772 // Evaluate the relation between the two constants, per the predicate.
1773 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1774 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1775 default: llvm_unreachable("Unknown relational!");
1776 case ICmpInst::BAD_ICMP_PREDICATE:
1777 break; // Couldn't determine anything about these constants.
1778 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1779 // If we know the constants are equal, we can decide the result of this
1780 // computation precisely.
1781 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1783 case ICmpInst::ICMP_ULT:
1785 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1787 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1791 case ICmpInst::ICMP_SLT:
1793 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1795 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1799 case ICmpInst::ICMP_UGT:
1801 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1803 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1807 case ICmpInst::ICMP_SGT:
1809 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1811 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1815 case ICmpInst::ICMP_ULE:
1816 if (pred == ICmpInst::ICMP_UGT) Result = 0;
1817 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1819 case ICmpInst::ICMP_SLE:
1820 if (pred == ICmpInst::ICMP_SGT) Result = 0;
1821 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1823 case ICmpInst::ICMP_UGE:
1824 if (pred == ICmpInst::ICMP_ULT) Result = 0;
1825 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1827 case ICmpInst::ICMP_SGE:
1828 if (pred == ICmpInst::ICMP_SLT) Result = 0;
1829 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1831 case ICmpInst::ICMP_NE:
1832 if (pred == ICmpInst::ICMP_EQ) Result = 0;
1833 if (pred == ICmpInst::ICMP_NE) Result = 1;
1837 // If we evaluated the result, return it now.
1839 return ConstantInt::get(ResultTy, Result);
1841 // If the right hand side is a bitcast, try using its inverse to simplify
1842 // it by moving it to the left hand side. We can't do this if it would turn
1843 // a vector compare into a scalar compare or visa versa.
1844 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1845 Constant *CE2Op0 = CE2->getOperand(0);
1846 if (CE2->getOpcode() == Instruction::BitCast &&
1847 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1848 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1849 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1853 // If the left hand side is an extension, try eliminating it.
1854 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1855 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1856 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1857 Constant *CE1Op0 = CE1->getOperand(0);
1858 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1859 if (CE1Inverse == CE1Op0) {
1860 // Check whether we can safely truncate the right hand side.
1861 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1862 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
1863 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1869 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1870 (C1->isNullValue() && !C2->isNullValue())) {
1871 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1872 // other way if possible.
1873 // Also, if C1 is null and C2 isn't, flip them around.
1874 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1875 return ConstantExpr::getICmp(pred, C2, C1);
1881 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1883 template<typename IndexTy>
1884 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1885 // No indices means nothing that could be out of bounds.
1886 if (Idxs.empty()) return true;
1888 // If the first index is zero, it's in bounds.
1889 if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1891 // If the first index is one and all the rest are zero, it's in bounds,
1892 // by the one-past-the-end rule.
1893 if (!cast<ConstantInt>(Idxs[0])->isOne())
1895 for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1896 if (!cast<Constant>(Idxs[i])->isNullValue())
1901 template<typename IndexTy>
1902 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1904 ArrayRef<IndexTy> Idxs) {
1905 if (Idxs.empty()) return C;
1906 Constant *Idx0 = cast<Constant>(Idxs[0]);
1907 if ((Idxs.size() == 1 && Idx0->isNullValue()))
1910 if (isa<UndefValue>(C)) {
1911 PointerType *Ptr = cast<PointerType>(C->getType());
1912 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1913 assert(Ty != 0 && "Invalid indices for GEP!");
1914 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1917 if (C->isNullValue()) {
1919 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1920 if (!cast<Constant>(Idxs[i])->isNullValue()) {
1925 PointerType *Ptr = cast<PointerType>(C->getType());
1926 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1927 assert(Ty != 0 && "Invalid indices for GEP!");
1928 return ConstantPointerNull::get(PointerType::get(Ty,
1929 Ptr->getAddressSpace()));
1933 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1934 // Combine Indices - If the source pointer to this getelementptr instruction
1935 // is a getelementptr instruction, combine the indices of the two
1936 // getelementptr instructions into a single instruction.
1938 if (CE->getOpcode() == Instruction::GetElementPtr) {
1940 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1944 if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
1945 SmallVector<Value*, 16> NewIndices;
1946 NewIndices.reserve(Idxs.size() + CE->getNumOperands());
1947 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1948 NewIndices.push_back(CE->getOperand(i));
1950 // Add the last index of the source with the first index of the new GEP.
1951 // Make sure to handle the case when they are actually different types.
1952 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1953 // Otherwise it must be an array.
1954 if (!Idx0->isNullValue()) {
1955 Type *IdxTy = Combined->getType();
1956 if (IdxTy != Idx0->getType()) {
1957 Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
1958 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
1959 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
1960 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1963 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1967 NewIndices.push_back(Combined);
1968 NewIndices.append(Idxs.begin() + 1, Idxs.end());
1970 ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
1972 cast<GEPOperator>(CE)->isInBounds());
1976 // Implement folding of:
1977 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
1979 // To: i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
1981 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
1982 if (PointerType *SPT =
1983 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1984 if (ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1985 if (ArrayType *CAT =
1986 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1987 if (CAT->getElementType() == SAT->getElementType())
1989 ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
1994 // Check to see if any array indices are not within the corresponding
1995 // notional array bounds. If so, try to determine if they can be factored
1996 // out into preceding dimensions.
1997 bool Unknown = false;
1998 SmallVector<Constant *, 8> NewIdxs;
1999 Type *Ty = C->getType();
2001 for (unsigned i = 0, e = Idxs.size(); i != e;
2002 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2003 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2004 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2005 if (ATy->getNumElements() <= INT64_MAX &&
2006 ATy->getNumElements() != 0 &&
2007 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2008 if (isa<SequentialType>(Prev)) {
2009 // It's out of range, but we can factor it into the prior
2011 NewIdxs.resize(Idxs.size());
2012 ConstantInt *Factor = ConstantInt::get(CI->getType(),
2013 ATy->getNumElements());
2014 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2016 Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2017 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2019 // Before adding, extend both operands to i64 to avoid
2020 // overflow trouble.
2021 if (!PrevIdx->getType()->isIntegerTy(64))
2022 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2023 Type::getInt64Ty(Div->getContext()));
2024 if (!Div->getType()->isIntegerTy(64))
2025 Div = ConstantExpr::getSExt(Div,
2026 Type::getInt64Ty(Div->getContext()));
2028 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2030 // It's out of range, but the prior dimension is a struct
2031 // so we can't do anything about it.
2036 // We don't know if it's in range or not.
2041 // If we did any factoring, start over with the adjusted indices.
2042 if (!NewIdxs.empty()) {
2043 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2044 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2045 return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2048 // If all indices are known integers and normalized, we can do a simple
2049 // check for the "inbounds" property.
2050 if (!Unknown && !inBounds &&
2051 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
2052 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2057 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2059 ArrayRef<Constant *> Idxs) {
2060 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2063 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2065 ArrayRef<Value *> Idxs) {
2066 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);