1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements folding of constants for LLVM. This implements the
11 // (internal) ConstantFold.h interface, which is used by the
12 // ConstantExpr::get* methods to automatically fold constants when possible.
14 // The current constant folding implementation is implemented in two pieces: the
15 // pieces that don't need TargetData, and the pieces that do. This is to avoid
16 // a dependence in VMCore on Target.
18 //===----------------------------------------------------------------------===//
20 #include "ConstantFold.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
37 //===----------------------------------------------------------------------===//
38 // ConstantFold*Instruction Implementations
39 //===----------------------------------------------------------------------===//
41 /// BitCastConstantVector - Convert the specified ConstantVector node to the
42 /// specified vector type. At this point, we know that the elements of the
43 /// input vector constant are all simple integer or FP values.
44 static Constant
*BitCastConstantVector(LLVMContext
&Context
, ConstantVector
*CV
,
45 const VectorType
*DstTy
) {
46 // If this cast changes element count then we can't handle it here:
47 // doing so requires endianness information. This should be handled by
48 // Analysis/ConstantFolding.cpp
49 unsigned NumElts
= DstTy
->getNumElements();
50 if (NumElts
!= CV
->getNumOperands())
53 // Check to verify that all elements of the input are simple.
54 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
55 if (!isa
<ConstantInt
>(CV
->getOperand(i
)) &&
56 !isa
<ConstantFP
>(CV
->getOperand(i
)))
60 // Bitcast each element now.
61 std::vector
<Constant
*> Result
;
62 const Type
*DstEltTy
= DstTy
->getElementType();
63 for (unsigned i
= 0; i
!= NumElts
; ++i
)
64 Result
.push_back(ConstantExpr::getBitCast(CV
->getOperand(i
),
66 return ConstantVector::get(Result
);
69 /// This function determines which opcode to use to fold two constant cast
70 /// expressions together. It uses CastInst::isEliminableCastPair to determine
71 /// the opcode. Consequently its just a wrapper around that function.
72 /// @brief Determine if it is valid to fold a cast of a cast
75 unsigned opc
, ///< opcode of the second cast constant expression
76 const ConstantExpr
*Op
, ///< the first cast constant expression
77 const Type
*DstTy
///< desintation type of the first cast
79 assert(Op
&& Op
->isCast() && "Can't fold cast of cast without a cast!");
80 assert(DstTy
&& DstTy
->isFirstClassType() && "Invalid cast destination type");
81 assert(CastInst::isCast(opc
) && "Invalid cast opcode");
83 // The the types and opcodes for the two Cast constant expressions
84 const Type
*SrcTy
= Op
->getOperand(0)->getType();
85 const Type
*MidTy
= Op
->getType();
86 Instruction::CastOps firstOp
= Instruction::CastOps(Op
->getOpcode());
87 Instruction::CastOps secondOp
= Instruction::CastOps(opc
);
89 // Let CastInst::isEliminableCastPair do the heavy lifting.
90 return CastInst::isEliminableCastPair(firstOp
, secondOp
, SrcTy
, MidTy
, DstTy
,
91 Type::getInt64Ty(DstTy
->getContext()));
94 static Constant
*FoldBitCast(LLVMContext
&Context
,
95 Constant
*V
, const Type
*DestTy
) {
96 const Type
*SrcTy
= V
->getType();
98 return V
; // no-op cast
100 // Check to see if we are casting a pointer to an aggregate to a pointer to
101 // the first element. If so, return the appropriate GEP instruction.
102 if (const PointerType
*PTy
= dyn_cast
<PointerType
>(V
->getType()))
103 if (const PointerType
*DPTy
= dyn_cast
<PointerType
>(DestTy
))
104 if (PTy
->getAddressSpace() == DPTy
->getAddressSpace()) {
105 SmallVector
<Value
*, 8> IdxList
;
106 Value
*Zero
= Constant::getNullValue(Type::getInt32Ty(Context
));
107 IdxList
.push_back(Zero
);
108 const Type
*ElTy
= PTy
->getElementType();
109 while (ElTy
!= DPTy
->getElementType()) {
110 if (const StructType
*STy
= dyn_cast
<StructType
>(ElTy
)) {
111 if (STy
->getNumElements() == 0) break;
112 ElTy
= STy
->getElementType(0);
113 IdxList
.push_back(Zero
);
114 } else if (const SequentialType
*STy
=
115 dyn_cast
<SequentialType
>(ElTy
)) {
116 if (isa
<PointerType
>(ElTy
)) break; // Can't index into pointers!
117 ElTy
= STy
->getElementType();
118 IdxList
.push_back(Zero
);
124 if (ElTy
== DPTy
->getElementType())
125 // This GEP is inbounds because all indices are zero.
126 return ConstantExpr::getInBoundsGetElementPtr(V
, &IdxList
[0],
130 // Handle casts from one vector constant to another. We know that the src
131 // and dest type have the same size (otherwise its an illegal cast).
132 if (const VectorType
*DestPTy
= dyn_cast
<VectorType
>(DestTy
)) {
133 if (const VectorType
*SrcTy
= dyn_cast
<VectorType
>(V
->getType())) {
134 assert(DestPTy
->getBitWidth() == SrcTy
->getBitWidth() &&
135 "Not cast between same sized vectors!");
137 // First, check for null. Undef is already handled.
138 if (isa
<ConstantAggregateZero
>(V
))
139 return Constant::getNullValue(DestTy
);
141 if (ConstantVector
*CV
= dyn_cast
<ConstantVector
>(V
))
142 return BitCastConstantVector(Context
, CV
, DestPTy
);
145 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
146 // This allows for other simplifications (although some of them
147 // can only be handled by Analysis/ConstantFolding.cpp).
148 if (isa
<ConstantInt
>(V
) || isa
<ConstantFP
>(V
))
149 return ConstantExpr::getBitCast(
150 ConstantVector::get(&V
, 1), DestPTy
);
153 // Finally, implement bitcast folding now. The code below doesn't handle
155 if (isa
<ConstantPointerNull
>(V
)) // ptr->ptr cast.
156 return ConstantPointerNull::get(cast
<PointerType
>(DestTy
));
158 // Handle integral constant input.
159 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
160 if (DestTy
->isInteger())
161 // Integral -> Integral. This is a no-op because the bit widths must
162 // be the same. Consequently, we just fold to V.
165 if (DestTy
->isFloatingPoint())
166 return ConstantFP::get(Context
, APFloat(CI
->getValue(),
167 DestTy
!= Type::getPPC_FP128Ty(Context
)));
169 // Otherwise, can't fold this (vector?)
173 // Handle ConstantFP input.
174 if (const ConstantFP
*FP
= dyn_cast
<ConstantFP
>(V
))
176 return ConstantInt::get(Context
, FP
->getValueAPF().bitcastToAPInt());
182 Constant
*llvm::ConstantFoldCastInstruction(LLVMContext
&Context
,
183 unsigned opc
, const Constant
*V
,
184 const Type
*DestTy
) {
185 if (isa
<UndefValue
>(V
)) {
186 // zext(undef) = 0, because the top bits will be zero.
187 // sext(undef) = 0, because the top bits will all be the same.
188 // [us]itofp(undef) = 0, because the result value is bounded.
189 if (opc
== Instruction::ZExt
|| opc
== Instruction::SExt
||
190 opc
== Instruction::UIToFP
|| opc
== Instruction::SIToFP
)
191 return Constant::getNullValue(DestTy
);
192 return UndefValue::get(DestTy
);
194 // No compile-time operations on this type yet.
195 if (V
->getType() == Type::getPPC_FP128Ty(Context
) || DestTy
== Type::getPPC_FP128Ty(Context
))
198 // If the cast operand is a constant expression, there's a few things we can
199 // do to try to simplify it.
200 if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(V
)) {
202 // Try hard to fold cast of cast because they are often eliminable.
203 if (unsigned newOpc
= foldConstantCastPair(opc
, CE
, DestTy
))
204 return ConstantExpr::getCast(newOpc
, CE
->getOperand(0), DestTy
);
205 } else if (CE
->getOpcode() == Instruction::GetElementPtr
) {
206 // If all of the indexes in the GEP are null values, there is no pointer
207 // adjustment going on. We might as well cast the source pointer.
208 bool isAllNull
= true;
209 for (unsigned i
= 1, e
= CE
->getNumOperands(); i
!= e
; ++i
)
210 if (!CE
->getOperand(i
)->isNullValue()) {
215 // This is casting one pointer type to another, always BitCast
216 return ConstantExpr::getPointerCast(CE
->getOperand(0), DestTy
);
220 // If the cast operand is a constant vector, perform the cast by
221 // operating on each element. In the cast of bitcasts, the element
222 // count may be mismatched; don't attempt to handle that here.
223 if (const ConstantVector
*CV
= dyn_cast
<ConstantVector
>(V
))
224 if (isa
<VectorType
>(DestTy
) &&
225 cast
<VectorType
>(DestTy
)->getNumElements() ==
226 CV
->getType()->getNumElements()) {
227 std::vector
<Constant
*> res
;
228 const VectorType
*DestVecTy
= cast
<VectorType
>(DestTy
);
229 const Type
*DstEltTy
= DestVecTy
->getElementType();
230 for (unsigned i
= 0, e
= CV
->getType()->getNumElements(); i
!= e
; ++i
)
231 res
.push_back(ConstantExpr::getCast(opc
,
232 CV
->getOperand(i
), DstEltTy
));
233 return ConstantVector::get(DestVecTy
, res
);
236 // We actually have to do a cast now. Perform the cast according to the
239 case Instruction::FPTrunc
:
240 case Instruction::FPExt
:
241 if (const ConstantFP
*FPC
= dyn_cast
<ConstantFP
>(V
)) {
243 APFloat Val
= FPC
->getValueAPF();
244 Val
.convert(DestTy
== Type::getFloatTy(Context
) ? APFloat::IEEEsingle
:
245 DestTy
== Type::getDoubleTy(Context
) ? APFloat::IEEEdouble
:
246 DestTy
== Type::getX86_FP80Ty(Context
) ? APFloat::x87DoubleExtended
:
247 DestTy
== Type::getFP128Ty(Context
) ? APFloat::IEEEquad
:
249 APFloat::rmNearestTiesToEven
, &ignored
);
250 return ConstantFP::get(Context
, Val
);
252 return 0; // Can't fold.
253 case Instruction::FPToUI
:
254 case Instruction::FPToSI
:
255 if (const ConstantFP
*FPC
= dyn_cast
<ConstantFP
>(V
)) {
256 const APFloat
&V
= FPC
->getValueAPF();
259 uint32_t DestBitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
260 (void) V
.convertToInteger(x
, DestBitWidth
, opc
==Instruction::FPToSI
,
261 APFloat::rmTowardZero
, &ignored
);
262 APInt
Val(DestBitWidth
, 2, x
);
263 return ConstantInt::get(Context
, Val
);
265 return 0; // Can't fold.
266 case Instruction::IntToPtr
: //always treated as unsigned
267 if (V
->isNullValue()) // Is it an integral null value?
268 return ConstantPointerNull::get(cast
<PointerType
>(DestTy
));
269 return 0; // Other pointer types cannot be casted
270 case Instruction::PtrToInt
: // always treated as unsigned
271 if (V
->isNullValue()) // is it a null pointer value?
272 return ConstantInt::get(DestTy
, 0);
273 return 0; // Other pointer types cannot be casted
274 case Instruction::UIToFP
:
275 case Instruction::SIToFP
:
276 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
277 APInt api
= CI
->getValue();
278 const uint64_t zero
[] = {0, 0};
279 APFloat apf
= APFloat(APInt(DestTy
->getPrimitiveSizeInBits(),
281 (void)apf
.convertFromAPInt(api
,
282 opc
==Instruction::SIToFP
,
283 APFloat::rmNearestTiesToEven
);
284 return ConstantFP::get(Context
, apf
);
287 case Instruction::ZExt
:
288 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
289 uint32_t BitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
290 APInt
Result(CI
->getValue());
291 Result
.zext(BitWidth
);
292 return ConstantInt::get(Context
, Result
);
295 case Instruction::SExt
:
296 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
297 uint32_t BitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
298 APInt
Result(CI
->getValue());
299 Result
.sext(BitWidth
);
300 return ConstantInt::get(Context
, Result
);
303 case Instruction::Trunc
:
304 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
305 uint32_t BitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
306 APInt
Result(CI
->getValue());
307 Result
.trunc(BitWidth
);
308 return ConstantInt::get(Context
, Result
);
311 case Instruction::BitCast
:
312 return FoldBitCast(Context
, const_cast<Constant
*>(V
), DestTy
);
314 assert(!"Invalid CE CastInst opcode");
318 llvm_unreachable("Failed to cast constant expression");
322 Constant
*llvm::ConstantFoldSelectInstruction(LLVMContext
&,
323 const Constant
*Cond
,
325 const Constant
*V2
) {
326 if (const ConstantInt
*CB
= dyn_cast
<ConstantInt
>(Cond
))
327 return const_cast<Constant
*>(CB
->getZExtValue() ? V1
: V2
);
329 if (isa
<UndefValue
>(V1
)) return const_cast<Constant
*>(V2
);
330 if (isa
<UndefValue
>(V2
)) return const_cast<Constant
*>(V1
);
331 if (isa
<UndefValue
>(Cond
)) return const_cast<Constant
*>(V1
);
332 if (V1
== V2
) return const_cast<Constant
*>(V1
);
336 Constant
*llvm::ConstantFoldExtractElementInstruction(LLVMContext
&Context
,
338 const Constant
*Idx
) {
339 if (isa
<UndefValue
>(Val
)) // ee(undef, x) -> undef
340 return UndefValue::get(cast
<VectorType
>(Val
->getType())->getElementType());
341 if (Val
->isNullValue()) // ee(zero, x) -> zero
342 return Constant::getNullValue(
343 cast
<VectorType
>(Val
->getType())->getElementType());
345 if (const ConstantVector
*CVal
= dyn_cast
<ConstantVector
>(Val
)) {
346 if (const ConstantInt
*CIdx
= dyn_cast
<ConstantInt
>(Idx
)) {
347 return CVal
->getOperand(CIdx
->getZExtValue());
348 } else if (isa
<UndefValue
>(Idx
)) {
349 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
350 return CVal
->getOperand(0);
356 Constant
*llvm::ConstantFoldInsertElementInstruction(LLVMContext
&Context
,
359 const Constant
*Idx
) {
360 const ConstantInt
*CIdx
= dyn_cast
<ConstantInt
>(Idx
);
362 APInt idxVal
= CIdx
->getValue();
363 if (isa
<UndefValue
>(Val
)) {
364 // Insertion of scalar constant into vector undef
365 // Optimize away insertion of undef
366 if (isa
<UndefValue
>(Elt
))
367 return const_cast<Constant
*>(Val
);
368 // Otherwise break the aggregate undef into multiple undefs and do
371 cast
<VectorType
>(Val
->getType())->getNumElements();
372 std::vector
<Constant
*> Ops
;
374 for (unsigned i
= 0; i
< numOps
; ++i
) {
376 (idxVal
== i
) ? Elt
: UndefValue::get(Elt
->getType());
377 Ops
.push_back(const_cast<Constant
*>(Op
));
379 return ConstantVector::get(Ops
);
381 if (isa
<ConstantAggregateZero
>(Val
)) {
382 // Insertion of scalar constant into vector aggregate zero
383 // Optimize away insertion of zero
384 if (Elt
->isNullValue())
385 return const_cast<Constant
*>(Val
);
386 // Otherwise break the aggregate zero into multiple zeros and do
389 cast
<VectorType
>(Val
->getType())->getNumElements();
390 std::vector
<Constant
*> Ops
;
392 for (unsigned i
= 0; i
< numOps
; ++i
) {
394 (idxVal
== i
) ? Elt
: Constant::getNullValue(Elt
->getType());
395 Ops
.push_back(const_cast<Constant
*>(Op
));
397 return ConstantVector::get(Ops
);
399 if (const ConstantVector
*CVal
= dyn_cast
<ConstantVector
>(Val
)) {
400 // Insertion of scalar constant into vector constant
401 std::vector
<Constant
*> Ops
;
402 Ops
.reserve(CVal
->getNumOperands());
403 for (unsigned i
= 0; i
< CVal
->getNumOperands(); ++i
) {
405 (idxVal
== i
) ? Elt
: cast
<Constant
>(CVal
->getOperand(i
));
406 Ops
.push_back(const_cast<Constant
*>(Op
));
408 return ConstantVector::get(Ops
);
414 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
415 /// return the specified element value. Otherwise return null.
416 static Constant
*GetVectorElement(LLVMContext
&Context
, const Constant
*C
,
418 if (const ConstantVector
*CV
= dyn_cast
<ConstantVector
>(C
))
419 return CV
->getOperand(EltNo
);
421 const Type
*EltTy
= cast
<VectorType
>(C
->getType())->getElementType();
422 if (isa
<ConstantAggregateZero
>(C
))
423 return Constant::getNullValue(EltTy
);
424 if (isa
<UndefValue
>(C
))
425 return UndefValue::get(EltTy
);
429 Constant
*llvm::ConstantFoldShuffleVectorInstruction(LLVMContext
&Context
,
432 const Constant
*Mask
) {
433 // Undefined shuffle mask -> undefined value.
434 if (isa
<UndefValue
>(Mask
)) return UndefValue::get(V1
->getType());
436 unsigned MaskNumElts
= cast
<VectorType
>(Mask
->getType())->getNumElements();
437 unsigned SrcNumElts
= cast
<VectorType
>(V1
->getType())->getNumElements();
438 const Type
*EltTy
= cast
<VectorType
>(V1
->getType())->getElementType();
440 // Loop over the shuffle mask, evaluating each element.
441 SmallVector
<Constant
*, 32> Result
;
442 for (unsigned i
= 0; i
!= MaskNumElts
; ++i
) {
443 Constant
*InElt
= GetVectorElement(Context
, Mask
, i
);
444 if (InElt
== 0) return 0;
446 if (isa
<UndefValue
>(InElt
))
447 InElt
= UndefValue::get(EltTy
);
448 else if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(InElt
)) {
449 unsigned Elt
= CI
->getZExtValue();
450 if (Elt
>= SrcNumElts
*2)
451 InElt
= UndefValue::get(EltTy
);
452 else if (Elt
>= SrcNumElts
)
453 InElt
= GetVectorElement(Context
, V2
, Elt
- SrcNumElts
);
455 InElt
= GetVectorElement(Context
, V1
, Elt
);
456 if (InElt
== 0) return 0;
461 Result
.push_back(InElt
);
464 return ConstantVector::get(&Result
[0], Result
.size());
467 Constant
*llvm::ConstantFoldExtractValueInstruction(LLVMContext
&Context
,
469 const unsigned *Idxs
,
471 // Base case: no indices, so return the entire value.
473 return const_cast<Constant
*>(Agg
);
475 if (isa
<UndefValue
>(Agg
)) // ev(undef, x) -> undef
476 return UndefValue::get(ExtractValueInst::getIndexedType(Agg
->getType(),
480 if (isa
<ConstantAggregateZero
>(Agg
)) // ev(0, x) -> 0
482 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg
->getType(),
486 // Otherwise recurse.
487 return ConstantFoldExtractValueInstruction(Context
, Agg
->getOperand(*Idxs
),
491 Constant
*llvm::ConstantFoldInsertValueInstruction(LLVMContext
&Context
,
494 const unsigned *Idxs
,
496 // Base case: no indices, so replace the entire value.
498 return const_cast<Constant
*>(Val
);
500 if (isa
<UndefValue
>(Agg
)) {
501 // Insertion of constant into aggregate undef
502 // Optimize away insertion of undef.
503 if (isa
<UndefValue
>(Val
))
504 return const_cast<Constant
*>(Agg
);
506 // Otherwise break the aggregate undef into multiple undefs and do
508 const CompositeType
*AggTy
= cast
<CompositeType
>(Agg
->getType());
510 if (const ArrayType
*AR
= dyn_cast
<ArrayType
>(AggTy
))
511 numOps
= AR
->getNumElements();
513 numOps
= cast
<StructType
>(AggTy
)->getNumElements();
515 std::vector
<Constant
*> Ops(numOps
);
516 for (unsigned i
= 0; i
< numOps
; ++i
) {
517 const Type
*MemberTy
= AggTy
->getTypeAtIndex(i
);
520 ConstantFoldInsertValueInstruction(Context
, UndefValue::get(MemberTy
),
521 Val
, Idxs
+1, NumIdx
-1) :
522 UndefValue::get(MemberTy
);
523 Ops
[i
] = const_cast<Constant
*>(Op
);
526 if (const StructType
* ST
= dyn_cast
<StructType
>(AggTy
))
527 return ConstantStruct::get(Context
, Ops
, ST
->isPacked());
528 return ConstantArray::get(cast
<ArrayType
>(AggTy
), Ops
);
531 if (isa
<ConstantAggregateZero
>(Agg
)) {
532 // Insertion of constant into aggregate zero
533 // Optimize away insertion of zero.
534 if (Val
->isNullValue())
535 return const_cast<Constant
*>(Agg
);
537 // Otherwise break the aggregate zero into multiple zeros and do
539 const CompositeType
*AggTy
= cast
<CompositeType
>(Agg
->getType());
541 if (const ArrayType
*AR
= dyn_cast
<ArrayType
>(AggTy
))
542 numOps
= AR
->getNumElements();
544 numOps
= cast
<StructType
>(AggTy
)->getNumElements();
546 std::vector
<Constant
*> Ops(numOps
);
547 for (unsigned i
= 0; i
< numOps
; ++i
) {
548 const Type
*MemberTy
= AggTy
->getTypeAtIndex(i
);
551 ConstantFoldInsertValueInstruction(Context
,
552 Constant::getNullValue(MemberTy
),
553 Val
, Idxs
+1, NumIdx
-1) :
554 Constant::getNullValue(MemberTy
);
555 Ops
[i
] = const_cast<Constant
*>(Op
);
558 if (const StructType
* ST
= dyn_cast
<StructType
>(AggTy
))
559 return ConstantStruct::get(Context
, Ops
, ST
->isPacked());
560 return ConstantArray::get(cast
<ArrayType
>(AggTy
), Ops
);
563 if (isa
<ConstantStruct
>(Agg
) || isa
<ConstantArray
>(Agg
)) {
564 // Insertion of constant into aggregate constant.
565 std::vector
<Constant
*> Ops(Agg
->getNumOperands());
566 for (unsigned i
= 0; i
< Agg
->getNumOperands(); ++i
) {
569 ConstantFoldInsertValueInstruction(Context
, Agg
->getOperand(i
),
570 Val
, Idxs
+1, NumIdx
-1) :
572 Ops
[i
] = const_cast<Constant
*>(Op
);
575 if (const StructType
* ST
= dyn_cast
<StructType
>(Agg
->getType()))
576 return ConstantStruct::get(Context
, Ops
, ST
->isPacked());
577 return ConstantArray::get(cast
<ArrayType
>(Agg
->getType()), Ops
);
584 Constant
*llvm::ConstantFoldBinaryInstruction(LLVMContext
&Context
,
587 const Constant
*C2
) {
588 // No compile-time operations on this type yet.
589 if (C1
->getType() == Type::getPPC_FP128Ty(Context
))
592 // Handle UndefValue up front.
593 if (isa
<UndefValue
>(C1
) || isa
<UndefValue
>(C2
)) {
595 case Instruction::Xor
:
596 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
))
597 // Handle undef ^ undef -> 0 special case. This is a common
599 return Constant::getNullValue(C1
->getType());
601 case Instruction::Add
:
602 case Instruction::Sub
:
603 return UndefValue::get(C1
->getType());
604 case Instruction::Mul
:
605 case Instruction::And
:
606 return Constant::getNullValue(C1
->getType());
607 case Instruction::UDiv
:
608 case Instruction::SDiv
:
609 case Instruction::URem
:
610 case Instruction::SRem
:
611 if (!isa
<UndefValue
>(C2
)) // undef / X -> 0
612 return Constant::getNullValue(C1
->getType());
613 return const_cast<Constant
*>(C2
); // X / undef -> undef
614 case Instruction::Or
: // X | undef -> -1
615 if (const VectorType
*PTy
= dyn_cast
<VectorType
>(C1
->getType()))
616 return Constant::getAllOnesValue(PTy
);
617 return Constant::getAllOnesValue(C1
->getType());
618 case Instruction::LShr
:
619 if (isa
<UndefValue
>(C2
) && isa
<UndefValue
>(C1
))
620 return const_cast<Constant
*>(C1
); // undef lshr undef -> undef
621 return Constant::getNullValue(C1
->getType()); // X lshr undef -> 0
623 case Instruction::AShr
:
624 if (!isa
<UndefValue
>(C2
))
625 return const_cast<Constant
*>(C1
); // undef ashr X --> undef
626 else if (isa
<UndefValue
>(C1
))
627 return const_cast<Constant
*>(C1
); // undef ashr undef -> undef
629 return const_cast<Constant
*>(C1
); // X ashr undef --> X
630 case Instruction::Shl
:
631 // undef << X -> 0 or X << undef -> 0
632 return Constant::getNullValue(C1
->getType());
636 // Handle simplifications when the RHS is a constant int.
637 if (const ConstantInt
*CI2
= dyn_cast
<ConstantInt
>(C2
)) {
639 case Instruction::Add
:
640 if (CI2
->equalsInt(0)) return const_cast<Constant
*>(C1
); // X + 0 == X
642 case Instruction::Sub
:
643 if (CI2
->equalsInt(0)) return const_cast<Constant
*>(C1
); // X - 0 == X
645 case Instruction::Mul
:
646 if (CI2
->equalsInt(0)) return const_cast<Constant
*>(C2
); // X * 0 == 0
647 if (CI2
->equalsInt(1))
648 return const_cast<Constant
*>(C1
); // X * 1 == X
650 case Instruction::UDiv
:
651 case Instruction::SDiv
:
652 if (CI2
->equalsInt(1))
653 return const_cast<Constant
*>(C1
); // X / 1 == X
654 if (CI2
->equalsInt(0))
655 return UndefValue::get(CI2
->getType()); // X / 0 == undef
657 case Instruction::URem
:
658 case Instruction::SRem
:
659 if (CI2
->equalsInt(1))
660 return Constant::getNullValue(CI2
->getType()); // X % 1 == 0
661 if (CI2
->equalsInt(0))
662 return UndefValue::get(CI2
->getType()); // X % 0 == undef
664 case Instruction::And
:
665 if (CI2
->isZero()) return const_cast<Constant
*>(C2
); // X & 0 == 0
666 if (CI2
->isAllOnesValue())
667 return const_cast<Constant
*>(C1
); // X & -1 == X
669 if (const ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
670 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
671 if (CE1
->getOpcode() == Instruction::ZExt
) {
672 unsigned DstWidth
= CI2
->getType()->getBitWidth();
674 CE1
->getOperand(0)->getType()->getPrimitiveSizeInBits();
675 APInt
PossiblySetBits(APInt::getLowBitsSet(DstWidth
, SrcWidth
));
676 if ((PossiblySetBits
& CI2
->getValue()) == PossiblySetBits
)
677 return const_cast<Constant
*>(C1
);
680 // If and'ing the address of a global with a constant, fold it.
681 if (CE1
->getOpcode() == Instruction::PtrToInt
&&
682 isa
<GlobalValue
>(CE1
->getOperand(0))) {
683 GlobalValue
*GV
= cast
<GlobalValue
>(CE1
->getOperand(0));
685 // Functions are at least 4-byte aligned.
686 unsigned GVAlign
= GV
->getAlignment();
687 if (isa
<Function
>(GV
))
688 GVAlign
= std::max(GVAlign
, 4U);
691 unsigned DstWidth
= CI2
->getType()->getBitWidth();
692 unsigned SrcWidth
= std::min(DstWidth
, Log2_32(GVAlign
));
693 APInt
BitsNotSet(APInt::getLowBitsSet(DstWidth
, SrcWidth
));
695 // If checking bits we know are clear, return zero.
696 if ((CI2
->getValue() & BitsNotSet
) == CI2
->getValue())
697 return Constant::getNullValue(CI2
->getType());
702 case Instruction::Or
:
703 if (CI2
->equalsInt(0)) return const_cast<Constant
*>(C1
); // X | 0 == X
704 if (CI2
->isAllOnesValue())
705 return const_cast<Constant
*>(C2
); // X | -1 == -1
707 case Instruction::Xor
:
708 if (CI2
->equalsInt(0)) return const_cast<Constant
*>(C1
); // X ^ 0 == X
710 case Instruction::AShr
:
711 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
712 if (const ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
))
713 if (CE1
->getOpcode() == Instruction::ZExt
) // Top bits known zero.
714 return ConstantExpr::getLShr(const_cast<Constant
*>(C1
),
715 const_cast<Constant
*>(C2
));
720 // At this point we know neither constant is an UndefValue.
721 if (const ConstantInt
*CI1
= dyn_cast
<ConstantInt
>(C1
)) {
722 if (const ConstantInt
*CI2
= dyn_cast
<ConstantInt
>(C2
)) {
723 using namespace APIntOps
;
724 const APInt
&C1V
= CI1
->getValue();
725 const APInt
&C2V
= CI2
->getValue();
729 case Instruction::Add
:
730 return ConstantInt::get(Context
, C1V
+ C2V
);
731 case Instruction::Sub
:
732 return ConstantInt::get(Context
, C1V
- C2V
);
733 case Instruction::Mul
:
734 return ConstantInt::get(Context
, C1V
* C2V
);
735 case Instruction::UDiv
:
736 assert(!CI2
->isNullValue() && "Div by zero handled above");
737 return ConstantInt::get(Context
, C1V
.udiv(C2V
));
738 case Instruction::SDiv
:
739 assert(!CI2
->isNullValue() && "Div by zero handled above");
740 if (C2V
.isAllOnesValue() && C1V
.isMinSignedValue())
741 return UndefValue::get(CI1
->getType()); // MIN_INT / -1 -> undef
742 return ConstantInt::get(Context
, C1V
.sdiv(C2V
));
743 case Instruction::URem
:
744 assert(!CI2
->isNullValue() && "Div by zero handled above");
745 return ConstantInt::get(Context
, C1V
.urem(C2V
));
746 case Instruction::SRem
:
747 assert(!CI2
->isNullValue() && "Div by zero handled above");
748 if (C2V
.isAllOnesValue() && C1V
.isMinSignedValue())
749 return UndefValue::get(CI1
->getType()); // MIN_INT % -1 -> undef
750 return ConstantInt::get(Context
, C1V
.srem(C2V
));
751 case Instruction::And
:
752 return ConstantInt::get(Context
, C1V
& C2V
);
753 case Instruction::Or
:
754 return ConstantInt::get(Context
, C1V
| C2V
);
755 case Instruction::Xor
:
756 return ConstantInt::get(Context
, C1V
^ C2V
);
757 case Instruction::Shl
: {
758 uint32_t shiftAmt
= C2V
.getZExtValue();
759 if (shiftAmt
< C1V
.getBitWidth())
760 return ConstantInt::get(Context
, C1V
.shl(shiftAmt
));
762 return UndefValue::get(C1
->getType()); // too big shift is undef
764 case Instruction::LShr
: {
765 uint32_t shiftAmt
= C2V
.getZExtValue();
766 if (shiftAmt
< C1V
.getBitWidth())
767 return ConstantInt::get(Context
, C1V
.lshr(shiftAmt
));
769 return UndefValue::get(C1
->getType()); // too big shift is undef
771 case Instruction::AShr
: {
772 uint32_t shiftAmt
= C2V
.getZExtValue();
773 if (shiftAmt
< C1V
.getBitWidth())
774 return ConstantInt::get(Context
, C1V
.ashr(shiftAmt
));
776 return UndefValue::get(C1
->getType()); // too big shift is undef
782 case Instruction::SDiv
:
783 case Instruction::UDiv
:
784 case Instruction::URem
:
785 case Instruction::SRem
:
786 case Instruction::LShr
:
787 case Instruction::AShr
:
788 case Instruction::Shl
:
789 if (CI1
->equalsInt(0)) return const_cast<Constant
*>(C1
);
794 } else if (const ConstantFP
*CFP1
= dyn_cast
<ConstantFP
>(C1
)) {
795 if (const ConstantFP
*CFP2
= dyn_cast
<ConstantFP
>(C2
)) {
796 APFloat C1V
= CFP1
->getValueAPF();
797 APFloat C2V
= CFP2
->getValueAPF();
798 APFloat C3V
= C1V
; // copy for modification
802 case Instruction::FAdd
:
803 (void)C3V
.add(C2V
, APFloat::rmNearestTiesToEven
);
804 return ConstantFP::get(Context
, C3V
);
805 case Instruction::FSub
:
806 (void)C3V
.subtract(C2V
, APFloat::rmNearestTiesToEven
);
807 return ConstantFP::get(Context
, C3V
);
808 case Instruction::FMul
:
809 (void)C3V
.multiply(C2V
, APFloat::rmNearestTiesToEven
);
810 return ConstantFP::get(Context
, C3V
);
811 case Instruction::FDiv
:
812 (void)C3V
.divide(C2V
, APFloat::rmNearestTiesToEven
);
813 return ConstantFP::get(Context
, C3V
);
814 case Instruction::FRem
:
815 (void)C3V
.mod(C2V
, APFloat::rmNearestTiesToEven
);
816 return ConstantFP::get(Context
, C3V
);
819 } else if (const VectorType
*VTy
= dyn_cast
<VectorType
>(C1
->getType())) {
820 const ConstantVector
*CP1
= dyn_cast
<ConstantVector
>(C1
);
821 const ConstantVector
*CP2
= dyn_cast
<ConstantVector
>(C2
);
822 if ((CP1
!= NULL
|| isa
<ConstantAggregateZero
>(C1
)) &&
823 (CP2
!= NULL
|| isa
<ConstantAggregateZero
>(C2
))) {
824 std::vector
<Constant
*> Res
;
825 const Type
* EltTy
= VTy
->getElementType();
826 const Constant
*C1
= 0;
827 const Constant
*C2
= 0;
831 case Instruction::Add
:
832 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
833 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
834 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
835 Res
.push_back(ConstantExpr::getAdd(const_cast<Constant
*>(C1
),
836 const_cast<Constant
*>(C2
)));
838 return ConstantVector::get(Res
);
839 case Instruction::FAdd
:
840 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
841 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
842 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
843 Res
.push_back(ConstantExpr::getFAdd(const_cast<Constant
*>(C1
),
844 const_cast<Constant
*>(C2
)));
846 return ConstantVector::get(Res
);
847 case Instruction::Sub
:
848 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
849 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
850 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
851 Res
.push_back(ConstantExpr::getSub(const_cast<Constant
*>(C1
),
852 const_cast<Constant
*>(C2
)));
854 return ConstantVector::get(Res
);
855 case Instruction::FSub
:
856 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
857 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
858 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
859 Res
.push_back(ConstantExpr::getFSub(const_cast<Constant
*>(C1
),
860 const_cast<Constant
*>(C2
)));
862 return ConstantVector::get(Res
);
863 case Instruction::Mul
:
864 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
865 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
866 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
867 Res
.push_back(ConstantExpr::getMul(const_cast<Constant
*>(C1
),
868 const_cast<Constant
*>(C2
)));
870 return ConstantVector::get(Res
);
871 case Instruction::FMul
:
872 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
873 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
874 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
875 Res
.push_back(ConstantExpr::getFMul(const_cast<Constant
*>(C1
),
876 const_cast<Constant
*>(C2
)));
878 return ConstantVector::get(Res
);
879 case Instruction::UDiv
:
880 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
881 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
882 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
883 Res
.push_back(ConstantExpr::getUDiv(const_cast<Constant
*>(C1
),
884 const_cast<Constant
*>(C2
)));
886 return ConstantVector::get(Res
);
887 case Instruction::SDiv
:
888 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
889 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
890 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
891 Res
.push_back(ConstantExpr::getSDiv(const_cast<Constant
*>(C1
),
892 const_cast<Constant
*>(C2
)));
894 return ConstantVector::get(Res
);
895 case Instruction::FDiv
:
896 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
897 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
898 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
899 Res
.push_back(ConstantExpr::getFDiv(const_cast<Constant
*>(C1
),
900 const_cast<Constant
*>(C2
)));
902 return ConstantVector::get(Res
);
903 case Instruction::URem
:
904 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
905 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
906 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
907 Res
.push_back(ConstantExpr::getURem(const_cast<Constant
*>(C1
),
908 const_cast<Constant
*>(C2
)));
910 return ConstantVector::get(Res
);
911 case Instruction::SRem
:
912 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
913 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
914 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
915 Res
.push_back(ConstantExpr::getSRem(const_cast<Constant
*>(C1
),
916 const_cast<Constant
*>(C2
)));
918 return ConstantVector::get(Res
);
919 case Instruction::FRem
:
920 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
921 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
922 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
923 Res
.push_back(ConstantExpr::getFRem(const_cast<Constant
*>(C1
),
924 const_cast<Constant
*>(C2
)));
926 return ConstantVector::get(Res
);
927 case Instruction::And
:
928 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
929 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
930 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
931 Res
.push_back(ConstantExpr::getAnd(const_cast<Constant
*>(C1
),
932 const_cast<Constant
*>(C2
)));
934 return ConstantVector::get(Res
);
935 case Instruction::Or
:
936 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
937 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
938 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
939 Res
.push_back(ConstantExpr::getOr(const_cast<Constant
*>(C1
),
940 const_cast<Constant
*>(C2
)));
942 return ConstantVector::get(Res
);
943 case Instruction::Xor
:
944 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
945 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
946 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
947 Res
.push_back(ConstantExpr::getXor(const_cast<Constant
*>(C1
),
948 const_cast<Constant
*>(C2
)));
950 return ConstantVector::get(Res
);
951 case Instruction::LShr
:
952 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
953 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
954 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
955 Res
.push_back(ConstantExpr::getLShr(const_cast<Constant
*>(C1
),
956 const_cast<Constant
*>(C2
)));
958 return ConstantVector::get(Res
);
959 case Instruction::AShr
:
960 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
961 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
962 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
963 Res
.push_back(ConstantExpr::getAShr(const_cast<Constant
*>(C1
),
964 const_cast<Constant
*>(C2
)));
966 return ConstantVector::get(Res
);
967 case Instruction::Shl
:
968 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
969 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
970 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
971 Res
.push_back(ConstantExpr::getShl(const_cast<Constant
*>(C1
),
972 const_cast<Constant
*>(C2
)));
974 return ConstantVector::get(Res
);
979 if (isa
<ConstantExpr
>(C1
)) {
980 // There are many possible foldings we could do here. We should probably
981 // at least fold add of a pointer with an integer into the appropriate
982 // getelementptr. This will improve alias analysis a bit.
983 } else if (isa
<ConstantExpr
>(C2
)) {
984 // If C2 is a constant expr and C1 isn't, flop them around and fold the
985 // other way if possible.
987 case Instruction::Add
:
988 case Instruction::FAdd
:
989 case Instruction::Mul
:
990 case Instruction::FMul
:
991 case Instruction::And
:
992 case Instruction::Or
:
993 case Instruction::Xor
:
994 // No change of opcode required.
995 return ConstantFoldBinaryInstruction(Context
, Opcode
, C2
, C1
);
997 case Instruction::Shl
:
998 case Instruction::LShr
:
999 case Instruction::AShr
:
1000 case Instruction::Sub
:
1001 case Instruction::FSub
:
1002 case Instruction::SDiv
:
1003 case Instruction::UDiv
:
1004 case Instruction::FDiv
:
1005 case Instruction::URem
:
1006 case Instruction::SRem
:
1007 case Instruction::FRem
:
1008 default: // These instructions cannot be flopped around.
1013 // We don't know how to fold this.
1017 /// isZeroSizedType - This type is zero sized if its an array or structure of
1018 /// zero sized types. The only leaf zero sized type is an empty structure.
1019 static bool isMaybeZeroSizedType(const Type
*Ty
) {
1020 if (isa
<OpaqueType
>(Ty
)) return true; // Can't say.
1021 if (const StructType
*STy
= dyn_cast
<StructType
>(Ty
)) {
1023 // If all of elements have zero size, this does too.
1024 for (unsigned i
= 0, e
= STy
->getNumElements(); i
!= e
; ++i
)
1025 if (!isMaybeZeroSizedType(STy
->getElementType(i
))) return false;
1028 } else if (const ArrayType
*ATy
= dyn_cast
<ArrayType
>(Ty
)) {
1029 return isMaybeZeroSizedType(ATy
->getElementType());
1034 /// IdxCompare - Compare the two constants as though they were getelementptr
1035 /// indices. This allows coersion of the types to be the same thing.
1037 /// If the two constants are the "same" (after coersion), return 0. If the
1038 /// first is less than the second, return -1, if the second is less than the
1039 /// first, return 1. If the constants are not integral, return -2.
1041 static int IdxCompare(LLVMContext
&Context
, Constant
*C1
, Constant
*C2
,
1043 if (C1
== C2
) return 0;
1045 // Ok, we found a different index. If they are not ConstantInt, we can't do
1046 // anything with them.
1047 if (!isa
<ConstantInt
>(C1
) || !isa
<ConstantInt
>(C2
))
1048 return -2; // don't know!
1050 // Ok, we have two differing integer indices. Sign extend them to be the same
1051 // type. Long is always big enough, so we use it.
1052 if (C1
->getType() != Type::getInt64Ty(Context
))
1053 C1
= ConstantExpr::getSExt(C1
, Type::getInt64Ty(Context
));
1055 if (C2
->getType() != Type::getInt64Ty(Context
))
1056 C2
= ConstantExpr::getSExt(C2
, Type::getInt64Ty(Context
));
1058 if (C1
== C2
) return 0; // They are equal
1060 // If the type being indexed over is really just a zero sized type, there is
1061 // no pointer difference being made here.
1062 if (isMaybeZeroSizedType(ElTy
))
1063 return -2; // dunno.
1065 // If they are really different, now that they are the same type, then we
1066 // found a difference!
1067 if (cast
<ConstantInt
>(C1
)->getSExtValue() <
1068 cast
<ConstantInt
>(C2
)->getSExtValue())
1074 /// evaluateFCmpRelation - This function determines if there is anything we can
1075 /// decide about the two constants provided. This doesn't need to handle simple
1076 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1077 /// If we can determine that the two constants have a particular relation to
1078 /// each other, we should return the corresponding FCmpInst predicate,
1079 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1080 /// ConstantFoldCompareInstruction.
1082 /// To simplify this code we canonicalize the relation so that the first
1083 /// operand is always the most "complex" of the two. We consider ConstantFP
1084 /// to be the simplest, and ConstantExprs to be the most complex.
1085 static FCmpInst::Predicate
evaluateFCmpRelation(LLVMContext
&Context
,
1087 const Constant
*V2
) {
1088 assert(V1
->getType() == V2
->getType() &&
1089 "Cannot compare values of different types!");
1091 // No compile-time operations on this type yet.
1092 if (V1
->getType() == Type::getPPC_FP128Ty(Context
))
1093 return FCmpInst::BAD_FCMP_PREDICATE
;
1095 // Handle degenerate case quickly
1096 if (V1
== V2
) return FCmpInst::FCMP_OEQ
;
1098 if (!isa
<ConstantExpr
>(V1
)) {
1099 if (!isa
<ConstantExpr
>(V2
)) {
1100 // We distilled thisUse the standard constant folder for a few cases
1102 Constant
*C1
= const_cast<Constant
*>(V1
);
1103 Constant
*C2
= const_cast<Constant
*>(V2
);
1104 R
= dyn_cast
<ConstantInt
>(
1105 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ
, C1
, C2
));
1106 if (R
&& !R
->isZero())
1107 return FCmpInst::FCMP_OEQ
;
1108 R
= dyn_cast
<ConstantInt
>(
1109 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT
, C1
, C2
));
1110 if (R
&& !R
->isZero())
1111 return FCmpInst::FCMP_OLT
;
1112 R
= dyn_cast
<ConstantInt
>(
1113 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT
, C1
, C2
));
1114 if (R
&& !R
->isZero())
1115 return FCmpInst::FCMP_OGT
;
1117 // Nothing more we can do
1118 return FCmpInst::BAD_FCMP_PREDICATE
;
1121 // If the first operand is simple and second is ConstantExpr, swap operands.
1122 FCmpInst::Predicate SwappedRelation
= evaluateFCmpRelation(Context
, V2
, V1
);
1123 if (SwappedRelation
!= FCmpInst::BAD_FCMP_PREDICATE
)
1124 return FCmpInst::getSwappedPredicate(SwappedRelation
);
1126 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1127 // constantexpr or a simple constant.
1128 const ConstantExpr
*CE1
= cast
<ConstantExpr
>(V1
);
1129 switch (CE1
->getOpcode()) {
1130 case Instruction::FPTrunc
:
1131 case Instruction::FPExt
:
1132 case Instruction::UIToFP
:
1133 case Instruction::SIToFP
:
1134 // We might be able to do something with these but we don't right now.
1140 // There are MANY other foldings that we could perform here. They will
1141 // probably be added on demand, as they seem needed.
1142 return FCmpInst::BAD_FCMP_PREDICATE
;
1145 /// evaluateICmpRelation - This function determines if there is anything we can
1146 /// decide about the two constants provided. This doesn't need to handle simple
1147 /// things like integer comparisons, but should instead handle ConstantExprs
1148 /// and GlobalValues. If we can determine that the two constants have a
1149 /// particular relation to each other, we should return the corresponding ICmp
1150 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1152 /// To simplify this code we canonicalize the relation so that the first
1153 /// operand is always the most "complex" of the two. We consider simple
1154 /// constants (like ConstantInt) to be the simplest, followed by
1155 /// GlobalValues, followed by ConstantExpr's (the most complex).
1157 static ICmpInst::Predicate
evaluateICmpRelation(LLVMContext
&Context
,
1161 assert(V1
->getType() == V2
->getType() &&
1162 "Cannot compare different types of values!");
1163 if (V1
== V2
) return ICmpInst::ICMP_EQ
;
1165 if (!isa
<ConstantExpr
>(V1
) && !isa
<GlobalValue
>(V1
)) {
1166 if (!isa
<GlobalValue
>(V2
) && !isa
<ConstantExpr
>(V2
)) {
1167 // We distilled this down to a simple case, use the standard constant
1170 Constant
*C1
= const_cast<Constant
*>(V1
);
1171 Constant
*C2
= const_cast<Constant
*>(V2
);
1172 ICmpInst::Predicate pred
= ICmpInst::ICMP_EQ
;
1173 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, C1
, C2
));
1174 if (R
&& !R
->isZero())
1176 pred
= isSigned
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
;
1177 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, C1
, C2
));
1178 if (R
&& !R
->isZero())
1180 pred
= isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1181 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, C1
, C2
));
1182 if (R
&& !R
->isZero())
1185 // If we couldn't figure it out, bail.
1186 return ICmpInst::BAD_ICMP_PREDICATE
;
1189 // If the first operand is simple, swap operands.
1190 ICmpInst::Predicate SwappedRelation
=
1191 evaluateICmpRelation(Context
, V2
, V1
, isSigned
);
1192 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1193 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1195 } else if (const GlobalValue
*CPR1
= dyn_cast
<GlobalValue
>(V1
)) {
1196 if (isa
<ConstantExpr
>(V2
)) { // Swap as necessary.
1197 ICmpInst::Predicate SwappedRelation
=
1198 evaluateICmpRelation(Context
, V2
, V1
, isSigned
);
1199 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1200 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1202 return ICmpInst::BAD_ICMP_PREDICATE
;
1205 // Now we know that the RHS is a GlobalValue or simple constant,
1206 // which (since the types must match) means that it's a ConstantPointerNull.
1207 if (const GlobalValue
*CPR2
= dyn_cast
<GlobalValue
>(V2
)) {
1208 // Don't try to decide equality of aliases.
1209 if (!isa
<GlobalAlias
>(CPR1
) && !isa
<GlobalAlias
>(CPR2
))
1210 if (!CPR1
->hasExternalWeakLinkage() || !CPR2
->hasExternalWeakLinkage())
1211 return ICmpInst::ICMP_NE
;
1213 assert(isa
<ConstantPointerNull
>(V2
) && "Canonicalization guarantee!");
1214 // GlobalVals can never be null. Don't try to evaluate aliases.
1215 if (!CPR1
->hasExternalWeakLinkage() && !isa
<GlobalAlias
>(CPR1
))
1216 return ICmpInst::ICMP_NE
;
1219 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1220 // constantexpr, a CPR, or a simple constant.
1221 const ConstantExpr
*CE1
= cast
<ConstantExpr
>(V1
);
1222 const Constant
*CE1Op0
= CE1
->getOperand(0);
1224 switch (CE1
->getOpcode()) {
1225 case Instruction::Trunc
:
1226 case Instruction::FPTrunc
:
1227 case Instruction::FPExt
:
1228 case Instruction::FPToUI
:
1229 case Instruction::FPToSI
:
1230 break; // We can't evaluate floating point casts or truncations.
1232 case Instruction::UIToFP
:
1233 case Instruction::SIToFP
:
1234 case Instruction::BitCast
:
1235 case Instruction::ZExt
:
1236 case Instruction::SExt
:
1237 // If the cast is not actually changing bits, and the second operand is a
1238 // null pointer, do the comparison with the pre-casted value.
1239 if (V2
->isNullValue() &&
1240 (isa
<PointerType
>(CE1
->getType()) || CE1
->getType()->isInteger())) {
1241 bool sgnd
= isSigned
;
1242 if (CE1
->getOpcode() == Instruction::ZExt
) isSigned
= false;
1243 if (CE1
->getOpcode() == Instruction::SExt
) isSigned
= true;
1244 return evaluateICmpRelation(Context
, CE1Op0
,
1245 Constant::getNullValue(CE1Op0
->getType()),
1249 // If the dest type is a pointer type, and the RHS is a constantexpr cast
1250 // from the same type as the src of the LHS, evaluate the inputs. This is
1251 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
1252 // which happens a lot in compilers with tagged integers.
1253 if (const ConstantExpr
*CE2
= dyn_cast
<ConstantExpr
>(V2
))
1254 if (CE2
->isCast() && isa
<PointerType
>(CE1
->getType()) &&
1255 CE1
->getOperand(0)->getType() == CE2
->getOperand(0)->getType() &&
1256 CE1
->getOperand(0)->getType()->isInteger()) {
1257 bool sgnd
= isSigned
;
1258 if (CE1
->getOpcode() == Instruction::ZExt
) isSigned
= false;
1259 if (CE1
->getOpcode() == Instruction::SExt
) isSigned
= true;
1260 return evaluateICmpRelation(Context
, CE1
->getOperand(0),
1261 CE2
->getOperand(0), sgnd
);
1265 case Instruction::GetElementPtr
:
1266 // Ok, since this is a getelementptr, we know that the constant has a
1267 // pointer type. Check the various cases.
1268 if (isa
<ConstantPointerNull
>(V2
)) {
1269 // If we are comparing a GEP to a null pointer, check to see if the base
1270 // of the GEP equals the null pointer.
1271 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CE1Op0
)) {
1272 if (GV
->hasExternalWeakLinkage())
1273 // Weak linkage GVals could be zero or not. We're comparing that
1274 // to null pointer so its greater-or-equal
1275 return isSigned
? ICmpInst::ICMP_SGE
: ICmpInst::ICMP_UGE
;
1277 // If its not weak linkage, the GVal must have a non-zero address
1278 // so the result is greater-than
1279 return isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1280 } else if (isa
<ConstantPointerNull
>(CE1Op0
)) {
1281 // If we are indexing from a null pointer, check to see if we have any
1282 // non-zero indices.
1283 for (unsigned i
= 1, e
= CE1
->getNumOperands(); i
!= e
; ++i
)
1284 if (!CE1
->getOperand(i
)->isNullValue())
1285 // Offsetting from null, must not be equal.
1286 return isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1287 // Only zero indexes from null, must still be zero.
1288 return ICmpInst::ICMP_EQ
;
1290 // Otherwise, we can't really say if the first operand is null or not.
1291 } else if (const GlobalValue
*CPR2
= dyn_cast
<GlobalValue
>(V2
)) {
1292 if (isa
<ConstantPointerNull
>(CE1Op0
)) {
1293 if (CPR2
->hasExternalWeakLinkage())
1294 // Weak linkage GVals could be zero or not. We're comparing it to
1295 // a null pointer, so its less-or-equal
1296 return isSigned
? ICmpInst::ICMP_SLE
: ICmpInst::ICMP_ULE
;
1298 // If its not weak linkage, the GVal must have a non-zero address
1299 // so the result is less-than
1300 return isSigned
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
;
1301 } else if (const GlobalValue
*CPR1
= dyn_cast
<GlobalValue
>(CE1Op0
)) {
1303 // If this is a getelementptr of the same global, then it must be
1304 // different. Because the types must match, the getelementptr could
1305 // only have at most one index, and because we fold getelementptr's
1306 // with a single zero index, it must be nonzero.
1307 assert(CE1
->getNumOperands() == 2 &&
1308 !CE1
->getOperand(1)->isNullValue() &&
1309 "Suprising getelementptr!");
1310 return isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1312 // If they are different globals, we don't know what the value is,
1313 // but they can't be equal.
1314 return ICmpInst::ICMP_NE
;
1318 const ConstantExpr
*CE2
= cast
<ConstantExpr
>(V2
);
1319 const Constant
*CE2Op0
= CE2
->getOperand(0);
1321 // There are MANY other foldings that we could perform here. They will
1322 // probably be added on demand, as they seem needed.
1323 switch (CE2
->getOpcode()) {
1325 case Instruction::GetElementPtr
:
1326 // By far the most common case to handle is when the base pointers are
1327 // obviously to the same or different globals.
1328 if (isa
<GlobalValue
>(CE1Op0
) && isa
<GlobalValue
>(CE2Op0
)) {
1329 if (CE1Op0
!= CE2Op0
) // Don't know relative ordering, but not equal
1330 return ICmpInst::ICMP_NE
;
1331 // Ok, we know that both getelementptr instructions are based on the
1332 // same global. From this, we can precisely determine the relative
1333 // ordering of the resultant pointers.
1336 // The logic below assumes that the result of the comparison
1337 // can be determined by finding the first index that differs.
1338 // This doesn't work if there is over-indexing in any
1339 // subsequent indices, so check for that case first.
1340 if (!CE1
->isGEPWithNoNotionalOverIndexing() ||
1341 !CE2
->isGEPWithNoNotionalOverIndexing())
1342 return ICmpInst::BAD_ICMP_PREDICATE
; // Might be equal.
1344 // Compare all of the operands the GEP's have in common.
1345 gep_type_iterator GTI
= gep_type_begin(CE1
);
1346 for (;i
!= CE1
->getNumOperands() && i
!= CE2
->getNumOperands();
1348 switch (IdxCompare(Context
, CE1
->getOperand(i
),
1349 CE2
->getOperand(i
), GTI
.getIndexedType())) {
1350 case -1: return isSigned
? ICmpInst::ICMP_SLT
:ICmpInst::ICMP_ULT
;
1351 case 1: return isSigned
? ICmpInst::ICMP_SGT
:ICmpInst::ICMP_UGT
;
1352 case -2: return ICmpInst::BAD_ICMP_PREDICATE
;
1355 // Ok, we ran out of things they have in common. If any leftovers
1356 // are non-zero then we have a difference, otherwise we are equal.
1357 for (; i
< CE1
->getNumOperands(); ++i
)
1358 if (!CE1
->getOperand(i
)->isNullValue()) {
1359 if (isa
<ConstantInt
>(CE1
->getOperand(i
)))
1360 return isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1362 return ICmpInst::BAD_ICMP_PREDICATE
; // Might be equal.
1365 for (; i
< CE2
->getNumOperands(); ++i
)
1366 if (!CE2
->getOperand(i
)->isNullValue()) {
1367 if (isa
<ConstantInt
>(CE2
->getOperand(i
)))
1368 return isSigned
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
;
1370 return ICmpInst::BAD_ICMP_PREDICATE
; // Might be equal.
1372 return ICmpInst::ICMP_EQ
;
1381 return ICmpInst::BAD_ICMP_PREDICATE
;
1384 Constant
*llvm::ConstantFoldCompareInstruction(LLVMContext
&Context
,
1385 unsigned short pred
,
1387 const Constant
*C2
) {
1388 const Type
*ResultTy
;
1389 if (const VectorType
*VT
= dyn_cast
<VectorType
>(C1
->getType()))
1390 ResultTy
= VectorType::get(Type::getInt1Ty(Context
), VT
->getNumElements());
1392 ResultTy
= Type::getInt1Ty(Context
);
1394 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1395 if (pred
== FCmpInst::FCMP_FALSE
)
1396 return Constant::getNullValue(ResultTy
);
1398 if (pred
== FCmpInst::FCMP_TRUE
)
1399 return Constant::getAllOnesValue(ResultTy
);
1401 // Handle some degenerate cases first
1402 if (isa
<UndefValue
>(C1
) || isa
<UndefValue
>(C2
))
1403 return UndefValue::get(ResultTy
);
1405 // No compile-time operations on this type yet.
1406 if (C1
->getType() == Type::getPPC_FP128Ty(Context
))
1409 // icmp eq/ne(null,GV) -> false/true
1410 if (C1
->isNullValue()) {
1411 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(C2
))
1412 // Don't try to evaluate aliases. External weak GV can be null.
1413 if (!isa
<GlobalAlias
>(GV
) && !GV
->hasExternalWeakLinkage()) {
1414 if (pred
== ICmpInst::ICMP_EQ
)
1415 return ConstantInt::getFalse(Context
);
1416 else if (pred
== ICmpInst::ICMP_NE
)
1417 return ConstantInt::getTrue(Context
);
1419 // icmp eq/ne(GV,null) -> false/true
1420 } else if (C2
->isNullValue()) {
1421 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(C1
))
1422 // Don't try to evaluate aliases. External weak GV can be null.
1423 if (!isa
<GlobalAlias
>(GV
) && !GV
->hasExternalWeakLinkage()) {
1424 if (pred
== ICmpInst::ICMP_EQ
)
1425 return ConstantInt::getFalse(Context
);
1426 else if (pred
== ICmpInst::ICMP_NE
)
1427 return ConstantInt::getTrue(Context
);
1431 if (isa
<ConstantInt
>(C1
) && isa
<ConstantInt
>(C2
)) {
1432 APInt V1
= cast
<ConstantInt
>(C1
)->getValue();
1433 APInt V2
= cast
<ConstantInt
>(C2
)->getValue();
1435 default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1436 case ICmpInst::ICMP_EQ
:
1437 return ConstantInt::get(Type::getInt1Ty(Context
), V1
== V2
);
1438 case ICmpInst::ICMP_NE
:
1439 return ConstantInt::get(Type::getInt1Ty(Context
), V1
!= V2
);
1440 case ICmpInst::ICMP_SLT
:
1441 return ConstantInt::get(Type::getInt1Ty(Context
), V1
.slt(V2
));
1442 case ICmpInst::ICMP_SGT
:
1443 return ConstantInt::get(Type::getInt1Ty(Context
), V1
.sgt(V2
));
1444 case ICmpInst::ICMP_SLE
:
1445 return ConstantInt::get(Type::getInt1Ty(Context
), V1
.sle(V2
));
1446 case ICmpInst::ICMP_SGE
:
1447 return ConstantInt::get(Type::getInt1Ty(Context
), V1
.sge(V2
));
1448 case ICmpInst::ICMP_ULT
:
1449 return ConstantInt::get(Type::getInt1Ty(Context
), V1
.ult(V2
));
1450 case ICmpInst::ICMP_UGT
:
1451 return ConstantInt::get(Type::getInt1Ty(Context
), V1
.ugt(V2
));
1452 case ICmpInst::ICMP_ULE
:
1453 return ConstantInt::get(Type::getInt1Ty(Context
), V1
.ule(V2
));
1454 case ICmpInst::ICMP_UGE
:
1455 return ConstantInt::get(Type::getInt1Ty(Context
), V1
.uge(V2
));
1457 } else if (isa
<ConstantFP
>(C1
) && isa
<ConstantFP
>(C2
)) {
1458 APFloat C1V
= cast
<ConstantFP
>(C1
)->getValueAPF();
1459 APFloat C2V
= cast
<ConstantFP
>(C2
)->getValueAPF();
1460 APFloat::cmpResult R
= C1V
.compare(C2V
);
1462 default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1463 case FCmpInst::FCMP_FALSE
: return ConstantInt::getFalse(Context
);
1464 case FCmpInst::FCMP_TRUE
: return ConstantInt::getTrue(Context
);
1465 case FCmpInst::FCMP_UNO
:
1466 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpUnordered
);
1467 case FCmpInst::FCMP_ORD
:
1468 return ConstantInt::get(Type::getInt1Ty(Context
), R
!=APFloat::cmpUnordered
);
1469 case FCmpInst::FCMP_UEQ
:
1470 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpUnordered
||
1471 R
==APFloat::cmpEqual
);
1472 case FCmpInst::FCMP_OEQ
:
1473 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpEqual
);
1474 case FCmpInst::FCMP_UNE
:
1475 return ConstantInt::get(Type::getInt1Ty(Context
), R
!=APFloat::cmpEqual
);
1476 case FCmpInst::FCMP_ONE
:
1477 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpLessThan
||
1478 R
==APFloat::cmpGreaterThan
);
1479 case FCmpInst::FCMP_ULT
:
1480 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpUnordered
||
1481 R
==APFloat::cmpLessThan
);
1482 case FCmpInst::FCMP_OLT
:
1483 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpLessThan
);
1484 case FCmpInst::FCMP_UGT
:
1485 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpUnordered
||
1486 R
==APFloat::cmpGreaterThan
);
1487 case FCmpInst::FCMP_OGT
:
1488 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpGreaterThan
);
1489 case FCmpInst::FCMP_ULE
:
1490 return ConstantInt::get(Type::getInt1Ty(Context
), R
!=APFloat::cmpGreaterThan
);
1491 case FCmpInst::FCMP_OLE
:
1492 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpLessThan
||
1493 R
==APFloat::cmpEqual
);
1494 case FCmpInst::FCMP_UGE
:
1495 return ConstantInt::get(Type::getInt1Ty(Context
), R
!=APFloat::cmpLessThan
);
1496 case FCmpInst::FCMP_OGE
:
1497 return ConstantInt::get(Type::getInt1Ty(Context
), R
==APFloat::cmpGreaterThan
||
1498 R
==APFloat::cmpEqual
);
1500 } else if (isa
<VectorType
>(C1
->getType())) {
1501 SmallVector
<Constant
*, 16> C1Elts
, C2Elts
;
1502 C1
->getVectorElements(Context
, C1Elts
);
1503 C2
->getVectorElements(Context
, C2Elts
);
1505 // If we can constant fold the comparison of each element, constant fold
1506 // the whole vector comparison.
1507 SmallVector
<Constant
*, 4> ResElts
;
1508 for (unsigned i
= 0, e
= C1Elts
.size(); i
!= e
; ++i
) {
1509 // Compare the elements, producing an i1 result or constant expr.
1511 ConstantExpr::getCompare(pred
, C1Elts
[i
], C2Elts
[i
]));
1513 return ConstantVector::get(&ResElts
[0], ResElts
.size());
1516 if (C1
->getType()->isFloatingPoint()) {
1517 int Result
= -1; // -1 = unknown, 0 = known false, 1 = known true.
1518 switch (evaluateFCmpRelation(Context
, C1
, C2
)) {
1519 default: llvm_unreachable("Unknown relation!");
1520 case FCmpInst::FCMP_UNO
:
1521 case FCmpInst::FCMP_ORD
:
1522 case FCmpInst::FCMP_UEQ
:
1523 case FCmpInst::FCMP_UNE
:
1524 case FCmpInst::FCMP_ULT
:
1525 case FCmpInst::FCMP_UGT
:
1526 case FCmpInst::FCMP_ULE
:
1527 case FCmpInst::FCMP_UGE
:
1528 case FCmpInst::FCMP_TRUE
:
1529 case FCmpInst::FCMP_FALSE
:
1530 case FCmpInst::BAD_FCMP_PREDICATE
:
1531 break; // Couldn't determine anything about these constants.
1532 case FCmpInst::FCMP_OEQ
: // We know that C1 == C2
1533 Result
= (pred
== FCmpInst::FCMP_UEQ
|| pred
== FCmpInst::FCMP_OEQ
||
1534 pred
== FCmpInst::FCMP_ULE
|| pred
== FCmpInst::FCMP_OLE
||
1535 pred
== FCmpInst::FCMP_UGE
|| pred
== FCmpInst::FCMP_OGE
);
1537 case FCmpInst::FCMP_OLT
: // We know that C1 < C2
1538 Result
= (pred
== FCmpInst::FCMP_UNE
|| pred
== FCmpInst::FCMP_ONE
||
1539 pred
== FCmpInst::FCMP_ULT
|| pred
== FCmpInst::FCMP_OLT
||
1540 pred
== FCmpInst::FCMP_ULE
|| pred
== FCmpInst::FCMP_OLE
);
1542 case FCmpInst::FCMP_OGT
: // We know that C1 > C2
1543 Result
= (pred
== FCmpInst::FCMP_UNE
|| pred
== FCmpInst::FCMP_ONE
||
1544 pred
== FCmpInst::FCMP_UGT
|| pred
== FCmpInst::FCMP_OGT
||
1545 pred
== FCmpInst::FCMP_UGE
|| pred
== FCmpInst::FCMP_OGE
);
1547 case FCmpInst::FCMP_OLE
: // We know that C1 <= C2
1548 // We can only partially decide this relation.
1549 if (pred
== FCmpInst::FCMP_UGT
|| pred
== FCmpInst::FCMP_OGT
)
1551 else if (pred
== FCmpInst::FCMP_ULT
|| pred
== FCmpInst::FCMP_OLT
)
1554 case FCmpInst::FCMP_OGE
: // We known that C1 >= C2
1555 // We can only partially decide this relation.
1556 if (pred
== FCmpInst::FCMP_ULT
|| pred
== FCmpInst::FCMP_OLT
)
1558 else if (pred
== FCmpInst::FCMP_UGT
|| pred
== FCmpInst::FCMP_OGT
)
1561 case ICmpInst::ICMP_NE
: // We know that C1 != C2
1562 // We can only partially decide this relation.
1563 if (pred
== FCmpInst::FCMP_OEQ
|| pred
== FCmpInst::FCMP_UEQ
)
1565 else if (pred
== FCmpInst::FCMP_ONE
|| pred
== FCmpInst::FCMP_UNE
)
1570 // If we evaluated the result, return it now.
1572 return ConstantInt::get(Type::getInt1Ty(Context
), Result
);
1575 // Evaluate the relation between the two constants, per the predicate.
1576 int Result
= -1; // -1 = unknown, 0 = known false, 1 = known true.
1577 switch (evaluateICmpRelation(Context
, C1
, C2
, CmpInst::isSigned(pred
))) {
1578 default: llvm_unreachable("Unknown relational!");
1579 case ICmpInst::BAD_ICMP_PREDICATE
:
1580 break; // Couldn't determine anything about these constants.
1581 case ICmpInst::ICMP_EQ
: // We know the constants are equal!
1582 // If we know the constants are equal, we can decide the result of this
1583 // computation precisely.
1584 Result
= (pred
== ICmpInst::ICMP_EQ
||
1585 pred
== ICmpInst::ICMP_ULE
||
1586 pred
== ICmpInst::ICMP_SLE
||
1587 pred
== ICmpInst::ICMP_UGE
||
1588 pred
== ICmpInst::ICMP_SGE
);
1590 case ICmpInst::ICMP_ULT
:
1591 // If we know that C1 < C2, we can decide the result of this computation
1593 Result
= (pred
== ICmpInst::ICMP_ULT
||
1594 pred
== ICmpInst::ICMP_NE
||
1595 pred
== ICmpInst::ICMP_ULE
);
1597 case ICmpInst::ICMP_SLT
:
1598 // If we know that C1 < C2, we can decide the result of this computation
1600 Result
= (pred
== ICmpInst::ICMP_SLT
||
1601 pred
== ICmpInst::ICMP_NE
||
1602 pred
== ICmpInst::ICMP_SLE
);
1604 case ICmpInst::ICMP_UGT
:
1605 // If we know that C1 > C2, we can decide the result of this computation
1607 Result
= (pred
== ICmpInst::ICMP_UGT
||
1608 pred
== ICmpInst::ICMP_NE
||
1609 pred
== ICmpInst::ICMP_UGE
);
1611 case ICmpInst::ICMP_SGT
:
1612 // If we know that C1 > C2, we can decide the result of this computation
1614 Result
= (pred
== ICmpInst::ICMP_SGT
||
1615 pred
== ICmpInst::ICMP_NE
||
1616 pred
== ICmpInst::ICMP_SGE
);
1618 case ICmpInst::ICMP_ULE
:
1619 // If we know that C1 <= C2, we can only partially decide this relation.
1620 if (pred
== ICmpInst::ICMP_UGT
) Result
= 0;
1621 if (pred
== ICmpInst::ICMP_ULT
) Result
= 1;
1623 case ICmpInst::ICMP_SLE
:
1624 // If we know that C1 <= C2, we can only partially decide this relation.
1625 if (pred
== ICmpInst::ICMP_SGT
) Result
= 0;
1626 if (pred
== ICmpInst::ICMP_SLT
) Result
= 1;
1629 case ICmpInst::ICMP_UGE
:
1630 // If we know that C1 >= C2, we can only partially decide this relation.
1631 if (pred
== ICmpInst::ICMP_ULT
) Result
= 0;
1632 if (pred
== ICmpInst::ICMP_UGT
) Result
= 1;
1634 case ICmpInst::ICMP_SGE
:
1635 // If we know that C1 >= C2, we can only partially decide this relation.
1636 if (pred
== ICmpInst::ICMP_SLT
) Result
= 0;
1637 if (pred
== ICmpInst::ICMP_SGT
) Result
= 1;
1640 case ICmpInst::ICMP_NE
:
1641 // If we know that C1 != C2, we can only partially decide this relation.
1642 if (pred
== ICmpInst::ICMP_EQ
) Result
= 0;
1643 if (pred
== ICmpInst::ICMP_NE
) Result
= 1;
1647 // If we evaluated the result, return it now.
1649 return ConstantInt::get(Type::getInt1Ty(Context
), Result
);
1651 if (!isa
<ConstantExpr
>(C1
) && isa
<ConstantExpr
>(C2
)) {
1652 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1653 // other way if possible.
1655 case ICmpInst::ICMP_EQ
:
1656 case ICmpInst::ICMP_NE
:
1657 // No change of predicate required.
1658 return ConstantFoldCompareInstruction(Context
, pred
, C2
, C1
);
1660 case ICmpInst::ICMP_ULT
:
1661 case ICmpInst::ICMP_SLT
:
1662 case ICmpInst::ICMP_UGT
:
1663 case ICmpInst::ICMP_SGT
:
1664 case ICmpInst::ICMP_ULE
:
1665 case ICmpInst::ICMP_SLE
:
1666 case ICmpInst::ICMP_UGE
:
1667 case ICmpInst::ICMP_SGE
:
1668 // Change the predicate as necessary to swap the operands.
1669 pred
= ICmpInst::getSwappedPredicate((ICmpInst::Predicate
)pred
);
1670 return ConstantFoldCompareInstruction(Context
, pred
, C2
, C1
);
1672 default: // These predicates cannot be flopped around.
1680 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1682 static bool isInBoundsIndices(Constant
*const *Idxs
, size_t NumIdx
) {
1683 // No indices means nothing that could be out of bounds.
1684 if (NumIdx
== 0) return true;
1686 // If the first index is zero, it's in bounds.
1687 if (Idxs
[0]->isNullValue()) return true;
1689 // If the first index is one and all the rest are zero, it's in bounds,
1690 // by the one-past-the-end rule.
1691 if (!cast
<ConstantInt
>(Idxs
[0])->isOne())
1693 for (unsigned i
= 1, e
= NumIdx
; i
!= e
; ++i
)
1694 if (!Idxs
[i
]->isNullValue())
1699 Constant
*llvm::ConstantFoldGetElementPtr(LLVMContext
&Context
,
1702 Constant
* const *Idxs
,
1705 (NumIdx
== 1 && Idxs
[0]->isNullValue()))
1706 return const_cast<Constant
*>(C
);
1708 if (isa
<UndefValue
>(C
)) {
1709 const PointerType
*Ptr
= cast
<PointerType
>(C
->getType());
1710 const Type
*Ty
= GetElementPtrInst::getIndexedType(Ptr
,
1712 (Value
**)Idxs
+NumIdx
);
1713 assert(Ty
!= 0 && "Invalid indices for GEP!");
1714 return UndefValue::get(PointerType::get(Ty
, Ptr
->getAddressSpace()));
1717 Constant
*Idx0
= Idxs
[0];
1718 if (C
->isNullValue()) {
1720 for (unsigned i
= 0, e
= NumIdx
; i
!= e
; ++i
)
1721 if (!Idxs
[i
]->isNullValue()) {
1726 const PointerType
*Ptr
= cast
<PointerType
>(C
->getType());
1727 const Type
*Ty
= GetElementPtrInst::getIndexedType(Ptr
,
1729 (Value
**)Idxs
+NumIdx
);
1730 assert(Ty
!= 0 && "Invalid indices for GEP!");
1731 return ConstantPointerNull::get(
1732 PointerType::get(Ty
,Ptr
->getAddressSpace()));
1736 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(const_cast<Constant
*>(C
))) {
1737 // Combine Indices - If the source pointer to this getelementptr instruction
1738 // is a getelementptr instruction, combine the indices of the two
1739 // getelementptr instructions into a single instruction.
1741 if (CE
->getOpcode() == Instruction::GetElementPtr
) {
1742 const Type
*LastTy
= 0;
1743 for (gep_type_iterator I
= gep_type_begin(CE
), E
= gep_type_end(CE
);
1747 if ((LastTy
&& isa
<ArrayType
>(LastTy
)) || Idx0
->isNullValue()) {
1748 SmallVector
<Value
*, 16> NewIndices
;
1749 NewIndices
.reserve(NumIdx
+ CE
->getNumOperands());
1750 for (unsigned i
= 1, e
= CE
->getNumOperands()-1; i
!= e
; ++i
)
1751 NewIndices
.push_back(CE
->getOperand(i
));
1753 // Add the last index of the source with the first index of the new GEP.
1754 // Make sure to handle the case when they are actually different types.
1755 Constant
*Combined
= CE
->getOperand(CE
->getNumOperands()-1);
1756 // Otherwise it must be an array.
1757 if (!Idx0
->isNullValue()) {
1758 const Type
*IdxTy
= Combined
->getType();
1759 if (IdxTy
!= Idx0
->getType()) {
1761 ConstantExpr::getSExtOrBitCast(Idx0
, Type::getInt64Ty(Context
));
1762 Constant
*C2
= ConstantExpr::getSExtOrBitCast(Combined
,
1763 Type::getInt64Ty(Context
));
1764 Combined
= ConstantExpr::get(Instruction::Add
, C1
, C2
);
1767 ConstantExpr::get(Instruction::Add
, Idx0
, Combined
);
1771 NewIndices
.push_back(Combined
);
1772 NewIndices
.insert(NewIndices
.end(), Idxs
+1, Idxs
+NumIdx
);
1773 return (inBounds
&& cast
<GEPOperator
>(CE
)->isInBounds()) ?
1774 ConstantExpr::getInBoundsGetElementPtr(CE
->getOperand(0),
1776 NewIndices
.size()) :
1777 ConstantExpr::getGetElementPtr(CE
->getOperand(0),
1783 // Implement folding of:
1784 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1786 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1788 if (CE
->isCast() && NumIdx
> 1 && Idx0
->isNullValue()) {
1789 if (const PointerType
*SPT
=
1790 dyn_cast
<PointerType
>(CE
->getOperand(0)->getType()))
1791 if (const ArrayType
*SAT
= dyn_cast
<ArrayType
>(SPT
->getElementType()))
1792 if (const ArrayType
*CAT
=
1793 dyn_cast
<ArrayType
>(cast
<PointerType
>(C
->getType())->getElementType()))
1794 if (CAT
->getElementType() == SAT
->getElementType())
1796 ConstantExpr::getInBoundsGetElementPtr(
1797 (Constant
*)CE
->getOperand(0), Idxs
, NumIdx
) :
1798 ConstantExpr::getGetElementPtr(
1799 (Constant
*)CE
->getOperand(0), Idxs
, NumIdx
);
1802 // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1803 // Into: inttoptr (i64 0 to i8*)
1804 // This happens with pointers to member functions in C++.
1805 if (CE
->getOpcode() == Instruction::IntToPtr
&& NumIdx
== 1 &&
1806 isa
<ConstantInt
>(CE
->getOperand(0)) && isa
<ConstantInt
>(Idxs
[0]) &&
1807 cast
<PointerType
>(CE
->getType())->getElementType() == Type::getInt8Ty(Context
)) {
1808 Constant
*Base
= CE
->getOperand(0);
1809 Constant
*Offset
= Idxs
[0];
1811 // Convert the smaller integer to the larger type.
1812 if (Offset
->getType()->getPrimitiveSizeInBits() <
1813 Base
->getType()->getPrimitiveSizeInBits())
1814 Offset
= ConstantExpr::getSExt(Offset
, Base
->getType());
1815 else if (Base
->getType()->getPrimitiveSizeInBits() <
1816 Offset
->getType()->getPrimitiveSizeInBits())
1817 Base
= ConstantExpr::getZExt(Base
, Offset
->getType());
1819 Base
= ConstantExpr::getAdd(Base
, Offset
);
1820 return ConstantExpr::getIntToPtr(Base
, CE
->getType());
1824 // Check to see if any array indices are not within the corresponding
1825 // notional array bounds. If so, try to determine if they can be factored
1826 // out into preceding dimensions.
1827 bool Unknown
= false;
1828 SmallVector
<Constant
*, 8> NewIdxs
;
1829 const Type
*Ty
= C
->getType();
1830 const Type
*Prev
= 0;
1831 for (unsigned i
= 0; i
!= NumIdx
;
1832 Prev
= Ty
, Ty
= cast
<CompositeType
>(Ty
)->getTypeAtIndex(Idxs
[i
]), ++i
) {
1833 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(Idxs
[i
])) {
1834 if (const ArrayType
*ATy
= dyn_cast
<ArrayType
>(Ty
))
1835 if (ATy
->getNumElements() <= INT64_MAX
&&
1836 ATy
->getNumElements() != 0 &&
1837 CI
->getSExtValue() >= (int64_t)ATy
->getNumElements()) {
1838 if (isa
<SequentialType
>(Prev
)) {
1839 // It's out of range, but we can factor it into the prior
1841 NewIdxs
.resize(NumIdx
);
1842 ConstantInt
*Factor
= ConstantInt::get(CI
->getType(),
1843 ATy
->getNumElements());
1844 NewIdxs
[i
] = ConstantExpr::getSRem(CI
, Factor
);
1846 Constant
*PrevIdx
= Idxs
[i
-1];
1847 Constant
*Div
= ConstantExpr::getSDiv(CI
, Factor
);
1849 // Before adding, extend both operands to i64 to avoid
1850 // overflow trouble.
1851 if (PrevIdx
->getType() != Type::getInt64Ty(Context
))
1852 PrevIdx
= ConstantExpr::getSExt(PrevIdx
,
1853 Type::getInt64Ty(Context
));
1854 if (Div
->getType() != Type::getInt64Ty(Context
))
1855 Div
= ConstantExpr::getSExt(Div
,
1856 Type::getInt64Ty(Context
));
1858 NewIdxs
[i
-1] = ConstantExpr::getAdd(PrevIdx
, Div
);
1860 // It's out of range, but the prior dimension is a struct
1861 // so we can't do anything about it.
1866 // We don't know if it's in range or not.
1871 // If we did any factoring, start over with the adjusted indices.
1872 if (!NewIdxs
.empty()) {
1873 for (unsigned i
= 0; i
!= NumIdx
; ++i
)
1874 if (!NewIdxs
[i
]) NewIdxs
[i
] = Idxs
[i
];
1876 ConstantExpr::getInBoundsGetElementPtr(const_cast<Constant
*>(C
),
1877 NewIdxs
.data(), NewIdxs
.size()) :
1878 ConstantExpr::getGetElementPtr(const_cast<Constant
*>(C
),
1879 NewIdxs
.data(), NewIdxs
.size());
1882 // If all indices are known integers and normalized, we can do a simple
1883 // check for the "inbounds" property.
1884 if (!Unknown
&& !inBounds
&&
1885 isa
<GlobalVariable
>(C
) && isInBoundsIndices(Idxs
, NumIdx
))
1886 return ConstantExpr::getInBoundsGetElementPtr(const_cast<Constant
*>(C
),