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/LLVMContext.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
37 //===----------------------------------------------------------------------===//
38 // ConstantFold*Instruction Implementations
39 //===----------------------------------------------------------------------===//
41 /// BitCastConstantVector - Convert the specified ConstantVector node to the
42 /// specified vector type. At this point, we know that the elements of the
43 /// input vector constant are all simple integer or FP values.
44 static Constant *BitCastConstantVector(LLVMContext &Context, ConstantVector *CV,
45 const VectorType *DstTy) {
46 // If this cast changes element count then we can't handle it here:
47 // doing so requires endianness information. This should be handled by
48 // Analysis/ConstantFolding.cpp
49 unsigned NumElts = DstTy->getNumElements();
50 if (NumElts != CV->getNumOperands())
53 // Check to verify that all elements of the input are simple.
54 for (unsigned i = 0; i != NumElts; ++i) {
55 if (!isa<ConstantInt>(CV->getOperand(i)) &&
56 !isa<ConstantFP>(CV->getOperand(i)))
60 // Bitcast each element now.
61 std::vector<Constant*> Result;
62 const Type *DstEltTy = DstTy->getElementType();
63 for (unsigned i = 0; i != NumElts; ++i)
64 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i),
66 return ConstantVector::get(Result);
69 /// This function determines which opcode to use to fold two constant cast
70 /// expressions together. It uses CastInst::isEliminableCastPair to determine
71 /// the opcode. Consequently its just a wrapper around that function.
72 /// @brief Determine if it is valid to fold a cast of a cast
75 unsigned opc, ///< opcode of the second cast constant expression
76 ConstantExpr *Op, ///< the first cast constant expression
77 const Type *DstTy ///< desintation type of the first cast
79 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
80 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
81 assert(CastInst::isCast(opc) && "Invalid cast opcode");
83 // The the types and opcodes for the two Cast constant expressions
84 const Type *SrcTy = Op->getOperand(0)->getType();
85 const Type *MidTy = Op->getType();
86 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
87 Instruction::CastOps secondOp = Instruction::CastOps(opc);
89 // Let CastInst::isEliminableCastPair do the heavy lifting.
90 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
91 Type::getInt64Ty(DstTy->getContext()));
94 static Constant *FoldBitCast(LLVMContext &Context,
95 Constant *V, const Type *DestTy) {
96 const Type *SrcTy = V->getType();
98 return V; // no-op cast
100 // Check to see if we are casting a pointer to an aggregate to a pointer to
101 // the first element. If so, return the appropriate GEP instruction.
102 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
103 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
104 if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
105 SmallVector<Value*, 8> IdxList;
106 Value *Zero = Constant::getNullValue(Type::getInt32Ty(Context));
107 IdxList.push_back(Zero);
108 const Type *ElTy = PTy->getElementType();
109 while (ElTy != DPTy->getElementType()) {
110 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
111 if (STy->getNumElements() == 0) break;
112 ElTy = STy->getElementType(0);
113 IdxList.push_back(Zero);
114 } else if (const SequentialType *STy =
115 dyn_cast<SequentialType>(ElTy)) {
116 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
117 ElTy = STy->getElementType();
118 IdxList.push_back(Zero);
124 if (ElTy == DPTy->getElementType())
125 // This GEP is inbounds because all indices are zero.
126 return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
130 // Handle casts from one vector constant to another. We know that the src
131 // and dest type have the same size (otherwise its an illegal cast).
132 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
133 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
134 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
135 "Not cast between same sized vectors!");
137 // First, check for null. Undef is already handled.
138 if (isa<ConstantAggregateZero>(V))
139 return Constant::getNullValue(DestTy);
141 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
142 return BitCastConstantVector(Context, CV, DestPTy);
145 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
146 // This allows for other simplifications (although some of them
147 // can only be handled by Analysis/ConstantFolding.cpp).
148 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
149 return ConstantExpr::getBitCast(
150 ConstantVector::get(&V, 1), DestPTy);
153 // Finally, implement bitcast folding now. The code below doesn't handle
155 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
156 return ConstantPointerNull::get(cast<PointerType>(DestTy));
158 // Handle integral constant input.
159 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
160 if (DestTy->isInteger())
161 // Integral -> Integral. This is a no-op because the bit widths must
162 // be the same. Consequently, we just fold to V.
165 if (DestTy->isFloatingPoint())
166 return ConstantFP::get(Context, APFloat(CI->getValue(),
167 DestTy != Type::getPPC_FP128Ty(Context)));
169 // Otherwise, can't fold this (vector?)
173 // Handle ConstantFP input.
174 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
176 return ConstantInt::get(Context, FP->getValueAPF().bitcastToAPInt());
182 /// ExtractConstantBytes - V is an integer constant which only has a subset of
183 /// its bytes used. The bytes used are indicated by ByteStart (which is the
184 /// first byte used, counting from the least significant byte) and ByteSize,
185 /// which is the number of bytes used.
187 /// This function analyzes the specified constant to see if the specified byte
188 /// range can be returned as a simplified constant. If so, the constant is
189 /// returned, otherwise null is returned.
191 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
193 assert(isa<IntegerType>(C->getType()) &&
194 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
195 "Non-byte sized integer input");
196 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
197 assert(ByteSize && "Must be accessing some piece");
198 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
199 assert(ByteSize != CSize && "Should not extract everything");
201 // Constant Integers are simple.
202 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
203 APInt V = CI->getValue();
205 V = V.lshr(ByteStart*8);
207 return ConstantInt::get(CI->getContext(), V);
210 // In the input is a constant expr, we might be able to recursively simplify.
211 // If not, we definitely can't do anything.
212 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
213 if (CE == 0) return 0;
215 switch (CE->getOpcode()) {
217 case Instruction::Or: {
218 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
223 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
224 if (RHSC->isAllOnesValue())
227 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
230 return ConstantExpr::getOr(LHS, RHS);
232 case Instruction::And: {
233 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
238 if (RHS->isNullValue())
241 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
244 return ConstantExpr::getAnd(LHS, RHS);
246 case Instruction::LShr: {
247 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
250 unsigned ShAmt = Amt->getZExtValue();
251 // Cannot analyze non-byte shifts.
252 if ((ShAmt & 7) != 0)
256 // If the extract is known to be all zeros, return zero.
257 if (ByteStart >= CSize-ShAmt)
258 return Constant::getNullValue(IntegerType::get(CE->getContext(),
260 // If the extract is known to be fully in the input, extract it.
261 if (ByteStart+ByteSize+ShAmt <= CSize)
262 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
264 // TODO: Handle the 'partially zero' case.
268 case Instruction::Shl: {
269 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
272 unsigned ShAmt = Amt->getZExtValue();
273 // Cannot analyze non-byte shifts.
274 if ((ShAmt & 7) != 0)
278 // If the extract is known to be all zeros, return zero.
279 if (ByteStart+ByteSize <= ShAmt)
280 return Constant::getNullValue(IntegerType::get(CE->getContext(),
282 // If the extract is known to be fully in the input, extract it.
283 if (ByteStart >= ShAmt)
284 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
286 // TODO: Handle the 'partially zero' case.
290 case Instruction::ZExt: {
291 unsigned SrcBitSize =
292 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
294 // If extracting something that is completely zero, return 0.
295 if (ByteStart*8 >= SrcBitSize)
296 return Constant::getNullValue(IntegerType::get(CE->getContext(),
299 // If exactly extracting the input, return it.
300 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
301 return CE->getOperand(0);
303 // If extracting something completely in the input, if if the input is a
304 // multiple of 8 bits, recurse.
305 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
306 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
308 // Otherwise, if extracting a subset of the input, which is not multiple of
309 // 8 bits, do a shift and trunc to get the bits.
310 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
311 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
312 Constant *Res = CE->getOperand(0);
314 Res = ConstantExpr::getLShr(Res,
315 ConstantInt::get(Res->getType(), ByteStart*8));
316 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
320 // TODO: Handle the 'partially zero' case.
326 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
327 /// on Ty, with any known factors factored out. If Folded is false,
328 /// return null if no factoring was possible, to avoid endlessly
329 /// bouncing an unfoldable expression back into the top-level folder.
331 static Constant *getFoldedSizeOf(const Type *Ty, const Type *DestTy,
333 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
334 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
335 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
336 return ConstantExpr::getNUWMul(E, N);
338 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
339 Constant *N = ConstantInt::get(DestTy, VTy->getNumElements());
340 Constant *E = getFoldedSizeOf(VTy->getElementType(), DestTy, true);
341 return ConstantExpr::getNUWMul(E, N);
343 if (const StructType *STy = dyn_cast<StructType>(Ty))
344 if (!STy->isPacked()) {
345 unsigned NumElems = STy->getNumElements();
346 // An empty struct has size zero.
348 return ConstantExpr::getNullValue(DestTy);
349 // Check for a struct with all members having the same type.
350 const Type *MemberTy = STy->getElementType(0);
352 for (unsigned i = 1; i != NumElems; ++i)
353 if (MemberTy != STy->getElementType(i)) {
358 Constant *N = ConstantInt::get(DestTy, NumElems);
359 Constant *E = getFoldedSizeOf(MemberTy, DestTy, true);
360 return ConstantExpr::getNUWMul(E, N);
364 // If there's no interesting folding happening, bail so that we don't create
365 // a constant that looks like it needs folding but really doesn't.
369 // Base case: Get a regular sizeof expression.
370 Constant *C = ConstantExpr::getSizeOf(Ty);
371 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
377 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
378 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
379 /// return null if no factoring was possible, to avoid endlessly
380 /// bouncing an unfoldable expression back into the top-level folder.
382 static Constant *getFoldedOffsetOf(const Type *Ty, Constant *FieldNo,
385 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
386 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
389 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
390 return ConstantExpr::getNUWMul(E, N);
392 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
393 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
396 Constant *E = getFoldedSizeOf(VTy->getElementType(), DestTy, true);
397 return ConstantExpr::getNUWMul(E, N);
399 if (const StructType *STy = dyn_cast<StructType>(Ty))
400 if (!STy->isPacked()) {
401 unsigned NumElems = STy->getNumElements();
402 // An empty struct has no members.
405 // Check for a struct with all members having the same type.
406 const Type *MemberTy = STy->getElementType(0);
408 for (unsigned i = 1; i != NumElems; ++i)
409 if (MemberTy != STy->getElementType(i)) {
414 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
419 Constant *E = getFoldedSizeOf(MemberTy, DestTy, true);
420 return ConstantExpr::getNUWMul(E, N);
424 // If there's no interesting folding happening, bail so that we don't create
425 // a constant that looks like it needs folding but really doesn't.
429 // Base case: Get a regular offsetof expression.
430 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
431 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
437 Constant *llvm::ConstantFoldCastInstruction(LLVMContext &Context,
438 unsigned opc, Constant *V,
439 const Type *DestTy) {
440 if (isa<UndefValue>(V)) {
441 // zext(undef) = 0, because the top bits will be zero.
442 // sext(undef) = 0, because the top bits will all be the same.
443 // [us]itofp(undef) = 0, because the result value is bounded.
444 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
445 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
446 return Constant::getNullValue(DestTy);
447 return UndefValue::get(DestTy);
449 // No compile-time operations on this type yet.
450 if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
453 // If the cast operand is a constant expression, there's a few things we can
454 // do to try to simplify it.
455 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
457 // Try hard to fold cast of cast because they are often eliminable.
458 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
459 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
460 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
461 // If all of the indexes in the GEP are null values, there is no pointer
462 // adjustment going on. We might as well cast the source pointer.
463 bool isAllNull = true;
464 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
465 if (!CE->getOperand(i)->isNullValue()) {
470 // This is casting one pointer type to another, always BitCast
471 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
475 // If the cast operand is a constant vector, perform the cast by
476 // operating on each element. In the cast of bitcasts, the element
477 // count may be mismatched; don't attempt to handle that here.
478 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
479 if (isa<VectorType>(DestTy) &&
480 cast<VectorType>(DestTy)->getNumElements() ==
481 CV->getType()->getNumElements()) {
482 std::vector<Constant*> res;
483 const VectorType *DestVecTy = cast<VectorType>(DestTy);
484 const Type *DstEltTy = DestVecTy->getElementType();
485 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
486 res.push_back(ConstantExpr::getCast(opc,
487 CV->getOperand(i), DstEltTy));
488 return ConstantVector::get(DestVecTy, res);
491 // We actually have to do a cast now. Perform the cast according to the
495 llvm_unreachable("Failed to cast constant expression");
496 case Instruction::FPTrunc:
497 case Instruction::FPExt:
498 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
500 APFloat Val = FPC->getValueAPF();
501 Val.convert(DestTy->isFloatTy() ? APFloat::IEEEsingle :
502 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
503 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
504 DestTy->isFP128Ty() ? APFloat::IEEEquad :
506 APFloat::rmNearestTiesToEven, &ignored);
507 return ConstantFP::get(Context, Val);
509 return 0; // Can't fold.
510 case Instruction::FPToUI:
511 case Instruction::FPToSI:
512 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
513 const APFloat &V = FPC->getValueAPF();
516 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
517 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
518 APFloat::rmTowardZero, &ignored);
519 APInt Val(DestBitWidth, 2, x);
520 return ConstantInt::get(Context, Val);
522 return 0; // Can't fold.
523 case Instruction::IntToPtr: //always treated as unsigned
524 if (V->isNullValue()) // Is it an integral null value?
525 return ConstantPointerNull::get(cast<PointerType>(DestTy));
526 return 0; // Other pointer types cannot be casted
527 case Instruction::PtrToInt: // always treated as unsigned
528 // Is it a null pointer value?
529 if (V->isNullValue())
530 return ConstantInt::get(DestTy, 0);
531 // If this is a sizeof-like expression, pull out multiplications by
532 // known factors to expose them to subsequent folding. If it's an
533 // alignof-like expression, factor out known factors.
534 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
535 if (CE->getOpcode() == Instruction::GetElementPtr &&
536 CE->getOperand(0)->isNullValue()) {
538 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
539 if (CE->getNumOperands() == 2) {
540 // Handle a sizeof-like expression.
541 Constant *Idx = CE->getOperand(1);
542 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
543 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
544 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
547 return ConstantExpr::getMul(C, Idx);
549 } else if (CE->getNumOperands() == 3 &&
550 CE->getOperand(1)->isNullValue()) {
551 // Handle an alignof-like expression.
552 if (const StructType *STy = dyn_cast<StructType>(Ty))
553 if (!STy->isPacked()) {
554 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
556 STy->getNumElements() == 2 &&
557 STy->getElementType(0)->isInteger(1)) {
558 // The alignment of an array is equal to the alignment of the
559 // array element. Note that this is not always true for vectors.
560 if (const ArrayType *ATy =
561 dyn_cast<ArrayType>(STy->getElementType(1))) {
562 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
563 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
569 // Packed structs always have an alignment of 1.
570 if (const StructType *InnerSTy =
571 dyn_cast<StructType>(STy->getElementType(1)))
572 if (InnerSTy->isPacked())
573 return ConstantInt::get(DestTy, 1);
576 // Handle an offsetof-like expression.
577 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)){
578 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
584 // Other pointer types cannot be casted
586 case Instruction::UIToFP:
587 case Instruction::SIToFP:
588 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
589 APInt api = CI->getValue();
590 const uint64_t zero[] = {0, 0};
591 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
593 (void)apf.convertFromAPInt(api,
594 opc==Instruction::SIToFP,
595 APFloat::rmNearestTiesToEven);
596 return ConstantFP::get(Context, apf);
599 case Instruction::ZExt:
600 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
601 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
602 APInt Result(CI->getValue());
603 Result.zext(BitWidth);
604 return ConstantInt::get(Context, Result);
607 case Instruction::SExt:
608 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
609 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
610 APInt Result(CI->getValue());
611 Result.sext(BitWidth);
612 return ConstantInt::get(Context, Result);
615 case Instruction::Trunc: {
616 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
617 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
618 APInt Result(CI->getValue());
619 Result.trunc(DestBitWidth);
620 return ConstantInt::get(Context, Result);
623 // The input must be a constantexpr. See if we can simplify this based on
624 // the bytes we are demanding. Only do this if the source and dest are an
625 // even multiple of a byte.
626 if ((DestBitWidth & 7) == 0 &&
627 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
628 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
633 case Instruction::BitCast:
634 return FoldBitCast(Context, V, DestTy);
638 Constant *llvm::ConstantFoldSelectInstruction(LLVMContext&,
640 Constant *V1, Constant *V2) {
641 if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
642 return CB->getZExtValue() ? V1 : V2;
644 if (isa<UndefValue>(V1)) return V2;
645 if (isa<UndefValue>(V2)) return V1;
646 if (isa<UndefValue>(Cond)) return V1;
647 if (V1 == V2) return V1;
651 Constant *llvm::ConstantFoldExtractElementInstruction(LLVMContext &Context,
654 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
655 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
656 if (Val->isNullValue()) // ee(zero, x) -> zero
657 return Constant::getNullValue(
658 cast<VectorType>(Val->getType())->getElementType());
660 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
661 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
662 return CVal->getOperand(CIdx->getZExtValue());
663 } else if (isa<UndefValue>(Idx)) {
664 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
665 return CVal->getOperand(0);
671 Constant *llvm::ConstantFoldInsertElementInstruction(LLVMContext &Context,
675 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
677 APInt idxVal = CIdx->getValue();
678 if (isa<UndefValue>(Val)) {
679 // Insertion of scalar constant into vector undef
680 // Optimize away insertion of undef
681 if (isa<UndefValue>(Elt))
683 // Otherwise break the aggregate undef into multiple undefs and do
686 cast<VectorType>(Val->getType())->getNumElements();
687 std::vector<Constant*> Ops;
689 for (unsigned i = 0; i < numOps; ++i) {
691 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
694 return ConstantVector::get(Ops);
696 if (isa<ConstantAggregateZero>(Val)) {
697 // Insertion of scalar constant into vector aggregate zero
698 // Optimize away insertion of zero
699 if (Elt->isNullValue())
701 // Otherwise break the aggregate zero into multiple zeros and do
704 cast<VectorType>(Val->getType())->getNumElements();
705 std::vector<Constant*> Ops;
707 for (unsigned i = 0; i < numOps; ++i) {
709 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
712 return ConstantVector::get(Ops);
714 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
715 // Insertion of scalar constant into vector constant
716 std::vector<Constant*> Ops;
717 Ops.reserve(CVal->getNumOperands());
718 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
720 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
723 return ConstantVector::get(Ops);
729 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
730 /// return the specified element value. Otherwise return null.
731 static Constant *GetVectorElement(LLVMContext &Context, Constant *C,
733 if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
734 return CV->getOperand(EltNo);
736 const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
737 if (isa<ConstantAggregateZero>(C))
738 return Constant::getNullValue(EltTy);
739 if (isa<UndefValue>(C))
740 return UndefValue::get(EltTy);
744 Constant *llvm::ConstantFoldShuffleVectorInstruction(LLVMContext &Context,
748 // Undefined shuffle mask -> undefined value.
749 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
751 unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
752 unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
753 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
755 // Loop over the shuffle mask, evaluating each element.
756 SmallVector<Constant*, 32> Result;
757 for (unsigned i = 0; i != MaskNumElts; ++i) {
758 Constant *InElt = GetVectorElement(Context, Mask, i);
759 if (InElt == 0) return 0;
761 if (isa<UndefValue>(InElt))
762 InElt = UndefValue::get(EltTy);
763 else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
764 unsigned Elt = CI->getZExtValue();
765 if (Elt >= SrcNumElts*2)
766 InElt = UndefValue::get(EltTy);
767 else if (Elt >= SrcNumElts)
768 InElt = GetVectorElement(Context, V2, Elt - SrcNumElts);
770 InElt = GetVectorElement(Context, V1, Elt);
771 if (InElt == 0) return 0;
776 Result.push_back(InElt);
779 return ConstantVector::get(&Result[0], Result.size());
782 Constant *llvm::ConstantFoldExtractValueInstruction(LLVMContext &Context,
784 const unsigned *Idxs,
786 // Base case: no indices, so return the entire value.
790 if (isa<UndefValue>(Agg)) // ev(undef, x) -> undef
791 return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
795 if (isa<ConstantAggregateZero>(Agg)) // ev(0, x) -> 0
797 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
801 // Otherwise recurse.
802 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg))
803 return ConstantFoldExtractValueInstruction(Context, CS->getOperand(*Idxs),
806 if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg))
807 return ConstantFoldExtractValueInstruction(Context, CA->getOperand(*Idxs),
809 ConstantVector *CV = cast<ConstantVector>(Agg);
810 return ConstantFoldExtractValueInstruction(Context, CV->getOperand(*Idxs),
814 Constant *llvm::ConstantFoldInsertValueInstruction(LLVMContext &Context,
817 const unsigned *Idxs,
819 // Base case: no indices, so replace the entire value.
823 if (isa<UndefValue>(Agg)) {
824 // Insertion of constant into aggregate undef
825 // Optimize away insertion of undef.
826 if (isa<UndefValue>(Val))
829 // Otherwise break the aggregate undef into multiple undefs and do
831 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
833 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
834 numOps = AR->getNumElements();
836 numOps = cast<StructType>(AggTy)->getNumElements();
838 std::vector<Constant*> Ops(numOps);
839 for (unsigned i = 0; i < numOps; ++i) {
840 const Type *MemberTy = AggTy->getTypeAtIndex(i);
843 ConstantFoldInsertValueInstruction(Context, UndefValue::get(MemberTy),
844 Val, Idxs+1, NumIdx-1) :
845 UndefValue::get(MemberTy);
849 if (const StructType* ST = dyn_cast<StructType>(AggTy))
850 return ConstantStruct::get(Context, Ops, ST->isPacked());
851 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
854 if (isa<ConstantAggregateZero>(Agg)) {
855 // Insertion of constant into aggregate zero
856 // Optimize away insertion of zero.
857 if (Val->isNullValue())
860 // Otherwise break the aggregate zero into multiple zeros and do
862 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
864 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
865 numOps = AR->getNumElements();
867 numOps = cast<StructType>(AggTy)->getNumElements();
869 std::vector<Constant*> Ops(numOps);
870 for (unsigned i = 0; i < numOps; ++i) {
871 const Type *MemberTy = AggTy->getTypeAtIndex(i);
874 ConstantFoldInsertValueInstruction(Context,
875 Constant::getNullValue(MemberTy),
876 Val, Idxs+1, NumIdx-1) :
877 Constant::getNullValue(MemberTy);
881 if (const StructType* ST = dyn_cast<StructType>(AggTy))
882 return ConstantStruct::get(Context, Ops, ST->isPacked());
883 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
886 if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
887 // Insertion of constant into aggregate constant.
888 std::vector<Constant*> Ops(Agg->getNumOperands());
889 for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
890 Constant *Op = cast<Constant>(Agg->getOperand(i));
892 Op = ConstantFoldInsertValueInstruction(Context, Op,
893 Val, Idxs+1, NumIdx-1);
897 if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
898 return ConstantStruct::get(Context, Ops, ST->isPacked());
899 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
906 Constant *llvm::ConstantFoldBinaryInstruction(LLVMContext &Context,
908 Constant *C1, Constant *C2) {
909 // No compile-time operations on this type yet.
910 if (C1->getType()->isPPC_FP128Ty())
913 // Handle UndefValue up front.
914 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
916 case Instruction::Xor:
917 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
918 // Handle undef ^ undef -> 0 special case. This is a common
920 return Constant::getNullValue(C1->getType());
922 case Instruction::Add:
923 case Instruction::Sub:
924 return UndefValue::get(C1->getType());
925 case Instruction::Mul:
926 case Instruction::And:
927 return Constant::getNullValue(C1->getType());
928 case Instruction::UDiv:
929 case Instruction::SDiv:
930 case Instruction::URem:
931 case Instruction::SRem:
932 if (!isa<UndefValue>(C2)) // undef / X -> 0
933 return Constant::getNullValue(C1->getType());
934 return C2; // X / undef -> undef
935 case Instruction::Or: // X | undef -> -1
936 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
937 return Constant::getAllOnesValue(PTy);
938 return Constant::getAllOnesValue(C1->getType());
939 case Instruction::LShr:
940 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
941 return C1; // undef lshr undef -> undef
942 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
944 case Instruction::AShr:
945 if (!isa<UndefValue>(C2))
946 return C1; // undef ashr X --> undef
947 else if (isa<UndefValue>(C1))
948 return C1; // undef ashr undef -> undef
950 return C1; // X ashr undef --> X
951 case Instruction::Shl:
952 // undef << X -> 0 or X << undef -> 0
953 return Constant::getNullValue(C1->getType());
957 // Handle simplifications when the RHS is a constant int.
958 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
960 case Instruction::Add:
961 if (CI2->equalsInt(0)) return C1; // X + 0 == X
963 case Instruction::Sub:
964 if (CI2->equalsInt(0)) return C1; // X - 0 == X
966 case Instruction::Mul:
967 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
968 if (CI2->equalsInt(1))
969 return C1; // X * 1 == X
971 case Instruction::UDiv:
972 case Instruction::SDiv:
973 if (CI2->equalsInt(1))
974 return C1; // X / 1 == X
975 if (CI2->equalsInt(0))
976 return UndefValue::get(CI2->getType()); // X / 0 == undef
978 case Instruction::URem:
979 case Instruction::SRem:
980 if (CI2->equalsInt(1))
981 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
982 if (CI2->equalsInt(0))
983 return UndefValue::get(CI2->getType()); // X % 0 == undef
985 case Instruction::And:
986 if (CI2->isZero()) return C2; // X & 0 == 0
987 if (CI2->isAllOnesValue())
988 return C1; // X & -1 == X
990 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
991 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
992 if (CE1->getOpcode() == Instruction::ZExt) {
993 unsigned DstWidth = CI2->getType()->getBitWidth();
995 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
996 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
997 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1001 // If and'ing the address of a global with a constant, fold it.
1002 if (CE1->getOpcode() == Instruction::PtrToInt &&
1003 isa<GlobalValue>(CE1->getOperand(0))) {
1004 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1006 // Functions are at least 4-byte aligned.
1007 unsigned GVAlign = GV->getAlignment();
1008 if (isa<Function>(GV))
1009 GVAlign = std::max(GVAlign, 4U);
1012 unsigned DstWidth = CI2->getType()->getBitWidth();
1013 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1014 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1016 // If checking bits we know are clear, return zero.
1017 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1018 return Constant::getNullValue(CI2->getType());
1023 case Instruction::Or:
1024 if (CI2->equalsInt(0)) return C1; // X | 0 == X
1025 if (CI2->isAllOnesValue())
1026 return C2; // X | -1 == -1
1028 case Instruction::Xor:
1029 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
1031 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1032 switch (CE1->getOpcode()) {
1034 case Instruction::ICmp:
1035 case Instruction::FCmp:
1036 // cmp pred ^ true -> cmp !pred
1037 assert(CI2->equalsInt(1));
1038 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1039 pred = CmpInst::getInversePredicate(pred);
1040 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1041 CE1->getOperand(1));
1045 case Instruction::AShr:
1046 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1047 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1048 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1049 return ConstantExpr::getLShr(C1, C2);
1054 // At this point we know neither constant is an UndefValue.
1055 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1056 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1057 using namespace APIntOps;
1058 const APInt &C1V = CI1->getValue();
1059 const APInt &C2V = CI2->getValue();
1063 case Instruction::Add:
1064 return ConstantInt::get(Context, C1V + C2V);
1065 case Instruction::Sub:
1066 return ConstantInt::get(Context, C1V - C2V);
1067 case Instruction::Mul:
1068 return ConstantInt::get(Context, C1V * C2V);
1069 case Instruction::UDiv:
1070 assert(!CI2->isNullValue() && "Div by zero handled above");
1071 return ConstantInt::get(Context, C1V.udiv(C2V));
1072 case Instruction::SDiv:
1073 assert(!CI2->isNullValue() && "Div by zero handled above");
1074 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1075 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
1076 return ConstantInt::get(Context, C1V.sdiv(C2V));
1077 case Instruction::URem:
1078 assert(!CI2->isNullValue() && "Div by zero handled above");
1079 return ConstantInt::get(Context, C1V.urem(C2V));
1080 case Instruction::SRem:
1081 assert(!CI2->isNullValue() && "Div by zero handled above");
1082 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1083 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
1084 return ConstantInt::get(Context, C1V.srem(C2V));
1085 case Instruction::And:
1086 return ConstantInt::get(Context, C1V & C2V);
1087 case Instruction::Or:
1088 return ConstantInt::get(Context, C1V | C2V);
1089 case Instruction::Xor:
1090 return ConstantInt::get(Context, C1V ^ C2V);
1091 case Instruction::Shl: {
1092 uint32_t shiftAmt = C2V.getZExtValue();
1093 if (shiftAmt < C1V.getBitWidth())
1094 return ConstantInt::get(Context, C1V.shl(shiftAmt));
1096 return UndefValue::get(C1->getType()); // too big shift is undef
1098 case Instruction::LShr: {
1099 uint32_t shiftAmt = C2V.getZExtValue();
1100 if (shiftAmt < C1V.getBitWidth())
1101 return ConstantInt::get(Context, C1V.lshr(shiftAmt));
1103 return UndefValue::get(C1->getType()); // too big shift is undef
1105 case Instruction::AShr: {
1106 uint32_t shiftAmt = C2V.getZExtValue();
1107 if (shiftAmt < C1V.getBitWidth())
1108 return ConstantInt::get(Context, C1V.ashr(shiftAmt));
1110 return UndefValue::get(C1->getType()); // too big shift is undef
1116 case Instruction::SDiv:
1117 case Instruction::UDiv:
1118 case Instruction::URem:
1119 case Instruction::SRem:
1120 case Instruction::LShr:
1121 case Instruction::AShr:
1122 case Instruction::Shl:
1123 if (CI1->equalsInt(0)) return C1;
1128 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1129 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1130 APFloat C1V = CFP1->getValueAPF();
1131 APFloat C2V = CFP2->getValueAPF();
1132 APFloat C3V = C1V; // copy for modification
1136 case Instruction::FAdd:
1137 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1138 return ConstantFP::get(Context, C3V);
1139 case Instruction::FSub:
1140 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1141 return ConstantFP::get(Context, C3V);
1142 case Instruction::FMul:
1143 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1144 return ConstantFP::get(Context, C3V);
1145 case Instruction::FDiv:
1146 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1147 return ConstantFP::get(Context, C3V);
1148 case Instruction::FRem:
1149 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1150 return ConstantFP::get(Context, C3V);
1153 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1154 ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
1155 ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
1156 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
1157 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
1158 std::vector<Constant*> Res;
1159 const Type* EltTy = VTy->getElementType();
1165 case Instruction::Add:
1166 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1167 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1168 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1169 Res.push_back(ConstantExpr::getAdd(C1, C2));
1171 return ConstantVector::get(Res);
1172 case Instruction::FAdd:
1173 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1174 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1175 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1176 Res.push_back(ConstantExpr::getFAdd(C1, C2));
1178 return ConstantVector::get(Res);
1179 case Instruction::Sub:
1180 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1181 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1182 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1183 Res.push_back(ConstantExpr::getSub(C1, C2));
1185 return ConstantVector::get(Res);
1186 case Instruction::FSub:
1187 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1188 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1189 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1190 Res.push_back(ConstantExpr::getFSub(C1, C2));
1192 return ConstantVector::get(Res);
1193 case Instruction::Mul:
1194 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1195 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1196 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1197 Res.push_back(ConstantExpr::getMul(C1, C2));
1199 return ConstantVector::get(Res);
1200 case Instruction::FMul:
1201 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1202 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1203 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1204 Res.push_back(ConstantExpr::getFMul(C1, C2));
1206 return ConstantVector::get(Res);
1207 case Instruction::UDiv:
1208 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1209 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1210 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1211 Res.push_back(ConstantExpr::getUDiv(C1, C2));
1213 return ConstantVector::get(Res);
1214 case Instruction::SDiv:
1215 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1216 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1217 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1218 Res.push_back(ConstantExpr::getSDiv(C1, C2));
1220 return ConstantVector::get(Res);
1221 case Instruction::FDiv:
1222 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1223 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1224 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1225 Res.push_back(ConstantExpr::getFDiv(C1, C2));
1227 return ConstantVector::get(Res);
1228 case Instruction::URem:
1229 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1230 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1231 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1232 Res.push_back(ConstantExpr::getURem(C1, C2));
1234 return ConstantVector::get(Res);
1235 case Instruction::SRem:
1236 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1237 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1238 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1239 Res.push_back(ConstantExpr::getSRem(C1, C2));
1241 return ConstantVector::get(Res);
1242 case Instruction::FRem:
1243 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1244 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1245 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1246 Res.push_back(ConstantExpr::getFRem(C1, C2));
1248 return ConstantVector::get(Res);
1249 case Instruction::And:
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::getAnd(C1, C2));
1255 return ConstantVector::get(Res);
1256 case Instruction::Or:
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::getOr(C1, C2));
1262 return ConstantVector::get(Res);
1263 case Instruction::Xor:
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::getXor(C1, C2));
1269 return ConstantVector::get(Res);
1270 case Instruction::LShr:
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::getLShr(C1, C2));
1276 return ConstantVector::get(Res);
1277 case Instruction::AShr:
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::getAShr(C1, C2));
1283 return ConstantVector::get(Res);
1284 case Instruction::Shl:
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::getShl(C1, C2));
1290 return ConstantVector::get(Res);
1295 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1296 // There are many possible foldings we could do here. We should probably
1297 // at least fold add of a pointer with an integer into the appropriate
1298 // getelementptr. This will improve alias analysis a bit.
1300 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1302 if (Instruction::isAssociative(Opcode, C1->getType()) &&
1303 CE1->getOpcode() == Opcode) {
1304 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1305 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1306 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1308 } else if (isa<ConstantExpr>(C2)) {
1309 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1310 // other way if possible.
1312 case Instruction::Add:
1313 case Instruction::FAdd:
1314 case Instruction::Mul:
1315 case Instruction::FMul:
1316 case Instruction::And:
1317 case Instruction::Or:
1318 case Instruction::Xor:
1319 // No change of opcode required.
1320 return ConstantFoldBinaryInstruction(Context, Opcode, C2, C1);
1322 case Instruction::Shl:
1323 case Instruction::LShr:
1324 case Instruction::AShr:
1325 case Instruction::Sub:
1326 case Instruction::FSub:
1327 case Instruction::SDiv:
1328 case Instruction::UDiv:
1329 case Instruction::FDiv:
1330 case Instruction::URem:
1331 case Instruction::SRem:
1332 case Instruction::FRem:
1333 default: // These instructions cannot be flopped around.
1338 // i1 can be simplified in many cases.
1339 if (C1->getType()->isInteger(1)) {
1341 case Instruction::Add:
1342 case Instruction::Sub:
1343 return ConstantExpr::getXor(C1, C2);
1344 case Instruction::Mul:
1345 return ConstantExpr::getAnd(C1, C2);
1346 case Instruction::Shl:
1347 case Instruction::LShr:
1348 case Instruction::AShr:
1349 // We can assume that C2 == 0. If it were one the result would be
1350 // undefined because the shift value is as large as the bitwidth.
1352 case Instruction::SDiv:
1353 case Instruction::UDiv:
1354 // We can assume that C2 == 1. If it were zero the result would be
1355 // undefined through division by zero.
1357 case Instruction::URem:
1358 case Instruction::SRem:
1359 // We can assume that C2 == 1. If it were zero the result would be
1360 // undefined through division by zero.
1361 return ConstantInt::getFalse(Context);
1367 // We don't know how to fold this.
1371 /// isZeroSizedType - This type is zero sized if its an array or structure of
1372 /// zero sized types. The only leaf zero sized type is an empty structure.
1373 static bool isMaybeZeroSizedType(const Type *Ty) {
1374 if (isa<OpaqueType>(Ty)) return true; // Can't say.
1375 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1377 // If all of elements have zero size, this does too.
1378 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1379 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1382 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1383 return isMaybeZeroSizedType(ATy->getElementType());
1388 /// IdxCompare - Compare the two constants as though they were getelementptr
1389 /// indices. This allows coersion of the types to be the same thing.
1391 /// If the two constants are the "same" (after coersion), return 0. If the
1392 /// first is less than the second, return -1, if the second is less than the
1393 /// first, return 1. If the constants are not integral, return -2.
1395 static int IdxCompare(LLVMContext &Context, Constant *C1, Constant *C2,
1397 if (C1 == C2) return 0;
1399 // Ok, we found a different index. If they are not ConstantInt, we can't do
1400 // anything with them.
1401 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1402 return -2; // don't know!
1404 // Ok, we have two differing integer indices. Sign extend them to be the same
1405 // type. Long is always big enough, so we use it.
1406 if (!C1->getType()->isInteger(64))
1407 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(Context));
1409 if (!C2->getType()->isInteger(64))
1410 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(Context));
1412 if (C1 == C2) return 0; // They are equal
1414 // If the type being indexed over is really just a zero sized type, there is
1415 // no pointer difference being made here.
1416 if (isMaybeZeroSizedType(ElTy))
1417 return -2; // dunno.
1419 // If they are really different, now that they are the same type, then we
1420 // found a difference!
1421 if (cast<ConstantInt>(C1)->getSExtValue() <
1422 cast<ConstantInt>(C2)->getSExtValue())
1428 /// evaluateFCmpRelation - This function determines if there is anything we can
1429 /// decide about the two constants provided. This doesn't need to handle simple
1430 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1431 /// If we can determine that the two constants have a particular relation to
1432 /// each other, we should return the corresponding FCmpInst predicate,
1433 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1434 /// ConstantFoldCompareInstruction.
1436 /// To simplify this code we canonicalize the relation so that the first
1437 /// operand is always the most "complex" of the two. We consider ConstantFP
1438 /// to be the simplest, and ConstantExprs to be the most complex.
1439 static FCmpInst::Predicate evaluateFCmpRelation(LLVMContext &Context,
1440 Constant *V1, Constant *V2) {
1441 assert(V1->getType() == V2->getType() &&
1442 "Cannot compare values of different types!");
1444 // No compile-time operations on this type yet.
1445 if (V1->getType()->isPPC_FP128Ty())
1446 return FCmpInst::BAD_FCMP_PREDICATE;
1448 // Handle degenerate case quickly
1449 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1451 if (!isa<ConstantExpr>(V1)) {
1452 if (!isa<ConstantExpr>(V2)) {
1453 // We distilled thisUse the standard constant folder for a few cases
1455 R = dyn_cast<ConstantInt>(
1456 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1457 if (R && !R->isZero())
1458 return FCmpInst::FCMP_OEQ;
1459 R = dyn_cast<ConstantInt>(
1460 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1461 if (R && !R->isZero())
1462 return FCmpInst::FCMP_OLT;
1463 R = dyn_cast<ConstantInt>(
1464 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1465 if (R && !R->isZero())
1466 return FCmpInst::FCMP_OGT;
1468 // Nothing more we can do
1469 return FCmpInst::BAD_FCMP_PREDICATE;
1472 // If the first operand is simple and second is ConstantExpr, swap operands.
1473 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(Context, V2, V1);
1474 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1475 return FCmpInst::getSwappedPredicate(SwappedRelation);
1477 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1478 // constantexpr or a simple constant.
1479 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1480 switch (CE1->getOpcode()) {
1481 case Instruction::FPTrunc:
1482 case Instruction::FPExt:
1483 case Instruction::UIToFP:
1484 case Instruction::SIToFP:
1485 // We might be able to do something with these but we don't right now.
1491 // There are MANY other foldings that we could perform here. They will
1492 // probably be added on demand, as they seem needed.
1493 return FCmpInst::BAD_FCMP_PREDICATE;
1496 /// evaluateICmpRelation - This function determines if there is anything we can
1497 /// decide about the two constants provided. This doesn't need to handle simple
1498 /// things like integer comparisons, but should instead handle ConstantExprs
1499 /// and GlobalValues. If we can determine that the two constants have a
1500 /// particular relation to each other, we should return the corresponding ICmp
1501 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1503 /// To simplify this code we canonicalize the relation so that the first
1504 /// operand is always the most "complex" of the two. We consider simple
1505 /// constants (like ConstantInt) to be the simplest, followed by
1506 /// GlobalValues, followed by ConstantExpr's (the most complex).
1508 static ICmpInst::Predicate evaluateICmpRelation(LLVMContext &Context,
1509 Constant *V1, Constant *V2,
1511 assert(V1->getType() == V2->getType() &&
1512 "Cannot compare different types of values!");
1513 if (V1 == V2) return ICmpInst::ICMP_EQ;
1515 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1516 !isa<BlockAddress>(V1)) {
1517 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1518 !isa<BlockAddress>(V2)) {
1519 // We distilled this down to a simple case, use the standard constant
1522 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1523 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1524 if (R && !R->isZero())
1526 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1527 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1528 if (R && !R->isZero())
1530 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1531 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1532 if (R && !R->isZero())
1535 // If we couldn't figure it out, bail.
1536 return ICmpInst::BAD_ICMP_PREDICATE;
1539 // If the first operand is simple, swap operands.
1540 ICmpInst::Predicate SwappedRelation =
1541 evaluateICmpRelation(Context, V2, V1, isSigned);
1542 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1543 return ICmpInst::getSwappedPredicate(SwappedRelation);
1545 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1546 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1547 ICmpInst::Predicate SwappedRelation =
1548 evaluateICmpRelation(Context, V2, V1, isSigned);
1549 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1550 return ICmpInst::getSwappedPredicate(SwappedRelation);
1551 return ICmpInst::BAD_ICMP_PREDICATE;
1554 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1555 // constant (which, since the types must match, means that it's a
1556 // ConstantPointerNull).
1557 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1558 // Don't try to decide equality of aliases.
1559 if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1560 if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1561 return ICmpInst::ICMP_NE;
1562 } else if (isa<BlockAddress>(V2)) {
1563 return ICmpInst::ICMP_NE; // Globals never equal labels.
1565 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1566 // GlobalVals can never be null unless they have external weak linkage.
1567 // We don't try to evaluate aliases here.
1568 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1569 return ICmpInst::ICMP_NE;
1571 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1572 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1573 ICmpInst::Predicate SwappedRelation =
1574 evaluateICmpRelation(Context, V2, V1, isSigned);
1575 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1576 return ICmpInst::getSwappedPredicate(SwappedRelation);
1577 return ICmpInst::BAD_ICMP_PREDICATE;
1580 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1581 // constant (which, since the types must match, means that it is a
1582 // ConstantPointerNull).
1583 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1584 // Block address in another function can't equal this one, but block
1585 // addresses in the current function might be the same if blocks are
1587 if (BA2->getFunction() != BA->getFunction())
1588 return ICmpInst::ICMP_NE;
1590 // Block addresses aren't null, don't equal the address of globals.
1591 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1592 "Canonicalization guarantee!");
1593 return ICmpInst::ICMP_NE;
1596 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1597 // constantexpr, a global, block address, or a simple constant.
1598 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1599 Constant *CE1Op0 = CE1->getOperand(0);
1601 switch (CE1->getOpcode()) {
1602 case Instruction::Trunc:
1603 case Instruction::FPTrunc:
1604 case Instruction::FPExt:
1605 case Instruction::FPToUI:
1606 case Instruction::FPToSI:
1607 break; // We can't evaluate floating point casts or truncations.
1609 case Instruction::UIToFP:
1610 case Instruction::SIToFP:
1611 case Instruction::BitCast:
1612 case Instruction::ZExt:
1613 case Instruction::SExt:
1614 // If the cast is not actually changing bits, and the second operand is a
1615 // null pointer, do the comparison with the pre-casted value.
1616 if (V2->isNullValue() &&
1617 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
1618 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1619 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1620 return evaluateICmpRelation(Context, CE1Op0,
1621 Constant::getNullValue(CE1Op0->getType()),
1626 case Instruction::GetElementPtr:
1627 // Ok, since this is a getelementptr, we know that the constant has a
1628 // pointer type. Check the various cases.
1629 if (isa<ConstantPointerNull>(V2)) {
1630 // If we are comparing a GEP to a null pointer, check to see if the base
1631 // of the GEP equals the null pointer.
1632 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1633 if (GV->hasExternalWeakLinkage())
1634 // Weak linkage GVals could be zero or not. We're comparing that
1635 // to null pointer so its greater-or-equal
1636 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1638 // If its not weak linkage, the GVal must have a non-zero address
1639 // so the result is greater-than
1640 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1641 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1642 // If we are indexing from a null pointer, check to see if we have any
1643 // non-zero indices.
1644 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1645 if (!CE1->getOperand(i)->isNullValue())
1646 // Offsetting from null, must not be equal.
1647 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1648 // Only zero indexes from null, must still be zero.
1649 return ICmpInst::ICMP_EQ;
1651 // Otherwise, we can't really say if the first operand is null or not.
1652 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1653 if (isa<ConstantPointerNull>(CE1Op0)) {
1654 if (GV2->hasExternalWeakLinkage())
1655 // Weak linkage GVals could be zero or not. We're comparing it to
1656 // a null pointer, so its less-or-equal
1657 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1659 // If its not weak linkage, the GVal must have a non-zero address
1660 // so the result is less-than
1661 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1662 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1664 // If this is a getelementptr of the same global, then it must be
1665 // different. Because the types must match, the getelementptr could
1666 // only have at most one index, and because we fold getelementptr's
1667 // with a single zero index, it must be nonzero.
1668 assert(CE1->getNumOperands() == 2 &&
1669 !CE1->getOperand(1)->isNullValue() &&
1670 "Suprising getelementptr!");
1671 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1673 // If they are different globals, we don't know what the value is,
1674 // but they can't be equal.
1675 return ICmpInst::ICMP_NE;
1679 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1680 Constant *CE2Op0 = CE2->getOperand(0);
1682 // There are MANY other foldings that we could perform here. They will
1683 // probably be added on demand, as they seem needed.
1684 switch (CE2->getOpcode()) {
1686 case Instruction::GetElementPtr:
1687 // By far the most common case to handle is when the base pointers are
1688 // obviously to the same or different globals.
1689 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1690 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1691 return ICmpInst::ICMP_NE;
1692 // Ok, we know that both getelementptr instructions are based on the
1693 // same global. From this, we can precisely determine the relative
1694 // ordering of the resultant pointers.
1697 // The logic below assumes that the result of the comparison
1698 // can be determined by finding the first index that differs.
1699 // This doesn't work if there is over-indexing in any
1700 // subsequent indices, so check for that case first.
1701 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1702 !CE2->isGEPWithNoNotionalOverIndexing())
1703 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1705 // Compare all of the operands the GEP's have in common.
1706 gep_type_iterator GTI = gep_type_begin(CE1);
1707 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1709 switch (IdxCompare(Context, CE1->getOperand(i),
1710 CE2->getOperand(i), GTI.getIndexedType())) {
1711 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1712 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1713 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1716 // Ok, we ran out of things they have in common. If any leftovers
1717 // are non-zero then we have a difference, otherwise we are equal.
1718 for (; i < CE1->getNumOperands(); ++i)
1719 if (!CE1->getOperand(i)->isNullValue()) {
1720 if (isa<ConstantInt>(CE1->getOperand(i)))
1721 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1723 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1726 for (; i < CE2->getNumOperands(); ++i)
1727 if (!CE2->getOperand(i)->isNullValue()) {
1728 if (isa<ConstantInt>(CE2->getOperand(i)))
1729 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1731 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1733 return ICmpInst::ICMP_EQ;
1742 return ICmpInst::BAD_ICMP_PREDICATE;
1745 Constant *llvm::ConstantFoldCompareInstruction(LLVMContext &Context,
1746 unsigned short pred,
1747 Constant *C1, Constant *C2) {
1748 const Type *ResultTy;
1749 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1750 ResultTy = VectorType::get(Type::getInt1Ty(Context), VT->getNumElements());
1752 ResultTy = Type::getInt1Ty(Context);
1754 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1755 if (pred == FCmpInst::FCMP_FALSE)
1756 return Constant::getNullValue(ResultTy);
1758 if (pred == FCmpInst::FCMP_TRUE)
1759 return Constant::getAllOnesValue(ResultTy);
1761 // Handle some degenerate cases first
1762 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1763 return UndefValue::get(ResultTy);
1765 // No compile-time operations on this type yet.
1766 if (C1->getType()->isPPC_FP128Ty())
1769 // icmp eq/ne(null,GV) -> false/true
1770 if (C1->isNullValue()) {
1771 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1772 // Don't try to evaluate aliases. External weak GV can be null.
1773 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1774 if (pred == ICmpInst::ICMP_EQ)
1775 return ConstantInt::getFalse(Context);
1776 else if (pred == ICmpInst::ICMP_NE)
1777 return ConstantInt::getTrue(Context);
1779 // icmp eq/ne(GV,null) -> false/true
1780 } else if (C2->isNullValue()) {
1781 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1782 // Don't try to evaluate aliases. External weak GV can be null.
1783 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1784 if (pred == ICmpInst::ICMP_EQ)
1785 return ConstantInt::getFalse(Context);
1786 else if (pred == ICmpInst::ICMP_NE)
1787 return ConstantInt::getTrue(Context);
1791 // If the comparison is a comparison between two i1's, simplify it.
1792 if (C1->getType()->isInteger(1)) {
1794 case ICmpInst::ICMP_EQ:
1795 if (isa<ConstantInt>(C2))
1796 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1797 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1798 case ICmpInst::ICMP_NE:
1799 return ConstantExpr::getXor(C1, C2);
1805 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1806 APInt V1 = cast<ConstantInt>(C1)->getValue();
1807 APInt V2 = cast<ConstantInt>(C2)->getValue();
1809 default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1810 case ICmpInst::ICMP_EQ:
1811 return ConstantInt::get(Type::getInt1Ty(Context), V1 == V2);
1812 case ICmpInst::ICMP_NE:
1813 return ConstantInt::get(Type::getInt1Ty(Context), V1 != V2);
1814 case ICmpInst::ICMP_SLT:
1815 return ConstantInt::get(Type::getInt1Ty(Context), V1.slt(V2));
1816 case ICmpInst::ICMP_SGT:
1817 return ConstantInt::get(Type::getInt1Ty(Context), V1.sgt(V2));
1818 case ICmpInst::ICMP_SLE:
1819 return ConstantInt::get(Type::getInt1Ty(Context), V1.sle(V2));
1820 case ICmpInst::ICMP_SGE:
1821 return ConstantInt::get(Type::getInt1Ty(Context), V1.sge(V2));
1822 case ICmpInst::ICMP_ULT:
1823 return ConstantInt::get(Type::getInt1Ty(Context), V1.ult(V2));
1824 case ICmpInst::ICMP_UGT:
1825 return ConstantInt::get(Type::getInt1Ty(Context), V1.ugt(V2));
1826 case ICmpInst::ICMP_ULE:
1827 return ConstantInt::get(Type::getInt1Ty(Context), V1.ule(V2));
1828 case ICmpInst::ICMP_UGE:
1829 return ConstantInt::get(Type::getInt1Ty(Context), V1.uge(V2));
1831 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1832 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1833 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1834 APFloat::cmpResult R = C1V.compare(C2V);
1836 default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1837 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse(Context);
1838 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue(Context);
1839 case FCmpInst::FCMP_UNO:
1840 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered);
1841 case FCmpInst::FCMP_ORD:
1842 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpUnordered);
1843 case FCmpInst::FCMP_UEQ:
1844 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1845 R==APFloat::cmpEqual);
1846 case FCmpInst::FCMP_OEQ:
1847 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpEqual);
1848 case FCmpInst::FCMP_UNE:
1849 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpEqual);
1850 case FCmpInst::FCMP_ONE:
1851 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
1852 R==APFloat::cmpGreaterThan);
1853 case FCmpInst::FCMP_ULT:
1854 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1855 R==APFloat::cmpLessThan);
1856 case FCmpInst::FCMP_OLT:
1857 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan);
1858 case FCmpInst::FCMP_UGT:
1859 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1860 R==APFloat::cmpGreaterThan);
1861 case FCmpInst::FCMP_OGT:
1862 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan);
1863 case FCmpInst::FCMP_ULE:
1864 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpGreaterThan);
1865 case FCmpInst::FCMP_OLE:
1866 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
1867 R==APFloat::cmpEqual);
1868 case FCmpInst::FCMP_UGE:
1869 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpLessThan);
1870 case FCmpInst::FCMP_OGE:
1871 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan ||
1872 R==APFloat::cmpEqual);
1874 } else if (isa<VectorType>(C1->getType())) {
1875 SmallVector<Constant*, 16> C1Elts, C2Elts;
1876 C1->getVectorElements(Context, C1Elts);
1877 C2->getVectorElements(Context, C2Elts);
1878 if (C1Elts.empty() || C2Elts.empty())
1881 // If we can constant fold the comparison of each element, constant fold
1882 // the whole vector comparison.
1883 SmallVector<Constant*, 4> ResElts;
1884 for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1885 // Compare the elements, producing an i1 result or constant expr.
1886 ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
1888 return ConstantVector::get(&ResElts[0], ResElts.size());
1891 if (C1->getType()->isFloatingPoint()) {
1892 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1893 switch (evaluateFCmpRelation(Context, C1, C2)) {
1894 default: llvm_unreachable("Unknown relation!");
1895 case FCmpInst::FCMP_UNO:
1896 case FCmpInst::FCMP_ORD:
1897 case FCmpInst::FCMP_UEQ:
1898 case FCmpInst::FCMP_UNE:
1899 case FCmpInst::FCMP_ULT:
1900 case FCmpInst::FCMP_UGT:
1901 case FCmpInst::FCMP_ULE:
1902 case FCmpInst::FCMP_UGE:
1903 case FCmpInst::FCMP_TRUE:
1904 case FCmpInst::FCMP_FALSE:
1905 case FCmpInst::BAD_FCMP_PREDICATE:
1906 break; // Couldn't determine anything about these constants.
1907 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1908 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1909 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1910 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1912 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1913 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1914 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1915 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1917 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1918 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1919 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1920 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1922 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1923 // We can only partially decide this relation.
1924 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1926 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1929 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1930 // We can only partially decide this relation.
1931 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1933 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1936 case ICmpInst::ICMP_NE: // We know that C1 != C2
1937 // We can only partially decide this relation.
1938 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1940 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1945 // If we evaluated the result, return it now.
1947 return ConstantInt::get(Type::getInt1Ty(Context), Result);
1950 // Evaluate the relation between the two constants, per the predicate.
1951 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1952 switch (evaluateICmpRelation(Context, C1, C2, CmpInst::isSigned(pred))) {
1953 default: llvm_unreachable("Unknown relational!");
1954 case ICmpInst::BAD_ICMP_PREDICATE:
1955 break; // Couldn't determine anything about these constants.
1956 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1957 // If we know the constants are equal, we can decide the result of this
1958 // computation precisely.
1959 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1961 case ICmpInst::ICMP_ULT:
1963 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1965 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1969 case ICmpInst::ICMP_SLT:
1971 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1973 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1977 case ICmpInst::ICMP_UGT:
1979 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1981 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1985 case ICmpInst::ICMP_SGT:
1987 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1989 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1993 case ICmpInst::ICMP_ULE:
1994 if (pred == ICmpInst::ICMP_UGT) Result = 0;
1995 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1997 case ICmpInst::ICMP_SLE:
1998 if (pred == ICmpInst::ICMP_SGT) Result = 0;
1999 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
2001 case ICmpInst::ICMP_UGE:
2002 if (pred == ICmpInst::ICMP_ULT) Result = 0;
2003 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
2005 case ICmpInst::ICMP_SGE:
2006 if (pred == ICmpInst::ICMP_SLT) Result = 0;
2007 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
2009 case ICmpInst::ICMP_NE:
2010 if (pred == ICmpInst::ICMP_EQ) Result = 0;
2011 if (pred == ICmpInst::ICMP_NE) Result = 1;
2015 // If we evaluated the result, return it now.
2017 return ConstantInt::get(Type::getInt1Ty(Context), Result);
2019 // If the right hand side is a bitcast, try using its inverse to simplify
2020 // it by moving it to the left hand side. We can't do this if it would turn
2021 // a vector compare into a scalar compare or visa versa.
2022 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
2023 Constant *CE2Op0 = CE2->getOperand(0);
2024 if (CE2->getOpcode() == Instruction::BitCast &&
2025 isa<VectorType>(CE2->getType())==isa<VectorType>(CE2Op0->getType())) {
2026 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
2027 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
2031 // If the left hand side is an extension, try eliminating it.
2032 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2033 if (CE1->getOpcode() == Instruction::SExt ||
2034 CE1->getOpcode() == Instruction::ZExt) {
2035 Constant *CE1Op0 = CE1->getOperand(0);
2036 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2037 if (CE1Inverse == CE1Op0) {
2038 // Check whether we can safely truncate the right hand side.
2039 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2040 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
2041 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2047 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2048 (C1->isNullValue() && !C2->isNullValue())) {
2049 // If C2 is a constant expr and C1 isn't, flip them around and fold the
2050 // other way if possible.
2051 // Also, if C1 is null and C2 isn't, flip them around.
2053 case ICmpInst::ICMP_EQ:
2054 case ICmpInst::ICMP_NE:
2055 // No change of predicate required.
2056 return ConstantExpr::getICmp(pred, C2, C1);
2058 case ICmpInst::ICMP_ULT:
2059 case ICmpInst::ICMP_SLT:
2060 case ICmpInst::ICMP_UGT:
2061 case ICmpInst::ICMP_SGT:
2062 case ICmpInst::ICMP_ULE:
2063 case ICmpInst::ICMP_SLE:
2064 case ICmpInst::ICMP_UGE:
2065 case ICmpInst::ICMP_SGE:
2066 // Change the predicate as necessary to swap the operands.
2067 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
2068 return ConstantExpr::getICmp(pred, C2, C1);
2070 default: // These predicates cannot be flopped around.
2078 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
2080 static bool isInBoundsIndices(Constant *const *Idxs, size_t NumIdx) {
2081 // No indices means nothing that could be out of bounds.
2082 if (NumIdx == 0) return true;
2084 // If the first index is zero, it's in bounds.
2085 if (Idxs[0]->isNullValue()) return true;
2087 // If the first index is one and all the rest are zero, it's in bounds,
2088 // by the one-past-the-end rule.
2089 if (!cast<ConstantInt>(Idxs[0])->isOne())
2091 for (unsigned i = 1, e = NumIdx; i != e; ++i)
2092 if (!Idxs[i]->isNullValue())
2097 Constant *llvm::ConstantFoldGetElementPtr(LLVMContext &Context,
2100 Constant* const *Idxs,
2103 (NumIdx == 1 && Idxs[0]->isNullValue()))
2106 if (isa<UndefValue>(C)) {
2107 const PointerType *Ptr = cast<PointerType>(C->getType());
2108 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
2110 (Value **)Idxs+NumIdx);
2111 assert(Ty != 0 && "Invalid indices for GEP!");
2112 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
2115 Constant *Idx0 = Idxs[0];
2116 if (C->isNullValue()) {
2118 for (unsigned i = 0, e = NumIdx; i != e; ++i)
2119 if (!Idxs[i]->isNullValue()) {
2124 const PointerType *Ptr = cast<PointerType>(C->getType());
2125 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
2127 (Value**)Idxs+NumIdx);
2128 assert(Ty != 0 && "Invalid indices for GEP!");
2129 return ConstantPointerNull::get(
2130 PointerType::get(Ty,Ptr->getAddressSpace()));
2134 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2135 // Combine Indices - If the source pointer to this getelementptr instruction
2136 // is a getelementptr instruction, combine the indices of the two
2137 // getelementptr instructions into a single instruction.
2139 if (CE->getOpcode() == Instruction::GetElementPtr) {
2140 const Type *LastTy = 0;
2141 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2145 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
2146 SmallVector<Value*, 16> NewIndices;
2147 NewIndices.reserve(NumIdx + CE->getNumOperands());
2148 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2149 NewIndices.push_back(CE->getOperand(i));
2151 // Add the last index of the source with the first index of the new GEP.
2152 // Make sure to handle the case when they are actually different types.
2153 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2154 // Otherwise it must be an array.
2155 if (!Idx0->isNullValue()) {
2156 const Type *IdxTy = Combined->getType();
2157 if (IdxTy != Idx0->getType()) {
2159 ConstantExpr::getSExtOrBitCast(Idx0, Type::getInt64Ty(Context));
2160 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
2161 Type::getInt64Ty(Context));
2162 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2165 ConstantExpr::get(Instruction::Add, Idx0, Combined);
2169 NewIndices.push_back(Combined);
2170 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
2171 return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
2172 ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
2174 NewIndices.size()) :
2175 ConstantExpr::getGetElementPtr(CE->getOperand(0),
2181 // Implement folding of:
2182 // int* getelementptr ([2 x int]* bitcast ([3 x int]* %X to [2 x int]*),
2184 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
2186 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
2187 if (const PointerType *SPT =
2188 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
2189 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
2190 if (const ArrayType *CAT =
2191 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
2192 if (CAT->getElementType() == SAT->getElementType())
2194 ConstantExpr::getInBoundsGetElementPtr(
2195 (Constant*)CE->getOperand(0), Idxs, NumIdx) :
2196 ConstantExpr::getGetElementPtr(
2197 (Constant*)CE->getOperand(0), Idxs, NumIdx);
2201 // Check to see if any array indices are not within the corresponding
2202 // notional array bounds. If so, try to determine if they can be factored
2203 // out into preceding dimensions.
2204 bool Unknown = false;
2205 SmallVector<Constant *, 8> NewIdxs;
2206 const Type *Ty = C->getType();
2207 const Type *Prev = 0;
2208 for (unsigned i = 0; i != NumIdx;
2209 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2210 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2211 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2212 if (ATy->getNumElements() <= INT64_MAX &&
2213 ATy->getNumElements() != 0 &&
2214 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2215 if (isa<SequentialType>(Prev)) {
2216 // It's out of range, but we can factor it into the prior
2218 NewIdxs.resize(NumIdx);
2219 ConstantInt *Factor = ConstantInt::get(CI->getType(),
2220 ATy->getNumElements());
2221 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2223 Constant *PrevIdx = Idxs[i-1];
2224 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2226 // Before adding, extend both operands to i64 to avoid
2227 // overflow trouble.
2228 if (!PrevIdx->getType()->isInteger(64))
2229 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2230 Type::getInt64Ty(Context));
2231 if (!Div->getType()->isInteger(64))
2232 Div = ConstantExpr::getSExt(Div,
2233 Type::getInt64Ty(Context));
2235 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2237 // It's out of range, but the prior dimension is a struct
2238 // so we can't do anything about it.
2243 // We don't know if it's in range or not.
2248 // If we did any factoring, start over with the adjusted indices.
2249 if (!NewIdxs.empty()) {
2250 for (unsigned i = 0; i != NumIdx; ++i)
2251 if (!NewIdxs[i]) NewIdxs[i] = Idxs[i];
2253 ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
2255 ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
2258 // If all indices are known integers and normalized, we can do a simple
2259 // check for the "inbounds" property.
2260 if (!Unknown && !inBounds &&
2261 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
2262 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);