1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 // template-based folder for simple primitive constants like ConstantInt, and
16 // the special case hackery that we use to symbolically evaluate expressions
17 // that use ConstantExprs.
19 //===----------------------------------------------------------------------===//
21 #include "ConstantFold.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/GetElementPtrTypeIterator.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
34 //===----------------------------------------------------------------------===//
35 // ConstantFold*Instruction Implementations
36 //===----------------------------------------------------------------------===//
38 /// CastConstantVector - Convert the specified ConstantVector node to the
39 /// specified vector type. At this point, we know that the elements of the
40 /// input packed constant are all simple integer or FP values.
41 static Constant *CastConstantVector(ConstantVector *CV,
42 const VectorType *DstTy) {
43 unsigned SrcNumElts = CV->getType()->getNumElements();
44 unsigned DstNumElts = DstTy->getNumElements();
45 const Type *SrcEltTy = CV->getType()->getElementType();
46 const Type *DstEltTy = DstTy->getElementType();
48 // If both vectors have the same number of elements (thus, the elements
49 // are the same size), perform the conversion now.
50 if (SrcNumElts == DstNumElts) {
51 std::vector<Constant*> Result;
53 // If the src and dest elements are both integers, or both floats, we can
54 // just BitCast each element because the elements are the same size.
55 if ((SrcEltTy->isInteger() && DstEltTy->isInteger()) ||
56 (SrcEltTy->isFloatingPoint() && DstEltTy->isFloatingPoint())) {
57 for (unsigned i = 0; i != SrcNumElts; ++i)
59 ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
60 return ConstantVector::get(Result);
63 // If this is an int-to-fp cast ..
64 if (SrcEltTy->isInteger()) {
65 // Ensure that it is int-to-fp cast
66 assert(DstEltTy->isFloatingPoint());
67 if (DstEltTy->getTypeID() == Type::DoubleTyID) {
68 for (unsigned i = 0; i != SrcNumElts; ++i) {
70 BitsToDouble(cast<ConstantInt>(CV->getOperand(i))->getZExtValue());
71 Result.push_back(ConstantFP::get(Type::DoubleTy, V));
73 return ConstantVector::get(Result);
75 assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
76 for (unsigned i = 0; i != SrcNumElts; ++i) {
78 BitsToFloat(cast<ConstantInt>(CV->getOperand(i))->getZExtValue());
79 Result.push_back(ConstantFP::get(Type::FloatTy, V));
81 return ConstantVector::get(Result);
84 // Otherwise, this is an fp-to-int cast.
85 assert(SrcEltTy->isFloatingPoint() && DstEltTy->isInteger());
87 if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
88 for (unsigned i = 0; i != SrcNumElts; ++i) {
90 DoubleToBits(cast<ConstantFP>(CV->getOperand(i))->getValue());
91 Constant *C = ConstantInt::get(Type::Int64Ty,
92 APIntOps::RoundDoubleToAPInt(V));
93 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
95 return ConstantVector::get(Result);
98 assert(SrcEltTy->getTypeID() == Type::FloatTyID);
99 for (unsigned i = 0; i != SrcNumElts; ++i) {
100 uint32_t V = FloatToBits(cast<ConstantFP>(CV->getOperand(i))->getValue());
101 Constant *C = ConstantInt::get(Type::Int32Ty, V);
102 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
104 return ConstantVector::get(Result);
107 // Otherwise, this is a cast that changes element count and size. Handle
108 // casts which shrink the elements here.
110 // FIXME: We need to know endianness to do this!
115 /// This function determines which opcode to use to fold two constant cast
116 /// expressions together. It uses CastInst::isEliminableCastPair to determine
117 /// the opcode. Consequently its just a wrapper around that function.
118 /// @Determine if it is valid to fold a cast of a cast
120 foldConstantCastPair(
121 unsigned opc, ///< opcode of the second cast constant expression
122 const ConstantExpr*Op, ///< the first cast constant expression
123 const Type *DstTy ///< desintation type of the first cast
125 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
126 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
127 assert(CastInst::isCast(opc) && "Invalid cast opcode");
129 // The the types and opcodes for the two Cast constant expressions
130 const Type *SrcTy = Op->getOperand(0)->getType();
131 const Type *MidTy = Op->getType();
132 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
133 Instruction::CastOps secondOp = Instruction::CastOps(opc);
135 // Let CastInst::isEliminableCastPair do the heavy lifting.
136 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
140 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
141 const Type *DestTy) {
142 const Type *SrcTy = V->getType();
144 if (isa<UndefValue>(V))
145 return UndefValue::get(DestTy);
147 // If the cast operand is a constant expression, there's a few things we can
148 // do to try to simplify it.
149 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
151 // Try hard to fold cast of cast because they are often eliminable.
152 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
153 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
154 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
155 // If all of the indexes in the GEP are null values, there is no pointer
156 // adjustment going on. We might as well cast the source pointer.
157 bool isAllNull = true;
158 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
159 if (!CE->getOperand(i)->isNullValue()) {
164 // This is casting one pointer type to another, always BitCast
165 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
169 // We actually have to do a cast now. Perform the cast according to the
172 case Instruction::FPTrunc:
173 case Instruction::FPExt:
174 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
175 return ConstantFP::get(DestTy, FPC->getValue());
176 return 0; // Can't fold.
177 case Instruction::FPToUI:
178 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
179 APInt Val(APIntOps::RoundDoubleToAPInt(FPC->getValue()));
180 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
181 if (Val.getBitWidth() > DestBitWidth)
182 Val.trunc(DestBitWidth);
183 else if (Val.getBitWidth() < DestBitWidth)
184 Val.zext(DestBitWidth);
185 return ConstantInt::get(DestTy, Val);
187 return 0; // Can't fold.
188 case Instruction::FPToSI:
189 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
190 APInt Val(APIntOps::RoundDoubleToAPInt(FPC->getValue()));
191 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
192 if (Val.getBitWidth() > DestBitWidth)
193 Val.trunc(DestBitWidth);
194 else if (Val.getBitWidth() < DestBitWidth)
195 Val.sext(DestBitWidth);
196 return ConstantInt::get(DestTy, Val);
198 return 0; // Can't fold.
199 case Instruction::IntToPtr: //always treated as unsigned
200 if (V->isNullValue()) // Is it an integral null value?
201 return ConstantPointerNull::get(cast<PointerType>(DestTy));
202 return 0; // Other pointer types cannot be casted
203 case Instruction::PtrToInt: // always treated as unsigned
204 if (V->isNullValue()) // is it a null pointer value?
205 return ConstantInt::get(DestTy, 0);
206 return 0; // Other pointer types cannot be casted
207 case Instruction::UIToFP:
208 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
209 if (CI->getType()->getBitWidth() <= APInt::APINT_BITS_PER_WORD)
210 return ConstantFP::get(DestTy, CI->getValue().roundToDouble(false));
212 case Instruction::SIToFP:
213 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
214 if (CI->getType()->getBitWidth() <= APInt::APINT_BITS_PER_WORD)
215 return ConstantFP::get(DestTy, CI->getValue().roundToDouble(true));
217 case Instruction::ZExt:
218 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
219 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
220 APInt Result(CI->getValue());
221 Result.zext(BitWidth);
222 return ConstantInt::get(DestTy, Result);
225 case Instruction::SExt:
226 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
227 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
228 APInt Result(CI->getValue());
229 Result.sext(BitWidth);
230 return ConstantInt::get(DestTy, Result);
233 case Instruction::Trunc:
234 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
235 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
236 APInt Result(CI->getValue());
237 Result.trunc(BitWidth);
238 return ConstantInt::get(DestTy, Result);
241 case Instruction::BitCast:
243 return (Constant*)V; // no-op cast
245 // Check to see if we are casting a pointer to an aggregate to a pointer to
246 // the first element. If so, return the appropriate GEP instruction.
247 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
248 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
249 SmallVector<Value*, 8> IdxList;
250 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
251 const Type *ElTy = PTy->getElementType();
252 while (ElTy != DPTy->getElementType()) {
253 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
254 if (STy->getNumElements() == 0) break;
255 ElTy = STy->getElementType(0);
256 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
257 } else if (const SequentialType *STy =
258 dyn_cast<SequentialType>(ElTy)) {
259 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
260 ElTy = STy->getElementType();
261 IdxList.push_back(IdxList[0]);
267 if (ElTy == DPTy->getElementType())
268 return ConstantExpr::getGetElementPtr(
269 const_cast<Constant*>(V), &IdxList[0], IdxList.size());
272 // Handle casts from one packed constant to another. We know that the src
273 // and dest type have the same size (otherwise its an illegal cast).
274 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
275 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
276 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
277 "Not cast between same sized vectors!");
278 // First, check for null and undef
279 if (isa<ConstantAggregateZero>(V))
280 return Constant::getNullValue(DestTy);
281 if (isa<UndefValue>(V))
282 return UndefValue::get(DestTy);
284 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
285 // This is a cast from a ConstantVector of one type to a
286 // ConstantVector of another type. Check to see if all elements of
287 // the input are simple.
288 bool AllSimpleConstants = true;
289 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
290 if (!isa<ConstantInt>(CV->getOperand(i)) &&
291 !isa<ConstantFP>(CV->getOperand(i))) {
292 AllSimpleConstants = false;
297 // If all of the elements are simple constants, we can fold this.
298 if (AllSimpleConstants)
299 return CastConstantVector(const_cast<ConstantVector*>(CV), DestPTy);
304 // Finally, implement bitcast folding now. The code below doesn't handle
306 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
307 return ConstantPointerNull::get(cast<PointerType>(DestTy));
309 // Handle integral constant input.
310 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
311 if (DestTy->isInteger())
312 // Integral -> Integral. This is a no-op because the bit widths must
313 // be the same. Consequently, we just fold to V.
314 return const_cast<Constant*>(V);
316 if (DestTy->isFloatingPoint()) {
317 if (DestTy == Type::FloatTy)
318 return ConstantFP::get(DestTy, BitsToFloat(CI->getZExtValue()));
319 assert(DestTy == Type::DoubleTy && "Unknown FP type!");
320 return ConstantFP::get(DestTy, BitsToDouble(CI->getZExtValue()));
322 // Otherwise, can't fold this (packed?)
326 // Handle ConstantFP input.
327 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
329 if (DestTy == Type::Int32Ty) {
330 return ConstantInt::get(DestTy, FloatToBits(FP->getValue()));
332 assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
333 return ConstantInt::get(DestTy, DoubleToBits(FP->getValue()));
338 assert(!"Invalid CE CastInst opcode");
342 assert(0 && "Failed to cast constant expression");
346 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
348 const Constant *V2) {
349 if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
350 return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
352 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
353 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
354 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
355 if (V1 == V2) return const_cast<Constant*>(V1);
359 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
360 const Constant *Idx) {
361 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
362 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
363 if (Val->isNullValue()) // ee(zero, x) -> zero
364 return Constant::getNullValue(
365 cast<VectorType>(Val->getType())->getElementType());
367 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
368 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
369 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
370 } else if (isa<UndefValue>(Idx)) {
371 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
372 return const_cast<Constant*>(CVal->getOperand(0));
378 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
380 const Constant *Idx) {
381 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
383 APInt idxVal = CIdx->getValue();
384 if (isa<UndefValue>(Val)) {
385 // Insertion of scalar constant into packed undef
386 // Optimize away insertion of undef
387 if (isa<UndefValue>(Elt))
388 return const_cast<Constant*>(Val);
389 // Otherwise break the aggregate undef into multiple undefs and do
392 cast<VectorType>(Val->getType())->getNumElements();
393 std::vector<Constant*> Ops;
395 for (unsigned i = 0; i < numOps; ++i) {
397 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
398 Ops.push_back(const_cast<Constant*>(Op));
400 return ConstantVector::get(Ops);
402 if (isa<ConstantAggregateZero>(Val)) {
403 // Insertion of scalar constant into packed aggregate zero
404 // Optimize away insertion of zero
405 if (Elt->isNullValue())
406 return const_cast<Constant*>(Val);
407 // Otherwise break the aggregate zero into multiple zeros and do
410 cast<VectorType>(Val->getType())->getNumElements();
411 std::vector<Constant*> Ops;
413 for (unsigned i = 0; i < numOps; ++i) {
415 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
416 Ops.push_back(const_cast<Constant*>(Op));
418 return ConstantVector::get(Ops);
420 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
421 // Insertion of scalar constant into packed constant
422 std::vector<Constant*> Ops;
423 Ops.reserve(CVal->getNumOperands());
424 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
426 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
427 Ops.push_back(const_cast<Constant*>(Op));
429 return ConstantVector::get(Ops);
434 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
436 const Constant *Mask) {
441 /// EvalVectorOp - Given two packed constants and a function pointer, apply the
442 /// function pointer to each element pair, producing a new ConstantVector
444 static Constant *EvalVectorOp(const ConstantVector *V1,
445 const ConstantVector *V2,
446 Constant *(*FP)(Constant*, Constant*)) {
447 std::vector<Constant*> Res;
448 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
449 Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
450 const_cast<Constant*>(V2->getOperand(i))));
451 return ConstantVector::get(Res);
454 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
456 const Constant *C2) {
457 // Handle UndefValue up front
458 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
460 case Instruction::Add:
461 case Instruction::Sub:
462 case Instruction::Xor:
463 return UndefValue::get(C1->getType());
464 case Instruction::Mul:
465 case Instruction::And:
466 return Constant::getNullValue(C1->getType());
467 case Instruction::UDiv:
468 case Instruction::SDiv:
469 case Instruction::FDiv:
470 case Instruction::URem:
471 case Instruction::SRem:
472 case Instruction::FRem:
473 if (!isa<UndefValue>(C2)) // undef / X -> 0
474 return Constant::getNullValue(C1->getType());
475 return const_cast<Constant*>(C2); // X / undef -> undef
476 case Instruction::Or: // X | undef -> -1
477 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
478 return ConstantVector::getAllOnesValue(PTy);
479 return ConstantInt::getAllOnesValue(C1->getType());
480 case Instruction::LShr:
481 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
482 return const_cast<Constant*>(C1); // undef lshr undef -> undef
483 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
485 case Instruction::AShr:
486 if (!isa<UndefValue>(C2))
487 return const_cast<Constant*>(C1); // undef ashr X --> undef
488 else if (isa<UndefValue>(C1))
489 return const_cast<Constant*>(C1); // undef ashr undef -> undef
491 return const_cast<Constant*>(C1); // X ashr undef --> X
492 case Instruction::Shl:
493 // undef << X -> 0 or X << undef -> 0
494 return Constant::getNullValue(C1->getType());
498 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
499 if (isa<ConstantExpr>(C2)) {
500 // There are many possible foldings we could do here. We should probably
501 // at least fold add of a pointer with an integer into the appropriate
502 // getelementptr. This will improve alias analysis a bit.
504 // Just implement a couple of simple identities.
506 case Instruction::Add:
507 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
509 case Instruction::Sub:
510 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
512 case Instruction::Mul:
513 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
514 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
515 if (CI->equalsInt(1))
516 return const_cast<Constant*>(C1); // X * 1 == X
518 case Instruction::UDiv:
519 case Instruction::SDiv:
520 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
521 if (CI->equalsInt(1))
522 return const_cast<Constant*>(C1); // X / 1 == X
524 case Instruction::URem:
525 case Instruction::SRem:
526 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
527 if (CI->equalsInt(1))
528 return Constant::getNullValue(CI->getType()); // X % 1 == 0
530 case Instruction::And:
531 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
532 if (CI->isAllOnesValue())
533 return const_cast<Constant*>(C1); // X & -1 == X
534 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X & 0 == 0
535 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
536 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
538 // Functions are at least 4-byte aligned. If and'ing the address of a
539 // function with a constant < 4, fold it to zero.
540 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
541 if (CI->getValue().ult(APInt(CI->getType()->getBitWidth(),4)) &&
543 return Constant::getNullValue(CI->getType());
546 case Instruction::Or:
547 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
548 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
549 if (CI->isAllOnesValue())
550 return const_cast<Constant*>(C2); // X | -1 == -1
552 case Instruction::Xor:
553 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
557 } else if (isa<ConstantExpr>(C2)) {
558 // If C2 is a constant expr and C1 isn't, flop them around and fold the
559 // other way if possible.
561 case Instruction::Add:
562 case Instruction::Mul:
563 case Instruction::And:
564 case Instruction::Or:
565 case Instruction::Xor:
566 // No change of opcode required.
567 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
569 case Instruction::Shl:
570 case Instruction::LShr:
571 case Instruction::AShr:
572 case Instruction::Sub:
573 case Instruction::SDiv:
574 case Instruction::UDiv:
575 case Instruction::FDiv:
576 case Instruction::URem:
577 case Instruction::SRem:
578 case Instruction::FRem:
579 default: // These instructions cannot be flopped around.
584 // At this point we know neither constant is an UndefValue nor a ConstantExpr
585 // so look at directly computing the value.
586 if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
587 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
588 using namespace APIntOps;
589 APInt C1V = CI1->getValue();
590 APInt C2V = CI2->getValue();
594 case Instruction::Add:
595 return ConstantInt::get(C1->getType(), C1V + C2V);
596 case Instruction::Sub:
597 return ConstantInt::get(C1->getType(), C1V - C2V);
598 case Instruction::Mul:
599 return ConstantInt::get(C1->getType(), C1V * C2V);
600 case Instruction::UDiv:
601 if (CI2->isNullValue())
602 return 0; // X / 0 -> can't fold
603 return ConstantInt::get(C1->getType(), C1V.udiv(C2V));
604 case Instruction::SDiv:
605 if (CI2->isNullValue())
606 return 0; // X / 0 -> can't fold
607 return ConstantInt::get(C1->getType(), C1V.sdiv(C2V));
608 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
609 return 0; // MIN_INT / -1 -> overflow
610 return ConstantInt::get(C1->getType(), C1V.sdiv(C2V));
611 case Instruction::URem:
612 if (C2->isNullValue())
613 return 0; // X / 0 -> can't fold
614 return ConstantInt::get(C1->getType(), C1V.urem(C2V));
615 case Instruction::SRem:
616 if (CI2->isNullValue())
617 return 0; // X % 0 -> can't fold
618 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
619 return 0; // MIN_INT % -1 -> overflow
620 return ConstantInt::get(C1->getType(), C1V.srem(C2V));
621 case Instruction::And:
622 return ConstantInt::get(C1->getType(), C1V & C2V);
623 case Instruction::Or:
624 return ConstantInt::get(C1->getType(), C1V | C2V);
625 case Instruction::Xor:
626 return ConstantInt::get(C1->getType(), C1V ^ C2V);
627 case Instruction::Shl:
628 if (uint32_t shiftAmt = C2V.getZExtValue())
629 if (shiftAmt <= C1V.getBitWidth())
630 return ConstantInt::get(C1->getType(), C1V.shl(shiftAmt));
632 return UndefValue::get(C1->getType()); // too big shift is undef
633 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
634 case Instruction::LShr:
635 if (uint32_t shiftAmt = C2V.getZExtValue())
636 if (shiftAmt <= C1V.getBitWidth())
637 return ConstantInt::get(C1->getType(), C1V.lshr(shiftAmt));
639 return UndefValue::get(C1->getType()); // too big shift is undef
640 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
641 case Instruction::AShr:
642 if (uint32_t shiftAmt = C2V.getZExtValue())
643 if (shiftAmt <= C1V.getBitWidth())
644 return ConstantInt::get(C1->getType(), C1V.ashr(shiftAmt));
646 return UndefValue::get(C1->getType()); // too big shift is undef
647 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
650 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
651 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
652 double C1Val = CFP1->getValue();
653 double C2Val = CFP2->getValue();
657 case Instruction::Add:
658 return ConstantFP::get(CFP1->getType(), C1Val + C2Val);
659 case Instruction::Sub:
660 return ConstantFP::get(CFP1->getType(), C1Val - C2Val);
661 case Instruction::Mul:
662 return ConstantFP::get(CFP1->getType(), C1Val * C2Val);
663 case Instruction::FDiv:
664 if (CFP2->isExactlyValue(0.0))
665 return ConstantFP::get(CFP1->getType(),
666 std::numeric_limits<double>::infinity());
667 if (CFP2->isExactlyValue(-0.0))
668 return ConstantFP::get(CFP1->getType(),
669 -std::numeric_limits<double>::infinity());
670 return ConstantFP::get(CFP1->getType(), C1Val / C2Val);
671 case Instruction::FRem:
672 if (CFP2->isNullValue())
674 return ConstantFP::get(CFP1->getType(), std::fmod(C1Val, C2Val));
677 } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
678 if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
682 case Instruction::Add:
683 return EvalVectorOp(CP1, CP2, ConstantExpr::getAdd);
684 case Instruction::Sub:
685 return EvalVectorOp(CP1, CP2, ConstantExpr::getSub);
686 case Instruction::Mul:
687 return EvalVectorOp(CP1, CP2, ConstantExpr::getMul);
688 case Instruction::UDiv:
689 return EvalVectorOp(CP1, CP2, ConstantExpr::getUDiv);
690 case Instruction::SDiv:
691 return EvalVectorOp(CP1, CP2, ConstantExpr::getSDiv);
692 case Instruction::FDiv:
693 return EvalVectorOp(CP1, CP2, ConstantExpr::getFDiv);
694 case Instruction::URem:
695 return EvalVectorOp(CP1, CP2, ConstantExpr::getURem);
696 case Instruction::SRem:
697 return EvalVectorOp(CP1, CP2, ConstantExpr::getSRem);
698 case Instruction::FRem:
699 return EvalVectorOp(CP1, CP2, ConstantExpr::getFRem);
700 case Instruction::And:
701 return EvalVectorOp(CP1, CP2, ConstantExpr::getAnd);
702 case Instruction::Or:
703 return EvalVectorOp(CP1, CP2, ConstantExpr::getOr);
704 case Instruction::Xor:
705 return EvalVectorOp(CP1, CP2, ConstantExpr::getXor);
710 // We don't know how to fold this
714 /// isZeroSizedType - This type is zero sized if its an array or structure of
715 /// zero sized types. The only leaf zero sized type is an empty structure.
716 static bool isMaybeZeroSizedType(const Type *Ty) {
717 if (isa<OpaqueType>(Ty)) return true; // Can't say.
718 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
720 // If all of elements have zero size, this does too.
721 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
722 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
725 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
726 return isMaybeZeroSizedType(ATy->getElementType());
731 /// IdxCompare - Compare the two constants as though they were getelementptr
732 /// indices. This allows coersion of the types to be the same thing.
734 /// If the two constants are the "same" (after coersion), return 0. If the
735 /// first is less than the second, return -1, if the second is less than the
736 /// first, return 1. If the constants are not integral, return -2.
738 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
739 if (C1 == C2) return 0;
741 // Ok, we found a different index. If they are not ConstantInt, we can't do
742 // anything with them.
743 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
744 return -2; // don't know!
746 // Ok, we have two differing integer indices. Sign extend them to be the same
747 // type. Long is always big enough, so we use it.
748 if (C1->getType() != Type::Int64Ty)
749 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
751 if (C2->getType() != Type::Int64Ty)
752 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
754 if (C1 == C2) return 0; // They are equal
756 // If the type being indexed over is really just a zero sized type, there is
757 // no pointer difference being made here.
758 if (isMaybeZeroSizedType(ElTy))
761 // If they are really different, now that they are the same type, then we
762 // found a difference!
763 if (cast<ConstantInt>(C1)->getSExtValue() <
764 cast<ConstantInt>(C2)->getSExtValue())
770 /// evaluateFCmpRelation - This function determines if there is anything we can
771 /// decide about the two constants provided. This doesn't need to handle simple
772 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
773 /// If we can determine that the two constants have a particular relation to
774 /// each other, we should return the corresponding FCmpInst predicate,
775 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
776 /// ConstantFoldCompareInstruction.
778 /// To simplify this code we canonicalize the relation so that the first
779 /// operand is always the most "complex" of the two. We consider ConstantFP
780 /// to be the simplest, and ConstantExprs to be the most complex.
781 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
782 const Constant *V2) {
783 assert(V1->getType() == V2->getType() &&
784 "Cannot compare values of different types!");
785 // Handle degenerate case quickly
786 if (V1 == V2) return FCmpInst::FCMP_OEQ;
788 if (!isa<ConstantExpr>(V1)) {
789 if (!isa<ConstantExpr>(V2)) {
790 // We distilled thisUse the standard constant folder for a few cases
792 Constant *C1 = const_cast<Constant*>(V1);
793 Constant *C2 = const_cast<Constant*>(V2);
794 R = dyn_cast<ConstantInt>(
795 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
796 if (R && !R->isNullValue())
797 return FCmpInst::FCMP_OEQ;
798 R = dyn_cast<ConstantInt>(
799 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
800 if (R && !R->isNullValue())
801 return FCmpInst::FCMP_OLT;
802 R = dyn_cast<ConstantInt>(
803 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
804 if (R && !R->isNullValue())
805 return FCmpInst::FCMP_OGT;
807 // Nothing more we can do
808 return FCmpInst::BAD_FCMP_PREDICATE;
811 // If the first operand is simple and second is ConstantExpr, swap operands.
812 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
813 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
814 return FCmpInst::getSwappedPredicate(SwappedRelation);
816 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
817 // constantexpr or a simple constant.
818 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
819 switch (CE1->getOpcode()) {
820 case Instruction::FPTrunc:
821 case Instruction::FPExt:
822 case Instruction::UIToFP:
823 case Instruction::SIToFP:
824 // We might be able to do something with these but we don't right now.
830 // There are MANY other foldings that we could perform here. They will
831 // probably be added on demand, as they seem needed.
832 return FCmpInst::BAD_FCMP_PREDICATE;
835 /// evaluateICmpRelation - This function determines if there is anything we can
836 /// decide about the two constants provided. This doesn't need to handle simple
837 /// things like integer comparisons, but should instead handle ConstantExprs
838 /// and GlobalValues. If we can determine that the two constants have a
839 /// particular relation to each other, we should return the corresponding ICmp
840 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
842 /// To simplify this code we canonicalize the relation so that the first
843 /// operand is always the most "complex" of the two. We consider simple
844 /// constants (like ConstantInt) to be the simplest, followed by
845 /// GlobalValues, followed by ConstantExpr's (the most complex).
847 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
850 assert(V1->getType() == V2->getType() &&
851 "Cannot compare different types of values!");
852 if (V1 == V2) return ICmpInst::ICMP_EQ;
854 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
855 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
856 // We distilled this down to a simple case, use the standard constant
859 Constant *C1 = const_cast<Constant*>(V1);
860 Constant *C2 = const_cast<Constant*>(V2);
861 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
862 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
863 if (R && !R->isNullValue())
865 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
866 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
867 if (R && !R->isNullValue())
869 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
870 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
871 if (R && !R->isNullValue())
874 // If we couldn't figure it out, bail.
875 return ICmpInst::BAD_ICMP_PREDICATE;
878 // If the first operand is simple, swap operands.
879 ICmpInst::Predicate SwappedRelation =
880 evaluateICmpRelation(V2, V1, isSigned);
881 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
882 return ICmpInst::getSwappedPredicate(SwappedRelation);
884 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
885 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
886 ICmpInst::Predicate SwappedRelation =
887 evaluateICmpRelation(V2, V1, isSigned);
888 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
889 return ICmpInst::getSwappedPredicate(SwappedRelation);
891 return ICmpInst::BAD_ICMP_PREDICATE;
894 // Now we know that the RHS is a GlobalValue or simple constant,
895 // which (since the types must match) means that it's a ConstantPointerNull.
896 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
897 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
898 return ICmpInst::ICMP_NE;
900 // GlobalVals can never be null.
901 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
902 if (!CPR1->hasExternalWeakLinkage())
903 return ICmpInst::ICMP_NE;
906 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
907 // constantexpr, a CPR, or a simple constant.
908 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
909 const Constant *CE1Op0 = CE1->getOperand(0);
911 switch (CE1->getOpcode()) {
912 case Instruction::Trunc:
913 case Instruction::FPTrunc:
914 case Instruction::FPExt:
915 case Instruction::FPToUI:
916 case Instruction::FPToSI:
917 break; // We can't evaluate floating point casts or truncations.
919 case Instruction::UIToFP:
920 case Instruction::SIToFP:
921 case Instruction::IntToPtr:
922 case Instruction::BitCast:
923 case Instruction::ZExt:
924 case Instruction::SExt:
925 case Instruction::PtrToInt:
926 // If the cast is not actually changing bits, and the second operand is a
927 // null pointer, do the comparison with the pre-casted value.
928 if (V2->isNullValue() &&
929 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
930 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
931 (CE1->getOpcode() == Instruction::SExt ? true :
932 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
933 return evaluateICmpRelation(
934 CE1Op0, Constant::getNullValue(CE1Op0->getType()), sgnd);
937 // If the dest type is a pointer type, and the RHS is a constantexpr cast
938 // from the same type as the src of the LHS, evaluate the inputs. This is
939 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
940 // which happens a lot in compilers with tagged integers.
941 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
942 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
943 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
944 CE1->getOperand(0)->getType()->isInteger()) {
945 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
946 (CE1->getOpcode() == Instruction::SExt ? true :
947 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
948 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
953 case Instruction::GetElementPtr:
954 // Ok, since this is a getelementptr, we know that the constant has a
955 // pointer type. Check the various cases.
956 if (isa<ConstantPointerNull>(V2)) {
957 // If we are comparing a GEP to a null pointer, check to see if the base
958 // of the GEP equals the null pointer.
959 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
960 if (GV->hasExternalWeakLinkage())
961 // Weak linkage GVals could be zero or not. We're comparing that
962 // to null pointer so its greater-or-equal
963 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
965 // If its not weak linkage, the GVal must have a non-zero address
966 // so the result is greater-than
967 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
968 } else if (isa<ConstantPointerNull>(CE1Op0)) {
969 // If we are indexing from a null pointer, check to see if we have any
971 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
972 if (!CE1->getOperand(i)->isNullValue())
973 // Offsetting from null, must not be equal.
974 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
975 // Only zero indexes from null, must still be zero.
976 return ICmpInst::ICMP_EQ;
978 // Otherwise, we can't really say if the first operand is null or not.
979 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
980 if (isa<ConstantPointerNull>(CE1Op0)) {
981 if (CPR2->hasExternalWeakLinkage())
982 // Weak linkage GVals could be zero or not. We're comparing it to
983 // a null pointer, so its less-or-equal
984 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
986 // If its not weak linkage, the GVal must have a non-zero address
987 // so the result is less-than
988 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
989 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
991 // If this is a getelementptr of the same global, then it must be
992 // different. Because the types must match, the getelementptr could
993 // only have at most one index, and because we fold getelementptr's
994 // with a single zero index, it must be nonzero.
995 assert(CE1->getNumOperands() == 2 &&
996 !CE1->getOperand(1)->isNullValue() &&
997 "Suprising getelementptr!");
998 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1000 // If they are different globals, we don't know what the value is,
1001 // but they can't be equal.
1002 return ICmpInst::ICMP_NE;
1006 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1007 const Constant *CE2Op0 = CE2->getOperand(0);
1009 // There are MANY other foldings that we could perform here. They will
1010 // probably be added on demand, as they seem needed.
1011 switch (CE2->getOpcode()) {
1013 case Instruction::GetElementPtr:
1014 // By far the most common case to handle is when the base pointers are
1015 // obviously to the same or different globals.
1016 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1017 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1018 return ICmpInst::ICMP_NE;
1019 // Ok, we know that both getelementptr instructions are based on the
1020 // same global. From this, we can precisely determine the relative
1021 // ordering of the resultant pointers.
1024 // Compare all of the operands the GEP's have in common.
1025 gep_type_iterator GTI = gep_type_begin(CE1);
1026 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1028 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1029 GTI.getIndexedType())) {
1030 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1031 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1032 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1035 // Ok, we ran out of things they have in common. If any leftovers
1036 // are non-zero then we have a difference, otherwise we are equal.
1037 for (; i < CE1->getNumOperands(); ++i)
1038 if (!CE1->getOperand(i)->isNullValue())
1039 if (isa<ConstantInt>(CE1->getOperand(i)))
1040 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1042 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1044 for (; i < CE2->getNumOperands(); ++i)
1045 if (!CE2->getOperand(i)->isNullValue())
1046 if (isa<ConstantInt>(CE2->getOperand(i)))
1047 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1049 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1050 return ICmpInst::ICMP_EQ;
1059 return ICmpInst::BAD_ICMP_PREDICATE;
1062 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1064 const Constant *C2) {
1066 // Handle some degenerate cases first
1067 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1068 return UndefValue::get(Type::Int1Ty);
1070 // icmp eq/ne(null,GV) -> false/true
1071 if (C1->isNullValue()) {
1072 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1073 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1074 if (pred == ICmpInst::ICMP_EQ)
1075 return ConstantInt::getFalse();
1076 else if (pred == ICmpInst::ICMP_NE)
1077 return ConstantInt::getTrue();
1078 // icmp eq/ne(GV,null) -> false/true
1079 } else if (C2->isNullValue()) {
1080 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1081 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1082 if (pred == ICmpInst::ICMP_EQ)
1083 return ConstantInt::getFalse();
1084 else if (pred == ICmpInst::ICMP_NE)
1085 return ConstantInt::getTrue();
1088 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1089 APInt V1 = cast<ConstantInt>(C1)->getValue();
1090 APInt V2 = cast<ConstantInt>(C2)->getValue();
1092 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1093 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1094 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1095 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1096 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1097 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1098 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1099 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1100 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1101 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1102 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1104 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1105 double C1Val = cast<ConstantFP>(C1)->getValue();
1106 double C2Val = cast<ConstantFP>(C2)->getValue();
1108 default: assert(0 && "Invalid FCmp Predicate"); return 0;
1109 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1110 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
1111 case FCmpInst::FCMP_UNO:
1112 return ConstantInt::get(Type::Int1Ty, C1Val != C1Val || C2Val != C2Val);
1113 case FCmpInst::FCMP_ORD:
1114 return ConstantInt::get(Type::Int1Ty, C1Val == C1Val && C2Val == C2Val);
1115 case FCmpInst::FCMP_UEQ:
1116 if (C1Val != C1Val || C2Val != C2Val)
1117 return ConstantInt::getTrue();
1119 case FCmpInst::FCMP_OEQ:
1120 return ConstantInt::get(Type::Int1Ty, C1Val == C2Val);
1121 case FCmpInst::FCMP_UNE:
1122 if (C1Val != C1Val || C2Val != C2Val)
1123 return ConstantInt::getTrue();
1125 case FCmpInst::FCMP_ONE:
1126 return ConstantInt::get(Type::Int1Ty, C1Val != C2Val);
1127 case FCmpInst::FCMP_ULT:
1128 if (C1Val != C1Val || C2Val != C2Val)
1129 return ConstantInt::getTrue();
1131 case FCmpInst::FCMP_OLT:
1132 return ConstantInt::get(Type::Int1Ty, C1Val < C2Val);
1133 case FCmpInst::FCMP_UGT:
1134 if (C1Val != C1Val || C2Val != C2Val)
1135 return ConstantInt::getTrue();
1137 case FCmpInst::FCMP_OGT:
1138 return ConstantInt::get(Type::Int1Ty, C1Val > C2Val);
1139 case FCmpInst::FCMP_ULE:
1140 if (C1Val != C1Val || C2Val != C2Val)
1141 return ConstantInt::getTrue();
1143 case FCmpInst::FCMP_OLE:
1144 return ConstantInt::get(Type::Int1Ty, C1Val <= C2Val);
1145 case FCmpInst::FCMP_UGE:
1146 if (C1Val != C1Val || C2Val != C2Val)
1147 return ConstantInt::getTrue();
1149 case FCmpInst::FCMP_OGE:
1150 return ConstantInt::get(Type::Int1Ty, C1Val >= C2Val);
1152 } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1153 if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1154 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1155 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1156 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1157 const_cast<Constant*>(CP1->getOperand(i)),
1158 const_cast<Constant*>(CP2->getOperand(i)));
1159 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1162 // Otherwise, could not decide from any element pairs.
1164 } else if (pred == ICmpInst::ICMP_EQ) {
1165 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1166 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1167 const_cast<Constant*>(CP1->getOperand(i)),
1168 const_cast<Constant*>(CP2->getOperand(i)));
1169 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1172 // Otherwise, could not decide from any element pairs.
1178 if (C1->getType()->isFloatingPoint()) {
1179 switch (evaluateFCmpRelation(C1, C2)) {
1180 default: assert(0 && "Unknown relation!");
1181 case FCmpInst::FCMP_UNO:
1182 case FCmpInst::FCMP_ORD:
1183 case FCmpInst::FCMP_UEQ:
1184 case FCmpInst::FCMP_UNE:
1185 case FCmpInst::FCMP_ULT:
1186 case FCmpInst::FCMP_UGT:
1187 case FCmpInst::FCMP_ULE:
1188 case FCmpInst::FCMP_UGE:
1189 case FCmpInst::FCMP_TRUE:
1190 case FCmpInst::FCMP_FALSE:
1191 case FCmpInst::BAD_FCMP_PREDICATE:
1192 break; // Couldn't determine anything about these constants.
1193 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1194 return ConstantInt::get(Type::Int1Ty,
1195 pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1196 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1197 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1198 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1199 return ConstantInt::get(Type::Int1Ty,
1200 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1201 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1202 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1203 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1204 return ConstantInt::get(Type::Int1Ty,
1205 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1206 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1207 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1208 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1209 // We can only partially decide this relation.
1210 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1211 return ConstantInt::getFalse();
1212 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1213 return ConstantInt::getTrue();
1215 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1216 // We can only partially decide this relation.
1217 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1218 return ConstantInt::getFalse();
1219 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1220 return ConstantInt::getTrue();
1222 case ICmpInst::ICMP_NE: // We know that C1 != C2
1223 // We can only partially decide this relation.
1224 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1225 return ConstantInt::getFalse();
1226 if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1227 return ConstantInt::getTrue();
1231 // Evaluate the relation between the two constants, per the predicate.
1232 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1233 default: assert(0 && "Unknown relational!");
1234 case ICmpInst::BAD_ICMP_PREDICATE:
1235 break; // Couldn't determine anything about these constants.
1236 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1237 // If we know the constants are equal, we can decide the result of this
1238 // computation precisely.
1239 return ConstantInt::get(Type::Int1Ty,
1240 pred == ICmpInst::ICMP_EQ ||
1241 pred == ICmpInst::ICMP_ULE ||
1242 pred == ICmpInst::ICMP_SLE ||
1243 pred == ICmpInst::ICMP_UGE ||
1244 pred == ICmpInst::ICMP_SGE);
1245 case ICmpInst::ICMP_ULT:
1246 // If we know that C1 < C2, we can decide the result of this computation
1248 return ConstantInt::get(Type::Int1Ty,
1249 pred == ICmpInst::ICMP_ULT ||
1250 pred == ICmpInst::ICMP_NE ||
1251 pred == ICmpInst::ICMP_ULE);
1252 case ICmpInst::ICMP_SLT:
1253 // If we know that C1 < C2, we can decide the result of this computation
1255 return ConstantInt::get(Type::Int1Ty,
1256 pred == ICmpInst::ICMP_SLT ||
1257 pred == ICmpInst::ICMP_NE ||
1258 pred == ICmpInst::ICMP_SLE);
1259 case ICmpInst::ICMP_UGT:
1260 // If we know that C1 > C2, we can decide the result of this computation
1262 return ConstantInt::get(Type::Int1Ty,
1263 pred == ICmpInst::ICMP_UGT ||
1264 pred == ICmpInst::ICMP_NE ||
1265 pred == ICmpInst::ICMP_UGE);
1266 case ICmpInst::ICMP_SGT:
1267 // If we know that C1 > C2, we can decide the result of this computation
1269 return ConstantInt::get(Type::Int1Ty,
1270 pred == ICmpInst::ICMP_SGT ||
1271 pred == ICmpInst::ICMP_NE ||
1272 pred == ICmpInst::ICMP_SGE);
1273 case ICmpInst::ICMP_ULE:
1274 // If we know that C1 <= C2, we can only partially decide this relation.
1275 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1276 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1278 case ICmpInst::ICMP_SLE:
1279 // If we know that C1 <= C2, we can only partially decide this relation.
1280 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1281 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1284 case ICmpInst::ICMP_UGE:
1285 // If we know that C1 >= C2, we can only partially decide this relation.
1286 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1287 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1289 case ICmpInst::ICMP_SGE:
1290 // If we know that C1 >= C2, we can only partially decide this relation.
1291 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1292 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1295 case ICmpInst::ICMP_NE:
1296 // If we know that C1 != C2, we can only partially decide this relation.
1297 if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1298 if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1302 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1303 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1304 // other way if possible.
1306 case ICmpInst::ICMP_EQ:
1307 case ICmpInst::ICMP_NE:
1308 // No change of predicate required.
1309 return ConstantFoldCompareInstruction(pred, C2, C1);
1311 case ICmpInst::ICMP_ULT:
1312 case ICmpInst::ICMP_SLT:
1313 case ICmpInst::ICMP_UGT:
1314 case ICmpInst::ICMP_SGT:
1315 case ICmpInst::ICMP_ULE:
1316 case ICmpInst::ICMP_SLE:
1317 case ICmpInst::ICMP_UGE:
1318 case ICmpInst::ICMP_SGE:
1319 // Change the predicate as necessary to swap the operands.
1320 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1321 return ConstantFoldCompareInstruction(pred, C2, C1);
1323 default: // These predicates cannot be flopped around.
1331 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1332 Constant* const *Idxs,
1335 (NumIdx == 1 && Idxs[0]->isNullValue()))
1336 return const_cast<Constant*>(C);
1338 if (isa<UndefValue>(C)) {
1339 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1340 (Value**)Idxs, NumIdx,
1342 assert(Ty != 0 && "Invalid indices for GEP!");
1343 return UndefValue::get(PointerType::get(Ty));
1346 Constant *Idx0 = Idxs[0];
1347 if (C->isNullValue()) {
1349 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1350 if (!Idxs[i]->isNullValue()) {
1355 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1356 (Value**)Idxs, NumIdx,
1358 assert(Ty != 0 && "Invalid indices for GEP!");
1359 return ConstantPointerNull::get(PointerType::get(Ty));
1363 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1364 // Combine Indices - If the source pointer to this getelementptr instruction
1365 // is a getelementptr instruction, combine the indices of the two
1366 // getelementptr instructions into a single instruction.
1368 if (CE->getOpcode() == Instruction::GetElementPtr) {
1369 const Type *LastTy = 0;
1370 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1374 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1375 SmallVector<Value*, 16> NewIndices;
1376 NewIndices.reserve(NumIdx + CE->getNumOperands());
1377 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1378 NewIndices.push_back(CE->getOperand(i));
1380 // Add the last index of the source with the first index of the new GEP.
1381 // Make sure to handle the case when they are actually different types.
1382 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1383 // Otherwise it must be an array.
1384 if (!Idx0->isNullValue()) {
1385 const Type *IdxTy = Combined->getType();
1386 if (IdxTy != Idx0->getType()) {
1387 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1388 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1390 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1393 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1397 NewIndices.push_back(Combined);
1398 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1399 return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1404 // Implement folding of:
1405 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1407 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1409 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue())
1410 if (const PointerType *SPT =
1411 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1412 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1413 if (const ArrayType *CAT =
1414 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1415 if (CAT->getElementType() == SAT->getElementType())
1416 return ConstantExpr::getGetElementPtr(
1417 (Constant*)CE->getOperand(0), Idxs, NumIdx);