1 //===- ConstantFolding.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) ConstantFolding.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 "ConstantFolding.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 /// CastConstantPacked - Convert the specified ConstantPacked node to the
39 /// specified packed 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 *CastConstantPacked(ConstantPacked *CP,
42 const PackedType *DstTy) {
43 unsigned SrcNumElts = CP->getType()->getNumElements();
44 unsigned DstNumElts = DstTy->getNumElements();
45 const Type *SrcEltTy = CP->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(CP->getOperand(i), DstEltTy));
60 return ConstantPacked::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>(CP->getOperand(i))->getZExtValue());
71 Result.push_back(ConstantFP::get(Type::DoubleTy, V));
73 return ConstantPacked::get(Result);
75 assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
76 for (unsigned i = 0; i != SrcNumElts; ++i) {
78 BitsToFloat(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
79 Result.push_back(ConstantFP::get(Type::FloatTy, V));
81 return ConstantPacked::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>(CP->getOperand(i))->getValue());
91 Constant *C = ConstantInt::get(Type::Int64Ty, V);
92 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
94 return ConstantPacked::get(Result);
97 assert(SrcEltTy->getTypeID() == Type::FloatTyID);
98 for (unsigned i = 0; i != SrcNumElts; ++i) {
99 uint32_t V = FloatToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
100 Constant *C = ConstantInt::get(Type::Int32Ty, V);
101 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
103 return ConstantPacked::get(Result);
106 // Otherwise, this is a cast that changes element count and size. Handle
107 // casts which shrink the elements here.
109 // FIXME: We need to know endianness to do this!
114 /// This function determines which opcode to use to fold two constant cast
115 /// expressions together. It uses CastInst::isEliminableCastPair to determine
116 /// the opcode. Consequently its just a wrapper around that function.
117 /// @Determine if it is valid to fold a cast of a cast
119 foldConstantCastPair(
120 unsigned opc, ///< opcode of the second cast constant expression
121 const ConstantExpr*Op, ///< the first cast constant expression
122 const Type *DstTy ///< desintation type of the first cast
124 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
125 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
126 assert(CastInst::isCast(opc) && "Invalid cast opcode");
128 // The the types and opcodes for the two Cast constant expressions
129 const Type *SrcTy = Op->getOperand(0)->getType();
130 const Type *MidTy = Op->getType();
131 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
132 Instruction::CastOps secondOp = Instruction::CastOps(opc);
134 // Let CastInst::isEliminableCastPair do the heavy lifting.
135 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
139 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
140 const Type *DestTy) {
141 const Type *SrcTy = V->getType();
143 if (isa<UndefValue>(V))
144 return UndefValue::get(DestTy);
146 // If the cast operand is a constant expression, there's a few things we can
147 // do to try to simplify it.
148 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
150 // Try hard to fold cast of cast because they are often eliminable.
151 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
152 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
153 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
154 // If all of the indexes in the GEP are null values, there is no pointer
155 // adjustment going on. We might as well cast the source pointer.
156 bool isAllNull = true;
157 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
158 if (!CE->getOperand(i)->isNullValue()) {
163 // This is casting one pointer type to another, always BitCast
164 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
168 // We actually have to do a cast now. Perform the cast according to the
171 case Instruction::FPTrunc:
172 case Instruction::FPExt:
173 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
174 return ConstantFP::get(DestTy, FPC->getValue());
175 return 0; // Can't fold.
176 case Instruction::FPToUI:
177 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
178 return ConstantInt::get(DestTy,(uint64_t) FPC->getValue());
179 return 0; // Can't fold.
180 case Instruction::FPToSI:
181 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
182 return ConstantInt::get(DestTy,(int64_t) FPC->getValue());
183 return 0; // Can't fold.
184 case Instruction::IntToPtr: //always treated as unsigned
185 if (V->isNullValue()) // Is it an integral null value?
186 return ConstantPointerNull::get(cast<PointerType>(DestTy));
187 return 0; // Other pointer types cannot be casted
188 case Instruction::PtrToInt: // always treated as unsigned
189 if (V->isNullValue()) // is it a null pointer value?
190 return ConstantInt::get(DestTy, 0);
191 return 0; // Other pointer types cannot be casted
192 case Instruction::UIToFP:
193 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
194 return ConstantFP::get(DestTy, double(CI->getZExtValue()));
196 case Instruction::SIToFP:
197 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
198 return ConstantFP::get(DestTy, double(CI->getSExtValue()));
200 case Instruction::ZExt:
201 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
202 return ConstantInt::get(DestTy, CI->getZExtValue());
204 case Instruction::SExt:
205 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
206 return ConstantInt::get(DestTy, CI->getSExtValue());
208 case Instruction::Trunc:
209 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) // Can't trunc a bool
210 return ConstantInt::get(DestTy, CI->getZExtValue());
212 case Instruction::BitCast:
214 return (Constant*)V; // no-op cast
216 // Check to see if we are casting a pointer to an aggregate to a pointer to
217 // the first element. If so, return the appropriate GEP instruction.
218 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
219 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
220 SmallVector<Value*, 8> IdxList;
221 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
222 const Type *ElTy = PTy->getElementType();
223 while (ElTy != DPTy->getElementType()) {
224 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
225 if (STy->getNumElements() == 0) break;
226 ElTy = STy->getElementType(0);
227 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
228 } else if (const SequentialType *STy =
229 dyn_cast<SequentialType>(ElTy)) {
230 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
231 ElTy = STy->getElementType();
232 IdxList.push_back(IdxList[0]);
238 if (ElTy == DPTy->getElementType())
239 return ConstantExpr::getGetElementPtr(
240 const_cast<Constant*>(V), &IdxList[0], IdxList.size());
243 // Handle casts from one packed constant to another. We know that the src
244 // and dest type have the same size (otherwise its an illegal cast).
245 if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
246 if (const PackedType *SrcTy = dyn_cast<PackedType>(V->getType())) {
247 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
248 "Not cast between same sized vectors!");
249 // First, check for null and undef
250 if (isa<ConstantAggregateZero>(V))
251 return Constant::getNullValue(DestTy);
252 if (isa<UndefValue>(V))
253 return UndefValue::get(DestTy);
255 if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
256 // This is a cast from a ConstantPacked of one type to a
257 // ConstantPacked of another type. Check to see if all elements of
258 // the input are simple.
259 bool AllSimpleConstants = true;
260 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
261 if (!isa<ConstantInt>(CP->getOperand(i)) &&
262 !isa<ConstantFP>(CP->getOperand(i))) {
263 AllSimpleConstants = false;
268 // If all of the elements are simple constants, we can fold this.
269 if (AllSimpleConstants)
270 return CastConstantPacked(const_cast<ConstantPacked*>(CP), DestPTy);
275 // Finally, implement bitcast folding now. The code below doesn't handle
277 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
278 return ConstantPointerNull::get(cast<PointerType>(DestTy));
280 // Handle integral constant input.
281 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
282 // Integral -> Integral, must be changing sign.
283 if (DestTy->isInteger())
284 return ConstantInt::get(DestTy, CI->getZExtValue());
286 if (DestTy->isFloatingPoint()) {
287 if (DestTy == Type::FloatTy)
288 return ConstantFP::get(DestTy, BitsToFloat(CI->getZExtValue()));
289 assert(DestTy == Type::DoubleTy && "Unknown FP type!");
290 return ConstantFP::get(DestTy, BitsToDouble(CI->getZExtValue()));
292 // Otherwise, can't fold this (packed?)
296 // Handle ConstantFP input.
297 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
299 if (DestTy->isInteger())
300 return ConstantInt::get(DestTy, DoubleToBits(FP->getValue()));
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<PackedType>(Val->getType())->getElementType());
329 if (Val->isNullValue()) // ee(zero, x) -> zero
330 return Constant::getNullValue(
331 cast<PackedType>(Val->getType())->getElementType());
333 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
334 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
335 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
336 } else if (isa<UndefValue>(Idx)) {
337 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
338 return const_cast<Constant*>(CVal->getOperand(0));
344 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
346 const Constant *Idx) {
347 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
349 uint64_t idxVal = CIdx->getZExtValue();
350 if (isa<UndefValue>(Val)) {
351 // Insertion of scalar constant into packed 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<PackedType>(Val->getType())->getNumElements();
359 std::vector<Constant*> Ops;
361 for (unsigned i = 0; i < numOps; ++i) {
363 (i == idxVal) ? Elt : UndefValue::get(Elt->getType());
364 Ops.push_back(const_cast<Constant*>(Op));
366 return ConstantPacked::get(Ops);
368 if (isa<ConstantAggregateZero>(Val)) {
369 // Insertion of scalar constant into packed 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<PackedType>(Val->getType())->getNumElements();
377 std::vector<Constant*> Ops;
379 for (unsigned i = 0; i < numOps; ++i) {
381 (i == idxVal) ? Elt : Constant::getNullValue(Elt->getType());
382 Ops.push_back(const_cast<Constant*>(Op));
384 return ConstantPacked::get(Ops);
386 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
387 // Insertion of scalar constant into packed constant
388 std::vector<Constant*> Ops;
389 Ops.reserve(CVal->getNumOperands());
390 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
392 (i == idxVal) ? Elt : cast<Constant>(CVal->getOperand(i));
393 Ops.push_back(const_cast<Constant*>(Op));
395 return ConstantPacked::get(Ops);
400 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
402 const Constant *Mask) {
407 /// EvalVectorOp - Given two packed constants and a function pointer, apply the
408 /// function pointer to each element pair, producing a new ConstantPacked
410 static Constant *EvalVectorOp(const ConstantPacked *V1,
411 const ConstantPacked *V2,
412 Constant *(*FP)(Constant*, Constant*)) {
413 std::vector<Constant*> Res;
414 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
415 Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
416 const_cast<Constant*>(V2->getOperand(i))));
417 return ConstantPacked::get(Res);
420 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
422 const Constant *C2) {
423 // Handle UndefValue up front
424 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
426 case Instruction::Add:
427 case Instruction::Sub:
428 case Instruction::Xor:
429 return UndefValue::get(C1->getType());
430 case Instruction::Mul:
431 case Instruction::And:
432 return Constant::getNullValue(C1->getType());
433 case Instruction::UDiv:
434 case Instruction::SDiv:
435 case Instruction::FDiv:
436 case Instruction::URem:
437 case Instruction::SRem:
438 case Instruction::FRem:
439 if (!isa<UndefValue>(C2)) // undef / X -> 0
440 return Constant::getNullValue(C1->getType());
441 return const_cast<Constant*>(C2); // X / undef -> undef
442 case Instruction::Or: // X | undef -> -1
443 if (const PackedType *PTy = dyn_cast<PackedType>(C1->getType()))
444 return ConstantPacked::getAllOnesValue(PTy);
445 return ConstantInt::getAllOnesValue(C1->getType());
446 case Instruction::LShr:
447 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
448 return const_cast<Constant*>(C1); // undef lshr undef -> undef
449 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
451 case Instruction::AShr:
452 if (!isa<UndefValue>(C2))
453 return const_cast<Constant*>(C1); // undef ashr X --> undef
454 else if (isa<UndefValue>(C1))
455 return const_cast<Constant*>(C1); // undef ashr undef -> undef
457 return const_cast<Constant*>(C1); // X ashr undef --> X
458 case Instruction::Shl:
459 // undef << X -> 0 or X << undef -> 0
460 return Constant::getNullValue(C1->getType());
464 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
465 if (isa<ConstantExpr>(C2)) {
466 // There are many possible foldings we could do here. We should probably
467 // at least fold add of a pointer with an integer into the appropriate
468 // getelementptr. This will improve alias analysis a bit.
470 // Just implement a couple of simple identities.
472 case Instruction::Add:
473 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
475 case Instruction::Sub:
476 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
478 case Instruction::Mul:
479 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
480 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
481 if (CI->getZExtValue() == 1)
482 return const_cast<Constant*>(C1); // X * 1 == X
484 case Instruction::UDiv:
485 case Instruction::SDiv:
486 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
487 if (CI->getZExtValue() == 1)
488 return const_cast<Constant*>(C1); // X / 1 == X
490 case Instruction::URem:
491 case Instruction::SRem:
492 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
493 if (CI->getZExtValue() == 1)
494 return Constant::getNullValue(CI->getType()); // X % 1 == 0
496 case Instruction::And:
497 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
498 if (CI->isAllOnesValue())
499 return const_cast<Constant*>(C1); // X & -1 == X
500 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X & 0 == 0
501 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
502 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
504 // Functions are at least 4-byte aligned. If and'ing the address of a
505 // function with a constant < 4, fold it to zero.
506 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
507 if (CI->getZExtValue() < 4 && isa<Function>(CPR))
508 return Constant::getNullValue(CI->getType());
511 case Instruction::Or:
512 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
513 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
514 if (CI->isAllOnesValue())
515 return const_cast<Constant*>(C2); // X | -1 == -1
517 case Instruction::Xor:
518 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
522 } else if (isa<ConstantExpr>(C2)) {
523 // If C2 is a constant expr and C1 isn't, flop them around and fold the
524 // other way if possible.
526 case Instruction::Add:
527 case Instruction::Mul:
528 case Instruction::And:
529 case Instruction::Or:
530 case Instruction::Xor:
531 // No change of opcode required.
532 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
534 case Instruction::Shl:
535 case Instruction::LShr:
536 case Instruction::AShr:
537 case Instruction::Sub:
538 case Instruction::SDiv:
539 case Instruction::UDiv:
540 case Instruction::FDiv:
541 case Instruction::URem:
542 case Instruction::SRem:
543 case Instruction::FRem:
544 default: // These instructions cannot be flopped around.
549 // At this point we know neither constant is an UndefValue nor a ConstantExpr
550 // so look at directly computing the value.
551 if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
552 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
553 uint64_t C1Val = CI1->getZExtValue();
554 uint64_t C2Val = CI2->getZExtValue();
558 case Instruction::Add:
559 return ConstantInt::get(C1->getType(), C1Val + C2Val);
560 case Instruction::Sub:
561 return ConstantInt::get(C1->getType(), C1Val - C2Val);
562 case Instruction::Mul:
563 return ConstantInt::get(C1->getType(), C1Val * C2Val);
564 case Instruction::UDiv:
565 if (CI2->isNullValue()) // X / 0 -> can't fold
567 return ConstantInt::get(C1->getType(), C1Val / C2Val);
568 case Instruction::SDiv:
569 if (CI2->isNullValue()) return 0; // X / 0 -> can't fold
570 if (CI2->isAllOnesValue() &&
571 (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
572 (CI1->getSExtValue() == INT64_MIN)) ||
573 (CI1->getSExtValue() == -CI1->getSExtValue())))
574 return 0; // MIN_INT / -1 -> overflow
575 return ConstantInt::get(C1->getType(),
576 CI1->getSExtValue() / CI2->getSExtValue());
577 case Instruction::URem:
578 if (C2->isNullValue()) return 0; // X / 0 -> can't fold
579 return ConstantInt::get(C1->getType(), C1Val % C2Val);
580 case Instruction::SRem:
581 if (CI2->isNullValue()) return 0; // X % 0 -> can't fold
582 if (CI2->isAllOnesValue() &&
583 (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
584 (CI1->getSExtValue() == INT64_MIN)) ||
585 (CI1->getSExtValue() == -CI1->getSExtValue())))
586 return 0; // MIN_INT % -1 -> overflow
587 return ConstantInt::get(C1->getType(),
588 CI1->getSExtValue() % CI2->getSExtValue());
589 case Instruction::And:
590 return ConstantInt::get(C1->getType(), C1Val & C2Val);
591 case Instruction::Or:
592 return ConstantInt::get(C1->getType(), C1Val | C2Val);
593 case Instruction::Xor:
594 return ConstantInt::get(C1->getType(), C1Val ^ C2Val);
595 case Instruction::Shl:
596 return ConstantInt::get(C1->getType(), C1Val << C2Val);
597 case Instruction::LShr:
598 return ConstantInt::get(C1->getType(), C1Val >> C2Val);
599 case Instruction::AShr:
600 return ConstantInt::get(C1->getType(),
601 CI1->getSExtValue() >> C2Val);
604 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
605 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
606 double C1Val = CFP1->getValue();
607 double C2Val = CFP2->getValue();
611 case Instruction::Add:
612 return ConstantFP::get(CFP1->getType(), C1Val + C2Val);
613 case Instruction::Sub:
614 return ConstantFP::get(CFP1->getType(), C1Val - C2Val);
615 case Instruction::Mul:
616 return ConstantFP::get(CFP1->getType(), C1Val * C2Val);
617 case Instruction::FDiv:
618 if (CFP2->isExactlyValue(0.0))
619 return ConstantFP::get(CFP1->getType(),
620 std::numeric_limits<double>::infinity());
621 if (CFP2->isExactlyValue(-0.0))
622 return ConstantFP::get(CFP1->getType(),
623 -std::numeric_limits<double>::infinity());
624 return ConstantFP::get(CFP1->getType(), C1Val / C2Val);
625 case Instruction::FRem:
626 if (CFP2->isNullValue())
628 return ConstantFP::get(CFP1->getType(), std::fmod(C1Val, C2Val));
631 } else if (const ConstantPacked *CP1 = dyn_cast<ConstantPacked>(C1)) {
632 if (const ConstantPacked *CP2 = dyn_cast<ConstantPacked>(C2)) {
636 case Instruction::Add:
637 return EvalVectorOp(CP1, CP2, ConstantExpr::getAdd);
638 case Instruction::Sub:
639 return EvalVectorOp(CP1, CP2, ConstantExpr::getSub);
640 case Instruction::Mul:
641 return EvalVectorOp(CP1, CP2, ConstantExpr::getMul);
642 case Instruction::UDiv:
643 return EvalVectorOp(CP1, CP2, ConstantExpr::getUDiv);
644 case Instruction::SDiv:
645 return EvalVectorOp(CP1, CP2, ConstantExpr::getSDiv);
646 case Instruction::FDiv:
647 return EvalVectorOp(CP1, CP2, ConstantExpr::getFDiv);
648 case Instruction::URem:
649 return EvalVectorOp(CP1, CP2, ConstantExpr::getURem);
650 case Instruction::SRem:
651 return EvalVectorOp(CP1, CP2, ConstantExpr::getSRem);
652 case Instruction::FRem:
653 return EvalVectorOp(CP1, CP2, ConstantExpr::getFRem);
654 case Instruction::And:
655 return EvalVectorOp(CP1, CP2, ConstantExpr::getAnd);
656 case Instruction::Or:
657 return EvalVectorOp(CP1, CP2, ConstantExpr::getOr);
658 case Instruction::Xor:
659 return EvalVectorOp(CP1, CP2, ConstantExpr::getXor);
664 // We don't know how to fold this
668 /// isZeroSizedType - This type is zero sized if its an array or structure of
669 /// zero sized types. The only leaf zero sized type is an empty structure.
670 static bool isMaybeZeroSizedType(const Type *Ty) {
671 if (isa<OpaqueType>(Ty)) return true; // Can't say.
672 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
674 // If all of elements have zero size, this does too.
675 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
676 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
679 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
680 return isMaybeZeroSizedType(ATy->getElementType());
685 /// IdxCompare - Compare the two constants as though they were getelementptr
686 /// indices. This allows coersion of the types to be the same thing.
688 /// If the two constants are the "same" (after coersion), return 0. If the
689 /// first is less than the second, return -1, if the second is less than the
690 /// first, return 1. If the constants are not integral, return -2.
692 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
693 if (C1 == C2) return 0;
695 // Ok, we found a different index. If they are not ConstantInt, we can't do
696 // anything with them.
697 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
698 return -2; // don't know!
700 // Ok, we have two differing integer indices. Sign extend them to be the same
701 // type. Long is always big enough, so we use it.
702 if (C1->getType() != Type::Int64Ty)
703 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
705 if (C2->getType() != Type::Int64Ty)
706 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
708 if (C1 == C2) return 0; // They are equal
710 // If the type being indexed over is really just a zero sized type, there is
711 // no pointer difference being made here.
712 if (isMaybeZeroSizedType(ElTy))
715 // If they are really different, now that they are the same type, then we
716 // found a difference!
717 if (cast<ConstantInt>(C1)->getSExtValue() <
718 cast<ConstantInt>(C2)->getSExtValue())
724 /// evaluateFCmpRelation - This function determines if there is anything we can
725 /// decide about the two constants provided. This doesn't need to handle simple
726 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
727 /// If we can determine that the two constants have a particular relation to
728 /// each other, we should return the corresponding FCmpInst predicate,
729 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
730 /// ConstantFoldCompareInstruction.
732 /// To simplify this code we canonicalize the relation so that the first
733 /// operand is always the most "complex" of the two. We consider ConstantFP
734 /// to be the simplest, and ConstantExprs to be the most complex.
735 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
736 const Constant *V2) {
737 assert(V1->getType() == V2->getType() &&
738 "Cannot compare values of different types!");
739 // Handle degenerate case quickly
740 if (V1 == V2) return FCmpInst::FCMP_OEQ;
742 if (!isa<ConstantExpr>(V1)) {
743 if (!isa<ConstantExpr>(V2)) {
744 // We distilled thisUse the standard constant folder for a few cases
746 Constant *C1 = const_cast<Constant*>(V1);
747 Constant *C2 = const_cast<Constant*>(V2);
748 R = dyn_cast<ConstantInt>(
749 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
750 if (R && R->getZExtValue())
751 return FCmpInst::FCMP_OEQ;
752 R = dyn_cast<ConstantInt>(
753 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
754 if (R && R->getZExtValue())
755 return FCmpInst::FCMP_OLT;
756 R = dyn_cast<ConstantInt>(
757 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
758 if (R && R->getZExtValue())
759 return FCmpInst::FCMP_OGT;
761 // Nothing more we can do
762 return FCmpInst::BAD_FCMP_PREDICATE;
765 // If the first operand is simple and second is ConstantExpr, swap operands.
766 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
767 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
768 return FCmpInst::getSwappedPredicate(SwappedRelation);
770 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
771 // constantexpr or a simple constant.
772 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
773 switch (CE1->getOpcode()) {
774 case Instruction::FPTrunc:
775 case Instruction::FPExt:
776 case Instruction::UIToFP:
777 case Instruction::SIToFP:
778 // We might be able to do something with these but we don't right now.
784 // There are MANY other foldings that we could perform here. They will
785 // probably be added on demand, as they seem needed.
786 return FCmpInst::BAD_FCMP_PREDICATE;
789 /// evaluateICmpRelation - This function determines if there is anything we can
790 /// decide about the two constants provided. This doesn't need to handle simple
791 /// things like integer comparisons, but should instead handle ConstantExprs
792 /// and GlobalValues. If we can determine that the two constants have a
793 /// particular relation to each other, we should return the corresponding ICmp
794 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
796 /// To simplify this code we canonicalize the relation so that the first
797 /// operand is always the most "complex" of the two. We consider simple
798 /// constants (like ConstantInt) to be the simplest, followed by
799 /// GlobalValues, followed by ConstantExpr's (the most complex).
801 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
804 assert(V1->getType() == V2->getType() &&
805 "Cannot compare different types of values!");
806 if (V1 == V2) return ICmpInst::ICMP_EQ;
808 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
809 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
810 // We distilled this down to a simple case, use the standard constant
813 Constant *C1 = const_cast<Constant*>(V1);
814 Constant *C2 = const_cast<Constant*>(V2);
815 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
816 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
817 if (R && R->getZExtValue())
819 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
820 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
821 if (R && R->getZExtValue())
823 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
824 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
825 if (R && R->getZExtValue())
828 // If we couldn't figure it out, bail.
829 return ICmpInst::BAD_ICMP_PREDICATE;
832 // If the first operand is simple, swap operands.
833 ICmpInst::Predicate SwappedRelation =
834 evaluateICmpRelation(V2, V1, isSigned);
835 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
836 return ICmpInst::getSwappedPredicate(SwappedRelation);
838 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
839 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
840 ICmpInst::Predicate SwappedRelation =
841 evaluateICmpRelation(V2, V1, isSigned);
842 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
843 return ICmpInst::getSwappedPredicate(SwappedRelation);
845 return ICmpInst::BAD_ICMP_PREDICATE;
848 // Now we know that the RHS is a GlobalValue or simple constant,
849 // which (since the types must match) means that it's a ConstantPointerNull.
850 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
851 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
852 return ICmpInst::ICMP_NE;
854 // GlobalVals can never be null.
855 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
856 if (!CPR1->hasExternalWeakLinkage())
857 return ICmpInst::ICMP_NE;
860 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
861 // constantexpr, a CPR, or a simple constant.
862 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
863 const Constant *CE1Op0 = CE1->getOperand(0);
865 switch (CE1->getOpcode()) {
866 case Instruction::Trunc:
867 case Instruction::FPTrunc:
868 case Instruction::FPExt:
869 case Instruction::FPToUI:
870 case Instruction::FPToSI:
871 break; // We can't evaluate floating point casts or truncations.
873 case Instruction::UIToFP:
874 case Instruction::SIToFP:
875 case Instruction::IntToPtr:
876 case Instruction::BitCast:
877 case Instruction::ZExt:
878 case Instruction::SExt:
879 case Instruction::PtrToInt:
880 // If the cast is not actually changing bits, and the second operand is a
881 // null pointer, do the comparison with the pre-casted value.
882 if (V2->isNullValue() &&
883 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
884 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
885 (CE1->getOpcode() == Instruction::SExt ? true :
886 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
887 return evaluateICmpRelation(
888 CE1Op0, Constant::getNullValue(CE1Op0->getType()), sgnd);
891 // If the dest type is a pointer type, and the RHS is a constantexpr cast
892 // from the same type as the src of the LHS, evaluate the inputs. This is
893 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
894 // which happens a lot in compilers with tagged integers.
895 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
896 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
897 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
898 CE1->getOperand(0)->getType()->isInteger()) {
899 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
900 (CE1->getOpcode() == Instruction::SExt ? true :
901 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
902 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
907 case Instruction::GetElementPtr:
908 // Ok, since this is a getelementptr, we know that the constant has a
909 // pointer type. Check the various cases.
910 if (isa<ConstantPointerNull>(V2)) {
911 // If we are comparing a GEP to a null pointer, check to see if the base
912 // of the GEP equals the null pointer.
913 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
914 if (GV->hasExternalWeakLinkage())
915 // Weak linkage GVals could be zero or not. We're comparing that
916 // to null pointer so its greater-or-equal
917 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
919 // If its not weak linkage, the GVal must have a non-zero address
920 // so the result is greater-than
921 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
922 } else if (isa<ConstantPointerNull>(CE1Op0)) {
923 // If we are indexing from a null pointer, check to see if we have any
925 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
926 if (!CE1->getOperand(i)->isNullValue())
927 // Offsetting from null, must not be equal.
928 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
929 // Only zero indexes from null, must still be zero.
930 return ICmpInst::ICMP_EQ;
932 // Otherwise, we can't really say if the first operand is null or not.
933 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
934 if (isa<ConstantPointerNull>(CE1Op0)) {
935 if (CPR2->hasExternalWeakLinkage())
936 // Weak linkage GVals could be zero or not. We're comparing it to
937 // a null pointer, so its less-or-equal
938 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
940 // If its not weak linkage, the GVal must have a non-zero address
941 // so the result is less-than
942 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
943 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
945 // If this is a getelementptr of the same global, then it must be
946 // different. Because the types must match, the getelementptr could
947 // only have at most one index, and because we fold getelementptr's
948 // with a single zero index, it must be nonzero.
949 assert(CE1->getNumOperands() == 2 &&
950 !CE1->getOperand(1)->isNullValue() &&
951 "Suprising getelementptr!");
952 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
954 // If they are different globals, we don't know what the value is,
955 // but they can't be equal.
956 return ICmpInst::ICMP_NE;
960 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
961 const Constant *CE2Op0 = CE2->getOperand(0);
963 // There are MANY other foldings that we could perform here. They will
964 // probably be added on demand, as they seem needed.
965 switch (CE2->getOpcode()) {
967 case Instruction::GetElementPtr:
968 // By far the most common case to handle is when the base pointers are
969 // obviously to the same or different globals.
970 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
971 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
972 return ICmpInst::ICMP_NE;
973 // Ok, we know that both getelementptr instructions are based on the
974 // same global. From this, we can precisely determine the relative
975 // ordering of the resultant pointers.
978 // Compare all of the operands the GEP's have in common.
979 gep_type_iterator GTI = gep_type_begin(CE1);
980 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
982 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
983 GTI.getIndexedType())) {
984 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
985 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
986 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
989 // Ok, we ran out of things they have in common. If any leftovers
990 // are non-zero then we have a difference, otherwise we are equal.
991 for (; i < CE1->getNumOperands(); ++i)
992 if (!CE1->getOperand(i)->isNullValue())
993 if (isa<ConstantInt>(CE1->getOperand(i)))
994 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
996 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
998 for (; i < CE2->getNumOperands(); ++i)
999 if (!CE2->getOperand(i)->isNullValue())
1000 if (isa<ConstantInt>(CE2->getOperand(i)))
1001 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1003 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1004 return ICmpInst::ICMP_EQ;
1013 return ICmpInst::BAD_ICMP_PREDICATE;
1016 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1018 const Constant *C2) {
1020 // Handle some degenerate cases first
1021 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1022 return UndefValue::get(Type::Int1Ty);
1024 // icmp eq/ne(null,GV) -> false/true
1025 if (C1->isNullValue()) {
1026 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1027 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1028 if (pred == ICmpInst::ICMP_EQ)
1029 return ConstantInt::getFalse();
1030 else if (pred == ICmpInst::ICMP_NE)
1031 return ConstantInt::getTrue();
1032 // icmp eq/ne(GV,null) -> false/true
1033 } else if (C2->isNullValue()) {
1034 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1035 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1036 if (pred == ICmpInst::ICMP_EQ)
1037 return ConstantInt::getFalse();
1038 else if (pred == ICmpInst::ICMP_NE)
1039 return ConstantInt::getTrue();
1042 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1043 if (ICmpInst::isSignedPredicate(ICmpInst::Predicate(pred))) {
1044 int64_t V1 = cast<ConstantInt>(C1)->getSExtValue();
1045 int64_t V2 = cast<ConstantInt>(C2)->getSExtValue();
1047 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1048 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1 < V2);
1049 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1 > V2);
1050 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1 <= V2);
1051 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1 >= V2);
1054 uint64_t V1 = cast<ConstantInt>(C1)->getZExtValue();
1055 uint64_t V2 = cast<ConstantInt>(C2)->getZExtValue();
1057 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1058 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1059 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1060 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1 < V2);
1061 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1 > V2);
1062 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1 <= V2);
1063 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1 >= V2);
1066 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1067 double C1Val = cast<ConstantFP>(C1)->getValue();
1068 double C2Val = cast<ConstantFP>(C2)->getValue();
1070 default: assert(0 && "Invalid FCmp Predicate"); return 0;
1071 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1072 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
1073 case FCmpInst::FCMP_UNO:
1074 return ConstantInt::get(Type::Int1Ty, C1Val != C1Val || C2Val != C2Val);
1075 case FCmpInst::FCMP_ORD:
1076 return ConstantInt::get(Type::Int1Ty, C1Val == C1Val && C2Val == C2Val);
1077 case FCmpInst::FCMP_UEQ:
1078 if (C1Val != C1Val || C2Val != C2Val)
1079 return ConstantInt::getTrue();
1081 case FCmpInst::FCMP_OEQ:
1082 return ConstantInt::get(Type::Int1Ty, C1Val == C2Val);
1083 case FCmpInst::FCMP_UNE:
1084 if (C1Val != C1Val || C2Val != C2Val)
1085 return ConstantInt::getTrue();
1087 case FCmpInst::FCMP_ONE:
1088 return ConstantInt::get(Type::Int1Ty, C1Val != C2Val);
1089 case FCmpInst::FCMP_ULT:
1090 if (C1Val != C1Val || C2Val != C2Val)
1091 return ConstantInt::getTrue();
1093 case FCmpInst::FCMP_OLT:
1094 return ConstantInt::get(Type::Int1Ty, C1Val < C2Val);
1095 case FCmpInst::FCMP_UGT:
1096 if (C1Val != C1Val || C2Val != C2Val)
1097 return ConstantInt::getTrue();
1099 case FCmpInst::FCMP_OGT:
1100 return ConstantInt::get(Type::Int1Ty, C1Val > C2Val);
1101 case FCmpInst::FCMP_ULE:
1102 if (C1Val != C1Val || C2Val != C2Val)
1103 return ConstantInt::getTrue();
1105 case FCmpInst::FCMP_OLE:
1106 return ConstantInt::get(Type::Int1Ty, C1Val <= C2Val);
1107 case FCmpInst::FCMP_UGE:
1108 if (C1Val != C1Val || C2Val != C2Val)
1109 return ConstantInt::getTrue();
1111 case FCmpInst::FCMP_OGE:
1112 return ConstantInt::get(Type::Int1Ty, C1Val >= C2Val);
1114 } else if (const ConstantPacked *CP1 = dyn_cast<ConstantPacked>(C1)) {
1115 if (const ConstantPacked *CP2 = dyn_cast<ConstantPacked>(C2)) {
1116 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1117 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1118 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1119 const_cast<Constant*>(CP1->getOperand(i)),
1120 const_cast<Constant*>(CP2->getOperand(i)));
1121 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1124 // Otherwise, could not decide from any element pairs.
1126 } else if (pred == ICmpInst::ICMP_EQ) {
1127 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1128 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1129 const_cast<Constant*>(CP1->getOperand(i)),
1130 const_cast<Constant*>(CP2->getOperand(i)));
1131 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1134 // Otherwise, could not decide from any element pairs.
1140 if (C1->getType()->isFloatingPoint()) {
1141 switch (evaluateFCmpRelation(C1, C2)) {
1142 default: assert(0 && "Unknown relation!");
1143 case FCmpInst::FCMP_UNO:
1144 case FCmpInst::FCMP_ORD:
1145 case FCmpInst::FCMP_UEQ:
1146 case FCmpInst::FCMP_UNE:
1147 case FCmpInst::FCMP_ULT:
1148 case FCmpInst::FCMP_UGT:
1149 case FCmpInst::FCMP_ULE:
1150 case FCmpInst::FCMP_UGE:
1151 case FCmpInst::FCMP_TRUE:
1152 case FCmpInst::FCMP_FALSE:
1153 case FCmpInst::BAD_FCMP_PREDICATE:
1154 break; // Couldn't determine anything about these constants.
1155 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1156 return ConstantInt::get(Type::Int1Ty,
1157 pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1158 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1159 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1160 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1161 return ConstantInt::get(Type::Int1Ty,
1162 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1163 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1164 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1165 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1166 return ConstantInt::get(Type::Int1Ty,
1167 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1168 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1169 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1170 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1171 // We can only partially decide this relation.
1172 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1173 return ConstantInt::getFalse();
1174 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1175 return ConstantInt::getTrue();
1177 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1178 // We can only partially decide this relation.
1179 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1180 return ConstantInt::getFalse();
1181 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1182 return ConstantInt::getTrue();
1184 case ICmpInst::ICMP_NE: // We know that C1 != C2
1185 // We can only partially decide this relation.
1186 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1187 return ConstantInt::getFalse();
1188 if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1189 return ConstantInt::getTrue();
1193 // Evaluate the relation between the two constants, per the predicate.
1194 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1195 default: assert(0 && "Unknown relational!");
1196 case ICmpInst::BAD_ICMP_PREDICATE:
1197 break; // Couldn't determine anything about these constants.
1198 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1199 // If we know the constants are equal, we can decide the result of this
1200 // computation precisely.
1201 return ConstantInt::get(Type::Int1Ty,
1202 pred == ICmpInst::ICMP_EQ ||
1203 pred == ICmpInst::ICMP_ULE ||
1204 pred == ICmpInst::ICMP_SLE ||
1205 pred == ICmpInst::ICMP_UGE ||
1206 pred == ICmpInst::ICMP_SGE);
1207 case ICmpInst::ICMP_ULT:
1208 // If we know that C1 < C2, we can decide the result of this computation
1210 return ConstantInt::get(Type::Int1Ty,
1211 pred == ICmpInst::ICMP_ULT ||
1212 pred == ICmpInst::ICMP_NE ||
1213 pred == ICmpInst::ICMP_ULE);
1214 case ICmpInst::ICMP_SLT:
1215 // If we know that C1 < C2, we can decide the result of this computation
1217 return ConstantInt::get(Type::Int1Ty,
1218 pred == ICmpInst::ICMP_SLT ||
1219 pred == ICmpInst::ICMP_NE ||
1220 pred == ICmpInst::ICMP_SLE);
1221 case ICmpInst::ICMP_UGT:
1222 // If we know that C1 > C2, we can decide the result of this computation
1224 return ConstantInt::get(Type::Int1Ty,
1225 pred == ICmpInst::ICMP_UGT ||
1226 pred == ICmpInst::ICMP_NE ||
1227 pred == ICmpInst::ICMP_UGE);
1228 case ICmpInst::ICMP_SGT:
1229 // If we know that C1 > C2, we can decide the result of this computation
1231 return ConstantInt::get(Type::Int1Ty,
1232 pred == ICmpInst::ICMP_SGT ||
1233 pred == ICmpInst::ICMP_NE ||
1234 pred == ICmpInst::ICMP_SGE);
1235 case ICmpInst::ICMP_ULE:
1236 // If we know that C1 <= C2, we can only partially decide this relation.
1237 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1238 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1240 case ICmpInst::ICMP_SLE:
1241 // If we know that C1 <= C2, we can only partially decide this relation.
1242 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1243 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1246 case ICmpInst::ICMP_UGE:
1247 // If we know that C1 >= C2, we can only partially decide this relation.
1248 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1249 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1251 case ICmpInst::ICMP_SGE:
1252 // If we know that C1 >= C2, we can only partially decide this relation.
1253 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1254 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1257 case ICmpInst::ICMP_NE:
1258 // If we know that C1 != C2, we can only partially decide this relation.
1259 if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1260 if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1264 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1265 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1266 // other way if possible.
1268 case ICmpInst::ICMP_EQ:
1269 case ICmpInst::ICMP_NE:
1270 // No change of predicate required.
1271 return ConstantFoldCompareInstruction(pred, C2, C1);
1273 case ICmpInst::ICMP_ULT:
1274 case ICmpInst::ICMP_SLT:
1275 case ICmpInst::ICMP_UGT:
1276 case ICmpInst::ICMP_SGT:
1277 case ICmpInst::ICMP_ULE:
1278 case ICmpInst::ICMP_SLE:
1279 case ICmpInst::ICMP_UGE:
1280 case ICmpInst::ICMP_SGE:
1281 // Change the predicate as necessary to swap the operands.
1282 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1283 return ConstantFoldCompareInstruction(pred, C2, C1);
1285 default: // These predicates cannot be flopped around.
1293 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1294 Constant* const *Idxs,
1297 (NumIdx == 1 && Idxs[0]->isNullValue()))
1298 return const_cast<Constant*>(C);
1300 if (isa<UndefValue>(C)) {
1301 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1302 (Value**)Idxs, NumIdx,
1304 assert(Ty != 0 && "Invalid indices for GEP!");
1305 return UndefValue::get(PointerType::get(Ty));
1308 Constant *Idx0 = Idxs[0];
1309 if (C->isNullValue()) {
1311 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1312 if (!Idxs[i]->isNullValue()) {
1317 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1318 (Value**)Idxs, NumIdx,
1320 assert(Ty != 0 && "Invalid indices for GEP!");
1321 return ConstantPointerNull::get(PointerType::get(Ty));
1325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1326 // Combine Indices - If the source pointer to this getelementptr instruction
1327 // is a getelementptr instruction, combine the indices of the two
1328 // getelementptr instructions into a single instruction.
1330 if (CE->getOpcode() == Instruction::GetElementPtr) {
1331 const Type *LastTy = 0;
1332 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1336 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1337 SmallVector<Value*, 16> NewIndices;
1338 NewIndices.reserve(NumIdx + CE->getNumOperands());
1339 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1340 NewIndices.push_back(CE->getOperand(i));
1342 // Add the last index of the source with the first index of the new GEP.
1343 // Make sure to handle the case when they are actually different types.
1344 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1345 // Otherwise it must be an array.
1346 if (!Idx0->isNullValue()) {
1347 const Type *IdxTy = Combined->getType();
1348 if (IdxTy != Idx0->getType()) {
1349 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1350 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1352 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1355 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1359 NewIndices.push_back(Combined);
1360 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1361 return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1366 // Implement folding of:
1367 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1369 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1371 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue())
1372 if (const PointerType *SPT =
1373 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1374 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1375 if (const ArrayType *CAT =
1376 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1377 if (CAT->getElementType() == SAT->getElementType())
1378 return ConstantExpr::getGetElementPtr(
1379 (Constant*)CE->getOperand(0), Idxs, NumIdx);