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 DataLayout, and the pieces that do. This is to avoid
16 // a dependence in IR on Target.
18 //===----------------------------------------------------------------------===//
20 #include "ConstantFold.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
37 //===----------------------------------------------------------------------===//
38 // ConstantFold*Instruction Implementations
39 //===----------------------------------------------------------------------===//
41 /// BitCastConstantVector - Convert the specified vector Constant node to the
42 /// specified vector type. At this point, we know that the elements of the
43 /// input vector constant are all simple integer or FP values.
44 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
46 if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
47 if (CV->isNullValue()) return Constant::getNullValue(DstTy);
49 // If this cast changes element count then we can't handle it here:
50 // doing so requires endianness information. This should be handled by
51 // Analysis/ConstantFolding.cpp
52 unsigned NumElts = DstTy->getNumElements();
53 if (NumElts != CV->getType()->getVectorNumElements())
56 Type *DstEltTy = DstTy->getElementType();
58 SmallVector<Constant*, 16> Result;
59 Type *Ty = IntegerType::get(CV->getContext(), 32);
60 for (unsigned i = 0; i != NumElts; ++i) {
62 ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
63 C = ConstantExpr::getBitCast(C, DstEltTy);
67 return ConstantVector::get(Result);
70 /// This function determines which opcode to use to fold two constant cast
71 /// expressions together. It uses CastInst::isEliminableCastPair to determine
72 /// the opcode. Consequently its just a wrapper around that function.
73 /// @brief Determine if it is valid to fold a cast of a cast
76 unsigned opc, ///< opcode of the second cast constant expression
77 ConstantExpr *Op, ///< the first cast constant expression
78 Type *DstTy ///< destination type of the first cast
80 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
81 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
82 assert(CastInst::isCast(opc) && "Invalid cast opcode");
84 // The the types and opcodes for the two Cast constant expressions
85 Type *SrcTy = Op->getOperand(0)->getType();
86 Type *MidTy = Op->getType();
87 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
88 Instruction::CastOps secondOp = Instruction::CastOps(opc);
90 // Assume that pointers are never more than 64 bits wide, and only use this
91 // for the middle type. Otherwise we could end up folding away illegal
92 // bitcasts between address spaces with different sizes.
93 IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
95 // Let CastInst::isEliminableCastPair do the heavy lifting.
96 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
97 nullptr, FakeIntPtrTy, nullptr);
100 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
101 Type *SrcTy = V->getType();
103 return V; // no-op cast
105 // Check to see if we are casting a pointer to an aggregate to a pointer to
106 // the first element. If so, return the appropriate GEP instruction.
107 if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
108 if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
109 if (PTy->getAddressSpace() == DPTy->getAddressSpace()
110 && DPTy->getElementType()->isSized()) {
111 SmallVector<Value*, 8> IdxList;
113 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
114 IdxList.push_back(Zero);
115 Type *ElTy = PTy->getElementType();
116 while (ElTy != DPTy->getElementType()) {
117 if (StructType *STy = dyn_cast<StructType>(ElTy)) {
118 if (STy->getNumElements() == 0) break;
119 ElTy = STy->getElementType(0);
120 IdxList.push_back(Zero);
121 } else if (SequentialType *STy =
122 dyn_cast<SequentialType>(ElTy)) {
123 if (ElTy->isPointerTy()) break; // Can't index into pointers!
124 ElTy = STy->getElementType();
125 IdxList.push_back(Zero);
131 if (ElTy == DPTy->getElementType())
132 // This GEP is inbounds because all indices are zero.
133 return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
136 // Handle casts from one vector constant to another. We know that the src
137 // and dest type have the same size (otherwise its an illegal cast).
138 if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
139 if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
140 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
141 "Not cast between same sized vectors!");
143 // First, check for null. Undef is already handled.
144 if (isa<ConstantAggregateZero>(V))
145 return Constant::getNullValue(DestTy);
147 // Handle ConstantVector and ConstantAggregateVector.
148 return BitCastConstantVector(V, DestPTy);
151 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
152 // This allows for other simplifications (although some of them
153 // can only be handled by Analysis/ConstantFolding.cpp).
154 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
155 return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
158 // Finally, implement bitcast folding now. The code below doesn't handle
160 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
161 return ConstantPointerNull::get(cast<PointerType>(DestTy));
163 // Handle integral constant input.
164 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
165 if (DestTy->isIntegerTy())
166 // Integral -> Integral. This is a no-op because the bit widths must
167 // be the same. Consequently, we just fold to V.
170 if (DestTy->isFloatingPointTy())
171 return ConstantFP::get(DestTy->getContext(),
172 APFloat(DestTy->getFltSemantics(),
175 // Otherwise, can't fold this (vector?)
179 // Handle ConstantFP input: FP -> Integral.
180 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
181 return ConstantInt::get(FP->getContext(),
182 FP->getValueAPF().bitcastToAPInt());
188 /// ExtractConstantBytes - V is an integer constant which only has a subset of
189 /// its bytes used. The bytes used are indicated by ByteStart (which is the
190 /// first byte used, counting from the least significant byte) and ByteSize,
191 /// which is the number of bytes used.
193 /// This function analyzes the specified constant to see if the specified byte
194 /// range can be returned as a simplified constant. If so, the constant is
195 /// returned, otherwise null is returned.
197 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
199 assert(C->getType()->isIntegerTy() &&
200 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
201 "Non-byte sized integer input");
202 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
203 assert(ByteSize && "Must be accessing some piece");
204 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
205 assert(ByteSize != CSize && "Should not extract everything");
207 // Constant Integers are simple.
208 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
209 APInt V = CI->getValue();
211 V = V.lshr(ByteStart*8);
212 V = V.trunc(ByteSize*8);
213 return ConstantInt::get(CI->getContext(), V);
216 // In the input is a constant expr, we might be able to recursively simplify.
217 // If not, we definitely can't do anything.
218 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
219 if (!CE) return nullptr;
221 switch (CE->getOpcode()) {
222 default: return nullptr;
223 case Instruction::Or: {
224 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
229 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
230 if (RHSC->isAllOnesValue())
233 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
236 return ConstantExpr::getOr(LHS, RHS);
238 case Instruction::And: {
239 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
244 if (RHS->isNullValue())
247 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
250 return ConstantExpr::getAnd(LHS, RHS);
252 case Instruction::LShr: {
253 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
256 unsigned ShAmt = Amt->getZExtValue();
257 // Cannot analyze non-byte shifts.
258 if ((ShAmt & 7) != 0)
262 // If the extract is known to be all zeros, return zero.
263 if (ByteStart >= CSize-ShAmt)
264 return Constant::getNullValue(IntegerType::get(CE->getContext(),
266 // If the extract is known to be fully in the input, extract it.
267 if (ByteStart+ByteSize+ShAmt <= CSize)
268 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
270 // TODO: Handle the 'partially zero' case.
274 case Instruction::Shl: {
275 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
278 unsigned ShAmt = Amt->getZExtValue();
279 // Cannot analyze non-byte shifts.
280 if ((ShAmt & 7) != 0)
284 // If the extract is known to be all zeros, return zero.
285 if (ByteStart+ByteSize <= ShAmt)
286 return Constant::getNullValue(IntegerType::get(CE->getContext(),
288 // If the extract is known to be fully in the input, extract it.
289 if (ByteStart >= ShAmt)
290 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
292 // TODO: Handle the 'partially zero' case.
296 case Instruction::ZExt: {
297 unsigned SrcBitSize =
298 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
300 // If extracting something that is completely zero, return 0.
301 if (ByteStart*8 >= SrcBitSize)
302 return Constant::getNullValue(IntegerType::get(CE->getContext(),
305 // If exactly extracting the input, return it.
306 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
307 return CE->getOperand(0);
309 // If extracting something completely in the input, if if the input is a
310 // multiple of 8 bits, recurse.
311 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
312 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
314 // Otherwise, if extracting a subset of the input, which is not multiple of
315 // 8 bits, do a shift and trunc to get the bits.
316 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
317 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
318 Constant *Res = CE->getOperand(0);
320 Res = ConstantExpr::getLShr(Res,
321 ConstantInt::get(Res->getType(), ByteStart*8));
322 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
326 // TODO: Handle the 'partially zero' case.
332 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
333 /// on Ty, with any known factors factored out. If Folded is false,
334 /// return null if no factoring was possible, to avoid endlessly
335 /// bouncing an unfoldable expression back into the top-level folder.
337 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
339 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
340 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
341 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
342 return ConstantExpr::getNUWMul(E, N);
345 if (StructType *STy = dyn_cast<StructType>(Ty))
346 if (!STy->isPacked()) {
347 unsigned NumElems = STy->getNumElements();
348 // An empty struct has size zero.
350 return ConstantExpr::getNullValue(DestTy);
351 // Check for a struct with all members having the same size.
352 Constant *MemberSize =
353 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
355 for (unsigned i = 1; i != NumElems; ++i)
357 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
362 Constant *N = ConstantInt::get(DestTy, NumElems);
363 return ConstantExpr::getNUWMul(MemberSize, N);
367 // Pointer size doesn't depend on the pointee type, so canonicalize them
368 // to an arbitrary pointee.
369 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
370 if (!PTy->getElementType()->isIntegerTy(1))
372 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
373 PTy->getAddressSpace()),
376 // If there's no interesting folding happening, bail so that we don't create
377 // a constant that looks like it needs folding but really doesn't.
381 // Base case: Get a regular sizeof expression.
382 Constant *C = ConstantExpr::getSizeOf(Ty);
383 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
389 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
390 /// on Ty, with any known factors factored out. If Folded is false,
391 /// return null if no factoring was possible, to avoid endlessly
392 /// bouncing an unfoldable expression back into the top-level folder.
394 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
396 // The alignment of an array is equal to the alignment of the
397 // array element. Note that this is not always true for vectors.
398 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
399 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
400 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
407 if (StructType *STy = dyn_cast<StructType>(Ty)) {
408 // Packed structs always have an alignment of 1.
410 return ConstantInt::get(DestTy, 1);
412 // Otherwise, struct alignment is the maximum alignment of any member.
413 // Without target data, we can't compare much, but we can check to see
414 // if all the members have the same alignment.
415 unsigned NumElems = STy->getNumElements();
416 // An empty struct has minimal alignment.
418 return ConstantInt::get(DestTy, 1);
419 // Check for a struct with all members having the same alignment.
420 Constant *MemberAlign =
421 getFoldedAlignOf(STy->getElementType(0), DestTy, true);
423 for (unsigned i = 1; i != NumElems; ++i)
424 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
432 // Pointer alignment doesn't depend on the pointee type, so canonicalize them
433 // to an arbitrary pointee.
434 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
435 if (!PTy->getElementType()->isIntegerTy(1))
437 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
439 PTy->getAddressSpace()),
442 // If there's no interesting folding happening, bail so that we don't create
443 // a constant that looks like it needs folding but really doesn't.
447 // Base case: Get a regular alignof expression.
448 Constant *C = ConstantExpr::getAlignOf(Ty);
449 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
455 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
456 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
457 /// return null if no factoring was possible, to avoid endlessly
458 /// bouncing an unfoldable expression back into the top-level folder.
460 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
463 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
464 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
467 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
468 return ConstantExpr::getNUWMul(E, N);
471 if (StructType *STy = dyn_cast<StructType>(Ty))
472 if (!STy->isPacked()) {
473 unsigned NumElems = STy->getNumElements();
474 // An empty struct has no members.
477 // Check for a struct with all members having the same size.
478 Constant *MemberSize =
479 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
481 for (unsigned i = 1; i != NumElems; ++i)
483 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
488 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
493 return ConstantExpr::getNUWMul(MemberSize, N);
497 // If there's no interesting folding happening, bail so that we don't create
498 // a constant that looks like it needs folding but really doesn't.
502 // Base case: Get a regular offsetof expression.
503 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
504 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
510 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
512 if (isa<UndefValue>(V)) {
513 // zext(undef) = 0, because the top bits will be zero.
514 // sext(undef) = 0, because the top bits will all be the same.
515 // [us]itofp(undef) = 0, because the result value is bounded.
516 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
517 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
518 return Constant::getNullValue(DestTy);
519 return UndefValue::get(DestTy);
522 if (V->isNullValue() && !DestTy->isX86_MMXTy())
523 return Constant::getNullValue(DestTy);
525 // If the cast operand is a constant expression, there's a few things we can
526 // do to try to simplify it.
527 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
529 // Try hard to fold cast of cast because they are often eliminable.
530 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
531 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
532 } else if (CE->getOpcode() == Instruction::GetElementPtr &&
533 // Do not fold addrspacecast (gep 0, .., 0). It might make the
534 // addrspacecast uncanonicalized.
535 opc != Instruction::AddrSpaceCast) {
536 // If all of the indexes in the GEP are null values, there is no pointer
537 // adjustment going on. We might as well cast the source pointer.
538 bool isAllNull = true;
539 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
540 if (!CE->getOperand(i)->isNullValue()) {
545 // This is casting one pointer type to another, always BitCast
546 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
550 // If the cast operand is a constant vector, perform the cast by
551 // operating on each element. In the cast of bitcasts, the element
552 // count may be mismatched; don't attempt to handle that here.
553 if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
554 DestTy->isVectorTy() &&
555 DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
556 SmallVector<Constant*, 16> res;
557 VectorType *DestVecTy = cast<VectorType>(DestTy);
558 Type *DstEltTy = DestVecTy->getElementType();
559 Type *Ty = IntegerType::get(V->getContext(), 32);
560 for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
562 ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
563 res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
565 return ConstantVector::get(res);
568 // We actually have to do a cast now. Perform the cast according to the
572 llvm_unreachable("Failed to cast constant expression");
573 case Instruction::FPTrunc:
574 case Instruction::FPExt:
575 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
577 APFloat Val = FPC->getValueAPF();
578 Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
579 DestTy->isFloatTy() ? APFloat::IEEEsingle :
580 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
581 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
582 DestTy->isFP128Ty() ? APFloat::IEEEquad :
583 DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
585 APFloat::rmNearestTiesToEven, &ignored);
586 return ConstantFP::get(V->getContext(), Val);
588 return nullptr; // Can't fold.
589 case Instruction::FPToUI:
590 case Instruction::FPToSI:
591 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
592 const APFloat &V = FPC->getValueAPF();
595 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
596 if (APFloat::opInvalidOp ==
597 V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
598 APFloat::rmTowardZero, &ignored)) {
599 // Undefined behavior invoked - the destination type can't represent
600 // the input constant.
601 return UndefValue::get(DestTy);
603 APInt Val(DestBitWidth, x);
604 return ConstantInt::get(FPC->getContext(), Val);
606 return nullptr; // Can't fold.
607 case Instruction::IntToPtr: //always treated as unsigned
608 if (V->isNullValue()) // Is it an integral null value?
609 return ConstantPointerNull::get(cast<PointerType>(DestTy));
610 return nullptr; // Other pointer types cannot be casted
611 case Instruction::PtrToInt: // always treated as unsigned
612 // Is it a null pointer value?
613 if (V->isNullValue())
614 return ConstantInt::get(DestTy, 0);
615 // If this is a sizeof-like expression, pull out multiplications by
616 // known factors to expose them to subsequent folding. If it's an
617 // alignof-like expression, factor out known factors.
618 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
619 if (CE->getOpcode() == Instruction::GetElementPtr &&
620 CE->getOperand(0)->isNullValue()) {
622 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
623 if (CE->getNumOperands() == 2) {
624 // Handle a sizeof-like expression.
625 Constant *Idx = CE->getOperand(1);
626 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
627 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
628 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
631 return ConstantExpr::getMul(C, Idx);
633 } else if (CE->getNumOperands() == 3 &&
634 CE->getOperand(1)->isNullValue()) {
635 // Handle an alignof-like expression.
636 if (StructType *STy = dyn_cast<StructType>(Ty))
637 if (!STy->isPacked()) {
638 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
640 STy->getNumElements() == 2 &&
641 STy->getElementType(0)->isIntegerTy(1)) {
642 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
645 // Handle an offsetof-like expression.
646 if (Ty->isStructTy() || Ty->isArrayTy()) {
647 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
653 // Other pointer types cannot be casted
655 case Instruction::UIToFP:
656 case Instruction::SIToFP:
657 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
658 APInt api = CI->getValue();
659 APFloat apf(DestTy->getFltSemantics(),
660 APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
661 if (APFloat::opOverflow &
662 apf.convertFromAPInt(api, opc==Instruction::SIToFP,
663 APFloat::rmNearestTiesToEven)) {
664 // Undefined behavior invoked - the destination type can't represent
665 // the input constant.
666 return UndefValue::get(DestTy);
668 return ConstantFP::get(V->getContext(), apf);
671 case Instruction::ZExt:
672 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
673 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
674 return ConstantInt::get(V->getContext(),
675 CI->getValue().zext(BitWidth));
678 case Instruction::SExt:
679 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
680 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
681 return ConstantInt::get(V->getContext(),
682 CI->getValue().sext(BitWidth));
685 case Instruction::Trunc: {
686 if (V->getType()->isVectorTy())
689 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
690 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
691 return ConstantInt::get(V->getContext(),
692 CI->getValue().trunc(DestBitWidth));
695 // The input must be a constantexpr. See if we can simplify this based on
696 // the bytes we are demanding. Only do this if the source and dest are an
697 // even multiple of a byte.
698 if ((DestBitWidth & 7) == 0 &&
699 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
700 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
705 case Instruction::BitCast:
706 return FoldBitCast(V, DestTy);
707 case Instruction::AddrSpaceCast:
712 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
713 Constant *V1, Constant *V2) {
714 // Check for i1 and vector true/false conditions.
715 if (Cond->isNullValue()) return V2;
716 if (Cond->isAllOnesValue()) return V1;
718 // If the condition is a vector constant, fold the result elementwise.
719 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
720 SmallVector<Constant*, 16> Result;
721 Type *Ty = IntegerType::get(CondV->getContext(), 32);
722 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
724 Constant *V1Element = ConstantExpr::getExtractElement(V1,
725 ConstantInt::get(Ty, i));
726 Constant *V2Element = ConstantExpr::getExtractElement(V2,
727 ConstantInt::get(Ty, i));
728 Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i));
729 if (V1Element == V2Element) {
731 } else if (isa<UndefValue>(Cond)) {
732 V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
734 if (!isa<ConstantInt>(Cond)) break;
735 V = Cond->isNullValue() ? V2Element : V1Element;
740 // If we were able to build the vector, return it.
741 if (Result.size() == V1->getType()->getVectorNumElements())
742 return ConstantVector::get(Result);
745 if (isa<UndefValue>(Cond)) {
746 if (isa<UndefValue>(V1)) return V1;
749 if (isa<UndefValue>(V1)) return V2;
750 if (isa<UndefValue>(V2)) return V1;
751 if (V1 == V2) return V1;
753 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
754 if (TrueVal->getOpcode() == Instruction::Select)
755 if (TrueVal->getOperand(0) == Cond)
756 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
758 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
759 if (FalseVal->getOpcode() == Instruction::Select)
760 if (FalseVal->getOperand(0) == Cond)
761 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
767 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
769 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
770 return UndefValue::get(Val->getType()->getVectorElementType());
771 if (Val->isNullValue()) // ee(zero, x) -> zero
772 return Constant::getNullValue(Val->getType()->getVectorElementType());
773 // ee({w,x,y,z}, undef) -> undef
774 if (isa<UndefValue>(Idx))
775 return UndefValue::get(Val->getType()->getVectorElementType());
777 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
778 uint64_t Index = CIdx->getZExtValue();
779 // ee({w,x,y,z}, wrong_value) -> undef
780 if (Index >= Val->getType()->getVectorNumElements())
781 return UndefValue::get(Val->getType()->getVectorElementType());
782 return Val->getAggregateElement(Index);
787 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
790 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
791 if (!CIdx) return nullptr;
792 const APInt &IdxVal = CIdx->getValue();
794 SmallVector<Constant*, 16> Result;
795 Type *Ty = IntegerType::get(Val->getContext(), 32);
796 for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
798 Result.push_back(Elt);
803 ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
807 return ConstantVector::get(Result);
810 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
813 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
814 Type *EltTy = V1->getType()->getVectorElementType();
816 // Undefined shuffle mask -> undefined value.
817 if (isa<UndefValue>(Mask))
818 return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
820 // Don't break the bitcode reader hack.
821 if (isa<ConstantExpr>(Mask)) return nullptr;
823 unsigned SrcNumElts = V1->getType()->getVectorNumElements();
825 // Loop over the shuffle mask, evaluating each element.
826 SmallVector<Constant*, 32> Result;
827 for (unsigned i = 0; i != MaskNumElts; ++i) {
828 int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
830 Result.push_back(UndefValue::get(EltTy));
834 if (unsigned(Elt) >= SrcNumElts*2)
835 InElt = UndefValue::get(EltTy);
836 else if (unsigned(Elt) >= SrcNumElts) {
837 Type *Ty = IntegerType::get(V2->getContext(), 32);
839 ConstantExpr::getExtractElement(V2,
840 ConstantInt::get(Ty, Elt - SrcNumElts));
842 Type *Ty = IntegerType::get(V1->getContext(), 32);
843 InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
845 Result.push_back(InElt);
848 return ConstantVector::get(Result);
851 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
852 ArrayRef<unsigned> Idxs) {
853 // Base case: no indices, so return the entire value.
857 if (Constant *C = Agg->getAggregateElement(Idxs[0]))
858 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
863 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
865 ArrayRef<unsigned> Idxs) {
866 // Base case: no indices, so replace the entire value.
871 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
872 NumElts = ST->getNumElements();
873 else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
874 NumElts = AT->getNumElements();
876 NumElts = Agg->getType()->getVectorNumElements();
878 SmallVector<Constant*, 32> Result;
879 for (unsigned i = 0; i != NumElts; ++i) {
880 Constant *C = Agg->getAggregateElement(i);
881 if (!C) return nullptr;
884 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
889 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
890 return ConstantStruct::get(ST, Result);
891 if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
892 return ConstantArray::get(AT, Result);
893 return ConstantVector::get(Result);
897 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
898 Constant *C1, Constant *C2) {
899 // Handle UndefValue up front.
900 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
902 case Instruction::Xor:
903 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
904 // Handle undef ^ undef -> 0 special case. This is a common
906 return Constant::getNullValue(C1->getType());
908 case Instruction::Add:
909 case Instruction::Sub:
910 return UndefValue::get(C1->getType());
911 case Instruction::And:
912 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
914 return Constant::getNullValue(C1->getType()); // undef & X -> 0
915 case Instruction::Mul: {
917 // X * undef -> undef if X is odd or undef
918 if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
919 ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
920 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
921 return UndefValue::get(C1->getType());
923 // X * undef -> 0 otherwise
924 return Constant::getNullValue(C1->getType());
926 case Instruction::UDiv:
927 case Instruction::SDiv:
928 // undef / 1 -> undef
929 if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
930 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
934 case Instruction::URem:
935 case Instruction::SRem:
936 if (!isa<UndefValue>(C2)) // undef / X -> 0
937 return Constant::getNullValue(C1->getType());
938 return C2; // X / undef -> undef
939 case Instruction::Or: // X | undef -> -1
940 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
942 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
943 case Instruction::LShr:
944 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
945 return C1; // undef lshr undef -> undef
946 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
948 case Instruction::AShr:
949 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones
950 return Constant::getAllOnesValue(C1->getType());
951 else if (isa<UndefValue>(C1))
952 return C1; // undef ashr undef -> undef
954 return C1; // X ashr undef --> X
955 case Instruction::Shl:
956 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
957 return C1; // undef shl undef -> undef
958 // undef << X -> 0 or X << undef -> 0
959 return Constant::getNullValue(C1->getType());
963 // Handle simplifications when the RHS is a constant int.
964 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
966 case Instruction::Add:
967 if (CI2->equalsInt(0)) return C1; // X + 0 == X
969 case Instruction::Sub:
970 if (CI2->equalsInt(0)) return C1; // X - 0 == X
972 case Instruction::Mul:
973 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
974 if (CI2->equalsInt(1))
975 return C1; // X * 1 == X
977 case Instruction::UDiv:
978 case Instruction::SDiv:
979 if (CI2->equalsInt(1))
980 return C1; // X / 1 == X
981 if (CI2->equalsInt(0))
982 return UndefValue::get(CI2->getType()); // X / 0 == undef
984 case Instruction::URem:
985 case Instruction::SRem:
986 if (CI2->equalsInt(1))
987 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
988 if (CI2->equalsInt(0))
989 return UndefValue::get(CI2->getType()); // X % 0 == undef
991 case Instruction::And:
992 if (CI2->isZero()) return C2; // X & 0 == 0
993 if (CI2->isAllOnesValue())
994 return C1; // X & -1 == X
996 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
997 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
998 if (CE1->getOpcode() == Instruction::ZExt) {
999 unsigned DstWidth = CI2->getType()->getBitWidth();
1001 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1002 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1003 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1007 // If and'ing the address of a global with a constant, fold it.
1008 if (CE1->getOpcode() == Instruction::PtrToInt &&
1009 isa<GlobalValue>(CE1->getOperand(0))) {
1010 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1012 // Functions are at least 4-byte aligned.
1013 unsigned GVAlign = GV->getAlignment();
1014 if (isa<Function>(GV))
1015 GVAlign = std::max(GVAlign, 4U);
1018 unsigned DstWidth = CI2->getType()->getBitWidth();
1019 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1020 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1022 // If checking bits we know are clear, return zero.
1023 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1024 return Constant::getNullValue(CI2->getType());
1029 case Instruction::Or:
1030 if (CI2->equalsInt(0)) return C1; // X | 0 == X
1031 if (CI2->isAllOnesValue())
1032 return C2; // X | -1 == -1
1034 case Instruction::Xor:
1035 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
1037 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1038 switch (CE1->getOpcode()) {
1040 case Instruction::ICmp:
1041 case Instruction::FCmp:
1042 // cmp pred ^ true -> cmp !pred
1043 assert(CI2->equalsInt(1));
1044 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1045 pred = CmpInst::getInversePredicate(pred);
1046 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1047 CE1->getOperand(1));
1051 case Instruction::AShr:
1052 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1053 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1054 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1055 return ConstantExpr::getLShr(C1, C2);
1058 } else if (isa<ConstantInt>(C1)) {
1059 // If C1 is a ConstantInt and C2 is not, swap the operands.
1060 if (Instruction::isCommutative(Opcode))
1061 return ConstantExpr::get(Opcode, C2, C1);
1064 // At this point we know neither constant is an UndefValue.
1065 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1066 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1067 const APInt &C1V = CI1->getValue();
1068 const APInt &C2V = CI2->getValue();
1072 case Instruction::Add:
1073 return ConstantInt::get(CI1->getContext(), C1V + C2V);
1074 case Instruction::Sub:
1075 return ConstantInt::get(CI1->getContext(), C1V - C2V);
1076 case Instruction::Mul:
1077 return ConstantInt::get(CI1->getContext(), C1V * C2V);
1078 case Instruction::UDiv:
1079 assert(!CI2->isNullValue() && "Div by zero handled above");
1080 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1081 case Instruction::SDiv:
1082 assert(!CI2->isNullValue() && "Div by zero handled above");
1083 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1084 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
1085 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1086 case Instruction::URem:
1087 assert(!CI2->isNullValue() && "Div by zero handled above");
1088 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1089 case Instruction::SRem:
1090 assert(!CI2->isNullValue() && "Div by zero handled above");
1091 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1092 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
1093 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1094 case Instruction::And:
1095 return ConstantInt::get(CI1->getContext(), C1V & C2V);
1096 case Instruction::Or:
1097 return ConstantInt::get(CI1->getContext(), C1V | C2V);
1098 case Instruction::Xor:
1099 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1100 case Instruction::Shl: {
1101 uint32_t shiftAmt = C2V.getZExtValue();
1102 if (shiftAmt < C1V.getBitWidth())
1103 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1105 return UndefValue::get(C1->getType()); // too big shift is undef
1107 case Instruction::LShr: {
1108 uint32_t shiftAmt = C2V.getZExtValue();
1109 if (shiftAmt < C1V.getBitWidth())
1110 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1112 return UndefValue::get(C1->getType()); // too big shift is undef
1114 case Instruction::AShr: {
1115 uint32_t shiftAmt = C2V.getZExtValue();
1116 if (shiftAmt < C1V.getBitWidth())
1117 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1119 return UndefValue::get(C1->getType()); // too big shift is undef
1125 case Instruction::SDiv:
1126 case Instruction::UDiv:
1127 case Instruction::URem:
1128 case Instruction::SRem:
1129 case Instruction::LShr:
1130 case Instruction::AShr:
1131 case Instruction::Shl:
1132 if (CI1->equalsInt(0)) return C1;
1137 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1138 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1139 APFloat C1V = CFP1->getValueAPF();
1140 APFloat C2V = CFP2->getValueAPF();
1141 APFloat C3V = C1V; // copy for modification
1145 case Instruction::FAdd:
1146 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1147 return ConstantFP::get(C1->getContext(), C3V);
1148 case Instruction::FSub:
1149 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1150 return ConstantFP::get(C1->getContext(), C3V);
1151 case Instruction::FMul:
1152 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1153 return ConstantFP::get(C1->getContext(), C3V);
1154 case Instruction::FDiv:
1155 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1156 return ConstantFP::get(C1->getContext(), C3V);
1157 case Instruction::FRem:
1158 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1159 return ConstantFP::get(C1->getContext(), C3V);
1162 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1163 // Perform elementwise folding.
1164 SmallVector<Constant*, 16> Result;
1165 Type *Ty = IntegerType::get(VTy->getContext(), 32);
1166 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1168 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1170 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1172 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1175 return ConstantVector::get(Result);
1178 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1179 // There are many possible foldings we could do here. We should probably
1180 // at least fold add of a pointer with an integer into the appropriate
1181 // getelementptr. This will improve alias analysis a bit.
1183 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1185 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1186 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1187 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1188 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1190 } else if (isa<ConstantExpr>(C2)) {
1191 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1192 // other way if possible.
1193 if (Instruction::isCommutative(Opcode))
1194 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1197 // i1 can be simplified in many cases.
1198 if (C1->getType()->isIntegerTy(1)) {
1200 case Instruction::Add:
1201 case Instruction::Sub:
1202 return ConstantExpr::getXor(C1, C2);
1203 case Instruction::Mul:
1204 return ConstantExpr::getAnd(C1, C2);
1205 case Instruction::Shl:
1206 case Instruction::LShr:
1207 case Instruction::AShr:
1208 // We can assume that C2 == 0. If it were one the result would be
1209 // undefined because the shift value is as large as the bitwidth.
1211 case Instruction::SDiv:
1212 case Instruction::UDiv:
1213 // We can assume that C2 == 1. If it were zero the result would be
1214 // undefined through division by zero.
1216 case Instruction::URem:
1217 case Instruction::SRem:
1218 // We can assume that C2 == 1. If it were zero the result would be
1219 // undefined through division by zero.
1220 return ConstantInt::getFalse(C1->getContext());
1226 // We don't know how to fold this.
1230 /// isZeroSizedType - This type is zero sized if its an array or structure of
1231 /// zero sized types. The only leaf zero sized type is an empty structure.
1232 static bool isMaybeZeroSizedType(Type *Ty) {
1233 if (StructType *STy = dyn_cast<StructType>(Ty)) {
1234 if (STy->isOpaque()) return true; // Can't say.
1236 // If all of elements have zero size, this does too.
1237 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1238 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1241 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1242 return isMaybeZeroSizedType(ATy->getElementType());
1247 /// IdxCompare - Compare the two constants as though they were getelementptr
1248 /// indices. This allows coersion of the types to be the same thing.
1250 /// If the two constants are the "same" (after coersion), return 0. If the
1251 /// first is less than the second, return -1, if the second is less than the
1252 /// first, return 1. If the constants are not integral, return -2.
1254 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1255 if (C1 == C2) return 0;
1257 // Ok, we found a different index. If they are not ConstantInt, we can't do
1258 // anything with them.
1259 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1260 return -2; // don't know!
1262 // Ok, we have two differing integer indices. Sign extend them to be the same
1263 // type. Long is always big enough, so we use it.
1264 if (!C1->getType()->isIntegerTy(64))
1265 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1267 if (!C2->getType()->isIntegerTy(64))
1268 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1270 if (C1 == C2) return 0; // They are equal
1272 // If the type being indexed over is really just a zero sized type, there is
1273 // no pointer difference being made here.
1274 if (isMaybeZeroSizedType(ElTy))
1275 return -2; // dunno.
1277 // If they are really different, now that they are the same type, then we
1278 // found a difference!
1279 if (cast<ConstantInt>(C1)->getSExtValue() <
1280 cast<ConstantInt>(C2)->getSExtValue())
1286 /// evaluateFCmpRelation - This function determines if there is anything we can
1287 /// decide about the two constants provided. This doesn't need to handle simple
1288 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1289 /// If we can determine that the two constants have a particular relation to
1290 /// each other, we should return the corresponding FCmpInst predicate,
1291 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1292 /// ConstantFoldCompareInstruction.
1294 /// To simplify this code we canonicalize the relation so that the first
1295 /// operand is always the most "complex" of the two. We consider ConstantFP
1296 /// to be the simplest, and ConstantExprs to be the most complex.
1297 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1298 assert(V1->getType() == V2->getType() &&
1299 "Cannot compare values of different types!");
1301 // Handle degenerate case quickly
1302 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1304 if (!isa<ConstantExpr>(V1)) {
1305 if (!isa<ConstantExpr>(V2)) {
1306 // We distilled thisUse the standard constant folder for a few cases
1307 ConstantInt *R = nullptr;
1308 R = dyn_cast<ConstantInt>(
1309 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1310 if (R && !R->isZero())
1311 return FCmpInst::FCMP_OEQ;
1312 R = dyn_cast<ConstantInt>(
1313 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1314 if (R && !R->isZero())
1315 return FCmpInst::FCMP_OLT;
1316 R = dyn_cast<ConstantInt>(
1317 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1318 if (R && !R->isZero())
1319 return FCmpInst::FCMP_OGT;
1321 // Nothing more we can do
1322 return FCmpInst::BAD_FCMP_PREDICATE;
1325 // If the first operand is simple and second is ConstantExpr, swap operands.
1326 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1327 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1328 return FCmpInst::getSwappedPredicate(SwappedRelation);
1330 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1331 // constantexpr or a simple constant.
1332 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1333 switch (CE1->getOpcode()) {
1334 case Instruction::FPTrunc:
1335 case Instruction::FPExt:
1336 case Instruction::UIToFP:
1337 case Instruction::SIToFP:
1338 // We might be able to do something with these but we don't right now.
1344 // There are MANY other foldings that we could perform here. They will
1345 // probably be added on demand, as they seem needed.
1346 return FCmpInst::BAD_FCMP_PREDICATE;
1349 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
1350 const GlobalValue *GV2) {
1351 auto isLinkageUnsafeForEquality = [](const GlobalValue *GV) {
1352 return GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage();
1354 // Don't try to decide equality of aliases.
1355 if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
1356 if (!isLinkageUnsafeForEquality(GV1) && !isLinkageUnsafeForEquality(GV2))
1357 return ICmpInst::ICMP_NE;
1358 return ICmpInst::BAD_ICMP_PREDICATE;
1361 /// evaluateICmpRelation - This function determines if there is anything we can
1362 /// decide about the two constants provided. This doesn't need to handle simple
1363 /// things like integer comparisons, but should instead handle ConstantExprs
1364 /// and GlobalValues. If we can determine that the two constants have a
1365 /// particular relation to each other, we should return the corresponding ICmp
1366 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1368 /// To simplify this code we canonicalize the relation so that the first
1369 /// operand is always the most "complex" of the two. We consider simple
1370 /// constants (like ConstantInt) to be the simplest, followed by
1371 /// GlobalValues, followed by ConstantExpr's (the most complex).
1373 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1375 assert(V1->getType() == V2->getType() &&
1376 "Cannot compare different types of values!");
1377 if (V1 == V2) return ICmpInst::ICMP_EQ;
1379 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1380 !isa<BlockAddress>(V1)) {
1381 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1382 !isa<BlockAddress>(V2)) {
1383 // We distilled this down to a simple case, use the standard constant
1385 ConstantInt *R = nullptr;
1386 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1387 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1388 if (R && !R->isZero())
1390 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1391 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1392 if (R && !R->isZero())
1394 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1395 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1396 if (R && !R->isZero())
1399 // If we couldn't figure it out, bail.
1400 return ICmpInst::BAD_ICMP_PREDICATE;
1403 // If the first operand is simple, swap operands.
1404 ICmpInst::Predicate SwappedRelation =
1405 evaluateICmpRelation(V2, V1, isSigned);
1406 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1407 return ICmpInst::getSwappedPredicate(SwappedRelation);
1409 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1410 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1411 ICmpInst::Predicate SwappedRelation =
1412 evaluateICmpRelation(V2, V1, isSigned);
1413 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1414 return ICmpInst::getSwappedPredicate(SwappedRelation);
1415 return ICmpInst::BAD_ICMP_PREDICATE;
1418 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1419 // constant (which, since the types must match, means that it's a
1420 // ConstantPointerNull).
1421 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1422 return areGlobalsPotentiallyEqual(GV, GV2);
1423 } else if (isa<BlockAddress>(V2)) {
1424 return ICmpInst::ICMP_NE; // Globals never equal labels.
1426 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1427 // GlobalVals can never be null unless they have external weak linkage.
1428 // We don't try to evaluate aliases here.
1429 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1430 return ICmpInst::ICMP_NE;
1432 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1433 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1434 ICmpInst::Predicate SwappedRelation =
1435 evaluateICmpRelation(V2, V1, isSigned);
1436 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1437 return ICmpInst::getSwappedPredicate(SwappedRelation);
1438 return ICmpInst::BAD_ICMP_PREDICATE;
1441 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1442 // constant (which, since the types must match, means that it is a
1443 // ConstantPointerNull).
1444 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1445 // Block address in another function can't equal this one, but block
1446 // addresses in the current function might be the same if blocks are
1448 if (BA2->getFunction() != BA->getFunction())
1449 return ICmpInst::ICMP_NE;
1451 // Block addresses aren't null, don't equal the address of globals.
1452 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1453 "Canonicalization guarantee!");
1454 return ICmpInst::ICMP_NE;
1457 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1458 // constantexpr, a global, block address, or a simple constant.
1459 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1460 Constant *CE1Op0 = CE1->getOperand(0);
1462 switch (CE1->getOpcode()) {
1463 case Instruction::Trunc:
1464 case Instruction::FPTrunc:
1465 case Instruction::FPExt:
1466 case Instruction::FPToUI:
1467 case Instruction::FPToSI:
1468 break; // We can't evaluate floating point casts or truncations.
1470 case Instruction::UIToFP:
1471 case Instruction::SIToFP:
1472 case Instruction::BitCast:
1473 case Instruction::ZExt:
1474 case Instruction::SExt:
1475 // If the cast is not actually changing bits, and the second operand is a
1476 // null pointer, do the comparison with the pre-casted value.
1477 if (V2->isNullValue() &&
1478 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1479 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1480 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1481 return evaluateICmpRelation(CE1Op0,
1482 Constant::getNullValue(CE1Op0->getType()),
1487 case Instruction::GetElementPtr: {
1488 GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1489 // Ok, since this is a getelementptr, we know that the constant has a
1490 // pointer type. Check the various cases.
1491 if (isa<ConstantPointerNull>(V2)) {
1492 // If we are comparing a GEP to a null pointer, check to see if the base
1493 // of the GEP equals the null pointer.
1494 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1495 if (GV->hasExternalWeakLinkage())
1496 // Weak linkage GVals could be zero or not. We're comparing that
1497 // to null pointer so its greater-or-equal
1498 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1500 // If its not weak linkage, the GVal must have a non-zero address
1501 // so the result is greater-than
1502 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1503 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1504 // If we are indexing from a null pointer, check to see if we have any
1505 // non-zero indices.
1506 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1507 if (!CE1->getOperand(i)->isNullValue())
1508 // Offsetting from null, must not be equal.
1509 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1510 // Only zero indexes from null, must still be zero.
1511 return ICmpInst::ICMP_EQ;
1513 // Otherwise, we can't really say if the first operand is null or not.
1514 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1515 if (isa<ConstantPointerNull>(CE1Op0)) {
1516 if (GV2->hasExternalWeakLinkage())
1517 // Weak linkage GVals could be zero or not. We're comparing it to
1518 // a null pointer, so its less-or-equal
1519 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1521 // If its not weak linkage, the GVal must have a non-zero address
1522 // so the result is less-than
1523 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1524 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1526 // If this is a getelementptr of the same global, then it must be
1527 // different. Because the types must match, the getelementptr could
1528 // only have at most one index, and because we fold getelementptr's
1529 // with a single zero index, it must be nonzero.
1530 assert(CE1->getNumOperands() == 2 &&
1531 !CE1->getOperand(1)->isNullValue() &&
1532 "Surprising getelementptr!");
1533 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1535 if (CE1GEP->hasAllZeroIndices())
1536 return areGlobalsPotentiallyEqual(GV, GV2);
1537 return ICmpInst::BAD_ICMP_PREDICATE;
1541 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1542 Constant *CE2Op0 = CE2->getOperand(0);
1544 // There are MANY other foldings that we could perform here. They will
1545 // probably be added on demand, as they seem needed.
1546 switch (CE2->getOpcode()) {
1548 case Instruction::GetElementPtr:
1549 // By far the most common case to handle is when the base pointers are
1550 // obviously to the same global.
1551 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1552 // Don't know relative ordering, but check for inequality.
1553 if (CE1Op0 != CE2Op0) {
1554 GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
1555 if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1556 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1557 cast<GlobalValue>(CE2Op0));
1558 return ICmpInst::BAD_ICMP_PREDICATE;
1560 // Ok, we know that both getelementptr instructions are based on the
1561 // same global. From this, we can precisely determine the relative
1562 // ordering of the resultant pointers.
1565 // The logic below assumes that the result of the comparison
1566 // can be determined by finding the first index that differs.
1567 // This doesn't work if there is over-indexing in any
1568 // subsequent indices, so check for that case first.
1569 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1570 !CE2->isGEPWithNoNotionalOverIndexing())
1571 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1573 // Compare all of the operands the GEP's have in common.
1574 gep_type_iterator GTI = gep_type_begin(CE1);
1575 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1577 switch (IdxCompare(CE1->getOperand(i),
1578 CE2->getOperand(i), GTI.getIndexedType())) {
1579 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1580 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1581 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1584 // Ok, we ran out of things they have in common. If any leftovers
1585 // are non-zero then we have a difference, otherwise we are equal.
1586 for (; i < CE1->getNumOperands(); ++i)
1587 if (!CE1->getOperand(i)->isNullValue()) {
1588 if (isa<ConstantInt>(CE1->getOperand(i)))
1589 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1591 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1594 for (; i < CE2->getNumOperands(); ++i)
1595 if (!CE2->getOperand(i)->isNullValue()) {
1596 if (isa<ConstantInt>(CE2->getOperand(i)))
1597 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1599 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1601 return ICmpInst::ICMP_EQ;
1611 return ICmpInst::BAD_ICMP_PREDICATE;
1614 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1615 Constant *C1, Constant *C2) {
1617 if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1618 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1619 VT->getNumElements());
1621 ResultTy = Type::getInt1Ty(C1->getContext());
1623 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1624 if (pred == FCmpInst::FCMP_FALSE)
1625 return Constant::getNullValue(ResultTy);
1627 if (pred == FCmpInst::FCMP_TRUE)
1628 return Constant::getAllOnesValue(ResultTy);
1630 // Handle some degenerate cases first
1631 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1632 // For EQ and NE, we can always pick a value for the undef to make the
1633 // predicate pass or fail, so we can return undef.
1634 // Also, if both operands are undef, we can return undef.
1635 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1636 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1637 return UndefValue::get(ResultTy);
1638 // Otherwise, pick the same value as the non-undef operand, and fold
1639 // it to true or false.
1640 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1643 // icmp eq/ne(null,GV) -> false/true
1644 if (C1->isNullValue()) {
1645 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1646 // Don't try to evaluate aliases. External weak GV can be null.
1647 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1648 if (pred == ICmpInst::ICMP_EQ)
1649 return ConstantInt::getFalse(C1->getContext());
1650 else if (pred == ICmpInst::ICMP_NE)
1651 return ConstantInt::getTrue(C1->getContext());
1653 // icmp eq/ne(GV,null) -> false/true
1654 } else if (C2->isNullValue()) {
1655 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1656 // Don't try to evaluate aliases. External weak GV can be null.
1657 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1658 if (pred == ICmpInst::ICMP_EQ)
1659 return ConstantInt::getFalse(C1->getContext());
1660 else if (pred == ICmpInst::ICMP_NE)
1661 return ConstantInt::getTrue(C1->getContext());
1665 // If the comparison is a comparison between two i1's, simplify it.
1666 if (C1->getType()->isIntegerTy(1)) {
1668 case ICmpInst::ICMP_EQ:
1669 if (isa<ConstantInt>(C2))
1670 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1671 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1672 case ICmpInst::ICMP_NE:
1673 return ConstantExpr::getXor(C1, C2);
1679 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1680 APInt V1 = cast<ConstantInt>(C1)->getValue();
1681 APInt V2 = cast<ConstantInt>(C2)->getValue();
1683 default: llvm_unreachable("Invalid ICmp Predicate");
1684 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
1685 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
1686 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1687 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1688 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1689 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1690 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1691 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1692 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1693 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1695 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1696 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1697 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1698 APFloat::cmpResult R = C1V.compare(C2V);
1700 default: llvm_unreachable("Invalid FCmp Predicate");
1701 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1702 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
1703 case FCmpInst::FCMP_UNO:
1704 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1705 case FCmpInst::FCMP_ORD:
1706 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1707 case FCmpInst::FCMP_UEQ:
1708 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1709 R==APFloat::cmpEqual);
1710 case FCmpInst::FCMP_OEQ:
1711 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1712 case FCmpInst::FCMP_UNE:
1713 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1714 case FCmpInst::FCMP_ONE:
1715 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1716 R==APFloat::cmpGreaterThan);
1717 case FCmpInst::FCMP_ULT:
1718 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1719 R==APFloat::cmpLessThan);
1720 case FCmpInst::FCMP_OLT:
1721 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1722 case FCmpInst::FCMP_UGT:
1723 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1724 R==APFloat::cmpGreaterThan);
1725 case FCmpInst::FCMP_OGT:
1726 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1727 case FCmpInst::FCMP_ULE:
1728 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1729 case FCmpInst::FCMP_OLE:
1730 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1731 R==APFloat::cmpEqual);
1732 case FCmpInst::FCMP_UGE:
1733 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1734 case FCmpInst::FCMP_OGE:
1735 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1736 R==APFloat::cmpEqual);
1738 } else if (C1->getType()->isVectorTy()) {
1739 // If we can constant fold the comparison of each element, constant fold
1740 // the whole vector comparison.
1741 SmallVector<Constant*, 4> ResElts;
1742 Type *Ty = IntegerType::get(C1->getContext(), 32);
1743 // Compare the elements, producing an i1 result or constant expr.
1744 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1746 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1748 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1750 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1753 return ConstantVector::get(ResElts);
1756 if (C1->getType()->isFloatingPointTy()) {
1757 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1758 switch (evaluateFCmpRelation(C1, C2)) {
1759 default: llvm_unreachable("Unknown relation!");
1760 case FCmpInst::FCMP_UNO:
1761 case FCmpInst::FCMP_ORD:
1762 case FCmpInst::FCMP_UEQ:
1763 case FCmpInst::FCMP_UNE:
1764 case FCmpInst::FCMP_ULT:
1765 case FCmpInst::FCMP_UGT:
1766 case FCmpInst::FCMP_ULE:
1767 case FCmpInst::FCMP_UGE:
1768 case FCmpInst::FCMP_TRUE:
1769 case FCmpInst::FCMP_FALSE:
1770 case FCmpInst::BAD_FCMP_PREDICATE:
1771 break; // Couldn't determine anything about these constants.
1772 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1773 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1774 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1775 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1777 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1778 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1779 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1780 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1782 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1783 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1784 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1785 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1787 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1788 // We can only partially decide this relation.
1789 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1791 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1794 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1795 // We can only partially decide this relation.
1796 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1798 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1801 case FCmpInst::FCMP_ONE: // We know that C1 != C2
1802 // We can only partially decide this relation.
1803 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1805 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1810 // If we evaluated the result, return it now.
1812 return ConstantInt::get(ResultTy, Result);
1815 // Evaluate the relation between the two constants, per the predicate.
1816 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1817 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1818 default: llvm_unreachable("Unknown relational!");
1819 case ICmpInst::BAD_ICMP_PREDICATE:
1820 break; // Couldn't determine anything about these constants.
1821 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1822 // If we know the constants are equal, we can decide the result of this
1823 // computation precisely.
1824 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1826 case ICmpInst::ICMP_ULT:
1828 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1830 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1834 case ICmpInst::ICMP_SLT:
1836 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1838 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1842 case ICmpInst::ICMP_UGT:
1844 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1846 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1850 case ICmpInst::ICMP_SGT:
1852 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1854 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1858 case ICmpInst::ICMP_ULE:
1859 if (pred == ICmpInst::ICMP_UGT) Result = 0;
1860 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1862 case ICmpInst::ICMP_SLE:
1863 if (pred == ICmpInst::ICMP_SGT) Result = 0;
1864 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1866 case ICmpInst::ICMP_UGE:
1867 if (pred == ICmpInst::ICMP_ULT) Result = 0;
1868 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1870 case ICmpInst::ICMP_SGE:
1871 if (pred == ICmpInst::ICMP_SLT) Result = 0;
1872 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1874 case ICmpInst::ICMP_NE:
1875 if (pred == ICmpInst::ICMP_EQ) Result = 0;
1876 if (pred == ICmpInst::ICMP_NE) Result = 1;
1880 // If we evaluated the result, return it now.
1882 return ConstantInt::get(ResultTy, Result);
1884 // If the right hand side is a bitcast, try using its inverse to simplify
1885 // it by moving it to the left hand side. We can't do this if it would turn
1886 // a vector compare into a scalar compare or visa versa.
1887 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1888 Constant *CE2Op0 = CE2->getOperand(0);
1889 if (CE2->getOpcode() == Instruction::BitCast &&
1890 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1891 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1892 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1896 // If the left hand side is an extension, try eliminating it.
1897 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1898 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1899 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1900 Constant *CE1Op0 = CE1->getOperand(0);
1901 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1902 if (CE1Inverse == CE1Op0) {
1903 // Check whether we can safely truncate the right hand side.
1904 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1905 if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
1906 C2->getType()) == C2)
1907 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1912 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1913 (C1->isNullValue() && !C2->isNullValue())) {
1914 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1915 // other way if possible.
1916 // Also, if C1 is null and C2 isn't, flip them around.
1917 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1918 return ConstantExpr::getICmp(pred, C2, C1);
1924 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1926 template<typename IndexTy>
1927 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1928 // No indices means nothing that could be out of bounds.
1929 if (Idxs.empty()) return true;
1931 // If the first index is zero, it's in bounds.
1932 if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1934 // If the first index is one and all the rest are zero, it's in bounds,
1935 // by the one-past-the-end rule.
1936 if (!cast<ConstantInt>(Idxs[0])->isOne())
1938 for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1939 if (!cast<Constant>(Idxs[i])->isNullValue())
1944 /// \brief Test whether a given ConstantInt is in-range for a SequentialType.
1945 static bool isIndexInRangeOfSequentialType(const SequentialType *STy,
1946 const ConstantInt *CI) {
1947 if (const PointerType *PTy = dyn_cast<PointerType>(STy))
1948 // Only handle pointers to sized types, not pointers to functions.
1949 return PTy->getElementType()->isSized();
1951 uint64_t NumElements = 0;
1952 // Determine the number of elements in our sequential type.
1953 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
1954 NumElements = ATy->getNumElements();
1955 else if (const VectorType *VTy = dyn_cast<VectorType>(STy))
1956 NumElements = VTy->getNumElements();
1958 assert((isa<ArrayType>(STy) || NumElements > 0) &&
1959 "didn't expect non-array type to have zero elements!");
1961 // We cannot bounds check the index if it doesn't fit in an int64_t.
1962 if (CI->getValue().getActiveBits() > 64)
1965 // A negative index or an index past the end of our sequential type is
1966 // considered out-of-range.
1967 int64_t IndexVal = CI->getSExtValue();
1968 if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
1971 // Otherwise, it is in-range.
1975 template<typename IndexTy>
1976 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1978 ArrayRef<IndexTy> Idxs) {
1979 if (Idxs.empty()) return C;
1980 Constant *Idx0 = cast<Constant>(Idxs[0]);
1981 if ((Idxs.size() == 1 && Idx0->isNullValue()))
1984 if (isa<UndefValue>(C)) {
1985 PointerType *Ptr = cast<PointerType>(C->getType());
1986 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1987 assert(Ty && "Invalid indices for GEP!");
1988 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1991 if (C->isNullValue()) {
1993 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1994 if (!cast<Constant>(Idxs[i])->isNullValue()) {
1999 PointerType *Ptr = cast<PointerType>(C->getType());
2000 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
2001 assert(Ty && "Invalid indices for GEP!");
2002 return ConstantPointerNull::get(PointerType::get(Ty,
2003 Ptr->getAddressSpace()));
2007 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2008 // Combine Indices - If the source pointer to this getelementptr instruction
2009 // is a getelementptr instruction, combine the indices of the two
2010 // getelementptr instructions into a single instruction.
2012 if (CE->getOpcode() == Instruction::GetElementPtr) {
2013 Type *LastTy = nullptr;
2014 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2018 // We cannot combine indices if doing so would take us outside of an
2019 // array or vector. Doing otherwise could trick us if we evaluated such a
2020 // GEP as part of a load.
2022 // e.g. Consider if the original GEP was:
2023 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2024 // i32 0, i32 0, i64 0)
2026 // If we then tried to offset it by '8' to get to the third element,
2027 // an i8, we should *not* get:
2028 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2029 // i32 0, i32 0, i64 8)
2031 // This GEP tries to index array element '8 which runs out-of-bounds.
2032 // Subsequent evaluation would get confused and produce erroneous results.
2034 // The following prohibits such a GEP from being formed by checking to see
2035 // if the index is in-range with respect to an array or vector.
2036 bool PerformFold = false;
2037 if (Idx0->isNullValue())
2039 else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy))
2040 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
2041 PerformFold = isIndexInRangeOfSequentialType(STy, CI);
2044 SmallVector<Value*, 16> NewIndices;
2045 NewIndices.reserve(Idxs.size() + CE->getNumOperands());
2046 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2047 NewIndices.push_back(CE->getOperand(i));
2049 // Add the last index of the source with the first index of the new GEP.
2050 // Make sure to handle the case when they are actually different types.
2051 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2052 // Otherwise it must be an array.
2053 if (!Idx0->isNullValue()) {
2054 Type *IdxTy = Combined->getType();
2055 if (IdxTy != Idx0->getType()) {
2056 Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2057 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2058 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
2059 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2062 ConstantExpr::get(Instruction::Add, Idx0, Combined);
2066 NewIndices.push_back(Combined);
2067 NewIndices.append(Idxs.begin() + 1, Idxs.end());
2069 ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
2071 cast<GEPOperator>(CE)->isInBounds());
2075 // Attempt to fold casts to the same type away. For example, folding:
2077 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2081 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2083 // Don't fold if the cast is changing address spaces.
2084 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
2085 PointerType *SrcPtrTy =
2086 dyn_cast<PointerType>(CE->getOperand(0)->getType());
2087 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
2088 if (SrcPtrTy && DstPtrTy) {
2089 ArrayType *SrcArrayTy =
2090 dyn_cast<ArrayType>(SrcPtrTy->getElementType());
2091 ArrayType *DstArrayTy =
2092 dyn_cast<ArrayType>(DstPtrTy->getElementType());
2093 if (SrcArrayTy && DstArrayTy
2094 && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
2095 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2096 return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
2102 // Check to see if any array indices are not within the corresponding
2103 // notional array or vector bounds. If so, try to determine if they can be
2104 // factored out into preceding dimensions.
2105 bool Unknown = false;
2106 SmallVector<Constant *, 8> NewIdxs;
2107 Type *Ty = C->getType();
2108 Type *Prev = nullptr;
2109 for (unsigned i = 0, e = Idxs.size(); i != e;
2110 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2112 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty))
2113 if (CI->getSExtValue() > 0 &&
2114 !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) {
2115 if (isa<SequentialType>(Prev)) {
2116 // It's out of range, but we can factor it into the prior
2118 NewIdxs.resize(Idxs.size());
2119 uint64_t NumElements = 0;
2120 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2121 NumElements = ATy->getNumElements();
2123 NumElements = cast<VectorType>(Ty)->getNumElements();
2125 ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements);
2126 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2128 Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2129 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2131 // Before adding, extend both operands to i64 to avoid
2132 // overflow trouble.
2133 if (!PrevIdx->getType()->isIntegerTy(64))
2134 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2135 Type::getInt64Ty(Div->getContext()));
2136 if (!Div->getType()->isIntegerTy(64))
2137 Div = ConstantExpr::getSExt(Div,
2138 Type::getInt64Ty(Div->getContext()));
2140 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2142 // It's out of range, but the prior dimension is a struct
2143 // so we can't do anything about it.
2148 // We don't know if it's in range or not.
2153 // If we did any factoring, start over with the adjusted indices.
2154 if (!NewIdxs.empty()) {
2155 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2156 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2157 return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2160 // If all indices are known integers and normalized, we can do a simple
2161 // check for the "inbounds" property.
2162 if (!Unknown && !inBounds)
2163 if (auto *GV = dyn_cast<GlobalVariable>(C))
2164 if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
2165 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2170 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2172 ArrayRef<Constant *> Idxs) {
2173 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2176 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2178 ArrayRef<Value *> Idxs) {
2179 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);