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/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MathExtras.h"
36 //===----------------------------------------------------------------------===//
37 // ConstantFold*Instruction Implementations
38 //===----------------------------------------------------------------------===//
40 /// BitCastConstantVector - Convert the specified ConstantVector node to the
41 /// specified vector type. At this point, we know that the elements of the
42 /// input vector constant are all simple integer or FP values.
43 static Constant *BitCastConstantVector(ConstantVector *CV,
44 const VectorType *DstTy) {
46 if (CV->isAllOnesValue() && DstTy->getElementType()->isIntegerTy())
47 return Constant::getAllOnesValue(DstTy);
48 if (CV->isNullValue()) return Constant::getNullValue(DstTy);
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())
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)))
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),
70 return ConstantVector::get(Result);
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
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
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");
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);
93 // Let CastInst::isEliminableCastPair do the heavy lifting.
94 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
95 Type::getInt64Ty(DstTy->getContext()));
98 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
99 const Type *SrcTy = V->getType();
101 return V; // no-op cast
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;
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);
128 if (ElTy == DPTy->getElementType())
129 // This GEP is inbounds because all indices are zero.
130 return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
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!");
141 // First, check for null. Undef is already handled.
142 if (isa<ConstantAggregateZero>(V))
143 return Constant::getNullValue(DestTy);
145 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
146 return BitCastConstantVector(CV, DestPTy);
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, 1), DestPTy);
156 // Finally, implement bitcast folding now. The code below doesn't handle
158 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
159 return ConstantPointerNull::get(cast<PointerType>(DestTy));
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.
168 if (DestTy->isFloatingPointTy())
169 return ConstantFP::get(DestTy->getContext(),
170 APFloat(CI->getValue(),
171 !DestTy->isPPC_FP128Ty()));
173 // Otherwise, can't fold this (vector?)
177 // Handle ConstantFP input: FP -> Integral.
178 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
179 return ConstantInt::get(FP->getContext(),
180 FP->getValueAPF().bitcastToAPInt());
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.
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.
195 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
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");
205 // Constant Integers are simple.
206 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
207 APInt V = CI->getValue();
209 V = V.lshr(ByteStart*8);
210 V = V.trunc(ByteSize*8);
211 return ConstantInt::get(CI->getContext(), V);
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;
219 switch (CE->getOpcode()) {
221 case Instruction::Or: {
222 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
227 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
228 if (RHSC->isAllOnesValue())
231 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
234 return ConstantExpr::getOr(LHS, RHS);
236 case Instruction::And: {
237 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
242 if (RHS->isNullValue())
245 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
248 return ConstantExpr::getAnd(LHS, RHS);
250 case Instruction::LShr: {
251 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
254 unsigned ShAmt = Amt->getZExtValue();
255 // Cannot analyze non-byte shifts.
256 if ((ShAmt & 7) != 0)
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(),
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);
268 // TODO: Handle the 'partially zero' case.
272 case Instruction::Shl: {
273 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
276 unsigned ShAmt = Amt->getZExtValue();
277 // Cannot analyze non-byte shifts.
278 if ((ShAmt & 7) != 0)
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(),
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);
290 // TODO: Handle the 'partially zero' case.
294 case Instruction::ZExt: {
295 unsigned SrcBitSize =
296 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
298 // If extracting something that is completely zero, return 0.
299 if (ByteStart*8 >= SrcBitSize)
300 return Constant::getNullValue(IntegerType::get(CE->getContext(),
303 // If exactly extracting the input, return it.
304 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
305 return CE->getOperand(0);
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);
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);
318 Res = ConstantExpr::getLShr(Res,
319 ConstantInt::get(Res->getType(), ByteStart*8));
320 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
324 // TODO: Handle the 'partially zero' case.
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.
335 static Constant *getFoldedSizeOf(const Type *Ty, const Type *DestTy,
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);
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.
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);
353 for (unsigned i = 1; i != NumElems; ++i)
355 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
360 Constant *N = ConstantInt::get(DestTy, NumElems);
361 return ConstantExpr::getNUWMul(MemberSize, N);
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))
370 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
371 PTy->getAddressSpace()),
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.
379 // Base case: Get a regular sizeof expression.
380 Constant *C = ConstantExpr::getSizeOf(Ty);
381 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
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.
392 static Constant *getFoldedAlignOf(const Type *Ty, const Type *DestTy,
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,
405 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
406 // Packed structs always have an alignment of 1.
408 return ConstantInt::get(DestTy, 1);
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.
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);
421 for (unsigned i = 1; i != NumElems; ++i)
422 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
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))
435 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
437 PTy->getAddressSpace()),
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.
445 // Base case: Get a regular alignof expression.
446 Constant *C = ConstantExpr::getAlignOf(Ty);
447 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
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.
458 static Constant *getFoldedOffsetOf(const Type *Ty, Constant *FieldNo,
461 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
462 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
465 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
466 return ConstantExpr::getNUWMul(E, N);
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.
475 // Check for a struct with all members having the same size.
476 Constant *MemberSize =
477 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
479 for (unsigned i = 1; i != NumElems; ++i)
481 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
486 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
491 return ConstantExpr::getNUWMul(MemberSize, N);
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.
500 // Base case: Get a regular offsetof expression.
501 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
502 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
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);
520 // No compile-time operations on this type yet.
521 if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
524 if (V->isNullValue() && !DestTy->isX86_MMXTy())
525 return Constant::getNullValue(DestTy);
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)) {
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()) {
544 // This is casting one pointer type to another, always BitCast
545 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
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(DestVecTy, res);
565 // We actually have to do a cast now. Perform the cast according to the
569 llvm_unreachable("Failed to cast constant expression");
570 case Instruction::FPTrunc:
571 case Instruction::FPExt:
572 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
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 :
580 APFloat::rmNearestTiesToEven, &ignored);
581 return ConstantFP::get(V->getContext(), Val);
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();
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);
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()) {
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,
621 return ConstantExpr::getMul(C, Idx);
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));
630 STy->getNumElements() == 2 &&
631 STy->getElementType(0)->isIntegerTy(1)) {
632 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
635 // Handle an offsetof-like expression.
636 if (Ty->isStructTy() || Ty->isArrayTy()) {
637 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
643 // Other pointer types cannot be casted
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);
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));
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));
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));
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))
687 case Instruction::BitCast:
688 return FoldBitCast(V, DestTy);
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;
697 // Check for zero aggregate and ConstantVector of zeros
698 if (Cond->isNullValue()) return V2;
700 if (ConstantVector* CondV = dyn_cast<ConstantVector>(Cond)) {
702 if (CondV->isAllOnesValue()) return V1;
704 const VectorType *VTy = cast<VectorType>(V1->getType());
705 ConstantVector *CP1 = dyn_cast<ConstantVector>(V1);
706 ConstantVector *CP2 = dyn_cast<ConstantVector>(V2);
708 if ((CP1 || isa<ConstantAggregateZero>(V1)) &&
709 (CP2 || isa<ConstantAggregateZero>(V2))) {
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);
717 for (unsigned i = 0; i < NumElem; ++i) {
718 ConstantInt* c = dyn_cast<ConstantInt>(CondV->getOperand(i));
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;
727 // If we were able to build the vector, return it
728 if (Valid) return ConstantVector::get(Res);
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;
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);
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));
752 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
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());
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);
771 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
774 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
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))
782 // Otherwise break the aggregate undef into multiple undefs and do
785 cast<VectorType>(Val->getType())->getNumElements();
786 std::vector<Constant*> Ops;
788 for (unsigned i = 0; i < numOps; ++i) {
790 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
793 return ConstantVector::get(Ops);
795 if (isa<ConstantAggregateZero>(Val)) {
796 // Insertion of scalar constant into vector aggregate zero
797 // Optimize away insertion of zero
798 if (Elt->isNullValue())
800 // Otherwise break the aggregate zero into multiple zeros and do
803 cast<VectorType>(Val->getType())->getNumElements();
804 std::vector<Constant*> Ops;
806 for (unsigned i = 0; i < numOps; ++i) {
808 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
811 return ConstantVector::get(Ops);
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) {
819 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
822 return ConstantVector::get(Ops);
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);
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);
842 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
845 // Undefined shuffle mask -> undefined value.
846 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
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();
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;
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);
867 InElt = GetVectorElement(V1, Elt);
868 if (InElt == 0) return 0;
873 Result.push_back(InElt);
876 return ConstantVector::get(&Result[0], Result.size());
879 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
880 const unsigned *Idxs,
882 // Base case: no indices, so return the entire value.
886 if (isa<UndefValue>(Agg)) // ev(undef, x) -> undef
887 return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
891 if (isa<ConstantAggregateZero>(Agg)) // ev(0, x) -> 0
893 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
897 // Otherwise recurse.
898 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg))
899 return ConstantFoldExtractValueInstruction(CS->getOperand(*Idxs),
902 if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg))
903 return ConstantFoldExtractValueInstruction(CA->getOperand(*Idxs),
905 ConstantVector *CV = cast<ConstantVector>(Agg);
906 return ConstantFoldExtractValueInstruction(CV->getOperand(*Idxs),
910 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
912 const unsigned *Idxs,
914 // Base case: no indices, so replace the entire value.
918 if (isa<UndefValue>(Agg)) {
919 // Insertion of constant into aggregate undef
920 // Optimize away insertion of undef.
921 if (isa<UndefValue>(Val))
924 // Otherwise break the aggregate undef into multiple undefs and do
926 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
928 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
929 numOps = AR->getNumElements();
931 numOps = cast<StructType>(AggTy)->getNumElements();
933 std::vector<Constant*> Ops(numOps);
934 for (unsigned i = 0; i < numOps; ++i) {
935 const Type *MemberTy = AggTy->getTypeAtIndex(i);
938 ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
939 Val, Idxs+1, NumIdx-1) :
940 UndefValue::get(MemberTy);
944 if (const StructType* ST = dyn_cast<StructType>(AggTy))
945 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
946 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
949 if (isa<ConstantAggregateZero>(Agg)) {
950 // Insertion of constant into aggregate zero
951 // Optimize away insertion of zero.
952 if (Val->isNullValue())
955 // Otherwise break the aggregate zero into multiple zeros and do
957 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
959 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
960 numOps = AR->getNumElements();
962 numOps = cast<StructType>(AggTy)->getNumElements();
964 std::vector<Constant*> Ops(numOps);
965 for (unsigned i = 0; i < numOps; ++i) {
966 const Type *MemberTy = AggTy->getTypeAtIndex(i);
969 ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
970 Val, Idxs+1, NumIdx-1) :
971 Constant::getNullValue(MemberTy);
975 if (const StructType *ST = dyn_cast<StructType>(AggTy))
976 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
977 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
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));
986 Op = ConstantFoldInsertValueInstruction(Op, Val, Idxs+1, NumIdx-1);
990 if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
991 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
992 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
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())
1005 // Handle UndefValue up front.
1006 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1008 case Instruction::Xor:
1009 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
1010 // Handle undef ^ undef -> 0 special case. This is a common
1012 return Constant::getNullValue(C1->getType());
1014 case Instruction::Add:
1015 case Instruction::Sub:
1016 return UndefValue::get(C1->getType());
1017 case Instruction::Mul:
1018 case Instruction::And:
1019 return Constant::getNullValue(C1->getType());
1020 case Instruction::UDiv:
1021 case Instruction::SDiv:
1022 case Instruction::URem:
1023 case Instruction::SRem:
1024 if (!isa<UndefValue>(C2)) // undef / X -> 0
1025 return Constant::getNullValue(C1->getType());
1026 return C2; // X / undef -> undef
1027 case Instruction::Or: // X | undef -> -1
1028 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
1029 return Constant::getAllOnesValue(PTy);
1030 return Constant::getAllOnesValue(C1->getType());
1031 case Instruction::LShr:
1032 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
1033 return C1; // undef lshr undef -> undef
1034 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
1035 // undef lshr X -> 0
1036 case Instruction::AShr:
1037 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones
1038 return Constant::getAllOnesValue(C1->getType());
1039 else if (isa<UndefValue>(C1))
1040 return C1; // undef ashr undef -> undef
1042 return C1; // X ashr undef --> X
1043 case Instruction::Shl:
1044 // undef << X -> 0 or X << undef -> 0
1045 return Constant::getNullValue(C1->getType());
1049 // Handle simplifications when the RHS is a constant int.
1050 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1052 case Instruction::Add:
1053 if (CI2->equalsInt(0)) return C1; // X + 0 == X
1055 case Instruction::Sub:
1056 if (CI2->equalsInt(0)) return C1; // X - 0 == X
1058 case Instruction::Mul:
1059 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
1060 if (CI2->equalsInt(1))
1061 return C1; // X * 1 == X
1063 case Instruction::UDiv:
1064 case Instruction::SDiv:
1065 if (CI2->equalsInt(1))
1066 return C1; // X / 1 == X
1067 if (CI2->equalsInt(0))
1068 return UndefValue::get(CI2->getType()); // X / 0 == undef
1070 case Instruction::URem:
1071 case Instruction::SRem:
1072 if (CI2->equalsInt(1))
1073 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
1074 if (CI2->equalsInt(0))
1075 return UndefValue::get(CI2->getType()); // X % 0 == undef
1077 case Instruction::And:
1078 if (CI2->isZero()) return C2; // X & 0 == 0
1079 if (CI2->isAllOnesValue())
1080 return C1; // X & -1 == X
1082 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1083 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1084 if (CE1->getOpcode() == Instruction::ZExt) {
1085 unsigned DstWidth = CI2->getType()->getBitWidth();
1087 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1088 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1089 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1093 // If and'ing the address of a global with a constant, fold it.
1094 if (CE1->getOpcode() == Instruction::PtrToInt &&
1095 isa<GlobalValue>(CE1->getOperand(0))) {
1096 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1098 // Functions are at least 4-byte aligned.
1099 unsigned GVAlign = GV->getAlignment();
1100 if (isa<Function>(GV))
1101 GVAlign = std::max(GVAlign, 4U);
1104 unsigned DstWidth = CI2->getType()->getBitWidth();
1105 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1106 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1108 // If checking bits we know are clear, return zero.
1109 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1110 return Constant::getNullValue(CI2->getType());
1115 case Instruction::Or:
1116 if (CI2->equalsInt(0)) return C1; // X | 0 == X
1117 if (CI2->isAllOnesValue())
1118 return C2; // X | -1 == -1
1120 case Instruction::Xor:
1121 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
1123 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1124 switch (CE1->getOpcode()) {
1126 case Instruction::ICmp:
1127 case Instruction::FCmp:
1128 // cmp pred ^ true -> cmp !pred
1129 assert(CI2->equalsInt(1));
1130 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1131 pred = CmpInst::getInversePredicate(pred);
1132 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1133 CE1->getOperand(1));
1137 case Instruction::AShr:
1138 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1139 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1140 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1141 return ConstantExpr::getLShr(C1, C2);
1144 } else if (isa<ConstantInt>(C1)) {
1145 // If C1 is a ConstantInt and C2 is not, swap the operands.
1146 if (Instruction::isCommutative(Opcode))
1147 return ConstantExpr::get(Opcode, C2, C1);
1150 // At this point we know neither constant is an UndefValue.
1151 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1152 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1153 using namespace APIntOps;
1154 const APInt &C1V = CI1->getValue();
1155 const APInt &C2V = CI2->getValue();
1159 case Instruction::Add:
1160 return ConstantInt::get(CI1->getContext(), C1V + C2V);
1161 case Instruction::Sub:
1162 return ConstantInt::get(CI1->getContext(), C1V - C2V);
1163 case Instruction::Mul:
1164 return ConstantInt::get(CI1->getContext(), C1V * C2V);
1165 case Instruction::UDiv:
1166 assert(!CI2->isNullValue() && "Div by zero handled above");
1167 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1168 case Instruction::SDiv:
1169 assert(!CI2->isNullValue() && "Div by zero handled above");
1170 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1171 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
1172 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1173 case Instruction::URem:
1174 assert(!CI2->isNullValue() && "Div by zero handled above");
1175 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1176 case Instruction::SRem:
1177 assert(!CI2->isNullValue() && "Div by zero handled above");
1178 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1179 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
1180 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1181 case Instruction::And:
1182 return ConstantInt::get(CI1->getContext(), C1V & C2V);
1183 case Instruction::Or:
1184 return ConstantInt::get(CI1->getContext(), C1V | C2V);
1185 case Instruction::Xor:
1186 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1187 case Instruction::Shl: {
1188 uint32_t shiftAmt = C2V.getZExtValue();
1189 if (shiftAmt < C1V.getBitWidth())
1190 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1192 return UndefValue::get(C1->getType()); // too big shift is undef
1194 case Instruction::LShr: {
1195 uint32_t shiftAmt = C2V.getZExtValue();
1196 if (shiftAmt < C1V.getBitWidth())
1197 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1199 return UndefValue::get(C1->getType()); // too big shift is undef
1201 case Instruction::AShr: {
1202 uint32_t shiftAmt = C2V.getZExtValue();
1203 if (shiftAmt < C1V.getBitWidth())
1204 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1206 return UndefValue::get(C1->getType()); // too big shift is undef
1212 case Instruction::SDiv:
1213 case Instruction::UDiv:
1214 case Instruction::URem:
1215 case Instruction::SRem:
1216 case Instruction::LShr:
1217 case Instruction::AShr:
1218 case Instruction::Shl:
1219 if (CI1->equalsInt(0)) return C1;
1224 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1225 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1226 APFloat C1V = CFP1->getValueAPF();
1227 APFloat C2V = CFP2->getValueAPF();
1228 APFloat C3V = C1V; // copy for modification
1232 case Instruction::FAdd:
1233 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1234 return ConstantFP::get(C1->getContext(), C3V);
1235 case Instruction::FSub:
1236 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1237 return ConstantFP::get(C1->getContext(), C3V);
1238 case Instruction::FMul:
1239 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1240 return ConstantFP::get(C1->getContext(), C3V);
1241 case Instruction::FDiv:
1242 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1243 return ConstantFP::get(C1->getContext(), C3V);
1244 case Instruction::FRem:
1245 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1246 return ConstantFP::get(C1->getContext(), C3V);
1249 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1250 ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
1251 ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
1252 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
1253 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
1254 std::vector<Constant*> Res;
1255 const Type* EltTy = VTy->getElementType();
1261 case Instruction::Add:
1262 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1263 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1264 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1265 Res.push_back(ConstantExpr::getAdd(C1, C2));
1267 return ConstantVector::get(Res);
1268 case Instruction::FAdd:
1269 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1270 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1271 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1272 Res.push_back(ConstantExpr::getFAdd(C1, C2));
1274 return ConstantVector::get(Res);
1275 case Instruction::Sub:
1276 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1277 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1278 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1279 Res.push_back(ConstantExpr::getSub(C1, C2));
1281 return ConstantVector::get(Res);
1282 case Instruction::FSub:
1283 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1284 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1285 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1286 Res.push_back(ConstantExpr::getFSub(C1, C2));
1288 return ConstantVector::get(Res);
1289 case Instruction::Mul:
1290 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1291 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1292 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1293 Res.push_back(ConstantExpr::getMul(C1, C2));
1295 return ConstantVector::get(Res);
1296 case Instruction::FMul:
1297 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1298 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1299 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1300 Res.push_back(ConstantExpr::getFMul(C1, C2));
1302 return ConstantVector::get(Res);
1303 case Instruction::UDiv:
1304 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1305 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1306 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1307 Res.push_back(ConstantExpr::getUDiv(C1, C2));
1309 return ConstantVector::get(Res);
1310 case Instruction::SDiv:
1311 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1312 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1313 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1314 Res.push_back(ConstantExpr::getSDiv(C1, C2));
1316 return ConstantVector::get(Res);
1317 case Instruction::FDiv:
1318 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1319 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1320 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1321 Res.push_back(ConstantExpr::getFDiv(C1, C2));
1323 return ConstantVector::get(Res);
1324 case Instruction::URem:
1325 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1326 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1327 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1328 Res.push_back(ConstantExpr::getURem(C1, C2));
1330 return ConstantVector::get(Res);
1331 case Instruction::SRem:
1332 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1333 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1334 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1335 Res.push_back(ConstantExpr::getSRem(C1, C2));
1337 return ConstantVector::get(Res);
1338 case Instruction::FRem:
1339 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1340 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1341 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1342 Res.push_back(ConstantExpr::getFRem(C1, C2));
1344 return ConstantVector::get(Res);
1345 case Instruction::And:
1346 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1347 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1348 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1349 Res.push_back(ConstantExpr::getAnd(C1, C2));
1351 return ConstantVector::get(Res);
1352 case Instruction::Or:
1353 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1354 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1355 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1356 Res.push_back(ConstantExpr::getOr(C1, C2));
1358 return ConstantVector::get(Res);
1359 case Instruction::Xor:
1360 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1361 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1362 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1363 Res.push_back(ConstantExpr::getXor(C1, C2));
1365 return ConstantVector::get(Res);
1366 case Instruction::LShr:
1367 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1368 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1369 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1370 Res.push_back(ConstantExpr::getLShr(C1, C2));
1372 return ConstantVector::get(Res);
1373 case Instruction::AShr:
1374 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1375 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1376 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1377 Res.push_back(ConstantExpr::getAShr(C1, C2));
1379 return ConstantVector::get(Res);
1380 case Instruction::Shl:
1381 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1382 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1383 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1384 Res.push_back(ConstantExpr::getShl(C1, C2));
1386 return ConstantVector::get(Res);
1391 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1392 // There are many possible foldings we could do here. We should probably
1393 // at least fold add of a pointer with an integer into the appropriate
1394 // getelementptr. This will improve alias analysis a bit.
1396 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1398 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1399 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1400 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1401 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1403 } else if (isa<ConstantExpr>(C2)) {
1404 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1405 // other way if possible.
1406 if (Instruction::isCommutative(Opcode))
1407 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1410 // i1 can be simplified in many cases.
1411 if (C1->getType()->isIntegerTy(1)) {
1413 case Instruction::Add:
1414 case Instruction::Sub:
1415 return ConstantExpr::getXor(C1, C2);
1416 case Instruction::Mul:
1417 return ConstantExpr::getAnd(C1, C2);
1418 case Instruction::Shl:
1419 case Instruction::LShr:
1420 case Instruction::AShr:
1421 // We can assume that C2 == 0. If it were one the result would be
1422 // undefined because the shift value is as large as the bitwidth.
1424 case Instruction::SDiv:
1425 case Instruction::UDiv:
1426 // We can assume that C2 == 1. If it were zero the result would be
1427 // undefined through division by zero.
1429 case Instruction::URem:
1430 case Instruction::SRem:
1431 // We can assume that C2 == 1. If it were zero the result would be
1432 // undefined through division by zero.
1433 return ConstantInt::getFalse(C1->getContext());
1439 // We don't know how to fold this.
1443 /// isZeroSizedType - This type is zero sized if its an array or structure of
1444 /// zero sized types. The only leaf zero sized type is an empty structure.
1445 static bool isMaybeZeroSizedType(const Type *Ty) {
1446 if (Ty->isOpaqueTy()) return true; // Can't say.
1447 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1449 // If all of elements have zero size, this does too.
1450 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1451 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1454 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1455 return isMaybeZeroSizedType(ATy->getElementType());
1460 /// IdxCompare - Compare the two constants as though they were getelementptr
1461 /// indices. This allows coersion of the types to be the same thing.
1463 /// If the two constants are the "same" (after coersion), return 0. If the
1464 /// first is less than the second, return -1, if the second is less than the
1465 /// first, return 1. If the constants are not integral, return -2.
1467 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
1468 if (C1 == C2) return 0;
1470 // Ok, we found a different index. If they are not ConstantInt, we can't do
1471 // anything with them.
1472 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1473 return -2; // don't know!
1475 // Ok, we have two differing integer indices. Sign extend them to be the same
1476 // type. Long is always big enough, so we use it.
1477 if (!C1->getType()->isIntegerTy(64))
1478 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1480 if (!C2->getType()->isIntegerTy(64))
1481 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1483 if (C1 == C2) return 0; // They are equal
1485 // If the type being indexed over is really just a zero sized type, there is
1486 // no pointer difference being made here.
1487 if (isMaybeZeroSizedType(ElTy))
1488 return -2; // dunno.
1490 // If they are really different, now that they are the same type, then we
1491 // found a difference!
1492 if (cast<ConstantInt>(C1)->getSExtValue() <
1493 cast<ConstantInt>(C2)->getSExtValue())
1499 /// evaluateFCmpRelation - This function determines if there is anything we can
1500 /// decide about the two constants provided. This doesn't need to handle simple
1501 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1502 /// If we can determine that the two constants have a particular relation to
1503 /// each other, we should return the corresponding FCmpInst predicate,
1504 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1505 /// ConstantFoldCompareInstruction.
1507 /// To simplify this code we canonicalize the relation so that the first
1508 /// operand is always the most "complex" of the two. We consider ConstantFP
1509 /// to be the simplest, and ConstantExprs to be the most complex.
1510 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1511 assert(V1->getType() == V2->getType() &&
1512 "Cannot compare values of different types!");
1514 // No compile-time operations on this type yet.
1515 if (V1->getType()->isPPC_FP128Ty())
1516 return FCmpInst::BAD_FCMP_PREDICATE;
1518 // Handle degenerate case quickly
1519 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1521 if (!isa<ConstantExpr>(V1)) {
1522 if (!isa<ConstantExpr>(V2)) {
1523 // We distilled thisUse the standard constant folder for a few cases
1525 R = dyn_cast<ConstantInt>(
1526 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1527 if (R && !R->isZero())
1528 return FCmpInst::FCMP_OEQ;
1529 R = dyn_cast<ConstantInt>(
1530 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1531 if (R && !R->isZero())
1532 return FCmpInst::FCMP_OLT;
1533 R = dyn_cast<ConstantInt>(
1534 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1535 if (R && !R->isZero())
1536 return FCmpInst::FCMP_OGT;
1538 // Nothing more we can do
1539 return FCmpInst::BAD_FCMP_PREDICATE;
1542 // If the first operand is simple and second is ConstantExpr, swap operands.
1543 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1544 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1545 return FCmpInst::getSwappedPredicate(SwappedRelation);
1547 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1548 // constantexpr or a simple constant.
1549 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1550 switch (CE1->getOpcode()) {
1551 case Instruction::FPTrunc:
1552 case Instruction::FPExt:
1553 case Instruction::UIToFP:
1554 case Instruction::SIToFP:
1555 // We might be able to do something with these but we don't right now.
1561 // There are MANY other foldings that we could perform here. They will
1562 // probably be added on demand, as they seem needed.
1563 return FCmpInst::BAD_FCMP_PREDICATE;
1566 /// evaluateICmpRelation - This function determines if there is anything we can
1567 /// decide about the two constants provided. This doesn't need to handle simple
1568 /// things like integer comparisons, but should instead handle ConstantExprs
1569 /// and GlobalValues. If we can determine that the two constants have a
1570 /// particular relation to each other, we should return the corresponding ICmp
1571 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1573 /// To simplify this code we canonicalize the relation so that the first
1574 /// operand is always the most "complex" of the two. We consider simple
1575 /// constants (like ConstantInt) to be the simplest, followed by
1576 /// GlobalValues, followed by ConstantExpr's (the most complex).
1578 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1580 assert(V1->getType() == V2->getType() &&
1581 "Cannot compare different types of values!");
1582 if (V1 == V2) return ICmpInst::ICMP_EQ;
1584 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1585 !isa<BlockAddress>(V1)) {
1586 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1587 !isa<BlockAddress>(V2)) {
1588 // We distilled this down to a simple case, use the standard constant
1591 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1592 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1593 if (R && !R->isZero())
1595 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1596 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1597 if (R && !R->isZero())
1599 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1600 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1601 if (R && !R->isZero())
1604 // If we couldn't figure it out, bail.
1605 return ICmpInst::BAD_ICMP_PREDICATE;
1608 // If the first operand is simple, swap operands.
1609 ICmpInst::Predicate SwappedRelation =
1610 evaluateICmpRelation(V2, V1, isSigned);
1611 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1612 return ICmpInst::getSwappedPredicate(SwappedRelation);
1614 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1615 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1616 ICmpInst::Predicate SwappedRelation =
1617 evaluateICmpRelation(V2, V1, isSigned);
1618 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1619 return ICmpInst::getSwappedPredicate(SwappedRelation);
1620 return ICmpInst::BAD_ICMP_PREDICATE;
1623 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1624 // constant (which, since the types must match, means that it's a
1625 // ConstantPointerNull).
1626 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1627 // Don't try to decide equality of aliases.
1628 if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1629 if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1630 return ICmpInst::ICMP_NE;
1631 } else if (isa<BlockAddress>(V2)) {
1632 return ICmpInst::ICMP_NE; // Globals never equal labels.
1634 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1635 // GlobalVals can never be null unless they have external weak linkage.
1636 // We don't try to evaluate aliases here.
1637 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1638 return ICmpInst::ICMP_NE;
1640 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1641 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1642 ICmpInst::Predicate SwappedRelation =
1643 evaluateICmpRelation(V2, V1, isSigned);
1644 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1645 return ICmpInst::getSwappedPredicate(SwappedRelation);
1646 return ICmpInst::BAD_ICMP_PREDICATE;
1649 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1650 // constant (which, since the types must match, means that it is a
1651 // ConstantPointerNull).
1652 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1653 // Block address in another function can't equal this one, but block
1654 // addresses in the current function might be the same if blocks are
1656 if (BA2->getFunction() != BA->getFunction())
1657 return ICmpInst::ICMP_NE;
1659 // Block addresses aren't null, don't equal the address of globals.
1660 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1661 "Canonicalization guarantee!");
1662 return ICmpInst::ICMP_NE;
1665 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1666 // constantexpr, a global, block address, or a simple constant.
1667 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1668 Constant *CE1Op0 = CE1->getOperand(0);
1670 switch (CE1->getOpcode()) {
1671 case Instruction::Trunc:
1672 case Instruction::FPTrunc:
1673 case Instruction::FPExt:
1674 case Instruction::FPToUI:
1675 case Instruction::FPToSI:
1676 break; // We can't evaluate floating point casts or truncations.
1678 case Instruction::UIToFP:
1679 case Instruction::SIToFP:
1680 case Instruction::BitCast:
1681 case Instruction::ZExt:
1682 case Instruction::SExt:
1683 // If the cast is not actually changing bits, and the second operand is a
1684 // null pointer, do the comparison with the pre-casted value.
1685 if (V2->isNullValue() &&
1686 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1687 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1688 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1689 return evaluateICmpRelation(CE1Op0,
1690 Constant::getNullValue(CE1Op0->getType()),
1695 case Instruction::GetElementPtr:
1696 // Ok, since this is a getelementptr, we know that the constant has a
1697 // pointer type. Check the various cases.
1698 if (isa<ConstantPointerNull>(V2)) {
1699 // If we are comparing a GEP to a null pointer, check to see if the base
1700 // of the GEP equals the null pointer.
1701 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1702 if (GV->hasExternalWeakLinkage())
1703 // Weak linkage GVals could be zero or not. We're comparing that
1704 // to null pointer so its greater-or-equal
1705 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1707 // If its not weak linkage, the GVal must have a non-zero address
1708 // so the result is greater-than
1709 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1710 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1711 // If we are indexing from a null pointer, check to see if we have any
1712 // non-zero indices.
1713 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1714 if (!CE1->getOperand(i)->isNullValue())
1715 // Offsetting from null, must not be equal.
1716 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1717 // Only zero indexes from null, must still be zero.
1718 return ICmpInst::ICMP_EQ;
1720 // Otherwise, we can't really say if the first operand is null or not.
1721 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1722 if (isa<ConstantPointerNull>(CE1Op0)) {
1723 if (GV2->hasExternalWeakLinkage())
1724 // Weak linkage GVals could be zero or not. We're comparing it to
1725 // a null pointer, so its less-or-equal
1726 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1728 // If its not weak linkage, the GVal must have a non-zero address
1729 // so the result is less-than
1730 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1731 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1733 // If this is a getelementptr of the same global, then it must be
1734 // different. Because the types must match, the getelementptr could
1735 // only have at most one index, and because we fold getelementptr's
1736 // with a single zero index, it must be nonzero.
1737 assert(CE1->getNumOperands() == 2 &&
1738 !CE1->getOperand(1)->isNullValue() &&
1739 "Suprising getelementptr!");
1740 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1742 // If they are different globals, we don't know what the value is,
1743 // but they can't be equal.
1744 return ICmpInst::ICMP_NE;
1748 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1749 Constant *CE2Op0 = CE2->getOperand(0);
1751 // There are MANY other foldings that we could perform here. They will
1752 // probably be added on demand, as they seem needed.
1753 switch (CE2->getOpcode()) {
1755 case Instruction::GetElementPtr:
1756 // By far the most common case to handle is when the base pointers are
1757 // obviously to the same or different globals.
1758 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1759 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1760 return ICmpInst::ICMP_NE;
1761 // Ok, we know that both getelementptr instructions are based on the
1762 // same global. From this, we can precisely determine the relative
1763 // ordering of the resultant pointers.
1766 // The logic below assumes that the result of the comparison
1767 // can be determined by finding the first index that differs.
1768 // This doesn't work if there is over-indexing in any
1769 // subsequent indices, so check for that case first.
1770 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1771 !CE2->isGEPWithNoNotionalOverIndexing())
1772 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1774 // Compare all of the operands the GEP's have in common.
1775 gep_type_iterator GTI = gep_type_begin(CE1);
1776 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1778 switch (IdxCompare(CE1->getOperand(i),
1779 CE2->getOperand(i), GTI.getIndexedType())) {
1780 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1781 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1782 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1785 // Ok, we ran out of things they have in common. If any leftovers
1786 // are non-zero then we have a difference, otherwise we are equal.
1787 for (; i < CE1->getNumOperands(); ++i)
1788 if (!CE1->getOperand(i)->isNullValue()) {
1789 if (isa<ConstantInt>(CE1->getOperand(i)))
1790 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1792 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1795 for (; i < CE2->getNumOperands(); ++i)
1796 if (!CE2->getOperand(i)->isNullValue()) {
1797 if (isa<ConstantInt>(CE2->getOperand(i)))
1798 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1800 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1802 return ICmpInst::ICMP_EQ;
1811 return ICmpInst::BAD_ICMP_PREDICATE;
1814 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1815 Constant *C1, Constant *C2) {
1816 const Type *ResultTy;
1817 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1818 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1819 VT->getNumElements());
1821 ResultTy = Type::getInt1Ty(C1->getContext());
1823 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1824 if (pred == FCmpInst::FCMP_FALSE)
1825 return Constant::getNullValue(ResultTy);
1827 if (pred == FCmpInst::FCMP_TRUE)
1828 return Constant::getAllOnesValue(ResultTy);
1830 // Handle some degenerate cases first
1831 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1832 // For EQ and NE, we can always pick a value for the undef to make the
1833 // predicate pass or fail, so we can return undef.
1834 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)))
1835 return UndefValue::get(ResultTy);
1836 // Otherwise, pick the same value as the non-undef operand, and fold
1837 // it to true or false.
1838 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1841 // No compile-time operations on this type yet.
1842 if (C1->getType()->isPPC_FP128Ty())
1845 // icmp eq/ne(null,GV) -> false/true
1846 if (C1->isNullValue()) {
1847 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1848 // Don't try to evaluate aliases. External weak GV can be null.
1849 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1850 if (pred == ICmpInst::ICMP_EQ)
1851 return ConstantInt::getFalse(C1->getContext());
1852 else if (pred == ICmpInst::ICMP_NE)
1853 return ConstantInt::getTrue(C1->getContext());
1855 // icmp eq/ne(GV,null) -> false/true
1856 } else if (C2->isNullValue()) {
1857 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1858 // Don't try to evaluate aliases. External weak GV can be null.
1859 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1860 if (pred == ICmpInst::ICMP_EQ)
1861 return ConstantInt::getFalse(C1->getContext());
1862 else if (pred == ICmpInst::ICMP_NE)
1863 return ConstantInt::getTrue(C1->getContext());
1867 // If the comparison is a comparison between two i1's, simplify it.
1868 if (C1->getType()->isIntegerTy(1)) {
1870 case ICmpInst::ICMP_EQ:
1871 if (isa<ConstantInt>(C2))
1872 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1873 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1874 case ICmpInst::ICMP_NE:
1875 return ConstantExpr::getXor(C1, C2);
1881 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1882 APInt V1 = cast<ConstantInt>(C1)->getValue();
1883 APInt V2 = cast<ConstantInt>(C2)->getValue();
1885 default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1886 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
1887 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
1888 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1889 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1890 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1891 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1892 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1893 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1894 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1895 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1897 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1898 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1899 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1900 APFloat::cmpResult R = C1V.compare(C2V);
1902 default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1903 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1904 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
1905 case FCmpInst::FCMP_UNO:
1906 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1907 case FCmpInst::FCMP_ORD:
1908 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1909 case FCmpInst::FCMP_UEQ:
1910 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1911 R==APFloat::cmpEqual);
1912 case FCmpInst::FCMP_OEQ:
1913 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1914 case FCmpInst::FCMP_UNE:
1915 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1916 case FCmpInst::FCMP_ONE:
1917 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1918 R==APFloat::cmpGreaterThan);
1919 case FCmpInst::FCMP_ULT:
1920 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1921 R==APFloat::cmpLessThan);
1922 case FCmpInst::FCMP_OLT:
1923 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1924 case FCmpInst::FCMP_UGT:
1925 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1926 R==APFloat::cmpGreaterThan);
1927 case FCmpInst::FCMP_OGT:
1928 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1929 case FCmpInst::FCMP_ULE:
1930 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1931 case FCmpInst::FCMP_OLE:
1932 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1933 R==APFloat::cmpEqual);
1934 case FCmpInst::FCMP_UGE:
1935 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1936 case FCmpInst::FCMP_OGE:
1937 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1938 R==APFloat::cmpEqual);
1940 } else if (C1->getType()->isVectorTy()) {
1941 SmallVector<Constant*, 16> C1Elts, C2Elts;
1942 C1->getVectorElements(C1Elts);
1943 C2->getVectorElements(C2Elts);
1944 if (C1Elts.empty() || C2Elts.empty())
1947 // If we can constant fold the comparison of each element, constant fold
1948 // the whole vector comparison.
1949 SmallVector<Constant*, 4> ResElts;
1950 for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1951 // Compare the elements, producing an i1 result or constant expr.
1952 ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
1954 return ConstantVector::get(&ResElts[0], ResElts.size());
1957 if (C1->getType()->isFloatingPointTy()) {
1958 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1959 switch (evaluateFCmpRelation(C1, C2)) {
1960 default: llvm_unreachable("Unknown relation!");
1961 case FCmpInst::FCMP_UNO:
1962 case FCmpInst::FCMP_ORD:
1963 case FCmpInst::FCMP_UEQ:
1964 case FCmpInst::FCMP_UNE:
1965 case FCmpInst::FCMP_ULT:
1966 case FCmpInst::FCMP_UGT:
1967 case FCmpInst::FCMP_ULE:
1968 case FCmpInst::FCMP_UGE:
1969 case FCmpInst::FCMP_TRUE:
1970 case FCmpInst::FCMP_FALSE:
1971 case FCmpInst::BAD_FCMP_PREDICATE:
1972 break; // Couldn't determine anything about these constants.
1973 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1974 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1975 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1976 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1978 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1979 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1980 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1981 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1983 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1984 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1985 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1986 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1988 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1989 // We can only partially decide this relation.
1990 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1992 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1995 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1996 // We can only partially decide this relation.
1997 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1999 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
2002 case FCmpInst::FCMP_ONE: // We know that C1 != C2
2003 // We can only partially decide this relation.
2004 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
2006 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
2011 // If we evaluated the result, return it now.
2013 return ConstantInt::get(ResultTy, Result);
2016 // Evaluate the relation between the two constants, per the predicate.
2017 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
2018 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
2019 default: llvm_unreachable("Unknown relational!");
2020 case ICmpInst::BAD_ICMP_PREDICATE:
2021 break; // Couldn't determine anything about these constants.
2022 case ICmpInst::ICMP_EQ: // We know the constants are equal!
2023 // If we know the constants are equal, we can decide the result of this
2024 // computation precisely.
2025 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
2027 case ICmpInst::ICMP_ULT:
2029 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
2031 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
2035 case ICmpInst::ICMP_SLT:
2037 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
2039 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
2043 case ICmpInst::ICMP_UGT:
2045 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
2047 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
2051 case ICmpInst::ICMP_SGT:
2053 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
2055 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
2059 case ICmpInst::ICMP_ULE:
2060 if (pred == ICmpInst::ICMP_UGT) Result = 0;
2061 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
2063 case ICmpInst::ICMP_SLE:
2064 if (pred == ICmpInst::ICMP_SGT) Result = 0;
2065 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
2067 case ICmpInst::ICMP_UGE:
2068 if (pred == ICmpInst::ICMP_ULT) Result = 0;
2069 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
2071 case ICmpInst::ICMP_SGE:
2072 if (pred == ICmpInst::ICMP_SLT) Result = 0;
2073 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
2075 case ICmpInst::ICMP_NE:
2076 if (pred == ICmpInst::ICMP_EQ) Result = 0;
2077 if (pred == ICmpInst::ICMP_NE) Result = 1;
2081 // If we evaluated the result, return it now.
2083 return ConstantInt::get(ResultTy, Result);
2085 // If the right hand side is a bitcast, try using its inverse to simplify
2086 // it by moving it to the left hand side. We can't do this if it would turn
2087 // a vector compare into a scalar compare or visa versa.
2088 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
2089 Constant *CE2Op0 = CE2->getOperand(0);
2090 if (CE2->getOpcode() == Instruction::BitCast &&
2091 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
2092 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
2093 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
2097 // If the left hand side is an extension, try eliminating it.
2098 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2099 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
2100 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
2101 Constant *CE1Op0 = CE1->getOperand(0);
2102 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2103 if (CE1Inverse == CE1Op0) {
2104 // Check whether we can safely truncate the right hand side.
2105 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2106 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
2107 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2113 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2114 (C1->isNullValue() && !C2->isNullValue())) {
2115 // If C2 is a constant expr and C1 isn't, flip them around and fold the
2116 // other way if possible.
2117 // Also, if C1 is null and C2 isn't, flip them around.
2118 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
2119 return ConstantExpr::getICmp(pred, C2, C1);
2125 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
2127 template<typename IndexTy>
2128 static bool isInBoundsIndices(IndexTy const *Idxs, size_t NumIdx) {
2129 // No indices means nothing that could be out of bounds.
2130 if (NumIdx == 0) return true;
2132 // If the first index is zero, it's in bounds.
2133 if (cast<Constant>(Idxs[0])->isNullValue()) return true;
2135 // If the first index is one and all the rest are zero, it's in bounds,
2136 // by the one-past-the-end rule.
2137 if (!cast<ConstantInt>(Idxs[0])->isOne())
2139 for (unsigned i = 1, e = NumIdx; i != e; ++i)
2140 if (!cast<Constant>(Idxs[i])->isNullValue())
2145 template<typename IndexTy>
2146 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
2148 IndexTy const *Idxs,
2150 Constant *Idx0 = cast<Constant>(Idxs[0]);
2152 (NumIdx == 1 && Idx0->isNullValue()))
2155 if (isa<UndefValue>(C)) {
2156 const PointerType *Ptr = cast<PointerType>(C->getType());
2157 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs, Idxs+NumIdx);
2158 assert(Ty != 0 && "Invalid indices for GEP!");
2159 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
2162 if (C->isNullValue()) {
2164 for (unsigned i = 0, e = NumIdx; i != e; ++i)
2165 if (!cast<Constant>(Idxs[i])->isNullValue()) {
2170 const PointerType *Ptr = cast<PointerType>(C->getType());
2171 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs,
2173 assert(Ty != 0 && "Invalid indices for GEP!");
2174 return ConstantPointerNull::get(PointerType::get(Ty,
2175 Ptr->getAddressSpace()));
2179 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2180 // Combine Indices - If the source pointer to this getelementptr instruction
2181 // is a getelementptr instruction, combine the indices of the two
2182 // getelementptr instructions into a single instruction.
2184 if (CE->getOpcode() == Instruction::GetElementPtr) {
2185 const Type *LastTy = 0;
2186 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2190 if ((LastTy && LastTy->isArrayTy()) || Idx0->isNullValue()) {
2191 SmallVector<Value*, 16> NewIndices;
2192 NewIndices.reserve(NumIdx + CE->getNumOperands());
2193 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2194 NewIndices.push_back(CE->getOperand(i));
2196 // Add the last index of the source with the first index of the new GEP.
2197 // Make sure to handle the case when they are actually different types.
2198 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2199 // Otherwise it must be an array.
2200 if (!Idx0->isNullValue()) {
2201 const Type *IdxTy = Combined->getType();
2202 if (IdxTy != Idx0->getType()) {
2203 const Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2204 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2205 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
2206 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2209 ConstantExpr::get(Instruction::Add, Idx0, Combined);
2213 NewIndices.push_back(Combined);
2214 NewIndices.append(Idxs+1, Idxs+NumIdx);
2215 return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
2216 ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
2218 NewIndices.size()) :
2219 ConstantExpr::getGetElementPtr(CE->getOperand(0),
2225 // Implement folding of:
2226 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2228 // To: i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2230 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
2231 if (const PointerType *SPT =
2232 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
2233 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
2234 if (const ArrayType *CAT =
2235 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
2236 if (CAT->getElementType() == SAT->getElementType())
2238 ConstantExpr::getInBoundsGetElementPtr(
2239 (Constant*)CE->getOperand(0), Idxs, NumIdx) :
2240 ConstantExpr::getGetElementPtr(
2241 (Constant*)CE->getOperand(0), Idxs, NumIdx);
2245 // Check to see if any array indices are not within the corresponding
2246 // notional array bounds. If so, try to determine if they can be factored
2247 // out into preceding dimensions.
2248 bool Unknown = false;
2249 SmallVector<Constant *, 8> NewIdxs;
2250 const Type *Ty = C->getType();
2251 const Type *Prev = 0;
2252 for (unsigned i = 0; i != NumIdx;
2253 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2254 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2255 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2256 if (ATy->getNumElements() <= INT64_MAX &&
2257 ATy->getNumElements() != 0 &&
2258 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2259 if (isa<SequentialType>(Prev)) {
2260 // It's out of range, but we can factor it into the prior
2262 NewIdxs.resize(NumIdx);
2263 ConstantInt *Factor = ConstantInt::get(CI->getType(),
2264 ATy->getNumElements());
2265 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2267 Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2268 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2270 // Before adding, extend both operands to i64 to avoid
2271 // overflow trouble.
2272 if (!PrevIdx->getType()->isIntegerTy(64))
2273 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2274 Type::getInt64Ty(Div->getContext()));
2275 if (!Div->getType()->isIntegerTy(64))
2276 Div = ConstantExpr::getSExt(Div,
2277 Type::getInt64Ty(Div->getContext()));
2279 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2281 // It's out of range, but the prior dimension is a struct
2282 // so we can't do anything about it.
2287 // We don't know if it's in range or not.
2292 // If we did any factoring, start over with the adjusted indices.
2293 if (!NewIdxs.empty()) {
2294 for (unsigned i = 0; i != NumIdx; ++i)
2295 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2297 ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
2299 ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
2302 // If all indices are known integers and normalized, we can do a simple
2303 // check for the "inbounds" property.
2304 if (!Unknown && !inBounds &&
2305 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
2306 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);
2311 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2313 Constant* const *Idxs,
2315 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs, NumIdx);
2318 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2322 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs, NumIdx);