1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements folding of constants for LLVM. This implements the
10 // (internal) ConstantFold.h interface, which is used by the
11 // ConstantExpr::get* methods to automatically fold constants when possible.
13 // The current constant folding implementation is implemented in two pieces: the
14 // pieces that don't need DataLayout, and the pieces that do. This is to avoid
15 // a dependence in IR on Target.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/IR/ConstantFold.h"
20 #include "llvm/ADT/APSInt.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Support/ErrorHandling.h"
34 using namespace llvm::PatternMatch
;
36 //===----------------------------------------------------------------------===//
37 // ConstantFold*Instruction Implementations
38 //===----------------------------------------------------------------------===//
40 /// Convert the specified vector Constant node to the specified vector type.
41 /// At this point, we know that the elements of the input vector constant are
42 /// all simple integer or FP values.
43 static Constant
*BitCastConstantVector(Constant
*CV
, VectorType
*DstTy
) {
45 if (CV
->isAllOnesValue()) return Constant::getAllOnesValue(DstTy
);
46 if (CV
->isNullValue()) return Constant::getNullValue(DstTy
);
48 // Do not iterate on scalable vector. The num of elements is unknown at
50 if (isa
<ScalableVectorType
>(DstTy
))
53 // If this cast changes element count then we can't handle it here:
54 // doing so requires endianness information. This should be handled by
55 // Analysis/ConstantFolding.cpp
56 unsigned NumElts
= cast
<FixedVectorType
>(DstTy
)->getNumElements();
57 if (NumElts
!= cast
<FixedVectorType
>(CV
->getType())->getNumElements())
60 Type
*DstEltTy
= DstTy
->getElementType();
61 // Fast path for splatted constants.
62 if (Constant
*Splat
= CV
->getSplatValue()) {
63 return ConstantVector::getSplat(DstTy
->getElementCount(),
64 ConstantExpr::getBitCast(Splat
, DstEltTy
));
67 SmallVector
<Constant
*, 16> Result
;
68 Type
*Ty
= IntegerType::get(CV
->getContext(), 32);
69 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
71 ConstantExpr::getExtractElement(CV
, ConstantInt::get(Ty
, i
));
72 C
= ConstantExpr::getBitCast(C
, DstEltTy
);
76 return ConstantVector::get(Result
);
79 /// This function determines which opcode to use to fold two constant cast
80 /// expressions together. It uses CastInst::isEliminableCastPair to determine
81 /// the opcode. Consequently its just a wrapper around that function.
82 /// Determine if it is valid to fold a cast of a cast
85 unsigned opc
, ///< opcode of the second cast constant expression
86 ConstantExpr
*Op
, ///< the first cast constant expression
87 Type
*DstTy
///< destination type of the first cast
89 assert(Op
&& Op
->isCast() && "Can't fold cast of cast without a cast!");
90 assert(DstTy
&& DstTy
->isFirstClassType() && "Invalid cast destination type");
91 assert(CastInst::isCast(opc
) && "Invalid cast opcode");
93 // The types and opcodes for the two Cast constant expressions
94 Type
*SrcTy
= Op
->getOperand(0)->getType();
95 Type
*MidTy
= Op
->getType();
96 Instruction::CastOps firstOp
= Instruction::CastOps(Op
->getOpcode());
97 Instruction::CastOps secondOp
= Instruction::CastOps(opc
);
99 // Assume that pointers are never more than 64 bits wide, and only use this
100 // for the middle type. Otherwise we could end up folding away illegal
101 // bitcasts between address spaces with different sizes.
102 IntegerType
*FakeIntPtrTy
= Type::getInt64Ty(DstTy
->getContext());
104 // Let CastInst::isEliminableCastPair do the heavy lifting.
105 return CastInst::isEliminableCastPair(firstOp
, secondOp
, SrcTy
, MidTy
, DstTy
,
106 nullptr, FakeIntPtrTy
, nullptr);
109 static Constant
*FoldBitCast(Constant
*V
, Type
*DestTy
) {
110 Type
*SrcTy
= V
->getType();
112 return V
; // no-op cast
114 // Handle casts from one vector constant to another. We know that the src
115 // and dest type have the same size (otherwise its an illegal cast).
116 if (VectorType
*DestPTy
= dyn_cast
<VectorType
>(DestTy
)) {
117 if (VectorType
*SrcTy
= dyn_cast
<VectorType
>(V
->getType())) {
118 assert(DestPTy
->getPrimitiveSizeInBits() ==
119 SrcTy
->getPrimitiveSizeInBits() &&
120 "Not cast between same sized vectors!");
122 // First, check for null. Undef is already handled.
123 if (isa
<ConstantAggregateZero
>(V
))
124 return Constant::getNullValue(DestTy
);
126 // Handle ConstantVector and ConstantAggregateVector.
127 return BitCastConstantVector(V
, DestPTy
);
130 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
131 // This allows for other simplifications (although some of them
132 // can only be handled by Analysis/ConstantFolding.cpp).
133 if (isa
<ConstantInt
>(V
) || isa
<ConstantFP
>(V
))
134 return ConstantExpr::getBitCast(ConstantVector::get(V
), DestPTy
);
137 // Finally, implement bitcast folding now. The code below doesn't handle
139 if (isa
<ConstantPointerNull
>(V
)) // ptr->ptr cast.
140 return ConstantPointerNull::get(cast
<PointerType
>(DestTy
));
142 // Handle integral constant input.
143 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
144 if (DestTy
->isIntegerTy())
145 // Integral -> Integral. This is a no-op because the bit widths must
146 // be the same. Consequently, we just fold to V.
149 // See note below regarding the PPC_FP128 restriction.
150 if (DestTy
->isFloatingPointTy() && !DestTy
->isPPC_FP128Ty())
151 return ConstantFP::get(DestTy
->getContext(),
152 APFloat(DestTy
->getFltSemantics(),
155 // Otherwise, can't fold this (vector?)
159 // Handle ConstantFP input: FP -> Integral.
160 if (ConstantFP
*FP
= dyn_cast
<ConstantFP
>(V
)) {
161 // PPC_FP128 is really the sum of two consecutive doubles, where the first
162 // double is always stored first in memory, regardless of the target
163 // endianness. The memory layout of i128, however, depends on the target
164 // endianness, and so we can't fold this without target endianness
165 // information. This should instead be handled by
166 // Analysis/ConstantFolding.cpp
167 if (FP
->getType()->isPPC_FP128Ty())
170 // Make sure dest type is compatible with the folded integer constant.
171 if (!DestTy
->isIntegerTy())
174 return ConstantInt::get(FP
->getContext(),
175 FP
->getValueAPF().bitcastToAPInt());
182 /// V is an integer constant which only has a subset of its bytes used.
183 /// The bytes used are indicated by ByteStart (which is the first byte used,
184 /// counting from the least significant byte) and ByteSize, which is the number
187 /// This function analyzes the specified constant to see if the specified byte
188 /// range can be returned as a simplified constant. If so, the constant is
189 /// returned, otherwise null is returned.
190 static Constant
*ExtractConstantBytes(Constant
*C
, unsigned ByteStart
,
192 assert(C
->getType()->isIntegerTy() &&
193 (cast
<IntegerType
>(C
->getType())->getBitWidth() & 7) == 0 &&
194 "Non-byte sized integer input");
195 unsigned CSize
= cast
<IntegerType
>(C
->getType())->getBitWidth()/8;
196 assert(ByteSize
&& "Must be accessing some piece");
197 assert(ByteStart
+ByteSize
<= CSize
&& "Extracting invalid piece from input");
198 assert(ByteSize
!= CSize
&& "Should not extract everything");
200 // Constant Integers are simple.
201 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(C
)) {
202 APInt V
= CI
->getValue();
204 V
.lshrInPlace(ByteStart
*8);
205 V
= V
.trunc(ByteSize
*8);
206 return ConstantInt::get(CI
->getContext(), V
);
209 // In the input is a constant expr, we might be able to recursively simplify.
210 // If not, we definitely can't do anything.
211 ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
);
212 if (!CE
) return nullptr;
214 switch (CE
->getOpcode()) {
215 default: return nullptr;
216 case Instruction::LShr
: {
217 ConstantInt
*Amt
= dyn_cast
<ConstantInt
>(CE
->getOperand(1));
220 APInt ShAmt
= Amt
->getValue();
221 // Cannot analyze non-byte shifts.
222 if ((ShAmt
& 7) != 0)
224 ShAmt
.lshrInPlace(3);
226 // If the extract is known to be all zeros, return zero.
227 if (ShAmt
.uge(CSize
- ByteStart
))
228 return Constant::getNullValue(
229 IntegerType::get(CE
->getContext(), ByteSize
* 8));
230 // If the extract is known to be fully in the input, extract it.
231 if (ShAmt
.ule(CSize
- (ByteStart
+ ByteSize
)))
232 return ExtractConstantBytes(CE
->getOperand(0),
233 ByteStart
+ ShAmt
.getZExtValue(), ByteSize
);
235 // TODO: Handle the 'partially zero' case.
239 case Instruction::Shl
: {
240 ConstantInt
*Amt
= dyn_cast
<ConstantInt
>(CE
->getOperand(1));
243 APInt ShAmt
= Amt
->getValue();
244 // Cannot analyze non-byte shifts.
245 if ((ShAmt
& 7) != 0)
247 ShAmt
.lshrInPlace(3);
249 // If the extract is known to be all zeros, return zero.
250 if (ShAmt
.uge(ByteStart
+ ByteSize
))
251 return Constant::getNullValue(
252 IntegerType::get(CE
->getContext(), ByteSize
* 8));
253 // If the extract is known to be fully in the input, extract it.
254 if (ShAmt
.ule(ByteStart
))
255 return ExtractConstantBytes(CE
->getOperand(0),
256 ByteStart
- ShAmt
.getZExtValue(), ByteSize
);
258 // TODO: Handle the 'partially zero' case.
262 case Instruction::ZExt
: {
263 unsigned SrcBitSize
=
264 cast
<IntegerType
>(CE
->getOperand(0)->getType())->getBitWidth();
266 // If extracting something that is completely zero, return 0.
267 if (ByteStart
*8 >= SrcBitSize
)
268 return Constant::getNullValue(IntegerType::get(CE
->getContext(),
271 // If exactly extracting the input, return it.
272 if (ByteStart
== 0 && ByteSize
*8 == SrcBitSize
)
273 return CE
->getOperand(0);
275 // If extracting something completely in the input, if the input is a
276 // multiple of 8 bits, recurse.
277 if ((SrcBitSize
&7) == 0 && (ByteStart
+ByteSize
)*8 <= SrcBitSize
)
278 return ExtractConstantBytes(CE
->getOperand(0), ByteStart
, ByteSize
);
280 // Otherwise, if extracting a subset of the input, which is not multiple of
281 // 8 bits, do a shift and trunc to get the bits.
282 if ((ByteStart
+ByteSize
)*8 < SrcBitSize
) {
283 assert((SrcBitSize
&7) && "Shouldn't get byte sized case here");
284 Constant
*Res
= CE
->getOperand(0);
286 Res
= ConstantExpr::getLShr(Res
,
287 ConstantInt::get(Res
->getType(), ByteStart
*8));
288 return ConstantExpr::getTrunc(Res
, IntegerType::get(C
->getContext(),
292 // TODO: Handle the 'partially zero' case.
298 static Constant
*foldMaybeUndesirableCast(unsigned opc
, Constant
*V
,
300 return ConstantExpr::isDesirableCastOp(opc
)
301 ? ConstantExpr::getCast(opc
, V
, DestTy
)
302 : ConstantFoldCastInstruction(opc
, V
, DestTy
);
305 Constant
*llvm::ConstantFoldCastInstruction(unsigned opc
, Constant
*V
,
307 if (isa
<PoisonValue
>(V
))
308 return PoisonValue::get(DestTy
);
310 if (isa
<UndefValue
>(V
)) {
311 // zext(undef) = 0, because the top bits will be zero.
312 // sext(undef) = 0, because the top bits will all be the same.
313 // [us]itofp(undef) = 0, because the result value is bounded.
314 if (opc
== Instruction::ZExt
|| opc
== Instruction::SExt
||
315 opc
== Instruction::UIToFP
|| opc
== Instruction::SIToFP
)
316 return Constant::getNullValue(DestTy
);
317 return UndefValue::get(DestTy
);
320 if (V
->isNullValue() && !DestTy
->isX86_MMXTy() && !DestTy
->isX86_AMXTy() &&
321 opc
!= Instruction::AddrSpaceCast
)
322 return Constant::getNullValue(DestTy
);
324 // If the cast operand is a constant expression, there's a few things we can
325 // do to try to simplify it.
326 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(V
)) {
328 // Try hard to fold cast of cast because they are often eliminable.
329 if (unsigned newOpc
= foldConstantCastPair(opc
, CE
, DestTy
))
330 return foldMaybeUndesirableCast(newOpc
, CE
->getOperand(0), DestTy
);
331 } else if (CE
->getOpcode() == Instruction::GetElementPtr
&&
332 // Do not fold addrspacecast (gep 0, .., 0). It might make the
333 // addrspacecast uncanonicalized.
334 opc
!= Instruction::AddrSpaceCast
&&
335 // Do not fold bitcast (gep) with inrange index, as this loses
337 !cast
<GEPOperator
>(CE
)->getInRangeIndex() &&
338 // Do not fold if the gep type is a vector, as bitcasting
339 // operand 0 of a vector gep will result in a bitcast between
341 !CE
->getType()->isVectorTy()) {
342 // If all of the indexes in the GEP are null values, there is no pointer
343 // adjustment going on. We might as well cast the source pointer.
344 bool isAllNull
= true;
345 for (unsigned i
= 1, e
= CE
->getNumOperands(); i
!= e
; ++i
)
346 if (!CE
->getOperand(i
)->isNullValue()) {
351 // This is casting one pointer type to another, always BitCast
352 return ConstantExpr::getPointerCast(CE
->getOperand(0), DestTy
);
356 // If the cast operand is a constant vector, perform the cast by
357 // operating on each element. In the cast of bitcasts, the element
358 // count may be mismatched; don't attempt to handle that here.
359 if ((isa
<ConstantVector
>(V
) || isa
<ConstantDataVector
>(V
)) &&
360 DestTy
->isVectorTy() &&
361 cast
<FixedVectorType
>(DestTy
)->getNumElements() ==
362 cast
<FixedVectorType
>(V
->getType())->getNumElements()) {
363 VectorType
*DestVecTy
= cast
<VectorType
>(DestTy
);
364 Type
*DstEltTy
= DestVecTy
->getElementType();
365 // Fast path for splatted constants.
366 if (Constant
*Splat
= V
->getSplatValue()) {
367 Constant
*Res
= foldMaybeUndesirableCast(opc
, Splat
, DstEltTy
);
370 return ConstantVector::getSplat(
371 cast
<VectorType
>(DestTy
)->getElementCount(), Res
);
373 SmallVector
<Constant
*, 16> res
;
374 Type
*Ty
= IntegerType::get(V
->getContext(), 32);
376 e
= cast
<FixedVectorType
>(V
->getType())->getNumElements();
378 Constant
*C
= ConstantExpr::getExtractElement(V
, ConstantInt::get(Ty
, i
));
379 Constant
*Casted
= foldMaybeUndesirableCast(opc
, C
, DstEltTy
);
382 res
.push_back(Casted
);
384 return ConstantVector::get(res
);
387 // We actually have to do a cast now. Perform the cast according to the
391 llvm_unreachable("Failed to cast constant expression");
392 case Instruction::FPTrunc
:
393 case Instruction::FPExt
:
394 if (ConstantFP
*FPC
= dyn_cast
<ConstantFP
>(V
)) {
396 APFloat Val
= FPC
->getValueAPF();
397 Val
.convert(DestTy
->getFltSemantics(), APFloat::rmNearestTiesToEven
,
399 return ConstantFP::get(V
->getContext(), Val
);
401 return nullptr; // Can't fold.
402 case Instruction::FPToUI
:
403 case Instruction::FPToSI
:
404 if (ConstantFP
*FPC
= dyn_cast
<ConstantFP
>(V
)) {
405 const APFloat
&V
= FPC
->getValueAPF();
407 uint32_t DestBitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
408 APSInt
IntVal(DestBitWidth
, opc
== Instruction::FPToUI
);
409 if (APFloat::opInvalidOp
==
410 V
.convertToInteger(IntVal
, APFloat::rmTowardZero
, &ignored
)) {
411 // Undefined behavior invoked - the destination type can't represent
412 // the input constant.
413 return PoisonValue::get(DestTy
);
415 return ConstantInt::get(FPC
->getContext(), IntVal
);
417 return nullptr; // Can't fold.
418 case Instruction::IntToPtr
: //always treated as unsigned
419 if (V
->isNullValue()) // Is it an integral null value?
420 return ConstantPointerNull::get(cast
<PointerType
>(DestTy
));
421 return nullptr; // Other pointer types cannot be casted
422 case Instruction::PtrToInt
: // always treated as unsigned
423 // Is it a null pointer value?
424 if (V
->isNullValue())
425 return ConstantInt::get(DestTy
, 0);
426 // Other pointer types cannot be casted
428 case Instruction::UIToFP
:
429 case Instruction::SIToFP
:
430 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
431 const APInt
&api
= CI
->getValue();
432 APFloat
apf(DestTy
->getFltSemantics(),
433 APInt::getZero(DestTy
->getPrimitiveSizeInBits()));
434 apf
.convertFromAPInt(api
, opc
==Instruction::SIToFP
,
435 APFloat::rmNearestTiesToEven
);
436 return ConstantFP::get(V
->getContext(), apf
);
439 case Instruction::ZExt
:
440 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
441 uint32_t BitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
442 return ConstantInt::get(V
->getContext(),
443 CI
->getValue().zext(BitWidth
));
446 case Instruction::SExt
:
447 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
448 uint32_t BitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
449 return ConstantInt::get(V
->getContext(),
450 CI
->getValue().sext(BitWidth
));
453 case Instruction::Trunc
: {
454 if (V
->getType()->isVectorTy())
457 uint32_t DestBitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
458 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
459 return ConstantInt::get(V
->getContext(),
460 CI
->getValue().trunc(DestBitWidth
));
463 // The input must be a constantexpr. See if we can simplify this based on
464 // the bytes we are demanding. Only do this if the source and dest are an
465 // even multiple of a byte.
466 if ((DestBitWidth
& 7) == 0 &&
467 (cast
<IntegerType
>(V
->getType())->getBitWidth() & 7) == 0)
468 if (Constant
*Res
= ExtractConstantBytes(V
, 0, DestBitWidth
/ 8))
473 case Instruction::BitCast
:
474 return FoldBitCast(V
, DestTy
);
475 case Instruction::AddrSpaceCast
:
480 Constant
*llvm::ConstantFoldSelectInstruction(Constant
*Cond
,
481 Constant
*V1
, Constant
*V2
) {
482 // Check for i1 and vector true/false conditions.
483 if (Cond
->isNullValue()) return V2
;
484 if (Cond
->isAllOnesValue()) return V1
;
486 // If the condition is a vector constant, fold the result elementwise.
487 if (ConstantVector
*CondV
= dyn_cast
<ConstantVector
>(Cond
)) {
488 auto *V1VTy
= CondV
->getType();
489 SmallVector
<Constant
*, 16> Result
;
490 Type
*Ty
= IntegerType::get(CondV
->getContext(), 32);
491 for (unsigned i
= 0, e
= V1VTy
->getNumElements(); i
!= e
; ++i
) {
493 Constant
*V1Element
= ConstantExpr::getExtractElement(V1
,
494 ConstantInt::get(Ty
, i
));
495 Constant
*V2Element
= ConstantExpr::getExtractElement(V2
,
496 ConstantInt::get(Ty
, i
));
497 auto *Cond
= cast
<Constant
>(CondV
->getOperand(i
));
498 if (isa
<PoisonValue
>(Cond
)) {
499 V
= PoisonValue::get(V1Element
->getType());
500 } else if (V1Element
== V2Element
) {
502 } else if (isa
<UndefValue
>(Cond
)) {
503 V
= isa
<UndefValue
>(V1Element
) ? V1Element
: V2Element
;
505 if (!isa
<ConstantInt
>(Cond
)) break;
506 V
= Cond
->isNullValue() ? V2Element
: V1Element
;
511 // If we were able to build the vector, return it.
512 if (Result
.size() == V1VTy
->getNumElements())
513 return ConstantVector::get(Result
);
516 if (isa
<PoisonValue
>(Cond
))
517 return PoisonValue::get(V1
->getType());
519 if (isa
<UndefValue
>(Cond
)) {
520 if (isa
<UndefValue
>(V1
)) return V1
;
524 if (V1
== V2
) return V1
;
526 if (isa
<PoisonValue
>(V1
))
528 if (isa
<PoisonValue
>(V2
))
531 // If the true or false value is undef, we can fold to the other value as
532 // long as the other value isn't poison.
533 auto NotPoison
= [](Constant
*C
) {
534 if (isa
<PoisonValue
>(C
))
537 // TODO: We can analyze ConstExpr by opcode to determine if there is any
538 // possibility of poison.
539 if (isa
<ConstantExpr
>(C
))
542 if (isa
<ConstantInt
>(C
) || isa
<GlobalVariable
>(C
) || isa
<ConstantFP
>(C
) ||
543 isa
<ConstantPointerNull
>(C
) || isa
<Function
>(C
))
546 if (C
->getType()->isVectorTy())
547 return !C
->containsPoisonElement() && !C
->containsConstantExpression();
549 // TODO: Recursively analyze aggregates or other constants.
552 if (isa
<UndefValue
>(V1
) && NotPoison(V2
)) return V2
;
553 if (isa
<UndefValue
>(V2
) && NotPoison(V1
)) return V1
;
558 Constant
*llvm::ConstantFoldExtractElementInstruction(Constant
*Val
,
560 auto *ValVTy
= cast
<VectorType
>(Val
->getType());
562 // extractelt poison, C -> poison
563 // extractelt C, undef -> poison
564 if (isa
<PoisonValue
>(Val
) || isa
<UndefValue
>(Idx
))
565 return PoisonValue::get(ValVTy
->getElementType());
567 // extractelt undef, C -> undef
568 if (isa
<UndefValue
>(Val
))
569 return UndefValue::get(ValVTy
->getElementType());
571 auto *CIdx
= dyn_cast
<ConstantInt
>(Idx
);
575 if (auto *ValFVTy
= dyn_cast
<FixedVectorType
>(Val
->getType())) {
576 // ee({w,x,y,z}, wrong_value) -> poison
577 if (CIdx
->uge(ValFVTy
->getNumElements()))
578 return PoisonValue::get(ValFVTy
->getElementType());
581 // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
582 if (auto *CE
= dyn_cast
<ConstantExpr
>(Val
)) {
583 if (auto *GEP
= dyn_cast
<GEPOperator
>(CE
)) {
584 SmallVector
<Constant
*, 8> Ops
;
585 Ops
.reserve(CE
->getNumOperands());
586 for (unsigned i
= 0, e
= CE
->getNumOperands(); i
!= e
; ++i
) {
587 Constant
*Op
= CE
->getOperand(i
);
588 if (Op
->getType()->isVectorTy()) {
589 Constant
*ScalarOp
= ConstantExpr::getExtractElement(Op
, Idx
);
592 Ops
.push_back(ScalarOp
);
596 return CE
->getWithOperands(Ops
, ValVTy
->getElementType(), false,
597 GEP
->getSourceElementType());
598 } else if (CE
->getOpcode() == Instruction::InsertElement
) {
599 if (const auto *IEIdx
= dyn_cast
<ConstantInt
>(CE
->getOperand(2))) {
600 if (APSInt::isSameValue(APSInt(IEIdx
->getValue()),
601 APSInt(CIdx
->getValue()))) {
602 return CE
->getOperand(1);
604 return ConstantExpr::getExtractElement(CE
->getOperand(0), CIdx
);
610 if (Constant
*C
= Val
->getAggregateElement(CIdx
))
613 // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x
614 if (CIdx
->getValue().ult(ValVTy
->getElementCount().getKnownMinValue())) {
615 if (Constant
*SplatVal
= Val
->getSplatValue())
622 Constant
*llvm::ConstantFoldInsertElementInstruction(Constant
*Val
,
625 if (isa
<UndefValue
>(Idx
))
626 return PoisonValue::get(Val
->getType());
628 // Inserting null into all zeros is still all zeros.
629 // TODO: This is true for undef and poison splats too.
630 if (isa
<ConstantAggregateZero
>(Val
) && Elt
->isNullValue())
633 ConstantInt
*CIdx
= dyn_cast
<ConstantInt
>(Idx
);
634 if (!CIdx
) return nullptr;
636 // Do not iterate on scalable vector. The num of elements is unknown at
638 if (isa
<ScalableVectorType
>(Val
->getType()))
641 auto *ValTy
= cast
<FixedVectorType
>(Val
->getType());
643 unsigned NumElts
= ValTy
->getNumElements();
644 if (CIdx
->uge(NumElts
))
645 return PoisonValue::get(Val
->getType());
647 SmallVector
<Constant
*, 16> Result
;
648 Result
.reserve(NumElts
);
649 auto *Ty
= Type::getInt32Ty(Val
->getContext());
650 uint64_t IdxVal
= CIdx
->getZExtValue();
651 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
653 Result
.push_back(Elt
);
657 Constant
*C
= ConstantExpr::getExtractElement(Val
, ConstantInt::get(Ty
, i
));
661 return ConstantVector::get(Result
);
664 Constant
*llvm::ConstantFoldShuffleVectorInstruction(Constant
*V1
, Constant
*V2
,
665 ArrayRef
<int> Mask
) {
666 auto *V1VTy
= cast
<VectorType
>(V1
->getType());
667 unsigned MaskNumElts
= Mask
.size();
669 ElementCount::get(MaskNumElts
, isa
<ScalableVectorType
>(V1VTy
));
670 Type
*EltTy
= V1VTy
->getElementType();
672 // Poison shuffle mask -> poison value.
673 if (all_of(Mask
, [](int Elt
) { return Elt
== PoisonMaskElem
; })) {
674 return PoisonValue::get(VectorType::get(EltTy
, MaskEltCount
));
677 // If the mask is all zeros this is a splat, no need to go through all
679 if (all_of(Mask
, [](int Elt
) { return Elt
== 0; })) {
680 Type
*Ty
= IntegerType::get(V1
->getContext(), 32);
682 ConstantExpr::getExtractElement(V1
, ConstantInt::get(Ty
, 0));
684 if (Elt
->isNullValue()) {
685 auto *VTy
= VectorType::get(EltTy
, MaskEltCount
);
686 return ConstantAggregateZero::get(VTy
);
687 } else if (!MaskEltCount
.isScalable())
688 return ConstantVector::getSplat(MaskEltCount
, Elt
);
690 // Do not iterate on scalable vector. The num of elements is unknown at
692 if (isa
<ScalableVectorType
>(V1VTy
))
695 unsigned SrcNumElts
= V1VTy
->getElementCount().getKnownMinValue();
697 // Loop over the shuffle mask, evaluating each element.
698 SmallVector
<Constant
*, 32> Result
;
699 for (unsigned i
= 0; i
!= MaskNumElts
; ++i
) {
702 Result
.push_back(UndefValue::get(EltTy
));
706 if (unsigned(Elt
) >= SrcNumElts
*2)
707 InElt
= UndefValue::get(EltTy
);
708 else if (unsigned(Elt
) >= SrcNumElts
) {
709 Type
*Ty
= IntegerType::get(V2
->getContext(), 32);
711 ConstantExpr::getExtractElement(V2
,
712 ConstantInt::get(Ty
, Elt
- SrcNumElts
));
714 Type
*Ty
= IntegerType::get(V1
->getContext(), 32);
715 InElt
= ConstantExpr::getExtractElement(V1
, ConstantInt::get(Ty
, Elt
));
717 Result
.push_back(InElt
);
720 return ConstantVector::get(Result
);
723 Constant
*llvm::ConstantFoldExtractValueInstruction(Constant
*Agg
,
724 ArrayRef
<unsigned> Idxs
) {
725 // Base case: no indices, so return the entire value.
729 if (Constant
*C
= Agg
->getAggregateElement(Idxs
[0]))
730 return ConstantFoldExtractValueInstruction(C
, Idxs
.slice(1));
735 Constant
*llvm::ConstantFoldInsertValueInstruction(Constant
*Agg
,
737 ArrayRef
<unsigned> Idxs
) {
738 // Base case: no indices, so replace the entire value.
743 if (StructType
*ST
= dyn_cast
<StructType
>(Agg
->getType()))
744 NumElts
= ST
->getNumElements();
746 NumElts
= cast
<ArrayType
>(Agg
->getType())->getNumElements();
748 SmallVector
<Constant
*, 32> Result
;
749 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
750 Constant
*C
= Agg
->getAggregateElement(i
);
751 if (!C
) return nullptr;
754 C
= ConstantFoldInsertValueInstruction(C
, Val
, Idxs
.slice(1));
759 if (StructType
*ST
= dyn_cast
<StructType
>(Agg
->getType()))
760 return ConstantStruct::get(ST
, Result
);
761 return ConstantArray::get(cast
<ArrayType
>(Agg
->getType()), Result
);
764 Constant
*llvm::ConstantFoldUnaryInstruction(unsigned Opcode
, Constant
*C
) {
765 assert(Instruction::isUnaryOp(Opcode
) && "Non-unary instruction detected");
767 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
768 // vectors are always evaluated per element.
769 bool IsScalableVector
= isa
<ScalableVectorType
>(C
->getType());
770 bool HasScalarUndefOrScalableVectorUndef
=
771 (!C
->getType()->isVectorTy() || IsScalableVector
) && isa
<UndefValue
>(C
);
773 if (HasScalarUndefOrScalableVectorUndef
) {
774 switch (static_cast<Instruction::UnaryOps
>(Opcode
)) {
775 case Instruction::FNeg
:
776 return C
; // -undef -> undef
777 case Instruction::UnaryOpsEnd
:
778 llvm_unreachable("Invalid UnaryOp");
782 // Constant should not be UndefValue, unless these are vector constants.
783 assert(!HasScalarUndefOrScalableVectorUndef
&& "Unexpected UndefValue");
784 // We only have FP UnaryOps right now.
785 assert(!isa
<ConstantInt
>(C
) && "Unexpected Integer UnaryOp");
787 if (ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(C
)) {
788 const APFloat
&CV
= CFP
->getValueAPF();
792 case Instruction::FNeg
:
793 return ConstantFP::get(C
->getContext(), neg(CV
));
795 } else if (auto *VTy
= dyn_cast
<FixedVectorType
>(C
->getType())) {
797 Type
*Ty
= IntegerType::get(VTy
->getContext(), 32);
798 // Fast path for splatted constants.
799 if (Constant
*Splat
= C
->getSplatValue())
800 if (Constant
*Elt
= ConstantFoldUnaryInstruction(Opcode
, Splat
))
801 return ConstantVector::getSplat(VTy
->getElementCount(), Elt
);
803 // Fold each element and create a vector constant from those constants.
804 SmallVector
<Constant
*, 16> Result
;
805 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
806 Constant
*ExtractIdx
= ConstantInt::get(Ty
, i
);
807 Constant
*Elt
= ConstantExpr::getExtractElement(C
, ExtractIdx
);
808 Constant
*Res
= ConstantFoldUnaryInstruction(Opcode
, Elt
);
811 Result
.push_back(Res
);
814 return ConstantVector::get(Result
);
817 // We don't know how to fold this.
821 Constant
*llvm::ConstantFoldBinaryInstruction(unsigned Opcode
, Constant
*C1
,
823 assert(Instruction::isBinaryOp(Opcode
) && "Non-binary instruction detected");
825 // Simplify BinOps with their identity values first. They are no-ops and we
826 // can always return the other value, including undef or poison values.
827 // FIXME: remove unnecessary duplicated identity patterns below.
828 // FIXME: Use AllowRHSConstant with getBinOpIdentity to handle additional ops,
830 Constant
*Identity
= ConstantExpr::getBinOpIdentity(Opcode
, C1
->getType());
838 // Binary operations propagate poison.
839 if (isa
<PoisonValue
>(C1
) || isa
<PoisonValue
>(C2
))
840 return PoisonValue::get(C1
->getType());
842 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
843 // vectors are always evaluated per element.
844 bool IsScalableVector
= isa
<ScalableVectorType
>(C1
->getType());
845 bool HasScalarUndefOrScalableVectorUndef
=
846 (!C1
->getType()->isVectorTy() || IsScalableVector
) &&
847 (isa
<UndefValue
>(C1
) || isa
<UndefValue
>(C2
));
848 if (HasScalarUndefOrScalableVectorUndef
) {
849 switch (static_cast<Instruction::BinaryOps
>(Opcode
)) {
850 case Instruction::Xor
:
851 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
))
852 // Handle undef ^ undef -> 0 special case. This is a common
854 return Constant::getNullValue(C1
->getType());
856 case Instruction::Add
:
857 case Instruction::Sub
:
858 return UndefValue::get(C1
->getType());
859 case Instruction::And
:
860 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
)) // undef & undef -> undef
862 return Constant::getNullValue(C1
->getType()); // undef & X -> 0
863 case Instruction::Mul
: {
864 // undef * undef -> undef
865 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
))
868 // X * undef -> undef if X is odd
869 if (match(C1
, m_APInt(CV
)) || match(C2
, m_APInt(CV
)))
871 return UndefValue::get(C1
->getType());
873 // X * undef -> 0 otherwise
874 return Constant::getNullValue(C1
->getType());
876 case Instruction::SDiv
:
877 case Instruction::UDiv
:
878 // X / undef -> poison
880 if (match(C2
, m_CombineOr(m_Undef(), m_Zero())))
881 return PoisonValue::get(C2
->getType());
882 // undef / 1 -> undef
883 if (match(C2
, m_One()))
885 // undef / X -> 0 otherwise
886 return Constant::getNullValue(C1
->getType());
887 case Instruction::URem
:
888 case Instruction::SRem
:
889 // X % undef -> poison
891 if (match(C2
, m_CombineOr(m_Undef(), m_Zero())))
892 return PoisonValue::get(C2
->getType());
893 // undef % X -> 0 otherwise
894 return Constant::getNullValue(C1
->getType());
895 case Instruction::Or
: // X | undef -> -1
896 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
)) // undef | undef -> undef
898 return Constant::getAllOnesValue(C1
->getType()); // undef | X -> ~0
899 case Instruction::LShr
:
900 // X >>l undef -> poison
901 if (isa
<UndefValue
>(C2
))
902 return PoisonValue::get(C2
->getType());
903 // undef >>l 0 -> undef
904 if (match(C2
, m_Zero()))
907 return Constant::getNullValue(C1
->getType());
908 case Instruction::AShr
:
909 // X >>a undef -> poison
910 if (isa
<UndefValue
>(C2
))
911 return PoisonValue::get(C2
->getType());
912 // undef >>a 0 -> undef
913 if (match(C2
, m_Zero()))
915 // TODO: undef >>a X -> poison if the shift is exact
917 return Constant::getNullValue(C1
->getType());
918 case Instruction::Shl
:
919 // X << undef -> undef
920 if (isa
<UndefValue
>(C2
))
921 return PoisonValue::get(C2
->getType());
922 // undef << 0 -> undef
923 if (match(C2
, m_Zero()))
926 return Constant::getNullValue(C1
->getType());
927 case Instruction::FSub
:
928 // -0.0 - undef --> undef (consistent with "fneg undef")
929 if (match(C1
, m_NegZeroFP()) && isa
<UndefValue
>(C2
))
932 case Instruction::FAdd
:
933 case Instruction::FMul
:
934 case Instruction::FDiv
:
935 case Instruction::FRem
:
936 // [any flop] undef, undef -> undef
937 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
))
939 // [any flop] C, undef -> NaN
940 // [any flop] undef, C -> NaN
941 // We could potentially specialize NaN/Inf constants vs. 'normal'
942 // constants (possibly differently depending on opcode and operand). This
943 // would allow returning undef sometimes. But it is always safe to fold to
944 // NaN because we can choose the undef operand as NaN, and any FP opcode
945 // with a NaN operand will propagate NaN.
946 return ConstantFP::getNaN(C1
->getType());
947 case Instruction::BinaryOpsEnd
:
948 llvm_unreachable("Invalid BinaryOp");
952 // Neither constant should be UndefValue, unless these are vector constants.
953 assert((!HasScalarUndefOrScalableVectorUndef
) && "Unexpected UndefValue");
955 // Handle simplifications when the RHS is a constant int.
956 if (ConstantInt
*CI2
= dyn_cast
<ConstantInt
>(C2
)) {
958 case Instruction::Add
:
959 if (CI2
->isZero()) return C1
; // X + 0 == X
961 case Instruction::Sub
:
962 if (CI2
->isZero()) return C1
; // X - 0 == X
964 case Instruction::Mul
:
965 if (CI2
->isZero()) return C2
; // X * 0 == 0
967 return C1
; // X * 1 == X
969 case Instruction::UDiv
:
970 case Instruction::SDiv
:
972 return C1
; // X / 1 == X
974 return PoisonValue::get(CI2
->getType()); // X / 0 == poison
976 case Instruction::URem
:
977 case Instruction::SRem
:
979 return Constant::getNullValue(CI2
->getType()); // X % 1 == 0
981 return PoisonValue::get(CI2
->getType()); // X % 0 == poison
983 case Instruction::And
:
984 if (CI2
->isZero()) return C2
; // X & 0 == 0
985 if (CI2
->isMinusOne())
986 return C1
; // X & -1 == X
988 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
989 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
990 if (CE1
->getOpcode() == Instruction::ZExt
) {
991 unsigned DstWidth
= CI2
->getType()->getBitWidth();
993 CE1
->getOperand(0)->getType()->getPrimitiveSizeInBits();
994 APInt
PossiblySetBits(APInt::getLowBitsSet(DstWidth
, SrcWidth
));
995 if ((PossiblySetBits
& CI2
->getValue()) == PossiblySetBits
)
999 // If and'ing the address of a global with a constant, fold it.
1000 if (CE1
->getOpcode() == Instruction::PtrToInt
&&
1001 isa
<GlobalValue
>(CE1
->getOperand(0))) {
1002 GlobalValue
*GV
= cast
<GlobalValue
>(CE1
->getOperand(0));
1004 Align GVAlign
; // defaults to 1
1006 if (Module
*TheModule
= GV
->getParent()) {
1007 const DataLayout
&DL
= TheModule
->getDataLayout();
1008 GVAlign
= GV
->getPointerAlignment(DL
);
1010 // If the function alignment is not specified then assume that it
1012 // This is dangerous; on x86, the alignment of the pointer
1013 // corresponds to the alignment of the function, but might be less
1014 // than 4 if it isn't explicitly specified.
1015 // However, a fix for this behaviour was reverted because it
1016 // increased code size (see https://reviews.llvm.org/D55115)
1017 // FIXME: This code should be deleted once existing targets have
1018 // appropriate defaults
1019 if (isa
<Function
>(GV
) && !DL
.getFunctionPtrAlign())
1021 } else if (isa
<GlobalVariable
>(GV
)) {
1022 GVAlign
= cast
<GlobalVariable
>(GV
)->getAlign().valueOrOne();
1026 unsigned DstWidth
= CI2
->getType()->getBitWidth();
1027 unsigned SrcWidth
= std::min(DstWidth
, Log2(GVAlign
));
1028 APInt
BitsNotSet(APInt::getLowBitsSet(DstWidth
, SrcWidth
));
1030 // If checking bits we know are clear, return zero.
1031 if ((CI2
->getValue() & BitsNotSet
) == CI2
->getValue())
1032 return Constant::getNullValue(CI2
->getType());
1037 case Instruction::Or
:
1038 if (CI2
->isZero()) return C1
; // X | 0 == X
1039 if (CI2
->isMinusOne())
1040 return C2
; // X | -1 == -1
1042 case Instruction::Xor
:
1043 if (CI2
->isZero()) return C1
; // X ^ 0 == X
1045 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
1046 switch (CE1
->getOpcode()) {
1048 case Instruction::ICmp
:
1049 case Instruction::FCmp
:
1050 // cmp pred ^ true -> cmp !pred
1051 assert(CI2
->isOne());
1052 CmpInst::Predicate pred
= (CmpInst::Predicate
)CE1
->getPredicate();
1053 pred
= CmpInst::getInversePredicate(pred
);
1054 return ConstantExpr::getCompare(pred
, CE1
->getOperand(0),
1055 CE1
->getOperand(1));
1059 case Instruction::AShr
:
1060 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1061 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
))
1062 if (CE1
->getOpcode() == Instruction::ZExt
) // Top bits known zero.
1063 return ConstantExpr::getLShr(C1
, C2
);
1066 } else if (isa
<ConstantInt
>(C1
)) {
1067 // If C1 is a ConstantInt and C2 is not, swap the operands.
1068 if (Instruction::isCommutative(Opcode
))
1069 return ConstantExpr::isDesirableBinOp(Opcode
)
1070 ? ConstantExpr::get(Opcode
, C2
, C1
)
1071 : ConstantFoldBinaryInstruction(Opcode
, C2
, C1
);
1074 if (ConstantInt
*CI1
= dyn_cast
<ConstantInt
>(C1
)) {
1075 if (ConstantInt
*CI2
= dyn_cast
<ConstantInt
>(C2
)) {
1076 const APInt
&C1V
= CI1
->getValue();
1077 const APInt
&C2V
= CI2
->getValue();
1081 case Instruction::Add
:
1082 return ConstantInt::get(CI1
->getContext(), C1V
+ C2V
);
1083 case Instruction::Sub
:
1084 return ConstantInt::get(CI1
->getContext(), C1V
- C2V
);
1085 case Instruction::Mul
:
1086 return ConstantInt::get(CI1
->getContext(), C1V
* C2V
);
1087 case Instruction::UDiv
:
1088 assert(!CI2
->isZero() && "Div by zero handled above");
1089 return ConstantInt::get(CI1
->getContext(), C1V
.udiv(C2V
));
1090 case Instruction::SDiv
:
1091 assert(!CI2
->isZero() && "Div by zero handled above");
1092 if (C2V
.isAllOnes() && C1V
.isMinSignedValue())
1093 return PoisonValue::get(CI1
->getType()); // MIN_INT / -1 -> poison
1094 return ConstantInt::get(CI1
->getContext(), C1V
.sdiv(C2V
));
1095 case Instruction::URem
:
1096 assert(!CI2
->isZero() && "Div by zero handled above");
1097 return ConstantInt::get(CI1
->getContext(), C1V
.urem(C2V
));
1098 case Instruction::SRem
:
1099 assert(!CI2
->isZero() && "Div by zero handled above");
1100 if (C2V
.isAllOnes() && C1V
.isMinSignedValue())
1101 return PoisonValue::get(CI1
->getType()); // MIN_INT % -1 -> poison
1102 return ConstantInt::get(CI1
->getContext(), C1V
.srem(C2V
));
1103 case Instruction::And
:
1104 return ConstantInt::get(CI1
->getContext(), C1V
& C2V
);
1105 case Instruction::Or
:
1106 return ConstantInt::get(CI1
->getContext(), C1V
| C2V
);
1107 case Instruction::Xor
:
1108 return ConstantInt::get(CI1
->getContext(), C1V
^ C2V
);
1109 case Instruction::Shl
:
1110 if (C2V
.ult(C1V
.getBitWidth()))
1111 return ConstantInt::get(CI1
->getContext(), C1V
.shl(C2V
));
1112 return PoisonValue::get(C1
->getType()); // too big shift is poison
1113 case Instruction::LShr
:
1114 if (C2V
.ult(C1V
.getBitWidth()))
1115 return ConstantInt::get(CI1
->getContext(), C1V
.lshr(C2V
));
1116 return PoisonValue::get(C1
->getType()); // too big shift is poison
1117 case Instruction::AShr
:
1118 if (C2V
.ult(C1V
.getBitWidth()))
1119 return ConstantInt::get(CI1
->getContext(), C1V
.ashr(C2V
));
1120 return PoisonValue::get(C1
->getType()); // too big shift is poison
1125 case Instruction::SDiv
:
1126 case Instruction::UDiv
:
1127 case Instruction::URem
:
1128 case Instruction::SRem
:
1129 case Instruction::LShr
:
1130 case Instruction::AShr
:
1131 case Instruction::Shl
:
1132 if (CI1
->isZero()) return C1
;
1137 } else if (ConstantFP
*CFP1
= dyn_cast
<ConstantFP
>(C1
)) {
1138 if (ConstantFP
*CFP2
= dyn_cast
<ConstantFP
>(C2
)) {
1139 const APFloat
&C1V
= CFP1
->getValueAPF();
1140 const APFloat
&C2V
= CFP2
->getValueAPF();
1141 APFloat C3V
= C1V
; // copy for modification
1145 case Instruction::FAdd
:
1146 (void)C3V
.add(C2V
, APFloat::rmNearestTiesToEven
);
1147 return ConstantFP::get(C1
->getContext(), C3V
);
1148 case Instruction::FSub
:
1149 (void)C3V
.subtract(C2V
, APFloat::rmNearestTiesToEven
);
1150 return ConstantFP::get(C1
->getContext(), C3V
);
1151 case Instruction::FMul
:
1152 (void)C3V
.multiply(C2V
, APFloat::rmNearestTiesToEven
);
1153 return ConstantFP::get(C1
->getContext(), C3V
);
1154 case Instruction::FDiv
:
1155 (void)C3V
.divide(C2V
, APFloat::rmNearestTiesToEven
);
1156 return ConstantFP::get(C1
->getContext(), C3V
);
1157 case Instruction::FRem
:
1159 return ConstantFP::get(C1
->getContext(), C3V
);
1162 } else if (auto *VTy
= dyn_cast
<VectorType
>(C1
->getType())) {
1163 // Fast path for splatted constants.
1164 if (Constant
*C2Splat
= C2
->getSplatValue()) {
1165 if (Instruction::isIntDivRem(Opcode
) && C2Splat
->isNullValue())
1166 return PoisonValue::get(VTy
);
1167 if (Constant
*C1Splat
= C1
->getSplatValue()) {
1169 ConstantExpr::isDesirableBinOp(Opcode
)
1170 ? ConstantExpr::get(Opcode
, C1Splat
, C2Splat
)
1171 : ConstantFoldBinaryInstruction(Opcode
, C1Splat
, C2Splat
);
1174 return ConstantVector::getSplat(VTy
->getElementCount(), Res
);
1178 if (auto *FVTy
= dyn_cast
<FixedVectorType
>(VTy
)) {
1179 // Fold each element and create a vector constant from those constants.
1180 SmallVector
<Constant
*, 16> Result
;
1181 Type
*Ty
= IntegerType::get(FVTy
->getContext(), 32);
1182 for (unsigned i
= 0, e
= FVTy
->getNumElements(); i
!= e
; ++i
) {
1183 Constant
*ExtractIdx
= ConstantInt::get(Ty
, i
);
1184 Constant
*LHS
= ConstantExpr::getExtractElement(C1
, ExtractIdx
);
1185 Constant
*RHS
= ConstantExpr::getExtractElement(C2
, ExtractIdx
);
1187 // If any element of a divisor vector is zero, the whole op is poison.
1188 if (Instruction::isIntDivRem(Opcode
) && RHS
->isNullValue())
1189 return PoisonValue::get(VTy
);
1191 Constant
*Res
= ConstantExpr::isDesirableBinOp(Opcode
)
1192 ? ConstantExpr::get(Opcode
, LHS
, RHS
)
1193 : ConstantFoldBinaryInstruction(Opcode
, LHS
, RHS
);
1196 Result
.push_back(Res
);
1199 return ConstantVector::get(Result
);
1203 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
1204 // There are many possible foldings we could do here. We should probably
1205 // at least fold add of a pointer with an integer into the appropriate
1206 // getelementptr. This will improve alias analysis a bit.
1208 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1210 if (Instruction::isAssociative(Opcode
) && CE1
->getOpcode() == Opcode
) {
1211 Constant
*T
= ConstantExpr::get(Opcode
, CE1
->getOperand(1), C2
);
1212 if (!isa
<ConstantExpr
>(T
) || cast
<ConstantExpr
>(T
)->getOpcode() != Opcode
)
1213 return ConstantExpr::get(Opcode
, CE1
->getOperand(0), T
);
1215 } else if (isa
<ConstantExpr
>(C2
)) {
1216 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1217 // other way if possible.
1218 if (Instruction::isCommutative(Opcode
))
1219 return ConstantFoldBinaryInstruction(Opcode
, C2
, C1
);
1222 // i1 can be simplified in many cases.
1223 if (C1
->getType()->isIntegerTy(1)) {
1225 case Instruction::Add
:
1226 case Instruction::Sub
:
1227 return ConstantExpr::getXor(C1
, C2
);
1228 case Instruction::Shl
:
1229 case Instruction::LShr
:
1230 case Instruction::AShr
:
1231 // We can assume that C2 == 0. If it were one the result would be
1232 // undefined because the shift value is as large as the bitwidth.
1234 case Instruction::SDiv
:
1235 case Instruction::UDiv
:
1236 // We can assume that C2 == 1. If it were zero the result would be
1237 // undefined through division by zero.
1239 case Instruction::URem
:
1240 case Instruction::SRem
:
1241 // We can assume that C2 == 1. If it were zero the result would be
1242 // undefined through division by zero.
1243 return ConstantInt::getFalse(C1
->getContext());
1249 // We don't know how to fold this.
1253 /// This function determines if there is anything we can decide about the two
1254 /// constants provided. This doesn't need to handle simple things like
1255 /// ConstantFP comparisons, but should instead handle ConstantExprs.
1256 /// If we can determine that the two constants have a particular relation to
1257 /// each other, we should return the corresponding FCmpInst predicate,
1258 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1259 /// ConstantFoldCompareInstruction.
1261 /// To simplify this code we canonicalize the relation so that the first
1262 /// operand is always the most "complex" of the two. We consider ConstantFP
1263 /// to be the simplest, and ConstantExprs to be the most complex.
1264 static FCmpInst::Predicate
evaluateFCmpRelation(Constant
*V1
, Constant
*V2
) {
1265 assert(V1
->getType() == V2
->getType() &&
1266 "Cannot compare values of different types!");
1268 // We do not know if a constant expression will evaluate to a number or NaN.
1269 // Therefore, we can only say that the relation is unordered or equal.
1270 if (V1
== V2
) return FCmpInst::FCMP_UEQ
;
1272 if (!isa
<ConstantExpr
>(V1
)) {
1273 if (!isa
<ConstantExpr
>(V2
)) {
1274 // Simple case, use the standard constant folder.
1275 ConstantInt
*R
= nullptr;
1276 R
= dyn_cast
<ConstantInt
>(
1277 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ
, V1
, V2
));
1278 if (R
&& !R
->isZero())
1279 return FCmpInst::FCMP_OEQ
;
1280 R
= dyn_cast
<ConstantInt
>(
1281 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT
, V1
, V2
));
1282 if (R
&& !R
->isZero())
1283 return FCmpInst::FCMP_OLT
;
1284 R
= dyn_cast
<ConstantInt
>(
1285 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT
, V1
, V2
));
1286 if (R
&& !R
->isZero())
1287 return FCmpInst::FCMP_OGT
;
1289 // Nothing more we can do
1290 return FCmpInst::BAD_FCMP_PREDICATE
;
1293 // If the first operand is simple and second is ConstantExpr, swap operands.
1294 FCmpInst::Predicate SwappedRelation
= evaluateFCmpRelation(V2
, V1
);
1295 if (SwappedRelation
!= FCmpInst::BAD_FCMP_PREDICATE
)
1296 return FCmpInst::getSwappedPredicate(SwappedRelation
);
1298 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1299 // constantexpr or a simple constant.
1300 ConstantExpr
*CE1
= cast
<ConstantExpr
>(V1
);
1301 switch (CE1
->getOpcode()) {
1302 case Instruction::FPTrunc
:
1303 case Instruction::FPExt
:
1304 case Instruction::UIToFP
:
1305 case Instruction::SIToFP
:
1306 // We might be able to do something with these but we don't right now.
1312 // There are MANY other foldings that we could perform here. They will
1313 // probably be added on demand, as they seem needed.
1314 return FCmpInst::BAD_FCMP_PREDICATE
;
1317 static ICmpInst::Predicate
areGlobalsPotentiallyEqual(const GlobalValue
*GV1
,
1318 const GlobalValue
*GV2
) {
1319 auto isGlobalUnsafeForEquality
= [](const GlobalValue
*GV
) {
1320 if (GV
->isInterposable() || GV
->hasGlobalUnnamedAddr())
1322 if (const auto *GVar
= dyn_cast
<GlobalVariable
>(GV
)) {
1323 Type
*Ty
= GVar
->getValueType();
1324 // A global with opaque type might end up being zero sized.
1327 // A global with an empty type might lie at the address of any other
1329 if (Ty
->isEmptyTy())
1334 // Don't try to decide equality of aliases.
1335 if (!isa
<GlobalAlias
>(GV1
) && !isa
<GlobalAlias
>(GV2
))
1336 if (!isGlobalUnsafeForEquality(GV1
) && !isGlobalUnsafeForEquality(GV2
))
1337 return ICmpInst::ICMP_NE
;
1338 return ICmpInst::BAD_ICMP_PREDICATE
;
1341 /// This function determines if there is anything we can decide about the two
1342 /// constants provided. This doesn't need to handle simple things like integer
1343 /// comparisons, but should instead handle ConstantExprs and GlobalValues.
1344 /// If we can determine that the two constants have a particular relation to
1345 /// each other, we should return the corresponding ICmp predicate, otherwise
1346 /// return ICmpInst::BAD_ICMP_PREDICATE.
1348 /// To simplify this code we canonicalize the relation so that the first
1349 /// operand is always the most "complex" of the two. We consider simple
1350 /// constants (like ConstantInt) to be the simplest, followed by
1351 /// GlobalValues, followed by ConstantExpr's (the most complex).
1353 static ICmpInst::Predicate
evaluateICmpRelation(Constant
*V1
, Constant
*V2
,
1355 assert(V1
->getType() == V2
->getType() &&
1356 "Cannot compare different types of values!");
1357 if (V1
== V2
) return ICmpInst::ICMP_EQ
;
1359 if (!isa
<ConstantExpr
>(V1
) && !isa
<GlobalValue
>(V1
) &&
1360 !isa
<BlockAddress
>(V1
)) {
1361 if (!isa
<GlobalValue
>(V2
) && !isa
<ConstantExpr
>(V2
) &&
1362 !isa
<BlockAddress
>(V2
)) {
1363 // We distilled this down to a simple case, use the standard constant
1365 ConstantInt
*R
= nullptr;
1366 ICmpInst::Predicate pred
= ICmpInst::ICMP_EQ
;
1367 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, V1
, V2
));
1368 if (R
&& !R
->isZero())
1370 pred
= isSigned
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
;
1371 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, V1
, V2
));
1372 if (R
&& !R
->isZero())
1374 pred
= isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1375 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, V1
, V2
));
1376 if (R
&& !R
->isZero())
1379 // If we couldn't figure it out, bail.
1380 return ICmpInst::BAD_ICMP_PREDICATE
;
1383 // If the first operand is simple, swap operands.
1384 ICmpInst::Predicate SwappedRelation
=
1385 evaluateICmpRelation(V2
, V1
, isSigned
);
1386 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1387 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1389 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V1
)) {
1390 if (isa
<ConstantExpr
>(V2
)) { // Swap as necessary.
1391 ICmpInst::Predicate SwappedRelation
=
1392 evaluateICmpRelation(V2
, V1
, isSigned
);
1393 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1394 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1395 return ICmpInst::BAD_ICMP_PREDICATE
;
1398 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1399 // constant (which, since the types must match, means that it's a
1400 // ConstantPointerNull).
1401 if (const GlobalValue
*GV2
= dyn_cast
<GlobalValue
>(V2
)) {
1402 return areGlobalsPotentiallyEqual(GV
, GV2
);
1403 } else if (isa
<BlockAddress
>(V2
)) {
1404 return ICmpInst::ICMP_NE
; // Globals never equal labels.
1406 assert(isa
<ConstantPointerNull
>(V2
) && "Canonicalization guarantee!");
1407 // GlobalVals can never be null unless they have external weak linkage.
1408 // We don't try to evaluate aliases here.
1409 // NOTE: We should not be doing this constant folding if null pointer
1410 // is considered valid for the function. But currently there is no way to
1411 // query it from the Constant type.
1412 if (!GV
->hasExternalWeakLinkage() && !isa
<GlobalAlias
>(GV
) &&
1413 !NullPointerIsDefined(nullptr /* F */,
1414 GV
->getType()->getAddressSpace()))
1415 return ICmpInst::ICMP_UGT
;
1417 } else if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(V1
)) {
1418 if (isa
<ConstantExpr
>(V2
)) { // Swap as necessary.
1419 ICmpInst::Predicate SwappedRelation
=
1420 evaluateICmpRelation(V2
, V1
, isSigned
);
1421 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1422 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1423 return ICmpInst::BAD_ICMP_PREDICATE
;
1426 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1427 // constant (which, since the types must match, means that it is a
1428 // ConstantPointerNull).
1429 if (const BlockAddress
*BA2
= dyn_cast
<BlockAddress
>(V2
)) {
1430 // Block address in another function can't equal this one, but block
1431 // addresses in the current function might be the same if blocks are
1433 if (BA2
->getFunction() != BA
->getFunction())
1434 return ICmpInst::ICMP_NE
;
1436 // Block addresses aren't null, don't equal the address of globals.
1437 assert((isa
<ConstantPointerNull
>(V2
) || isa
<GlobalValue
>(V2
)) &&
1438 "Canonicalization guarantee!");
1439 return ICmpInst::ICMP_NE
;
1442 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1443 // constantexpr, a global, block address, or a simple constant.
1444 ConstantExpr
*CE1
= cast
<ConstantExpr
>(V1
);
1445 Constant
*CE1Op0
= CE1
->getOperand(0);
1447 switch (CE1
->getOpcode()) {
1448 case Instruction::Trunc
:
1449 case Instruction::FPTrunc
:
1450 case Instruction::FPExt
:
1451 case Instruction::FPToUI
:
1452 case Instruction::FPToSI
:
1453 break; // We can't evaluate floating point casts or truncations.
1455 case Instruction::BitCast
:
1456 // If this is a global value cast, check to see if the RHS is also a
1458 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CE1Op0
))
1459 if (const GlobalValue
*GV2
= dyn_cast
<GlobalValue
>(V2
))
1460 return areGlobalsPotentiallyEqual(GV
, GV2
);
1462 case Instruction::UIToFP
:
1463 case Instruction::SIToFP
:
1464 case Instruction::ZExt
:
1465 case Instruction::SExt
:
1466 // We can't evaluate floating point casts or truncations.
1467 if (CE1Op0
->getType()->isFPOrFPVectorTy())
1470 // If the cast is not actually changing bits, and the second operand is a
1471 // null pointer, do the comparison with the pre-casted value.
1472 if (V2
->isNullValue() && CE1
->getType()->isIntOrPtrTy()) {
1473 if (CE1
->getOpcode() == Instruction::ZExt
) isSigned
= false;
1474 if (CE1
->getOpcode() == Instruction::SExt
) isSigned
= true;
1475 return evaluateICmpRelation(CE1Op0
,
1476 Constant::getNullValue(CE1Op0
->getType()),
1481 case Instruction::GetElementPtr
: {
1482 GEPOperator
*CE1GEP
= cast
<GEPOperator
>(CE1
);
1483 // Ok, since this is a getelementptr, we know that the constant has a
1484 // pointer type. Check the various cases.
1485 if (isa
<ConstantPointerNull
>(V2
)) {
1486 // If we are comparing a GEP to a null pointer, check to see if the base
1487 // of the GEP equals the null pointer.
1488 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CE1Op0
)) {
1489 // If its not weak linkage, the GVal must have a non-zero address
1490 // so the result is greater-than
1491 if (!GV
->hasExternalWeakLinkage() && CE1GEP
->isInBounds())
1492 return ICmpInst::ICMP_UGT
;
1494 } else if (const GlobalValue
*GV2
= dyn_cast
<GlobalValue
>(V2
)) {
1495 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CE1Op0
)) {
1497 if (CE1GEP
->hasAllZeroIndices())
1498 return areGlobalsPotentiallyEqual(GV
, GV2
);
1499 return ICmpInst::BAD_ICMP_PREDICATE
;
1502 } else if (const auto *CE2GEP
= dyn_cast
<GEPOperator
>(V2
)) {
1503 // By far the most common case to handle is when the base pointers are
1504 // obviously to the same global.
1505 const Constant
*CE2Op0
= cast
<Constant
>(CE2GEP
->getPointerOperand());
1506 if (isa
<GlobalValue
>(CE1Op0
) && isa
<GlobalValue
>(CE2Op0
)) {
1507 // Don't know relative ordering, but check for inequality.
1508 if (CE1Op0
!= CE2Op0
) {
1509 if (CE1GEP
->hasAllZeroIndices() && CE2GEP
->hasAllZeroIndices())
1510 return areGlobalsPotentiallyEqual(cast
<GlobalValue
>(CE1Op0
),
1511 cast
<GlobalValue
>(CE2Op0
));
1512 return ICmpInst::BAD_ICMP_PREDICATE
;
1523 return ICmpInst::BAD_ICMP_PREDICATE
;
1526 static Constant
*constantFoldCompareGlobalToNull(CmpInst::Predicate Predicate
,
1527 Constant
*C1
, Constant
*C2
) {
1528 const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(C2
);
1529 if (!GV
|| !C1
->isNullValue())
1532 // Don't try to evaluate aliases. External weak GV can be null.
1533 if (!isa
<GlobalAlias
>(GV
) && !GV
->hasExternalWeakLinkage() &&
1534 !NullPointerIsDefined(nullptr /* F */,
1535 GV
->getType()->getAddressSpace())) {
1536 if (Predicate
== ICmpInst::ICMP_EQ
)
1537 return ConstantInt::getFalse(C1
->getContext());
1538 else if (Predicate
== ICmpInst::ICMP_NE
)
1539 return ConstantInt::getTrue(C1
->getContext());
1545 Constant
*llvm::ConstantFoldCompareInstruction(CmpInst::Predicate Predicate
,
1546 Constant
*C1
, Constant
*C2
) {
1548 if (VectorType
*VT
= dyn_cast
<VectorType
>(C1
->getType()))
1549 ResultTy
= VectorType::get(Type::getInt1Ty(C1
->getContext()),
1550 VT
->getElementCount());
1552 ResultTy
= Type::getInt1Ty(C1
->getContext());
1554 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1555 if (Predicate
== FCmpInst::FCMP_FALSE
)
1556 return Constant::getNullValue(ResultTy
);
1558 if (Predicate
== FCmpInst::FCMP_TRUE
)
1559 return Constant::getAllOnesValue(ResultTy
);
1561 // Handle some degenerate cases first
1562 if (isa
<PoisonValue
>(C1
) || isa
<PoisonValue
>(C2
))
1563 return PoisonValue::get(ResultTy
);
1565 if (isa
<UndefValue
>(C1
) || isa
<UndefValue
>(C2
)) {
1566 bool isIntegerPredicate
= ICmpInst::isIntPredicate(Predicate
);
1567 // For EQ and NE, we can always pick a value for the undef to make the
1568 // predicate pass or fail, so we can return undef.
1569 // Also, if both operands are undef, we can return undef for int comparison.
1570 if (ICmpInst::isEquality(Predicate
) || (isIntegerPredicate
&& C1
== C2
))
1571 return UndefValue::get(ResultTy
);
1573 // Otherwise, for integer compare, pick the same value as the non-undef
1574 // operand, and fold it to true or false.
1575 if (isIntegerPredicate
)
1576 return ConstantInt::get(ResultTy
, CmpInst::isTrueWhenEqual(Predicate
));
1578 // Choosing NaN for the undef will always make unordered comparison succeed
1579 // and ordered comparison fails.
1580 return ConstantInt::get(ResultTy
, CmpInst::isUnordered(Predicate
));
1583 // icmp eq/ne(null,GV) -> false/true
1584 if (Constant
*Folded
= constantFoldCompareGlobalToNull(Predicate
, C1
, C2
))
1587 // icmp eq/ne(GV,null) -> false/true
1588 if (Constant
*Folded
= constantFoldCompareGlobalToNull(Predicate
, C2
, C1
))
1591 if (C2
->isNullValue()) {
1592 // The caller is expected to commute the operands if the constant expression
1595 if (Predicate
== ICmpInst::ICMP_UGE
)
1596 return Constant::getAllOnesValue(ResultTy
);
1598 if (Predicate
== ICmpInst::ICMP_ULT
)
1599 return Constant::getNullValue(ResultTy
);
1602 // If the comparison is a comparison between two i1's, simplify it.
1603 if (C1
->getType()->isIntegerTy(1)) {
1604 switch (Predicate
) {
1605 case ICmpInst::ICMP_EQ
:
1606 if (isa
<ConstantInt
>(C2
))
1607 return ConstantExpr::getXor(C1
, ConstantExpr::getNot(C2
));
1608 return ConstantExpr::getXor(ConstantExpr::getNot(C1
), C2
);
1609 case ICmpInst::ICMP_NE
:
1610 return ConstantExpr::getXor(C1
, C2
);
1616 if (isa
<ConstantInt
>(C1
) && isa
<ConstantInt
>(C2
)) {
1617 const APInt
&V1
= cast
<ConstantInt
>(C1
)->getValue();
1618 const APInt
&V2
= cast
<ConstantInt
>(C2
)->getValue();
1619 return ConstantInt::get(ResultTy
, ICmpInst::compare(V1
, V2
, Predicate
));
1620 } else if (isa
<ConstantFP
>(C1
) && isa
<ConstantFP
>(C2
)) {
1621 const APFloat
&C1V
= cast
<ConstantFP
>(C1
)->getValueAPF();
1622 const APFloat
&C2V
= cast
<ConstantFP
>(C2
)->getValueAPF();
1623 return ConstantInt::get(ResultTy
, FCmpInst::compare(C1V
, C2V
, Predicate
));
1624 } else if (auto *C1VTy
= dyn_cast
<VectorType
>(C1
->getType())) {
1626 // Fast path for splatted constants.
1627 if (Constant
*C1Splat
= C1
->getSplatValue())
1628 if (Constant
*C2Splat
= C2
->getSplatValue())
1629 return ConstantVector::getSplat(
1630 C1VTy
->getElementCount(),
1631 ConstantExpr::getCompare(Predicate
, C1Splat
, C2Splat
));
1633 // Do not iterate on scalable vector. The number of elements is unknown at
1635 if (isa
<ScalableVectorType
>(C1VTy
))
1638 // If we can constant fold the comparison of each element, constant fold
1639 // the whole vector comparison.
1640 SmallVector
<Constant
*, 4> ResElts
;
1641 Type
*Ty
= IntegerType::get(C1
->getContext(), 32);
1642 // Compare the elements, producing an i1 result or constant expr.
1643 for (unsigned I
= 0, E
= C1VTy
->getElementCount().getKnownMinValue();
1646 ConstantExpr::getExtractElement(C1
, ConstantInt::get(Ty
, I
));
1648 ConstantExpr::getExtractElement(C2
, ConstantInt::get(Ty
, I
));
1650 ResElts
.push_back(ConstantExpr::getCompare(Predicate
, C1E
, C2E
));
1653 return ConstantVector::get(ResElts
);
1656 if (C1
->getType()->isFloatingPointTy() &&
1657 // Only call evaluateFCmpRelation if we have a constant expr to avoid
1658 // infinite recursive loop
1659 (isa
<ConstantExpr
>(C1
) || isa
<ConstantExpr
>(C2
))) {
1660 int Result
= -1; // -1 = unknown, 0 = known false, 1 = known true.
1661 switch (evaluateFCmpRelation(C1
, C2
)) {
1662 default: llvm_unreachable("Unknown relation!");
1663 case FCmpInst::FCMP_UNO
:
1664 case FCmpInst::FCMP_ORD
:
1665 case FCmpInst::FCMP_UNE
:
1666 case FCmpInst::FCMP_ULT
:
1667 case FCmpInst::FCMP_UGT
:
1668 case FCmpInst::FCMP_ULE
:
1669 case FCmpInst::FCMP_UGE
:
1670 case FCmpInst::FCMP_TRUE
:
1671 case FCmpInst::FCMP_FALSE
:
1672 case FCmpInst::BAD_FCMP_PREDICATE
:
1673 break; // Couldn't determine anything about these constants.
1674 case FCmpInst::FCMP_OEQ
: // We know that C1 == C2
1676 (Predicate
== FCmpInst::FCMP_UEQ
|| Predicate
== FCmpInst::FCMP_OEQ
||
1677 Predicate
== FCmpInst::FCMP_ULE
|| Predicate
== FCmpInst::FCMP_OLE
||
1678 Predicate
== FCmpInst::FCMP_UGE
|| Predicate
== FCmpInst::FCMP_OGE
);
1680 case FCmpInst::FCMP_OLT
: // We know that C1 < C2
1682 (Predicate
== FCmpInst::FCMP_UNE
|| Predicate
== FCmpInst::FCMP_ONE
||
1683 Predicate
== FCmpInst::FCMP_ULT
|| Predicate
== FCmpInst::FCMP_OLT
||
1684 Predicate
== FCmpInst::FCMP_ULE
|| Predicate
== FCmpInst::FCMP_OLE
);
1686 case FCmpInst::FCMP_OGT
: // We know that C1 > C2
1688 (Predicate
== FCmpInst::FCMP_UNE
|| Predicate
== FCmpInst::FCMP_ONE
||
1689 Predicate
== FCmpInst::FCMP_UGT
|| Predicate
== FCmpInst::FCMP_OGT
||
1690 Predicate
== FCmpInst::FCMP_UGE
|| Predicate
== FCmpInst::FCMP_OGE
);
1692 case FCmpInst::FCMP_OLE
: // We know that C1 <= C2
1693 // We can only partially decide this relation.
1694 if (Predicate
== FCmpInst::FCMP_UGT
|| Predicate
== FCmpInst::FCMP_OGT
)
1696 else if (Predicate
== FCmpInst::FCMP_ULT
||
1697 Predicate
== FCmpInst::FCMP_OLT
)
1700 case FCmpInst::FCMP_OGE
: // We known that C1 >= C2
1701 // We can only partially decide this relation.
1702 if (Predicate
== FCmpInst::FCMP_ULT
|| Predicate
== FCmpInst::FCMP_OLT
)
1704 else if (Predicate
== FCmpInst::FCMP_UGT
||
1705 Predicate
== FCmpInst::FCMP_OGT
)
1708 case FCmpInst::FCMP_ONE
: // We know that C1 != C2
1709 // We can only partially decide this relation.
1710 if (Predicate
== FCmpInst::FCMP_OEQ
|| Predicate
== FCmpInst::FCMP_UEQ
)
1712 else if (Predicate
== FCmpInst::FCMP_ONE
||
1713 Predicate
== FCmpInst::FCMP_UNE
)
1716 case FCmpInst::FCMP_UEQ
: // We know that C1 == C2 || isUnordered(C1, C2).
1717 // We can only partially decide this relation.
1718 if (Predicate
== FCmpInst::FCMP_ONE
)
1720 else if (Predicate
== FCmpInst::FCMP_UEQ
)
1725 // If we evaluated the result, return it now.
1727 return ConstantInt::get(ResultTy
, Result
);
1730 // Evaluate the relation between the two constants, per the predicate.
1731 int Result
= -1; // -1 = unknown, 0 = known false, 1 = known true.
1732 switch (evaluateICmpRelation(C1
, C2
, CmpInst::isSigned(Predicate
))) {
1733 default: llvm_unreachable("Unknown relational!");
1734 case ICmpInst::BAD_ICMP_PREDICATE
:
1735 break; // Couldn't determine anything about these constants.
1736 case ICmpInst::ICMP_EQ
: // We know the constants are equal!
1737 // If we know the constants are equal, we can decide the result of this
1738 // computation precisely.
1739 Result
= ICmpInst::isTrueWhenEqual(Predicate
);
1741 case ICmpInst::ICMP_ULT
:
1742 switch (Predicate
) {
1743 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_ULE
:
1745 case ICmpInst::ICMP_UGT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_UGE
:
1751 case ICmpInst::ICMP_SLT
:
1752 switch (Predicate
) {
1753 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_SLE
:
1755 case ICmpInst::ICMP_SGT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_SGE
:
1761 case ICmpInst::ICMP_UGT
:
1762 switch (Predicate
) {
1763 case ICmpInst::ICMP_UGT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_UGE
:
1765 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_ULE
:
1771 case ICmpInst::ICMP_SGT
:
1772 switch (Predicate
) {
1773 case ICmpInst::ICMP_SGT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_SGE
:
1775 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_SLE
:
1781 case ICmpInst::ICMP_ULE
:
1782 if (Predicate
== ICmpInst::ICMP_UGT
)
1784 if (Predicate
== ICmpInst::ICMP_ULT
|| Predicate
== ICmpInst::ICMP_ULE
)
1787 case ICmpInst::ICMP_SLE
:
1788 if (Predicate
== ICmpInst::ICMP_SGT
)
1790 if (Predicate
== ICmpInst::ICMP_SLT
|| Predicate
== ICmpInst::ICMP_SLE
)
1793 case ICmpInst::ICMP_UGE
:
1794 if (Predicate
== ICmpInst::ICMP_ULT
)
1796 if (Predicate
== ICmpInst::ICMP_UGT
|| Predicate
== ICmpInst::ICMP_UGE
)
1799 case ICmpInst::ICMP_SGE
:
1800 if (Predicate
== ICmpInst::ICMP_SLT
)
1802 if (Predicate
== ICmpInst::ICMP_SGT
|| Predicate
== ICmpInst::ICMP_SGE
)
1805 case ICmpInst::ICMP_NE
:
1806 if (Predicate
== ICmpInst::ICMP_EQ
)
1808 if (Predicate
== ICmpInst::ICMP_NE
)
1813 // If we evaluated the result, return it now.
1815 return ConstantInt::get(ResultTy
, Result
);
1817 // If the right hand side is a bitcast, try using its inverse to simplify
1818 // it by moving it to the left hand side. We can't do this if it would turn
1819 // a vector compare into a scalar compare or visa versa, or if it would turn
1820 // the operands into FP values.
1821 if (ConstantExpr
*CE2
= dyn_cast
<ConstantExpr
>(C2
)) {
1822 Constant
*CE2Op0
= CE2
->getOperand(0);
1823 if (CE2
->getOpcode() == Instruction::BitCast
&&
1824 CE2
->getType()->isVectorTy() == CE2Op0
->getType()->isVectorTy() &&
1825 !CE2Op0
->getType()->isFPOrFPVectorTy()) {
1826 Constant
*Inverse
= ConstantExpr::getBitCast(C1
, CE2Op0
->getType());
1827 return ConstantExpr::getICmp(Predicate
, Inverse
, CE2Op0
);
1831 // If the left hand side is an extension, try eliminating it.
1832 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
1833 if ((CE1
->getOpcode() == Instruction::SExt
&&
1834 ICmpInst::isSigned(Predicate
)) ||
1835 (CE1
->getOpcode() == Instruction::ZExt
&&
1836 !ICmpInst::isSigned(Predicate
))) {
1837 Constant
*CE1Op0
= CE1
->getOperand(0);
1838 Constant
*CE1Inverse
= ConstantExpr::getTrunc(CE1
, CE1Op0
->getType());
1839 if (CE1Inverse
== CE1Op0
) {
1840 // Check whether we can safely truncate the right hand side.
1841 Constant
*C2Inverse
= ConstantExpr::getTrunc(C2
, CE1Op0
->getType());
1842 if (ConstantExpr::getCast(CE1
->getOpcode(), C2Inverse
,
1843 C2
->getType()) == C2
)
1844 return ConstantExpr::getICmp(Predicate
, CE1Inverse
, C2Inverse
);
1849 if ((!isa
<ConstantExpr
>(C1
) && isa
<ConstantExpr
>(C2
)) ||
1850 (C1
->isNullValue() && !C2
->isNullValue())) {
1851 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1852 // other way if possible.
1853 // Also, if C1 is null and C2 isn't, flip them around.
1854 Predicate
= ICmpInst::getSwappedPredicate(Predicate
);
1855 return ConstantExpr::getICmp(Predicate
, C2
, C1
);
1861 /// Test whether the given sequence of *normalized* indices is "inbounds".
1862 template<typename IndexTy
>
1863 static bool isInBoundsIndices(ArrayRef
<IndexTy
> Idxs
) {
1864 // No indices means nothing that could be out of bounds.
1865 if (Idxs
.empty()) return true;
1867 // If the first index is zero, it's in bounds.
1868 if (cast
<Constant
>(Idxs
[0])->isNullValue()) return true;
1870 // If the first index is one and all the rest are zero, it's in bounds,
1871 // by the one-past-the-end rule.
1872 if (auto *CI
= dyn_cast
<ConstantInt
>(Idxs
[0])) {
1876 auto *CV
= cast
<ConstantDataVector
>(Idxs
[0]);
1877 CI
= dyn_cast_or_null
<ConstantInt
>(CV
->getSplatValue());
1878 if (!CI
|| !CI
->isOne())
1882 for (unsigned i
= 1, e
= Idxs
.size(); i
!= e
; ++i
)
1883 if (!cast
<Constant
>(Idxs
[i
])->isNullValue())
1888 /// Test whether a given ConstantInt is in-range for a SequentialType.
1889 static bool isIndexInRangeOfArrayType(uint64_t NumElements
,
1890 const ConstantInt
*CI
) {
1891 // We cannot bounds check the index if it doesn't fit in an int64_t.
1892 if (CI
->getValue().getSignificantBits() > 64)
1895 // A negative index or an index past the end of our sequential type is
1896 // considered out-of-range.
1897 int64_t IndexVal
= CI
->getSExtValue();
1898 if (IndexVal
< 0 || (IndexVal
!= 0 && (uint64_t)IndexVal
>= NumElements
))
1901 // Otherwise, it is in-range.
1905 // Combine Indices - If the source pointer to this getelementptr instruction
1906 // is a getelementptr instruction, combine the indices of the two
1907 // getelementptr instructions into a single instruction.
1908 static Constant
*foldGEPOfGEP(GEPOperator
*GEP
, Type
*PointeeTy
, bool InBounds
,
1909 ArrayRef
<Value
*> Idxs
) {
1910 if (PointeeTy
!= GEP
->getResultElementType())
1913 Constant
*Idx0
= cast
<Constant
>(Idxs
[0]);
1914 if (Idx0
->isNullValue()) {
1915 // Handle the simple case of a zero index.
1916 SmallVector
<Value
*, 16> NewIndices
;
1917 NewIndices
.reserve(Idxs
.size() + GEP
->getNumIndices());
1918 NewIndices
.append(GEP
->idx_begin(), GEP
->idx_end());
1919 NewIndices
.append(Idxs
.begin() + 1, Idxs
.end());
1920 return ConstantExpr::getGetElementPtr(
1921 GEP
->getSourceElementType(), cast
<Constant
>(GEP
->getPointerOperand()),
1922 NewIndices
, InBounds
&& GEP
->isInBounds(), GEP
->getInRangeIndex());
1925 gep_type_iterator LastI
= gep_type_end(GEP
);
1926 for (gep_type_iterator I
= gep_type_begin(GEP
), E
= gep_type_end(GEP
);
1930 // We can't combine GEPs if the last index is a struct type.
1931 if (!LastI
.isSequential())
1933 // We could perform the transform with non-constant index, but prefer leaving
1934 // it as GEP of GEP rather than GEP of add for now.
1935 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(Idx0
);
1939 // TODO: This code may be extended to handle vectors as well.
1940 auto *LastIdx
= cast
<Constant
>(GEP
->getOperand(GEP
->getNumOperands()-1));
1941 Type
*LastIdxTy
= LastIdx
->getType();
1942 if (LastIdxTy
->isVectorTy())
1945 SmallVector
<Value
*, 16> NewIndices
;
1946 NewIndices
.reserve(Idxs
.size() + GEP
->getNumIndices());
1947 NewIndices
.append(GEP
->idx_begin(), GEP
->idx_end() - 1);
1949 // Add the last index of the source with the first index of the new GEP.
1950 // Make sure to handle the case when they are actually different types.
1951 if (LastIdxTy
!= Idx0
->getType()) {
1952 unsigned CommonExtendedWidth
=
1953 std::max(LastIdxTy
->getIntegerBitWidth(),
1954 Idx0
->getType()->getIntegerBitWidth());
1955 CommonExtendedWidth
= std::max(CommonExtendedWidth
, 64U);
1958 Type::getIntNTy(LastIdxTy
->getContext(), CommonExtendedWidth
);
1959 if (Idx0
->getType() != CommonTy
)
1960 Idx0
= ConstantFoldCastInstruction(Instruction::SExt
, Idx0
, CommonTy
);
1961 if (LastIdx
->getType() != CommonTy
)
1963 ConstantFoldCastInstruction(Instruction::SExt
, LastIdx
, CommonTy
);
1964 if (!Idx0
|| !LastIdx
)
1968 NewIndices
.push_back(ConstantExpr::get(Instruction::Add
, Idx0
, LastIdx
));
1969 NewIndices
.append(Idxs
.begin() + 1, Idxs
.end());
1971 // The combined GEP normally inherits its index inrange attribute from
1972 // the inner GEP, but if the inner GEP's last index was adjusted by the
1973 // outer GEP, any inbounds attribute on that index is invalidated.
1974 std::optional
<unsigned> IRIndex
= GEP
->getInRangeIndex();
1975 if (IRIndex
&& *IRIndex
== GEP
->getNumIndices() - 1)
1976 IRIndex
= std::nullopt
;
1978 return ConstantExpr::getGetElementPtr(
1979 GEP
->getSourceElementType(), cast
<Constant
>(GEP
->getPointerOperand()),
1980 NewIndices
, InBounds
&& GEP
->isInBounds(), IRIndex
);
1983 Constant
*llvm::ConstantFoldGetElementPtr(Type
*PointeeTy
, Constant
*C
,
1985 std::optional
<unsigned> InRangeIndex
,
1986 ArrayRef
<Value
*> Idxs
) {
1987 if (Idxs
.empty()) return C
;
1989 Type
*GEPTy
= GetElementPtrInst::getGEPReturnType(
1990 C
, ArrayRef((Value
*const *)Idxs
.data(), Idxs
.size()));
1992 if (isa
<PoisonValue
>(C
))
1993 return PoisonValue::get(GEPTy
);
1995 if (isa
<UndefValue
>(C
))
1996 // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
1997 return InBounds
? PoisonValue::get(GEPTy
) : UndefValue::get(GEPTy
);
1999 auto IsNoOp
= [&]() {
2000 // Avoid losing inrange information.
2004 return all_of(Idxs
, [](Value
*Idx
) {
2005 Constant
*IdxC
= cast
<Constant
>(Idx
);
2006 return IdxC
->isNullValue() || isa
<UndefValue
>(IdxC
);
2010 return GEPTy
->isVectorTy() && !C
->getType()->isVectorTy()
2011 ? ConstantVector::getSplat(
2012 cast
<VectorType
>(GEPTy
)->getElementCount(), C
)
2015 if (C
->isNullValue()) {
2017 for (Value
*Idx
: Idxs
)
2018 if (!isa
<UndefValue
>(Idx
) && !cast
<Constant
>(Idx
)->isNullValue()) {
2023 PointerType
*PtrTy
= cast
<PointerType
>(C
->getType()->getScalarType());
2024 Type
*Ty
= GetElementPtrInst::getIndexedType(PointeeTy
, Idxs
);
2026 assert(Ty
&& "Invalid indices for GEP!");
2027 Type
*OrigGEPTy
= PointerType::get(Ty
, PtrTy
->getAddressSpace());
2028 Type
*GEPTy
= PointerType::get(Ty
, PtrTy
->getAddressSpace());
2029 if (VectorType
*VT
= dyn_cast
<VectorType
>(C
->getType()))
2030 GEPTy
= VectorType::get(OrigGEPTy
, VT
->getElementCount());
2032 // The GEP returns a vector of pointers when one of more of
2033 // its arguments is a vector.
2034 for (Value
*Idx
: Idxs
) {
2035 if (auto *VT
= dyn_cast
<VectorType
>(Idx
->getType())) {
2036 assert((!isa
<VectorType
>(GEPTy
) || isa
<ScalableVectorType
>(GEPTy
) ==
2037 isa
<ScalableVectorType
>(VT
)) &&
2038 "Mismatched GEPTy vector types");
2039 GEPTy
= VectorType::get(OrigGEPTy
, VT
->getElementCount());
2044 return Constant::getNullValue(GEPTy
);
2048 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
))
2049 if (auto *GEP
= dyn_cast
<GEPOperator
>(CE
))
2050 if (Constant
*C
= foldGEPOfGEP(GEP
, PointeeTy
, InBounds
, Idxs
))
2053 // Check to see if any array indices are not within the corresponding
2054 // notional array or vector bounds. If so, try to determine if they can be
2055 // factored out into preceding dimensions.
2056 SmallVector
<Constant
*, 8> NewIdxs
;
2057 Type
*Ty
= PointeeTy
;
2058 Type
*Prev
= C
->getType();
2059 auto GEPIter
= gep_type_begin(PointeeTy
, Idxs
);
2061 !isa
<ConstantInt
>(Idxs
[0]) && !isa
<ConstantDataVector
>(Idxs
[0]);
2062 for (unsigned i
= 1, e
= Idxs
.size(); i
!= e
;
2063 Prev
= Ty
, Ty
= (++GEPIter
).getIndexedType(), ++i
) {
2064 if (!isa
<ConstantInt
>(Idxs
[i
]) && !isa
<ConstantDataVector
>(Idxs
[i
])) {
2065 // We don't know if it's in range or not.
2069 if (!isa
<ConstantInt
>(Idxs
[i
- 1]) && !isa
<ConstantDataVector
>(Idxs
[i
- 1]))
2070 // Skip if the type of the previous index is not supported.
2072 if (InRangeIndex
&& i
== *InRangeIndex
+ 1) {
2073 // If an index is marked inrange, we cannot apply this canonicalization to
2074 // the following index, as that will cause the inrange index to point to
2075 // the wrong element.
2078 if (isa
<StructType
>(Ty
)) {
2079 // The verify makes sure that GEPs into a struct are in range.
2082 if (isa
<VectorType
>(Ty
)) {
2083 // There can be awkward padding in after a non-power of two vector.
2087 auto *STy
= cast
<ArrayType
>(Ty
);
2088 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(Idxs
[i
])) {
2089 if (isIndexInRangeOfArrayType(STy
->getNumElements(), CI
))
2090 // It's in range, skip to the next index.
2092 if (CI
->isNegative()) {
2093 // It's out of range and negative, don't try to factor it.
2098 auto *CV
= cast
<ConstantDataVector
>(Idxs
[i
]);
2099 bool InRange
= true;
2100 for (unsigned I
= 0, E
= CV
->getNumElements(); I
!= E
; ++I
) {
2101 auto *CI
= cast
<ConstantInt
>(CV
->getElementAsConstant(I
));
2102 InRange
&= isIndexInRangeOfArrayType(STy
->getNumElements(), CI
);
2103 if (CI
->isNegative()) {
2108 if (InRange
|| Unknown
)
2109 // It's in range, skip to the next index.
2110 // It's out of range and negative, don't try to factor it.
2113 if (isa
<StructType
>(Prev
)) {
2114 // It's out of range, but the prior dimension is a struct
2115 // so we can't do anything about it.
2120 // Determine the number of elements in our sequential type.
2121 uint64_t NumElements
= STy
->getArrayNumElements();
2127 // It's out of range, but we can factor it into the prior
2129 NewIdxs
.resize(Idxs
.size());
2131 // Expand the current index or the previous index to a vector from a scalar
2133 Constant
*CurrIdx
= cast
<Constant
>(Idxs
[i
]);
2135 NewIdxs
[i
- 1] ? NewIdxs
[i
- 1] : cast
<Constant
>(Idxs
[i
- 1]);
2136 bool IsCurrIdxVector
= CurrIdx
->getType()->isVectorTy();
2137 bool IsPrevIdxVector
= PrevIdx
->getType()->isVectorTy();
2138 bool UseVector
= IsCurrIdxVector
|| IsPrevIdxVector
;
2140 if (!IsCurrIdxVector
&& IsPrevIdxVector
)
2141 CurrIdx
= ConstantDataVector::getSplat(
2142 cast
<FixedVectorType
>(PrevIdx
->getType())->getNumElements(), CurrIdx
);
2144 if (!IsPrevIdxVector
&& IsCurrIdxVector
)
2145 PrevIdx
= ConstantDataVector::getSplat(
2146 cast
<FixedVectorType
>(CurrIdx
->getType())->getNumElements(), PrevIdx
);
2149 ConstantInt::get(CurrIdx
->getType()->getScalarType(), NumElements
);
2151 Factor
= ConstantDataVector::getSplat(
2153 ? cast
<FixedVectorType
>(PrevIdx
->getType())->getNumElements()
2154 : cast
<FixedVectorType
>(CurrIdx
->getType())->getNumElements(),
2158 ConstantFoldBinaryInstruction(Instruction::SRem
, CurrIdx
, Factor
);
2161 ConstantFoldBinaryInstruction(Instruction::SDiv
, CurrIdx
, Factor
);
2163 // We're working on either ConstantInt or vectors of ConstantInt,
2164 // so these should always fold.
2165 assert(NewIdxs
[i
] != nullptr && Div
!= nullptr && "Should have folded");
2167 unsigned CommonExtendedWidth
=
2168 std::max(PrevIdx
->getType()->getScalarSizeInBits(),
2169 Div
->getType()->getScalarSizeInBits());
2170 CommonExtendedWidth
= std::max(CommonExtendedWidth
, 64U);
2172 // Before adding, extend both operands to i64 to avoid
2173 // overflow trouble.
2174 Type
*ExtendedTy
= Type::getIntNTy(Div
->getContext(), CommonExtendedWidth
);
2176 ExtendedTy
= FixedVectorType::get(
2179 ? cast
<FixedVectorType
>(PrevIdx
->getType())->getNumElements()
2180 : cast
<FixedVectorType
>(CurrIdx
->getType())->getNumElements());
2182 if (!PrevIdx
->getType()->isIntOrIntVectorTy(CommonExtendedWidth
))
2184 ConstantFoldCastInstruction(Instruction::SExt
, PrevIdx
, ExtendedTy
);
2186 if (!Div
->getType()->isIntOrIntVectorTy(CommonExtendedWidth
))
2187 Div
= ConstantFoldCastInstruction(Instruction::SExt
, Div
, ExtendedTy
);
2189 assert(PrevIdx
&& Div
&& "Should have folded");
2190 NewIdxs
[i
- 1] = ConstantExpr::getAdd(PrevIdx
, Div
);
2193 // If we did any factoring, start over with the adjusted indices.
2194 if (!NewIdxs
.empty()) {
2195 for (unsigned i
= 0, e
= Idxs
.size(); i
!= e
; ++i
)
2196 if (!NewIdxs
[i
]) NewIdxs
[i
] = cast
<Constant
>(Idxs
[i
]);
2197 return ConstantExpr::getGetElementPtr(PointeeTy
, C
, NewIdxs
, InBounds
,
2201 // If all indices are known integers and normalized, we can do a simple
2202 // check for the "inbounds" property.
2203 if (!Unknown
&& !InBounds
)
2204 if (auto *GV
= dyn_cast
<GlobalVariable
>(C
))
2205 if (!GV
->hasExternalWeakLinkage() && GV
->getValueType() == PointeeTy
&&
2206 isInBoundsIndices(Idxs
))
2207 return ConstantExpr::getGetElementPtr(PointeeTy
, C
, Idxs
,
2208 /*InBounds=*/true, InRangeIndex
);