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 // 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/GlobalAlias.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MathExtras.h"
35 //===----------------------------------------------------------------------===//
36 // ConstantFold*Instruction Implementations
37 //===----------------------------------------------------------------------===//
39 /// BitCastConstantVector - Convert the specified ConstantVector node to the
40 /// specified vector type. At this point, we know that the elements of the
41 /// input vector constant are all simple integer or FP values.
42 static Constant *BitCastConstantVector(ConstantVector *CV,
43 const VectorType *DstTy) {
44 // If this cast changes element count then we can't handle it here:
45 // doing so requires endianness information. This should be handled by
46 // Analysis/ConstantFolding.cpp
47 unsigned NumElts = DstTy->getNumElements();
48 if (NumElts != CV->getNumOperands())
51 // Check to verify that all elements of the input are simple.
52 for (unsigned i = 0; i != NumElts; ++i) {
53 if (!isa<ConstantInt>(CV->getOperand(i)) &&
54 !isa<ConstantFP>(CV->getOperand(i)))
58 // Bitcast each element now.
59 std::vector<Constant*> Result;
60 const Type *DstEltTy = DstTy->getElementType();
61 for (unsigned i = 0; i != NumElts; ++i)
62 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
63 return ConstantVector::get(Result);
66 /// This function determines which opcode to use to fold two constant cast
67 /// expressions together. It uses CastInst::isEliminableCastPair to determine
68 /// the opcode. Consequently its just a wrapper around that function.
69 /// @brief Determine if it is valid to fold a cast of a cast
72 unsigned opc, ///< opcode of the second cast constant expression
73 const ConstantExpr*Op, ///< the first cast constant expression
74 const Type *DstTy ///< desintation type of the first cast
76 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
77 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
78 assert(CastInst::isCast(opc) && "Invalid cast opcode");
80 // The the types and opcodes for the two Cast constant expressions
81 const Type *SrcTy = Op->getOperand(0)->getType();
82 const Type *MidTy = Op->getType();
83 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
84 Instruction::CastOps secondOp = Instruction::CastOps(opc);
86 // Let CastInst::isEliminableCastPair do the heavy lifting.
87 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
91 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
92 const Type *SrcTy = V->getType();
94 return V; // no-op cast
96 // Check to see if we are casting a pointer to an aggregate to a pointer to
97 // the first element. If so, return the appropriate GEP instruction.
98 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
99 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
100 if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
101 SmallVector<Value*, 8> IdxList;
102 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
103 const Type *ElTy = PTy->getElementType();
104 while (ElTy != DPTy->getElementType()) {
105 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
106 if (STy->getNumElements() == 0) break;
107 ElTy = STy->getElementType(0);
108 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
109 } else if (const SequentialType *STy =
110 dyn_cast<SequentialType>(ElTy)) {
111 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
112 ElTy = STy->getElementType();
113 IdxList.push_back(IdxList[0]);
119 if (ElTy == DPTy->getElementType())
120 return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
123 // Handle casts from one vector constant to another. We know that the src
124 // and dest type have the same size (otherwise its an illegal cast).
125 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
126 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
127 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
128 "Not cast between same sized vectors!");
129 // First, check for null. Undef is already handled.
130 if (isa<ConstantAggregateZero>(V))
131 return Constant::getNullValue(DestTy);
133 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
134 return BitCastConstantVector(CV, DestPTy);
138 // Finally, implement bitcast folding now. The code below doesn't handle
140 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
141 return ConstantPointerNull::get(cast<PointerType>(DestTy));
143 // Handle integral constant input.
144 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
145 if (DestTy->isInteger())
146 // Integral -> Integral. This is a no-op because the bit widths must
147 // be the same. Consequently, we just fold to V.
150 if (DestTy->isFloatingPoint()) {
151 assert((DestTy == Type::DoubleTy || DestTy == Type::FloatTy) &&
153 return ConstantFP::get(APFloat(CI->getValue()));
155 // Otherwise, can't fold this (vector?)
159 // Handle ConstantFP input.
160 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
162 if (DestTy == Type::Int32Ty) {
163 return ConstantInt::get(FP->getValueAPF().bitcastToAPInt());
165 assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
166 return ConstantInt::get(FP->getValueAPF().bitcastToAPInt());
173 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
174 const Type *DestTy) {
175 if (isa<UndefValue>(V)) {
176 // zext(undef) = 0, because the top bits will be zero.
177 // sext(undef) = 0, because the top bits will all be the same.
178 // [us]itofp(undef) = 0, because the result value is bounded.
179 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
180 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
181 return Constant::getNullValue(DestTy);
182 return UndefValue::get(DestTy);
184 // No compile-time operations on this type yet.
185 if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
188 // If the cast operand is a constant expression, there's a few things we can
189 // do to try to simplify it.
190 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
192 // Try hard to fold cast of cast because they are often eliminable.
193 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
194 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
195 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
196 // If all of the indexes in the GEP are null values, there is no pointer
197 // adjustment going on. We might as well cast the source pointer.
198 bool isAllNull = true;
199 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
200 if (!CE->getOperand(i)->isNullValue()) {
205 // This is casting one pointer type to another, always BitCast
206 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
210 // We actually have to do a cast now. Perform the cast according to the
213 case Instruction::FPTrunc:
214 case Instruction::FPExt:
215 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
217 APFloat Val = FPC->getValueAPF();
218 Val.convert(DestTy == Type::FloatTy ? APFloat::IEEEsingle :
219 DestTy == Type::DoubleTy ? APFloat::IEEEdouble :
220 DestTy == Type::X86_FP80Ty ? APFloat::x87DoubleExtended :
221 DestTy == Type::FP128Ty ? APFloat::IEEEquad :
223 APFloat::rmNearestTiesToEven, &ignored);
224 return ConstantFP::get(Val);
226 return 0; // Can't fold.
227 case Instruction::FPToUI:
228 case Instruction::FPToSI:
229 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
230 const APFloat &V = FPC->getValueAPF();
233 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
234 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
235 APFloat::rmTowardZero, &ignored);
236 APInt Val(DestBitWidth, 2, x);
237 return ConstantInt::get(Val);
239 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
240 std::vector<Constant*> res;
241 const VectorType *DestVecTy = cast<VectorType>(DestTy);
242 const Type *DstEltTy = DestVecTy->getElementType();
243 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
244 res.push_back(ConstantExpr::getCast(opc, CV->getOperand(i), DstEltTy));
245 return ConstantVector::get(DestVecTy, res);
247 return 0; // Can't fold.
248 case Instruction::IntToPtr: //always treated as unsigned
249 if (V->isNullValue()) // Is it an integral null value?
250 return ConstantPointerNull::get(cast<PointerType>(DestTy));
251 return 0; // Other pointer types cannot be casted
252 case Instruction::PtrToInt: // always treated as unsigned
253 if (V->isNullValue()) // is it a null pointer value?
254 return ConstantInt::get(DestTy, 0);
255 return 0; // Other pointer types cannot be casted
256 case Instruction::UIToFP:
257 case Instruction::SIToFP:
258 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
259 APInt api = CI->getValue();
260 const uint64_t zero[] = {0, 0};
261 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
263 (void)apf.convertFromAPInt(api,
264 opc==Instruction::SIToFP,
265 APFloat::rmNearestTiesToEven);
266 return ConstantFP::get(apf);
268 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
269 std::vector<Constant*> res;
270 const VectorType *DestVecTy = cast<VectorType>(DestTy);
271 const Type *DstEltTy = DestVecTy->getElementType();
272 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
273 res.push_back(ConstantExpr::getCast(opc, CV->getOperand(i), DstEltTy));
274 return ConstantVector::get(DestVecTy, res);
277 case Instruction::ZExt:
278 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
279 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
280 APInt Result(CI->getValue());
281 Result.zext(BitWidth);
282 return ConstantInt::get(Result);
285 case Instruction::SExt:
286 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
287 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
288 APInt Result(CI->getValue());
289 Result.sext(BitWidth);
290 return ConstantInt::get(Result);
293 case Instruction::Trunc:
294 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
295 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
296 APInt Result(CI->getValue());
297 Result.trunc(BitWidth);
298 return ConstantInt::get(Result);
301 case Instruction::BitCast:
302 return FoldBitCast(const_cast<Constant*>(V), DestTy);
304 assert(!"Invalid CE CastInst opcode");
308 assert(0 && "Failed to cast constant expression");
312 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
314 const Constant *V2) {
315 if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
316 return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
318 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
319 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
320 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
321 if (V1 == V2) return const_cast<Constant*>(V1);
325 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
326 const Constant *Idx) {
327 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
328 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
329 if (Val->isNullValue()) // ee(zero, x) -> zero
330 return Constant::getNullValue(
331 cast<VectorType>(Val->getType())->getElementType());
333 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
334 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
335 return CVal->getOperand(CIdx->getZExtValue());
336 } else if (isa<UndefValue>(Idx)) {
337 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
338 return CVal->getOperand(0);
344 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
346 const Constant *Idx) {
347 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
349 APInt idxVal = CIdx->getValue();
350 if (isa<UndefValue>(Val)) {
351 // Insertion of scalar constant into vector undef
352 // Optimize away insertion of undef
353 if (isa<UndefValue>(Elt))
354 return const_cast<Constant*>(Val);
355 // Otherwise break the aggregate undef into multiple undefs and do
358 cast<VectorType>(Val->getType())->getNumElements();
359 std::vector<Constant*> Ops;
361 for (unsigned i = 0; i < numOps; ++i) {
363 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
364 Ops.push_back(const_cast<Constant*>(Op));
366 return ConstantVector::get(Ops);
368 if (isa<ConstantAggregateZero>(Val)) {
369 // Insertion of scalar constant into vector aggregate zero
370 // Optimize away insertion of zero
371 if (Elt->isNullValue())
372 return const_cast<Constant*>(Val);
373 // Otherwise break the aggregate zero into multiple zeros and do
376 cast<VectorType>(Val->getType())->getNumElements();
377 std::vector<Constant*> Ops;
379 for (unsigned i = 0; i < numOps; ++i) {
381 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
382 Ops.push_back(const_cast<Constant*>(Op));
384 return ConstantVector::get(Ops);
386 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
387 // Insertion of scalar constant into vector constant
388 std::vector<Constant*> Ops;
389 Ops.reserve(CVal->getNumOperands());
390 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
392 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
393 Ops.push_back(const_cast<Constant*>(Op));
395 return ConstantVector::get(Ops);
401 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
402 /// return the specified element value. Otherwise return null.
403 static Constant *GetVectorElement(const Constant *C, unsigned EltNo) {
404 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C))
405 return CV->getOperand(EltNo);
407 const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
408 if (isa<ConstantAggregateZero>(C))
409 return Constant::getNullValue(EltTy);
410 if (isa<UndefValue>(C))
411 return UndefValue::get(EltTy);
415 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
417 const Constant *Mask) {
418 // Undefined shuffle mask -> undefined value.
419 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
421 unsigned NumElts = cast<VectorType>(V1->getType())->getNumElements();
422 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
424 // Loop over the shuffle mask, evaluating each element.
425 SmallVector<Constant*, 32> Result;
426 for (unsigned i = 0; i != NumElts; ++i) {
427 Constant *InElt = GetVectorElement(Mask, i);
428 if (InElt == 0) return 0;
430 if (isa<UndefValue>(InElt))
431 InElt = UndefValue::get(EltTy);
432 else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
433 unsigned Elt = CI->getZExtValue();
434 if (Elt >= NumElts*2)
435 InElt = UndefValue::get(EltTy);
436 else if (Elt >= NumElts)
437 InElt = GetVectorElement(V2, Elt-NumElts);
439 InElt = GetVectorElement(V1, Elt);
440 if (InElt == 0) return 0;
445 Result.push_back(InElt);
448 return ConstantVector::get(&Result[0], Result.size());
451 Constant *llvm::ConstantFoldExtractValueInstruction(const Constant *Agg,
452 const unsigned *Idxs,
454 // Base case: no indices, so return the entire value.
456 return const_cast<Constant *>(Agg);
458 if (isa<UndefValue>(Agg)) // ev(undef, x) -> undef
459 return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
463 if (isa<ConstantAggregateZero>(Agg)) // ev(0, x) -> 0
465 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
469 // Otherwise recurse.
470 return ConstantFoldExtractValueInstruction(Agg->getOperand(*Idxs),
474 Constant *llvm::ConstantFoldInsertValueInstruction(const Constant *Agg,
476 const unsigned *Idxs,
478 // Base case: no indices, so replace the entire value.
480 return const_cast<Constant *>(Val);
482 if (isa<UndefValue>(Agg)) {
483 // Insertion of constant into aggregate undef
484 // Optimize away insertion of undef
485 if (isa<UndefValue>(Val))
486 return const_cast<Constant*>(Agg);
487 // Otherwise break the aggregate undef into multiple undefs and do
489 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
491 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
492 numOps = AR->getNumElements();
494 numOps = cast<StructType>(AggTy)->getNumElements();
495 std::vector<Constant*> Ops(numOps);
496 for (unsigned i = 0; i < numOps; ++i) {
497 const Type *MemberTy = AggTy->getTypeAtIndex(i);
500 ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
501 Val, Idxs+1, NumIdx-1) :
502 UndefValue::get(MemberTy);
503 Ops[i] = const_cast<Constant*>(Op);
505 if (isa<StructType>(AggTy))
506 return ConstantStruct::get(Ops);
508 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
510 if (isa<ConstantAggregateZero>(Agg)) {
511 // Insertion of constant into aggregate zero
512 // Optimize away insertion of zero
513 if (Val->isNullValue())
514 return const_cast<Constant*>(Agg);
515 // Otherwise break the aggregate zero into multiple zeros and do
517 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
519 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
520 numOps = AR->getNumElements();
522 numOps = cast<StructType>(AggTy)->getNumElements();
523 std::vector<Constant*> Ops(numOps);
524 for (unsigned i = 0; i < numOps; ++i) {
525 const Type *MemberTy = AggTy->getTypeAtIndex(i);
528 ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
529 Val, Idxs+1, NumIdx-1) :
530 Constant::getNullValue(MemberTy);
531 Ops[i] = const_cast<Constant*>(Op);
533 if (isa<StructType>(AggTy))
534 return ConstantStruct::get(Ops);
536 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
538 if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
539 // Insertion of constant into aggregate constant
540 std::vector<Constant*> Ops(Agg->getNumOperands());
541 for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
544 ConstantFoldInsertValueInstruction(Agg->getOperand(i),
545 Val, Idxs+1, NumIdx-1) :
547 Ops[i] = const_cast<Constant*>(Op);
550 if (isa<StructType>(Agg->getType()))
551 C = ConstantStruct::get(Ops);
553 C = ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
560 /// EvalVectorOp - Given two vector constants and a function pointer, apply the
561 /// function pointer to each element pair, producing a new ConstantVector
562 /// constant. Either or both of V1 and V2 may be NULL, meaning a
563 /// ConstantAggregateZero operand.
564 static Constant *EvalVectorOp(const ConstantVector *V1,
565 const ConstantVector *V2,
566 const VectorType *VTy,
567 Constant *(*FP)(Constant*, Constant*)) {
568 std::vector<Constant*> Res;
569 const Type *EltTy = VTy->getElementType();
570 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
571 const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
572 const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
573 Res.push_back(FP(const_cast<Constant*>(C1),
574 const_cast<Constant*>(C2)));
576 return ConstantVector::get(Res);
579 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
581 const Constant *C2) {
582 // No compile-time operations on this type yet.
583 if (C1->getType() == Type::PPC_FP128Ty)
586 // Handle UndefValue up front
587 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
589 case Instruction::Xor:
590 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
591 // Handle undef ^ undef -> 0 special case. This is a common
593 return Constant::getNullValue(C1->getType());
595 case Instruction::Add:
596 case Instruction::Sub:
597 return UndefValue::get(C1->getType());
598 case Instruction::Mul:
599 case Instruction::And:
600 return Constant::getNullValue(C1->getType());
601 case Instruction::UDiv:
602 case Instruction::SDiv:
603 case Instruction::FDiv:
604 case Instruction::URem:
605 case Instruction::SRem:
606 case Instruction::FRem:
607 if (!isa<UndefValue>(C2)) // undef / X -> 0
608 return Constant::getNullValue(C1->getType());
609 return const_cast<Constant*>(C2); // X / undef -> undef
610 case Instruction::Or: // X | undef -> -1
611 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
612 return ConstantVector::getAllOnesValue(PTy);
613 return ConstantInt::getAllOnesValue(C1->getType());
614 case Instruction::LShr:
615 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
616 return const_cast<Constant*>(C1); // undef lshr undef -> undef
617 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
619 case Instruction::AShr:
620 if (!isa<UndefValue>(C2))
621 return const_cast<Constant*>(C1); // undef ashr X --> undef
622 else if (isa<UndefValue>(C1))
623 return const_cast<Constant*>(C1); // undef ashr undef -> undef
625 return const_cast<Constant*>(C1); // X ashr undef --> X
626 case Instruction::Shl:
627 // undef << X -> 0 or X << undef -> 0
628 return Constant::getNullValue(C1->getType());
632 // Handle simplifications of the RHS when a constant int.
633 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
635 case Instruction::Add:
636 if (CI2->equalsInt(0)) return const_cast<Constant*>(C1); // X + 0 == X
638 case Instruction::Sub:
639 if (CI2->equalsInt(0)) return const_cast<Constant*>(C1); // X - 0 == X
641 case Instruction::Mul:
642 if (CI2->equalsInt(0)) return const_cast<Constant*>(C2); // X * 0 == 0
643 if (CI2->equalsInt(1))
644 return const_cast<Constant*>(C1); // X * 1 == X
646 case Instruction::UDiv:
647 case Instruction::SDiv:
648 if (CI2->equalsInt(1))
649 return const_cast<Constant*>(C1); // X / 1 == X
651 case Instruction::URem:
652 case Instruction::SRem:
653 if (CI2->equalsInt(1))
654 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
656 case Instruction::And:
657 if (CI2->isZero()) return const_cast<Constant*>(C2); // X & 0 == 0
658 if (CI2->isAllOnesValue())
659 return const_cast<Constant*>(C1); // X & -1 == X
661 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
662 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
663 if (CE1->getOpcode() == Instruction::ZExt) {
664 unsigned DstWidth = CI2->getType()->getBitWidth();
666 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
667 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
668 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
669 return const_cast<Constant*>(C1);
672 // If and'ing the address of a global with a constant, fold it.
673 if (CE1->getOpcode() == Instruction::PtrToInt &&
674 isa<GlobalValue>(CE1->getOperand(0))) {
675 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
677 // Functions are at least 4-byte aligned.
678 unsigned GVAlign = GV->getAlignment();
679 if (isa<Function>(GV))
680 GVAlign = std::max(GVAlign, 4U);
683 unsigned DstWidth = CI2->getType()->getBitWidth();
684 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
685 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
687 // If checking bits we know are clear, return zero.
688 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
689 return Constant::getNullValue(CI2->getType());
694 case Instruction::Or:
695 if (CI2->equalsInt(0)) return const_cast<Constant*>(C1); // X | 0 == X
696 if (CI2->isAllOnesValue())
697 return const_cast<Constant*>(C2); // X | -1 == -1
699 case Instruction::Xor:
700 if (CI2->equalsInt(0)) return const_cast<Constant*>(C1); // X ^ 0 == X
702 case Instruction::AShr:
703 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
704 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
705 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
706 return ConstantExpr::getLShr(const_cast<Constant*>(C1),
707 const_cast<Constant*>(C2));
712 // At this point we know neither constant is an UndefValue.
713 if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
714 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
715 using namespace APIntOps;
716 const APInt &C1V = CI1->getValue();
717 const APInt &C2V = CI2->getValue();
721 case Instruction::Add:
722 return ConstantInt::get(C1V + C2V);
723 case Instruction::Sub:
724 return ConstantInt::get(C1V - C2V);
725 case Instruction::Mul:
726 return ConstantInt::get(C1V * C2V);
727 case Instruction::UDiv:
728 if (CI2->isNullValue())
729 return 0; // X / 0 -> can't fold
730 return ConstantInt::get(C1V.udiv(C2V));
731 case Instruction::SDiv:
732 if (CI2->isNullValue())
733 return 0; // X / 0 -> can't fold
734 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
735 return 0; // MIN_INT / -1 -> overflow
736 return ConstantInt::get(C1V.sdiv(C2V));
737 case Instruction::URem:
738 if (C2->isNullValue())
739 return 0; // X / 0 -> can't fold
740 return ConstantInt::get(C1V.urem(C2V));
741 case Instruction::SRem:
742 if (CI2->isNullValue())
743 return 0; // X % 0 -> can't fold
744 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
745 return 0; // MIN_INT % -1 -> overflow
746 return ConstantInt::get(C1V.srem(C2V));
747 case Instruction::And:
748 return ConstantInt::get(C1V & C2V);
749 case Instruction::Or:
750 return ConstantInt::get(C1V | C2V);
751 case Instruction::Xor:
752 return ConstantInt::get(C1V ^ C2V);
753 case Instruction::Shl: {
754 uint32_t shiftAmt = C2V.getZExtValue();
755 if (shiftAmt < C1V.getBitWidth())
756 return ConstantInt::get(C1V.shl(shiftAmt));
758 return UndefValue::get(C1->getType()); // too big shift is undef
760 case Instruction::LShr: {
761 uint32_t shiftAmt = C2V.getZExtValue();
762 if (shiftAmt < C1V.getBitWidth())
763 return ConstantInt::get(C1V.lshr(shiftAmt));
765 return UndefValue::get(C1->getType()); // too big shift is undef
767 case Instruction::AShr: {
768 uint32_t shiftAmt = C2V.getZExtValue();
769 if (shiftAmt < C1V.getBitWidth())
770 return ConstantInt::get(C1V.ashr(shiftAmt));
772 return UndefValue::get(C1->getType()); // too big shift is undef
776 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
777 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
778 APFloat C1V = CFP1->getValueAPF();
779 APFloat C2V = CFP2->getValueAPF();
780 APFloat C3V = C1V; // copy for modification
784 case Instruction::Add:
785 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
786 return ConstantFP::get(C3V);
787 case Instruction::Sub:
788 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
789 return ConstantFP::get(C3V);
790 case Instruction::Mul:
791 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
792 return ConstantFP::get(C3V);
793 case Instruction::FDiv:
794 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
795 return ConstantFP::get(C3V);
796 case Instruction::FRem:
798 // IEEE 754, Section 7.1, #5
799 if (CFP1->getType() == Type::DoubleTy)
800 return ConstantFP::get(APFloat(std::numeric_limits<double>::
802 if (CFP1->getType() == Type::FloatTy)
803 return ConstantFP::get(APFloat(std::numeric_limits<float>::
807 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
808 return ConstantFP::get(C3V);
811 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
812 const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
813 const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
814 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
815 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
819 case Instruction::Add:
820 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
821 case Instruction::Sub:
822 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
823 case Instruction::Mul:
824 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
825 case Instruction::UDiv:
826 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
827 case Instruction::SDiv:
828 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
829 case Instruction::FDiv:
830 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
831 case Instruction::URem:
832 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
833 case Instruction::SRem:
834 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
835 case Instruction::FRem:
836 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
837 case Instruction::And:
838 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
839 case Instruction::Or:
840 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
841 case Instruction::Xor:
842 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
847 if (isa<ConstantExpr>(C1)) {
848 // There are many possible foldings we could do here. We should probably
849 // at least fold add of a pointer with an integer into the appropriate
850 // getelementptr. This will improve alias analysis a bit.
851 } else if (isa<ConstantExpr>(C2)) {
852 // If C2 is a constant expr and C1 isn't, flop them around and fold the
853 // other way if possible.
855 case Instruction::Add:
856 case Instruction::Mul:
857 case Instruction::And:
858 case Instruction::Or:
859 case Instruction::Xor:
860 // No change of opcode required.
861 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
863 case Instruction::Shl:
864 case Instruction::LShr:
865 case Instruction::AShr:
866 case Instruction::Sub:
867 case Instruction::SDiv:
868 case Instruction::UDiv:
869 case Instruction::FDiv:
870 case Instruction::URem:
871 case Instruction::SRem:
872 case Instruction::FRem:
873 default: // These instructions cannot be flopped around.
878 // We don't know how to fold this.
882 /// isZeroSizedType - This type is zero sized if its an array or structure of
883 /// zero sized types. The only leaf zero sized type is an empty structure.
884 static bool isMaybeZeroSizedType(const Type *Ty) {
885 if (isa<OpaqueType>(Ty)) return true; // Can't say.
886 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
888 // If all of elements have zero size, this does too.
889 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
890 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
893 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
894 return isMaybeZeroSizedType(ATy->getElementType());
899 /// IdxCompare - Compare the two constants as though they were getelementptr
900 /// indices. This allows coersion of the types to be the same thing.
902 /// If the two constants are the "same" (after coersion), return 0. If the
903 /// first is less than the second, return -1, if the second is less than the
904 /// first, return 1. If the constants are not integral, return -2.
906 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
907 if (C1 == C2) return 0;
909 // Ok, we found a different index. If they are not ConstantInt, we can't do
910 // anything with them.
911 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
912 return -2; // don't know!
914 // Ok, we have two differing integer indices. Sign extend them to be the same
915 // type. Long is always big enough, so we use it.
916 if (C1->getType() != Type::Int64Ty)
917 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
919 if (C2->getType() != Type::Int64Ty)
920 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
922 if (C1 == C2) return 0; // They are equal
924 // If the type being indexed over is really just a zero sized type, there is
925 // no pointer difference being made here.
926 if (isMaybeZeroSizedType(ElTy))
929 // If they are really different, now that they are the same type, then we
930 // found a difference!
931 if (cast<ConstantInt>(C1)->getSExtValue() <
932 cast<ConstantInt>(C2)->getSExtValue())
938 /// evaluateFCmpRelation - This function determines if there is anything we can
939 /// decide about the two constants provided. This doesn't need to handle simple
940 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
941 /// If we can determine that the two constants have a particular relation to
942 /// each other, we should return the corresponding FCmpInst predicate,
943 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
944 /// ConstantFoldCompareInstruction.
946 /// To simplify this code we canonicalize the relation so that the first
947 /// operand is always the most "complex" of the two. We consider ConstantFP
948 /// to be the simplest, and ConstantExprs to be the most complex.
949 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
950 const Constant *V2) {
951 assert(V1->getType() == V2->getType() &&
952 "Cannot compare values of different types!");
954 // No compile-time operations on this type yet.
955 if (V1->getType() == Type::PPC_FP128Ty)
956 return FCmpInst::BAD_FCMP_PREDICATE;
958 // Handle degenerate case quickly
959 if (V1 == V2) return FCmpInst::FCMP_OEQ;
961 if (!isa<ConstantExpr>(V1)) {
962 if (!isa<ConstantExpr>(V2)) {
963 // We distilled thisUse the standard constant folder for a few cases
965 Constant *C1 = const_cast<Constant*>(V1);
966 Constant *C2 = const_cast<Constant*>(V2);
967 R = dyn_cast<ConstantInt>(
968 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
969 if (R && !R->isZero())
970 return FCmpInst::FCMP_OEQ;
971 R = dyn_cast<ConstantInt>(
972 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
973 if (R && !R->isZero())
974 return FCmpInst::FCMP_OLT;
975 R = dyn_cast<ConstantInt>(
976 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
977 if (R && !R->isZero())
978 return FCmpInst::FCMP_OGT;
980 // Nothing more we can do
981 return FCmpInst::BAD_FCMP_PREDICATE;
984 // If the first operand is simple and second is ConstantExpr, swap operands.
985 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
986 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
987 return FCmpInst::getSwappedPredicate(SwappedRelation);
989 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
990 // constantexpr or a simple constant.
991 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
992 switch (CE1->getOpcode()) {
993 case Instruction::FPTrunc:
994 case Instruction::FPExt:
995 case Instruction::UIToFP:
996 case Instruction::SIToFP:
997 // We might be able to do something with these but we don't right now.
1003 // There are MANY other foldings that we could perform here. They will
1004 // probably be added on demand, as they seem needed.
1005 return FCmpInst::BAD_FCMP_PREDICATE;
1008 /// evaluateICmpRelation - This function determines if there is anything we can
1009 /// decide about the two constants provided. This doesn't need to handle simple
1010 /// things like integer comparisons, but should instead handle ConstantExprs
1011 /// and GlobalValues. If we can determine that the two constants have a
1012 /// particular relation to each other, we should return the corresponding ICmp
1013 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1015 /// To simplify this code we canonicalize the relation so that the first
1016 /// operand is always the most "complex" of the two. We consider simple
1017 /// constants (like ConstantInt) to be the simplest, followed by
1018 /// GlobalValues, followed by ConstantExpr's (the most complex).
1020 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
1023 assert(V1->getType() == V2->getType() &&
1024 "Cannot compare different types of values!");
1025 if (V1 == V2) return ICmpInst::ICMP_EQ;
1027 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1028 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1029 // We distilled this down to a simple case, use the standard constant
1032 Constant *C1 = const_cast<Constant*>(V1);
1033 Constant *C2 = const_cast<Constant*>(V2);
1034 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1035 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
1036 if (R && !R->isZero())
1038 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1039 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
1040 if (R && !R->isZero())
1042 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1043 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
1044 if (R && !R->isZero())
1047 // If we couldn't figure it out, bail.
1048 return ICmpInst::BAD_ICMP_PREDICATE;
1051 // If the first operand is simple, swap operands.
1052 ICmpInst::Predicate SwappedRelation =
1053 evaluateICmpRelation(V2, V1, isSigned);
1054 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1055 return ICmpInst::getSwappedPredicate(SwappedRelation);
1057 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1058 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1059 ICmpInst::Predicate SwappedRelation =
1060 evaluateICmpRelation(V2, V1, isSigned);
1061 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1062 return ICmpInst::getSwappedPredicate(SwappedRelation);
1064 return ICmpInst::BAD_ICMP_PREDICATE;
1067 // Now we know that the RHS is a GlobalValue or simple constant,
1068 // which (since the types must match) means that it's a ConstantPointerNull.
1069 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1070 // Don't try to decide equality of aliases.
1071 if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
1072 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
1073 return ICmpInst::ICMP_NE;
1075 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1076 // GlobalVals can never be null. Don't try to evaluate aliases.
1077 if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
1078 return ICmpInst::ICMP_NE;
1081 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1082 // constantexpr, a CPR, or a simple constant.
1083 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1084 const Constant *CE1Op0 = CE1->getOperand(0);
1086 switch (CE1->getOpcode()) {
1087 case Instruction::Trunc:
1088 case Instruction::FPTrunc:
1089 case Instruction::FPExt:
1090 case Instruction::FPToUI:
1091 case Instruction::FPToSI:
1092 break; // We can't evaluate floating point casts or truncations.
1094 case Instruction::UIToFP:
1095 case Instruction::SIToFP:
1096 case Instruction::BitCast:
1097 case Instruction::ZExt:
1098 case Instruction::SExt:
1099 // If the cast is not actually changing bits, and the second operand is a
1100 // null pointer, do the comparison with the pre-casted value.
1101 if (V2->isNullValue() &&
1102 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
1103 bool sgnd = isSigned;
1104 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1105 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1106 return evaluateICmpRelation(CE1Op0,
1107 Constant::getNullValue(CE1Op0->getType()),
1111 // If the dest type is a pointer type, and the RHS is a constantexpr cast
1112 // from the same type as the src of the LHS, evaluate the inputs. This is
1113 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
1114 // which happens a lot in compilers with tagged integers.
1115 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
1116 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
1117 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
1118 CE1->getOperand(0)->getType()->isInteger()) {
1119 bool sgnd = isSigned;
1120 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1121 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1122 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
1127 case Instruction::GetElementPtr:
1128 // Ok, since this is a getelementptr, we know that the constant has a
1129 // pointer type. Check the various cases.
1130 if (isa<ConstantPointerNull>(V2)) {
1131 // If we are comparing a GEP to a null pointer, check to see if the base
1132 // of the GEP equals the null pointer.
1133 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1134 if (GV->hasExternalWeakLinkage())
1135 // Weak linkage GVals could be zero or not. We're comparing that
1136 // to null pointer so its greater-or-equal
1137 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1139 // If its not weak linkage, the GVal must have a non-zero address
1140 // so the result is greater-than
1141 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1142 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1143 // If we are indexing from a null pointer, check to see if we have any
1144 // non-zero indices.
1145 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1146 if (!CE1->getOperand(i)->isNullValue())
1147 // Offsetting from null, must not be equal.
1148 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1149 // Only zero indexes from null, must still be zero.
1150 return ICmpInst::ICMP_EQ;
1152 // Otherwise, we can't really say if the first operand is null or not.
1153 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1154 if (isa<ConstantPointerNull>(CE1Op0)) {
1155 if (CPR2->hasExternalWeakLinkage())
1156 // Weak linkage GVals could be zero or not. We're comparing it to
1157 // a null pointer, so its less-or-equal
1158 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1160 // If its not weak linkage, the GVal must have a non-zero address
1161 // so the result is less-than
1162 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1163 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1165 // If this is a getelementptr of the same global, then it must be
1166 // different. Because the types must match, the getelementptr could
1167 // only have at most one index, and because we fold getelementptr's
1168 // with a single zero index, it must be nonzero.
1169 assert(CE1->getNumOperands() == 2 &&
1170 !CE1->getOperand(1)->isNullValue() &&
1171 "Suprising getelementptr!");
1172 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1174 // If they are different globals, we don't know what the value is,
1175 // but they can't be equal.
1176 return ICmpInst::ICMP_NE;
1180 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1181 const Constant *CE2Op0 = CE2->getOperand(0);
1183 // There are MANY other foldings that we could perform here. They will
1184 // probably be added on demand, as they seem needed.
1185 switch (CE2->getOpcode()) {
1187 case Instruction::GetElementPtr:
1188 // By far the most common case to handle is when the base pointers are
1189 // obviously to the same or different globals.
1190 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1191 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1192 return ICmpInst::ICMP_NE;
1193 // Ok, we know that both getelementptr instructions are based on the
1194 // same global. From this, we can precisely determine the relative
1195 // ordering of the resultant pointers.
1198 // Compare all of the operands the GEP's have in common.
1199 gep_type_iterator GTI = gep_type_begin(CE1);
1200 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1202 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1203 GTI.getIndexedType())) {
1204 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1205 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1206 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1209 // Ok, we ran out of things they have in common. If any leftovers
1210 // are non-zero then we have a difference, otherwise we are equal.
1211 for (; i < CE1->getNumOperands(); ++i)
1212 if (!CE1->getOperand(i)->isNullValue()) {
1213 if (isa<ConstantInt>(CE1->getOperand(i)))
1214 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1216 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1219 for (; i < CE2->getNumOperands(); ++i)
1220 if (!CE2->getOperand(i)->isNullValue()) {
1221 if (isa<ConstantInt>(CE2->getOperand(i)))
1222 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1224 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1226 return ICmpInst::ICMP_EQ;
1235 return ICmpInst::BAD_ICMP_PREDICATE;
1238 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1240 const Constant *C2) {
1241 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1242 if (pred == FCmpInst::FCMP_FALSE) {
1243 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1244 return Constant::getNullValue(VectorType::getInteger(VT));
1246 return ConstantInt::getFalse();
1249 if (pred == FCmpInst::FCMP_TRUE) {
1250 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1251 return Constant::getAllOnesValue(VectorType::getInteger(VT));
1253 return ConstantInt::getTrue();
1256 // Handle some degenerate cases first
1257 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1258 // vicmp/vfcmp -> [vector] undef
1259 if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType()))
1260 return UndefValue::get(VectorType::getInteger(VTy));
1262 // icmp/fcmp -> i1 undef
1263 return UndefValue::get(Type::Int1Ty);
1266 // No compile-time operations on this type yet.
1267 if (C1->getType() == Type::PPC_FP128Ty)
1270 // icmp eq/ne(null,GV) -> false/true
1271 if (C1->isNullValue()) {
1272 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1273 // Don't try to evaluate aliases. External weak GV can be null.
1274 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1275 if (pred == ICmpInst::ICMP_EQ)
1276 return ConstantInt::getFalse();
1277 else if (pred == ICmpInst::ICMP_NE)
1278 return ConstantInt::getTrue();
1280 // icmp eq/ne(GV,null) -> false/true
1281 } else if (C2->isNullValue()) {
1282 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1283 // Don't try to evaluate aliases. External weak GV can be null.
1284 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1285 if (pred == ICmpInst::ICMP_EQ)
1286 return ConstantInt::getFalse();
1287 else if (pred == ICmpInst::ICMP_NE)
1288 return ConstantInt::getTrue();
1292 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1293 APInt V1 = cast<ConstantInt>(C1)->getValue();
1294 APInt V2 = cast<ConstantInt>(C2)->getValue();
1296 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1297 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1298 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1299 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1300 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1301 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1302 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1303 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1304 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1305 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1306 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1308 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1309 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1310 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1311 APFloat::cmpResult R = C1V.compare(C2V);
1313 default: assert(0 && "Invalid FCmp Predicate"); return 0;
1314 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1315 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
1316 case FCmpInst::FCMP_UNO:
1317 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
1318 case FCmpInst::FCMP_ORD:
1319 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
1320 case FCmpInst::FCMP_UEQ:
1321 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1322 R==APFloat::cmpEqual);
1323 case FCmpInst::FCMP_OEQ:
1324 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
1325 case FCmpInst::FCMP_UNE:
1326 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
1327 case FCmpInst::FCMP_ONE:
1328 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1329 R==APFloat::cmpGreaterThan);
1330 case FCmpInst::FCMP_ULT:
1331 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1332 R==APFloat::cmpLessThan);
1333 case FCmpInst::FCMP_OLT:
1334 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
1335 case FCmpInst::FCMP_UGT:
1336 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1337 R==APFloat::cmpGreaterThan);
1338 case FCmpInst::FCMP_OGT:
1339 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
1340 case FCmpInst::FCMP_ULE:
1341 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
1342 case FCmpInst::FCMP_OLE:
1343 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1344 R==APFloat::cmpEqual);
1345 case FCmpInst::FCMP_UGE:
1346 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
1347 case FCmpInst::FCMP_OGE:
1348 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1349 R==APFloat::cmpEqual);
1351 } else if (isa<VectorType>(C1->getType())) {
1352 SmallVector<Constant*, 16> C1Elts, C2Elts;
1353 C1->getVectorElements(C1Elts);
1354 C2->getVectorElements(C2Elts);
1356 // If we can constant fold the comparison of each element, constant fold
1357 // the whole vector comparison.
1358 SmallVector<Constant*, 4> ResElts;
1359 const Type *InEltTy = C1Elts[0]->getType();
1360 bool isFP = InEltTy->isFloatingPoint();
1361 const Type *ResEltTy = InEltTy;
1363 ResEltTy = IntegerType::get(InEltTy->getPrimitiveSizeInBits());
1365 for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1366 // Compare the elements, producing an i1 result or constant expr.
1369 C = ConstantExpr::getFCmp(pred, C1Elts[i], C2Elts[i]);
1371 C = ConstantExpr::getICmp(pred, C1Elts[i], C2Elts[i]);
1373 // If it is a bool or undef result, convert to the dest type.
1374 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1376 ResElts.push_back(Constant::getNullValue(ResEltTy));
1378 ResElts.push_back(Constant::getAllOnesValue(ResEltTy));
1379 } else if (isa<UndefValue>(C)) {
1380 ResElts.push_back(UndefValue::get(ResEltTy));
1386 if (ResElts.size() == C1Elts.size())
1387 return ConstantVector::get(&ResElts[0], ResElts.size());
1390 if (C1->getType()->isFloatingPoint()) {
1391 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1392 switch (evaluateFCmpRelation(C1, C2)) {
1393 default: assert(0 && "Unknown relation!");
1394 case FCmpInst::FCMP_UNO:
1395 case FCmpInst::FCMP_ORD:
1396 case FCmpInst::FCMP_UEQ:
1397 case FCmpInst::FCMP_UNE:
1398 case FCmpInst::FCMP_ULT:
1399 case FCmpInst::FCMP_UGT:
1400 case FCmpInst::FCMP_ULE:
1401 case FCmpInst::FCMP_UGE:
1402 case FCmpInst::FCMP_TRUE:
1403 case FCmpInst::FCMP_FALSE:
1404 case FCmpInst::BAD_FCMP_PREDICATE:
1405 break; // Couldn't determine anything about these constants.
1406 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1407 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1408 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1409 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1411 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1412 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1413 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1414 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1416 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1417 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1418 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1419 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1421 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1422 // We can only partially decide this relation.
1423 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1425 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1428 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1429 // We can only partially decide this relation.
1430 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1432 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1435 case ICmpInst::ICMP_NE: // We know that C1 != C2
1436 // We can only partially decide this relation.
1437 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1439 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1444 // If we evaluated the result, return it now.
1446 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType())) {
1448 return Constant::getNullValue(VectorType::getInteger(VT));
1450 return Constant::getAllOnesValue(VectorType::getInteger(VT));
1452 return ConstantInt::get(Type::Int1Ty, Result);
1456 // Evaluate the relation between the two constants, per the predicate.
1457 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1458 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1459 default: assert(0 && "Unknown relational!");
1460 case ICmpInst::BAD_ICMP_PREDICATE:
1461 break; // Couldn't determine anything about these constants.
1462 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1463 // If we know the constants are equal, we can decide the result of this
1464 // computation precisely.
1465 Result = (pred == ICmpInst::ICMP_EQ ||
1466 pred == ICmpInst::ICMP_ULE ||
1467 pred == ICmpInst::ICMP_SLE ||
1468 pred == ICmpInst::ICMP_UGE ||
1469 pred == ICmpInst::ICMP_SGE);
1471 case ICmpInst::ICMP_ULT:
1472 // If we know that C1 < C2, we can decide the result of this computation
1474 Result = (pred == ICmpInst::ICMP_ULT ||
1475 pred == ICmpInst::ICMP_NE ||
1476 pred == ICmpInst::ICMP_ULE);
1478 case ICmpInst::ICMP_SLT:
1479 // If we know that C1 < C2, we can decide the result of this computation
1481 Result = (pred == ICmpInst::ICMP_SLT ||
1482 pred == ICmpInst::ICMP_NE ||
1483 pred == ICmpInst::ICMP_SLE);
1485 case ICmpInst::ICMP_UGT:
1486 // If we know that C1 > C2, we can decide the result of this computation
1488 Result = (pred == ICmpInst::ICMP_UGT ||
1489 pred == ICmpInst::ICMP_NE ||
1490 pred == ICmpInst::ICMP_UGE);
1492 case ICmpInst::ICMP_SGT:
1493 // If we know that C1 > C2, we can decide the result of this computation
1495 Result = (pred == ICmpInst::ICMP_SGT ||
1496 pred == ICmpInst::ICMP_NE ||
1497 pred == ICmpInst::ICMP_SGE);
1499 case ICmpInst::ICMP_ULE:
1500 // If we know that C1 <= C2, we can only partially decide this relation.
1501 if (pred == ICmpInst::ICMP_UGT) Result = 0;
1502 if (pred == ICmpInst::ICMP_ULT) Result = 1;
1504 case ICmpInst::ICMP_SLE:
1505 // If we know that C1 <= C2, we can only partially decide this relation.
1506 if (pred == ICmpInst::ICMP_SGT) Result = 0;
1507 if (pred == ICmpInst::ICMP_SLT) Result = 1;
1510 case ICmpInst::ICMP_UGE:
1511 // If we know that C1 >= C2, we can only partially decide this relation.
1512 if (pred == ICmpInst::ICMP_ULT) Result = 0;
1513 if (pred == ICmpInst::ICMP_UGT) Result = 1;
1515 case ICmpInst::ICMP_SGE:
1516 // If we know that C1 >= C2, we can only partially decide this relation.
1517 if (pred == ICmpInst::ICMP_SLT) Result = 0;
1518 if (pred == ICmpInst::ICMP_SGT) Result = 1;
1521 case ICmpInst::ICMP_NE:
1522 // If we know that C1 != C2, we can only partially decide this relation.
1523 if (pred == ICmpInst::ICMP_EQ) Result = 0;
1524 if (pred == ICmpInst::ICMP_NE) Result = 1;
1528 // If we evaluated the result, return it now.
1530 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType())) {
1532 return Constant::getNullValue(VT);
1534 return Constant::getAllOnesValue(VT);
1536 return ConstantInt::get(Type::Int1Ty, Result);
1539 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1540 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1541 // other way if possible.
1543 case ICmpInst::ICMP_EQ:
1544 case ICmpInst::ICMP_NE:
1545 // No change of predicate required.
1546 return ConstantFoldCompareInstruction(pred, C2, C1);
1548 case ICmpInst::ICMP_ULT:
1549 case ICmpInst::ICMP_SLT:
1550 case ICmpInst::ICMP_UGT:
1551 case ICmpInst::ICMP_SGT:
1552 case ICmpInst::ICMP_ULE:
1553 case ICmpInst::ICMP_SLE:
1554 case ICmpInst::ICMP_UGE:
1555 case ICmpInst::ICMP_SGE:
1556 // Change the predicate as necessary to swap the operands.
1557 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1558 return ConstantFoldCompareInstruction(pred, C2, C1);
1560 default: // These predicates cannot be flopped around.
1568 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1569 Constant* const *Idxs,
1572 (NumIdx == 1 && Idxs[0]->isNullValue()))
1573 return const_cast<Constant*>(C);
1575 if (isa<UndefValue>(C)) {
1576 const PointerType *Ptr = cast<PointerType>(C->getType());
1577 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1579 (Value **)Idxs+NumIdx);
1580 assert(Ty != 0 && "Invalid indices for GEP!");
1581 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1584 Constant *Idx0 = Idxs[0];
1585 if (C->isNullValue()) {
1587 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1588 if (!Idxs[i]->isNullValue()) {
1593 const PointerType *Ptr = cast<PointerType>(C->getType());
1594 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1596 (Value**)Idxs+NumIdx);
1597 assert(Ty != 0 && "Invalid indices for GEP!");
1599 ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
1603 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1604 // Combine Indices - If the source pointer to this getelementptr instruction
1605 // is a getelementptr instruction, combine the indices of the two
1606 // getelementptr instructions into a single instruction.
1608 if (CE->getOpcode() == Instruction::GetElementPtr) {
1609 const Type *LastTy = 0;
1610 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1614 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1615 SmallVector<Value*, 16> NewIndices;
1616 NewIndices.reserve(NumIdx + CE->getNumOperands());
1617 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1618 NewIndices.push_back(CE->getOperand(i));
1620 // Add the last index of the source with the first index of the new GEP.
1621 // Make sure to handle the case when they are actually different types.
1622 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1623 // Otherwise it must be an array.
1624 if (!Idx0->isNullValue()) {
1625 const Type *IdxTy = Combined->getType();
1626 if (IdxTy != Idx0->getType()) {
1627 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1628 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1630 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1633 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1637 NewIndices.push_back(Combined);
1638 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1639 return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1644 // Implement folding of:
1645 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1647 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1649 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1650 if (const PointerType *SPT =
1651 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1652 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1653 if (const ArrayType *CAT =
1654 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1655 if (CAT->getElementType() == SAT->getElementType())
1656 return ConstantExpr::getGetElementPtr(
1657 (Constant*)CE->getOperand(0), Idxs, NumIdx);
1660 // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1661 // Into: inttoptr (i64 0 to i8*)
1662 // This happens with pointers to member functions in C++.
1663 if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1664 isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1665 cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1666 Constant *Base = CE->getOperand(0);
1667 Constant *Offset = Idxs[0];
1669 // Convert the smaller integer to the larger type.
1670 if (Offset->getType()->getPrimitiveSizeInBits() <
1671 Base->getType()->getPrimitiveSizeInBits())
1672 Offset = ConstantExpr::getSExt(Offset, Base->getType());
1673 else if (Base->getType()->getPrimitiveSizeInBits() <
1674 Offset->getType()->getPrimitiveSizeInBits())
1675 Base = ConstantExpr::getZExt(Base, Base->getType());
1677 Base = ConstantExpr::getAdd(Base, Offset);
1678 return ConstantExpr::getIntToPtr(Base, CE->getType());