Path: blob/main/contrib/llvm-project/llvm/lib/IR/ConstantFold.cpp
35234 views
//===- ConstantFold.cpp - LLVM constant folder ----------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements folding of constants for LLVM. This implements the9// (internal) ConstantFold.h interface, which is used by the10// ConstantExpr::get* methods to automatically fold constants when possible.11//12// The current constant folding implementation is implemented in two pieces: the13// pieces that don't need DataLayout, and the pieces that do. This is to avoid14// a dependence in IR on Target.15//16//===----------------------------------------------------------------------===//1718#include "llvm/IR/ConstantFold.h"19#include "llvm/ADT/APSInt.h"20#include "llvm/ADT/SmallVector.h"21#include "llvm/IR/Constants.h"22#include "llvm/IR/DerivedTypes.h"23#include "llvm/IR/Function.h"24#include "llvm/IR/GetElementPtrTypeIterator.h"25#include "llvm/IR/GlobalAlias.h"26#include "llvm/IR/GlobalVariable.h"27#include "llvm/IR/Instructions.h"28#include "llvm/IR/Module.h"29#include "llvm/IR/Operator.h"30#include "llvm/IR/PatternMatch.h"31#include "llvm/Support/ErrorHandling.h"32using namespace llvm;33using namespace llvm::PatternMatch;3435//===----------------------------------------------------------------------===//36// ConstantFold*Instruction Implementations37//===----------------------------------------------------------------------===//3839/// This function determines which opcode to use to fold two constant cast40/// expressions together. It uses CastInst::isEliminableCastPair to determine41/// the opcode. Consequently its just a wrapper around that function.42/// Determine if it is valid to fold a cast of a cast43static unsigned44foldConstantCastPair(45unsigned opc, ///< opcode of the second cast constant expression46ConstantExpr *Op, ///< the first cast constant expression47Type *DstTy ///< destination type of the first cast48) {49assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");50assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");51assert(CastInst::isCast(opc) && "Invalid cast opcode");5253// The types and opcodes for the two Cast constant expressions54Type *SrcTy = Op->getOperand(0)->getType();55Type *MidTy = Op->getType();56Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());57Instruction::CastOps secondOp = Instruction::CastOps(opc);5859// Assume that pointers are never more than 64 bits wide, and only use this60// for the middle type. Otherwise we could end up folding away illegal61// bitcasts between address spaces with different sizes.62IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());6364// Let CastInst::isEliminableCastPair do the heavy lifting.65return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,66nullptr, FakeIntPtrTy, nullptr);67}6869static Constant *FoldBitCast(Constant *V, Type *DestTy) {70Type *SrcTy = V->getType();71if (SrcTy == DestTy)72return V; // no-op cast7374// Handle casts from one vector constant to another. We know that the src75// and dest type have the same size (otherwise its an illegal cast).76if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {77if (V->isAllOnesValue())78return Constant::getAllOnesValue(DestTy);7980// Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts81// This allows for other simplifications (although some of them82// can only be handled by Analysis/ConstantFolding.cpp).83if (isa<ConstantInt>(V) || isa<ConstantFP>(V))84return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);85return nullptr;86}8788// Handle integral constant input.89if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {90// See note below regarding the PPC_FP128 restriction.91if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())92return ConstantFP::get(DestTy->getContext(),93APFloat(DestTy->getFltSemantics(),94CI->getValue()));9596// Otherwise, can't fold this (vector?)97return nullptr;98}99100// Handle ConstantFP input: FP -> Integral.101if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {102// PPC_FP128 is really the sum of two consecutive doubles, where the first103// double is always stored first in memory, regardless of the target104// endianness. The memory layout of i128, however, depends on the target105// endianness, and so we can't fold this without target endianness106// information. This should instead be handled by107// Analysis/ConstantFolding.cpp108if (FP->getType()->isPPC_FP128Ty())109return nullptr;110111// Make sure dest type is compatible with the folded integer constant.112if (!DestTy->isIntegerTy())113return nullptr;114115return ConstantInt::get(FP->getContext(),116FP->getValueAPF().bitcastToAPInt());117}118119return nullptr;120}121122static Constant *foldMaybeUndesirableCast(unsigned opc, Constant *V,123Type *DestTy) {124return ConstantExpr::isDesirableCastOp(opc)125? ConstantExpr::getCast(opc, V, DestTy)126: ConstantFoldCastInstruction(opc, V, DestTy);127}128129Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,130Type *DestTy) {131if (isa<PoisonValue>(V))132return PoisonValue::get(DestTy);133134if (isa<UndefValue>(V)) {135// zext(undef) = 0, because the top bits will be zero.136// sext(undef) = 0, because the top bits will all be the same.137// [us]itofp(undef) = 0, because the result value is bounded.138if (opc == Instruction::ZExt || opc == Instruction::SExt ||139opc == Instruction::UIToFP || opc == Instruction::SIToFP)140return Constant::getNullValue(DestTy);141return UndefValue::get(DestTy);142}143144if (V->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy() &&145opc != Instruction::AddrSpaceCast)146return Constant::getNullValue(DestTy);147148// If the cast operand is a constant expression, there's a few things we can149// do to try to simplify it.150if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {151if (CE->isCast()) {152// Try hard to fold cast of cast because they are often eliminable.153if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))154return foldMaybeUndesirableCast(newOpc, CE->getOperand(0), DestTy);155}156}157158// If the cast operand is a constant vector, perform the cast by159// operating on each element. In the cast of bitcasts, the element160// count may be mismatched; don't attempt to handle that here.161if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&162DestTy->isVectorTy() &&163cast<FixedVectorType>(DestTy)->getNumElements() ==164cast<FixedVectorType>(V->getType())->getNumElements()) {165VectorType *DestVecTy = cast<VectorType>(DestTy);166Type *DstEltTy = DestVecTy->getElementType();167// Fast path for splatted constants.168if (Constant *Splat = V->getSplatValue()) {169Constant *Res = foldMaybeUndesirableCast(opc, Splat, DstEltTy);170if (!Res)171return nullptr;172return ConstantVector::getSplat(173cast<VectorType>(DestTy)->getElementCount(), Res);174}175SmallVector<Constant *, 16> res;176Type *Ty = IntegerType::get(V->getContext(), 32);177for (unsigned i = 0,178e = cast<FixedVectorType>(V->getType())->getNumElements();179i != e; ++i) {180Constant *C = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));181Constant *Casted = foldMaybeUndesirableCast(opc, C, DstEltTy);182if (!Casted)183return nullptr;184res.push_back(Casted);185}186return ConstantVector::get(res);187}188189// We actually have to do a cast now. Perform the cast according to the190// opcode specified.191switch (opc) {192default:193llvm_unreachable("Failed to cast constant expression");194case Instruction::FPTrunc:195case Instruction::FPExt:196if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {197bool ignored;198APFloat Val = FPC->getValueAPF();199Val.convert(DestTy->getFltSemantics(), APFloat::rmNearestTiesToEven,200&ignored);201return ConstantFP::get(V->getContext(), Val);202}203return nullptr; // Can't fold.204case Instruction::FPToUI:205case Instruction::FPToSI:206if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {207const APFloat &V = FPC->getValueAPF();208bool ignored;209uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();210APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI);211if (APFloat::opInvalidOp ==212V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) {213// Undefined behavior invoked - the destination type can't represent214// the input constant.215return PoisonValue::get(DestTy);216}217return ConstantInt::get(FPC->getContext(), IntVal);218}219return nullptr; // Can't fold.220case Instruction::UIToFP:221case Instruction::SIToFP:222if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {223const APInt &api = CI->getValue();224APFloat apf(DestTy->getFltSemantics(),225APInt::getZero(DestTy->getPrimitiveSizeInBits()));226apf.convertFromAPInt(api, opc==Instruction::SIToFP,227APFloat::rmNearestTiesToEven);228return ConstantFP::get(V->getContext(), apf);229}230return nullptr;231case Instruction::ZExt:232if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {233uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();234return ConstantInt::get(V->getContext(),235CI->getValue().zext(BitWidth));236}237return nullptr;238case Instruction::SExt:239if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {240uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();241return ConstantInt::get(V->getContext(),242CI->getValue().sext(BitWidth));243}244return nullptr;245case Instruction::Trunc: {246if (V->getType()->isVectorTy())247return nullptr;248249uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();250if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {251return ConstantInt::get(V->getContext(),252CI->getValue().trunc(DestBitWidth));253}254255return nullptr;256}257case Instruction::BitCast:258return FoldBitCast(V, DestTy);259case Instruction::AddrSpaceCast:260case Instruction::IntToPtr:261case Instruction::PtrToInt:262return nullptr;263}264}265266Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,267Constant *V1, Constant *V2) {268// Check for i1 and vector true/false conditions.269if (Cond->isNullValue()) return V2;270if (Cond->isAllOnesValue()) return V1;271272// If the condition is a vector constant, fold the result elementwise.273if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {274auto *V1VTy = CondV->getType();275SmallVector<Constant*, 16> Result;276Type *Ty = IntegerType::get(CondV->getContext(), 32);277for (unsigned i = 0, e = V1VTy->getNumElements(); i != e; ++i) {278Constant *V;279Constant *V1Element = ConstantExpr::getExtractElement(V1,280ConstantInt::get(Ty, i));281Constant *V2Element = ConstantExpr::getExtractElement(V2,282ConstantInt::get(Ty, i));283auto *Cond = cast<Constant>(CondV->getOperand(i));284if (isa<PoisonValue>(Cond)) {285V = PoisonValue::get(V1Element->getType());286} else if (V1Element == V2Element) {287V = V1Element;288} else if (isa<UndefValue>(Cond)) {289V = isa<UndefValue>(V1Element) ? V1Element : V2Element;290} else {291if (!isa<ConstantInt>(Cond)) break;292V = Cond->isNullValue() ? V2Element : V1Element;293}294Result.push_back(V);295}296297// If we were able to build the vector, return it.298if (Result.size() == V1VTy->getNumElements())299return ConstantVector::get(Result);300}301302if (isa<PoisonValue>(Cond))303return PoisonValue::get(V1->getType());304305if (isa<UndefValue>(Cond)) {306if (isa<UndefValue>(V1)) return V1;307return V2;308}309310if (V1 == V2) return V1;311312if (isa<PoisonValue>(V1))313return V2;314if (isa<PoisonValue>(V2))315return V1;316317// If the true or false value is undef, we can fold to the other value as318// long as the other value isn't poison.319auto NotPoison = [](Constant *C) {320if (isa<PoisonValue>(C))321return false;322323// TODO: We can analyze ConstExpr by opcode to determine if there is any324// possibility of poison.325if (isa<ConstantExpr>(C))326return false;327328if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(C) ||329isa<ConstantPointerNull>(C) || isa<Function>(C))330return true;331332if (C->getType()->isVectorTy())333return !C->containsPoisonElement() && !C->containsConstantExpression();334335// TODO: Recursively analyze aggregates or other constants.336return false;337};338if (isa<UndefValue>(V1) && NotPoison(V2)) return V2;339if (isa<UndefValue>(V2) && NotPoison(V1)) return V1;340341return nullptr;342}343344Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,345Constant *Idx) {346auto *ValVTy = cast<VectorType>(Val->getType());347348// extractelt poison, C -> poison349// extractelt C, undef -> poison350if (isa<PoisonValue>(Val) || isa<UndefValue>(Idx))351return PoisonValue::get(ValVTy->getElementType());352353// extractelt undef, C -> undef354if (isa<UndefValue>(Val))355return UndefValue::get(ValVTy->getElementType());356357auto *CIdx = dyn_cast<ConstantInt>(Idx);358if (!CIdx)359return nullptr;360361if (auto *ValFVTy = dyn_cast<FixedVectorType>(Val->getType())) {362// ee({w,x,y,z}, wrong_value) -> poison363if (CIdx->uge(ValFVTy->getNumElements()))364return PoisonValue::get(ValFVTy->getElementType());365}366367// ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)368if (auto *CE = dyn_cast<ConstantExpr>(Val)) {369if (auto *GEP = dyn_cast<GEPOperator>(CE)) {370SmallVector<Constant *, 8> Ops;371Ops.reserve(CE->getNumOperands());372for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {373Constant *Op = CE->getOperand(i);374if (Op->getType()->isVectorTy()) {375Constant *ScalarOp = ConstantExpr::getExtractElement(Op, Idx);376if (!ScalarOp)377return nullptr;378Ops.push_back(ScalarOp);379} else380Ops.push_back(Op);381}382return CE->getWithOperands(Ops, ValVTy->getElementType(), false,383GEP->getSourceElementType());384} else if (CE->getOpcode() == Instruction::InsertElement) {385if (const auto *IEIdx = dyn_cast<ConstantInt>(CE->getOperand(2))) {386if (APSInt::isSameValue(APSInt(IEIdx->getValue()),387APSInt(CIdx->getValue()))) {388return CE->getOperand(1);389} else {390return ConstantExpr::getExtractElement(CE->getOperand(0), CIdx);391}392}393}394}395396if (Constant *C = Val->getAggregateElement(CIdx))397return C;398399// Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x400if (CIdx->getValue().ult(ValVTy->getElementCount().getKnownMinValue())) {401if (Constant *SplatVal = Val->getSplatValue())402return SplatVal;403}404405return nullptr;406}407408Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,409Constant *Elt,410Constant *Idx) {411if (isa<UndefValue>(Idx))412return PoisonValue::get(Val->getType());413414// Inserting null into all zeros is still all zeros.415// TODO: This is true for undef and poison splats too.416if (isa<ConstantAggregateZero>(Val) && Elt->isNullValue())417return Val;418419ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);420if (!CIdx) return nullptr;421422// Do not iterate on scalable vector. The num of elements is unknown at423// compile-time.424if (isa<ScalableVectorType>(Val->getType()))425return nullptr;426427auto *ValTy = cast<FixedVectorType>(Val->getType());428429unsigned NumElts = ValTy->getNumElements();430if (CIdx->uge(NumElts))431return PoisonValue::get(Val->getType());432433SmallVector<Constant*, 16> Result;434Result.reserve(NumElts);435auto *Ty = Type::getInt32Ty(Val->getContext());436uint64_t IdxVal = CIdx->getZExtValue();437for (unsigned i = 0; i != NumElts; ++i) {438if (i == IdxVal) {439Result.push_back(Elt);440continue;441}442443Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));444Result.push_back(C);445}446447return ConstantVector::get(Result);448}449450Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2,451ArrayRef<int> Mask) {452auto *V1VTy = cast<VectorType>(V1->getType());453unsigned MaskNumElts = Mask.size();454auto MaskEltCount =455ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy));456Type *EltTy = V1VTy->getElementType();457458// Poison shuffle mask -> poison value.459if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {460return PoisonValue::get(VectorType::get(EltTy, MaskEltCount));461}462463// If the mask is all zeros this is a splat, no need to go through all464// elements.465if (all_of(Mask, [](int Elt) { return Elt == 0; })) {466Type *Ty = IntegerType::get(V1->getContext(), 32);467Constant *Elt =468ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, 0));469470if (Elt->isNullValue()) {471auto *VTy = VectorType::get(EltTy, MaskEltCount);472return ConstantAggregateZero::get(VTy);473} else if (!MaskEltCount.isScalable())474return ConstantVector::getSplat(MaskEltCount, Elt);475}476477// Do not iterate on scalable vector. The num of elements is unknown at478// compile-time.479if (isa<ScalableVectorType>(V1VTy))480return nullptr;481482unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();483484// Loop over the shuffle mask, evaluating each element.485SmallVector<Constant*, 32> Result;486for (unsigned i = 0; i != MaskNumElts; ++i) {487int Elt = Mask[i];488if (Elt == -1) {489Result.push_back(UndefValue::get(EltTy));490continue;491}492Constant *InElt;493if (unsigned(Elt) >= SrcNumElts*2)494InElt = UndefValue::get(EltTy);495else if (unsigned(Elt) >= SrcNumElts) {496Type *Ty = IntegerType::get(V2->getContext(), 32);497InElt =498ConstantExpr::getExtractElement(V2,499ConstantInt::get(Ty, Elt - SrcNumElts));500} else {501Type *Ty = IntegerType::get(V1->getContext(), 32);502InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));503}504Result.push_back(InElt);505}506507return ConstantVector::get(Result);508}509510Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,511ArrayRef<unsigned> Idxs) {512// Base case: no indices, so return the entire value.513if (Idxs.empty())514return Agg;515516if (Constant *C = Agg->getAggregateElement(Idxs[0]))517return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));518519return nullptr;520}521522Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,523Constant *Val,524ArrayRef<unsigned> Idxs) {525// Base case: no indices, so replace the entire value.526if (Idxs.empty())527return Val;528529unsigned NumElts;530if (StructType *ST = dyn_cast<StructType>(Agg->getType()))531NumElts = ST->getNumElements();532else533NumElts = cast<ArrayType>(Agg->getType())->getNumElements();534535SmallVector<Constant*, 32> Result;536for (unsigned i = 0; i != NumElts; ++i) {537Constant *C = Agg->getAggregateElement(i);538if (!C) return nullptr;539540if (Idxs[0] == i)541C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));542543Result.push_back(C);544}545546if (StructType *ST = dyn_cast<StructType>(Agg->getType()))547return ConstantStruct::get(ST, Result);548return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result);549}550551Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) {552assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");553554// Handle scalar UndefValue and scalable vector UndefValue. Fixed-length555// vectors are always evaluated per element.556bool IsScalableVector = isa<ScalableVectorType>(C->getType());557bool HasScalarUndefOrScalableVectorUndef =558(!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C);559560if (HasScalarUndefOrScalableVectorUndef) {561switch (static_cast<Instruction::UnaryOps>(Opcode)) {562case Instruction::FNeg:563return C; // -undef -> undef564case Instruction::UnaryOpsEnd:565llvm_unreachable("Invalid UnaryOp");566}567}568569// Constant should not be UndefValue, unless these are vector constants.570assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue");571// We only have FP UnaryOps right now.572assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");573574if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {575const APFloat &CV = CFP->getValueAPF();576switch (Opcode) {577default:578break;579case Instruction::FNeg:580return ConstantFP::get(C->getContext(), neg(CV));581}582} else if (auto *VTy = dyn_cast<FixedVectorType>(C->getType())) {583584Type *Ty = IntegerType::get(VTy->getContext(), 32);585// Fast path for splatted constants.586if (Constant *Splat = C->getSplatValue())587if (Constant *Elt = ConstantFoldUnaryInstruction(Opcode, Splat))588return ConstantVector::getSplat(VTy->getElementCount(), Elt);589590// Fold each element and create a vector constant from those constants.591SmallVector<Constant *, 16> Result;592for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {593Constant *ExtractIdx = ConstantInt::get(Ty, i);594Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);595Constant *Res = ConstantFoldUnaryInstruction(Opcode, Elt);596if (!Res)597return nullptr;598Result.push_back(Res);599}600601return ConstantVector::get(Result);602}603604// We don't know how to fold this.605return nullptr;606}607608Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1,609Constant *C2) {610assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");611612// Simplify BinOps with their identity values first. They are no-ops and we613// can always return the other value, including undef or poison values.614if (Constant *Identity = ConstantExpr::getBinOpIdentity(615Opcode, C1->getType(), /*AllowRHSIdentity*/ false)) {616if (C1 == Identity)617return C2;618if (C2 == Identity)619return C1;620} else if (Constant *Identity = ConstantExpr::getBinOpIdentity(621Opcode, C1->getType(), /*AllowRHSIdentity*/ true)) {622if (C2 == Identity)623return C1;624}625626// Binary operations propagate poison.627if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))628return PoisonValue::get(C1->getType());629630// Handle scalar UndefValue and scalable vector UndefValue. Fixed-length631// vectors are always evaluated per element.632bool IsScalableVector = isa<ScalableVectorType>(C1->getType());633bool HasScalarUndefOrScalableVectorUndef =634(!C1->getType()->isVectorTy() || IsScalableVector) &&635(isa<UndefValue>(C1) || isa<UndefValue>(C2));636if (HasScalarUndefOrScalableVectorUndef) {637switch (static_cast<Instruction::BinaryOps>(Opcode)) {638case Instruction::Xor:639if (isa<UndefValue>(C1) && isa<UndefValue>(C2))640// Handle undef ^ undef -> 0 special case. This is a common641// idiom (misuse).642return Constant::getNullValue(C1->getType());643[[fallthrough]];644case Instruction::Add:645case Instruction::Sub:646return UndefValue::get(C1->getType());647case Instruction::And:648if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef649return C1;650return Constant::getNullValue(C1->getType()); // undef & X -> 0651case Instruction::Mul: {652// undef * undef -> undef653if (isa<UndefValue>(C1) && isa<UndefValue>(C2))654return C1;655const APInt *CV;656// X * undef -> undef if X is odd657if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))658if ((*CV)[0])659return UndefValue::get(C1->getType());660661// X * undef -> 0 otherwise662return Constant::getNullValue(C1->getType());663}664case Instruction::SDiv:665case Instruction::UDiv:666// X / undef -> poison667// X / 0 -> poison668if (match(C2, m_CombineOr(m_Undef(), m_Zero())))669return PoisonValue::get(C2->getType());670// undef / X -> 0 otherwise671return Constant::getNullValue(C1->getType());672case Instruction::URem:673case Instruction::SRem:674// X % undef -> poison675// X % 0 -> poison676if (match(C2, m_CombineOr(m_Undef(), m_Zero())))677return PoisonValue::get(C2->getType());678// undef % X -> 0 otherwise679return Constant::getNullValue(C1->getType());680case Instruction::Or: // X | undef -> -1681if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef682return C1;683return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0684case Instruction::LShr:685// X >>l undef -> poison686if (isa<UndefValue>(C2))687return PoisonValue::get(C2->getType());688// undef >>l X -> 0689return Constant::getNullValue(C1->getType());690case Instruction::AShr:691// X >>a undef -> poison692if (isa<UndefValue>(C2))693return PoisonValue::get(C2->getType());694// TODO: undef >>a X -> poison if the shift is exact695// undef >>a X -> 0696return Constant::getNullValue(C1->getType());697case Instruction::Shl:698// X << undef -> undef699if (isa<UndefValue>(C2))700return PoisonValue::get(C2->getType());701// undef << X -> 0702return Constant::getNullValue(C1->getType());703case Instruction::FSub:704// -0.0 - undef --> undef (consistent with "fneg undef")705if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2))706return C2;707[[fallthrough]];708case Instruction::FAdd:709case Instruction::FMul:710case Instruction::FDiv:711case Instruction::FRem:712// [any flop] undef, undef -> undef713if (isa<UndefValue>(C1) && isa<UndefValue>(C2))714return C1;715// [any flop] C, undef -> NaN716// [any flop] undef, C -> NaN717// We could potentially specialize NaN/Inf constants vs. 'normal'718// constants (possibly differently depending on opcode and operand). This719// would allow returning undef sometimes. But it is always safe to fold to720// NaN because we can choose the undef operand as NaN, and any FP opcode721// with a NaN operand will propagate NaN.722return ConstantFP::getNaN(C1->getType());723case Instruction::BinaryOpsEnd:724llvm_unreachable("Invalid BinaryOp");725}726}727728// Neither constant should be UndefValue, unless these are vector constants.729assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue");730731// Handle simplifications when the RHS is a constant int.732if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {733switch (Opcode) {734case Instruction::Mul:735if (CI2->isZero())736return C2; // X * 0 == 0737break;738case Instruction::UDiv:739case Instruction::SDiv:740if (CI2->isZero())741return PoisonValue::get(CI2->getType()); // X / 0 == poison742break;743case Instruction::URem:744case Instruction::SRem:745if (CI2->isOne())746return Constant::getNullValue(CI2->getType()); // X % 1 == 0747if (CI2->isZero())748return PoisonValue::get(CI2->getType()); // X % 0 == poison749break;750case Instruction::And:751if (CI2->isZero())752return C2; // X & 0 == 0753754if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {755// If and'ing the address of a global with a constant, fold it.756if (CE1->getOpcode() == Instruction::PtrToInt &&757isa<GlobalValue>(CE1->getOperand(0))) {758GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));759760Align GVAlign; // defaults to 1761762if (Module *TheModule = GV->getParent()) {763const DataLayout &DL = TheModule->getDataLayout();764GVAlign = GV->getPointerAlignment(DL);765766// If the function alignment is not specified then assume that it767// is 4.768// This is dangerous; on x86, the alignment of the pointer769// corresponds to the alignment of the function, but might be less770// than 4 if it isn't explicitly specified.771// However, a fix for this behaviour was reverted because it772// increased code size (see https://reviews.llvm.org/D55115)773// FIXME: This code should be deleted once existing targets have774// appropriate defaults775if (isa<Function>(GV) && !DL.getFunctionPtrAlign())776GVAlign = Align(4);777} else if (isa<GlobalVariable>(GV)) {778GVAlign = cast<GlobalVariable>(GV)->getAlign().valueOrOne();779}780781if (GVAlign > 1) {782unsigned DstWidth = CI2->getBitWidth();783unsigned SrcWidth = std::min(DstWidth, Log2(GVAlign));784APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));785786// If checking bits we know are clear, return zero.787if ((CI2->getValue() & BitsNotSet) == CI2->getValue())788return Constant::getNullValue(CI2->getType());789}790}791}792break;793case Instruction::Or:794if (CI2->isMinusOne())795return C2; // X | -1 == -1796break;797}798} else if (isa<ConstantInt>(C1)) {799// If C1 is a ConstantInt and C2 is not, swap the operands.800if (Instruction::isCommutative(Opcode))801return ConstantExpr::isDesirableBinOp(Opcode)802? ConstantExpr::get(Opcode, C2, C1)803: ConstantFoldBinaryInstruction(Opcode, C2, C1);804}805806if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {807if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {808const APInt &C1V = CI1->getValue();809const APInt &C2V = CI2->getValue();810switch (Opcode) {811default:812break;813case Instruction::Add:814return ConstantInt::get(CI1->getContext(), C1V + C2V);815case Instruction::Sub:816return ConstantInt::get(CI1->getContext(), C1V - C2V);817case Instruction::Mul:818return ConstantInt::get(CI1->getContext(), C1V * C2V);819case Instruction::UDiv:820assert(!CI2->isZero() && "Div by zero handled above");821return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));822case Instruction::SDiv:823assert(!CI2->isZero() && "Div by zero handled above");824if (C2V.isAllOnes() && C1V.isMinSignedValue())825return PoisonValue::get(CI1->getType()); // MIN_INT / -1 -> poison826return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));827case Instruction::URem:828assert(!CI2->isZero() && "Div by zero handled above");829return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));830case Instruction::SRem:831assert(!CI2->isZero() && "Div by zero handled above");832if (C2V.isAllOnes() && C1V.isMinSignedValue())833return PoisonValue::get(CI1->getType()); // MIN_INT % -1 -> poison834return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));835case Instruction::And:836return ConstantInt::get(CI1->getContext(), C1V & C2V);837case Instruction::Or:838return ConstantInt::get(CI1->getContext(), C1V | C2V);839case Instruction::Xor:840return ConstantInt::get(CI1->getContext(), C1V ^ C2V);841case Instruction::Shl:842if (C2V.ult(C1V.getBitWidth()))843return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));844return PoisonValue::get(C1->getType()); // too big shift is poison845case Instruction::LShr:846if (C2V.ult(C1V.getBitWidth()))847return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));848return PoisonValue::get(C1->getType()); // too big shift is poison849case Instruction::AShr:850if (C2V.ult(C1V.getBitWidth()))851return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));852return PoisonValue::get(C1->getType()); // too big shift is poison853}854}855856switch (Opcode) {857case Instruction::SDiv:858case Instruction::UDiv:859case Instruction::URem:860case Instruction::SRem:861case Instruction::LShr:862case Instruction::AShr:863case Instruction::Shl:864if (CI1->isZero()) return C1;865break;866default:867break;868}869} else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {870if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {871const APFloat &C1V = CFP1->getValueAPF();872const APFloat &C2V = CFP2->getValueAPF();873APFloat C3V = C1V; // copy for modification874switch (Opcode) {875default:876break;877case Instruction::FAdd:878(void)C3V.add(C2V, APFloat::rmNearestTiesToEven);879return ConstantFP::get(C1->getContext(), C3V);880case Instruction::FSub:881(void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);882return ConstantFP::get(C1->getContext(), C3V);883case Instruction::FMul:884(void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);885return ConstantFP::get(C1->getContext(), C3V);886case Instruction::FDiv:887(void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);888return ConstantFP::get(C1->getContext(), C3V);889case Instruction::FRem:890(void)C3V.mod(C2V);891return ConstantFP::get(C1->getContext(), C3V);892}893}894} else if (auto *VTy = dyn_cast<VectorType>(C1->getType())) {895// Fast path for splatted constants.896if (Constant *C2Splat = C2->getSplatValue()) {897if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue())898return PoisonValue::get(VTy);899if (Constant *C1Splat = C1->getSplatValue()) {900Constant *Res =901ConstantExpr::isDesirableBinOp(Opcode)902? ConstantExpr::get(Opcode, C1Splat, C2Splat)903: ConstantFoldBinaryInstruction(Opcode, C1Splat, C2Splat);904if (!Res)905return nullptr;906return ConstantVector::getSplat(VTy->getElementCount(), Res);907}908}909910if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {911// Fold each element and create a vector constant from those constants.912SmallVector<Constant*, 16> Result;913Type *Ty = IntegerType::get(FVTy->getContext(), 32);914for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {915Constant *ExtractIdx = ConstantInt::get(Ty, i);916Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);917Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);918919// If any element of a divisor vector is zero, the whole op is poison.920if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())921return PoisonValue::get(VTy);922923Constant *Res = ConstantExpr::isDesirableBinOp(Opcode)924? ConstantExpr::get(Opcode, LHS, RHS)925: ConstantFoldBinaryInstruction(Opcode, LHS, RHS);926if (!Res)927return nullptr;928Result.push_back(Res);929}930931return ConstantVector::get(Result);932}933}934935if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {936// There are many possible foldings we could do here. We should probably937// at least fold add of a pointer with an integer into the appropriate938// getelementptr. This will improve alias analysis a bit.939940// Given ((a + b) + c), if (b + c) folds to something interesting, return941// (a + (b + c)).942if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {943Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);944if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)945return ConstantExpr::get(Opcode, CE1->getOperand(0), T);946}947} else if (isa<ConstantExpr>(C2)) {948// If C2 is a constant expr and C1 isn't, flop them around and fold the949// other way if possible.950if (Instruction::isCommutative(Opcode))951return ConstantFoldBinaryInstruction(Opcode, C2, C1);952}953954// i1 can be simplified in many cases.955if (C1->getType()->isIntegerTy(1)) {956switch (Opcode) {957case Instruction::Add:958case Instruction::Sub:959return ConstantExpr::getXor(C1, C2);960case Instruction::Shl:961case Instruction::LShr:962case Instruction::AShr:963// We can assume that C2 == 0. If it were one the result would be964// undefined because the shift value is as large as the bitwidth.965return C1;966case Instruction::SDiv:967case Instruction::UDiv:968// We can assume that C2 == 1. If it were zero the result would be969// undefined through division by zero.970return C1;971case Instruction::URem:972case Instruction::SRem:973// We can assume that C2 == 1. If it were zero the result would be974// undefined through division by zero.975return ConstantInt::getFalse(C1->getContext());976default:977break;978}979}980981// We don't know how to fold this.982return nullptr;983}984985static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,986const GlobalValue *GV2) {987auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {988if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())989return true;990if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {991Type *Ty = GVar->getValueType();992// A global with opaque type might end up being zero sized.993if (!Ty->isSized())994return true;995// A global with an empty type might lie at the address of any other996// global.997if (Ty->isEmptyTy())998return true;999}1000return false;1001};1002// Don't try to decide equality of aliases.1003if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))1004if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))1005return ICmpInst::ICMP_NE;1006return ICmpInst::BAD_ICMP_PREDICATE;1007}10081009/// This function determines if there is anything we can decide about the two1010/// constants provided. This doesn't need to handle simple things like integer1011/// comparisons, but should instead handle ConstantExprs and GlobalValues.1012/// If we can determine that the two constants have a particular relation to1013/// each other, we should return the corresponding ICmp predicate, otherwise1014/// return ICmpInst::BAD_ICMP_PREDICATE.1015static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2) {1016assert(V1->getType() == V2->getType() &&1017"Cannot compare different types of values!");1018if (V1 == V2) return ICmpInst::ICMP_EQ;10191020// The following folds only apply to pointers.1021if (!V1->getType()->isPointerTy())1022return ICmpInst::BAD_ICMP_PREDICATE;10231024// To simplify this code we canonicalize the relation so that the first1025// operand is always the most "complex" of the two. We consider simple1026// constants (like ConstantPointerNull) to be the simplest, followed by1027// BlockAddress, GlobalValues, and ConstantExpr's (the most complex).1028auto GetComplexity = [](Constant *V) {1029if (isa<ConstantExpr>(V))1030return 3;1031if (isa<GlobalValue>(V))1032return 2;1033if (isa<BlockAddress>(V))1034return 1;1035return 0;1036};1037if (GetComplexity(V1) < GetComplexity(V2)) {1038ICmpInst::Predicate SwappedRelation = evaluateICmpRelation(V2, V1);1039if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)1040return ICmpInst::getSwappedPredicate(SwappedRelation);1041return ICmpInst::BAD_ICMP_PREDICATE;1042}10431044if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {1045// Now we know that the RHS is a BlockAddress or simple constant.1046if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {1047// Block address in another function can't equal this one, but block1048// addresses in the current function might be the same if blocks are1049// empty.1050if (BA2->getFunction() != BA->getFunction())1051return ICmpInst::ICMP_NE;1052} else if (isa<ConstantPointerNull>(V2)) {1053return ICmpInst::ICMP_NE;1054}1055} else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {1056// Now we know that the RHS is a GlobalValue, BlockAddress or simple1057// constant.1058if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {1059return areGlobalsPotentiallyEqual(GV, GV2);1060} else if (isa<BlockAddress>(V2)) {1061return ICmpInst::ICMP_NE; // Globals never equal labels.1062} else if (isa<ConstantPointerNull>(V2)) {1063// GlobalVals can never be null unless they have external weak linkage.1064// We don't try to evaluate aliases here.1065// NOTE: We should not be doing this constant folding if null pointer1066// is considered valid for the function. But currently there is no way to1067// query it from the Constant type.1068if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&1069!NullPointerIsDefined(nullptr /* F */,1070GV->getType()->getAddressSpace()))1071return ICmpInst::ICMP_UGT;1072}1073} else if (auto *CE1 = dyn_cast<ConstantExpr>(V1)) {1074// Ok, the LHS is known to be a constantexpr. The RHS can be any of a1075// constantexpr, a global, block address, or a simple constant.1076Constant *CE1Op0 = CE1->getOperand(0);10771078switch (CE1->getOpcode()) {1079case Instruction::GetElementPtr: {1080GEPOperator *CE1GEP = cast<GEPOperator>(CE1);1081// Ok, since this is a getelementptr, we know that the constant has a1082// pointer type. Check the various cases.1083if (isa<ConstantPointerNull>(V2)) {1084// If we are comparing a GEP to a null pointer, check to see if the base1085// of the GEP equals the null pointer.1086if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {1087// If its not weak linkage, the GVal must have a non-zero address1088// so the result is greater-than1089if (!GV->hasExternalWeakLinkage() && CE1GEP->isInBounds())1090return ICmpInst::ICMP_UGT;1091}1092} else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {1093if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {1094if (GV != GV2) {1095if (CE1GEP->hasAllZeroIndices())1096return areGlobalsPotentiallyEqual(GV, GV2);1097return ICmpInst::BAD_ICMP_PREDICATE;1098}1099}1100} else if (const auto *CE2GEP = dyn_cast<GEPOperator>(V2)) {1101// By far the most common case to handle is when the base pointers are1102// obviously to the same global.1103const Constant *CE2Op0 = cast<Constant>(CE2GEP->getPointerOperand());1104if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {1105// Don't know relative ordering, but check for inequality.1106if (CE1Op0 != CE2Op0) {1107if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())1108return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),1109cast<GlobalValue>(CE2Op0));1110return ICmpInst::BAD_ICMP_PREDICATE;1111}1112}1113}1114break;1115}1116default:1117break;1118}1119}11201121return ICmpInst::BAD_ICMP_PREDICATE;1122}11231124Constant *llvm::ConstantFoldCompareInstruction(CmpInst::Predicate Predicate,1125Constant *C1, Constant *C2) {1126Type *ResultTy;1127if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))1128ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),1129VT->getElementCount());1130else1131ResultTy = Type::getInt1Ty(C1->getContext());11321133// Fold FCMP_FALSE/FCMP_TRUE unconditionally.1134if (Predicate == FCmpInst::FCMP_FALSE)1135return Constant::getNullValue(ResultTy);11361137if (Predicate == FCmpInst::FCMP_TRUE)1138return Constant::getAllOnesValue(ResultTy);11391140// Handle some degenerate cases first1141if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))1142return PoisonValue::get(ResultTy);11431144if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {1145bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);1146// For EQ and NE, we can always pick a value for the undef to make the1147// predicate pass or fail, so we can return undef.1148// Also, if both operands are undef, we can return undef for int comparison.1149if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))1150return UndefValue::get(ResultTy);11511152// Otherwise, for integer compare, pick the same value as the non-undef1153// operand, and fold it to true or false.1154if (isIntegerPredicate)1155return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));11561157// Choosing NaN for the undef will always make unordered comparison succeed1158// and ordered comparison fails.1159return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));1160}11611162if (C2->isNullValue()) {1163// The caller is expected to commute the operands if the constant expression1164// is C2.1165// C1 >= 0 --> true1166if (Predicate == ICmpInst::ICMP_UGE)1167return Constant::getAllOnesValue(ResultTy);1168// C1 < 0 --> false1169if (Predicate == ICmpInst::ICMP_ULT)1170return Constant::getNullValue(ResultTy);1171}11721173// If the comparison is a comparison between two i1's, simplify it.1174if (C1->getType()->isIntegerTy(1)) {1175switch (Predicate) {1176case ICmpInst::ICMP_EQ:1177if (isa<ConstantInt>(C2))1178return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));1179return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);1180case ICmpInst::ICMP_NE:1181return ConstantExpr::getXor(C1, C2);1182default:1183break;1184}1185}11861187if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {1188const APInt &V1 = cast<ConstantInt>(C1)->getValue();1189const APInt &V2 = cast<ConstantInt>(C2)->getValue();1190return ConstantInt::get(ResultTy, ICmpInst::compare(V1, V2, Predicate));1191} else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {1192const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();1193const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();1194return ConstantInt::get(ResultTy, FCmpInst::compare(C1V, C2V, Predicate));1195} else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) {11961197// Fast path for splatted constants.1198if (Constant *C1Splat = C1->getSplatValue())1199if (Constant *C2Splat = C2->getSplatValue())1200if (Constant *Elt =1201ConstantFoldCompareInstruction(Predicate, C1Splat, C2Splat))1202return ConstantVector::getSplat(C1VTy->getElementCount(), Elt);12031204// Do not iterate on scalable vector. The number of elements is unknown at1205// compile-time.1206if (isa<ScalableVectorType>(C1VTy))1207return nullptr;12081209// If we can constant fold the comparison of each element, constant fold1210// the whole vector comparison.1211SmallVector<Constant*, 4> ResElts;1212Type *Ty = IntegerType::get(C1->getContext(), 32);1213// Compare the elements, producing an i1 result or constant expr.1214for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();1215I != E; ++I) {1216Constant *C1E =1217ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, I));1218Constant *C2E =1219ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, I));1220Constant *Elt = ConstantFoldCompareInstruction(Predicate, C1E, C2E);1221if (!Elt)1222return nullptr;12231224ResElts.push_back(Elt);1225}12261227return ConstantVector::get(ResElts);1228}12291230if (C1->getType()->isFPOrFPVectorTy()) {1231if (C1 == C2) {1232// We know that C1 == C2 || isUnordered(C1, C2).1233if (Predicate == FCmpInst::FCMP_ONE)1234return ConstantInt::getFalse(ResultTy);1235else if (Predicate == FCmpInst::FCMP_UEQ)1236return ConstantInt::getTrue(ResultTy);1237}1238} else {1239// Evaluate the relation between the two constants, per the predicate.1240int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.1241switch (evaluateICmpRelation(C1, C2)) {1242default: llvm_unreachable("Unknown relational!");1243case ICmpInst::BAD_ICMP_PREDICATE:1244break; // Couldn't determine anything about these constants.1245case ICmpInst::ICMP_EQ: // We know the constants are equal!1246// If we know the constants are equal, we can decide the result of this1247// computation precisely.1248Result = ICmpInst::isTrueWhenEqual(Predicate);1249break;1250case ICmpInst::ICMP_ULT:1251switch (Predicate) {1252case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:1253Result = 1; break;1254case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:1255Result = 0; break;1256default:1257break;1258}1259break;1260case ICmpInst::ICMP_SLT:1261switch (Predicate) {1262case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:1263Result = 1; break;1264case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:1265Result = 0; break;1266default:1267break;1268}1269break;1270case ICmpInst::ICMP_UGT:1271switch (Predicate) {1272case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:1273Result = 1; break;1274case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:1275Result = 0; break;1276default:1277break;1278}1279break;1280case ICmpInst::ICMP_SGT:1281switch (Predicate) {1282case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:1283Result = 1; break;1284case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:1285Result = 0; break;1286default:1287break;1288}1289break;1290case ICmpInst::ICMP_ULE:1291if (Predicate == ICmpInst::ICMP_UGT)1292Result = 0;1293if (Predicate == ICmpInst::ICMP_ULT || Predicate == ICmpInst::ICMP_ULE)1294Result = 1;1295break;1296case ICmpInst::ICMP_SLE:1297if (Predicate == ICmpInst::ICMP_SGT)1298Result = 0;1299if (Predicate == ICmpInst::ICMP_SLT || Predicate == ICmpInst::ICMP_SLE)1300Result = 1;1301break;1302case ICmpInst::ICMP_UGE:1303if (Predicate == ICmpInst::ICMP_ULT)1304Result = 0;1305if (Predicate == ICmpInst::ICMP_UGT || Predicate == ICmpInst::ICMP_UGE)1306Result = 1;1307break;1308case ICmpInst::ICMP_SGE:1309if (Predicate == ICmpInst::ICMP_SLT)1310Result = 0;1311if (Predicate == ICmpInst::ICMP_SGT || Predicate == ICmpInst::ICMP_SGE)1312Result = 1;1313break;1314case ICmpInst::ICMP_NE:1315if (Predicate == ICmpInst::ICMP_EQ)1316Result = 0;1317if (Predicate == ICmpInst::ICMP_NE)1318Result = 1;1319break;1320}13211322// If we evaluated the result, return it now.1323if (Result != -1)1324return ConstantInt::get(ResultTy, Result);13251326if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||1327(C1->isNullValue() && !C2->isNullValue())) {1328// If C2 is a constant expr and C1 isn't, flip them around and fold the1329// other way if possible.1330// Also, if C1 is null and C2 isn't, flip them around.1331Predicate = ICmpInst::getSwappedPredicate(Predicate);1332return ConstantFoldCompareInstruction(Predicate, C2, C1);1333}1334}1335return nullptr;1336}13371338Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C,1339std::optional<ConstantRange> InRange,1340ArrayRef<Value *> Idxs) {1341if (Idxs.empty()) return C;13421343Type *GEPTy = GetElementPtrInst::getGEPReturnType(1344C, ArrayRef((Value *const *)Idxs.data(), Idxs.size()));13451346if (isa<PoisonValue>(C))1347return PoisonValue::get(GEPTy);13481349if (isa<UndefValue>(C))1350return UndefValue::get(GEPTy);13511352auto IsNoOp = [&]() {1353// Avoid losing inrange information.1354if (InRange)1355return false;13561357return all_of(Idxs, [](Value *Idx) {1358Constant *IdxC = cast<Constant>(Idx);1359return IdxC->isNullValue() || isa<UndefValue>(IdxC);1360});1361};1362if (IsNoOp())1363return GEPTy->isVectorTy() && !C->getType()->isVectorTy()1364? ConstantVector::getSplat(1365cast<VectorType>(GEPTy)->getElementCount(), C)1366: C;13671368return nullptr;1369}137013711372