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) {
45 // If this cast changes element count then we can't handle it here:
46 // doing so requires endianness information. This should be handled by
47 // Analysis/ConstantFolding.cpp
48 unsigned NumElts = DstTy->getNumElements();
49 if (NumElts != CV->getNumOperands())
52 // Check to verify that all elements of the input are simple.
53 for (unsigned i = 0; i != NumElts; ++i) {
54 if (!isa<ConstantInt>(CV->getOperand(i)) &&
55 !isa<ConstantFP>(CV->getOperand(i)))
59 // Bitcast each element now.
60 std::vector<Constant*> Result;
61 const Type *DstEltTy = DstTy->getElementType();
62 for (unsigned i = 0; i != NumElts; ++i)
63 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i),
65 return ConstantVector::get(Result);
68 /// This function determines which opcode to use to fold two constant cast
69 /// expressions together. It uses CastInst::isEliminableCastPair to determine
70 /// the opcode. Consequently its just a wrapper around that function.
71 /// @brief Determine if it is valid to fold a cast of a cast
74 unsigned opc, ///< opcode of the second cast constant expression
75 ConstantExpr *Op, ///< the first cast constant expression
76 const Type *DstTy ///< desintation type of the first cast
78 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
79 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
80 assert(CastInst::isCast(opc) && "Invalid cast opcode");
82 // The the types and opcodes for the two Cast constant expressions
83 const Type *SrcTy = Op->getOperand(0)->getType();
84 const Type *MidTy = Op->getType();
85 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
86 Instruction::CastOps secondOp = Instruction::CastOps(opc);
88 // Let CastInst::isEliminableCastPair do the heavy lifting.
89 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
90 Type::getInt64Ty(DstTy->getContext()));
93 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
94 const Type *SrcTy = V->getType();
96 return V; // no-op cast
98 // Check to see if we are casting a pointer to an aggregate to a pointer to
99 // the first element. If so, return the appropriate GEP instruction.
100 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
101 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
102 if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
103 SmallVector<Value*, 8> IdxList;
105 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
106 IdxList.push_back(Zero);
107 const Type *ElTy = PTy->getElementType();
108 while (ElTy != DPTy->getElementType()) {
109 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
110 if (STy->getNumElements() == 0) break;
111 ElTy = STy->getElementType(0);
112 IdxList.push_back(Zero);
113 } else if (const SequentialType *STy =
114 dyn_cast<SequentialType>(ElTy)) {
115 if (ElTy->isPointerTy()) break; // Can't index into pointers!
116 ElTy = STy->getElementType();
117 IdxList.push_back(Zero);
123 if (ElTy == DPTy->getElementType())
124 // This GEP is inbounds because all indices are zero.
125 return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
129 // Handle casts from one vector constant to another. We know that the src
130 // and dest type have the same size (otherwise its an illegal cast).
131 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
132 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
133 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
134 "Not cast between same sized vectors!");
136 // First, check for null. Undef is already handled.
137 if (isa<ConstantAggregateZero>(V))
138 return Constant::getNullValue(DestTy);
140 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
141 return BitCastConstantVector(CV, DestPTy);
144 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
145 // This allows for other simplifications (although some of them
146 // can only be handled by Analysis/ConstantFolding.cpp).
147 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
148 return ConstantExpr::getBitCast(ConstantVector::get(&V, 1), DestPTy);
151 // Finally, implement bitcast folding now. The code below doesn't handle
153 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
154 return ConstantPointerNull::get(cast<PointerType>(DestTy));
156 // Handle integral constant input.
157 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
158 if (DestTy->isIntegerTy())
159 // Integral -> Integral. This is a no-op because the bit widths must
160 // be the same. Consequently, we just fold to V.
163 if (DestTy->isFloatingPointTy())
164 return ConstantFP::get(DestTy->getContext(),
165 APFloat(CI->getValue(),
166 !DestTy->isPPC_FP128Ty()));
168 // Otherwise, can't fold this (vector?)
172 // Handle ConstantFP input: FP -> Integral.
173 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
174 return ConstantInt::get(FP->getContext(),
175 FP->getValueAPF().bitcastToAPInt());
181 /// ExtractConstantBytes - V is an integer constant which only has a subset of
182 /// its bytes used. The bytes used are indicated by ByteStart (which is the
183 /// first byte used, counting from the least significant byte) and ByteSize,
184 /// which is the number of bytes used.
186 /// This function analyzes the specified constant to see if the specified byte
187 /// range can be returned as a simplified constant. If so, the constant is
188 /// returned, otherwise null is returned.
190 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
192 assert(C->getType()->isIntegerTy() &&
193 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
194 "Non-byte sized integer input");
195 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
196 assert(ByteSize && "Must be accessing some piece");
197 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
198 assert(ByteSize != CSize && "Should not extract everything");
200 // Constant Integers are simple.
201 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
202 APInt V = CI->getValue();
204 V = V.lshr(ByteStart*8);
206 return ConstantInt::get(CI->getContext(), V);
209 // In the input is a constant expr, we might be able to recursively simplify.
210 // If not, we definitely can't do anything.
211 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
212 if (CE == 0) return 0;
214 switch (CE->getOpcode()) {
216 case Instruction::Or: {
217 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
222 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
223 if (RHSC->isAllOnesValue())
226 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
229 return ConstantExpr::getOr(LHS, RHS);
231 case Instruction::And: {
232 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
237 if (RHS->isNullValue())
240 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
243 return ConstantExpr::getAnd(LHS, RHS);
245 case Instruction::LShr: {
246 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
249 unsigned ShAmt = Amt->getZExtValue();
250 // Cannot analyze non-byte shifts.
251 if ((ShAmt & 7) != 0)
255 // If the extract is known to be all zeros, return zero.
256 if (ByteStart >= CSize-ShAmt)
257 return Constant::getNullValue(IntegerType::get(CE->getContext(),
259 // If the extract is known to be fully in the input, extract it.
260 if (ByteStart+ByteSize+ShAmt <= CSize)
261 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
263 // TODO: Handle the 'partially zero' case.
267 case Instruction::Shl: {
268 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
271 unsigned ShAmt = Amt->getZExtValue();
272 // Cannot analyze non-byte shifts.
273 if ((ShAmt & 7) != 0)
277 // If the extract is known to be all zeros, return zero.
278 if (ByteStart+ByteSize <= ShAmt)
279 return Constant::getNullValue(IntegerType::get(CE->getContext(),
281 // If the extract is known to be fully in the input, extract it.
282 if (ByteStart >= ShAmt)
283 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
285 // TODO: Handle the 'partially zero' case.
289 case Instruction::ZExt: {
290 unsigned SrcBitSize =
291 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
293 // If extracting something that is completely zero, return 0.
294 if (ByteStart*8 >= SrcBitSize)
295 return Constant::getNullValue(IntegerType::get(CE->getContext(),
298 // If exactly extracting the input, return it.
299 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
300 return CE->getOperand(0);
302 // If extracting something completely in the input, if if the input is a
303 // multiple of 8 bits, recurse.
304 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
305 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
307 // Otherwise, if extracting a subset of the input, which is not multiple of
308 // 8 bits, do a shift and trunc to get the bits.
309 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
310 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
311 Constant *Res = CE->getOperand(0);
313 Res = ConstantExpr::getLShr(Res,
314 ConstantInt::get(Res->getType(), ByteStart*8));
315 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
319 // TODO: Handle the 'partially zero' case.
325 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
326 /// on Ty, with any known factors factored out. If Folded is false,
327 /// return null if no factoring was possible, to avoid endlessly
328 /// bouncing an unfoldable expression back into the top-level folder.
330 static Constant *getFoldedSizeOf(const Type *Ty, const Type *DestTy,
332 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
333 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
334 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
335 return ConstantExpr::getNUWMul(E, N);
338 if (const StructType *STy = dyn_cast<StructType>(Ty))
339 if (!STy->isPacked()) {
340 unsigned NumElems = STy->getNumElements();
341 // An empty struct has size zero.
343 return ConstantExpr::getNullValue(DestTy);
344 // Check for a struct with all members having the same size.
345 Constant *MemberSize =
346 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
348 for (unsigned i = 1; i != NumElems; ++i)
350 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
355 Constant *N = ConstantInt::get(DestTy, NumElems);
356 return ConstantExpr::getNUWMul(MemberSize, N);
360 if (const UnionType *UTy = dyn_cast<UnionType>(Ty)) {
361 unsigned NumElems = UTy->getNumElements();
362 // Check for a union with all members having the same size.
363 Constant *MemberSize =
364 getFoldedSizeOf(UTy->getElementType(0), DestTy, true);
366 for (unsigned i = 1; i != NumElems; ++i)
368 getFoldedSizeOf(UTy->getElementType(i), DestTy, true)) {
376 // Pointer size doesn't depend on the pointee type, so canonicalize them
377 // to an arbitrary pointee.
378 if (const PointerType *PTy = dyn_cast<PointerType>(Ty))
379 if (!PTy->getElementType()->isIntegerTy(1))
381 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
382 PTy->getAddressSpace()),
385 // If there's no interesting folding happening, bail so that we don't create
386 // a constant that looks like it needs folding but really doesn't.
390 // Base case: Get a regular sizeof expression.
391 Constant *C = ConstantExpr::getSizeOf(Ty);
392 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
398 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
399 /// on Ty, with any known factors factored out. If Folded is false,
400 /// return null if no factoring was possible, to avoid endlessly
401 /// bouncing an unfoldable expression back into the top-level folder.
403 static Constant *getFoldedAlignOf(const Type *Ty, const Type *DestTy,
405 // The alignment of an array is equal to the alignment of the
406 // array element. Note that this is not always true for vectors.
407 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
408 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
409 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
416 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
417 // Packed structs always have an alignment of 1.
419 return ConstantInt::get(DestTy, 1);
421 // Otherwise, struct alignment is the maximum alignment of any member.
422 // Without target data, we can't compare much, but we can check to see
423 // if all the members have the same alignment.
424 unsigned NumElems = STy->getNumElements();
425 // An empty struct has minimal alignment.
427 return ConstantInt::get(DestTy, 1);
428 // Check for a struct with all members having the same alignment.
429 Constant *MemberAlign =
430 getFoldedAlignOf(STy->getElementType(0), DestTy, true);
432 for (unsigned i = 1; i != NumElems; ++i)
433 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
441 if (const UnionType *UTy = dyn_cast<UnionType>(Ty)) {
442 // Union alignment is the maximum alignment of any member.
443 // Without target data, we can't compare much, but we can check to see
444 // if all the members have the same alignment.
445 unsigned NumElems = UTy->getNumElements();
446 // Check for a union with all members having the same alignment.
447 Constant *MemberAlign =
448 getFoldedAlignOf(UTy->getElementType(0), DestTy, true);
450 for (unsigned i = 1; i != NumElems; ++i)
451 if (MemberAlign != getFoldedAlignOf(UTy->getElementType(i), DestTy, true)) {
459 // Pointer alignment doesn't depend on the pointee type, so canonicalize them
460 // to an arbitrary pointee.
461 if (const PointerType *PTy = dyn_cast<PointerType>(Ty))
462 if (!PTy->getElementType()->isIntegerTy(1))
464 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
466 PTy->getAddressSpace()),
469 // If there's no interesting folding happening, bail so that we don't create
470 // a constant that looks like it needs folding but really doesn't.
474 // Base case: Get a regular alignof expression.
475 Constant *C = ConstantExpr::getAlignOf(Ty);
476 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
482 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
483 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
484 /// return null if no factoring was possible, to avoid endlessly
485 /// bouncing an unfoldable expression back into the top-level folder.
487 static Constant *getFoldedOffsetOf(const Type *Ty, Constant *FieldNo,
490 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
491 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
494 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
495 return ConstantExpr::getNUWMul(E, N);
498 if (const StructType *STy = dyn_cast<StructType>(Ty))
499 if (!STy->isPacked()) {
500 unsigned NumElems = STy->getNumElements();
501 // An empty struct has no members.
504 // Check for a struct with all members having the same size.
505 Constant *MemberSize =
506 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
508 for (unsigned i = 1; i != NumElems; ++i)
510 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
515 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
520 return ConstantExpr::getNUWMul(MemberSize, N);
524 // If there's no interesting folding happening, bail so that we don't create
525 // a constant that looks like it needs folding but really doesn't.
529 // Base case: Get a regular offsetof expression.
530 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
531 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
537 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
538 const Type *DestTy) {
539 if (isa<UndefValue>(V)) {
540 // zext(undef) = 0, because the top bits will be zero.
541 // sext(undef) = 0, because the top bits will all be the same.
542 // [us]itofp(undef) = 0, because the result value is bounded.
543 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
544 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
545 return Constant::getNullValue(DestTy);
546 return UndefValue::get(DestTy);
548 // No compile-time operations on this type yet.
549 if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
552 // If the cast operand is a constant expression, there's a few things we can
553 // do to try to simplify it.
554 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
556 // Try hard to fold cast of cast because they are often eliminable.
557 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
558 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
559 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
560 // If all of the indexes in the GEP are null values, there is no pointer
561 // adjustment going on. We might as well cast the source pointer.
562 bool isAllNull = true;
563 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
564 if (!CE->getOperand(i)->isNullValue()) {
569 // This is casting one pointer type to another, always BitCast
570 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
574 // If the cast operand is a constant vector, perform the cast by
575 // operating on each element. In the cast of bitcasts, the element
576 // count may be mismatched; don't attempt to handle that here.
577 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
578 if (DestTy->isVectorTy() &&
579 cast<VectorType>(DestTy)->getNumElements() ==
580 CV->getType()->getNumElements()) {
581 std::vector<Constant*> res;
582 const VectorType *DestVecTy = cast<VectorType>(DestTy);
583 const Type *DstEltTy = DestVecTy->getElementType();
584 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
585 res.push_back(ConstantExpr::getCast(opc,
586 CV->getOperand(i), DstEltTy));
587 return ConstantVector::get(DestVecTy, res);
590 // We actually have to do a cast now. Perform the cast according to the
594 llvm_unreachable("Failed to cast constant expression");
595 case Instruction::FPTrunc:
596 case Instruction::FPExt:
597 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
599 APFloat Val = FPC->getValueAPF();
600 Val.convert(DestTy->isFloatTy() ? APFloat::IEEEsingle :
601 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
602 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
603 DestTy->isFP128Ty() ? APFloat::IEEEquad :
605 APFloat::rmNearestTiesToEven, &ignored);
606 return ConstantFP::get(V->getContext(), Val);
608 return 0; // Can't fold.
609 case Instruction::FPToUI:
610 case Instruction::FPToSI:
611 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
612 const APFloat &V = FPC->getValueAPF();
615 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
616 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
617 APFloat::rmTowardZero, &ignored);
618 APInt Val(DestBitWidth, 2, x);
619 return ConstantInt::get(FPC->getContext(), Val);
621 return 0; // Can't fold.
622 case Instruction::IntToPtr: //always treated as unsigned
623 if (V->isNullValue()) // Is it an integral null value?
624 return ConstantPointerNull::get(cast<PointerType>(DestTy));
625 return 0; // Other pointer types cannot be casted
626 case Instruction::PtrToInt: // always treated as unsigned
627 // Is it a null pointer value?
628 if (V->isNullValue())
629 return ConstantInt::get(DestTy, 0);
630 // If this is a sizeof-like expression, pull out multiplications by
631 // known factors to expose them to subsequent folding. If it's an
632 // alignof-like expression, factor out known factors.
633 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
634 if (CE->getOpcode() == Instruction::GetElementPtr &&
635 CE->getOperand(0)->isNullValue()) {
637 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
638 if (CE->getNumOperands() == 2) {
639 // Handle a sizeof-like expression.
640 Constant *Idx = CE->getOperand(1);
641 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
642 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
643 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
646 return ConstantExpr::getMul(C, Idx);
648 } else if (CE->getNumOperands() == 3 &&
649 CE->getOperand(1)->isNullValue()) {
650 // Handle an alignof-like expression.
651 if (const StructType *STy = dyn_cast<StructType>(Ty))
652 if (!STy->isPacked()) {
653 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
655 STy->getNumElements() == 2 &&
656 STy->getElementType(0)->isIntegerTy(1)) {
657 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
660 // Handle an offsetof-like expression.
661 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()){
662 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
668 // Other pointer types cannot be casted
670 case Instruction::UIToFP:
671 case Instruction::SIToFP:
672 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
673 APInt api = CI->getValue();
674 const uint64_t zero[] = {0, 0};
675 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
677 (void)apf.convertFromAPInt(api,
678 opc==Instruction::SIToFP,
679 APFloat::rmNearestTiesToEven);
680 return ConstantFP::get(V->getContext(), apf);
683 case Instruction::ZExt:
684 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
685 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
686 APInt Result(CI->getValue());
687 Result.zext(BitWidth);
688 return ConstantInt::get(V->getContext(), Result);
691 case Instruction::SExt:
692 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
693 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
694 APInt Result(CI->getValue());
695 Result.sext(BitWidth);
696 return ConstantInt::get(V->getContext(), Result);
699 case Instruction::Trunc: {
700 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
701 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
702 APInt Result(CI->getValue());
703 Result.trunc(DestBitWidth);
704 return ConstantInt::get(V->getContext(), Result);
707 // The input must be a constantexpr. See if we can simplify this based on
708 // the bytes we are demanding. Only do this if the source and dest are an
709 // even multiple of a byte.
710 if ((DestBitWidth & 7) == 0 &&
711 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
712 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
717 case Instruction::BitCast:
718 return FoldBitCast(V, DestTy);
722 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
723 Constant *V1, Constant *V2) {
724 if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
725 return CB->getZExtValue() ? V1 : V2;
727 if (isa<UndefValue>(V1)) return V2;
728 if (isa<UndefValue>(V2)) return V1;
729 if (isa<UndefValue>(Cond)) return V1;
730 if (V1 == V2) return V1;
734 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
736 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
737 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
738 if (Val->isNullValue()) // ee(zero, x) -> zero
739 return Constant::getNullValue(
740 cast<VectorType>(Val->getType())->getElementType());
742 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
743 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
744 return CVal->getOperand(CIdx->getZExtValue());
745 } else if (isa<UndefValue>(Idx)) {
746 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
747 return CVal->getOperand(0);
753 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
756 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
758 APInt idxVal = CIdx->getValue();
759 if (isa<UndefValue>(Val)) {
760 // Insertion of scalar constant into vector undef
761 // Optimize away insertion of undef
762 if (isa<UndefValue>(Elt))
764 // Otherwise break the aggregate undef into multiple undefs and do
767 cast<VectorType>(Val->getType())->getNumElements();
768 std::vector<Constant*> Ops;
770 for (unsigned i = 0; i < numOps; ++i) {
772 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
775 return ConstantVector::get(Ops);
777 if (isa<ConstantAggregateZero>(Val)) {
778 // Insertion of scalar constant into vector aggregate zero
779 // Optimize away insertion of zero
780 if (Elt->isNullValue())
782 // Otherwise break the aggregate zero into multiple zeros 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 : Constant::getNullValue(Elt->getType());
793 return ConstantVector::get(Ops);
795 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
796 // Insertion of scalar constant into vector constant
797 std::vector<Constant*> Ops;
798 Ops.reserve(CVal->getNumOperands());
799 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
801 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
804 return ConstantVector::get(Ops);
810 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
811 /// return the specified element value. Otherwise return null.
812 static Constant *GetVectorElement(Constant *C, unsigned EltNo) {
813 if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
814 return CV->getOperand(EltNo);
816 const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
817 if (isa<ConstantAggregateZero>(C))
818 return Constant::getNullValue(EltTy);
819 if (isa<UndefValue>(C))
820 return UndefValue::get(EltTy);
824 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
827 // Undefined shuffle mask -> undefined value.
828 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
830 unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
831 unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
832 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
834 // Loop over the shuffle mask, evaluating each element.
835 SmallVector<Constant*, 32> Result;
836 for (unsigned i = 0; i != MaskNumElts; ++i) {
837 Constant *InElt = GetVectorElement(Mask, i);
838 if (InElt == 0) return 0;
840 if (isa<UndefValue>(InElt))
841 InElt = UndefValue::get(EltTy);
842 else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
843 unsigned Elt = CI->getZExtValue();
844 if (Elt >= SrcNumElts*2)
845 InElt = UndefValue::get(EltTy);
846 else if (Elt >= SrcNumElts)
847 InElt = GetVectorElement(V2, Elt - SrcNumElts);
849 InElt = GetVectorElement(V1, Elt);
850 if (InElt == 0) return 0;
855 Result.push_back(InElt);
858 return ConstantVector::get(&Result[0], Result.size());
861 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
862 const unsigned *Idxs,
864 // Base case: no indices, so return the entire value.
868 if (isa<UndefValue>(Agg)) // ev(undef, x) -> undef
869 return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
873 if (isa<ConstantAggregateZero>(Agg)) // ev(0, x) -> 0
875 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
879 // Otherwise recurse.
880 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg))
881 return ConstantFoldExtractValueInstruction(CS->getOperand(*Idxs),
884 if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg))
885 return ConstantFoldExtractValueInstruction(CA->getOperand(*Idxs),
887 ConstantVector *CV = cast<ConstantVector>(Agg);
888 return ConstantFoldExtractValueInstruction(CV->getOperand(*Idxs),
892 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
894 const unsigned *Idxs,
896 // Base case: no indices, so replace the entire value.
900 if (isa<UndefValue>(Agg)) {
901 // Insertion of constant into aggregate undef
902 // Optimize away insertion of undef.
903 if (isa<UndefValue>(Val))
906 // Otherwise break the aggregate undef into multiple undefs and do
908 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
910 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
911 numOps = AR->getNumElements();
912 else if (AggTy->isUnionTy())
915 numOps = cast<StructType>(AggTy)->getNumElements();
917 std::vector<Constant*> Ops(numOps);
918 for (unsigned i = 0; i < numOps; ++i) {
919 const Type *MemberTy = AggTy->getTypeAtIndex(i);
922 ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
923 Val, Idxs+1, NumIdx-1) :
924 UndefValue::get(MemberTy);
928 if (const StructType* ST = dyn_cast<StructType>(AggTy))
929 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
930 if (const UnionType* UT = dyn_cast<UnionType>(AggTy)) {
931 assert(Ops.size() == 1 && "Union can only contain a single value!");
932 return ConstantUnion::get(UT, Ops[0]);
934 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
937 if (isa<ConstantAggregateZero>(Agg)) {
938 // Insertion of constant into aggregate zero
939 // Optimize away insertion of zero.
940 if (Val->isNullValue())
943 // Otherwise break the aggregate zero into multiple zeros and do
945 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
947 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
948 numOps = AR->getNumElements();
950 numOps = cast<StructType>(AggTy)->getNumElements();
952 std::vector<Constant*> Ops(numOps);
953 for (unsigned i = 0; i < numOps; ++i) {
954 const Type *MemberTy = AggTy->getTypeAtIndex(i);
957 ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
958 Val, Idxs+1, NumIdx-1) :
959 Constant::getNullValue(MemberTy);
963 if (const StructType *ST = dyn_cast<StructType>(AggTy))
964 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
965 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
968 if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
969 // Insertion of constant into aggregate constant.
970 std::vector<Constant*> Ops(Agg->getNumOperands());
971 for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
972 Constant *Op = cast<Constant>(Agg->getOperand(i));
974 Op = ConstantFoldInsertValueInstruction(Op, Val, Idxs+1, NumIdx-1);
978 if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
979 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
980 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
987 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
988 Constant *C1, Constant *C2) {
989 // No compile-time operations on this type yet.
990 if (C1->getType()->isPPC_FP128Ty())
993 // Handle UndefValue up front.
994 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
996 case Instruction::Xor:
997 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
998 // Handle undef ^ undef -> 0 special case. This is a common
1000 return Constant::getNullValue(C1->getType());
1002 case Instruction::Add:
1003 case Instruction::Sub:
1004 return UndefValue::get(C1->getType());
1005 case Instruction::Mul:
1006 case Instruction::And:
1007 return Constant::getNullValue(C1->getType());
1008 case Instruction::UDiv:
1009 case Instruction::SDiv:
1010 case Instruction::URem:
1011 case Instruction::SRem:
1012 if (!isa<UndefValue>(C2)) // undef / X -> 0
1013 return Constant::getNullValue(C1->getType());
1014 return C2; // X / undef -> undef
1015 case Instruction::Or: // X | undef -> -1
1016 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
1017 return Constant::getAllOnesValue(PTy);
1018 return Constant::getAllOnesValue(C1->getType());
1019 case Instruction::LShr:
1020 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
1021 return C1; // undef lshr undef -> undef
1022 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
1023 // undef lshr X -> 0
1024 case Instruction::AShr:
1025 if (!isa<UndefValue>(C2))
1026 return C1; // undef ashr X --> undef
1027 else if (isa<UndefValue>(C1))
1028 return C1; // undef ashr undef -> undef
1030 return C1; // X ashr undef --> X
1031 case Instruction::Shl:
1032 // undef << X -> 0 or X << undef -> 0
1033 return Constant::getNullValue(C1->getType());
1037 // Handle simplifications when the RHS is a constant int.
1038 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1040 case Instruction::Add:
1041 if (CI2->equalsInt(0)) return C1; // X + 0 == X
1043 case Instruction::Sub:
1044 if (CI2->equalsInt(0)) return C1; // X - 0 == X
1046 case Instruction::Mul:
1047 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
1048 if (CI2->equalsInt(1))
1049 return C1; // X * 1 == X
1051 case Instruction::UDiv:
1052 case Instruction::SDiv:
1053 if (CI2->equalsInt(1))
1054 return C1; // X / 1 == X
1055 if (CI2->equalsInt(0))
1056 return UndefValue::get(CI2->getType()); // X / 0 == undef
1058 case Instruction::URem:
1059 case Instruction::SRem:
1060 if (CI2->equalsInt(1))
1061 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
1062 if (CI2->equalsInt(0))
1063 return UndefValue::get(CI2->getType()); // X % 0 == undef
1065 case Instruction::And:
1066 if (CI2->isZero()) return C2; // X & 0 == 0
1067 if (CI2->isAllOnesValue())
1068 return C1; // X & -1 == X
1070 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1071 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1072 if (CE1->getOpcode() == Instruction::ZExt) {
1073 unsigned DstWidth = CI2->getType()->getBitWidth();
1075 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1076 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1077 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1081 // If and'ing the address of a global with a constant, fold it.
1082 if (CE1->getOpcode() == Instruction::PtrToInt &&
1083 isa<GlobalValue>(CE1->getOperand(0))) {
1084 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1086 // Functions are at least 4-byte aligned.
1087 unsigned GVAlign = GV->getAlignment();
1088 if (isa<Function>(GV))
1089 GVAlign = std::max(GVAlign, 4U);
1092 unsigned DstWidth = CI2->getType()->getBitWidth();
1093 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1094 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1096 // If checking bits we know are clear, return zero.
1097 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1098 return Constant::getNullValue(CI2->getType());
1103 case Instruction::Or:
1104 if (CI2->equalsInt(0)) return C1; // X | 0 == X
1105 if (CI2->isAllOnesValue())
1106 return C2; // X | -1 == -1
1108 case Instruction::Xor:
1109 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
1111 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1112 switch (CE1->getOpcode()) {
1114 case Instruction::ICmp:
1115 case Instruction::FCmp:
1116 // cmp pred ^ true -> cmp !pred
1117 assert(CI2->equalsInt(1));
1118 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1119 pred = CmpInst::getInversePredicate(pred);
1120 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1121 CE1->getOperand(1));
1125 case Instruction::AShr:
1126 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1127 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1128 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1129 return ConstantExpr::getLShr(C1, C2);
1132 } else if (isa<ConstantInt>(C1)) {
1133 // If C1 is a ConstantInt and C2 is not, swap the operands.
1134 if (Instruction::isCommutative(Opcode))
1135 return ConstantExpr::get(Opcode, C2, C1);
1138 // At this point we know neither constant is an UndefValue.
1139 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1140 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1141 using namespace APIntOps;
1142 const APInt &C1V = CI1->getValue();
1143 const APInt &C2V = CI2->getValue();
1147 case Instruction::Add:
1148 return ConstantInt::get(CI1->getContext(), C1V + C2V);
1149 case Instruction::Sub:
1150 return ConstantInt::get(CI1->getContext(), C1V - C2V);
1151 case Instruction::Mul:
1152 return ConstantInt::get(CI1->getContext(), C1V * C2V);
1153 case Instruction::UDiv:
1154 assert(!CI2->isNullValue() && "Div by zero handled above");
1155 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1156 case Instruction::SDiv:
1157 assert(!CI2->isNullValue() && "Div by zero handled above");
1158 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1159 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
1160 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1161 case Instruction::URem:
1162 assert(!CI2->isNullValue() && "Div by zero handled above");
1163 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1164 case Instruction::SRem:
1165 assert(!CI2->isNullValue() && "Div by zero handled above");
1166 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1167 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
1168 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1169 case Instruction::And:
1170 return ConstantInt::get(CI1->getContext(), C1V & C2V);
1171 case Instruction::Or:
1172 return ConstantInt::get(CI1->getContext(), C1V | C2V);
1173 case Instruction::Xor:
1174 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1175 case Instruction::Shl: {
1176 uint32_t shiftAmt = C2V.getZExtValue();
1177 if (shiftAmt < C1V.getBitWidth())
1178 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1180 return UndefValue::get(C1->getType()); // too big shift is undef
1182 case Instruction::LShr: {
1183 uint32_t shiftAmt = C2V.getZExtValue();
1184 if (shiftAmt < C1V.getBitWidth())
1185 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1187 return UndefValue::get(C1->getType()); // too big shift is undef
1189 case Instruction::AShr: {
1190 uint32_t shiftAmt = C2V.getZExtValue();
1191 if (shiftAmt < C1V.getBitWidth())
1192 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1194 return UndefValue::get(C1->getType()); // too big shift is undef
1200 case Instruction::SDiv:
1201 case Instruction::UDiv:
1202 case Instruction::URem:
1203 case Instruction::SRem:
1204 case Instruction::LShr:
1205 case Instruction::AShr:
1206 case Instruction::Shl:
1207 if (CI1->equalsInt(0)) return C1;
1212 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1213 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1214 APFloat C1V = CFP1->getValueAPF();
1215 APFloat C2V = CFP2->getValueAPF();
1216 APFloat C3V = C1V; // copy for modification
1220 case Instruction::FAdd:
1221 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1222 return ConstantFP::get(C1->getContext(), C3V);
1223 case Instruction::FSub:
1224 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1225 return ConstantFP::get(C1->getContext(), C3V);
1226 case Instruction::FMul:
1227 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1228 return ConstantFP::get(C1->getContext(), C3V);
1229 case Instruction::FDiv:
1230 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1231 return ConstantFP::get(C1->getContext(), C3V);
1232 case Instruction::FRem:
1233 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1234 return ConstantFP::get(C1->getContext(), C3V);
1237 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1238 ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
1239 ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
1240 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
1241 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
1242 std::vector<Constant*> Res;
1243 const Type* EltTy = VTy->getElementType();
1249 case Instruction::Add:
1250 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1251 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1252 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1253 Res.push_back(ConstantExpr::getAdd(C1, C2));
1255 return ConstantVector::get(Res);
1256 case Instruction::FAdd:
1257 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1258 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1259 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1260 Res.push_back(ConstantExpr::getFAdd(C1, C2));
1262 return ConstantVector::get(Res);
1263 case Instruction::Sub:
1264 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1265 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1266 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1267 Res.push_back(ConstantExpr::getSub(C1, C2));
1269 return ConstantVector::get(Res);
1270 case Instruction::FSub:
1271 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1272 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1273 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1274 Res.push_back(ConstantExpr::getFSub(C1, C2));
1276 return ConstantVector::get(Res);
1277 case Instruction::Mul:
1278 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1279 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1280 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1281 Res.push_back(ConstantExpr::getMul(C1, C2));
1283 return ConstantVector::get(Res);
1284 case Instruction::FMul:
1285 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1286 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1287 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1288 Res.push_back(ConstantExpr::getFMul(C1, C2));
1290 return ConstantVector::get(Res);
1291 case Instruction::UDiv:
1292 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1293 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1294 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1295 Res.push_back(ConstantExpr::getUDiv(C1, C2));
1297 return ConstantVector::get(Res);
1298 case Instruction::SDiv:
1299 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1300 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1301 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1302 Res.push_back(ConstantExpr::getSDiv(C1, C2));
1304 return ConstantVector::get(Res);
1305 case Instruction::FDiv:
1306 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1307 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1308 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1309 Res.push_back(ConstantExpr::getFDiv(C1, C2));
1311 return ConstantVector::get(Res);
1312 case Instruction::URem:
1313 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1314 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1315 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1316 Res.push_back(ConstantExpr::getURem(C1, C2));
1318 return ConstantVector::get(Res);
1319 case Instruction::SRem:
1320 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1321 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1322 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1323 Res.push_back(ConstantExpr::getSRem(C1, C2));
1325 return ConstantVector::get(Res);
1326 case Instruction::FRem:
1327 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1328 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1329 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1330 Res.push_back(ConstantExpr::getFRem(C1, C2));
1332 return ConstantVector::get(Res);
1333 case Instruction::And:
1334 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1335 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1336 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1337 Res.push_back(ConstantExpr::getAnd(C1, C2));
1339 return ConstantVector::get(Res);
1340 case Instruction::Or:
1341 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1342 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1343 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1344 Res.push_back(ConstantExpr::getOr(C1, C2));
1346 return ConstantVector::get(Res);
1347 case Instruction::Xor:
1348 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1349 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1350 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1351 Res.push_back(ConstantExpr::getXor(C1, C2));
1353 return ConstantVector::get(Res);
1354 case Instruction::LShr:
1355 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1356 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1357 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1358 Res.push_back(ConstantExpr::getLShr(C1, C2));
1360 return ConstantVector::get(Res);
1361 case Instruction::AShr:
1362 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1363 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1364 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1365 Res.push_back(ConstantExpr::getAShr(C1, C2));
1367 return ConstantVector::get(Res);
1368 case Instruction::Shl:
1369 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1370 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1371 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1372 Res.push_back(ConstantExpr::getShl(C1, C2));
1374 return ConstantVector::get(Res);
1379 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1380 // There are many possible foldings we could do here. We should probably
1381 // at least fold add of a pointer with an integer into the appropriate
1382 // getelementptr. This will improve alias analysis a bit.
1384 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1386 if (Instruction::isAssociative(Opcode, C1->getType()) &&
1387 CE1->getOpcode() == Opcode) {
1388 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1389 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1390 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1392 } else if (isa<ConstantExpr>(C2)) {
1393 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1394 // other way if possible.
1395 if (Instruction::isCommutative(Opcode))
1396 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1399 // i1 can be simplified in many cases.
1400 if (C1->getType()->isIntegerTy(1)) {
1402 case Instruction::Add:
1403 case Instruction::Sub:
1404 return ConstantExpr::getXor(C1, C2);
1405 case Instruction::Mul:
1406 return ConstantExpr::getAnd(C1, C2);
1407 case Instruction::Shl:
1408 case Instruction::LShr:
1409 case Instruction::AShr:
1410 // We can assume that C2 == 0. If it were one the result would be
1411 // undefined because the shift value is as large as the bitwidth.
1413 case Instruction::SDiv:
1414 case Instruction::UDiv:
1415 // We can assume that C2 == 1. If it were zero the result would be
1416 // undefined through division by zero.
1418 case Instruction::URem:
1419 case Instruction::SRem:
1420 // We can assume that C2 == 1. If it were zero the result would be
1421 // undefined through division by zero.
1422 return ConstantInt::getFalse(C1->getContext());
1428 // We don't know how to fold this.
1432 /// isZeroSizedType - This type is zero sized if its an array or structure of
1433 /// zero sized types. The only leaf zero sized type is an empty structure.
1434 static bool isMaybeZeroSizedType(const Type *Ty) {
1435 if (Ty->isOpaqueTy()) return true; // Can't say.
1436 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1438 // If all of elements have zero size, this does too.
1439 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1440 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1443 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1444 return isMaybeZeroSizedType(ATy->getElementType());
1449 /// IdxCompare - Compare the two constants as though they were getelementptr
1450 /// indices. This allows coersion of the types to be the same thing.
1452 /// If the two constants are the "same" (after coersion), return 0. If the
1453 /// first is less than the second, return -1, if the second is less than the
1454 /// first, return 1. If the constants are not integral, return -2.
1456 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
1457 if (C1 == C2) return 0;
1459 // Ok, we found a different index. If they are not ConstantInt, we can't do
1460 // anything with them.
1461 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1462 return -2; // don't know!
1464 // Ok, we have two differing integer indices. Sign extend them to be the same
1465 // type. Long is always big enough, so we use it.
1466 if (!C1->getType()->isIntegerTy(64))
1467 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1469 if (!C2->getType()->isIntegerTy(64))
1470 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1472 if (C1 == C2) return 0; // They are equal
1474 // If the type being indexed over is really just a zero sized type, there is
1475 // no pointer difference being made here.
1476 if (isMaybeZeroSizedType(ElTy))
1477 return -2; // dunno.
1479 // If they are really different, now that they are the same type, then we
1480 // found a difference!
1481 if (cast<ConstantInt>(C1)->getSExtValue() <
1482 cast<ConstantInt>(C2)->getSExtValue())
1488 /// evaluateFCmpRelation - This function determines if there is anything we can
1489 /// decide about the two constants provided. This doesn't need to handle simple
1490 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1491 /// If we can determine that the two constants have a particular relation to
1492 /// each other, we should return the corresponding FCmpInst predicate,
1493 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1494 /// ConstantFoldCompareInstruction.
1496 /// To simplify this code we canonicalize the relation so that the first
1497 /// operand is always the most "complex" of the two. We consider ConstantFP
1498 /// to be the simplest, and ConstantExprs to be the most complex.
1499 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1500 assert(V1->getType() == V2->getType() &&
1501 "Cannot compare values of different types!");
1503 // No compile-time operations on this type yet.
1504 if (V1->getType()->isPPC_FP128Ty())
1505 return FCmpInst::BAD_FCMP_PREDICATE;
1507 // Handle degenerate case quickly
1508 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1510 if (!isa<ConstantExpr>(V1)) {
1511 if (!isa<ConstantExpr>(V2)) {
1512 // We distilled thisUse the standard constant folder for a few cases
1514 R = dyn_cast<ConstantInt>(
1515 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1516 if (R && !R->isZero())
1517 return FCmpInst::FCMP_OEQ;
1518 R = dyn_cast<ConstantInt>(
1519 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1520 if (R && !R->isZero())
1521 return FCmpInst::FCMP_OLT;
1522 R = dyn_cast<ConstantInt>(
1523 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1524 if (R && !R->isZero())
1525 return FCmpInst::FCMP_OGT;
1527 // Nothing more we can do
1528 return FCmpInst::BAD_FCMP_PREDICATE;
1531 // If the first operand is simple and second is ConstantExpr, swap operands.
1532 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1533 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1534 return FCmpInst::getSwappedPredicate(SwappedRelation);
1536 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1537 // constantexpr or a simple constant.
1538 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1539 switch (CE1->getOpcode()) {
1540 case Instruction::FPTrunc:
1541 case Instruction::FPExt:
1542 case Instruction::UIToFP:
1543 case Instruction::SIToFP:
1544 // We might be able to do something with these but we don't right now.
1550 // There are MANY other foldings that we could perform here. They will
1551 // probably be added on demand, as they seem needed.
1552 return FCmpInst::BAD_FCMP_PREDICATE;
1555 /// evaluateICmpRelation - This function determines if there is anything we can
1556 /// decide about the two constants provided. This doesn't need to handle simple
1557 /// things like integer comparisons, but should instead handle ConstantExprs
1558 /// and GlobalValues. If we can determine that the two constants have a
1559 /// particular relation to each other, we should return the corresponding ICmp
1560 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1562 /// To simplify this code we canonicalize the relation so that the first
1563 /// operand is always the most "complex" of the two. We consider simple
1564 /// constants (like ConstantInt) to be the simplest, followed by
1565 /// GlobalValues, followed by ConstantExpr's (the most complex).
1567 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1569 assert(V1->getType() == V2->getType() &&
1570 "Cannot compare different types of values!");
1571 if (V1 == V2) return ICmpInst::ICMP_EQ;
1573 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1574 !isa<BlockAddress>(V1)) {
1575 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1576 !isa<BlockAddress>(V2)) {
1577 // We distilled this down to a simple case, use the standard constant
1580 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1581 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1582 if (R && !R->isZero())
1584 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1585 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1586 if (R && !R->isZero())
1588 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1589 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1590 if (R && !R->isZero())
1593 // If we couldn't figure it out, bail.
1594 return ICmpInst::BAD_ICMP_PREDICATE;
1597 // If the first operand is simple, swap operands.
1598 ICmpInst::Predicate SwappedRelation =
1599 evaluateICmpRelation(V2, V1, isSigned);
1600 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1601 return ICmpInst::getSwappedPredicate(SwappedRelation);
1603 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1604 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1605 ICmpInst::Predicate SwappedRelation =
1606 evaluateICmpRelation(V2, V1, isSigned);
1607 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1608 return ICmpInst::getSwappedPredicate(SwappedRelation);
1609 return ICmpInst::BAD_ICMP_PREDICATE;
1612 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1613 // constant (which, since the types must match, means that it's a
1614 // ConstantPointerNull).
1615 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1616 // Don't try to decide equality of aliases.
1617 if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1618 if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1619 return ICmpInst::ICMP_NE;
1620 } else if (isa<BlockAddress>(V2)) {
1621 return ICmpInst::ICMP_NE; // Globals never equal labels.
1623 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1624 // GlobalVals can never be null unless they have external weak linkage.
1625 // We don't try to evaluate aliases here.
1626 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1627 return ICmpInst::ICMP_NE;
1629 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1630 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1631 ICmpInst::Predicate SwappedRelation =
1632 evaluateICmpRelation(V2, V1, isSigned);
1633 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1634 return ICmpInst::getSwappedPredicate(SwappedRelation);
1635 return ICmpInst::BAD_ICMP_PREDICATE;
1638 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1639 // constant (which, since the types must match, means that it is a
1640 // ConstantPointerNull).
1641 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1642 // Block address in another function can't equal this one, but block
1643 // addresses in the current function might be the same if blocks are
1645 if (BA2->getFunction() != BA->getFunction())
1646 return ICmpInst::ICMP_NE;
1648 // Block addresses aren't null, don't equal the address of globals.
1649 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1650 "Canonicalization guarantee!");
1651 return ICmpInst::ICMP_NE;
1654 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1655 // constantexpr, a global, block address, or a simple constant.
1656 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1657 Constant *CE1Op0 = CE1->getOperand(0);
1659 switch (CE1->getOpcode()) {
1660 case Instruction::Trunc:
1661 case Instruction::FPTrunc:
1662 case Instruction::FPExt:
1663 case Instruction::FPToUI:
1664 case Instruction::FPToSI:
1665 break; // We can't evaluate floating point casts or truncations.
1667 case Instruction::UIToFP:
1668 case Instruction::SIToFP:
1669 case Instruction::BitCast:
1670 case Instruction::ZExt:
1671 case Instruction::SExt:
1672 // If the cast is not actually changing bits, and the second operand is a
1673 // null pointer, do the comparison with the pre-casted value.
1674 if (V2->isNullValue() &&
1675 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1676 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1677 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1678 return evaluateICmpRelation(CE1Op0,
1679 Constant::getNullValue(CE1Op0->getType()),
1684 case Instruction::GetElementPtr:
1685 // Ok, since this is a getelementptr, we know that the constant has a
1686 // pointer type. Check the various cases.
1687 if (isa<ConstantPointerNull>(V2)) {
1688 // If we are comparing a GEP to a null pointer, check to see if the base
1689 // of the GEP equals the null pointer.
1690 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1691 if (GV->hasExternalWeakLinkage())
1692 // Weak linkage GVals could be zero or not. We're comparing that
1693 // to null pointer so its greater-or-equal
1694 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1696 // If its not weak linkage, the GVal must have a non-zero address
1697 // so the result is greater-than
1698 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1699 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1700 // If we are indexing from a null pointer, check to see if we have any
1701 // non-zero indices.
1702 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1703 if (!CE1->getOperand(i)->isNullValue())
1704 // Offsetting from null, must not be equal.
1705 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1706 // Only zero indexes from null, must still be zero.
1707 return ICmpInst::ICMP_EQ;
1709 // Otherwise, we can't really say if the first operand is null or not.
1710 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1711 if (isa<ConstantPointerNull>(CE1Op0)) {
1712 if (GV2->hasExternalWeakLinkage())
1713 // Weak linkage GVals could be zero or not. We're comparing it to
1714 // a null pointer, so its less-or-equal
1715 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1717 // If its not weak linkage, the GVal must have a non-zero address
1718 // so the result is less-than
1719 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1720 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1722 // If this is a getelementptr of the same global, then it must be
1723 // different. Because the types must match, the getelementptr could
1724 // only have at most one index, and because we fold getelementptr's
1725 // with a single zero index, it must be nonzero.
1726 assert(CE1->getNumOperands() == 2 &&
1727 !CE1->getOperand(1)->isNullValue() &&
1728 "Suprising getelementptr!");
1729 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1731 // If they are different globals, we don't know what the value is,
1732 // but they can't be equal.
1733 return ICmpInst::ICMP_NE;
1737 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1738 Constant *CE2Op0 = CE2->getOperand(0);
1740 // There are MANY other foldings that we could perform here. They will
1741 // probably be added on demand, as they seem needed.
1742 switch (CE2->getOpcode()) {
1744 case Instruction::GetElementPtr:
1745 // By far the most common case to handle is when the base pointers are
1746 // obviously to the same or different globals.
1747 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1748 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1749 return ICmpInst::ICMP_NE;
1750 // Ok, we know that both getelementptr instructions are based on the
1751 // same global. From this, we can precisely determine the relative
1752 // ordering of the resultant pointers.
1755 // The logic below assumes that the result of the comparison
1756 // can be determined by finding the first index that differs.
1757 // This doesn't work if there is over-indexing in any
1758 // subsequent indices, so check for that case first.
1759 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1760 !CE2->isGEPWithNoNotionalOverIndexing())
1761 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1763 // Compare all of the operands the GEP's have in common.
1764 gep_type_iterator GTI = gep_type_begin(CE1);
1765 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1767 switch (IdxCompare(CE1->getOperand(i),
1768 CE2->getOperand(i), GTI.getIndexedType())) {
1769 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1770 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1771 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1774 // Ok, we ran out of things they have in common. If any leftovers
1775 // are non-zero then we have a difference, otherwise we are equal.
1776 for (; i < CE1->getNumOperands(); ++i)
1777 if (!CE1->getOperand(i)->isNullValue()) {
1778 if (isa<ConstantInt>(CE1->getOperand(i)))
1779 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1781 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1784 for (; i < CE2->getNumOperands(); ++i)
1785 if (!CE2->getOperand(i)->isNullValue()) {
1786 if (isa<ConstantInt>(CE2->getOperand(i)))
1787 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1789 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1791 return ICmpInst::ICMP_EQ;
1800 return ICmpInst::BAD_ICMP_PREDICATE;
1803 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1804 Constant *C1, Constant *C2) {
1805 const Type *ResultTy;
1806 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1807 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1808 VT->getNumElements());
1810 ResultTy = Type::getInt1Ty(C1->getContext());
1812 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1813 if (pred == FCmpInst::FCMP_FALSE)
1814 return Constant::getNullValue(ResultTy);
1816 if (pred == FCmpInst::FCMP_TRUE)
1817 return Constant::getAllOnesValue(ResultTy);
1819 // Handle some degenerate cases first
1820 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1821 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1823 // No compile-time operations on this type yet.
1824 if (C1->getType()->isPPC_FP128Ty())
1827 // icmp eq/ne(null,GV) -> false/true
1828 if (C1->isNullValue()) {
1829 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1830 // Don't try to evaluate aliases. External weak GV can be null.
1831 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1832 if (pred == ICmpInst::ICMP_EQ)
1833 return ConstantInt::getFalse(C1->getContext());
1834 else if (pred == ICmpInst::ICMP_NE)
1835 return ConstantInt::getTrue(C1->getContext());
1837 // icmp eq/ne(GV,null) -> false/true
1838 } else if (C2->isNullValue()) {
1839 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1840 // Don't try to evaluate aliases. External weak GV can be null.
1841 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1842 if (pred == ICmpInst::ICMP_EQ)
1843 return ConstantInt::getFalse(C1->getContext());
1844 else if (pred == ICmpInst::ICMP_NE)
1845 return ConstantInt::getTrue(C1->getContext());
1849 // If the comparison is a comparison between two i1's, simplify it.
1850 if (C1->getType()->isIntegerTy(1)) {
1852 case ICmpInst::ICMP_EQ:
1853 if (isa<ConstantInt>(C2))
1854 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1855 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1856 case ICmpInst::ICMP_NE:
1857 return ConstantExpr::getXor(C1, C2);
1863 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1864 APInt V1 = cast<ConstantInt>(C1)->getValue();
1865 APInt V2 = cast<ConstantInt>(C2)->getValue();
1867 default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1868 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
1869 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
1870 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1871 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1872 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1873 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1874 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1875 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1876 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1877 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1879 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1880 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1881 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1882 APFloat::cmpResult R = C1V.compare(C2V);
1884 default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1885 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1886 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
1887 case FCmpInst::FCMP_UNO:
1888 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1889 case FCmpInst::FCMP_ORD:
1890 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1891 case FCmpInst::FCMP_UEQ:
1892 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1893 R==APFloat::cmpEqual);
1894 case FCmpInst::FCMP_OEQ:
1895 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1896 case FCmpInst::FCMP_UNE:
1897 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1898 case FCmpInst::FCMP_ONE:
1899 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1900 R==APFloat::cmpGreaterThan);
1901 case FCmpInst::FCMP_ULT:
1902 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1903 R==APFloat::cmpLessThan);
1904 case FCmpInst::FCMP_OLT:
1905 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1906 case FCmpInst::FCMP_UGT:
1907 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1908 R==APFloat::cmpGreaterThan);
1909 case FCmpInst::FCMP_OGT:
1910 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1911 case FCmpInst::FCMP_ULE:
1912 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1913 case FCmpInst::FCMP_OLE:
1914 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1915 R==APFloat::cmpEqual);
1916 case FCmpInst::FCMP_UGE:
1917 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1918 case FCmpInst::FCMP_OGE:
1919 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1920 R==APFloat::cmpEqual);
1922 } else if (C1->getType()->isVectorTy()) {
1923 SmallVector<Constant*, 16> C1Elts, C2Elts;
1924 C1->getVectorElements(C1Elts);
1925 C2->getVectorElements(C2Elts);
1926 if (C1Elts.empty() || C2Elts.empty())
1929 // If we can constant fold the comparison of each element, constant fold
1930 // the whole vector comparison.
1931 SmallVector<Constant*, 4> ResElts;
1932 for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1933 // Compare the elements, producing an i1 result or constant expr.
1934 ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
1936 return ConstantVector::get(&ResElts[0], ResElts.size());
1939 if (C1->getType()->isFloatingPointTy()) {
1940 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1941 switch (evaluateFCmpRelation(C1, C2)) {
1942 default: llvm_unreachable("Unknown relation!");
1943 case FCmpInst::FCMP_UNO:
1944 case FCmpInst::FCMP_ORD:
1945 case FCmpInst::FCMP_UEQ:
1946 case FCmpInst::FCMP_UNE:
1947 case FCmpInst::FCMP_ULT:
1948 case FCmpInst::FCMP_UGT:
1949 case FCmpInst::FCMP_ULE:
1950 case FCmpInst::FCMP_UGE:
1951 case FCmpInst::FCMP_TRUE:
1952 case FCmpInst::FCMP_FALSE:
1953 case FCmpInst::BAD_FCMP_PREDICATE:
1954 break; // Couldn't determine anything about these constants.
1955 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1956 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1957 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1958 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1960 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1961 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1962 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1963 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1965 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1966 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1967 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1968 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1970 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1971 // We can only partially decide this relation.
1972 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1974 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1977 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1978 // We can only partially decide this relation.
1979 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1981 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1984 case ICmpInst::ICMP_NE: // We know that C1 != C2
1985 // We can only partially decide this relation.
1986 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1988 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1993 // If we evaluated the result, return it now.
1995 return ConstantInt::get(ResultTy, Result);
1998 // Evaluate the relation between the two constants, per the predicate.
1999 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
2000 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
2001 default: llvm_unreachable("Unknown relational!");
2002 case ICmpInst::BAD_ICMP_PREDICATE:
2003 break; // Couldn't determine anything about these constants.
2004 case ICmpInst::ICMP_EQ: // We know the constants are equal!
2005 // If we know the constants are equal, we can decide the result of this
2006 // computation precisely.
2007 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
2009 case ICmpInst::ICMP_ULT:
2011 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
2013 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
2017 case ICmpInst::ICMP_SLT:
2019 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
2021 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
2025 case ICmpInst::ICMP_UGT:
2027 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
2029 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
2033 case ICmpInst::ICMP_SGT:
2035 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
2037 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
2041 case ICmpInst::ICMP_ULE:
2042 if (pred == ICmpInst::ICMP_UGT) Result = 0;
2043 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
2045 case ICmpInst::ICMP_SLE:
2046 if (pred == ICmpInst::ICMP_SGT) Result = 0;
2047 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
2049 case ICmpInst::ICMP_UGE:
2050 if (pred == ICmpInst::ICMP_ULT) Result = 0;
2051 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
2053 case ICmpInst::ICMP_SGE:
2054 if (pred == ICmpInst::ICMP_SLT) Result = 0;
2055 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
2057 case ICmpInst::ICMP_NE:
2058 if (pred == ICmpInst::ICMP_EQ) Result = 0;
2059 if (pred == ICmpInst::ICMP_NE) Result = 1;
2063 // If we evaluated the result, return it now.
2065 return ConstantInt::get(ResultTy, Result);
2067 // If the right hand side is a bitcast, try using its inverse to simplify
2068 // it by moving it to the left hand side. We can't do this if it would turn
2069 // a vector compare into a scalar compare or visa versa.
2070 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
2071 Constant *CE2Op0 = CE2->getOperand(0);
2072 if (CE2->getOpcode() == Instruction::BitCast &&
2073 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
2074 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
2075 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
2079 // If the left hand side is an extension, try eliminating it.
2080 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2081 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
2082 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
2083 Constant *CE1Op0 = CE1->getOperand(0);
2084 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2085 if (CE1Inverse == CE1Op0) {
2086 // Check whether we can safely truncate the right hand side.
2087 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2088 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
2089 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2095 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2096 (C1->isNullValue() && !C2->isNullValue())) {
2097 // If C2 is a constant expr and C1 isn't, flip them around and fold the
2098 // other way if possible.
2099 // Also, if C1 is null and C2 isn't, flip them around.
2100 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
2101 return ConstantExpr::getICmp(pred, C2, C1);
2107 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
2109 static bool isInBoundsIndices(Constant *const *Idxs, size_t NumIdx) {
2110 // No indices means nothing that could be out of bounds.
2111 if (NumIdx == 0) return true;
2113 // If the first index is zero, it's in bounds.
2114 if (Idxs[0]->isNullValue()) return true;
2116 // If the first index is one and all the rest are zero, it's in bounds,
2117 // by the one-past-the-end rule.
2118 if (!cast<ConstantInt>(Idxs[0])->isOne())
2120 for (unsigned i = 1, e = NumIdx; i != e; ++i)
2121 if (!Idxs[i]->isNullValue())
2126 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2128 Constant* const *Idxs,
2131 (NumIdx == 1 && Idxs[0]->isNullValue()))
2134 if (isa<UndefValue>(C)) {
2135 const PointerType *Ptr = cast<PointerType>(C->getType());
2136 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
2138 (Value **)Idxs+NumIdx);
2139 assert(Ty != 0 && "Invalid indices for GEP!");
2140 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
2143 Constant *Idx0 = Idxs[0];
2144 if (C->isNullValue()) {
2146 for (unsigned i = 0, e = NumIdx; i != e; ++i)
2147 if (!Idxs[i]->isNullValue()) {
2152 const PointerType *Ptr = cast<PointerType>(C->getType());
2153 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
2155 (Value**)Idxs+NumIdx);
2156 assert(Ty != 0 && "Invalid indices for GEP!");
2157 return ConstantPointerNull::get(
2158 PointerType::get(Ty,Ptr->getAddressSpace()));
2162 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2163 // Combine Indices - If the source pointer to this getelementptr instruction
2164 // is a getelementptr instruction, combine the indices of the two
2165 // getelementptr instructions into a single instruction.
2167 if (CE->getOpcode() == Instruction::GetElementPtr) {
2168 const Type *LastTy = 0;
2169 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2173 if ((LastTy && LastTy->isArrayTy()) || Idx0->isNullValue()) {
2174 SmallVector<Value*, 16> NewIndices;
2175 NewIndices.reserve(NumIdx + CE->getNumOperands());
2176 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2177 NewIndices.push_back(CE->getOperand(i));
2179 // Add the last index of the source with the first index of the new GEP.
2180 // Make sure to handle the case when they are actually different types.
2181 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2182 // Otherwise it must be an array.
2183 if (!Idx0->isNullValue()) {
2184 const Type *IdxTy = Combined->getType();
2185 if (IdxTy != Idx0->getType()) {
2186 const Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2187 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2188 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
2189 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2192 ConstantExpr::get(Instruction::Add, Idx0, Combined);
2196 NewIndices.push_back(Combined);
2197 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
2198 return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
2199 ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
2201 NewIndices.size()) :
2202 ConstantExpr::getGetElementPtr(CE->getOperand(0),
2208 // Implement folding of:
2209 // int* getelementptr ([2 x int]* bitcast ([3 x int]* %X to [2 x int]*),
2211 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
2213 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
2214 if (const PointerType *SPT =
2215 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
2216 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
2217 if (const ArrayType *CAT =
2218 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
2219 if (CAT->getElementType() == SAT->getElementType())
2221 ConstantExpr::getInBoundsGetElementPtr(
2222 (Constant*)CE->getOperand(0), Idxs, NumIdx) :
2223 ConstantExpr::getGetElementPtr(
2224 (Constant*)CE->getOperand(0), Idxs, NumIdx);
2228 // Check to see if any array indices are not within the corresponding
2229 // notional array bounds. If so, try to determine if they can be factored
2230 // out into preceding dimensions.
2231 bool Unknown = false;
2232 SmallVector<Constant *, 8> NewIdxs;
2233 const Type *Ty = C->getType();
2234 const Type *Prev = 0;
2235 for (unsigned i = 0; i != NumIdx;
2236 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2237 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2238 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2239 if (ATy->getNumElements() <= INT64_MAX &&
2240 ATy->getNumElements() != 0 &&
2241 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2242 if (isa<SequentialType>(Prev)) {
2243 // It's out of range, but we can factor it into the prior
2245 NewIdxs.resize(NumIdx);
2246 ConstantInt *Factor = ConstantInt::get(CI->getType(),
2247 ATy->getNumElements());
2248 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2250 Constant *PrevIdx = Idxs[i-1];
2251 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2253 // Before adding, extend both operands to i64 to avoid
2254 // overflow trouble.
2255 if (!PrevIdx->getType()->isIntegerTy(64))
2256 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2257 Type::getInt64Ty(Div->getContext()));
2258 if (!Div->getType()->isIntegerTy(64))
2259 Div = ConstantExpr::getSExt(Div,
2260 Type::getInt64Ty(Div->getContext()));
2262 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2264 // It's out of range, but the prior dimension is a struct
2265 // so we can't do anything about it.
2270 // We don't know if it's in range or not.
2275 // If we did any factoring, start over with the adjusted indices.
2276 if (!NewIdxs.empty()) {
2277 for (unsigned i = 0; i != NumIdx; ++i)
2278 if (!NewIdxs[i]) NewIdxs[i] = Idxs[i];
2280 ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
2282 ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
2285 // If all indices are known integers and normalized, we can do a simple
2286 // check for the "inbounds" property.
2287 if (!Unknown && !inBounds &&
2288 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
2289 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);