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 "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"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
36 using namespace llvm::PatternMatch
;
38 //===----------------------------------------------------------------------===//
39 // ConstantFold*Instruction Implementations
40 //===----------------------------------------------------------------------===//
42 /// Convert the specified vector Constant node to the specified vector type.
43 /// At this point, we know that the elements of the input vector constant are
44 /// all simple integer or FP values.
45 static Constant
*BitCastConstantVector(Constant
*CV
, VectorType
*DstTy
) {
47 if (CV
->isAllOnesValue()) return Constant::getAllOnesValue(DstTy
);
48 if (CV
->isNullValue()) return Constant::getNullValue(DstTy
);
50 // Do not iterate on scalable vector. The num of elements is unknown at
52 if (isa
<ScalableVectorType
>(DstTy
))
55 // If this cast changes element count then we can't handle it here:
56 // doing so requires endianness information. This should be handled by
57 // Analysis/ConstantFolding.cpp
58 unsigned NumElts
= cast
<FixedVectorType
>(DstTy
)->getNumElements();
59 if (NumElts
!= cast
<FixedVectorType
>(CV
->getType())->getNumElements())
62 Type
*DstEltTy
= DstTy
->getElementType();
63 // Fast path for splatted constants.
64 if (Constant
*Splat
= CV
->getSplatValue()) {
65 return ConstantVector::getSplat(DstTy
->getElementCount(),
66 ConstantExpr::getBitCast(Splat
, DstEltTy
));
69 SmallVector
<Constant
*, 16> Result
;
70 Type
*Ty
= IntegerType::get(CV
->getContext(), 32);
71 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
73 ConstantExpr::getExtractElement(CV
, ConstantInt::get(Ty
, i
));
74 C
= ConstantExpr::getBitCast(C
, DstEltTy
);
78 return ConstantVector::get(Result
);
81 /// This function determines which opcode to use to fold two constant cast
82 /// expressions together. It uses CastInst::isEliminableCastPair to determine
83 /// the opcode. Consequently its just a wrapper around that function.
84 /// Determine if it is valid to fold a cast of a cast
87 unsigned opc
, ///< opcode of the second cast constant expression
88 ConstantExpr
*Op
, ///< the first cast constant expression
89 Type
*DstTy
///< destination type of the first cast
91 assert(Op
&& Op
->isCast() && "Can't fold cast of cast without a cast!");
92 assert(DstTy
&& DstTy
->isFirstClassType() && "Invalid cast destination type");
93 assert(CastInst::isCast(opc
) && "Invalid cast opcode");
95 // The types and opcodes for the two Cast constant expressions
96 Type
*SrcTy
= Op
->getOperand(0)->getType();
97 Type
*MidTy
= Op
->getType();
98 Instruction::CastOps firstOp
= Instruction::CastOps(Op
->getOpcode());
99 Instruction::CastOps secondOp
= Instruction::CastOps(opc
);
101 // Assume that pointers are never more than 64 bits wide, and only use this
102 // for the middle type. Otherwise we could end up folding away illegal
103 // bitcasts between address spaces with different sizes.
104 IntegerType
*FakeIntPtrTy
= Type::getInt64Ty(DstTy
->getContext());
106 // Let CastInst::isEliminableCastPair do the heavy lifting.
107 return CastInst::isEliminableCastPair(firstOp
, secondOp
, SrcTy
, MidTy
, DstTy
,
108 nullptr, FakeIntPtrTy
, nullptr);
111 static Constant
*FoldBitCast(Constant
*V
, Type
*DestTy
) {
112 Type
*SrcTy
= V
->getType();
114 return V
; // no-op cast
116 // Check to see if we are casting a pointer to an aggregate to a pointer to
117 // the first element. If so, return the appropriate GEP instruction.
118 if (PointerType
*PTy
= dyn_cast
<PointerType
>(V
->getType()))
119 if (PointerType
*DPTy
= dyn_cast
<PointerType
>(DestTy
))
120 if (PTy
->getAddressSpace() == DPTy
->getAddressSpace() &&
121 !PTy
->isOpaque() && !DPTy
->isOpaque() &&
122 PTy
->getElementType()->isSized()) {
123 SmallVector
<Value
*, 8> IdxList
;
125 Constant::getNullValue(Type::getInt32Ty(DPTy
->getContext()));
126 IdxList
.push_back(Zero
);
127 Type
*ElTy
= PTy
->getElementType();
128 while (ElTy
&& ElTy
!= DPTy
->getElementType()) {
129 ElTy
= GetElementPtrInst::getTypeAtIndex(ElTy
, (uint64_t)0);
130 IdxList
.push_back(Zero
);
133 if (ElTy
== DPTy
->getElementType())
134 // This GEP is inbounds because all indices are zero.
135 return ConstantExpr::getInBoundsGetElementPtr(PTy
->getElementType(),
139 // Handle casts from one vector constant to another. We know that the src
140 // and dest type have the same size (otherwise its an illegal cast).
141 if (VectorType
*DestPTy
= dyn_cast
<VectorType
>(DestTy
)) {
142 if (VectorType
*SrcTy
= dyn_cast
<VectorType
>(V
->getType())) {
143 assert(DestPTy
->getPrimitiveSizeInBits() ==
144 SrcTy
->getPrimitiveSizeInBits() &&
145 "Not cast between same sized vectors!");
147 // First, check for null. Undef is already handled.
148 if (isa
<ConstantAggregateZero
>(V
))
149 return Constant::getNullValue(DestTy
);
151 // Handle ConstantVector and ConstantAggregateVector.
152 return BitCastConstantVector(V
, DestPTy
);
155 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
156 // This allows for other simplifications (although some of them
157 // can only be handled by Analysis/ConstantFolding.cpp).
158 if (isa
<ConstantInt
>(V
) || isa
<ConstantFP
>(V
))
159 return ConstantExpr::getBitCast(ConstantVector::get(V
), DestPTy
);
162 // Finally, implement bitcast folding now. The code below doesn't handle
164 if (isa
<ConstantPointerNull
>(V
)) // ptr->ptr cast.
165 return ConstantPointerNull::get(cast
<PointerType
>(DestTy
));
167 // Handle integral constant input.
168 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
169 if (DestTy
->isIntegerTy())
170 // Integral -> Integral. This is a no-op because the bit widths must
171 // be the same. Consequently, we just fold to V.
174 // See note below regarding the PPC_FP128 restriction.
175 if (DestTy
->isFloatingPointTy() && !DestTy
->isPPC_FP128Ty())
176 return ConstantFP::get(DestTy
->getContext(),
177 APFloat(DestTy
->getFltSemantics(),
180 // Otherwise, can't fold this (vector?)
184 // Handle ConstantFP input: FP -> Integral.
185 if (ConstantFP
*FP
= dyn_cast
<ConstantFP
>(V
)) {
186 // PPC_FP128 is really the sum of two consecutive doubles, where the first
187 // double is always stored first in memory, regardless of the target
188 // endianness. The memory layout of i128, however, depends on the target
189 // endianness, and so we can't fold this without target endianness
190 // information. This should instead be handled by
191 // Analysis/ConstantFolding.cpp
192 if (FP
->getType()->isPPC_FP128Ty())
195 // Make sure dest type is compatible with the folded integer constant.
196 if (!DestTy
->isIntegerTy())
199 return ConstantInt::get(FP
->getContext(),
200 FP
->getValueAPF().bitcastToAPInt());
207 /// V is an integer constant which only has a subset of its bytes used.
208 /// The bytes used are indicated by ByteStart (which is the first byte used,
209 /// counting from the least significant byte) and ByteSize, which is the number
212 /// This function analyzes the specified constant to see if the specified byte
213 /// range can be returned as a simplified constant. If so, the constant is
214 /// returned, otherwise null is returned.
215 static Constant
*ExtractConstantBytes(Constant
*C
, unsigned ByteStart
,
217 assert(C
->getType()->isIntegerTy() &&
218 (cast
<IntegerType
>(C
->getType())->getBitWidth() & 7) == 0 &&
219 "Non-byte sized integer input");
220 unsigned CSize
= cast
<IntegerType
>(C
->getType())->getBitWidth()/8;
221 assert(ByteSize
&& "Must be accessing some piece");
222 assert(ByteStart
+ByteSize
<= CSize
&& "Extracting invalid piece from input");
223 assert(ByteSize
!= CSize
&& "Should not extract everything");
225 // Constant Integers are simple.
226 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(C
)) {
227 APInt V
= CI
->getValue();
229 V
.lshrInPlace(ByteStart
*8);
230 V
= V
.trunc(ByteSize
*8);
231 return ConstantInt::get(CI
->getContext(), V
);
234 // In the input is a constant expr, we might be able to recursively simplify.
235 // If not, we definitely can't do anything.
236 ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
);
237 if (!CE
) return nullptr;
239 switch (CE
->getOpcode()) {
240 default: return nullptr;
241 case Instruction::Or
: {
242 Constant
*RHS
= ExtractConstantBytes(CE
->getOperand(1), ByteStart
,ByteSize
);
247 if (ConstantInt
*RHSC
= dyn_cast
<ConstantInt
>(RHS
))
248 if (RHSC
->isMinusOne())
251 Constant
*LHS
= ExtractConstantBytes(CE
->getOperand(0), ByteStart
,ByteSize
);
254 return ConstantExpr::getOr(LHS
, RHS
);
256 case Instruction::And
: {
257 Constant
*RHS
= ExtractConstantBytes(CE
->getOperand(1), ByteStart
,ByteSize
);
262 if (RHS
->isNullValue())
265 Constant
*LHS
= ExtractConstantBytes(CE
->getOperand(0), ByteStart
,ByteSize
);
268 return ConstantExpr::getAnd(LHS
, RHS
);
270 case Instruction::LShr
: {
271 ConstantInt
*Amt
= dyn_cast
<ConstantInt
>(CE
->getOperand(1));
274 APInt ShAmt
= Amt
->getValue();
275 // Cannot analyze non-byte shifts.
276 if ((ShAmt
& 7) != 0)
278 ShAmt
.lshrInPlace(3);
280 // If the extract is known to be all zeros, return zero.
281 if (ShAmt
.uge(CSize
- ByteStart
))
282 return Constant::getNullValue(
283 IntegerType::get(CE
->getContext(), ByteSize
* 8));
284 // If the extract is known to be fully in the input, extract it.
285 if (ShAmt
.ule(CSize
- (ByteStart
+ ByteSize
)))
286 return ExtractConstantBytes(CE
->getOperand(0),
287 ByteStart
+ ShAmt
.getZExtValue(), ByteSize
);
289 // TODO: Handle the 'partially zero' case.
293 case Instruction::Shl
: {
294 ConstantInt
*Amt
= dyn_cast
<ConstantInt
>(CE
->getOperand(1));
297 APInt ShAmt
= Amt
->getValue();
298 // Cannot analyze non-byte shifts.
299 if ((ShAmt
& 7) != 0)
301 ShAmt
.lshrInPlace(3);
303 // If the extract is known to be all zeros, return zero.
304 if (ShAmt
.uge(ByteStart
+ ByteSize
))
305 return Constant::getNullValue(
306 IntegerType::get(CE
->getContext(), ByteSize
* 8));
307 // If the extract is known to be fully in the input, extract it.
308 if (ShAmt
.ule(ByteStart
))
309 return ExtractConstantBytes(CE
->getOperand(0),
310 ByteStart
- ShAmt
.getZExtValue(), ByteSize
);
312 // TODO: Handle the 'partially zero' case.
316 case Instruction::ZExt
: {
317 unsigned SrcBitSize
=
318 cast
<IntegerType
>(CE
->getOperand(0)->getType())->getBitWidth();
320 // If extracting something that is completely zero, return 0.
321 if (ByteStart
*8 >= SrcBitSize
)
322 return Constant::getNullValue(IntegerType::get(CE
->getContext(),
325 // If exactly extracting the input, return it.
326 if (ByteStart
== 0 && ByteSize
*8 == SrcBitSize
)
327 return CE
->getOperand(0);
329 // If extracting something completely in the input, if the input is a
330 // multiple of 8 bits, recurse.
331 if ((SrcBitSize
&7) == 0 && (ByteStart
+ByteSize
)*8 <= SrcBitSize
)
332 return ExtractConstantBytes(CE
->getOperand(0), ByteStart
, ByteSize
);
334 // Otherwise, if extracting a subset of the input, which is not multiple of
335 // 8 bits, do a shift and trunc to get the bits.
336 if ((ByteStart
+ByteSize
)*8 < SrcBitSize
) {
337 assert((SrcBitSize
&7) && "Shouldn't get byte sized case here");
338 Constant
*Res
= CE
->getOperand(0);
340 Res
= ConstantExpr::getLShr(Res
,
341 ConstantInt::get(Res
->getType(), ByteStart
*8));
342 return ConstantExpr::getTrunc(Res
, IntegerType::get(C
->getContext(),
346 // TODO: Handle the 'partially zero' case.
352 Constant
*llvm::ConstantFoldCastInstruction(unsigned opc
, Constant
*V
,
354 if (isa
<PoisonValue
>(V
))
355 return PoisonValue::get(DestTy
);
357 if (isa
<UndefValue
>(V
)) {
358 // zext(undef) = 0, because the top bits will be zero.
359 // sext(undef) = 0, because the top bits will all be the same.
360 // [us]itofp(undef) = 0, because the result value is bounded.
361 if (opc
== Instruction::ZExt
|| opc
== Instruction::SExt
||
362 opc
== Instruction::UIToFP
|| opc
== Instruction::SIToFP
)
363 return Constant::getNullValue(DestTy
);
364 return UndefValue::get(DestTy
);
367 if (V
->isNullValue() && !DestTy
->isX86_MMXTy() && !DestTy
->isX86_AMXTy() &&
368 opc
!= Instruction::AddrSpaceCast
)
369 return Constant::getNullValue(DestTy
);
371 // If the cast operand is a constant expression, there's a few things we can
372 // do to try to simplify it.
373 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(V
)) {
375 // Try hard to fold cast of cast because they are often eliminable.
376 if (unsigned newOpc
= foldConstantCastPair(opc
, CE
, DestTy
))
377 return ConstantExpr::getCast(newOpc
, CE
->getOperand(0), DestTy
);
378 } else if (CE
->getOpcode() == Instruction::GetElementPtr
&&
379 // Do not fold addrspacecast (gep 0, .., 0). It might make the
380 // addrspacecast uncanonicalized.
381 opc
!= Instruction::AddrSpaceCast
&&
382 // Do not fold bitcast (gep) with inrange index, as this loses
384 !cast
<GEPOperator
>(CE
)->getInRangeIndex().hasValue() &&
385 // Do not fold if the gep type is a vector, as bitcasting
386 // operand 0 of a vector gep will result in a bitcast between
388 !CE
->getType()->isVectorTy()) {
389 // If all of the indexes in the GEP are null values, there is no pointer
390 // adjustment going on. We might as well cast the source pointer.
391 bool isAllNull
= true;
392 for (unsigned i
= 1, e
= CE
->getNumOperands(); i
!= e
; ++i
)
393 if (!CE
->getOperand(i
)->isNullValue()) {
398 // This is casting one pointer type to another, always BitCast
399 return ConstantExpr::getPointerCast(CE
->getOperand(0), DestTy
);
403 // If the cast operand is a constant vector, perform the cast by
404 // operating on each element. In the cast of bitcasts, the element
405 // count may be mismatched; don't attempt to handle that here.
406 if ((isa
<ConstantVector
>(V
) || isa
<ConstantDataVector
>(V
)) &&
407 DestTy
->isVectorTy() &&
408 cast
<FixedVectorType
>(DestTy
)->getNumElements() ==
409 cast
<FixedVectorType
>(V
->getType())->getNumElements()) {
410 VectorType
*DestVecTy
= cast
<VectorType
>(DestTy
);
411 Type
*DstEltTy
= DestVecTy
->getElementType();
412 // Fast path for splatted constants.
413 if (Constant
*Splat
= V
->getSplatValue()) {
414 return ConstantVector::getSplat(
415 cast
<VectorType
>(DestTy
)->getElementCount(),
416 ConstantExpr::getCast(opc
, Splat
, DstEltTy
));
418 SmallVector
<Constant
*, 16> res
;
419 Type
*Ty
= IntegerType::get(V
->getContext(), 32);
421 e
= cast
<FixedVectorType
>(V
->getType())->getNumElements();
424 ConstantExpr::getExtractElement(V
, ConstantInt::get(Ty
, i
));
425 res
.push_back(ConstantExpr::getCast(opc
, C
, DstEltTy
));
427 return ConstantVector::get(res
);
430 // We actually have to do a cast now. Perform the cast according to the
434 llvm_unreachable("Failed to cast constant expression");
435 case Instruction::FPTrunc
:
436 case Instruction::FPExt
:
437 if (ConstantFP
*FPC
= dyn_cast
<ConstantFP
>(V
)) {
439 APFloat Val
= FPC
->getValueAPF();
440 Val
.convert(DestTy
->isHalfTy() ? APFloat::IEEEhalf() :
441 DestTy
->isFloatTy() ? APFloat::IEEEsingle() :
442 DestTy
->isDoubleTy() ? APFloat::IEEEdouble() :
443 DestTy
->isX86_FP80Ty() ? APFloat::x87DoubleExtended() :
444 DestTy
->isFP128Ty() ? APFloat::IEEEquad() :
445 DestTy
->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble() :
447 APFloat::rmNearestTiesToEven
, &ignored
);
448 return ConstantFP::get(V
->getContext(), Val
);
450 return nullptr; // Can't fold.
451 case Instruction::FPToUI
:
452 case Instruction::FPToSI
:
453 if (ConstantFP
*FPC
= dyn_cast
<ConstantFP
>(V
)) {
454 const APFloat
&V
= FPC
->getValueAPF();
456 uint32_t DestBitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
457 APSInt
IntVal(DestBitWidth
, opc
== Instruction::FPToUI
);
458 if (APFloat::opInvalidOp
==
459 V
.convertToInteger(IntVal
, APFloat::rmTowardZero
, &ignored
)) {
460 // Undefined behavior invoked - the destination type can't represent
461 // the input constant.
462 return PoisonValue::get(DestTy
);
464 return ConstantInt::get(FPC
->getContext(), IntVal
);
466 return nullptr; // Can't fold.
467 case Instruction::IntToPtr
: //always treated as unsigned
468 if (V
->isNullValue()) // Is it an integral null value?
469 return ConstantPointerNull::get(cast
<PointerType
>(DestTy
));
470 return nullptr; // Other pointer types cannot be casted
471 case Instruction::PtrToInt
: // always treated as unsigned
472 // Is it a null pointer value?
473 if (V
->isNullValue())
474 return ConstantInt::get(DestTy
, 0);
475 // Other pointer types cannot be casted
477 case Instruction::UIToFP
:
478 case Instruction::SIToFP
:
479 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
480 const APInt
&api
= CI
->getValue();
481 APFloat
apf(DestTy
->getFltSemantics(),
482 APInt::getNullValue(DestTy
->getPrimitiveSizeInBits()));
483 apf
.convertFromAPInt(api
, opc
==Instruction::SIToFP
,
484 APFloat::rmNearestTiesToEven
);
485 return ConstantFP::get(V
->getContext(), apf
);
488 case Instruction::ZExt
:
489 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
490 uint32_t BitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
491 return ConstantInt::get(V
->getContext(),
492 CI
->getValue().zext(BitWidth
));
495 case Instruction::SExt
:
496 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
497 uint32_t BitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
498 return ConstantInt::get(V
->getContext(),
499 CI
->getValue().sext(BitWidth
));
502 case Instruction::Trunc
: {
503 if (V
->getType()->isVectorTy())
506 uint32_t DestBitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
507 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
508 return ConstantInt::get(V
->getContext(),
509 CI
->getValue().trunc(DestBitWidth
));
512 // The input must be a constantexpr. See if we can simplify this based on
513 // the bytes we are demanding. Only do this if the source and dest are an
514 // even multiple of a byte.
515 if ((DestBitWidth
& 7) == 0 &&
516 (cast
<IntegerType
>(V
->getType())->getBitWidth() & 7) == 0)
517 if (Constant
*Res
= ExtractConstantBytes(V
, 0, DestBitWidth
/ 8))
522 case Instruction::BitCast
:
523 return FoldBitCast(V
, DestTy
);
524 case Instruction::AddrSpaceCast
:
529 Constant
*llvm::ConstantFoldSelectInstruction(Constant
*Cond
,
530 Constant
*V1
, Constant
*V2
) {
531 // Check for i1 and vector true/false conditions.
532 if (Cond
->isNullValue()) return V2
;
533 if (Cond
->isAllOnesValue()) return V1
;
535 // If the condition is a vector constant, fold the result elementwise.
536 if (ConstantVector
*CondV
= dyn_cast
<ConstantVector
>(Cond
)) {
537 auto *V1VTy
= CondV
->getType();
538 SmallVector
<Constant
*, 16> Result
;
539 Type
*Ty
= IntegerType::get(CondV
->getContext(), 32);
540 for (unsigned i
= 0, e
= V1VTy
->getNumElements(); i
!= e
; ++i
) {
542 Constant
*V1Element
= ConstantExpr::getExtractElement(V1
,
543 ConstantInt::get(Ty
, i
));
544 Constant
*V2Element
= ConstantExpr::getExtractElement(V2
,
545 ConstantInt::get(Ty
, i
));
546 auto *Cond
= cast
<Constant
>(CondV
->getOperand(i
));
547 if (isa
<PoisonValue
>(Cond
)) {
548 V
= PoisonValue::get(V1Element
->getType());
549 } else if (V1Element
== V2Element
) {
551 } else if (isa
<UndefValue
>(Cond
)) {
552 V
= isa
<UndefValue
>(V1Element
) ? V1Element
: V2Element
;
554 if (!isa
<ConstantInt
>(Cond
)) break;
555 V
= Cond
->isNullValue() ? V2Element
: V1Element
;
560 // If we were able to build the vector, return it.
561 if (Result
.size() == V1VTy
->getNumElements())
562 return ConstantVector::get(Result
);
565 if (isa
<PoisonValue
>(Cond
))
566 return PoisonValue::get(V1
->getType());
568 if (isa
<UndefValue
>(Cond
)) {
569 if (isa
<UndefValue
>(V1
)) return V1
;
573 if (V1
== V2
) return V1
;
575 if (isa
<PoisonValue
>(V1
))
577 if (isa
<PoisonValue
>(V2
))
580 // If the true or false value is undef, we can fold to the other value as
581 // long as the other value isn't poison.
582 auto NotPoison
= [](Constant
*C
) {
583 if (isa
<PoisonValue
>(C
))
586 // TODO: We can analyze ConstExpr by opcode to determine if there is any
587 // possibility of poison.
588 if (isa
<ConstantExpr
>(C
))
591 if (isa
<ConstantInt
>(C
) || isa
<GlobalVariable
>(C
) || isa
<ConstantFP
>(C
) ||
592 isa
<ConstantPointerNull
>(C
) || isa
<Function
>(C
))
595 if (C
->getType()->isVectorTy())
596 return !C
->containsPoisonElement() && !C
->containsConstantExpression();
598 // TODO: Recursively analyze aggregates or other constants.
601 if (isa
<UndefValue
>(V1
) && NotPoison(V2
)) return V2
;
602 if (isa
<UndefValue
>(V2
) && NotPoison(V1
)) return V1
;
604 if (ConstantExpr
*TrueVal
= dyn_cast
<ConstantExpr
>(V1
)) {
605 if (TrueVal
->getOpcode() == Instruction::Select
)
606 if (TrueVal
->getOperand(0) == Cond
)
607 return ConstantExpr::getSelect(Cond
, TrueVal
->getOperand(1), V2
);
609 if (ConstantExpr
*FalseVal
= dyn_cast
<ConstantExpr
>(V2
)) {
610 if (FalseVal
->getOpcode() == Instruction::Select
)
611 if (FalseVal
->getOperand(0) == Cond
)
612 return ConstantExpr::getSelect(Cond
, V1
, FalseVal
->getOperand(2));
618 Constant
*llvm::ConstantFoldExtractElementInstruction(Constant
*Val
,
620 auto *ValVTy
= cast
<VectorType
>(Val
->getType());
622 // extractelt poison, C -> poison
623 // extractelt C, undef -> poison
624 if (isa
<PoisonValue
>(Val
) || isa
<UndefValue
>(Idx
))
625 return PoisonValue::get(ValVTy
->getElementType());
627 // extractelt undef, C -> undef
628 if (isa
<UndefValue
>(Val
))
629 return UndefValue::get(ValVTy
->getElementType());
631 auto *CIdx
= dyn_cast
<ConstantInt
>(Idx
);
635 if (auto *ValFVTy
= dyn_cast
<FixedVectorType
>(Val
->getType())) {
636 // ee({w,x,y,z}, wrong_value) -> poison
637 if (CIdx
->uge(ValFVTy
->getNumElements()))
638 return PoisonValue::get(ValFVTy
->getElementType());
641 // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
642 if (auto *CE
= dyn_cast
<ConstantExpr
>(Val
)) {
643 if (auto *GEP
= dyn_cast
<GEPOperator
>(CE
)) {
644 SmallVector
<Constant
*, 8> Ops
;
645 Ops
.reserve(CE
->getNumOperands());
646 for (unsigned i
= 0, e
= CE
->getNumOperands(); i
!= e
; ++i
) {
647 Constant
*Op
= CE
->getOperand(i
);
648 if (Op
->getType()->isVectorTy()) {
649 Constant
*ScalarOp
= ConstantExpr::getExtractElement(Op
, Idx
);
652 Ops
.push_back(ScalarOp
);
656 return CE
->getWithOperands(Ops
, ValVTy
->getElementType(), false,
657 GEP
->getSourceElementType());
658 } else if (CE
->getOpcode() == Instruction::InsertElement
) {
659 if (const auto *IEIdx
= dyn_cast
<ConstantInt
>(CE
->getOperand(2))) {
660 if (APSInt::isSameValue(APSInt(IEIdx
->getValue()),
661 APSInt(CIdx
->getValue()))) {
662 return CE
->getOperand(1);
664 return ConstantExpr::getExtractElement(CE
->getOperand(0), CIdx
);
670 if (Constant
*C
= Val
->getAggregateElement(CIdx
))
673 // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x
674 if (CIdx
->getValue().ult(ValVTy
->getElementCount().getKnownMinValue())) {
675 if (Constant
*SplatVal
= Val
->getSplatValue())
682 Constant
*llvm::ConstantFoldInsertElementInstruction(Constant
*Val
,
685 if (isa
<UndefValue
>(Idx
))
686 return PoisonValue::get(Val
->getType());
688 ConstantInt
*CIdx
= dyn_cast
<ConstantInt
>(Idx
);
689 if (!CIdx
) return nullptr;
691 // Do not iterate on scalable vector. The num of elements is unknown at
693 if (isa
<ScalableVectorType
>(Val
->getType()))
696 auto *ValTy
= cast
<FixedVectorType
>(Val
->getType());
698 unsigned NumElts
= ValTy
->getNumElements();
699 if (CIdx
->uge(NumElts
))
700 return PoisonValue::get(Val
->getType());
702 SmallVector
<Constant
*, 16> Result
;
703 Result
.reserve(NumElts
);
704 auto *Ty
= Type::getInt32Ty(Val
->getContext());
705 uint64_t IdxVal
= CIdx
->getZExtValue();
706 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
708 Result
.push_back(Elt
);
712 Constant
*C
= ConstantExpr::getExtractElement(Val
, ConstantInt::get(Ty
, i
));
716 return ConstantVector::get(Result
);
719 Constant
*llvm::ConstantFoldShuffleVectorInstruction(Constant
*V1
, Constant
*V2
,
720 ArrayRef
<int> Mask
) {
721 auto *V1VTy
= cast
<VectorType
>(V1
->getType());
722 unsigned MaskNumElts
= Mask
.size();
724 ElementCount::get(MaskNumElts
, isa
<ScalableVectorType
>(V1VTy
));
725 Type
*EltTy
= V1VTy
->getElementType();
727 // Undefined shuffle mask -> undefined value.
728 if (all_of(Mask
, [](int Elt
) { return Elt
== UndefMaskElem
; })) {
729 return UndefValue::get(FixedVectorType::get(EltTy
, MaskNumElts
));
732 // If the mask is all zeros this is a splat, no need to go through all
734 if (all_of(Mask
, [](int Elt
) { return Elt
== 0; }) &&
735 !MaskEltCount
.isScalable()) {
736 Type
*Ty
= IntegerType::get(V1
->getContext(), 32);
738 ConstantExpr::getExtractElement(V1
, ConstantInt::get(Ty
, 0));
739 return ConstantVector::getSplat(MaskEltCount
, Elt
);
741 // Do not iterate on scalable vector. The num of elements is unknown at
743 if (isa
<ScalableVectorType
>(V1VTy
))
746 unsigned SrcNumElts
= V1VTy
->getElementCount().getKnownMinValue();
748 // Loop over the shuffle mask, evaluating each element.
749 SmallVector
<Constant
*, 32> Result
;
750 for (unsigned i
= 0; i
!= MaskNumElts
; ++i
) {
753 Result
.push_back(UndefValue::get(EltTy
));
757 if (unsigned(Elt
) >= SrcNumElts
*2)
758 InElt
= UndefValue::get(EltTy
);
759 else if (unsigned(Elt
) >= SrcNumElts
) {
760 Type
*Ty
= IntegerType::get(V2
->getContext(), 32);
762 ConstantExpr::getExtractElement(V2
,
763 ConstantInt::get(Ty
, Elt
- SrcNumElts
));
765 Type
*Ty
= IntegerType::get(V1
->getContext(), 32);
766 InElt
= ConstantExpr::getExtractElement(V1
, ConstantInt::get(Ty
, Elt
));
768 Result
.push_back(InElt
);
771 return ConstantVector::get(Result
);
774 Constant
*llvm::ConstantFoldExtractValueInstruction(Constant
*Agg
,
775 ArrayRef
<unsigned> Idxs
) {
776 // Base case: no indices, so return the entire value.
780 if (Constant
*C
= Agg
->getAggregateElement(Idxs
[0]))
781 return ConstantFoldExtractValueInstruction(C
, Idxs
.slice(1));
786 Constant
*llvm::ConstantFoldInsertValueInstruction(Constant
*Agg
,
788 ArrayRef
<unsigned> Idxs
) {
789 // Base case: no indices, so replace the entire value.
794 if (StructType
*ST
= dyn_cast
<StructType
>(Agg
->getType()))
795 NumElts
= ST
->getNumElements();
797 NumElts
= cast
<ArrayType
>(Agg
->getType())->getNumElements();
799 SmallVector
<Constant
*, 32> Result
;
800 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
801 Constant
*C
= Agg
->getAggregateElement(i
);
802 if (!C
) return nullptr;
805 C
= ConstantFoldInsertValueInstruction(C
, Val
, Idxs
.slice(1));
810 if (StructType
*ST
= dyn_cast
<StructType
>(Agg
->getType()))
811 return ConstantStruct::get(ST
, Result
);
812 return ConstantArray::get(cast
<ArrayType
>(Agg
->getType()), Result
);
815 Constant
*llvm::ConstantFoldUnaryInstruction(unsigned Opcode
, Constant
*C
) {
816 assert(Instruction::isUnaryOp(Opcode
) && "Non-unary instruction detected");
818 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
819 // vectors are always evaluated per element.
820 bool IsScalableVector
= isa
<ScalableVectorType
>(C
->getType());
821 bool HasScalarUndefOrScalableVectorUndef
=
822 (!C
->getType()->isVectorTy() || IsScalableVector
) && isa
<UndefValue
>(C
);
824 if (HasScalarUndefOrScalableVectorUndef
) {
825 switch (static_cast<Instruction::UnaryOps
>(Opcode
)) {
826 case Instruction::FNeg
:
827 return C
; // -undef -> undef
828 case Instruction::UnaryOpsEnd
:
829 llvm_unreachable("Invalid UnaryOp");
833 // Constant should not be UndefValue, unless these are vector constants.
834 assert(!HasScalarUndefOrScalableVectorUndef
&& "Unexpected UndefValue");
835 // We only have FP UnaryOps right now.
836 assert(!isa
<ConstantInt
>(C
) && "Unexpected Integer UnaryOp");
838 if (ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(C
)) {
839 const APFloat
&CV
= CFP
->getValueAPF();
843 case Instruction::FNeg
:
844 return ConstantFP::get(C
->getContext(), neg(CV
));
846 } else if (auto *VTy
= dyn_cast
<FixedVectorType
>(C
->getType())) {
848 Type
*Ty
= IntegerType::get(VTy
->getContext(), 32);
849 // Fast path for splatted constants.
850 if (Constant
*Splat
= C
->getSplatValue()) {
851 Constant
*Elt
= ConstantExpr::get(Opcode
, Splat
);
852 return ConstantVector::getSplat(VTy
->getElementCount(), Elt
);
855 // Fold each element and create a vector constant from those constants.
856 SmallVector
<Constant
*, 16> Result
;
857 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
858 Constant
*ExtractIdx
= ConstantInt::get(Ty
, i
);
859 Constant
*Elt
= ConstantExpr::getExtractElement(C
, ExtractIdx
);
861 Result
.push_back(ConstantExpr::get(Opcode
, Elt
));
864 return ConstantVector::get(Result
);
867 // We don't know how to fold this.
871 Constant
*llvm::ConstantFoldBinaryInstruction(unsigned Opcode
, Constant
*C1
,
873 assert(Instruction::isBinaryOp(Opcode
) && "Non-binary instruction detected");
875 // Simplify BinOps with their identity values first. They are no-ops and we
876 // can always return the other value, including undef or poison values.
877 // FIXME: remove unnecessary duplicated identity patterns below.
878 // FIXME: Use AllowRHSConstant with getBinOpIdentity to handle additional ops,
880 Constant
*Identity
= ConstantExpr::getBinOpIdentity(Opcode
, C1
->getType());
888 // Binary operations propagate poison.
889 if (isa
<PoisonValue
>(C1
) || isa
<PoisonValue
>(C2
))
890 return PoisonValue::get(C1
->getType());
892 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
893 // vectors are always evaluated per element.
894 bool IsScalableVector
= isa
<ScalableVectorType
>(C1
->getType());
895 bool HasScalarUndefOrScalableVectorUndef
=
896 (!C1
->getType()->isVectorTy() || IsScalableVector
) &&
897 (isa
<UndefValue
>(C1
) || isa
<UndefValue
>(C2
));
898 if (HasScalarUndefOrScalableVectorUndef
) {
899 switch (static_cast<Instruction::BinaryOps
>(Opcode
)) {
900 case Instruction::Xor
:
901 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
))
902 // Handle undef ^ undef -> 0 special case. This is a common
904 return Constant::getNullValue(C1
->getType());
906 case Instruction::Add
:
907 case Instruction::Sub
:
908 return UndefValue::get(C1
->getType());
909 case Instruction::And
:
910 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
)) // undef & undef -> undef
912 return Constant::getNullValue(C1
->getType()); // undef & X -> 0
913 case Instruction::Mul
: {
914 // undef * undef -> undef
915 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
))
918 // X * undef -> undef if X is odd
919 if (match(C1
, m_APInt(CV
)) || match(C2
, m_APInt(CV
)))
921 return UndefValue::get(C1
->getType());
923 // X * undef -> 0 otherwise
924 return Constant::getNullValue(C1
->getType());
926 case Instruction::SDiv
:
927 case Instruction::UDiv
:
928 // X / undef -> poison
930 if (match(C2
, m_CombineOr(m_Undef(), m_Zero())))
931 return PoisonValue::get(C2
->getType());
932 // undef / 1 -> undef
933 if (match(C2
, m_One()))
935 // undef / X -> 0 otherwise
936 return Constant::getNullValue(C1
->getType());
937 case Instruction::URem
:
938 case Instruction::SRem
:
939 // X % undef -> poison
941 if (match(C2
, m_CombineOr(m_Undef(), m_Zero())))
942 return PoisonValue::get(C2
->getType());
943 // undef % X -> 0 otherwise
944 return Constant::getNullValue(C1
->getType());
945 case Instruction::Or
: // X | undef -> -1
946 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
)) // undef | undef -> undef
948 return Constant::getAllOnesValue(C1
->getType()); // undef | X -> ~0
949 case Instruction::LShr
:
950 // X >>l undef -> poison
951 if (isa
<UndefValue
>(C2
))
952 return PoisonValue::get(C2
->getType());
953 // undef >>l 0 -> undef
954 if (match(C2
, m_Zero()))
957 return Constant::getNullValue(C1
->getType());
958 case Instruction::AShr
:
959 // X >>a undef -> poison
960 if (isa
<UndefValue
>(C2
))
961 return PoisonValue::get(C2
->getType());
962 // undef >>a 0 -> undef
963 if (match(C2
, m_Zero()))
965 // TODO: undef >>a X -> poison if the shift is exact
967 return Constant::getNullValue(C1
->getType());
968 case Instruction::Shl
:
969 // X << undef -> undef
970 if (isa
<UndefValue
>(C2
))
971 return PoisonValue::get(C2
->getType());
972 // undef << 0 -> undef
973 if (match(C2
, m_Zero()))
976 return Constant::getNullValue(C1
->getType());
977 case Instruction::FSub
:
978 // -0.0 - undef --> undef (consistent with "fneg undef")
979 if (match(C1
, m_NegZeroFP()) && isa
<UndefValue
>(C2
))
982 case Instruction::FAdd
:
983 case Instruction::FMul
:
984 case Instruction::FDiv
:
985 case Instruction::FRem
:
986 // [any flop] undef, undef -> undef
987 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
))
989 // [any flop] C, undef -> NaN
990 // [any flop] undef, C -> NaN
991 // We could potentially specialize NaN/Inf constants vs. 'normal'
992 // constants (possibly differently depending on opcode and operand). This
993 // would allow returning undef sometimes. But it is always safe to fold to
994 // NaN because we can choose the undef operand as NaN, and any FP opcode
995 // with a NaN operand will propagate NaN.
996 return ConstantFP::getNaN(C1
->getType());
997 case Instruction::BinaryOpsEnd
:
998 llvm_unreachable("Invalid BinaryOp");
1002 // Neither constant should be UndefValue, unless these are vector constants.
1003 assert((!HasScalarUndefOrScalableVectorUndef
) && "Unexpected UndefValue");
1005 // Handle simplifications when the RHS is a constant int.
1006 if (ConstantInt
*CI2
= dyn_cast
<ConstantInt
>(C2
)) {
1008 case Instruction::Add
:
1009 if (CI2
->isZero()) return C1
; // X + 0 == X
1011 case Instruction::Sub
:
1012 if (CI2
->isZero()) return C1
; // X - 0 == X
1014 case Instruction::Mul
:
1015 if (CI2
->isZero()) return C2
; // X * 0 == 0
1017 return C1
; // X * 1 == X
1019 case Instruction::UDiv
:
1020 case Instruction::SDiv
:
1022 return C1
; // X / 1 == X
1024 return PoisonValue::get(CI2
->getType()); // X / 0 == poison
1026 case Instruction::URem
:
1027 case Instruction::SRem
:
1029 return Constant::getNullValue(CI2
->getType()); // X % 1 == 0
1031 return PoisonValue::get(CI2
->getType()); // X % 0 == poison
1033 case Instruction::And
:
1034 if (CI2
->isZero()) return C2
; // X & 0 == 0
1035 if (CI2
->isMinusOne())
1036 return C1
; // X & -1 == X
1038 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
1039 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1040 if (CE1
->getOpcode() == Instruction::ZExt
) {
1041 unsigned DstWidth
= CI2
->getType()->getBitWidth();
1043 CE1
->getOperand(0)->getType()->getPrimitiveSizeInBits();
1044 APInt
PossiblySetBits(APInt::getLowBitsSet(DstWidth
, SrcWidth
));
1045 if ((PossiblySetBits
& CI2
->getValue()) == PossiblySetBits
)
1049 // If and'ing the address of a global with a constant, fold it.
1050 if (CE1
->getOpcode() == Instruction::PtrToInt
&&
1051 isa
<GlobalValue
>(CE1
->getOperand(0))) {
1052 GlobalValue
*GV
= cast
<GlobalValue
>(CE1
->getOperand(0));
1056 if (Module
*TheModule
= GV
->getParent()) {
1057 const DataLayout
&DL
= TheModule
->getDataLayout();
1058 GVAlign
= GV
->getPointerAlignment(DL
);
1060 // If the function alignment is not specified then assume that it
1062 // This is dangerous; on x86, the alignment of the pointer
1063 // corresponds to the alignment of the function, but might be less
1064 // than 4 if it isn't explicitly specified.
1065 // However, a fix for this behaviour was reverted because it
1066 // increased code size (see https://reviews.llvm.org/D55115)
1067 // FIXME: This code should be deleted once existing targets have
1068 // appropriate defaults
1069 if (isa
<Function
>(GV
) && !DL
.getFunctionPtrAlign())
1071 } else if (isa
<Function
>(GV
)) {
1072 // Without a datalayout we have to assume the worst case: that the
1073 // function pointer isn't aligned at all.
1074 GVAlign
= llvm::None
;
1075 } else if (isa
<GlobalVariable
>(GV
)) {
1076 GVAlign
= cast
<GlobalVariable
>(GV
)->getAlign();
1079 if (GVAlign
&& *GVAlign
> 1) {
1080 unsigned DstWidth
= CI2
->getType()->getBitWidth();
1081 unsigned SrcWidth
= std::min(DstWidth
, Log2(*GVAlign
));
1082 APInt
BitsNotSet(APInt::getLowBitsSet(DstWidth
, SrcWidth
));
1084 // If checking bits we know are clear, return zero.
1085 if ((CI2
->getValue() & BitsNotSet
) == CI2
->getValue())
1086 return Constant::getNullValue(CI2
->getType());
1091 case Instruction::Or
:
1092 if (CI2
->isZero()) return C1
; // X | 0 == X
1093 if (CI2
->isMinusOne())
1094 return C2
; // X | -1 == -1
1096 case Instruction::Xor
:
1097 if (CI2
->isZero()) return C1
; // X ^ 0 == X
1099 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
1100 switch (CE1
->getOpcode()) {
1102 case Instruction::ICmp
:
1103 case Instruction::FCmp
:
1104 // cmp pred ^ true -> cmp !pred
1105 assert(CI2
->isOne());
1106 CmpInst::Predicate pred
= (CmpInst::Predicate
)CE1
->getPredicate();
1107 pred
= CmpInst::getInversePredicate(pred
);
1108 return ConstantExpr::getCompare(pred
, CE1
->getOperand(0),
1109 CE1
->getOperand(1));
1113 case Instruction::AShr
:
1114 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1115 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
))
1116 if (CE1
->getOpcode() == Instruction::ZExt
) // Top bits known zero.
1117 return ConstantExpr::getLShr(C1
, C2
);
1120 } else if (isa
<ConstantInt
>(C1
)) {
1121 // If C1 is a ConstantInt and C2 is not, swap the operands.
1122 if (Instruction::isCommutative(Opcode
))
1123 return ConstantExpr::get(Opcode
, C2
, C1
);
1126 if (ConstantInt
*CI1
= dyn_cast
<ConstantInt
>(C1
)) {
1127 if (ConstantInt
*CI2
= dyn_cast
<ConstantInt
>(C2
)) {
1128 const APInt
&C1V
= CI1
->getValue();
1129 const APInt
&C2V
= CI2
->getValue();
1133 case Instruction::Add
:
1134 return ConstantInt::get(CI1
->getContext(), C1V
+ C2V
);
1135 case Instruction::Sub
:
1136 return ConstantInt::get(CI1
->getContext(), C1V
- C2V
);
1137 case Instruction::Mul
:
1138 return ConstantInt::get(CI1
->getContext(), C1V
* C2V
);
1139 case Instruction::UDiv
:
1140 assert(!CI2
->isZero() && "Div by zero handled above");
1141 return ConstantInt::get(CI1
->getContext(), C1V
.udiv(C2V
));
1142 case Instruction::SDiv
:
1143 assert(!CI2
->isZero() && "Div by zero handled above");
1144 if (C2V
.isAllOnesValue() && C1V
.isMinSignedValue())
1145 return PoisonValue::get(CI1
->getType()); // MIN_INT / -1 -> poison
1146 return ConstantInt::get(CI1
->getContext(), C1V
.sdiv(C2V
));
1147 case Instruction::URem
:
1148 assert(!CI2
->isZero() && "Div by zero handled above");
1149 return ConstantInt::get(CI1
->getContext(), C1V
.urem(C2V
));
1150 case Instruction::SRem
:
1151 assert(!CI2
->isZero() && "Div by zero handled above");
1152 if (C2V
.isAllOnesValue() && C1V
.isMinSignedValue())
1153 return PoisonValue::get(CI1
->getType()); // MIN_INT % -1 -> poison
1154 return ConstantInt::get(CI1
->getContext(), C1V
.srem(C2V
));
1155 case Instruction::And
:
1156 return ConstantInt::get(CI1
->getContext(), C1V
& C2V
);
1157 case Instruction::Or
:
1158 return ConstantInt::get(CI1
->getContext(), C1V
| C2V
);
1159 case Instruction::Xor
:
1160 return ConstantInt::get(CI1
->getContext(), C1V
^ C2V
);
1161 case Instruction::Shl
:
1162 if (C2V
.ult(C1V
.getBitWidth()))
1163 return ConstantInt::get(CI1
->getContext(), C1V
.shl(C2V
));
1164 return PoisonValue::get(C1
->getType()); // too big shift is poison
1165 case Instruction::LShr
:
1166 if (C2V
.ult(C1V
.getBitWidth()))
1167 return ConstantInt::get(CI1
->getContext(), C1V
.lshr(C2V
));
1168 return PoisonValue::get(C1
->getType()); // too big shift is poison
1169 case Instruction::AShr
:
1170 if (C2V
.ult(C1V
.getBitWidth()))
1171 return ConstantInt::get(CI1
->getContext(), C1V
.ashr(C2V
));
1172 return PoisonValue::get(C1
->getType()); // too big shift is poison
1177 case Instruction::SDiv
:
1178 case Instruction::UDiv
:
1179 case Instruction::URem
:
1180 case Instruction::SRem
:
1181 case Instruction::LShr
:
1182 case Instruction::AShr
:
1183 case Instruction::Shl
:
1184 if (CI1
->isZero()) return C1
;
1189 } else if (ConstantFP
*CFP1
= dyn_cast
<ConstantFP
>(C1
)) {
1190 if (ConstantFP
*CFP2
= dyn_cast
<ConstantFP
>(C2
)) {
1191 const APFloat
&C1V
= CFP1
->getValueAPF();
1192 const APFloat
&C2V
= CFP2
->getValueAPF();
1193 APFloat C3V
= C1V
; // copy for modification
1197 case Instruction::FAdd
:
1198 (void)C3V
.add(C2V
, APFloat::rmNearestTiesToEven
);
1199 return ConstantFP::get(C1
->getContext(), C3V
);
1200 case Instruction::FSub
:
1201 (void)C3V
.subtract(C2V
, APFloat::rmNearestTiesToEven
);
1202 return ConstantFP::get(C1
->getContext(), C3V
);
1203 case Instruction::FMul
:
1204 (void)C3V
.multiply(C2V
, APFloat::rmNearestTiesToEven
);
1205 return ConstantFP::get(C1
->getContext(), C3V
);
1206 case Instruction::FDiv
:
1207 (void)C3V
.divide(C2V
, APFloat::rmNearestTiesToEven
);
1208 return ConstantFP::get(C1
->getContext(), C3V
);
1209 case Instruction::FRem
:
1211 return ConstantFP::get(C1
->getContext(), C3V
);
1214 } else if (auto *VTy
= dyn_cast
<VectorType
>(C1
->getType())) {
1215 // Fast path for splatted constants.
1216 if (Constant
*C2Splat
= C2
->getSplatValue()) {
1217 if (Instruction::isIntDivRem(Opcode
) && C2Splat
->isNullValue())
1218 return PoisonValue::get(VTy
);
1219 if (Constant
*C1Splat
= C1
->getSplatValue()) {
1220 return ConstantVector::getSplat(
1221 VTy
->getElementCount(),
1222 ConstantExpr::get(Opcode
, C1Splat
, C2Splat
));
1226 if (auto *FVTy
= dyn_cast
<FixedVectorType
>(VTy
)) {
1227 // Fold each element and create a vector constant from those constants.
1228 SmallVector
<Constant
*, 16> Result
;
1229 Type
*Ty
= IntegerType::get(FVTy
->getContext(), 32);
1230 for (unsigned i
= 0, e
= FVTy
->getNumElements(); i
!= e
; ++i
) {
1231 Constant
*ExtractIdx
= ConstantInt::get(Ty
, i
);
1232 Constant
*LHS
= ConstantExpr::getExtractElement(C1
, ExtractIdx
);
1233 Constant
*RHS
= ConstantExpr::getExtractElement(C2
, ExtractIdx
);
1235 // If any element of a divisor vector is zero, the whole op is poison.
1236 if (Instruction::isIntDivRem(Opcode
) && RHS
->isNullValue())
1237 return PoisonValue::get(VTy
);
1239 Result
.push_back(ConstantExpr::get(Opcode
, LHS
, RHS
));
1242 return ConstantVector::get(Result
);
1246 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
1247 // There are many possible foldings we could do here. We should probably
1248 // at least fold add of a pointer with an integer into the appropriate
1249 // getelementptr. This will improve alias analysis a bit.
1251 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1253 if (Instruction::isAssociative(Opcode
) && CE1
->getOpcode() == Opcode
) {
1254 Constant
*T
= ConstantExpr::get(Opcode
, CE1
->getOperand(1), C2
);
1255 if (!isa
<ConstantExpr
>(T
) || cast
<ConstantExpr
>(T
)->getOpcode() != Opcode
)
1256 return ConstantExpr::get(Opcode
, CE1
->getOperand(0), T
);
1258 } else if (isa
<ConstantExpr
>(C2
)) {
1259 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1260 // other way if possible.
1261 if (Instruction::isCommutative(Opcode
))
1262 return ConstantFoldBinaryInstruction(Opcode
, C2
, C1
);
1265 // i1 can be simplified in many cases.
1266 if (C1
->getType()->isIntegerTy(1)) {
1268 case Instruction::Add
:
1269 case Instruction::Sub
:
1270 return ConstantExpr::getXor(C1
, C2
);
1271 case Instruction::Mul
:
1272 return ConstantExpr::getAnd(C1
, C2
);
1273 case Instruction::Shl
:
1274 case Instruction::LShr
:
1275 case Instruction::AShr
:
1276 // We can assume that C2 == 0. If it were one the result would be
1277 // undefined because the shift value is as large as the bitwidth.
1279 case Instruction::SDiv
:
1280 case Instruction::UDiv
:
1281 // We can assume that C2 == 1. If it were zero the result would be
1282 // undefined through division by zero.
1284 case Instruction::URem
:
1285 case Instruction::SRem
:
1286 // We can assume that C2 == 1. If it were zero the result would be
1287 // undefined through division by zero.
1288 return ConstantInt::getFalse(C1
->getContext());
1294 // We don't know how to fold this.
1298 /// This type is zero-sized if it's an array or structure of zero-sized types.
1299 /// The only leaf zero-sized type is an empty structure.
1300 static bool isMaybeZeroSizedType(Type
*Ty
) {
1301 if (StructType
*STy
= dyn_cast
<StructType
>(Ty
)) {
1302 if (STy
->isOpaque()) return true; // Can't say.
1304 // If all of elements have zero size, this does too.
1305 for (unsigned i
= 0, e
= STy
->getNumElements(); i
!= e
; ++i
)
1306 if (!isMaybeZeroSizedType(STy
->getElementType(i
))) return false;
1309 } else if (ArrayType
*ATy
= dyn_cast
<ArrayType
>(Ty
)) {
1310 return isMaybeZeroSizedType(ATy
->getElementType());
1315 /// Compare the two constants as though they were getelementptr indices.
1316 /// This allows coercion of the types to be the same thing.
1318 /// If the two constants are the "same" (after coercion), return 0. If the
1319 /// first is less than the second, return -1, if the second is less than the
1320 /// first, return 1. If the constants are not integral, return -2.
1322 static int IdxCompare(Constant
*C1
, Constant
*C2
, Type
*ElTy
) {
1323 if (C1
== C2
) return 0;
1325 // Ok, we found a different index. If they are not ConstantInt, we can't do
1326 // anything with them.
1327 if (!isa
<ConstantInt
>(C1
) || !isa
<ConstantInt
>(C2
))
1328 return -2; // don't know!
1330 // We cannot compare the indices if they don't fit in an int64_t.
1331 if (cast
<ConstantInt
>(C1
)->getValue().getActiveBits() > 64 ||
1332 cast
<ConstantInt
>(C2
)->getValue().getActiveBits() > 64)
1333 return -2; // don't know!
1335 // Ok, we have two differing integer indices. Sign extend them to be the same
1337 int64_t C1Val
= cast
<ConstantInt
>(C1
)->getSExtValue();
1338 int64_t C2Val
= cast
<ConstantInt
>(C2
)->getSExtValue();
1340 if (C1Val
== C2Val
) return 0; // They are equal
1342 // If the type being indexed over is really just a zero sized type, there is
1343 // no pointer difference being made here.
1344 if (isMaybeZeroSizedType(ElTy
))
1345 return -2; // dunno.
1347 // If they are really different, now that they are the same type, then we
1348 // found a difference!
1355 /// This function determines if there is anything we can decide about the two
1356 /// constants provided. This doesn't need to handle simple things like
1357 /// ConstantFP comparisons, but should instead handle ConstantExprs.
1358 /// If we can determine that the two constants have a particular relation to
1359 /// each other, we should return the corresponding FCmpInst predicate,
1360 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1361 /// ConstantFoldCompareInstruction.
1363 /// To simplify this code we canonicalize the relation so that the first
1364 /// operand is always the most "complex" of the two. We consider ConstantFP
1365 /// to be the simplest, and ConstantExprs to be the most complex.
1366 static FCmpInst::Predicate
evaluateFCmpRelation(Constant
*V1
, Constant
*V2
) {
1367 assert(V1
->getType() == V2
->getType() &&
1368 "Cannot compare values of different types!");
1370 // We do not know if a constant expression will evaluate to a number or NaN.
1371 // Therefore, we can only say that the relation is unordered or equal.
1372 if (V1
== V2
) return FCmpInst::FCMP_UEQ
;
1374 if (!isa
<ConstantExpr
>(V1
)) {
1375 if (!isa
<ConstantExpr
>(V2
)) {
1376 // Simple case, use the standard constant folder.
1377 ConstantInt
*R
= nullptr;
1378 R
= dyn_cast
<ConstantInt
>(
1379 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ
, V1
, V2
));
1380 if (R
&& !R
->isZero())
1381 return FCmpInst::FCMP_OEQ
;
1382 R
= dyn_cast
<ConstantInt
>(
1383 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT
, V1
, V2
));
1384 if (R
&& !R
->isZero())
1385 return FCmpInst::FCMP_OLT
;
1386 R
= dyn_cast
<ConstantInt
>(
1387 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT
, V1
, V2
));
1388 if (R
&& !R
->isZero())
1389 return FCmpInst::FCMP_OGT
;
1391 // Nothing more we can do
1392 return FCmpInst::BAD_FCMP_PREDICATE
;
1395 // If the first operand is simple and second is ConstantExpr, swap operands.
1396 FCmpInst::Predicate SwappedRelation
= evaluateFCmpRelation(V2
, V1
);
1397 if (SwappedRelation
!= FCmpInst::BAD_FCMP_PREDICATE
)
1398 return FCmpInst::getSwappedPredicate(SwappedRelation
);
1400 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1401 // constantexpr or a simple constant.
1402 ConstantExpr
*CE1
= cast
<ConstantExpr
>(V1
);
1403 switch (CE1
->getOpcode()) {
1404 case Instruction::FPTrunc
:
1405 case Instruction::FPExt
:
1406 case Instruction::UIToFP
:
1407 case Instruction::SIToFP
:
1408 // We might be able to do something with these but we don't right now.
1414 // There are MANY other foldings that we could perform here. They will
1415 // probably be added on demand, as they seem needed.
1416 return FCmpInst::BAD_FCMP_PREDICATE
;
1419 static ICmpInst::Predicate
areGlobalsPotentiallyEqual(const GlobalValue
*GV1
,
1420 const GlobalValue
*GV2
) {
1421 auto isGlobalUnsafeForEquality
= [](const GlobalValue
*GV
) {
1422 if (GV
->isInterposable() || GV
->hasGlobalUnnamedAddr())
1424 if (const auto *GVar
= dyn_cast
<GlobalVariable
>(GV
)) {
1425 Type
*Ty
= GVar
->getValueType();
1426 // A global with opaque type might end up being zero sized.
1429 // A global with an empty type might lie at the address of any other
1431 if (Ty
->isEmptyTy())
1436 // Don't try to decide equality of aliases.
1437 if (!isa
<GlobalAlias
>(GV1
) && !isa
<GlobalAlias
>(GV2
))
1438 if (!isGlobalUnsafeForEquality(GV1
) && !isGlobalUnsafeForEquality(GV2
))
1439 return ICmpInst::ICMP_NE
;
1440 return ICmpInst::BAD_ICMP_PREDICATE
;
1443 /// This function determines if there is anything we can decide about the two
1444 /// constants provided. This doesn't need to handle simple things like integer
1445 /// comparisons, but should instead handle ConstantExprs and GlobalValues.
1446 /// If we can determine that the two constants have a particular relation to
1447 /// each other, we should return the corresponding ICmp predicate, otherwise
1448 /// return ICmpInst::BAD_ICMP_PREDICATE.
1450 /// To simplify this code we canonicalize the relation so that the first
1451 /// operand is always the most "complex" of the two. We consider simple
1452 /// constants (like ConstantInt) to be the simplest, followed by
1453 /// GlobalValues, followed by ConstantExpr's (the most complex).
1455 static ICmpInst::Predicate
evaluateICmpRelation(Constant
*V1
, Constant
*V2
,
1457 assert(V1
->getType() == V2
->getType() &&
1458 "Cannot compare different types of values!");
1459 if (V1
== V2
) return ICmpInst::ICMP_EQ
;
1461 if (!isa
<ConstantExpr
>(V1
) && !isa
<GlobalValue
>(V1
) &&
1462 !isa
<BlockAddress
>(V1
)) {
1463 if (!isa
<GlobalValue
>(V2
) && !isa
<ConstantExpr
>(V2
) &&
1464 !isa
<BlockAddress
>(V2
)) {
1465 // We distilled this down to a simple case, use the standard constant
1467 ConstantInt
*R
= nullptr;
1468 ICmpInst::Predicate pred
= ICmpInst::ICMP_EQ
;
1469 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, V1
, V2
));
1470 if (R
&& !R
->isZero())
1472 pred
= isSigned
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
;
1473 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, V1
, V2
));
1474 if (R
&& !R
->isZero())
1476 pred
= isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1477 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, V1
, V2
));
1478 if (R
&& !R
->isZero())
1481 // If we couldn't figure it out, bail.
1482 return ICmpInst::BAD_ICMP_PREDICATE
;
1485 // If the first operand is simple, swap operands.
1486 ICmpInst::Predicate SwappedRelation
=
1487 evaluateICmpRelation(V2
, V1
, isSigned
);
1488 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1489 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1491 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V1
)) {
1492 if (isa
<ConstantExpr
>(V2
)) { // Swap as necessary.
1493 ICmpInst::Predicate SwappedRelation
=
1494 evaluateICmpRelation(V2
, V1
, isSigned
);
1495 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1496 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1497 return ICmpInst::BAD_ICMP_PREDICATE
;
1500 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1501 // constant (which, since the types must match, means that it's a
1502 // ConstantPointerNull).
1503 if (const GlobalValue
*GV2
= dyn_cast
<GlobalValue
>(V2
)) {
1504 return areGlobalsPotentiallyEqual(GV
, GV2
);
1505 } else if (isa
<BlockAddress
>(V2
)) {
1506 return ICmpInst::ICMP_NE
; // Globals never equal labels.
1508 assert(isa
<ConstantPointerNull
>(V2
) && "Canonicalization guarantee!");
1509 // GlobalVals can never be null unless they have external weak linkage.
1510 // We don't try to evaluate aliases here.
1511 // NOTE: We should not be doing this constant folding if null pointer
1512 // is considered valid for the function. But currently there is no way to
1513 // query it from the Constant type.
1514 if (!GV
->hasExternalWeakLinkage() && !isa
<GlobalAlias
>(GV
) &&
1515 !NullPointerIsDefined(nullptr /* F */,
1516 GV
->getType()->getAddressSpace()))
1517 return ICmpInst::ICMP_UGT
;
1519 } else if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(V1
)) {
1520 if (isa
<ConstantExpr
>(V2
)) { // Swap as necessary.
1521 ICmpInst::Predicate SwappedRelation
=
1522 evaluateICmpRelation(V2
, V1
, isSigned
);
1523 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1524 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1525 return ICmpInst::BAD_ICMP_PREDICATE
;
1528 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1529 // constant (which, since the types must match, means that it is a
1530 // ConstantPointerNull).
1531 if (const BlockAddress
*BA2
= dyn_cast
<BlockAddress
>(V2
)) {
1532 // Block address in another function can't equal this one, but block
1533 // addresses in the current function might be the same if blocks are
1535 if (BA2
->getFunction() != BA
->getFunction())
1536 return ICmpInst::ICMP_NE
;
1538 // Block addresses aren't null, don't equal the address of globals.
1539 assert((isa
<ConstantPointerNull
>(V2
) || isa
<GlobalValue
>(V2
)) &&
1540 "Canonicalization guarantee!");
1541 return ICmpInst::ICMP_NE
;
1544 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1545 // constantexpr, a global, block address, or a simple constant.
1546 ConstantExpr
*CE1
= cast
<ConstantExpr
>(V1
);
1547 Constant
*CE1Op0
= CE1
->getOperand(0);
1549 switch (CE1
->getOpcode()) {
1550 case Instruction::Trunc
:
1551 case Instruction::FPTrunc
:
1552 case Instruction::FPExt
:
1553 case Instruction::FPToUI
:
1554 case Instruction::FPToSI
:
1555 break; // We can't evaluate floating point casts or truncations.
1557 case Instruction::BitCast
:
1558 // If this is a global value cast, check to see if the RHS is also a
1560 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CE1Op0
))
1561 if (const GlobalValue
*GV2
= dyn_cast
<GlobalValue
>(V2
))
1562 return areGlobalsPotentiallyEqual(GV
, GV2
);
1564 case Instruction::UIToFP
:
1565 case Instruction::SIToFP
:
1566 case Instruction::ZExt
:
1567 case Instruction::SExt
:
1568 // We can't evaluate floating point casts or truncations.
1569 if (CE1Op0
->getType()->isFPOrFPVectorTy())
1572 // If the cast is not actually changing bits, and the second operand is a
1573 // null pointer, do the comparison with the pre-casted value.
1574 if (V2
->isNullValue() && CE1
->getType()->isIntOrPtrTy()) {
1575 if (CE1
->getOpcode() == Instruction::ZExt
) isSigned
= false;
1576 if (CE1
->getOpcode() == Instruction::SExt
) isSigned
= true;
1577 return evaluateICmpRelation(CE1Op0
,
1578 Constant::getNullValue(CE1Op0
->getType()),
1583 case Instruction::GetElementPtr
: {
1584 GEPOperator
*CE1GEP
= cast
<GEPOperator
>(CE1
);
1585 // Ok, since this is a getelementptr, we know that the constant has a
1586 // pointer type. Check the various cases.
1587 if (isa
<ConstantPointerNull
>(V2
)) {
1588 // If we are comparing a GEP to a null pointer, check to see if the base
1589 // of the GEP equals the null pointer.
1590 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CE1Op0
)) {
1591 // If its not weak linkage, the GVal must have a non-zero address
1592 // so the result is greater-than
1593 if (!GV
->hasExternalWeakLinkage())
1594 return ICmpInst::ICMP_UGT
;
1595 } else if (isa
<ConstantPointerNull
>(CE1Op0
)) {
1596 // If we are indexing from a null pointer, check to see if we have any
1597 // non-zero indices.
1598 for (unsigned i
= 1, e
= CE1
->getNumOperands(); i
!= e
; ++i
)
1599 if (!CE1
->getOperand(i
)->isNullValue())
1600 // Offsetting from null, must not be equal.
1601 return ICmpInst::ICMP_UGT
;
1602 // Only zero indexes from null, must still be zero.
1603 return ICmpInst::ICMP_EQ
;
1605 // Otherwise, we can't really say if the first operand is null or not.
1606 } else if (const GlobalValue
*GV2
= dyn_cast
<GlobalValue
>(V2
)) {
1607 if (isa
<ConstantPointerNull
>(CE1Op0
)) {
1608 // If its not weak linkage, the GVal must have a non-zero address
1609 // so the result is less-than
1610 if (!GV2
->hasExternalWeakLinkage())
1611 return ICmpInst::ICMP_ULT
;
1612 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CE1Op0
)) {
1614 // If this is a getelementptr of the same global, then it must be
1615 // different. Because the types must match, the getelementptr could
1616 // only have at most one index, and because we fold getelementptr's
1617 // with a single zero index, it must be nonzero.
1618 assert(CE1
->getNumOperands() == 2 &&
1619 !CE1
->getOperand(1)->isNullValue() &&
1620 "Surprising getelementptr!");
1621 return ICmpInst::ICMP_UGT
;
1623 if (CE1GEP
->hasAllZeroIndices())
1624 return areGlobalsPotentiallyEqual(GV
, GV2
);
1625 return ICmpInst::BAD_ICMP_PREDICATE
;
1629 ConstantExpr
*CE2
= cast
<ConstantExpr
>(V2
);
1630 Constant
*CE2Op0
= CE2
->getOperand(0);
1632 // There are MANY other foldings that we could perform here. They will
1633 // probably be added on demand, as they seem needed.
1634 switch (CE2
->getOpcode()) {
1636 case Instruction::GetElementPtr
:
1637 // By far the most common case to handle is when the base pointers are
1638 // obviously to the same global.
1639 if (isa
<GlobalValue
>(CE1Op0
) && isa
<GlobalValue
>(CE2Op0
)) {
1640 // Don't know relative ordering, but check for inequality.
1641 if (CE1Op0
!= CE2Op0
) {
1642 GEPOperator
*CE2GEP
= cast
<GEPOperator
>(CE2
);
1643 if (CE1GEP
->hasAllZeroIndices() && CE2GEP
->hasAllZeroIndices())
1644 return areGlobalsPotentiallyEqual(cast
<GlobalValue
>(CE1Op0
),
1645 cast
<GlobalValue
>(CE2Op0
));
1646 return ICmpInst::BAD_ICMP_PREDICATE
;
1648 // Ok, we know that both getelementptr instructions are based on the
1649 // same global. From this, we can precisely determine the relative
1650 // ordering of the resultant pointers.
1653 // The logic below assumes that the result of the comparison
1654 // can be determined by finding the first index that differs.
1655 // This doesn't work if there is over-indexing in any
1656 // subsequent indices, so check for that case first.
1657 if (!CE1
->isGEPWithNoNotionalOverIndexing() ||
1658 !CE2
->isGEPWithNoNotionalOverIndexing())
1659 return ICmpInst::BAD_ICMP_PREDICATE
; // Might be equal.
1661 // Compare all of the operands the GEP's have in common.
1662 gep_type_iterator GTI
= gep_type_begin(CE1
);
1663 for (;i
!= CE1
->getNumOperands() && i
!= CE2
->getNumOperands();
1665 switch (IdxCompare(CE1
->getOperand(i
),
1666 CE2
->getOperand(i
), GTI
.getIndexedType())) {
1667 case -1: return isSigned
? ICmpInst::ICMP_SLT
:ICmpInst::ICMP_ULT
;
1668 case 1: return isSigned
? ICmpInst::ICMP_SGT
:ICmpInst::ICMP_UGT
;
1669 case -2: return ICmpInst::BAD_ICMP_PREDICATE
;
1672 // Ok, we ran out of things they have in common. If any leftovers
1673 // are non-zero then we have a difference, otherwise we are equal.
1674 for (; i
< CE1
->getNumOperands(); ++i
)
1675 if (!CE1
->getOperand(i
)->isNullValue()) {
1676 if (isa
<ConstantInt
>(CE1
->getOperand(i
)))
1677 return isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1679 return ICmpInst::BAD_ICMP_PREDICATE
; // Might be equal.
1682 for (; i
< CE2
->getNumOperands(); ++i
)
1683 if (!CE2
->getOperand(i
)->isNullValue()) {
1684 if (isa
<ConstantInt
>(CE2
->getOperand(i
)))
1685 return isSigned
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
;
1687 return ICmpInst::BAD_ICMP_PREDICATE
; // Might be equal.
1689 return ICmpInst::ICMP_EQ
;
1700 return ICmpInst::BAD_ICMP_PREDICATE
;
1703 Constant
*llvm::ConstantFoldCompareInstruction(unsigned short pred
,
1704 Constant
*C1
, Constant
*C2
) {
1706 if (VectorType
*VT
= dyn_cast
<VectorType
>(C1
->getType()))
1707 ResultTy
= VectorType::get(Type::getInt1Ty(C1
->getContext()),
1708 VT
->getElementCount());
1710 ResultTy
= Type::getInt1Ty(C1
->getContext());
1712 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1713 if (pred
== FCmpInst::FCMP_FALSE
)
1714 return Constant::getNullValue(ResultTy
);
1716 if (pred
== FCmpInst::FCMP_TRUE
)
1717 return Constant::getAllOnesValue(ResultTy
);
1719 // Handle some degenerate cases first
1720 if (isa
<PoisonValue
>(C1
) || isa
<PoisonValue
>(C2
))
1721 return PoisonValue::get(ResultTy
);
1723 if (isa
<UndefValue
>(C1
) || isa
<UndefValue
>(C2
)) {
1724 CmpInst::Predicate Predicate
= CmpInst::Predicate(pred
);
1725 bool isIntegerPredicate
= ICmpInst::isIntPredicate(Predicate
);
1726 // For EQ and NE, we can always pick a value for the undef to make the
1727 // predicate pass or fail, so we can return undef.
1728 // Also, if both operands are undef, we can return undef for int comparison.
1729 if (ICmpInst::isEquality(Predicate
) || (isIntegerPredicate
&& C1
== C2
))
1730 return UndefValue::get(ResultTy
);
1732 // Otherwise, for integer compare, pick the same value as the non-undef
1733 // operand, and fold it to true or false.
1734 if (isIntegerPredicate
)
1735 return ConstantInt::get(ResultTy
, CmpInst::isTrueWhenEqual(Predicate
));
1737 // Choosing NaN for the undef will always make unordered comparison succeed
1738 // and ordered comparison fails.
1739 return ConstantInt::get(ResultTy
, CmpInst::isUnordered(Predicate
));
1742 // icmp eq/ne(null,GV) -> false/true
1743 if (C1
->isNullValue()) {
1744 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(C2
))
1745 // Don't try to evaluate aliases. External weak GV can be null.
1746 if (!isa
<GlobalAlias
>(GV
) && !GV
->hasExternalWeakLinkage() &&
1747 !NullPointerIsDefined(nullptr /* F */,
1748 GV
->getType()->getAddressSpace())) {
1749 if (pred
== ICmpInst::ICMP_EQ
)
1750 return ConstantInt::getFalse(C1
->getContext());
1751 else if (pred
== ICmpInst::ICMP_NE
)
1752 return ConstantInt::getTrue(C1
->getContext());
1754 // icmp eq/ne(GV,null) -> false/true
1755 } else if (C2
->isNullValue()) {
1756 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(C1
)) {
1757 // Don't try to evaluate aliases. External weak GV can be null.
1758 if (!isa
<GlobalAlias
>(GV
) && !GV
->hasExternalWeakLinkage() &&
1759 !NullPointerIsDefined(nullptr /* F */,
1760 GV
->getType()->getAddressSpace())) {
1761 if (pred
== ICmpInst::ICMP_EQ
)
1762 return ConstantInt::getFalse(C1
->getContext());
1763 else if (pred
== ICmpInst::ICMP_NE
)
1764 return ConstantInt::getTrue(C1
->getContext());
1768 // The caller is expected to commute the operands if the constant expression
1771 if (pred
== ICmpInst::ICMP_UGE
)
1772 return Constant::getAllOnesValue(ResultTy
);
1774 if (pred
== ICmpInst::ICMP_ULT
)
1775 return Constant::getNullValue(ResultTy
);
1778 // If the comparison is a comparison between two i1's, simplify it.
1779 if (C1
->getType()->isIntegerTy(1)) {
1781 case ICmpInst::ICMP_EQ
:
1782 if (isa
<ConstantInt
>(C2
))
1783 return ConstantExpr::getXor(C1
, ConstantExpr::getNot(C2
));
1784 return ConstantExpr::getXor(ConstantExpr::getNot(C1
), C2
);
1785 case ICmpInst::ICMP_NE
:
1786 return ConstantExpr::getXor(C1
, C2
);
1792 if (isa
<ConstantInt
>(C1
) && isa
<ConstantInt
>(C2
)) {
1793 const APInt
&V1
= cast
<ConstantInt
>(C1
)->getValue();
1794 const APInt
&V2
= cast
<ConstantInt
>(C2
)->getValue();
1796 default: llvm_unreachable("Invalid ICmp Predicate");
1797 case ICmpInst::ICMP_EQ
: return ConstantInt::get(ResultTy
, V1
== V2
);
1798 case ICmpInst::ICMP_NE
: return ConstantInt::get(ResultTy
, V1
!= V2
);
1799 case ICmpInst::ICMP_SLT
: return ConstantInt::get(ResultTy
, V1
.slt(V2
));
1800 case ICmpInst::ICMP_SGT
: return ConstantInt::get(ResultTy
, V1
.sgt(V2
));
1801 case ICmpInst::ICMP_SLE
: return ConstantInt::get(ResultTy
, V1
.sle(V2
));
1802 case ICmpInst::ICMP_SGE
: return ConstantInt::get(ResultTy
, V1
.sge(V2
));
1803 case ICmpInst::ICMP_ULT
: return ConstantInt::get(ResultTy
, V1
.ult(V2
));
1804 case ICmpInst::ICMP_UGT
: return ConstantInt::get(ResultTy
, V1
.ugt(V2
));
1805 case ICmpInst::ICMP_ULE
: return ConstantInt::get(ResultTy
, V1
.ule(V2
));
1806 case ICmpInst::ICMP_UGE
: return ConstantInt::get(ResultTy
, V1
.uge(V2
));
1808 } else if (isa
<ConstantFP
>(C1
) && isa
<ConstantFP
>(C2
)) {
1809 const APFloat
&C1V
= cast
<ConstantFP
>(C1
)->getValueAPF();
1810 const APFloat
&C2V
= cast
<ConstantFP
>(C2
)->getValueAPF();
1811 APFloat::cmpResult R
= C1V
.compare(C2V
);
1813 default: llvm_unreachable("Invalid FCmp Predicate");
1814 case FCmpInst::FCMP_FALSE
: return Constant::getNullValue(ResultTy
);
1815 case FCmpInst::FCMP_TRUE
: return Constant::getAllOnesValue(ResultTy
);
1816 case FCmpInst::FCMP_UNO
:
1817 return ConstantInt::get(ResultTy
, R
==APFloat::cmpUnordered
);
1818 case FCmpInst::FCMP_ORD
:
1819 return ConstantInt::get(ResultTy
, R
!=APFloat::cmpUnordered
);
1820 case FCmpInst::FCMP_UEQ
:
1821 return ConstantInt::get(ResultTy
, R
==APFloat::cmpUnordered
||
1822 R
==APFloat::cmpEqual
);
1823 case FCmpInst::FCMP_OEQ
:
1824 return ConstantInt::get(ResultTy
, R
==APFloat::cmpEqual
);
1825 case FCmpInst::FCMP_UNE
:
1826 return ConstantInt::get(ResultTy
, R
!=APFloat::cmpEqual
);
1827 case FCmpInst::FCMP_ONE
:
1828 return ConstantInt::get(ResultTy
, R
==APFloat::cmpLessThan
||
1829 R
==APFloat::cmpGreaterThan
);
1830 case FCmpInst::FCMP_ULT
:
1831 return ConstantInt::get(ResultTy
, R
==APFloat::cmpUnordered
||
1832 R
==APFloat::cmpLessThan
);
1833 case FCmpInst::FCMP_OLT
:
1834 return ConstantInt::get(ResultTy
, R
==APFloat::cmpLessThan
);
1835 case FCmpInst::FCMP_UGT
:
1836 return ConstantInt::get(ResultTy
, R
==APFloat::cmpUnordered
||
1837 R
==APFloat::cmpGreaterThan
);
1838 case FCmpInst::FCMP_OGT
:
1839 return ConstantInt::get(ResultTy
, R
==APFloat::cmpGreaterThan
);
1840 case FCmpInst::FCMP_ULE
:
1841 return ConstantInt::get(ResultTy
, R
!=APFloat::cmpGreaterThan
);
1842 case FCmpInst::FCMP_OLE
:
1843 return ConstantInt::get(ResultTy
, R
==APFloat::cmpLessThan
||
1844 R
==APFloat::cmpEqual
);
1845 case FCmpInst::FCMP_UGE
:
1846 return ConstantInt::get(ResultTy
, R
!=APFloat::cmpLessThan
);
1847 case FCmpInst::FCMP_OGE
:
1848 return ConstantInt::get(ResultTy
, R
==APFloat::cmpGreaterThan
||
1849 R
==APFloat::cmpEqual
);
1851 } else if (auto *C1VTy
= dyn_cast
<VectorType
>(C1
->getType())) {
1853 // Fast path for splatted constants.
1854 if (Constant
*C1Splat
= C1
->getSplatValue())
1855 if (Constant
*C2Splat
= C2
->getSplatValue())
1856 return ConstantVector::getSplat(
1857 C1VTy
->getElementCount(),
1858 ConstantExpr::getCompare(pred
, C1Splat
, C2Splat
));
1860 // Do not iterate on scalable vector. The number of elements is unknown at
1862 if (isa
<ScalableVectorType
>(C1VTy
))
1865 // If we can constant fold the comparison of each element, constant fold
1866 // the whole vector comparison.
1867 SmallVector
<Constant
*, 4> ResElts
;
1868 Type
*Ty
= IntegerType::get(C1
->getContext(), 32);
1869 // Compare the elements, producing an i1 result or constant expr.
1870 for (unsigned I
= 0, E
= C1VTy
->getElementCount().getKnownMinValue();
1873 ConstantExpr::getExtractElement(C1
, ConstantInt::get(Ty
, I
));
1875 ConstantExpr::getExtractElement(C2
, ConstantInt::get(Ty
, I
));
1877 ResElts
.push_back(ConstantExpr::getCompare(pred
, C1E
, C2E
));
1880 return ConstantVector::get(ResElts
);
1883 if (C1
->getType()->isFloatingPointTy() &&
1884 // Only call evaluateFCmpRelation if we have a constant expr to avoid
1885 // infinite recursive loop
1886 (isa
<ConstantExpr
>(C1
) || isa
<ConstantExpr
>(C2
))) {
1887 int Result
= -1; // -1 = unknown, 0 = known false, 1 = known true.
1888 switch (evaluateFCmpRelation(C1
, C2
)) {
1889 default: llvm_unreachable("Unknown relation!");
1890 case FCmpInst::FCMP_UNO
:
1891 case FCmpInst::FCMP_ORD
:
1892 case FCmpInst::FCMP_UNE
:
1893 case FCmpInst::FCMP_ULT
:
1894 case FCmpInst::FCMP_UGT
:
1895 case FCmpInst::FCMP_ULE
:
1896 case FCmpInst::FCMP_UGE
:
1897 case FCmpInst::FCMP_TRUE
:
1898 case FCmpInst::FCMP_FALSE
:
1899 case FCmpInst::BAD_FCMP_PREDICATE
:
1900 break; // Couldn't determine anything about these constants.
1901 case FCmpInst::FCMP_OEQ
: // We know that C1 == C2
1902 Result
= (pred
== FCmpInst::FCMP_UEQ
|| pred
== FCmpInst::FCMP_OEQ
||
1903 pred
== FCmpInst::FCMP_ULE
|| pred
== FCmpInst::FCMP_OLE
||
1904 pred
== FCmpInst::FCMP_UGE
|| pred
== FCmpInst::FCMP_OGE
);
1906 case FCmpInst::FCMP_OLT
: // We know that C1 < C2
1907 Result
= (pred
== FCmpInst::FCMP_UNE
|| pred
== FCmpInst::FCMP_ONE
||
1908 pred
== FCmpInst::FCMP_ULT
|| pred
== FCmpInst::FCMP_OLT
||
1909 pred
== FCmpInst::FCMP_ULE
|| pred
== FCmpInst::FCMP_OLE
);
1911 case FCmpInst::FCMP_OGT
: // We know that C1 > C2
1912 Result
= (pred
== FCmpInst::FCMP_UNE
|| pred
== FCmpInst::FCMP_ONE
||
1913 pred
== FCmpInst::FCMP_UGT
|| pred
== FCmpInst::FCMP_OGT
||
1914 pred
== FCmpInst::FCMP_UGE
|| pred
== FCmpInst::FCMP_OGE
);
1916 case FCmpInst::FCMP_OLE
: // We know that C1 <= C2
1917 // We can only partially decide this relation.
1918 if (pred
== FCmpInst::FCMP_UGT
|| pred
== FCmpInst::FCMP_OGT
)
1920 else if (pred
== FCmpInst::FCMP_ULT
|| pred
== FCmpInst::FCMP_OLT
)
1923 case FCmpInst::FCMP_OGE
: // We known that C1 >= C2
1924 // We can only partially decide this relation.
1925 if (pred
== FCmpInst::FCMP_ULT
|| pred
== FCmpInst::FCMP_OLT
)
1927 else if (pred
== FCmpInst::FCMP_UGT
|| pred
== FCmpInst::FCMP_OGT
)
1930 case FCmpInst::FCMP_ONE
: // We know that C1 != C2
1931 // We can only partially decide this relation.
1932 if (pred
== FCmpInst::FCMP_OEQ
|| pred
== FCmpInst::FCMP_UEQ
)
1934 else if (pred
== FCmpInst::FCMP_ONE
|| pred
== FCmpInst::FCMP_UNE
)
1937 case FCmpInst::FCMP_UEQ
: // We know that C1 == C2 || isUnordered(C1, C2).
1938 // We can only partially decide this relation.
1939 if (pred
== FCmpInst::FCMP_ONE
)
1941 else if (pred
== FCmpInst::FCMP_UEQ
)
1946 // If we evaluated the result, return it now.
1948 return ConstantInt::get(ResultTy
, Result
);
1951 // Evaluate the relation between the two constants, per the predicate.
1952 int Result
= -1; // -1 = unknown, 0 = known false, 1 = known true.
1953 switch (evaluateICmpRelation(C1
, C2
,
1954 CmpInst::isSigned((CmpInst::Predicate
)pred
))) {
1955 default: llvm_unreachable("Unknown relational!");
1956 case ICmpInst::BAD_ICMP_PREDICATE
:
1957 break; // Couldn't determine anything about these constants.
1958 case ICmpInst::ICMP_EQ
: // We know the constants are equal!
1959 // If we know the constants are equal, we can decide the result of this
1960 // computation precisely.
1961 Result
= ICmpInst::isTrueWhenEqual((ICmpInst::Predicate
)pred
);
1963 case ICmpInst::ICMP_ULT
:
1965 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_ULE
:
1967 case ICmpInst::ICMP_UGT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_UGE
:
1971 case ICmpInst::ICMP_SLT
:
1973 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_SLE
:
1975 case ICmpInst::ICMP_SGT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_SGE
:
1979 case ICmpInst::ICMP_UGT
:
1981 case ICmpInst::ICMP_UGT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_UGE
:
1983 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_ULE
:
1987 case ICmpInst::ICMP_SGT
:
1989 case ICmpInst::ICMP_SGT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_SGE
:
1991 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_SLE
:
1995 case ICmpInst::ICMP_ULE
:
1996 if (pred
== ICmpInst::ICMP_UGT
) Result
= 0;
1997 if (pred
== ICmpInst::ICMP_ULT
|| pred
== ICmpInst::ICMP_ULE
) Result
= 1;
1999 case ICmpInst::ICMP_SLE
:
2000 if (pred
== ICmpInst::ICMP_SGT
) Result
= 0;
2001 if (pred
== ICmpInst::ICMP_SLT
|| pred
== ICmpInst::ICMP_SLE
) Result
= 1;
2003 case ICmpInst::ICMP_UGE
:
2004 if (pred
== ICmpInst::ICMP_ULT
) Result
= 0;
2005 if (pred
== ICmpInst::ICMP_UGT
|| pred
== ICmpInst::ICMP_UGE
) Result
= 1;
2007 case ICmpInst::ICMP_SGE
:
2008 if (pred
== ICmpInst::ICMP_SLT
) Result
= 0;
2009 if (pred
== ICmpInst::ICMP_SGT
|| pred
== ICmpInst::ICMP_SGE
) Result
= 1;
2011 case ICmpInst::ICMP_NE
:
2012 if (pred
== ICmpInst::ICMP_EQ
) Result
= 0;
2013 if (pred
== ICmpInst::ICMP_NE
) Result
= 1;
2017 // If we evaluated the result, return it now.
2019 return ConstantInt::get(ResultTy
, Result
);
2021 // If the right hand side is a bitcast, try using its inverse to simplify
2022 // it by moving it to the left hand side. We can't do this if it would turn
2023 // a vector compare into a scalar compare or visa versa, or if it would turn
2024 // the operands into FP values.
2025 if (ConstantExpr
*CE2
= dyn_cast
<ConstantExpr
>(C2
)) {
2026 Constant
*CE2Op0
= CE2
->getOperand(0);
2027 if (CE2
->getOpcode() == Instruction::BitCast
&&
2028 CE2
->getType()->isVectorTy() == CE2Op0
->getType()->isVectorTy() &&
2029 !CE2Op0
->getType()->isFPOrFPVectorTy()) {
2030 Constant
*Inverse
= ConstantExpr::getBitCast(C1
, CE2Op0
->getType());
2031 return ConstantExpr::getICmp(pred
, Inverse
, CE2Op0
);
2035 // If the left hand side is an extension, try eliminating it.
2036 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
2037 if ((CE1
->getOpcode() == Instruction::SExt
&&
2038 ICmpInst::isSigned((ICmpInst::Predicate
)pred
)) ||
2039 (CE1
->getOpcode() == Instruction::ZExt
&&
2040 !ICmpInst::isSigned((ICmpInst::Predicate
)pred
))){
2041 Constant
*CE1Op0
= CE1
->getOperand(0);
2042 Constant
*CE1Inverse
= ConstantExpr::getTrunc(CE1
, CE1Op0
->getType());
2043 if (CE1Inverse
== CE1Op0
) {
2044 // Check whether we can safely truncate the right hand side.
2045 Constant
*C2Inverse
= ConstantExpr::getTrunc(C2
, CE1Op0
->getType());
2046 if (ConstantExpr::getCast(CE1
->getOpcode(), C2Inverse
,
2047 C2
->getType()) == C2
)
2048 return ConstantExpr::getICmp(pred
, CE1Inverse
, C2Inverse
);
2053 if ((!isa
<ConstantExpr
>(C1
) && isa
<ConstantExpr
>(C2
)) ||
2054 (C1
->isNullValue() && !C2
->isNullValue())) {
2055 // If C2 is a constant expr and C1 isn't, flip them around and fold the
2056 // other way if possible.
2057 // Also, if C1 is null and C2 isn't, flip them around.
2058 pred
= ICmpInst::getSwappedPredicate((ICmpInst::Predicate
)pred
);
2059 return ConstantExpr::getICmp(pred
, C2
, C1
);
2065 /// Test whether the given sequence of *normalized* indices is "inbounds".
2066 template<typename IndexTy
>
2067 static bool isInBoundsIndices(ArrayRef
<IndexTy
> Idxs
) {
2068 // No indices means nothing that could be out of bounds.
2069 if (Idxs
.empty()) return true;
2071 // If the first index is zero, it's in bounds.
2072 if (cast
<Constant
>(Idxs
[0])->isNullValue()) return true;
2074 // If the first index is one and all the rest are zero, it's in bounds,
2075 // by the one-past-the-end rule.
2076 if (auto *CI
= dyn_cast
<ConstantInt
>(Idxs
[0])) {
2080 auto *CV
= cast
<ConstantDataVector
>(Idxs
[0]);
2081 CI
= dyn_cast_or_null
<ConstantInt
>(CV
->getSplatValue());
2082 if (!CI
|| !CI
->isOne())
2086 for (unsigned i
= 1, e
= Idxs
.size(); i
!= e
; ++i
)
2087 if (!cast
<Constant
>(Idxs
[i
])->isNullValue())
2092 /// Test whether a given ConstantInt is in-range for a SequentialType.
2093 static bool isIndexInRangeOfArrayType(uint64_t NumElements
,
2094 const ConstantInt
*CI
) {
2095 // We cannot bounds check the index if it doesn't fit in an int64_t.
2096 if (CI
->getValue().getMinSignedBits() > 64)
2099 // A negative index or an index past the end of our sequential type is
2100 // considered out-of-range.
2101 int64_t IndexVal
= CI
->getSExtValue();
2102 if (IndexVal
< 0 || (NumElements
> 0 && (uint64_t)IndexVal
>= NumElements
))
2105 // Otherwise, it is in-range.
2109 // Combine Indices - If the source pointer to this getelementptr instruction
2110 // is a getelementptr instruction, combine the indices of the two
2111 // getelementptr instructions into a single instruction.
2112 static Constant
*foldGEPOfGEP(GEPOperator
*GEP
, Type
*PointeeTy
, bool InBounds
,
2113 ArrayRef
<Value
*> Idxs
) {
2114 if (PointeeTy
!= GEP
->getResultElementType())
2117 Constant
*Idx0
= cast
<Constant
>(Idxs
[0]);
2118 if (Idx0
->isNullValue()) {
2119 // Handle the simple case of a zero index.
2120 SmallVector
<Value
*, 16> NewIndices
;
2121 NewIndices
.reserve(Idxs
.size() + GEP
->getNumIndices());
2122 NewIndices
.append(GEP
->idx_begin(), GEP
->idx_end());
2123 NewIndices
.append(Idxs
.begin() + 1, Idxs
.end());
2124 return ConstantExpr::getGetElementPtr(
2125 GEP
->getSourceElementType(), cast
<Constant
>(GEP
->getPointerOperand()),
2126 NewIndices
, InBounds
&& GEP
->isInBounds(), GEP
->getInRangeIndex());
2129 gep_type_iterator LastI
= gep_type_end(GEP
);
2130 for (gep_type_iterator I
= gep_type_begin(GEP
), E
= gep_type_end(GEP
);
2134 // We cannot combine indices if doing so would take us outside of an
2135 // array or vector. Doing otherwise could trick us if we evaluated such a
2136 // GEP as part of a load.
2138 // e.g. Consider if the original GEP was:
2139 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2140 // i32 0, i32 0, i64 0)
2142 // If we then tried to offset it by '8' to get to the third element,
2143 // an i8, we should *not* get:
2144 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2145 // i32 0, i32 0, i64 8)
2147 // This GEP tries to index array element '8 which runs out-of-bounds.
2148 // Subsequent evaluation would get confused and produce erroneous results.
2150 // The following prohibits such a GEP from being formed by checking to see
2151 // if the index is in-range with respect to an array.
2152 if (!LastI
.isSequential())
2154 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(Idx0
);
2157 if (LastI
.isBoundedSequential() &&
2158 !isIndexInRangeOfArrayType(LastI
.getSequentialNumElements(), CI
))
2161 // TODO: This code may be extended to handle vectors as well.
2162 auto *LastIdx
= cast
<Constant
>(GEP
->getOperand(GEP
->getNumOperands()-1));
2163 Type
*LastIdxTy
= LastIdx
->getType();
2164 if (LastIdxTy
->isVectorTy())
2167 SmallVector
<Value
*, 16> NewIndices
;
2168 NewIndices
.reserve(Idxs
.size() + GEP
->getNumIndices());
2169 NewIndices
.append(GEP
->idx_begin(), GEP
->idx_end() - 1);
2171 // Add the last index of the source with the first index of the new GEP.
2172 // Make sure to handle the case when they are actually different types.
2173 if (LastIdxTy
!= Idx0
->getType()) {
2174 unsigned CommonExtendedWidth
=
2175 std::max(LastIdxTy
->getIntegerBitWidth(),
2176 Idx0
->getType()->getIntegerBitWidth());
2177 CommonExtendedWidth
= std::max(CommonExtendedWidth
, 64U);
2180 Type::getIntNTy(LastIdxTy
->getContext(), CommonExtendedWidth
);
2181 Idx0
= ConstantExpr::getSExtOrBitCast(Idx0
, CommonTy
);
2182 LastIdx
= ConstantExpr::getSExtOrBitCast(LastIdx
, CommonTy
);
2185 NewIndices
.push_back(ConstantExpr::get(Instruction::Add
, Idx0
, LastIdx
));
2186 NewIndices
.append(Idxs
.begin() + 1, Idxs
.end());
2188 // The combined GEP normally inherits its index inrange attribute from
2189 // the inner GEP, but if the inner GEP's last index was adjusted by the
2190 // outer GEP, any inbounds attribute on that index is invalidated.
2191 Optional
<unsigned> IRIndex
= GEP
->getInRangeIndex();
2192 if (IRIndex
&& *IRIndex
== GEP
->getNumIndices() - 1)
2195 return ConstantExpr::getGetElementPtr(
2196 GEP
->getSourceElementType(), cast
<Constant
>(GEP
->getPointerOperand()),
2197 NewIndices
, InBounds
&& GEP
->isInBounds(), IRIndex
);
2200 Constant
*llvm::ConstantFoldGetElementPtr(Type
*PointeeTy
, Constant
*C
,
2202 Optional
<unsigned> InRangeIndex
,
2203 ArrayRef
<Value
*> Idxs
) {
2204 if (Idxs
.empty()) return C
;
2206 Type
*GEPTy
= GetElementPtrInst::getGEPReturnType(
2207 PointeeTy
, C
, makeArrayRef((Value
*const *)Idxs
.data(), Idxs
.size()));
2209 if (isa
<PoisonValue
>(C
))
2210 return PoisonValue::get(GEPTy
);
2212 if (isa
<UndefValue
>(C
))
2213 // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
2214 return InBounds
? PoisonValue::get(GEPTy
) : UndefValue::get(GEPTy
);
2216 Constant
*Idx0
= cast
<Constant
>(Idxs
[0]);
2217 if (Idxs
.size() == 1 && (Idx0
->isNullValue() || isa
<UndefValue
>(Idx0
)))
2218 return GEPTy
->isVectorTy() && !C
->getType()->isVectorTy()
2219 ? ConstantVector::getSplat(
2220 cast
<VectorType
>(GEPTy
)->getElementCount(), C
)
2223 if (C
->isNullValue()) {
2225 for (unsigned i
= 0, e
= Idxs
.size(); i
!= e
; ++i
)
2226 if (!isa
<UndefValue
>(Idxs
[i
]) &&
2227 !cast
<Constant
>(Idxs
[i
])->isNullValue()) {
2232 PointerType
*PtrTy
= cast
<PointerType
>(C
->getType()->getScalarType());
2233 Type
*Ty
= GetElementPtrInst::getIndexedType(PointeeTy
, Idxs
);
2235 assert(Ty
&& "Invalid indices for GEP!");
2236 Type
*OrigGEPTy
= PointerType::get(Ty
, PtrTy
->getAddressSpace());
2237 Type
*GEPTy
= PointerType::get(Ty
, PtrTy
->getAddressSpace());
2238 if (VectorType
*VT
= dyn_cast
<VectorType
>(C
->getType()))
2239 GEPTy
= VectorType::get(OrigGEPTy
, VT
->getElementCount());
2241 // The GEP returns a vector of pointers when one of more of
2242 // its arguments is a vector.
2243 for (unsigned i
= 0, e
= Idxs
.size(); i
!= e
; ++i
) {
2244 if (auto *VT
= dyn_cast
<VectorType
>(Idxs
[i
]->getType())) {
2245 assert((!isa
<VectorType
>(GEPTy
) || isa
<ScalableVectorType
>(GEPTy
) ==
2246 isa
<ScalableVectorType
>(VT
)) &&
2247 "Mismatched GEPTy vector types");
2248 GEPTy
= VectorType::get(OrigGEPTy
, VT
->getElementCount());
2253 return Constant::getNullValue(GEPTy
);
2257 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
)) {
2258 if (auto *GEP
= dyn_cast
<GEPOperator
>(CE
))
2259 if (Constant
*C
= foldGEPOfGEP(GEP
, PointeeTy
, InBounds
, Idxs
))
2262 // Attempt to fold casts to the same type away. For example, folding:
2264 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2268 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2270 // Don't fold if the cast is changing address spaces.
2271 if (CE
->isCast() && Idxs
.size() > 1 && Idx0
->isNullValue()) {
2272 PointerType
*SrcPtrTy
=
2273 dyn_cast
<PointerType
>(CE
->getOperand(0)->getType());
2274 PointerType
*DstPtrTy
= dyn_cast
<PointerType
>(CE
->getType());
2275 if (SrcPtrTy
&& DstPtrTy
) {
2276 ArrayType
*SrcArrayTy
=
2277 dyn_cast
<ArrayType
>(SrcPtrTy
->getElementType());
2278 ArrayType
*DstArrayTy
=
2279 dyn_cast
<ArrayType
>(DstPtrTy
->getElementType());
2280 if (SrcArrayTy
&& DstArrayTy
2281 && SrcArrayTy
->getElementType() == DstArrayTy
->getElementType()
2282 && SrcPtrTy
->getAddressSpace() == DstPtrTy
->getAddressSpace())
2283 return ConstantExpr::getGetElementPtr(SrcArrayTy
,
2284 (Constant
*)CE
->getOperand(0),
2285 Idxs
, InBounds
, InRangeIndex
);
2290 // Check to see if any array indices are not within the corresponding
2291 // notional array or vector bounds. If so, try to determine if they can be
2292 // factored out into preceding dimensions.
2293 SmallVector
<Constant
*, 8> NewIdxs
;
2294 Type
*Ty
= PointeeTy
;
2295 Type
*Prev
= C
->getType();
2296 auto GEPIter
= gep_type_begin(PointeeTy
, Idxs
);
2298 !isa
<ConstantInt
>(Idxs
[0]) && !isa
<ConstantDataVector
>(Idxs
[0]);
2299 for (unsigned i
= 1, e
= Idxs
.size(); i
!= e
;
2300 Prev
= Ty
, Ty
= (++GEPIter
).getIndexedType(), ++i
) {
2301 if (!isa
<ConstantInt
>(Idxs
[i
]) && !isa
<ConstantDataVector
>(Idxs
[i
])) {
2302 // We don't know if it's in range or not.
2306 if (!isa
<ConstantInt
>(Idxs
[i
- 1]) && !isa
<ConstantDataVector
>(Idxs
[i
- 1]))
2307 // Skip if the type of the previous index is not supported.
2309 if (InRangeIndex
&& i
== *InRangeIndex
+ 1) {
2310 // If an index is marked inrange, we cannot apply this canonicalization to
2311 // the following index, as that will cause the inrange index to point to
2312 // the wrong element.
2315 if (isa
<StructType
>(Ty
)) {
2316 // The verify makes sure that GEPs into a struct are in range.
2319 if (isa
<VectorType
>(Ty
)) {
2320 // There can be awkward padding in after a non-power of two vector.
2324 auto *STy
= cast
<ArrayType
>(Ty
);
2325 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(Idxs
[i
])) {
2326 if (isIndexInRangeOfArrayType(STy
->getNumElements(), CI
))
2327 // It's in range, skip to the next index.
2329 if (CI
->getSExtValue() < 0) {
2330 // It's out of range and negative, don't try to factor it.
2335 auto *CV
= cast
<ConstantDataVector
>(Idxs
[i
]);
2336 bool InRange
= true;
2337 for (unsigned I
= 0, E
= CV
->getNumElements(); I
!= E
; ++I
) {
2338 auto *CI
= cast
<ConstantInt
>(CV
->getElementAsConstant(I
));
2339 InRange
&= isIndexInRangeOfArrayType(STy
->getNumElements(), CI
);
2340 if (CI
->getSExtValue() < 0) {
2345 if (InRange
|| Unknown
)
2346 // It's in range, skip to the next index.
2347 // It's out of range and negative, don't try to factor it.
2350 if (isa
<StructType
>(Prev
)) {
2351 // It's out of range, but the prior dimension is a struct
2352 // so we can't do anything about it.
2356 // It's out of range, but we can factor it into the prior
2358 NewIdxs
.resize(Idxs
.size());
2359 // Determine the number of elements in our sequential type.
2360 uint64_t NumElements
= STy
->getArrayNumElements();
2362 // Expand the current index or the previous index to a vector from a scalar
2364 Constant
*CurrIdx
= cast
<Constant
>(Idxs
[i
]);
2366 NewIdxs
[i
- 1] ? NewIdxs
[i
- 1] : cast
<Constant
>(Idxs
[i
- 1]);
2367 bool IsCurrIdxVector
= CurrIdx
->getType()->isVectorTy();
2368 bool IsPrevIdxVector
= PrevIdx
->getType()->isVectorTy();
2369 bool UseVector
= IsCurrIdxVector
|| IsPrevIdxVector
;
2371 if (!IsCurrIdxVector
&& IsPrevIdxVector
)
2372 CurrIdx
= ConstantDataVector::getSplat(
2373 cast
<FixedVectorType
>(PrevIdx
->getType())->getNumElements(), CurrIdx
);
2375 if (!IsPrevIdxVector
&& IsCurrIdxVector
)
2376 PrevIdx
= ConstantDataVector::getSplat(
2377 cast
<FixedVectorType
>(CurrIdx
->getType())->getNumElements(), PrevIdx
);
2380 ConstantInt::get(CurrIdx
->getType()->getScalarType(), NumElements
);
2382 Factor
= ConstantDataVector::getSplat(
2384 ? cast
<FixedVectorType
>(PrevIdx
->getType())->getNumElements()
2385 : cast
<FixedVectorType
>(CurrIdx
->getType())->getNumElements(),
2388 NewIdxs
[i
] = ConstantExpr::getSRem(CurrIdx
, Factor
);
2390 Constant
*Div
= ConstantExpr::getSDiv(CurrIdx
, Factor
);
2392 unsigned CommonExtendedWidth
=
2393 std::max(PrevIdx
->getType()->getScalarSizeInBits(),
2394 Div
->getType()->getScalarSizeInBits());
2395 CommonExtendedWidth
= std::max(CommonExtendedWidth
, 64U);
2397 // Before adding, extend both operands to i64 to avoid
2398 // overflow trouble.
2399 Type
*ExtendedTy
= Type::getIntNTy(Div
->getContext(), CommonExtendedWidth
);
2401 ExtendedTy
= FixedVectorType::get(
2404 ? cast
<FixedVectorType
>(PrevIdx
->getType())->getNumElements()
2405 : cast
<FixedVectorType
>(CurrIdx
->getType())->getNumElements());
2407 if (!PrevIdx
->getType()->isIntOrIntVectorTy(CommonExtendedWidth
))
2408 PrevIdx
= ConstantExpr::getSExt(PrevIdx
, ExtendedTy
);
2410 if (!Div
->getType()->isIntOrIntVectorTy(CommonExtendedWidth
))
2411 Div
= ConstantExpr::getSExt(Div
, ExtendedTy
);
2413 NewIdxs
[i
- 1] = ConstantExpr::getAdd(PrevIdx
, Div
);
2416 // If we did any factoring, start over with the adjusted indices.
2417 if (!NewIdxs
.empty()) {
2418 for (unsigned i
= 0, e
= Idxs
.size(); i
!= e
; ++i
)
2419 if (!NewIdxs
[i
]) NewIdxs
[i
] = cast
<Constant
>(Idxs
[i
]);
2420 return ConstantExpr::getGetElementPtr(PointeeTy
, C
, NewIdxs
, InBounds
,
2424 // If all indices are known integers and normalized, we can do a simple
2425 // check for the "inbounds" property.
2426 if (!Unknown
&& !InBounds
)
2427 if (auto *GV
= dyn_cast
<GlobalVariable
>(C
))
2428 if (!GV
->hasExternalWeakLinkage() && isInBoundsIndices(Idxs
))
2429 return ConstantExpr::getGetElementPtr(PointeeTy
, C
, Idxs
,
2430 /*InBounds=*/true, InRangeIndex
);