Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
35266 views
//===- InstructionCombining.cpp - Combine multiple instructions -----------===//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// InstructionCombining - Combine instructions to form fewer, simple9// instructions. This pass does not modify the CFG. This pass is where10// algebraic simplification happens.11//12// This pass combines things like:13// %Y = add i32 %X, 114// %Z = add i32 %Y, 115// into:16// %Z = add i32 %X, 217//18// This is a simple worklist driven algorithm.19//20// This pass guarantees that the following canonicalizations are performed on21// the program:22// 1. If a binary operator has a constant operand, it is moved to the RHS23// 2. Bitwise operators with constant operands are always grouped so that24// shifts are performed first, then or's, then and's, then xor's.25// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible26// 4. All cmp instructions on boolean values are replaced with logical ops27// 5. add X, X is represented as (X*2) => (X << 1)28// 6. Multiplies with a power-of-two constant argument are transformed into29// shifts.30// ... etc.31//32//===----------------------------------------------------------------------===//3334#include "InstCombineInternal.h"35#include "llvm/ADT/APInt.h"36#include "llvm/ADT/ArrayRef.h"37#include "llvm/ADT/DenseMap.h"38#include "llvm/ADT/SmallPtrSet.h"39#include "llvm/ADT/SmallVector.h"40#include "llvm/ADT/Statistic.h"41#include "llvm/Analysis/AliasAnalysis.h"42#include "llvm/Analysis/AssumptionCache.h"43#include "llvm/Analysis/BasicAliasAnalysis.h"44#include "llvm/Analysis/BlockFrequencyInfo.h"45#include "llvm/Analysis/CFG.h"46#include "llvm/Analysis/ConstantFolding.h"47#include "llvm/Analysis/GlobalsModRef.h"48#include "llvm/Analysis/InstructionSimplify.h"49#include "llvm/Analysis/LazyBlockFrequencyInfo.h"50#include "llvm/Analysis/LoopInfo.h"51#include "llvm/Analysis/MemoryBuiltins.h"52#include "llvm/Analysis/OptimizationRemarkEmitter.h"53#include "llvm/Analysis/ProfileSummaryInfo.h"54#include "llvm/Analysis/TargetFolder.h"55#include "llvm/Analysis/TargetLibraryInfo.h"56#include "llvm/Analysis/TargetTransformInfo.h"57#include "llvm/Analysis/Utils/Local.h"58#include "llvm/Analysis/ValueTracking.h"59#include "llvm/Analysis/VectorUtils.h"60#include "llvm/IR/BasicBlock.h"61#include "llvm/IR/CFG.h"62#include "llvm/IR/Constant.h"63#include "llvm/IR/Constants.h"64#include "llvm/IR/DIBuilder.h"65#include "llvm/IR/DataLayout.h"66#include "llvm/IR/DebugInfo.h"67#include "llvm/IR/DerivedTypes.h"68#include "llvm/IR/Dominators.h"69#include "llvm/IR/EHPersonalities.h"70#include "llvm/IR/Function.h"71#include "llvm/IR/GetElementPtrTypeIterator.h"72#include "llvm/IR/IRBuilder.h"73#include "llvm/IR/InstrTypes.h"74#include "llvm/IR/Instruction.h"75#include "llvm/IR/Instructions.h"76#include "llvm/IR/IntrinsicInst.h"77#include "llvm/IR/Intrinsics.h"78#include "llvm/IR/Metadata.h"79#include "llvm/IR/Operator.h"80#include "llvm/IR/PassManager.h"81#include "llvm/IR/PatternMatch.h"82#include "llvm/IR/Type.h"83#include "llvm/IR/Use.h"84#include "llvm/IR/User.h"85#include "llvm/IR/Value.h"86#include "llvm/IR/ValueHandle.h"87#include "llvm/InitializePasses.h"88#include "llvm/Support/Casting.h"89#include "llvm/Support/CommandLine.h"90#include "llvm/Support/Compiler.h"91#include "llvm/Support/Debug.h"92#include "llvm/Support/DebugCounter.h"93#include "llvm/Support/ErrorHandling.h"94#include "llvm/Support/KnownBits.h"95#include "llvm/Support/raw_ostream.h"96#include "llvm/Transforms/InstCombine/InstCombine.h"97#include "llvm/Transforms/Utils/BasicBlockUtils.h"98#include "llvm/Transforms/Utils/Local.h"99#include <algorithm>100#include <cassert>101#include <cstdint>102#include <memory>103#include <optional>104#include <string>105#include <utility>106107#define DEBUG_TYPE "instcombine"108#include "llvm/Transforms/Utils/InstructionWorklist.h"109#include <optional>110111using namespace llvm;112using namespace llvm::PatternMatch;113114STATISTIC(NumWorklistIterations,115"Number of instruction combining iterations performed");116STATISTIC(NumOneIteration, "Number of functions with one iteration");117STATISTIC(NumTwoIterations, "Number of functions with two iterations");118STATISTIC(NumThreeIterations, "Number of functions with three iterations");119STATISTIC(NumFourOrMoreIterations,120"Number of functions with four or more iterations");121122STATISTIC(NumCombined , "Number of insts combined");123STATISTIC(NumConstProp, "Number of constant folds");124STATISTIC(NumDeadInst , "Number of dead inst eliminated");125STATISTIC(NumSunkInst , "Number of instructions sunk");126STATISTIC(NumExpand, "Number of expansions");127STATISTIC(NumFactor , "Number of factorizations");128STATISTIC(NumReassoc , "Number of reassociations");129DEBUG_COUNTER(VisitCounter, "instcombine-visit",130"Controls which instructions are visited");131132static cl::opt<bool>133EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"),134cl::init(true));135136static cl::opt<unsigned> MaxSinkNumUsers(137"instcombine-max-sink-users", cl::init(32),138cl::desc("Maximum number of undroppable users for instruction sinking"));139140static cl::opt<unsigned>141MaxArraySize("instcombine-maxarray-size", cl::init(1024),142cl::desc("Maximum array size considered when doing a combine"));143144// FIXME: Remove this flag when it is no longer necessary to convert145// llvm.dbg.declare to avoid inaccurate debug info. Setting this to false146// increases variable availability at the cost of accuracy. Variables that147// cannot be promoted by mem2reg or SROA will be described as living in memory148// for their entire lifetime. However, passes like DSE and instcombine can149// delete stores to the alloca, leading to misleading and inaccurate debug150// information. This flag can be removed when those passes are fixed.151static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare",152cl::Hidden, cl::init(true));153154std::optional<Instruction *>155InstCombiner::targetInstCombineIntrinsic(IntrinsicInst &II) {156// Handle target specific intrinsics157if (II.getCalledFunction()->isTargetIntrinsic()) {158return TTI.instCombineIntrinsic(*this, II);159}160return std::nullopt;161}162163std::optional<Value *> InstCombiner::targetSimplifyDemandedUseBitsIntrinsic(164IntrinsicInst &II, APInt DemandedMask, KnownBits &Known,165bool &KnownBitsComputed) {166// Handle target specific intrinsics167if (II.getCalledFunction()->isTargetIntrinsic()) {168return TTI.simplifyDemandedUseBitsIntrinsic(*this, II, DemandedMask, Known,169KnownBitsComputed);170}171return std::nullopt;172}173174std::optional<Value *> InstCombiner::targetSimplifyDemandedVectorEltsIntrinsic(175IntrinsicInst &II, APInt DemandedElts, APInt &PoisonElts,176APInt &PoisonElts2, APInt &PoisonElts3,177std::function<void(Instruction *, unsigned, APInt, APInt &)>178SimplifyAndSetOp) {179// Handle target specific intrinsics180if (II.getCalledFunction()->isTargetIntrinsic()) {181return TTI.simplifyDemandedVectorEltsIntrinsic(182*this, II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,183SimplifyAndSetOp);184}185return std::nullopt;186}187188bool InstCombiner::isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const {189return TTI.isValidAddrSpaceCast(FromAS, ToAS);190}191192Value *InstCombinerImpl::EmitGEPOffset(GEPOperator *GEP, bool RewriteGEP) {193if (!RewriteGEP)194return llvm::emitGEPOffset(&Builder, DL, GEP);195196IRBuilderBase::InsertPointGuard Guard(Builder);197auto *Inst = dyn_cast<Instruction>(GEP);198if (Inst)199Builder.SetInsertPoint(Inst);200201Value *Offset = EmitGEPOffset(GEP);202// If a non-trivial GEP has other uses, rewrite it to avoid duplicating203// the offset arithmetic.204if (Inst && !GEP->hasOneUse() && !GEP->hasAllConstantIndices() &&205!GEP->getSourceElementType()->isIntegerTy(8)) {206replaceInstUsesWith(207*Inst, Builder.CreateGEP(Builder.getInt8Ty(), GEP->getPointerOperand(),208Offset, "", GEP->getNoWrapFlags()));209eraseInstFromFunction(*Inst);210}211return Offset;212}213214/// Legal integers and common types are considered desirable. This is used to215/// avoid creating instructions with types that may not be supported well by the216/// the backend.217/// NOTE: This treats i8, i16 and i32 specially because they are common218/// types in frontend languages.219bool InstCombinerImpl::isDesirableIntType(unsigned BitWidth) const {220switch (BitWidth) {221case 8:222case 16:223case 32:224return true;225default:226return DL.isLegalInteger(BitWidth);227}228}229230/// Return true if it is desirable to convert an integer computation from a231/// given bit width to a new bit width.232/// We don't want to convert from a legal or desirable type (like i8) to an233/// illegal type or from a smaller to a larger illegal type. A width of '1'234/// is always treated as a desirable type because i1 is a fundamental type in235/// IR, and there are many specialized optimizations for i1 types.236/// Common/desirable widths are equally treated as legal to convert to, in237/// order to open up more combining opportunities.238bool InstCombinerImpl::shouldChangeType(unsigned FromWidth,239unsigned ToWidth) const {240bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);241bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);242243// Convert to desirable widths even if they are not legal types.244// Only shrink types, to prevent infinite loops.245if (ToWidth < FromWidth && isDesirableIntType(ToWidth))246return true;247248// If this is a legal or desiable integer from type, and the result would be249// an illegal type, don't do the transformation.250if ((FromLegal || isDesirableIntType(FromWidth)) && !ToLegal)251return false;252253// Otherwise, if both are illegal, do not increase the size of the result. We254// do allow things like i160 -> i64, but not i64 -> i160.255if (!FromLegal && !ToLegal && ToWidth > FromWidth)256return false;257258return true;259}260261/// Return true if it is desirable to convert a computation from 'From' to 'To'.262/// We don't want to convert from a legal to an illegal type or from a smaller263/// to a larger illegal type. i1 is always treated as a legal type because it is264/// a fundamental type in IR, and there are many specialized optimizations for265/// i1 types.266bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const {267// TODO: This could be extended to allow vectors. Datalayout changes might be268// needed to properly support that.269if (!From->isIntegerTy() || !To->isIntegerTy())270return false;271272unsigned FromWidth = From->getPrimitiveSizeInBits();273unsigned ToWidth = To->getPrimitiveSizeInBits();274return shouldChangeType(FromWidth, ToWidth);275}276277// Return true, if No Signed Wrap should be maintained for I.278// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",279// where both B and C should be ConstantInts, results in a constant that does280// not overflow. This function only handles the Add and Sub opcodes. For281// all other opcodes, the function conservatively returns false.282static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {283auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);284if (!OBO || !OBO->hasNoSignedWrap())285return false;286287// We reason about Add and Sub Only.288Instruction::BinaryOps Opcode = I.getOpcode();289if (Opcode != Instruction::Add && Opcode != Instruction::Sub)290return false;291292const APInt *BVal, *CVal;293if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))294return false;295296bool Overflow = false;297if (Opcode == Instruction::Add)298(void)BVal->sadd_ov(*CVal, Overflow);299else300(void)BVal->ssub_ov(*CVal, Overflow);301302return !Overflow;303}304305static bool hasNoUnsignedWrap(BinaryOperator &I) {306auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);307return OBO && OBO->hasNoUnsignedWrap();308}309310static bool hasNoSignedWrap(BinaryOperator &I) {311auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);312return OBO && OBO->hasNoSignedWrap();313}314315/// Conservatively clears subclassOptionalData after a reassociation or316/// commutation. We preserve fast-math flags when applicable as they can be317/// preserved.318static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {319FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);320if (!FPMO) {321I.clearSubclassOptionalData();322return;323}324325FastMathFlags FMF = I.getFastMathFlags();326I.clearSubclassOptionalData();327I.setFastMathFlags(FMF);328}329330/// Combine constant operands of associative operations either before or after a331/// cast to eliminate one of the associative operations:332/// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))333/// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))334static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1,335InstCombinerImpl &IC) {336auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));337if (!Cast || !Cast->hasOneUse())338return false;339340// TODO: Enhance logic for other casts and remove this check.341auto CastOpcode = Cast->getOpcode();342if (CastOpcode != Instruction::ZExt)343return false;344345// TODO: Enhance logic for other BinOps and remove this check.346if (!BinOp1->isBitwiseLogicOp())347return false;348349auto AssocOpcode = BinOp1->getOpcode();350auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));351if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)352return false;353354Constant *C1, *C2;355if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||356!match(BinOp2->getOperand(1), m_Constant(C2)))357return false;358359// TODO: This assumes a zext cast.360// Eg, if it was a trunc, we'd cast C1 to the source type because casting C2361// to the destination type might lose bits.362363// Fold the constants together in the destination type:364// (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)365const DataLayout &DL = IC.getDataLayout();366Type *DestTy = C1->getType();367Constant *CastC2 = ConstantFoldCastOperand(CastOpcode, C2, DestTy, DL);368if (!CastC2)369return false;370Constant *FoldedC = ConstantFoldBinaryOpOperands(AssocOpcode, C1, CastC2, DL);371if (!FoldedC)372return false;373374IC.replaceOperand(*Cast, 0, BinOp2->getOperand(0));375IC.replaceOperand(*BinOp1, 1, FoldedC);376BinOp1->dropPoisonGeneratingFlags();377Cast->dropPoisonGeneratingFlags();378return true;379}380381// Simplifies IntToPtr/PtrToInt RoundTrip Cast.382// inttoptr ( ptrtoint (x) ) --> x383Value *InstCombinerImpl::simplifyIntToPtrRoundTripCast(Value *Val) {384auto *IntToPtr = dyn_cast<IntToPtrInst>(Val);385if (IntToPtr && DL.getTypeSizeInBits(IntToPtr->getDestTy()) ==386DL.getTypeSizeInBits(IntToPtr->getSrcTy())) {387auto *PtrToInt = dyn_cast<PtrToIntInst>(IntToPtr->getOperand(0));388Type *CastTy = IntToPtr->getDestTy();389if (PtrToInt &&390CastTy->getPointerAddressSpace() ==391PtrToInt->getSrcTy()->getPointerAddressSpace() &&392DL.getTypeSizeInBits(PtrToInt->getSrcTy()) ==393DL.getTypeSizeInBits(PtrToInt->getDestTy()))394return PtrToInt->getOperand(0);395}396return nullptr;397}398399/// This performs a few simplifications for operators that are associative or400/// commutative:401///402/// Commutative operators:403///404/// 1. Order operands such that they are listed from right (least complex) to405/// left (most complex). This puts constants before unary operators before406/// binary operators.407///408/// Associative operators:409///410/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.411/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.412///413/// Associative and commutative operators:414///415/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.416/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.417/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"418/// if C1 and C2 are constants.419bool InstCombinerImpl::SimplifyAssociativeOrCommutative(BinaryOperator &I) {420Instruction::BinaryOps Opcode = I.getOpcode();421bool Changed = false;422423do {424// Order operands such that they are listed from right (least complex) to425// left (most complex). This puts constants before unary operators before426// binary operators.427if (I.isCommutative() && getComplexity(I.getOperand(0)) <428getComplexity(I.getOperand(1)))429Changed = !I.swapOperands();430431if (I.isCommutative()) {432if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {433replaceOperand(I, 0, Pair->first);434replaceOperand(I, 1, Pair->second);435Changed = true;436}437}438439BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));440BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));441442if (I.isAssociative()) {443// Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.444if (Op0 && Op0->getOpcode() == Opcode) {445Value *A = Op0->getOperand(0);446Value *B = Op0->getOperand(1);447Value *C = I.getOperand(1);448449// Does "B op C" simplify?450if (Value *V = simplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {451// It simplifies to V. Form "A op V".452replaceOperand(I, 0, A);453replaceOperand(I, 1, V);454bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0);455bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0);456457// Conservatively clear all optional flags since they may not be458// preserved by the reassociation. Reset nsw/nuw based on the above459// analysis.460ClearSubclassDataAfterReassociation(I);461462// Note: this is only valid because SimplifyBinOp doesn't look at463// the operands to Op0.464if (IsNUW)465I.setHasNoUnsignedWrap(true);466467if (IsNSW)468I.setHasNoSignedWrap(true);469470Changed = true;471++NumReassoc;472continue;473}474}475476// Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.477if (Op1 && Op1->getOpcode() == Opcode) {478Value *A = I.getOperand(0);479Value *B = Op1->getOperand(0);480Value *C = Op1->getOperand(1);481482// Does "A op B" simplify?483if (Value *V = simplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {484// It simplifies to V. Form "V op C".485replaceOperand(I, 0, V);486replaceOperand(I, 1, C);487// Conservatively clear the optional flags, since they may not be488// preserved by the reassociation.489ClearSubclassDataAfterReassociation(I);490Changed = true;491++NumReassoc;492continue;493}494}495}496497if (I.isAssociative() && I.isCommutative()) {498if (simplifyAssocCastAssoc(&I, *this)) {499Changed = true;500++NumReassoc;501continue;502}503504// Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.505if (Op0 && Op0->getOpcode() == Opcode) {506Value *A = Op0->getOperand(0);507Value *B = Op0->getOperand(1);508Value *C = I.getOperand(1);509510// Does "C op A" simplify?511if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {512// It simplifies to V. Form "V op B".513replaceOperand(I, 0, V);514replaceOperand(I, 1, B);515// Conservatively clear the optional flags, since they may not be516// preserved by the reassociation.517ClearSubclassDataAfterReassociation(I);518Changed = true;519++NumReassoc;520continue;521}522}523524// Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.525if (Op1 && Op1->getOpcode() == Opcode) {526Value *A = I.getOperand(0);527Value *B = Op1->getOperand(0);528Value *C = Op1->getOperand(1);529530// Does "C op A" simplify?531if (Value *V = simplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {532// It simplifies to V. Form "B op V".533replaceOperand(I, 0, B);534replaceOperand(I, 1, V);535// Conservatively clear the optional flags, since they may not be536// preserved by the reassociation.537ClearSubclassDataAfterReassociation(I);538Changed = true;539++NumReassoc;540continue;541}542}543544// Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"545// if C1 and C2 are constants.546Value *A, *B;547Constant *C1, *C2, *CRes;548if (Op0 && Op1 &&549Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&550match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) &&551match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2)))) &&552(CRes = ConstantFoldBinaryOpOperands(Opcode, C1, C2, DL))) {553bool IsNUW = hasNoUnsignedWrap(I) &&554hasNoUnsignedWrap(*Op0) &&555hasNoUnsignedWrap(*Op1);556BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ?557BinaryOperator::CreateNUW(Opcode, A, B) :558BinaryOperator::Create(Opcode, A, B);559560if (isa<FPMathOperator>(NewBO)) {561FastMathFlags Flags = I.getFastMathFlags() &562Op0->getFastMathFlags() &563Op1->getFastMathFlags();564NewBO->setFastMathFlags(Flags);565}566InsertNewInstWith(NewBO, I.getIterator());567NewBO->takeName(Op1);568replaceOperand(I, 0, NewBO);569replaceOperand(I, 1, CRes);570// Conservatively clear the optional flags, since they may not be571// preserved by the reassociation.572ClearSubclassDataAfterReassociation(I);573if (IsNUW)574I.setHasNoUnsignedWrap(true);575576Changed = true;577continue;578}579}580581// No further simplifications.582return Changed;583} while (true);584}585586/// Return whether "X LOp (Y ROp Z)" is always equal to587/// "(X LOp Y) ROp (X LOp Z)".588static bool leftDistributesOverRight(Instruction::BinaryOps LOp,589Instruction::BinaryOps ROp) {590// X & (Y | Z) <--> (X & Y) | (X & Z)591// X & (Y ^ Z) <--> (X & Y) ^ (X & Z)592if (LOp == Instruction::And)593return ROp == Instruction::Or || ROp == Instruction::Xor;594595// X | (Y & Z) <--> (X | Y) & (X | Z)596if (LOp == Instruction::Or)597return ROp == Instruction::And;598599// X * (Y + Z) <--> (X * Y) + (X * Z)600// X * (Y - Z) <--> (X * Y) - (X * Z)601if (LOp == Instruction::Mul)602return ROp == Instruction::Add || ROp == Instruction::Sub;603604return false;605}606607/// Return whether "(X LOp Y) ROp Z" is always equal to608/// "(X ROp Z) LOp (Y ROp Z)".609static bool rightDistributesOverLeft(Instruction::BinaryOps LOp,610Instruction::BinaryOps ROp) {611if (Instruction::isCommutative(ROp))612return leftDistributesOverRight(ROp, LOp);613614// (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.615return Instruction::isBitwiseLogicOp(LOp) && Instruction::isShift(ROp);616617// TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",618// but this requires knowing that the addition does not overflow and other619// such subtleties.620}621622/// This function returns identity value for given opcode, which can be used to623/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).624static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) {625if (isa<Constant>(V))626return nullptr;627628return ConstantExpr::getBinOpIdentity(Opcode, V->getType());629}630631/// This function predicates factorization using distributive laws. By default,632/// it just returns the 'Op' inputs. But for special-cases like633/// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add634/// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to635/// allow more factorization opportunities.636static Instruction::BinaryOps637getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op,638Value *&LHS, Value *&RHS, BinaryOperator *OtherOp) {639assert(Op && "Expected a binary operator");640LHS = Op->getOperand(0);641RHS = Op->getOperand(1);642if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {643Constant *C;644if (match(Op, m_Shl(m_Value(), m_ImmConstant(C)))) {645// X << C --> X * (1 << C)646RHS = ConstantFoldBinaryInstruction(647Instruction::Shl, ConstantInt::get(Op->getType(), 1), C);648assert(RHS && "Constant folding of immediate constants failed");649return Instruction::Mul;650}651// TODO: We can add other conversions e.g. shr => div etc.652}653if (Instruction::isBitwiseLogicOp(TopOpcode)) {654if (OtherOp && OtherOp->getOpcode() == Instruction::AShr &&655match(Op, m_LShr(m_NonNegative(), m_Value()))) {656// lshr nneg C, X --> ashr nneg C, X657return Instruction::AShr;658}659}660return Op->getOpcode();661}662663/// This tries to simplify binary operations by factorizing out common terms664/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").665static Value *tryFactorization(BinaryOperator &I, const SimplifyQuery &SQ,666InstCombiner::BuilderTy &Builder,667Instruction::BinaryOps InnerOpcode, Value *A,668Value *B, Value *C, Value *D) {669assert(A && B && C && D && "All values must be provided");670671Value *V = nullptr;672Value *RetVal = nullptr;673Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);674Instruction::BinaryOps TopLevelOpcode = I.getOpcode();675676// Does "X op' Y" always equal "Y op' X"?677bool InnerCommutative = Instruction::isCommutative(InnerOpcode);678679// Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?680if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode)) {681// Does the instruction have the form "(A op' B) op (A op' D)" or, in the682// commutative case, "(A op' B) op (C op' A)"?683if (A == C || (InnerCommutative && A == D)) {684if (A != C)685std::swap(C, D);686// Consider forming "A op' (B op D)".687// If "B op D" simplifies then it can be formed with no cost.688V = simplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));689690// If "B op D" doesn't simplify then only go on if one of the existing691// operations "A op' B" and "C op' D" will be zapped as no longer used.692if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))693V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName());694if (V)695RetVal = Builder.CreateBinOp(InnerOpcode, A, V);696}697}698699// Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?700if (!RetVal && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) {701// Does the instruction have the form "(A op' B) op (C op' B)" or, in the702// commutative case, "(A op' B) op (B op' D)"?703if (B == D || (InnerCommutative && B == C)) {704if (B != D)705std::swap(C, D);706// Consider forming "(A op C) op' B".707// If "A op C" simplifies then it can be formed with no cost.708V = simplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));709710// If "A op C" doesn't simplify then only go on if one of the existing711// operations "A op' B" and "C op' D" will be zapped as no longer used.712if (!V && (LHS->hasOneUse() || RHS->hasOneUse()))713V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName());714if (V)715RetVal = Builder.CreateBinOp(InnerOpcode, V, B);716}717}718719if (!RetVal)720return nullptr;721722++NumFactor;723RetVal->takeName(&I);724725// Try to add no-overflow flags to the final value.726if (isa<OverflowingBinaryOperator>(RetVal)) {727bool HasNSW = false;728bool HasNUW = false;729if (isa<OverflowingBinaryOperator>(&I)) {730HasNSW = I.hasNoSignedWrap();731HasNUW = I.hasNoUnsignedWrap();732}733if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) {734HasNSW &= LOBO->hasNoSignedWrap();735HasNUW &= LOBO->hasNoUnsignedWrap();736}737738if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) {739HasNSW &= ROBO->hasNoSignedWrap();740HasNUW &= ROBO->hasNoUnsignedWrap();741}742743if (TopLevelOpcode == Instruction::Add && InnerOpcode == Instruction::Mul) {744// We can propagate 'nsw' if we know that745// %Y = mul nsw i16 %X, C746// %Z = add nsw i16 %Y, %X747// =>748// %Z = mul nsw i16 %X, C+1749//750// iff C+1 isn't INT_MIN751const APInt *CInt;752if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())753cast<Instruction>(RetVal)->setHasNoSignedWrap(HasNSW);754755// nuw can be propagated with any constant or nuw value.756cast<Instruction>(RetVal)->setHasNoUnsignedWrap(HasNUW);757}758}759return RetVal;760}761762// If `I` has one Const operand and the other matches `(ctpop (not x))`,763// replace `(ctpop (not x))` with `(sub nuw nsw BitWidth(x), (ctpop x))`.764// This is only useful is the new subtract can fold so we only handle the765// following cases:766// 1) (add/sub/disjoint_or C, (ctpop (not x))767// -> (add/sub/disjoint_or C', (ctpop x))768// 1) (cmp pred C, (ctpop (not x))769// -> (cmp pred C', (ctpop x))770Instruction *InstCombinerImpl::tryFoldInstWithCtpopWithNot(Instruction *I) {771unsigned Opc = I->getOpcode();772unsigned ConstIdx = 1;773switch (Opc) {774default:775return nullptr;776// (ctpop (not x)) <-> (sub nuw nsw BitWidth(x) - (ctpop x))777// We can fold the BitWidth(x) with add/sub/icmp as long the other operand778// is constant.779case Instruction::Sub:780ConstIdx = 0;781break;782case Instruction::ICmp:783// Signed predicates aren't correct in some edge cases like for i2 types, as784// well since (ctpop x) is known [0, log2(BitWidth(x))] almost all signed785// comparisons against it are simplfied to unsigned.786if (cast<ICmpInst>(I)->isSigned())787return nullptr;788break;789case Instruction::Or:790if (!match(I, m_DisjointOr(m_Value(), m_Value())))791return nullptr;792[[fallthrough]];793case Instruction::Add:794break;795}796797Value *Op;798// Find ctpop.799if (!match(I->getOperand(1 - ConstIdx),800m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(Op)))))801return nullptr;802803Constant *C;804// Check other operand is ImmConstant.805if (!match(I->getOperand(ConstIdx), m_ImmConstant(C)))806return nullptr;807808Type *Ty = Op->getType();809Constant *BitWidthC = ConstantInt::get(Ty, Ty->getScalarSizeInBits());810// Need extra check for icmp. Note if this check is true, it generally means811// the icmp will simplify to true/false.812if (Opc == Instruction::ICmp && !cast<ICmpInst>(I)->isEquality()) {813Constant *Cmp =814ConstantFoldCompareInstOperands(ICmpInst::ICMP_UGT, C, BitWidthC, DL);815if (!Cmp || !Cmp->isZeroValue())816return nullptr;817}818819// Check we can invert `(not x)` for free.820bool Consumes = false;821if (!isFreeToInvert(Op, Op->hasOneUse(), Consumes) || !Consumes)822return nullptr;823Value *NotOp = getFreelyInverted(Op, Op->hasOneUse(), &Builder);824assert(NotOp != nullptr &&825"Desync between isFreeToInvert and getFreelyInverted");826827Value *CtpopOfNotOp = Builder.CreateIntrinsic(Ty, Intrinsic::ctpop, NotOp);828829Value *R = nullptr;830831// Do the transformation here to avoid potentially introducing an infinite832// loop.833switch (Opc) {834case Instruction::Sub:835R = Builder.CreateAdd(CtpopOfNotOp, ConstantExpr::getSub(C, BitWidthC));836break;837case Instruction::Or:838case Instruction::Add:839R = Builder.CreateSub(ConstantExpr::getAdd(C, BitWidthC), CtpopOfNotOp);840break;841case Instruction::ICmp:842R = Builder.CreateICmp(cast<ICmpInst>(I)->getSwappedPredicate(),843CtpopOfNotOp, ConstantExpr::getSub(BitWidthC, C));844break;845default:846llvm_unreachable("Unhandled Opcode");847}848assert(R != nullptr);849return replaceInstUsesWith(*I, R);850}851852// (Binop1 (Binop2 (logic_shift X, C), C1), (logic_shift Y, C))853// IFF854// 1) the logic_shifts match855// 2) either both binops are binops and one is `and` or856// BinOp1 is `and`857// (logic_shift (inv_logic_shift C1, C), C) == C1 or858//859// -> (logic_shift (Binop1 (Binop2 X, inv_logic_shift(C1, C)), Y), C)860//861// (Binop1 (Binop2 (logic_shift X, Amt), Mask), (logic_shift Y, Amt))862// IFF863// 1) the logic_shifts match864// 2) BinOp1 == BinOp2 (if BinOp == `add`, then also requires `shl`).865//866// -> (BinOp (logic_shift (BinOp X, Y)), Mask)867//868// (Binop1 (Binop2 (arithmetic_shift X, Amt), Mask), (arithmetic_shift Y, Amt))869// IFF870// 1) Binop1 is bitwise logical operator `and`, `or` or `xor`871// 2) Binop2 is `not`872//873// -> (arithmetic_shift Binop1((not X), Y), Amt)874875Instruction *InstCombinerImpl::foldBinOpShiftWithShift(BinaryOperator &I) {876const DataLayout &DL = I.getDataLayout();877auto IsValidBinOpc = [](unsigned Opc) {878switch (Opc) {879default:880return false;881case Instruction::And:882case Instruction::Or:883case Instruction::Xor:884case Instruction::Add:885// Skip Sub as we only match constant masks which will canonicalize to use886// add.887return true;888}889};890891// Check if we can distribute binop arbitrarily. `add` + `lshr` has extra892// constraints.893auto IsCompletelyDistributable = [](unsigned BinOpc1, unsigned BinOpc2,894unsigned ShOpc) {895assert(ShOpc != Instruction::AShr);896return (BinOpc1 != Instruction::Add && BinOpc2 != Instruction::Add) ||897ShOpc == Instruction::Shl;898};899900auto GetInvShift = [](unsigned ShOpc) {901assert(ShOpc != Instruction::AShr);902return ShOpc == Instruction::LShr ? Instruction::Shl : Instruction::LShr;903};904905auto CanDistributeBinops = [&](unsigned BinOpc1, unsigned BinOpc2,906unsigned ShOpc, Constant *CMask,907Constant *CShift) {908// If the BinOp1 is `and` we don't need to check the mask.909if (BinOpc1 == Instruction::And)910return true;911912// For all other possible transfers we need complete distributable913// binop/shift (anything but `add` + `lshr`).914if (!IsCompletelyDistributable(BinOpc1, BinOpc2, ShOpc))915return false;916917// If BinOp2 is `and`, any mask works (this only really helps for non-splat918// vecs, otherwise the mask will be simplified and the following check will919// handle it).920if (BinOpc2 == Instruction::And)921return true;922923// Otherwise, need mask that meets the below requirement.924// (logic_shift (inv_logic_shift Mask, ShAmt), ShAmt) == Mask925Constant *MaskInvShift =926ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL);927return ConstantFoldBinaryOpOperands(ShOpc, MaskInvShift, CShift, DL) ==928CMask;929};930931auto MatchBinOp = [&](unsigned ShOpnum) -> Instruction * {932Constant *CMask, *CShift;933Value *X, *Y, *ShiftedX, *Mask, *Shift;934if (!match(I.getOperand(ShOpnum),935m_OneUse(m_Shift(m_Value(Y), m_Value(Shift)))))936return nullptr;937if (!match(I.getOperand(1 - ShOpnum),938m_BinOp(m_Value(ShiftedX), m_Value(Mask))))939return nullptr;940941if (!match(ShiftedX, m_OneUse(m_Shift(m_Value(X), m_Specific(Shift)))))942return nullptr;943944// Make sure we are matching instruction shifts and not ConstantExpr945auto *IY = dyn_cast<Instruction>(I.getOperand(ShOpnum));946auto *IX = dyn_cast<Instruction>(ShiftedX);947if (!IY || !IX)948return nullptr;949950// LHS and RHS need same shift opcode951unsigned ShOpc = IY->getOpcode();952if (ShOpc != IX->getOpcode())953return nullptr;954955// Make sure binop is real instruction and not ConstantExpr956auto *BO2 = dyn_cast<Instruction>(I.getOperand(1 - ShOpnum));957if (!BO2)958return nullptr;959960unsigned BinOpc = BO2->getOpcode();961// Make sure we have valid binops.962if (!IsValidBinOpc(I.getOpcode()) || !IsValidBinOpc(BinOpc))963return nullptr;964965if (ShOpc == Instruction::AShr) {966if (Instruction::isBitwiseLogicOp(I.getOpcode()) &&967BinOpc == Instruction::Xor && match(Mask, m_AllOnes())) {968Value *NotX = Builder.CreateNot(X);969Value *NewBinOp = Builder.CreateBinOp(I.getOpcode(), Y, NotX);970return BinaryOperator::Create(971static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp, Shift);972}973974return nullptr;975}976977// If BinOp1 == BinOp2 and it's bitwise or shl with add, then just978// distribute to drop the shift irrelevant of constants.979if (BinOpc == I.getOpcode() &&980IsCompletelyDistributable(I.getOpcode(), BinOpc, ShOpc)) {981Value *NewBinOp2 = Builder.CreateBinOp(I.getOpcode(), X, Y);982Value *NewBinOp1 = Builder.CreateBinOp(983static_cast<Instruction::BinaryOps>(ShOpc), NewBinOp2, Shift);984return BinaryOperator::Create(I.getOpcode(), NewBinOp1, Mask);985}986987// Otherwise we can only distribute by constant shifting the mask, so988// ensure we have constants.989if (!match(Shift, m_ImmConstant(CShift)))990return nullptr;991if (!match(Mask, m_ImmConstant(CMask)))992return nullptr;993994// Check if we can distribute the binops.995if (!CanDistributeBinops(I.getOpcode(), BinOpc, ShOpc, CMask, CShift))996return nullptr;997998Constant *NewCMask =999ConstantFoldBinaryOpOperands(GetInvShift(ShOpc), CMask, CShift, DL);1000Value *NewBinOp2 = Builder.CreateBinOp(1001static_cast<Instruction::BinaryOps>(BinOpc), X, NewCMask);1002Value *NewBinOp1 = Builder.CreateBinOp(I.getOpcode(), Y, NewBinOp2);1003return BinaryOperator::Create(static_cast<Instruction::BinaryOps>(ShOpc),1004NewBinOp1, CShift);1005};10061007if (Instruction *R = MatchBinOp(0))1008return R;1009return MatchBinOp(1);1010}10111012// (Binop (zext C), (select C, T, F))1013// -> (select C, (binop 1, T), (binop 0, F))1014//1015// (Binop (sext C), (select C, T, F))1016// -> (select C, (binop -1, T), (binop 0, F))1017//1018// Attempt to simplify binary operations into a select with folded args, when1019// one operand of the binop is a select instruction and the other operand is a1020// zext/sext extension, whose value is the select condition.1021Instruction *1022InstCombinerImpl::foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I) {1023// TODO: this simplification may be extended to any speculatable instruction,1024// not just binops, and would possibly be handled better in FoldOpIntoSelect.1025Instruction::BinaryOps Opc = I.getOpcode();1026Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);1027Value *A, *CondVal, *TrueVal, *FalseVal;1028Value *CastOp;10291030auto MatchSelectAndCast = [&](Value *CastOp, Value *SelectOp) {1031return match(CastOp, m_ZExtOrSExt(m_Value(A))) &&1032A->getType()->getScalarSizeInBits() == 1 &&1033match(SelectOp, m_Select(m_Value(CondVal), m_Value(TrueVal),1034m_Value(FalseVal)));1035};10361037// Make sure one side of the binop is a select instruction, and the other is a1038// zero/sign extension operating on a i1.1039if (MatchSelectAndCast(LHS, RHS))1040CastOp = LHS;1041else if (MatchSelectAndCast(RHS, LHS))1042CastOp = RHS;1043else1044return nullptr;10451046auto NewFoldedConst = [&](bool IsTrueArm, Value *V) {1047bool IsCastOpRHS = (CastOp == RHS);1048bool IsZExt = isa<ZExtInst>(CastOp);1049Constant *C;10501051if (IsTrueArm) {1052C = Constant::getNullValue(V->getType());1053} else if (IsZExt) {1054unsigned BitWidth = V->getType()->getScalarSizeInBits();1055C = Constant::getIntegerValue(V->getType(), APInt(BitWidth, 1));1056} else {1057C = Constant::getAllOnesValue(V->getType());1058}10591060return IsCastOpRHS ? Builder.CreateBinOp(Opc, V, C)1061: Builder.CreateBinOp(Opc, C, V);1062};10631064// If the value used in the zext/sext is the select condition, or the negated1065// of the select condition, the binop can be simplified.1066if (CondVal == A) {1067Value *NewTrueVal = NewFoldedConst(false, TrueVal);1068return SelectInst::Create(CondVal, NewTrueVal,1069NewFoldedConst(true, FalseVal));1070}10711072if (match(A, m_Not(m_Specific(CondVal)))) {1073Value *NewTrueVal = NewFoldedConst(true, TrueVal);1074return SelectInst::Create(CondVal, NewTrueVal,1075NewFoldedConst(false, FalseVal));1076}10771078return nullptr;1079}10801081Value *InstCombinerImpl::tryFactorizationFolds(BinaryOperator &I) {1082Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);1083BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);1084BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);1085Instruction::BinaryOps TopLevelOpcode = I.getOpcode();1086Value *A, *B, *C, *D;1087Instruction::BinaryOps LHSOpcode, RHSOpcode;10881089if (Op0)1090LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B, Op1);1091if (Op1)1092RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D, Op0);10931094// The instruction has the form "(A op' B) op (C op' D)". Try to factorize1095// a common term.1096if (Op0 && Op1 && LHSOpcode == RHSOpcode)1097if (Value *V = tryFactorization(I, SQ, Builder, LHSOpcode, A, B, C, D))1098return V;10991100// The instruction has the form "(A op' B) op (C)". Try to factorize common1101// term.1102if (Op0)1103if (Value *Ident = getIdentityValue(LHSOpcode, RHS))1104if (Value *V =1105tryFactorization(I, SQ, Builder, LHSOpcode, A, B, RHS, Ident))1106return V;11071108// The instruction has the form "(B) op (C op' D)". Try to factorize common1109// term.1110if (Op1)1111if (Value *Ident = getIdentityValue(RHSOpcode, LHS))1112if (Value *V =1113tryFactorization(I, SQ, Builder, RHSOpcode, LHS, Ident, C, D))1114return V;11151116return nullptr;1117}11181119/// This tries to simplify binary operations which some other binary operation1120/// distributes over either by factorizing out common terms1121/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in1122/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).1123/// Returns the simplified value, or null if it didn't simplify.1124Value *InstCombinerImpl::foldUsingDistributiveLaws(BinaryOperator &I) {1125Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);1126BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);1127BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);1128Instruction::BinaryOps TopLevelOpcode = I.getOpcode();11291130// Factorization.1131if (Value *R = tryFactorizationFolds(I))1132return R;11331134// Expansion.1135if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {1136// The instruction has the form "(A op' B) op C". See if expanding it out1137// to "(A op C) op' (B op C)" results in simplifications.1138Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;1139Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'11401141// Disable the use of undef because it's not safe to distribute undef.1142auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();1143Value *L = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);1144Value *R = simplifyBinOp(TopLevelOpcode, B, C, SQDistributive);11451146// Do "A op C" and "B op C" both simplify?1147if (L && R) {1148// They do! Return "L op' R".1149++NumExpand;1150C = Builder.CreateBinOp(InnerOpcode, L, R);1151C->takeName(&I);1152return C;1153}11541155// Does "A op C" simplify to the identity value for the inner opcode?1156if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {1157// They do! Return "B op C".1158++NumExpand;1159C = Builder.CreateBinOp(TopLevelOpcode, B, C);1160C->takeName(&I);1161return C;1162}11631164// Does "B op C" simplify to the identity value for the inner opcode?1165if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {1166// They do! Return "A op C".1167++NumExpand;1168C = Builder.CreateBinOp(TopLevelOpcode, A, C);1169C->takeName(&I);1170return C;1171}1172}11731174if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {1175// The instruction has the form "A op (B op' C)". See if expanding it out1176// to "(A op B) op' (A op C)" results in simplifications.1177Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);1178Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'11791180// Disable the use of undef because it's not safe to distribute undef.1181auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();1182Value *L = simplifyBinOp(TopLevelOpcode, A, B, SQDistributive);1183Value *R = simplifyBinOp(TopLevelOpcode, A, C, SQDistributive);11841185// Do "A op B" and "A op C" both simplify?1186if (L && R) {1187// They do! Return "L op' R".1188++NumExpand;1189A = Builder.CreateBinOp(InnerOpcode, L, R);1190A->takeName(&I);1191return A;1192}11931194// Does "A op B" simplify to the identity value for the inner opcode?1195if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {1196// They do! Return "A op C".1197++NumExpand;1198A = Builder.CreateBinOp(TopLevelOpcode, A, C);1199A->takeName(&I);1200return A;1201}12021203// Does "A op C" simplify to the identity value for the inner opcode?1204if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {1205// They do! Return "A op B".1206++NumExpand;1207A = Builder.CreateBinOp(TopLevelOpcode, A, B);1208A->takeName(&I);1209return A;1210}1211}12121213return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);1214}12151216static std::optional<std::pair<Value *, Value *>>1217matchSymmetricPhiNodesPair(PHINode *LHS, PHINode *RHS) {1218if (LHS->getParent() != RHS->getParent())1219return std::nullopt;12201221if (LHS->getNumIncomingValues() < 2)1222return std::nullopt;12231224if (!equal(LHS->blocks(), RHS->blocks()))1225return std::nullopt;12261227Value *L0 = LHS->getIncomingValue(0);1228Value *R0 = RHS->getIncomingValue(0);12291230for (unsigned I = 1, E = LHS->getNumIncomingValues(); I != E; ++I) {1231Value *L1 = LHS->getIncomingValue(I);1232Value *R1 = RHS->getIncomingValue(I);12331234if ((L0 == L1 && R0 == R1) || (L0 == R1 && R0 == L1))1235continue;12361237return std::nullopt;1238}12391240return std::optional(std::pair(L0, R0));1241}12421243std::optional<std::pair<Value *, Value *>>1244InstCombinerImpl::matchSymmetricPair(Value *LHS, Value *RHS) {1245Instruction *LHSInst = dyn_cast<Instruction>(LHS);1246Instruction *RHSInst = dyn_cast<Instruction>(RHS);1247if (!LHSInst || !RHSInst || LHSInst->getOpcode() != RHSInst->getOpcode())1248return std::nullopt;1249switch (LHSInst->getOpcode()) {1250case Instruction::PHI:1251return matchSymmetricPhiNodesPair(cast<PHINode>(LHS), cast<PHINode>(RHS));1252case Instruction::Select: {1253Value *Cond = LHSInst->getOperand(0);1254Value *TrueVal = LHSInst->getOperand(1);1255Value *FalseVal = LHSInst->getOperand(2);1256if (Cond == RHSInst->getOperand(0) && TrueVal == RHSInst->getOperand(2) &&1257FalseVal == RHSInst->getOperand(1))1258return std::pair(TrueVal, FalseVal);1259return std::nullopt;1260}1261case Instruction::Call: {1262// Match min(a, b) and max(a, b)1263MinMaxIntrinsic *LHSMinMax = dyn_cast<MinMaxIntrinsic>(LHSInst);1264MinMaxIntrinsic *RHSMinMax = dyn_cast<MinMaxIntrinsic>(RHSInst);1265if (LHSMinMax && RHSMinMax &&1266LHSMinMax->getPredicate() ==1267ICmpInst::getSwappedPredicate(RHSMinMax->getPredicate()) &&1268((LHSMinMax->getLHS() == RHSMinMax->getLHS() &&1269LHSMinMax->getRHS() == RHSMinMax->getRHS()) ||1270(LHSMinMax->getLHS() == RHSMinMax->getRHS() &&1271LHSMinMax->getRHS() == RHSMinMax->getLHS())))1272return std::pair(LHSMinMax->getLHS(), LHSMinMax->getRHS());1273return std::nullopt;1274}1275default:1276return std::nullopt;1277}1278}12791280Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,1281Value *LHS,1282Value *RHS) {1283Value *A, *B, *C, *D, *E, *F;1284bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C)));1285bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F)));1286if (!LHSIsSelect && !RHSIsSelect)1287return nullptr;12881289FastMathFlags FMF;1290BuilderTy::FastMathFlagGuard Guard(Builder);1291if (isa<FPMathOperator>(&I)) {1292FMF = I.getFastMathFlags();1293Builder.setFastMathFlags(FMF);1294}12951296Instruction::BinaryOps Opcode = I.getOpcode();1297SimplifyQuery Q = SQ.getWithInstruction(&I);12981299Value *Cond, *True = nullptr, *False = nullptr;13001301// Special-case for add/negate combination. Replace the zero in the negation1302// with the trailing add operand:1303// (Cond ? TVal : -N) + Z --> Cond ? True : (Z - N)1304// (Cond ? -N : FVal) + Z --> Cond ? (Z - N) : False1305auto foldAddNegate = [&](Value *TVal, Value *FVal, Value *Z) -> Value * {1306// We need an 'add' and exactly 1 arm of the select to have been simplified.1307if (Opcode != Instruction::Add || (!True && !False) || (True && False))1308return nullptr;13091310Value *N;1311if (True && match(FVal, m_Neg(m_Value(N)))) {1312Value *Sub = Builder.CreateSub(Z, N);1313return Builder.CreateSelect(Cond, True, Sub, I.getName());1314}1315if (False && match(TVal, m_Neg(m_Value(N)))) {1316Value *Sub = Builder.CreateSub(Z, N);1317return Builder.CreateSelect(Cond, Sub, False, I.getName());1318}1319return nullptr;1320};13211322if (LHSIsSelect && RHSIsSelect && A == D) {1323// (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F)1324Cond = A;1325True = simplifyBinOp(Opcode, B, E, FMF, Q);1326False = simplifyBinOp(Opcode, C, F, FMF, Q);13271328if (LHS->hasOneUse() && RHS->hasOneUse()) {1329if (False && !True)1330True = Builder.CreateBinOp(Opcode, B, E);1331else if (True && !False)1332False = Builder.CreateBinOp(Opcode, C, F);1333}1334} else if (LHSIsSelect && LHS->hasOneUse()) {1335// (A ? B : C) op Y -> A ? (B op Y) : (C op Y)1336Cond = A;1337True = simplifyBinOp(Opcode, B, RHS, FMF, Q);1338False = simplifyBinOp(Opcode, C, RHS, FMF, Q);1339if (Value *NewSel = foldAddNegate(B, C, RHS))1340return NewSel;1341} else if (RHSIsSelect && RHS->hasOneUse()) {1342// X op (D ? E : F) -> D ? (X op E) : (X op F)1343Cond = D;1344True = simplifyBinOp(Opcode, LHS, E, FMF, Q);1345False = simplifyBinOp(Opcode, LHS, F, FMF, Q);1346if (Value *NewSel = foldAddNegate(E, F, LHS))1347return NewSel;1348}13491350if (!True || !False)1351return nullptr;13521353Value *SI = Builder.CreateSelect(Cond, True, False);1354SI->takeName(&I);1355return SI;1356}13571358/// Freely adapt every user of V as-if V was changed to !V.1359/// WARNING: only if canFreelyInvertAllUsersOf() said this can be done.1360void InstCombinerImpl::freelyInvertAllUsersOf(Value *I, Value *IgnoredUser) {1361assert(!isa<Constant>(I) && "Shouldn't invert users of constant");1362for (User *U : make_early_inc_range(I->users())) {1363if (U == IgnoredUser)1364continue; // Don't consider this user.1365switch (cast<Instruction>(U)->getOpcode()) {1366case Instruction::Select: {1367auto *SI = cast<SelectInst>(U);1368SI->swapValues();1369SI->swapProfMetadata();1370break;1371}1372case Instruction::Br: {1373BranchInst *BI = cast<BranchInst>(U);1374BI->swapSuccessors(); // swaps prof metadata too1375if (BPI)1376BPI->swapSuccEdgesProbabilities(BI->getParent());1377break;1378}1379case Instruction::Xor:1380replaceInstUsesWith(cast<Instruction>(*U), I);1381// Add to worklist for DCE.1382addToWorklist(cast<Instruction>(U));1383break;1384default:1385llvm_unreachable("Got unexpected user - out of sync with "1386"canFreelyInvertAllUsersOf() ?");1387}1388}1389}13901391/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a1392/// constant zero (which is the 'negate' form).1393Value *InstCombinerImpl::dyn_castNegVal(Value *V) const {1394Value *NegV;1395if (match(V, m_Neg(m_Value(NegV))))1396return NegV;13971398// Constants can be considered to be negated values if they can be folded.1399if (ConstantInt *C = dyn_cast<ConstantInt>(V))1400return ConstantExpr::getNeg(C);14011402if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))1403if (C->getType()->getElementType()->isIntegerTy())1404return ConstantExpr::getNeg(C);14051406if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {1407for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {1408Constant *Elt = CV->getAggregateElement(i);1409if (!Elt)1410return nullptr;14111412if (isa<UndefValue>(Elt))1413continue;14141415if (!isa<ConstantInt>(Elt))1416return nullptr;1417}1418return ConstantExpr::getNeg(CV);1419}14201421// Negate integer vector splats.1422if (auto *CV = dyn_cast<Constant>(V))1423if (CV->getType()->isVectorTy() &&1424CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue())1425return ConstantExpr::getNeg(CV);14261427return nullptr;1428}14291430// Try to fold:1431// 1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))1432// -> ({s|u}itofp (int_binop x, y))1433// 2) (fp_binop ({s|u}itofp x), FpC)1434// -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))1435//1436// Assuming the sign of the cast for x/y is `OpsFromSigned`.1437Instruction *InstCombinerImpl::foldFBinOpOfIntCastsFromSign(1438BinaryOperator &BO, bool OpsFromSigned, std::array<Value *, 2> IntOps,1439Constant *Op1FpC, SmallVectorImpl<WithCache<const Value *>> &OpsKnown) {14401441Type *FPTy = BO.getType();1442Type *IntTy = IntOps[0]->getType();14431444unsigned IntSz = IntTy->getScalarSizeInBits();1445// This is the maximum number of inuse bits by the integer where the int -> fp1446// casts are exact.1447unsigned MaxRepresentableBits =1448APFloat::semanticsPrecision(FPTy->getScalarType()->getFltSemantics());14491450// Preserve known number of leading bits. This can allow us to trivial nsw/nuw1451// checks later on.1452unsigned NumUsedLeadingBits[2] = {IntSz, IntSz};14531454// NB: This only comes up if OpsFromSigned is true, so there is no need to1455// cache if between calls to `foldFBinOpOfIntCastsFromSign`.1456auto IsNonZero = [&](unsigned OpNo) -> bool {1457if (OpsKnown[OpNo].hasKnownBits() &&1458OpsKnown[OpNo].getKnownBits(SQ).isNonZero())1459return true;1460return isKnownNonZero(IntOps[OpNo], SQ);1461};14621463auto IsNonNeg = [&](unsigned OpNo) -> bool {1464// NB: This matches the impl in ValueTracking, we just try to use cached1465// knownbits here. If we ever start supporting WithCache for1466// `isKnownNonNegative`, change this to an explicit call.1467return OpsKnown[OpNo].getKnownBits(SQ).isNonNegative();1468};14691470// Check if we know for certain that ({s|u}itofp op) is exact.1471auto IsValidPromotion = [&](unsigned OpNo) -> bool {1472// Can we treat this operand as the desired sign?1473if (OpsFromSigned != isa<SIToFPInst>(BO.getOperand(OpNo)) &&1474!IsNonNeg(OpNo))1475return false;14761477// If fp precision >= bitwidth(op) then its exact.1478// NB: This is slightly conservative for `sitofp`. For signed conversion, we1479// can handle `MaxRepresentableBits == IntSz - 1` as the sign bit will be1480// handled specially. We can't, however, increase the bound arbitrarily for1481// `sitofp` as for larger sizes, it won't sign extend.1482if (MaxRepresentableBits < IntSz) {1483// Otherwise if its signed cast check that fp precisions >= bitwidth(op) -1484// numSignBits(op).1485// TODO: If we add support for `WithCache` in `ComputeNumSignBits`, change1486// `IntOps[OpNo]` arguments to `KnownOps[OpNo]`.1487if (OpsFromSigned)1488NumUsedLeadingBits[OpNo] = IntSz - ComputeNumSignBits(IntOps[OpNo]);1489// Finally for unsigned check that fp precision >= bitwidth(op) -1490// numLeadingZeros(op).1491else {1492NumUsedLeadingBits[OpNo] =1493IntSz - OpsKnown[OpNo].getKnownBits(SQ).countMinLeadingZeros();1494}1495}1496// NB: We could also check if op is known to be a power of 2 or zero (which1497// will always be representable). Its unlikely, however, that is we are1498// unable to bound op in any way we will be able to pass the overflow checks1499// later on.15001501if (MaxRepresentableBits < NumUsedLeadingBits[OpNo])1502return false;1503// Signed + Mul also requires that op is non-zero to avoid -0 cases.1504return !OpsFromSigned || BO.getOpcode() != Instruction::FMul ||1505IsNonZero(OpNo);1506};15071508// If we have a constant rhs, see if we can losslessly convert it to an int.1509if (Op1FpC != nullptr) {1510// Signed + Mul req non-zero1511if (OpsFromSigned && BO.getOpcode() == Instruction::FMul &&1512!match(Op1FpC, m_NonZeroFP()))1513return nullptr;15141515Constant *Op1IntC = ConstantFoldCastOperand(1516OpsFromSigned ? Instruction::FPToSI : Instruction::FPToUI, Op1FpC,1517IntTy, DL);1518if (Op1IntC == nullptr)1519return nullptr;1520if (ConstantFoldCastOperand(OpsFromSigned ? Instruction::SIToFP1521: Instruction::UIToFP,1522Op1IntC, FPTy, DL) != Op1FpC)1523return nullptr;15241525// First try to keep sign of cast the same.1526IntOps[1] = Op1IntC;1527}15281529// Ensure lhs/rhs integer types match.1530if (IntTy != IntOps[1]->getType())1531return nullptr;15321533if (Op1FpC == nullptr) {1534if (!IsValidPromotion(1))1535return nullptr;1536}1537if (!IsValidPromotion(0))1538return nullptr;15391540// Final we check if the integer version of the binop will not overflow.1541BinaryOperator::BinaryOps IntOpc;1542// Because of the precision check, we can often rule out overflows.1543bool NeedsOverflowCheck = true;1544// Try to conservatively rule out overflow based on the already done precision1545// checks.1546unsigned OverflowMaxOutputBits = OpsFromSigned ? 2 : 1;1547unsigned OverflowMaxCurBits =1548std::max(NumUsedLeadingBits[0], NumUsedLeadingBits[1]);1549bool OutputSigned = OpsFromSigned;1550switch (BO.getOpcode()) {1551case Instruction::FAdd:1552IntOpc = Instruction::Add;1553OverflowMaxOutputBits += OverflowMaxCurBits;1554break;1555case Instruction::FSub:1556IntOpc = Instruction::Sub;1557OverflowMaxOutputBits += OverflowMaxCurBits;1558break;1559case Instruction::FMul:1560IntOpc = Instruction::Mul;1561OverflowMaxOutputBits += OverflowMaxCurBits * 2;1562break;1563default:1564llvm_unreachable("Unsupported binop");1565}1566// The precision check may have already ruled out overflow.1567if (OverflowMaxOutputBits < IntSz) {1568NeedsOverflowCheck = false;1569// We can bound unsigned overflow from sub to in range signed value (this is1570// what allows us to avoid the overflow check for sub).1571if (IntOpc == Instruction::Sub)1572OutputSigned = true;1573}15741575// Precision check did not rule out overflow, so need to check.1576// TODO: If we add support for `WithCache` in `willNotOverflow`, change1577// `IntOps[...]` arguments to `KnownOps[...]`.1578if (NeedsOverflowCheck &&1579!willNotOverflow(IntOpc, IntOps[0], IntOps[1], BO, OutputSigned))1580return nullptr;15811582Value *IntBinOp = Builder.CreateBinOp(IntOpc, IntOps[0], IntOps[1]);1583if (auto *IntBO = dyn_cast<BinaryOperator>(IntBinOp)) {1584IntBO->setHasNoSignedWrap(OutputSigned);1585IntBO->setHasNoUnsignedWrap(!OutputSigned);1586}1587if (OutputSigned)1588return new SIToFPInst(IntBinOp, FPTy);1589return new UIToFPInst(IntBinOp, FPTy);1590}15911592// Try to fold:1593// 1) (fp_binop ({s|u}itofp x), ({s|u}itofp y))1594// -> ({s|u}itofp (int_binop x, y))1595// 2) (fp_binop ({s|u}itofp x), FpC)1596// -> ({s|u}itofp (int_binop x, (fpto{s|u}i FpC)))1597Instruction *InstCombinerImpl::foldFBinOpOfIntCasts(BinaryOperator &BO) {1598std::array<Value *, 2> IntOps = {nullptr, nullptr};1599Constant *Op1FpC = nullptr;1600// Check for:1601// 1) (binop ({s|u}itofp x), ({s|u}itofp y))1602// 2) (binop ({s|u}itofp x), FpC)1603if (!match(BO.getOperand(0), m_SIToFP(m_Value(IntOps[0]))) &&1604!match(BO.getOperand(0), m_UIToFP(m_Value(IntOps[0]))))1605return nullptr;16061607if (!match(BO.getOperand(1), m_Constant(Op1FpC)) &&1608!match(BO.getOperand(1), m_SIToFP(m_Value(IntOps[1]))) &&1609!match(BO.getOperand(1), m_UIToFP(m_Value(IntOps[1]))))1610return nullptr;16111612// Cache KnownBits a bit to potentially save some analysis.1613SmallVector<WithCache<const Value *>, 2> OpsKnown = {IntOps[0], IntOps[1]};16141615// Try treating x/y as coming from both `uitofp` and `sitofp`. There are1616// different constraints depending on the sign of the cast.1617// NB: `(uitofp nneg X)` == `(sitofp nneg X)`.1618if (Instruction *R = foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/false,1619IntOps, Op1FpC, OpsKnown))1620return R;1621return foldFBinOpOfIntCastsFromSign(BO, /*OpsFromSigned=*/true, IntOps,1622Op1FpC, OpsKnown);1623}16241625/// A binop with a constant operand and a sign-extended boolean operand may be1626/// converted into a select of constants by applying the binary operation to1627/// the constant with the two possible values of the extended boolean (0 or -1).1628Instruction *InstCombinerImpl::foldBinopOfSextBoolToSelect(BinaryOperator &BO) {1629// TODO: Handle non-commutative binop (constant is operand 0).1630// TODO: Handle zext.1631// TODO: Peek through 'not' of cast.1632Value *BO0 = BO.getOperand(0);1633Value *BO1 = BO.getOperand(1);1634Value *X;1635Constant *C;1636if (!match(BO0, m_SExt(m_Value(X))) || !match(BO1, m_ImmConstant(C)) ||1637!X->getType()->isIntOrIntVectorTy(1))1638return nullptr;16391640// bo (sext i1 X), C --> select X, (bo -1, C), (bo 0, C)1641Constant *Ones = ConstantInt::getAllOnesValue(BO.getType());1642Constant *Zero = ConstantInt::getNullValue(BO.getType());1643Value *TVal = Builder.CreateBinOp(BO.getOpcode(), Ones, C);1644Value *FVal = Builder.CreateBinOp(BO.getOpcode(), Zero, C);1645return SelectInst::Create(X, TVal, FVal);1646}16471648static Constant *constantFoldOperationIntoSelectOperand(Instruction &I,1649SelectInst *SI,1650bool IsTrueArm) {1651SmallVector<Constant *> ConstOps;1652for (Value *Op : I.operands()) {1653CmpInst::Predicate Pred;1654Constant *C = nullptr;1655if (Op == SI) {1656C = dyn_cast<Constant>(IsTrueArm ? SI->getTrueValue()1657: SI->getFalseValue());1658} else if (match(SI->getCondition(),1659m_ICmp(Pred, m_Specific(Op), m_Constant(C))) &&1660Pred == (IsTrueArm ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&1661isGuaranteedNotToBeUndefOrPoison(C)) {1662// Pass1663} else {1664C = dyn_cast<Constant>(Op);1665}1666if (C == nullptr)1667return nullptr;16681669ConstOps.push_back(C);1670}16711672return ConstantFoldInstOperands(&I, ConstOps, I.getDataLayout());1673}16741675static Value *foldOperationIntoSelectOperand(Instruction &I, SelectInst *SI,1676Value *NewOp, InstCombiner &IC) {1677Instruction *Clone = I.clone();1678Clone->replaceUsesOfWith(SI, NewOp);1679Clone->dropUBImplyingAttrsAndMetadata();1680IC.InsertNewInstBefore(Clone, SI->getIterator());1681return Clone;1682}16831684Instruction *InstCombinerImpl::FoldOpIntoSelect(Instruction &Op, SelectInst *SI,1685bool FoldWithMultiUse) {1686// Don't modify shared select instructions unless set FoldWithMultiUse1687if (!SI->hasOneUse() && !FoldWithMultiUse)1688return nullptr;16891690Value *TV = SI->getTrueValue();1691Value *FV = SI->getFalseValue();1692if (!(isa<Constant>(TV) || isa<Constant>(FV)))1693return nullptr;16941695// Bool selects with constant operands can be folded to logical ops.1696if (SI->getType()->isIntOrIntVectorTy(1))1697return nullptr;16981699// Test if a FCmpInst instruction is used exclusively by a select as1700// part of a minimum or maximum operation. If so, refrain from doing1701// any other folding. This helps out other analyses which understand1702// non-obfuscated minimum and maximum idioms. And in this case, at1703// least one of the comparison operands has at least one user besides1704// the compare (the select), which would often largely negate the1705// benefit of folding anyway.1706if (auto *CI = dyn_cast<FCmpInst>(SI->getCondition())) {1707if (CI->hasOneUse()) {1708Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);1709if ((TV == Op0 && FV == Op1) || (FV == Op0 && TV == Op1))1710return nullptr;1711}1712}17131714// Make sure that one of the select arms constant folds successfully.1715Value *NewTV = constantFoldOperationIntoSelectOperand(Op, SI, /*IsTrueArm*/ true);1716Value *NewFV = constantFoldOperationIntoSelectOperand(Op, SI, /*IsTrueArm*/ false);1717if (!NewTV && !NewFV)1718return nullptr;17191720// Create an instruction for the arm that did not fold.1721if (!NewTV)1722NewTV = foldOperationIntoSelectOperand(Op, SI, TV, *this);1723if (!NewFV)1724NewFV = foldOperationIntoSelectOperand(Op, SI, FV, *this);1725return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);1726}17271728static Value *simplifyInstructionWithPHI(Instruction &I, PHINode *PN,1729Value *InValue, BasicBlock *InBB,1730const DataLayout &DL,1731const SimplifyQuery SQ) {1732// NB: It is a precondition of this transform that the operands be1733// phi translatable! This is usually trivially satisfied by limiting it1734// to constant ops, and for selects we do a more sophisticated check.1735SmallVector<Value *> Ops;1736for (Value *Op : I.operands()) {1737if (Op == PN)1738Ops.push_back(InValue);1739else1740Ops.push_back(Op->DoPHITranslation(PN->getParent(), InBB));1741}17421743// Don't consider the simplification successful if we get back a constant1744// expression. That's just an instruction in hiding.1745// Also reject the case where we simplify back to the phi node. We wouldn't1746// be able to remove it in that case.1747Value *NewVal = simplifyInstructionWithOperands(1748&I, Ops, SQ.getWithInstruction(InBB->getTerminator()));1749if (NewVal && NewVal != PN && !match(NewVal, m_ConstantExpr()))1750return NewVal;17511752// Check if incoming PHI value can be replaced with constant1753// based on implied condition.1754BranchInst *TerminatorBI = dyn_cast<BranchInst>(InBB->getTerminator());1755const ICmpInst *ICmp = dyn_cast<ICmpInst>(&I);1756if (TerminatorBI && TerminatorBI->isConditional() &&1757TerminatorBI->getSuccessor(0) != TerminatorBI->getSuccessor(1) && ICmp) {1758bool LHSIsTrue = TerminatorBI->getSuccessor(0) == PN->getParent();1759std::optional<bool> ImpliedCond =1760isImpliedCondition(TerminatorBI->getCondition(), ICmp->getPredicate(),1761Ops[0], Ops[1], DL, LHSIsTrue);1762if (ImpliedCond)1763return ConstantInt::getBool(I.getType(), ImpliedCond.value());1764}17651766return nullptr;1767}17681769Instruction *InstCombinerImpl::foldOpIntoPhi(Instruction &I, PHINode *PN) {1770unsigned NumPHIValues = PN->getNumIncomingValues();1771if (NumPHIValues == 0)1772return nullptr;17731774// We normally only transform phis with a single use. However, if a PHI has1775// multiple uses and they are all the same operation, we can fold *all* of the1776// uses into the PHI.1777if (!PN->hasOneUse()) {1778// Walk the use list for the instruction, comparing them to I.1779for (User *U : PN->users()) {1780Instruction *UI = cast<Instruction>(U);1781if (UI != &I && !I.isIdenticalTo(UI))1782return nullptr;1783}1784// Otherwise, we can replace *all* users with the new PHI we form.1785}17861787// Check to see whether the instruction can be folded into each phi operand.1788// If there is one operand that does not fold, remember the BB it is in.1789// If there is more than one or if *it* is a PHI, bail out.1790SmallVector<Value *> NewPhiValues;1791BasicBlock *NonSimplifiedBB = nullptr;1792Value *NonSimplifiedInVal = nullptr;1793for (unsigned i = 0; i != NumPHIValues; ++i) {1794Value *InVal = PN->getIncomingValue(i);1795BasicBlock *InBB = PN->getIncomingBlock(i);17961797if (auto *NewVal = simplifyInstructionWithPHI(I, PN, InVal, InBB, DL, SQ)) {1798NewPhiValues.push_back(NewVal);1799continue;1800}18011802if (NonSimplifiedBB) return nullptr; // More than one non-simplified value.18031804NonSimplifiedBB = InBB;1805NonSimplifiedInVal = InVal;1806NewPhiValues.push_back(nullptr);18071808// If the InVal is an invoke at the end of the pred block, then we can't1809// insert a computation after it without breaking the edge.1810if (isa<InvokeInst>(InVal))1811if (cast<Instruction>(InVal)->getParent() == NonSimplifiedBB)1812return nullptr;18131814// If the incoming non-constant value is reachable from the phis block,1815// we'll push the operation across a loop backedge. This could result in1816// an infinite combine loop, and is generally non-profitable (especially1817// if the operation was originally outside the loop).1818if (isPotentiallyReachable(PN->getParent(), NonSimplifiedBB, nullptr, &DT,1819LI))1820return nullptr;1821}18221823// If there is exactly one non-simplified value, we can insert a copy of the1824// operation in that block. However, if this is a critical edge, we would be1825// inserting the computation on some other paths (e.g. inside a loop). Only1826// do this if the pred block is unconditionally branching into the phi block.1827// Also, make sure that the pred block is not dead code.1828if (NonSimplifiedBB != nullptr) {1829BranchInst *BI = dyn_cast<BranchInst>(NonSimplifiedBB->getTerminator());1830if (!BI || !BI->isUnconditional() ||1831!DT.isReachableFromEntry(NonSimplifiedBB))1832return nullptr;1833}18341835// Okay, we can do the transformation: create the new PHI node.1836PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());1837InsertNewInstBefore(NewPN, PN->getIterator());1838NewPN->takeName(PN);1839NewPN->setDebugLoc(PN->getDebugLoc());18401841// If we are going to have to insert a new computation, do so right before the1842// predecessor's terminator.1843Instruction *Clone = nullptr;1844if (NonSimplifiedBB) {1845Clone = I.clone();1846for (Use &U : Clone->operands()) {1847if (U == PN)1848U = NonSimplifiedInVal;1849else1850U = U->DoPHITranslation(PN->getParent(), NonSimplifiedBB);1851}1852InsertNewInstBefore(Clone, NonSimplifiedBB->getTerminator()->getIterator());1853}18541855for (unsigned i = 0; i != NumPHIValues; ++i) {1856if (NewPhiValues[i])1857NewPN->addIncoming(NewPhiValues[i], PN->getIncomingBlock(i));1858else1859NewPN->addIncoming(Clone, PN->getIncomingBlock(i));1860}18611862for (User *U : make_early_inc_range(PN->users())) {1863Instruction *User = cast<Instruction>(U);1864if (User == &I) continue;1865replaceInstUsesWith(*User, NewPN);1866eraseInstFromFunction(*User);1867}18681869replaceAllDbgUsesWith(const_cast<PHINode &>(*PN),1870const_cast<PHINode &>(*NewPN),1871const_cast<PHINode &>(*PN), DT);1872return replaceInstUsesWith(I, NewPN);1873}18741875Instruction *InstCombinerImpl::foldBinopWithPhiOperands(BinaryOperator &BO) {1876// TODO: This should be similar to the incoming values check in foldOpIntoPhi:1877// we are guarding against replicating the binop in >1 predecessor.1878// This could miss matching a phi with 2 constant incoming values.1879auto *Phi0 = dyn_cast<PHINode>(BO.getOperand(0));1880auto *Phi1 = dyn_cast<PHINode>(BO.getOperand(1));1881if (!Phi0 || !Phi1 || !Phi0->hasOneUse() || !Phi1->hasOneUse() ||1882Phi0->getNumOperands() != Phi1->getNumOperands())1883return nullptr;18841885// TODO: Remove the restriction for binop being in the same block as the phis.1886if (BO.getParent() != Phi0->getParent() ||1887BO.getParent() != Phi1->getParent())1888return nullptr;18891890// Fold if there is at least one specific constant value in phi0 or phi1's1891// incoming values that comes from the same block and this specific constant1892// value can be used to do optimization for specific binary operator.1893// For example:1894// %phi0 = phi i32 [0, %bb0], [%i, %bb1]1895// %phi1 = phi i32 [%j, %bb0], [0, %bb1]1896// %add = add i32 %phi0, %phi11897// ==>1898// %add = phi i32 [%j, %bb0], [%i, %bb1]1899Constant *C = ConstantExpr::getBinOpIdentity(BO.getOpcode(), BO.getType(),1900/*AllowRHSConstant*/ false);1901if (C) {1902SmallVector<Value *, 4> NewIncomingValues;1903auto CanFoldIncomingValuePair = [&](std::tuple<Use &, Use &> T) {1904auto &Phi0Use = std::get<0>(T);1905auto &Phi1Use = std::get<1>(T);1906if (Phi0->getIncomingBlock(Phi0Use) != Phi1->getIncomingBlock(Phi1Use))1907return false;1908Value *Phi0UseV = Phi0Use.get();1909Value *Phi1UseV = Phi1Use.get();1910if (Phi0UseV == C)1911NewIncomingValues.push_back(Phi1UseV);1912else if (Phi1UseV == C)1913NewIncomingValues.push_back(Phi0UseV);1914else1915return false;1916return true;1917};19181919if (all_of(zip(Phi0->operands(), Phi1->operands()),1920CanFoldIncomingValuePair)) {1921PHINode *NewPhi =1922PHINode::Create(Phi0->getType(), Phi0->getNumOperands());1923assert(NewIncomingValues.size() == Phi0->getNumOperands() &&1924"The number of collected incoming values should equal the number "1925"of the original PHINode operands!");1926for (unsigned I = 0; I < Phi0->getNumOperands(); I++)1927NewPhi->addIncoming(NewIncomingValues[I], Phi0->getIncomingBlock(I));1928return NewPhi;1929}1930}19311932if (Phi0->getNumOperands() != 2 || Phi1->getNumOperands() != 2)1933return nullptr;19341935// Match a pair of incoming constants for one of the predecessor blocks.1936BasicBlock *ConstBB, *OtherBB;1937Constant *C0, *C1;1938if (match(Phi0->getIncomingValue(0), m_ImmConstant(C0))) {1939ConstBB = Phi0->getIncomingBlock(0);1940OtherBB = Phi0->getIncomingBlock(1);1941} else if (match(Phi0->getIncomingValue(1), m_ImmConstant(C0))) {1942ConstBB = Phi0->getIncomingBlock(1);1943OtherBB = Phi0->getIncomingBlock(0);1944} else {1945return nullptr;1946}1947if (!match(Phi1->getIncomingValueForBlock(ConstBB), m_ImmConstant(C1)))1948return nullptr;19491950// The block that we are hoisting to must reach here unconditionally.1951// Otherwise, we could be speculatively executing an expensive or1952// non-speculative op.1953auto *PredBlockBranch = dyn_cast<BranchInst>(OtherBB->getTerminator());1954if (!PredBlockBranch || PredBlockBranch->isConditional() ||1955!DT.isReachableFromEntry(OtherBB))1956return nullptr;19571958// TODO: This check could be tightened to only apply to binops (div/rem) that1959// are not safe to speculatively execute. But that could allow hoisting1960// potentially expensive instructions (fdiv for example).1961for (auto BBIter = BO.getParent()->begin(); &*BBIter != &BO; ++BBIter)1962if (!isGuaranteedToTransferExecutionToSuccessor(&*BBIter))1963return nullptr;19641965// Fold constants for the predecessor block with constant incoming values.1966Constant *NewC = ConstantFoldBinaryOpOperands(BO.getOpcode(), C0, C1, DL);1967if (!NewC)1968return nullptr;19691970// Make a new binop in the predecessor block with the non-constant incoming1971// values.1972Builder.SetInsertPoint(PredBlockBranch);1973Value *NewBO = Builder.CreateBinOp(BO.getOpcode(),1974Phi0->getIncomingValueForBlock(OtherBB),1975Phi1->getIncomingValueForBlock(OtherBB));1976if (auto *NotFoldedNewBO = dyn_cast<BinaryOperator>(NewBO))1977NotFoldedNewBO->copyIRFlags(&BO);19781979// Replace the binop with a phi of the new values. The old phis are dead.1980PHINode *NewPhi = PHINode::Create(BO.getType(), 2);1981NewPhi->addIncoming(NewBO, OtherBB);1982NewPhi->addIncoming(NewC, ConstBB);1983return NewPhi;1984}19851986Instruction *InstCombinerImpl::foldBinOpIntoSelectOrPhi(BinaryOperator &I) {1987if (!isa<Constant>(I.getOperand(1)))1988return nullptr;19891990if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {1991if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))1992return NewSel;1993} else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {1994if (Instruction *NewPhi = foldOpIntoPhi(I, PN))1995return NewPhi;1996}1997return nullptr;1998}19992000static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {2001// If this GEP has only 0 indices, it is the same pointer as2002// Src. If Src is not a trivial GEP too, don't combine2003// the indices.2004if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&2005!Src.hasOneUse())2006return false;2007return true;2008}20092010Instruction *InstCombinerImpl::foldVectorBinop(BinaryOperator &Inst) {2011if (!isa<VectorType>(Inst.getType()))2012return nullptr;20132014BinaryOperator::BinaryOps Opcode = Inst.getOpcode();2015Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);2016assert(cast<VectorType>(LHS->getType())->getElementCount() ==2017cast<VectorType>(Inst.getType())->getElementCount());2018assert(cast<VectorType>(RHS->getType())->getElementCount() ==2019cast<VectorType>(Inst.getType())->getElementCount());20202021// If both operands of the binop are vector concatenations, then perform the2022// narrow binop on each pair of the source operands followed by concatenation2023// of the results.2024Value *L0, *L1, *R0, *R1;2025ArrayRef<int> Mask;2026if (match(LHS, m_Shuffle(m_Value(L0), m_Value(L1), m_Mask(Mask))) &&2027match(RHS, m_Shuffle(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) &&2028LHS->hasOneUse() && RHS->hasOneUse() &&2029cast<ShuffleVectorInst>(LHS)->isConcat() &&2030cast<ShuffleVectorInst>(RHS)->isConcat()) {2031// This transform does not have the speculative execution constraint as2032// below because the shuffle is a concatenation. The new binops are2033// operating on exactly the same elements as the existing binop.2034// TODO: We could ease the mask requirement to allow different undef lanes,2035// but that requires an analysis of the binop-with-undef output value.2036Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0);2037if (auto *BO = dyn_cast<BinaryOperator>(NewBO0))2038BO->copyIRFlags(&Inst);2039Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1);2040if (auto *BO = dyn_cast<BinaryOperator>(NewBO1))2041BO->copyIRFlags(&Inst);2042return new ShuffleVectorInst(NewBO0, NewBO1, Mask);2043}20442045auto createBinOpReverse = [&](Value *X, Value *Y) {2046Value *V = Builder.CreateBinOp(Opcode, X, Y, Inst.getName());2047if (auto *BO = dyn_cast<BinaryOperator>(V))2048BO->copyIRFlags(&Inst);2049Module *M = Inst.getModule();2050Function *F =2051Intrinsic::getDeclaration(M, Intrinsic::vector_reverse, V->getType());2052return CallInst::Create(F, V);2053};20542055// NOTE: Reverse shuffles don't require the speculative execution protection2056// below because they don't affect which lanes take part in the computation.20572058Value *V1, *V2;2059if (match(LHS, m_VecReverse(m_Value(V1)))) {2060// Op(rev(V1), rev(V2)) -> rev(Op(V1, V2))2061if (match(RHS, m_VecReverse(m_Value(V2))) &&2062(LHS->hasOneUse() || RHS->hasOneUse() ||2063(LHS == RHS && LHS->hasNUses(2))))2064return createBinOpReverse(V1, V2);20652066// Op(rev(V1), RHSSplat)) -> rev(Op(V1, RHSSplat))2067if (LHS->hasOneUse() && isSplatValue(RHS))2068return createBinOpReverse(V1, RHS);2069}2070// Op(LHSSplat, rev(V2)) -> rev(Op(LHSSplat, V2))2071else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))2072return createBinOpReverse(LHS, V2);20732074// It may not be safe to reorder shuffles and things like div, urem, etc.2075// because we may trap when executing those ops on unknown vector elements.2076// See PR20059.2077if (!isSafeToSpeculativelyExecute(&Inst))2078return nullptr;20792080auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) {2081Value *XY = Builder.CreateBinOp(Opcode, X, Y);2082if (auto *BO = dyn_cast<BinaryOperator>(XY))2083BO->copyIRFlags(&Inst);2084return new ShuffleVectorInst(XY, M);2085};20862087// If both arguments of the binary operation are shuffles that use the same2088// mask and shuffle within a single vector, move the shuffle after the binop.2089if (match(LHS, m_Shuffle(m_Value(V1), m_Poison(), m_Mask(Mask))) &&2090match(RHS, m_Shuffle(m_Value(V2), m_Poison(), m_SpecificMask(Mask))) &&2091V1->getType() == V2->getType() &&2092(LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {2093// Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)2094return createBinOpShuffle(V1, V2, Mask);2095}20962097// If both arguments of a commutative binop are select-shuffles that use the2098// same mask with commuted operands, the shuffles are unnecessary.2099if (Inst.isCommutative() &&2100match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) &&2101match(RHS,2102m_Shuffle(m_Specific(V2), m_Specific(V1), m_SpecificMask(Mask)))) {2103auto *LShuf = cast<ShuffleVectorInst>(LHS);2104auto *RShuf = cast<ShuffleVectorInst>(RHS);2105// TODO: Allow shuffles that contain undefs in the mask?2106// That is legal, but it reduces undef knowledge.2107// TODO: Allow arbitrary shuffles by shuffling after binop?2108// That might be legal, but we have to deal with poison.2109if (LShuf->isSelect() &&2110!is_contained(LShuf->getShuffleMask(), PoisonMaskElem) &&2111RShuf->isSelect() &&2112!is_contained(RShuf->getShuffleMask(), PoisonMaskElem)) {2113// Example:2114// LHS = shuffle V1, V2, <0, 5, 6, 3>2115// RHS = shuffle V2, V1, <0, 5, 6, 3>2116// LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V22117Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2);2118NewBO->copyIRFlags(&Inst);2119return NewBO;2120}2121}21222123// If one argument is a shuffle within one vector and the other is a constant,2124// try moving the shuffle after the binary operation. This canonicalization2125// intends to move shuffles closer to other shuffles and binops closer to2126// other binops, so they can be folded. It may also enable demanded elements2127// transforms.2128Constant *C;2129auto *InstVTy = dyn_cast<FixedVectorType>(Inst.getType());2130if (InstVTy &&2131match(&Inst, m_c_BinOp(m_OneUse(m_Shuffle(m_Value(V1), m_Poison(),2132m_Mask(Mask))),2133m_ImmConstant(C))) &&2134cast<FixedVectorType>(V1->getType())->getNumElements() <=2135InstVTy->getNumElements()) {2136assert(InstVTy->getScalarType() == V1->getType()->getScalarType() &&2137"Shuffle should not change scalar type");21382139// Find constant NewC that has property:2140// shuffle(NewC, ShMask) = C2141// If such constant does not exist (example: ShMask=<0,0> and C=<1,2>)2142// reorder is not possible. A 1-to-1 mapping is not required. Example:2143// ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef>2144bool ConstOp1 = isa<Constant>(RHS);2145ArrayRef<int> ShMask = Mask;2146unsigned SrcVecNumElts =2147cast<FixedVectorType>(V1->getType())->getNumElements();2148PoisonValue *PoisonScalar = PoisonValue::get(C->getType()->getScalarType());2149SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, PoisonScalar);2150bool MayChange = true;2151unsigned NumElts = InstVTy->getNumElements();2152for (unsigned I = 0; I < NumElts; ++I) {2153Constant *CElt = C->getAggregateElement(I);2154if (ShMask[I] >= 0) {2155assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle");2156Constant *NewCElt = NewVecC[ShMask[I]];2157// Bail out if:2158// 1. The constant vector contains a constant expression.2159// 2. The shuffle needs an element of the constant vector that can't2160// be mapped to a new constant vector.2161// 3. This is a widening shuffle that copies elements of V1 into the2162// extended elements (extending with poison is allowed).2163if (!CElt || (!isa<PoisonValue>(NewCElt) && NewCElt != CElt) ||2164I >= SrcVecNumElts) {2165MayChange = false;2166break;2167}2168NewVecC[ShMask[I]] = CElt;2169}2170// If this is a widening shuffle, we must be able to extend with poison2171// elements. If the original binop does not produce a poison in the high2172// lanes, then this transform is not safe.2173// Similarly for poison lanes due to the shuffle mask, we can only2174// transform binops that preserve poison.2175// TODO: We could shuffle those non-poison constant values into the2176// result by using a constant vector (rather than an poison vector)2177// as operand 1 of the new binop, but that might be too aggressive2178// for target-independent shuffle creation.2179if (I >= SrcVecNumElts || ShMask[I] < 0) {2180Constant *MaybePoison =2181ConstOp12182? ConstantFoldBinaryOpOperands(Opcode, PoisonScalar, CElt, DL)2183: ConstantFoldBinaryOpOperands(Opcode, CElt, PoisonScalar, DL);2184if (!MaybePoison || !isa<PoisonValue>(MaybePoison)) {2185MayChange = false;2186break;2187}2188}2189}2190if (MayChange) {2191Constant *NewC = ConstantVector::get(NewVecC);2192// It may not be safe to execute a binop on a vector with poison elements2193// because the entire instruction can be folded to undef or create poison2194// that did not exist in the original code.2195// TODO: The shift case should not be necessary.2196if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1))2197NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);21982199// Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)2200// Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)2201Value *NewLHS = ConstOp1 ? V1 : NewC;2202Value *NewRHS = ConstOp1 ? NewC : V1;2203return createBinOpShuffle(NewLHS, NewRHS, Mask);2204}2205}22062207// Try to reassociate to sink a splat shuffle after a binary operation.2208if (Inst.isAssociative() && Inst.isCommutative()) {2209// Canonicalize shuffle operand as LHS.2210if (isa<ShuffleVectorInst>(RHS))2211std::swap(LHS, RHS);22122213Value *X;2214ArrayRef<int> MaskC;2215int SplatIndex;2216Value *Y, *OtherOp;2217if (!match(LHS,2218m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) ||2219!match(MaskC, m_SplatOrPoisonMask(SplatIndex)) ||2220X->getType() != Inst.getType() ||2221!match(RHS, m_OneUse(m_BinOp(Opcode, m_Value(Y), m_Value(OtherOp)))))2222return nullptr;22232224// FIXME: This may not be safe if the analysis allows undef elements. By2225// moving 'Y' before the splat shuffle, we are implicitly assuming2226// that it is not undef/poison at the splat index.2227if (isSplatValue(OtherOp, SplatIndex)) {2228std::swap(Y, OtherOp);2229} else if (!isSplatValue(Y, SplatIndex)) {2230return nullptr;2231}22322233// X and Y are splatted values, so perform the binary operation on those2234// values followed by a splat followed by the 2nd binary operation:2235// bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp2236Value *NewBO = Builder.CreateBinOp(Opcode, X, Y);2237SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);2238Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask);2239Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp);22402241// Intersect FMF on both new binops. Other (poison-generating) flags are2242// dropped to be safe.2243if (isa<FPMathOperator>(R)) {2244R->copyFastMathFlags(&Inst);2245R->andIRFlags(RHS);2246}2247if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO))2248NewInstBO->copyIRFlags(R);2249return R;2250}22512252return nullptr;2253}22542255/// Try to narrow the width of a binop if at least 1 operand is an extend of2256/// of a value. This requires a potentially expensive known bits check to make2257/// sure the narrow op does not overflow.2258Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) {2259// We need at least one extended operand.2260Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);22612262// If this is a sub, we swap the operands since we always want an extension2263// on the RHS. The LHS can be an extension or a constant.2264if (BO.getOpcode() == Instruction::Sub)2265std::swap(Op0, Op1);22662267Value *X;2268bool IsSext = match(Op0, m_SExt(m_Value(X)));2269if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))2270return nullptr;22712272// If both operands are the same extension from the same source type and we2273// can eliminate at least one (hasOneUse), this might work.2274CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;2275Value *Y;2276if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&2277cast<Operator>(Op1)->getOpcode() == CastOpc &&2278(Op0->hasOneUse() || Op1->hasOneUse()))) {2279// If that did not match, see if we have a suitable constant operand.2280// Truncating and extending must produce the same constant.2281Constant *WideC;2282if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))2283return nullptr;2284Constant *NarrowC = getLosslessTrunc(WideC, X->getType(), CastOpc);2285if (!NarrowC)2286return nullptr;2287Y = NarrowC;2288}22892290// Swap back now that we found our operands.2291if (BO.getOpcode() == Instruction::Sub)2292std::swap(X, Y);22932294// Both operands have narrow versions. Last step: the math must not overflow2295// in the narrow width.2296if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))2297return nullptr;22982299// bo (ext X), (ext Y) --> ext (bo X, Y)2300// bo (ext X), C --> ext (bo X, C')2301Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");2302if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {2303if (IsSext)2304NewBinOp->setHasNoSignedWrap();2305else2306NewBinOp->setHasNoUnsignedWrap();2307}2308return CastInst::Create(CastOpc, NarrowBO, BO.getType());2309}23102311static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2) {2312return GEP1.isInBounds() && GEP2.isInBounds();2313}23142315/// Thread a GEP operation with constant indices through the constant true/false2316/// arms of a select.2317static Instruction *foldSelectGEP(GetElementPtrInst &GEP,2318InstCombiner::BuilderTy &Builder) {2319if (!GEP.hasAllConstantIndices())2320return nullptr;23212322Instruction *Sel;2323Value *Cond;2324Constant *TrueC, *FalseC;2325if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) ||2326!match(Sel,2327m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))2328return nullptr;23292330// gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'2331// Propagate 'inbounds' and metadata from existing instructions.2332// Note: using IRBuilder to create the constants for efficiency.2333SmallVector<Value *, 4> IndexC(GEP.indices());2334GEPNoWrapFlags NW = GEP.getNoWrapFlags();2335Type *Ty = GEP.getSourceElementType();2336Value *NewTrueC = Builder.CreateGEP(Ty, TrueC, IndexC, "", NW);2337Value *NewFalseC = Builder.CreateGEP(Ty, FalseC, IndexC, "", NW);2338return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);2339}23402341// Canonicalization:2342// gep T, (gep i8, base, C1), (Index + C2) into2343// gep T, (gep i8, base, C1 + C2 * sizeof(T)), Index2344static Instruction *canonicalizeGEPOfConstGEPI8(GetElementPtrInst &GEP,2345GEPOperator *Src,2346InstCombinerImpl &IC) {2347if (GEP.getNumIndices() != 1)2348return nullptr;2349auto &DL = IC.getDataLayout();2350Value *Base;2351const APInt *C1;2352if (!match(Src, m_PtrAdd(m_Value(Base), m_APInt(C1))))2353return nullptr;2354Value *VarIndex;2355const APInt *C2;2356Type *PtrTy = Src->getType()->getScalarType();2357unsigned IndexSizeInBits = DL.getIndexTypeSizeInBits(PtrTy);2358if (!match(GEP.getOperand(1), m_AddLike(m_Value(VarIndex), m_APInt(C2))))2359return nullptr;2360if (C1->getBitWidth() != IndexSizeInBits ||2361C2->getBitWidth() != IndexSizeInBits)2362return nullptr;2363Type *BaseType = GEP.getSourceElementType();2364if (isa<ScalableVectorType>(BaseType))2365return nullptr;2366APInt TypeSize(IndexSizeInBits, DL.getTypeAllocSize(BaseType));2367APInt NewOffset = TypeSize * *C2 + *C1;2368if (NewOffset.isZero() ||2369(Src->hasOneUse() && GEP.getOperand(1)->hasOneUse())) {2370Value *GEPConst =2371IC.Builder.CreatePtrAdd(Base, IC.Builder.getInt(NewOffset));2372return GetElementPtrInst::Create(BaseType, GEPConst, VarIndex);2373}23742375return nullptr;2376}23772378Instruction *InstCombinerImpl::visitGEPOfGEP(GetElementPtrInst &GEP,2379GEPOperator *Src) {2380// Combine Indices - If the source pointer to this getelementptr instruction2381// is a getelementptr instruction with matching element type, combine the2382// indices of the two getelementptr instructions into a single instruction.2383if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))2384return nullptr;23852386if (auto *I = canonicalizeGEPOfConstGEPI8(GEP, Src, *this))2387return I;23882389// For constant GEPs, use a more general offset-based folding approach.2390Type *PtrTy = Src->getType()->getScalarType();2391if (GEP.hasAllConstantIndices() &&2392(Src->hasOneUse() || Src->hasAllConstantIndices())) {2393// Split Src into a variable part and a constant suffix.2394gep_type_iterator GTI = gep_type_begin(*Src);2395Type *BaseType = GTI.getIndexedType();2396bool IsFirstType = true;2397unsigned NumVarIndices = 0;2398for (auto Pair : enumerate(Src->indices())) {2399if (!isa<ConstantInt>(Pair.value())) {2400BaseType = GTI.getIndexedType();2401IsFirstType = false;2402NumVarIndices = Pair.index() + 1;2403}2404++GTI;2405}24062407// Determine the offset for the constant suffix of Src.2408APInt Offset(DL.getIndexTypeSizeInBits(PtrTy), 0);2409if (NumVarIndices != Src->getNumIndices()) {2410// FIXME: getIndexedOffsetInType() does not handled scalable vectors.2411if (BaseType->isScalableTy())2412return nullptr;24132414SmallVector<Value *> ConstantIndices;2415if (!IsFirstType)2416ConstantIndices.push_back(2417Constant::getNullValue(Type::getInt32Ty(GEP.getContext())));2418append_range(ConstantIndices, drop_begin(Src->indices(), NumVarIndices));2419Offset += DL.getIndexedOffsetInType(BaseType, ConstantIndices);2420}24212422// Add the offset for GEP (which is fully constant).2423if (!GEP.accumulateConstantOffset(DL, Offset))2424return nullptr;24252426APInt OffsetOld = Offset;2427// Convert the total offset back into indices.2428SmallVector<APInt> ConstIndices =2429DL.getGEPIndicesForOffset(BaseType, Offset);2430if (!Offset.isZero() || (!IsFirstType && !ConstIndices[0].isZero())) {2431// If both GEP are constant-indexed, and cannot be merged in either way,2432// convert them to a GEP of i8.2433if (Src->hasAllConstantIndices())2434return replaceInstUsesWith(2435GEP, Builder.CreateGEP(2436Builder.getInt8Ty(), Src->getOperand(0),2437Builder.getInt(OffsetOld), "",2438isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))));2439return nullptr;2440}24412442bool IsInBounds = isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP));2443SmallVector<Value *> Indices;2444append_range(Indices, drop_end(Src->indices(),2445Src->getNumIndices() - NumVarIndices));2446for (const APInt &Idx : drop_begin(ConstIndices, !IsFirstType)) {2447Indices.push_back(ConstantInt::get(GEP.getContext(), Idx));2448// Even if the total offset is inbounds, we may end up representing it2449// by first performing a larger negative offset, and then a smaller2450// positive one. The large negative offset might go out of bounds. Only2451// preserve inbounds if all signs are the same.2452IsInBounds &= Idx.isNonNegative() == ConstIndices[0].isNonNegative();2453}24542455return replaceInstUsesWith(2456GEP, Builder.CreateGEP(Src->getSourceElementType(), Src->getOperand(0),2457Indices, "", IsInBounds));2458}24592460if (Src->getResultElementType() != GEP.getSourceElementType())2461return nullptr;24622463SmallVector<Value*, 8> Indices;24642465// Find out whether the last index in the source GEP is a sequential idx.2466bool EndsWithSequential = false;2467for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);2468I != E; ++I)2469EndsWithSequential = I.isSequential();24702471// Can we combine the two pointer arithmetics offsets?2472if (EndsWithSequential) {2473// Replace: gep (gep %P, long B), long A, ...2474// With: T = long A+B; gep %P, T, ...2475Value *SO1 = Src->getOperand(Src->getNumOperands()-1);2476Value *GO1 = GEP.getOperand(1);24772478// If they aren't the same type, then the input hasn't been processed2479// by the loop above yet (which canonicalizes sequential index types to2480// intptr_t). Just avoid transforming this until the input has been2481// normalized.2482if (SO1->getType() != GO1->getType())2483return nullptr;24842485Value *Sum =2486simplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));2487// Only do the combine when we are sure the cost after the2488// merge is never more than that before the merge.2489if (Sum == nullptr)2490return nullptr;24912492// Update the GEP in place if possible.2493if (Src->getNumOperands() == 2) {2494GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)));2495replaceOperand(GEP, 0, Src->getOperand(0));2496replaceOperand(GEP, 1, Sum);2497return &GEP;2498}2499Indices.append(Src->op_begin()+1, Src->op_end()-1);2500Indices.push_back(Sum);2501Indices.append(GEP.op_begin()+2, GEP.op_end());2502} else if (isa<Constant>(*GEP.idx_begin()) &&2503cast<Constant>(*GEP.idx_begin())->isNullValue() &&2504Src->getNumOperands() != 1) {2505// Otherwise we can do the fold if the first index of the GEP is a zero2506Indices.append(Src->op_begin()+1, Src->op_end());2507Indices.append(GEP.idx_begin()+1, GEP.idx_end());2508}25092510if (!Indices.empty())2511return replaceInstUsesWith(2512GEP, Builder.CreateGEP(2513Src->getSourceElementType(), Src->getOperand(0), Indices, "",2514isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))));25152516return nullptr;2517}25182519Value *InstCombiner::getFreelyInvertedImpl(Value *V, bool WillInvertAllUses,2520BuilderTy *Builder,2521bool &DoesConsume, unsigned Depth) {2522static Value *const NonNull = reinterpret_cast<Value *>(uintptr_t(1));2523// ~(~(X)) -> X.2524Value *A, *B;2525if (match(V, m_Not(m_Value(A)))) {2526DoesConsume = true;2527return A;2528}25292530Constant *C;2531// Constants can be considered to be not'ed values.2532if (match(V, m_ImmConstant(C)))2533return ConstantExpr::getNot(C);25342535if (Depth++ >= MaxAnalysisRecursionDepth)2536return nullptr;25372538// The rest of the cases require that we invert all uses so don't bother2539// doing the analysis if we know we can't use the result.2540if (!WillInvertAllUses)2541return nullptr;25422543// Compares can be inverted if all of their uses are being modified to use2544// the ~V.2545if (auto *I = dyn_cast<CmpInst>(V)) {2546if (Builder != nullptr)2547return Builder->CreateCmp(I->getInversePredicate(), I->getOperand(0),2548I->getOperand(1));2549return NonNull;2550}25512552// If `V` is of the form `A + B` then `-1 - V` can be folded into2553// `(-1 - B) - A` if we are willing to invert all of the uses.2554if (match(V, m_Add(m_Value(A), m_Value(B)))) {2555if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,2556DoesConsume, Depth))2557return Builder ? Builder->CreateSub(BV, A) : NonNull;2558if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,2559DoesConsume, Depth))2560return Builder ? Builder->CreateSub(AV, B) : NonNull;2561return nullptr;2562}25632564// If `V` is of the form `A ^ ~B` then `~(A ^ ~B)` can be folded2565// into `A ^ B` if we are willing to invert all of the uses.2566if (match(V, m_Xor(m_Value(A), m_Value(B)))) {2567if (auto *BV = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,2568DoesConsume, Depth))2569return Builder ? Builder->CreateXor(A, BV) : NonNull;2570if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,2571DoesConsume, Depth))2572return Builder ? Builder->CreateXor(AV, B) : NonNull;2573return nullptr;2574}25752576// If `V` is of the form `B - A` then `-1 - V` can be folded into2577// `A + (-1 - B)` if we are willing to invert all of the uses.2578if (match(V, m_Sub(m_Value(A), m_Value(B)))) {2579if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,2580DoesConsume, Depth))2581return Builder ? Builder->CreateAdd(AV, B) : NonNull;2582return nullptr;2583}25842585// If `V` is of the form `(~A) s>> B` then `~((~A) s>> B)` can be folded2586// into `A s>> B` if we are willing to invert all of the uses.2587if (match(V, m_AShr(m_Value(A), m_Value(B)))) {2588if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,2589DoesConsume, Depth))2590return Builder ? Builder->CreateAShr(AV, B) : NonNull;2591return nullptr;2592}25932594Value *Cond;2595// LogicOps are special in that we canonicalize them at the cost of an2596// instruction.2597bool IsSelect = match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&2598!shouldAvoidAbsorbingNotIntoSelect(*cast<SelectInst>(V));2599// Selects/min/max with invertible operands are freely invertible2600if (IsSelect || match(V, m_MaxOrMin(m_Value(A), m_Value(B)))) {2601bool LocalDoesConsume = DoesConsume;2602if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder*/ nullptr,2603LocalDoesConsume, Depth))2604return nullptr;2605if (Value *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,2606LocalDoesConsume, Depth)) {2607DoesConsume = LocalDoesConsume;2608if (Builder != nullptr) {2609Value *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,2610DoesConsume, Depth);2611assert(NotB != nullptr &&2612"Unable to build inverted value for known freely invertable op");2613if (auto *II = dyn_cast<IntrinsicInst>(V))2614return Builder->CreateBinaryIntrinsic(2615getInverseMinMaxIntrinsic(II->getIntrinsicID()), NotA, NotB);2616return Builder->CreateSelect(Cond, NotA, NotB);2617}2618return NonNull;2619}2620}26212622if (PHINode *PN = dyn_cast<PHINode>(V)) {2623bool LocalDoesConsume = DoesConsume;2624SmallVector<std::pair<Value *, BasicBlock *>, 8> IncomingValues;2625for (Use &U : PN->operands()) {2626BasicBlock *IncomingBlock = PN->getIncomingBlock(U);2627Value *NewIncomingVal = getFreelyInvertedImpl(2628U.get(), /*WillInvertAllUses=*/false,2629/*Builder=*/nullptr, LocalDoesConsume, MaxAnalysisRecursionDepth - 1);2630if (NewIncomingVal == nullptr)2631return nullptr;2632// Make sure that we can safely erase the original PHI node.2633if (NewIncomingVal == V)2634return nullptr;2635if (Builder != nullptr)2636IncomingValues.emplace_back(NewIncomingVal, IncomingBlock);2637}26382639DoesConsume = LocalDoesConsume;2640if (Builder != nullptr) {2641IRBuilderBase::InsertPointGuard Guard(*Builder);2642Builder->SetInsertPoint(PN);2643PHINode *NewPN =2644Builder->CreatePHI(PN->getType(), PN->getNumIncomingValues());2645for (auto [Val, Pred] : IncomingValues)2646NewPN->addIncoming(Val, Pred);2647return NewPN;2648}2649return NonNull;2650}26512652if (match(V, m_SExtLike(m_Value(A)))) {2653if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,2654DoesConsume, Depth))2655return Builder ? Builder->CreateSExt(AV, V->getType()) : NonNull;2656return nullptr;2657}26582659if (match(V, m_Trunc(m_Value(A)))) {2660if (auto *AV = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,2661DoesConsume, Depth))2662return Builder ? Builder->CreateTrunc(AV, V->getType()) : NonNull;2663return nullptr;2664}26652666// De Morgan's Laws:2667// (~(A | B)) -> (~A & ~B)2668// (~(A & B)) -> (~A | ~B)2669auto TryInvertAndOrUsingDeMorgan = [&](Instruction::BinaryOps Opcode,2670bool IsLogical, Value *A,2671Value *B) -> Value * {2672bool LocalDoesConsume = DoesConsume;2673if (!getFreelyInvertedImpl(B, B->hasOneUse(), /*Builder=*/nullptr,2674LocalDoesConsume, Depth))2675return nullptr;2676if (auto *NotA = getFreelyInvertedImpl(A, A->hasOneUse(), Builder,2677LocalDoesConsume, Depth)) {2678auto *NotB = getFreelyInvertedImpl(B, B->hasOneUse(), Builder,2679LocalDoesConsume, Depth);2680DoesConsume = LocalDoesConsume;2681if (IsLogical)2682return Builder ? Builder->CreateLogicalOp(Opcode, NotA, NotB) : NonNull;2683return Builder ? Builder->CreateBinOp(Opcode, NotA, NotB) : NonNull;2684}26852686return nullptr;2687};26882689if (match(V, m_Or(m_Value(A), m_Value(B))))2690return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/false, A,2691B);26922693if (match(V, m_And(m_Value(A), m_Value(B))))2694return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/false, A,2695B);26962697if (match(V, m_LogicalOr(m_Value(A), m_Value(B))))2698return TryInvertAndOrUsingDeMorgan(Instruction::And, /*IsLogical=*/true, A,2699B);27002701if (match(V, m_LogicalAnd(m_Value(A), m_Value(B))))2702return TryInvertAndOrUsingDeMorgan(Instruction::Or, /*IsLogical=*/true, A,2703B);27042705return nullptr;2706}27072708Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) {2709Value *PtrOp = GEP.getOperand(0);2710SmallVector<Value *, 8> Indices(GEP.indices());2711Type *GEPType = GEP.getType();2712Type *GEPEltType = GEP.getSourceElementType();2713if (Value *V =2714simplifyGEPInst(GEPEltType, PtrOp, Indices, GEP.getNoWrapFlags(),2715SQ.getWithInstruction(&GEP)))2716return replaceInstUsesWith(GEP, V);27172718// For vector geps, use the generic demanded vector support.2719// Skip if GEP return type is scalable. The number of elements is unknown at2720// compile-time.2721if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) {2722auto VWidth = GEPFVTy->getNumElements();2723APInt PoisonElts(VWidth, 0);2724APInt AllOnesEltMask(APInt::getAllOnes(VWidth));2725if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,2726PoisonElts)) {2727if (V != &GEP)2728return replaceInstUsesWith(GEP, V);2729return &GEP;2730}27312732// TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if2733// possible (decide on canonical form for pointer broadcast), 3) exploit2734// undef elements to decrease demanded bits2735}27362737// Eliminate unneeded casts for indices, and replace indices which displace2738// by multiples of a zero size type with zero.2739bool MadeChange = false;27402741// Index width may not be the same width as pointer width.2742// Data layout chooses the right type based on supported integer types.2743Type *NewScalarIndexTy =2744DL.getIndexType(GEP.getPointerOperandType()->getScalarType());27452746gep_type_iterator GTI = gep_type_begin(GEP);2747for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;2748++I, ++GTI) {2749// Skip indices into struct types.2750if (GTI.isStruct())2751continue;27522753Type *IndexTy = (*I)->getType();2754Type *NewIndexType =2755IndexTy->isVectorTy()2756? VectorType::get(NewScalarIndexTy,2757cast<VectorType>(IndexTy)->getElementCount())2758: NewScalarIndexTy;27592760// If the element type has zero size then any index over it is equivalent2761// to an index of zero, so replace it with zero if it is not zero already.2762Type *EltTy = GTI.getIndexedType();2763if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero())2764if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {2765*I = Constant::getNullValue(NewIndexType);2766MadeChange = true;2767}27682769if (IndexTy != NewIndexType) {2770// If we are using a wider index than needed for this platform, shrink2771// it to what we need. If narrower, sign-extend it to what we need.2772// This explicit cast can make subsequent optimizations more obvious.2773*I = Builder.CreateIntCast(*I, NewIndexType, true);2774MadeChange = true;2775}2776}2777if (MadeChange)2778return &GEP;27792780// Canonicalize constant GEPs to i8 type.2781if (!GEPEltType->isIntegerTy(8) && GEP.hasAllConstantIndices()) {2782APInt Offset(DL.getIndexTypeSizeInBits(GEPType), 0);2783if (GEP.accumulateConstantOffset(DL, Offset))2784return replaceInstUsesWith(2785GEP, Builder.CreatePtrAdd(PtrOp, Builder.getInt(Offset), "",2786GEP.getNoWrapFlags()));2787}27882789// Canonicalize2790// - scalable GEPs to an explicit offset using the llvm.vscale intrinsic.2791// This has better support in BasicAA.2792// - gep i32 p, mul(O, C) -> gep i8, p, mul(O, C*4) to fold the two2793// multiplies together.2794if (GEPEltType->isScalableTy() ||2795(!GEPEltType->isIntegerTy(8) && GEP.getNumIndices() == 1 &&2796match(GEP.getOperand(1),2797m_OneUse(m_CombineOr(m_Mul(m_Value(), m_ConstantInt()),2798m_Shl(m_Value(), m_ConstantInt())))))) {2799Value *Offset = EmitGEPOffset(cast<GEPOperator>(&GEP));2800return replaceInstUsesWith(2801GEP, Builder.CreatePtrAdd(PtrOp, Offset, "", GEP.getNoWrapFlags()));2802}28032804// Check to see if the inputs to the PHI node are getelementptr instructions.2805if (auto *PN = dyn_cast<PHINode>(PtrOp)) {2806auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));2807if (!Op1)2808return nullptr;28092810// Don't fold a GEP into itself through a PHI node. This can only happen2811// through the back-edge of a loop. Folding a GEP into itself means that2812// the value of the previous iteration needs to be stored in the meantime,2813// thus requiring an additional register variable to be live, but not2814// actually achieving anything (the GEP still needs to be executed once per2815// loop iteration).2816if (Op1 == &GEP)2817return nullptr;28182819int DI = -1;28202821for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {2822auto *Op2 = dyn_cast<GetElementPtrInst>(*I);2823if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands() ||2824Op1->getSourceElementType() != Op2->getSourceElementType())2825return nullptr;28262827// As for Op1 above, don't try to fold a GEP into itself.2828if (Op2 == &GEP)2829return nullptr;28302831// Keep track of the type as we walk the GEP.2832Type *CurTy = nullptr;28332834for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {2835if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())2836return nullptr;28372838if (Op1->getOperand(J) != Op2->getOperand(J)) {2839if (DI == -1) {2840// We have not seen any differences yet in the GEPs feeding the2841// PHI yet, so we record this one if it is allowed to be a2842// variable.28432844// The first two arguments can vary for any GEP, the rest have to be2845// static for struct slots2846if (J > 1) {2847assert(CurTy && "No current type?");2848if (CurTy->isStructTy())2849return nullptr;2850}28512852DI = J;2853} else {2854// The GEP is different by more than one input. While this could be2855// extended to support GEPs that vary by more than one variable it2856// doesn't make sense since it greatly increases the complexity and2857// would result in an R+R+R addressing mode which no backend2858// directly supports and would need to be broken into several2859// simpler instructions anyway.2860return nullptr;2861}2862}28632864// Sink down a layer of the type for the next iteration.2865if (J > 0) {2866if (J == 1) {2867CurTy = Op1->getSourceElementType();2868} else {2869CurTy =2870GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J));2871}2872}2873}2874}28752876// If not all GEPs are identical we'll have to create a new PHI node.2877// Check that the old PHI node has only one use so that it will get2878// removed.2879if (DI != -1 && !PN->hasOneUse())2880return nullptr;28812882auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());2883if (DI == -1) {2884// All the GEPs feeding the PHI are identical. Clone one down into our2885// BB so that it can be merged with the current GEP.2886} else {2887// All the GEPs feeding the PHI differ at a single offset. Clone a GEP2888// into the current block so it can be merged, and create a new PHI to2889// set that index.2890PHINode *NewPN;2891{2892IRBuilderBase::InsertPointGuard Guard(Builder);2893Builder.SetInsertPoint(PN);2894NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),2895PN->getNumOperands());2896}28972898for (auto &I : PN->operands())2899NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),2900PN->getIncomingBlock(I));29012902NewGEP->setOperand(DI, NewPN);2903}29042905NewGEP->insertBefore(*GEP.getParent(), GEP.getParent()->getFirstInsertionPt());2906return replaceOperand(GEP, 0, NewGEP);2907}29082909if (auto *Src = dyn_cast<GEPOperator>(PtrOp))2910if (Instruction *I = visitGEPOfGEP(GEP, Src))2911return I;29122913if (GEP.getNumIndices() == 1) {2914unsigned AS = GEP.getPointerAddressSpace();2915if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==2916DL.getIndexSizeInBits(AS)) {2917uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedValue();29182919if (TyAllocSize == 1) {2920// Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y),2921// but only if the result pointer is only used as if it were an integer,2922// or both point to the same underlying object (otherwise provenance is2923// not necessarily retained).2924Value *X = GEP.getPointerOperand();2925Value *Y;2926if (match(GEP.getOperand(1),2927m_Sub(m_PtrToInt(m_Value(Y)), m_PtrToInt(m_Specific(X)))) &&2928GEPType == Y->getType()) {2929bool HasSameUnderlyingObject =2930getUnderlyingObject(X) == getUnderlyingObject(Y);2931bool Changed = false;2932GEP.replaceUsesWithIf(Y, [&](Use &U) {2933bool ShouldReplace = HasSameUnderlyingObject ||2934isa<ICmpInst>(U.getUser()) ||2935isa<PtrToIntInst>(U.getUser());2936Changed |= ShouldReplace;2937return ShouldReplace;2938});2939return Changed ? &GEP : nullptr;2940}2941} else if (auto *ExactIns =2942dyn_cast<PossiblyExactOperator>(GEP.getOperand(1))) {2943// Canonicalize (gep T* X, V / sizeof(T)) to (gep i8* X, V)2944Value *V;2945if (ExactIns->isExact()) {2946if ((has_single_bit(TyAllocSize) &&2947match(GEP.getOperand(1),2948m_Shr(m_Value(V),2949m_SpecificInt(countr_zero(TyAllocSize))))) ||2950match(GEP.getOperand(1),2951m_IDiv(m_Value(V), m_SpecificInt(TyAllocSize)))) {2952return GetElementPtrInst::Create(Builder.getInt8Ty(),2953GEP.getPointerOperand(), V,2954GEP.getNoWrapFlags());2955}2956}2957if (ExactIns->isExact() && ExactIns->hasOneUse()) {2958// Try to canonicalize non-i8 element type to i8 if the index is an2959// exact instruction. If the index is an exact instruction (div/shr)2960// with a constant RHS, we can fold the non-i8 element scale into the2961// div/shr (similiar to the mul case, just inverted).2962const APInt *C;2963std::optional<APInt> NewC;2964if (has_single_bit(TyAllocSize) &&2965match(ExactIns, m_Shr(m_Value(V), m_APInt(C))) &&2966C->uge(countr_zero(TyAllocSize)))2967NewC = *C - countr_zero(TyAllocSize);2968else if (match(ExactIns, m_UDiv(m_Value(V), m_APInt(C)))) {2969APInt Quot;2970uint64_t Rem;2971APInt::udivrem(*C, TyAllocSize, Quot, Rem);2972if (Rem == 0)2973NewC = Quot;2974} else if (match(ExactIns, m_SDiv(m_Value(V), m_APInt(C)))) {2975APInt Quot;2976int64_t Rem;2977APInt::sdivrem(*C, TyAllocSize, Quot, Rem);2978// For sdiv we need to make sure we arent creating INT_MIN / -1.2979if (!Quot.isAllOnes() && Rem == 0)2980NewC = Quot;2981}29822983if (NewC.has_value()) {2984Value *NewOp = Builder.CreateBinOp(2985static_cast<Instruction::BinaryOps>(ExactIns->getOpcode()), V,2986ConstantInt::get(V->getType(), *NewC));2987cast<BinaryOperator>(NewOp)->setIsExact();2988return GetElementPtrInst::Create(Builder.getInt8Ty(),2989GEP.getPointerOperand(), NewOp,2990GEP.getNoWrapFlags());2991}2992}2993}2994}2995}2996// We do not handle pointer-vector geps here.2997if (GEPType->isVectorTy())2998return nullptr;29993000if (GEP.getNumIndices() == 1) {3001// We can only preserve inbounds if the original gep is inbounds, the add3002// is nsw, and the add operands are non-negative.3003auto CanPreserveInBounds = [&](bool AddIsNSW, Value *Idx1, Value *Idx2) {3004SimplifyQuery Q = SQ.getWithInstruction(&GEP);3005return GEP.isInBounds() && AddIsNSW && isKnownNonNegative(Idx1, Q) &&3006isKnownNonNegative(Idx2, Q);3007};30083009// Try to replace ADD + GEP with GEP + GEP.3010Value *Idx1, *Idx2;3011if (match(GEP.getOperand(1),3012m_OneUse(m_Add(m_Value(Idx1), m_Value(Idx2))))) {3013// %idx = add i64 %idx1, %idx23014// %gep = getelementptr i32, ptr %ptr, i64 %idx3015// as:3016// %newptr = getelementptr i32, ptr %ptr, i64 %idx13017// %newgep = getelementptr i32, ptr %newptr, i64 %idx23018bool IsInBounds = CanPreserveInBounds(3019cast<OverflowingBinaryOperator>(GEP.getOperand(1))->hasNoSignedWrap(),3020Idx1, Idx2);3021auto *NewPtr =3022Builder.CreateGEP(GEP.getSourceElementType(), GEP.getPointerOperand(),3023Idx1, "", IsInBounds);3024return replaceInstUsesWith(3025GEP, Builder.CreateGEP(GEP.getSourceElementType(), NewPtr, Idx2, "",3026IsInBounds));3027}3028ConstantInt *C;3029if (match(GEP.getOperand(1), m_OneUse(m_SExtLike(m_OneUse(m_NSWAdd(3030m_Value(Idx1), m_ConstantInt(C))))))) {3031// %add = add nsw i32 %idx1, idx23032// %sidx = sext i32 %add to i643033// %gep = getelementptr i32, ptr %ptr, i64 %sidx3034// as:3035// %newptr = getelementptr i32, ptr %ptr, i32 %idx13036// %newgep = getelementptr i32, ptr %newptr, i32 idx23037bool IsInBounds = CanPreserveInBounds(3038/*IsNSW=*/true, Idx1, C);3039auto *NewPtr = Builder.CreateGEP(3040GEP.getSourceElementType(), GEP.getPointerOperand(),3041Builder.CreateSExt(Idx1, GEP.getOperand(1)->getType()), "",3042IsInBounds);3043return replaceInstUsesWith(3044GEP,3045Builder.CreateGEP(GEP.getSourceElementType(), NewPtr,3046Builder.CreateSExt(C, GEP.getOperand(1)->getType()),3047"", IsInBounds));3048}3049}30503051if (!GEP.isInBounds()) {3052unsigned IdxWidth =3053DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());3054APInt BasePtrOffset(IdxWidth, 0);3055Value *UnderlyingPtrOp =3056PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,3057BasePtrOffset);3058bool CanBeNull, CanBeFreed;3059uint64_t DerefBytes = UnderlyingPtrOp->getPointerDereferenceableBytes(3060DL, CanBeNull, CanBeFreed);3061if (!CanBeNull && !CanBeFreed && DerefBytes != 0) {3062if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&3063BasePtrOffset.isNonNegative()) {3064APInt AllocSize(IdxWidth, DerefBytes);3065if (BasePtrOffset.ule(AllocSize)) {3066return GetElementPtrInst::CreateInBounds(3067GEP.getSourceElementType(), PtrOp, Indices, GEP.getName());3068}3069}3070}3071}30723073if (Instruction *R = foldSelectGEP(GEP, Builder))3074return R;30753076return nullptr;3077}30783079static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo &TLI,3080Instruction *AI) {3081if (isa<ConstantPointerNull>(V))3082return true;3083if (auto *LI = dyn_cast<LoadInst>(V))3084return isa<GlobalVariable>(LI->getPointerOperand());3085// Two distinct allocations will never be equal.3086return isAllocLikeFn(V, &TLI) && V != AI;3087}30883089/// Given a call CB which uses an address UsedV, return true if we can prove the3090/// call's only possible effect is storing to V.3091static bool isRemovableWrite(CallBase &CB, Value *UsedV,3092const TargetLibraryInfo &TLI) {3093if (!CB.use_empty())3094// TODO: add recursion if returned attribute is present3095return false;30963097if (CB.isTerminator())3098// TODO: remove implementation restriction3099return false;31003101if (!CB.willReturn() || !CB.doesNotThrow())3102return false;31033104// If the only possible side effect of the call is writing to the alloca,3105// and the result isn't used, we can safely remove any reads implied by the3106// call including those which might read the alloca itself.3107std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(&CB, TLI);3108return Dest && Dest->Ptr == UsedV;3109}31103111static bool isAllocSiteRemovable(Instruction *AI,3112SmallVectorImpl<WeakTrackingVH> &Users,3113const TargetLibraryInfo &TLI) {3114SmallVector<Instruction*, 4> Worklist;3115const std::optional<StringRef> Family = getAllocationFamily(AI, &TLI);3116Worklist.push_back(AI);31173118do {3119Instruction *PI = Worklist.pop_back_val();3120for (User *U : PI->users()) {3121Instruction *I = cast<Instruction>(U);3122switch (I->getOpcode()) {3123default:3124// Give up the moment we see something we can't handle.3125return false;31263127case Instruction::AddrSpaceCast:3128case Instruction::BitCast:3129case Instruction::GetElementPtr:3130Users.emplace_back(I);3131Worklist.push_back(I);3132continue;31333134case Instruction::ICmp: {3135ICmpInst *ICI = cast<ICmpInst>(I);3136// We can fold eq/ne comparisons with null to false/true, respectively.3137// We also fold comparisons in some conditions provided the alloc has3138// not escaped (see isNeverEqualToUnescapedAlloc).3139if (!ICI->isEquality())3140return false;3141unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;3142if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))3143return false;31443145// Do not fold compares to aligned_alloc calls, as they may have to3146// return null in case the required alignment cannot be satisfied,3147// unless we can prove that both alignment and size are valid.3148auto AlignmentAndSizeKnownValid = [](CallBase *CB) {3149// Check if alignment and size of a call to aligned_alloc is valid,3150// that is alignment is a power-of-2 and the size is a multiple of the3151// alignment.3152const APInt *Alignment;3153const APInt *Size;3154return match(CB->getArgOperand(0), m_APInt(Alignment)) &&3155match(CB->getArgOperand(1), m_APInt(Size)) &&3156Alignment->isPowerOf2() && Size->urem(*Alignment).isZero();3157};3158auto *CB = dyn_cast<CallBase>(AI);3159LibFunc TheLibFunc;3160if (CB && TLI.getLibFunc(*CB->getCalledFunction(), TheLibFunc) &&3161TLI.has(TheLibFunc) && TheLibFunc == LibFunc_aligned_alloc &&3162!AlignmentAndSizeKnownValid(CB))3163return false;3164Users.emplace_back(I);3165continue;3166}31673168case Instruction::Call:3169// Ignore no-op and store intrinsics.3170if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {3171switch (II->getIntrinsicID()) {3172default:3173return false;31743175case Intrinsic::memmove:3176case Intrinsic::memcpy:3177case Intrinsic::memset: {3178MemIntrinsic *MI = cast<MemIntrinsic>(II);3179if (MI->isVolatile() || MI->getRawDest() != PI)3180return false;3181[[fallthrough]];3182}3183case Intrinsic::assume:3184case Intrinsic::invariant_start:3185case Intrinsic::invariant_end:3186case Intrinsic::lifetime_start:3187case Intrinsic::lifetime_end:3188case Intrinsic::objectsize:3189Users.emplace_back(I);3190continue;3191case Intrinsic::launder_invariant_group:3192case Intrinsic::strip_invariant_group:3193Users.emplace_back(I);3194Worklist.push_back(I);3195continue;3196}3197}31983199if (isRemovableWrite(*cast<CallBase>(I), PI, TLI)) {3200Users.emplace_back(I);3201continue;3202}32033204if (getFreedOperand(cast<CallBase>(I), &TLI) == PI &&3205getAllocationFamily(I, &TLI) == Family) {3206assert(Family);3207Users.emplace_back(I);3208continue;3209}32103211if (getReallocatedOperand(cast<CallBase>(I)) == PI &&3212getAllocationFamily(I, &TLI) == Family) {3213assert(Family);3214Users.emplace_back(I);3215Worklist.push_back(I);3216continue;3217}32183219return false;32203221case Instruction::Store: {3222StoreInst *SI = cast<StoreInst>(I);3223if (SI->isVolatile() || SI->getPointerOperand() != PI)3224return false;3225Users.emplace_back(I);3226continue;3227}3228}3229llvm_unreachable("missing a return?");3230}3231} while (!Worklist.empty());3232return true;3233}32343235Instruction *InstCombinerImpl::visitAllocSite(Instruction &MI) {3236assert(isa<AllocaInst>(MI) || isRemovableAlloc(&cast<CallBase>(MI), &TLI));32373238// If we have a malloc call which is only used in any amount of comparisons to3239// null and free calls, delete the calls and replace the comparisons with true3240// or false as appropriate.32413242// This is based on the principle that we can substitute our own allocation3243// function (which will never return null) rather than knowledge of the3244// specific function being called. In some sense this can change the permitted3245// outputs of a program (when we convert a malloc to an alloca, the fact that3246// the allocation is now on the stack is potentially visible, for example),3247// but we believe in a permissible manner.3248SmallVector<WeakTrackingVH, 64> Users;32493250// If we are removing an alloca with a dbg.declare, insert dbg.value calls3251// before each store.3252SmallVector<DbgVariableIntrinsic *, 8> DVIs;3253SmallVector<DbgVariableRecord *, 8> DVRs;3254std::unique_ptr<DIBuilder> DIB;3255if (isa<AllocaInst>(MI)) {3256findDbgUsers(DVIs, &MI, &DVRs);3257DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));3258}32593260if (isAllocSiteRemovable(&MI, Users, TLI)) {3261for (unsigned i = 0, e = Users.size(); i != e; ++i) {3262// Lowering all @llvm.objectsize calls first because they may3263// use a bitcast/GEP of the alloca we are removing.3264if (!Users[i])3265continue;32663267Instruction *I = cast<Instruction>(&*Users[i]);32683269if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {3270if (II->getIntrinsicID() == Intrinsic::objectsize) {3271SmallVector<Instruction *> InsertedInstructions;3272Value *Result = lowerObjectSizeCall(3273II, DL, &TLI, AA, /*MustSucceed=*/true, &InsertedInstructions);3274for (Instruction *Inserted : InsertedInstructions)3275Worklist.add(Inserted);3276replaceInstUsesWith(*I, Result);3277eraseInstFromFunction(*I);3278Users[i] = nullptr; // Skip examining in the next loop.3279}3280}3281}3282for (unsigned i = 0, e = Users.size(); i != e; ++i) {3283if (!Users[i])3284continue;32853286Instruction *I = cast<Instruction>(&*Users[i]);32873288if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {3289replaceInstUsesWith(*C,3290ConstantInt::get(Type::getInt1Ty(C->getContext()),3291C->isFalseWhenEqual()));3292} else if (auto *SI = dyn_cast<StoreInst>(I)) {3293for (auto *DVI : DVIs)3294if (DVI->isAddressOfVariable())3295ConvertDebugDeclareToDebugValue(DVI, SI, *DIB);3296for (auto *DVR : DVRs)3297if (DVR->isAddressOfVariable())3298ConvertDebugDeclareToDebugValue(DVR, SI, *DIB);3299} else {3300// Casts, GEP, or anything else: we're about to delete this instruction,3301// so it can not have any valid uses.3302replaceInstUsesWith(*I, PoisonValue::get(I->getType()));3303}3304eraseInstFromFunction(*I);3305}33063307if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {3308// Replace invoke with a NOP intrinsic to maintain the original CFG3309Module *M = II->getModule();3310Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);3311InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),3312std::nullopt, "", II->getParent());3313}33143315// Remove debug intrinsics which describe the value contained within the3316// alloca. In addition to removing dbg.{declare,addr} which simply point to3317// the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.:3318//3319// ```3320// define void @foo(i32 %0) {3321// %a = alloca i32 ; Deleted.3322// store i32 %0, i32* %a3323// dbg.value(i32 %0, "arg0") ; Not deleted.3324// dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted.3325// call void @trivially_inlinable_no_op(i32* %a)3326// ret void3327// }3328// ```3329//3330// This may not be required if we stop describing the contents of allocas3331// using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in3332// the LowerDbgDeclare utility.3333//3334// If there is a dead store to `%a` in @trivially_inlinable_no_op, the3335// "arg0" dbg.value may be stale after the call. However, failing to remove3336// the DW_OP_deref dbg.value causes large gaps in location coverage.3337//3338// FIXME: the Assignment Tracking project has now likely made this3339// redundant (and it's sometimes harmful).3340for (auto *DVI : DVIs)3341if (DVI->isAddressOfVariable() || DVI->getExpression()->startsWithDeref())3342DVI->eraseFromParent();3343for (auto *DVR : DVRs)3344if (DVR->isAddressOfVariable() || DVR->getExpression()->startsWithDeref())3345DVR->eraseFromParent();33463347return eraseInstFromFunction(MI);3348}3349return nullptr;3350}33513352/// Move the call to free before a NULL test.3353///3354/// Check if this free is accessed after its argument has been test3355/// against NULL (property 0).3356/// If yes, it is legal to move this call in its predecessor block.3357///3358/// The move is performed only if the block containing the call to free3359/// will be removed, i.e.:3360/// 1. it has only one predecessor P, and P has two successors3361/// 2. it contains the call, noops, and an unconditional branch3362/// 3. its successor is the same as its predecessor's successor3363///3364/// The profitability is out-of concern here and this function should3365/// be called only if the caller knows this transformation would be3366/// profitable (e.g., for code size).3367static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI,3368const DataLayout &DL) {3369Value *Op = FI.getArgOperand(0);3370BasicBlock *FreeInstrBB = FI.getParent();3371BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();33723373// Validate part of constraint #1: Only one predecessor3374// FIXME: We can extend the number of predecessor, but in that case, we3375// would duplicate the call to free in each predecessor and it may3376// not be profitable even for code size.3377if (!PredBB)3378return nullptr;33793380// Validate constraint #2: Does this block contains only the call to3381// free, noops, and an unconditional branch?3382BasicBlock *SuccBB;3383Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();3384if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))3385return nullptr;33863387// If there are only 2 instructions in the block, at this point,3388// this is the call to free and unconditional.3389// If there are more than 2 instructions, check that they are noops3390// i.e., they won't hurt the performance of the generated code.3391if (FreeInstrBB->size() != 2) {3392for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) {3393if (&Inst == &FI || &Inst == FreeInstrBBTerminator)3394continue;3395auto *Cast = dyn_cast<CastInst>(&Inst);3396if (!Cast || !Cast->isNoopCast(DL))3397return nullptr;3398}3399}3400// Validate the rest of constraint #1 by matching on the pred branch.3401Instruction *TI = PredBB->getTerminator();3402BasicBlock *TrueBB, *FalseBB;3403ICmpInst::Predicate Pred;3404if (!match(TI, m_Br(m_ICmp(Pred,3405m_CombineOr(m_Specific(Op),3406m_Specific(Op->stripPointerCasts())),3407m_Zero()),3408TrueBB, FalseBB)))3409return nullptr;3410if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)3411return nullptr;34123413// Validate constraint #3: Ensure the null case just falls through.3414if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))3415return nullptr;3416assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&3417"Broken CFG: missing edge from predecessor to successor");34183419// At this point, we know that everything in FreeInstrBB can be moved3420// before TI.3421for (Instruction &Instr : llvm::make_early_inc_range(*FreeInstrBB)) {3422if (&Instr == FreeInstrBBTerminator)3423break;3424Instr.moveBeforePreserving(TI);3425}3426assert(FreeInstrBB->size() == 1 &&3427"Only the branch instruction should remain");34283429// Now that we've moved the call to free before the NULL check, we have to3430// remove any attributes on its parameter that imply it's non-null, because3431// those attributes might have only been valid because of the NULL check, and3432// we can get miscompiles if we keep them. This is conservative if non-null is3433// also implied by something other than the NULL check, but it's guaranteed to3434// be correct, and the conservativeness won't matter in practice, since the3435// attributes are irrelevant for the call to free itself and the pointer3436// shouldn't be used after the call.3437AttributeList Attrs = FI.getAttributes();3438Attrs = Attrs.removeParamAttribute(FI.getContext(), 0, Attribute::NonNull);3439Attribute Dereferenceable = Attrs.getParamAttr(0, Attribute::Dereferenceable);3440if (Dereferenceable.isValid()) {3441uint64_t Bytes = Dereferenceable.getDereferenceableBytes();3442Attrs = Attrs.removeParamAttribute(FI.getContext(), 0,3443Attribute::Dereferenceable);3444Attrs = Attrs.addDereferenceableOrNullParamAttr(FI.getContext(), 0, Bytes);3445}3446FI.setAttributes(Attrs);34473448return &FI;3449}34503451Instruction *InstCombinerImpl::visitFree(CallInst &FI, Value *Op) {3452// free undef -> unreachable.3453if (isa<UndefValue>(Op)) {3454// Leave a marker since we can't modify the CFG here.3455CreateNonTerminatorUnreachable(&FI);3456return eraseInstFromFunction(FI);3457}34583459// If we have 'free null' delete the instruction. This can happen in stl code3460// when lots of inlining happens.3461if (isa<ConstantPointerNull>(Op))3462return eraseInstFromFunction(FI);34633464// If we had free(realloc(...)) with no intervening uses, then eliminate the3465// realloc() entirely.3466CallInst *CI = dyn_cast<CallInst>(Op);3467if (CI && CI->hasOneUse())3468if (Value *ReallocatedOp = getReallocatedOperand(CI))3469return eraseInstFromFunction(*replaceInstUsesWith(*CI, ReallocatedOp));34703471// If we optimize for code size, try to move the call to free before the null3472// test so that simplify cfg can remove the empty block and dead code3473// elimination the branch. I.e., helps to turn something like:3474// if (foo) free(foo);3475// into3476// free(foo);3477//3478// Note that we can only do this for 'free' and not for any flavor of3479// 'operator delete'; there is no 'operator delete' symbol for which we are3480// permitted to invent a call, even if we're passing in a null pointer.3481if (MinimizeSize) {3482LibFunc Func;3483if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free)3484if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL))3485return I;3486}34873488return nullptr;3489}34903491Instruction *InstCombinerImpl::visitReturnInst(ReturnInst &RI) {3492Value *RetVal = RI.getReturnValue();3493if (!RetVal || !AttributeFuncs::isNoFPClassCompatibleType(RetVal->getType()))3494return nullptr;34953496Function *F = RI.getFunction();3497FPClassTest ReturnClass = F->getAttributes().getRetNoFPClass();3498if (ReturnClass == fcNone)3499return nullptr;35003501KnownFPClass KnownClass;3502Value *Simplified =3503SimplifyDemandedUseFPClass(RetVal, ~ReturnClass, KnownClass, 0, &RI);3504if (!Simplified)3505return nullptr;35063507return ReturnInst::Create(RI.getContext(), Simplified);3508}35093510// WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()!3511bool InstCombinerImpl::removeInstructionsBeforeUnreachable(Instruction &I) {3512// Try to remove the previous instruction if it must lead to unreachable.3513// This includes instructions like stores and "llvm.assume" that may not get3514// removed by simple dead code elimination.3515bool Changed = false;3516while (Instruction *Prev = I.getPrevNonDebugInstruction()) {3517// While we theoretically can erase EH, that would result in a block that3518// used to start with an EH no longer starting with EH, which is invalid.3519// To make it valid, we'd need to fixup predecessors to no longer refer to3520// this block, but that changes CFG, which is not allowed in InstCombine.3521if (Prev->isEHPad())3522break; // Can not drop any more instructions. We're done here.35233524if (!isGuaranteedToTransferExecutionToSuccessor(Prev))3525break; // Can not drop any more instructions. We're done here.3526// Otherwise, this instruction can be freely erased,3527// even if it is not side-effect free.35283529// A value may still have uses before we process it here (for example, in3530// another unreachable block), so convert those to poison.3531replaceInstUsesWith(*Prev, PoisonValue::get(Prev->getType()));3532eraseInstFromFunction(*Prev);3533Changed = true;3534}3535return Changed;3536}35373538Instruction *InstCombinerImpl::visitUnreachableInst(UnreachableInst &I) {3539removeInstructionsBeforeUnreachable(I);3540return nullptr;3541}35423543Instruction *InstCombinerImpl::visitUnconditionalBranchInst(BranchInst &BI) {3544assert(BI.isUnconditional() && "Only for unconditional branches.");35453546// If this store is the second-to-last instruction in the basic block3547// (excluding debug info and bitcasts of pointers) and if the block ends with3548// an unconditional branch, try to move the store to the successor block.35493550auto GetLastSinkableStore = [](BasicBlock::iterator BBI) {3551auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) {3552return BBI->isDebugOrPseudoInst() ||3553(isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy());3554};35553556BasicBlock::iterator FirstInstr = BBI->getParent()->begin();3557do {3558if (BBI != FirstInstr)3559--BBI;3560} while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI));35613562return dyn_cast<StoreInst>(BBI);3563};35643565if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI)))3566if (mergeStoreIntoSuccessor(*SI))3567return &BI;35683569return nullptr;3570}35713572void InstCombinerImpl::addDeadEdge(BasicBlock *From, BasicBlock *To,3573SmallVectorImpl<BasicBlock *> &Worklist) {3574if (!DeadEdges.insert({From, To}).second)3575return;35763577// Replace phi node operands in successor with poison.3578for (PHINode &PN : To->phis())3579for (Use &U : PN.incoming_values())3580if (PN.getIncomingBlock(U) == From && !isa<PoisonValue>(U)) {3581replaceUse(U, PoisonValue::get(PN.getType()));3582addToWorklist(&PN);3583MadeIRChange = true;3584}35853586Worklist.push_back(To);3587}35883589// Under the assumption that I is unreachable, remove it and following3590// instructions. Changes are reported directly to MadeIRChange.3591void InstCombinerImpl::handleUnreachableFrom(3592Instruction *I, SmallVectorImpl<BasicBlock *> &Worklist) {3593BasicBlock *BB = I->getParent();3594for (Instruction &Inst : make_early_inc_range(3595make_range(std::next(BB->getTerminator()->getReverseIterator()),3596std::next(I->getReverseIterator())))) {3597if (!Inst.use_empty() && !Inst.getType()->isTokenTy()) {3598replaceInstUsesWith(Inst, PoisonValue::get(Inst.getType()));3599MadeIRChange = true;3600}3601if (Inst.isEHPad() || Inst.getType()->isTokenTy())3602continue;3603// RemoveDIs: erase debug-info on this instruction manually.3604Inst.dropDbgRecords();3605eraseInstFromFunction(Inst);3606MadeIRChange = true;3607}36083609SmallVector<Value *> Changed;3610if (handleUnreachableTerminator(BB->getTerminator(), Changed)) {3611MadeIRChange = true;3612for (Value *V : Changed)3613addToWorklist(cast<Instruction>(V));3614}36153616// Handle potentially dead successors.3617for (BasicBlock *Succ : successors(BB))3618addDeadEdge(BB, Succ, Worklist);3619}36203621void InstCombinerImpl::handlePotentiallyDeadBlocks(3622SmallVectorImpl<BasicBlock *> &Worklist) {3623while (!Worklist.empty()) {3624BasicBlock *BB = Worklist.pop_back_val();3625if (!all_of(predecessors(BB), [&](BasicBlock *Pred) {3626return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred);3627}))3628continue;36293630handleUnreachableFrom(&BB->front(), Worklist);3631}3632}36333634void InstCombinerImpl::handlePotentiallyDeadSuccessors(BasicBlock *BB,3635BasicBlock *LiveSucc) {3636SmallVector<BasicBlock *> Worklist;3637for (BasicBlock *Succ : successors(BB)) {3638// The live successor isn't dead.3639if (Succ == LiveSucc)3640continue;36413642addDeadEdge(BB, Succ, Worklist);3643}36443645handlePotentiallyDeadBlocks(Worklist);3646}36473648Instruction *InstCombinerImpl::visitBranchInst(BranchInst &BI) {3649if (BI.isUnconditional())3650return visitUnconditionalBranchInst(BI);36513652// Change br (not X), label True, label False to: br X, label False, True3653Value *Cond = BI.getCondition();3654Value *X;3655if (match(Cond, m_Not(m_Value(X))) && !isa<Constant>(X)) {3656// Swap Destinations and condition...3657BI.swapSuccessors();3658if (BPI)3659BPI->swapSuccEdgesProbabilities(BI.getParent());3660return replaceOperand(BI, 0, X);3661}36623663// Canonicalize logical-and-with-invert as logical-or-with-invert.3664// This is done by inverting the condition and swapping successors:3665// br (X && !Y), T, F --> br !(X && !Y), F, T --> br (!X || Y), F, T3666Value *Y;3667if (isa<SelectInst>(Cond) &&3668match(Cond,3669m_OneUse(m_LogicalAnd(m_Value(X), m_OneUse(m_Not(m_Value(Y))))))) {3670Value *NotX = Builder.CreateNot(X, "not." + X->getName());3671Value *Or = Builder.CreateLogicalOr(NotX, Y);3672BI.swapSuccessors();3673if (BPI)3674BPI->swapSuccEdgesProbabilities(BI.getParent());3675return replaceOperand(BI, 0, Or);3676}36773678// If the condition is irrelevant, remove the use so that other3679// transforms on the condition become more effective.3680if (!isa<ConstantInt>(Cond) && BI.getSuccessor(0) == BI.getSuccessor(1))3681return replaceOperand(BI, 0, ConstantInt::getFalse(Cond->getType()));36823683// Canonicalize, for example, fcmp_one -> fcmp_oeq.3684CmpInst::Predicate Pred;3685if (match(Cond, m_OneUse(m_FCmp(Pred, m_Value(), m_Value()))) &&3686!isCanonicalPredicate(Pred)) {3687// Swap destinations and condition.3688auto *Cmp = cast<CmpInst>(Cond);3689Cmp->setPredicate(CmpInst::getInversePredicate(Pred));3690BI.swapSuccessors();3691if (BPI)3692BPI->swapSuccEdgesProbabilities(BI.getParent());3693Worklist.push(Cmp);3694return &BI;3695}36963697if (isa<UndefValue>(Cond)) {3698handlePotentiallyDeadSuccessors(BI.getParent(), /*LiveSucc*/ nullptr);3699return nullptr;3700}3701if (auto *CI = dyn_cast<ConstantInt>(Cond)) {3702handlePotentiallyDeadSuccessors(BI.getParent(),3703BI.getSuccessor(!CI->getZExtValue()));3704return nullptr;3705}37063707DC.registerBranch(&BI);3708return nullptr;3709}37103711// Replaces (switch (select cond, X, C)/(select cond, C, X)) with (switch X) if3712// we can prove that both (switch C) and (switch X) go to the default when cond3713// is false/true.3714static Value *simplifySwitchOnSelectUsingRanges(SwitchInst &SI,3715SelectInst *Select,3716bool IsTrueArm) {3717unsigned CstOpIdx = IsTrueArm ? 1 : 2;3718auto *C = dyn_cast<ConstantInt>(Select->getOperand(CstOpIdx));3719if (!C)3720return nullptr;37213722BasicBlock *CstBB = SI.findCaseValue(C)->getCaseSuccessor();3723if (CstBB != SI.getDefaultDest())3724return nullptr;3725Value *X = Select->getOperand(3 - CstOpIdx);3726ICmpInst::Predicate Pred;3727const APInt *RHSC;3728if (!match(Select->getCondition(),3729m_ICmp(Pred, m_Specific(X), m_APInt(RHSC))))3730return nullptr;3731if (IsTrueArm)3732Pred = ICmpInst::getInversePredicate(Pred);37333734// See whether we can replace the select with X3735ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);3736for (auto Case : SI.cases())3737if (!CR.contains(Case.getCaseValue()->getValue()))3738return nullptr;37393740return X;3741}37423743Instruction *InstCombinerImpl::visitSwitchInst(SwitchInst &SI) {3744Value *Cond = SI.getCondition();3745Value *Op0;3746ConstantInt *AddRHS;3747if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {3748// Change 'switch (X+4) case 1:' into 'switch (X) case -3'.3749for (auto Case : SI.cases()) {3750Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);3751assert(isa<ConstantInt>(NewCase) &&3752"Result of expression should be constant");3753Case.setValue(cast<ConstantInt>(NewCase));3754}3755return replaceOperand(SI, 0, Op0);3756}37573758ConstantInt *SubLHS;3759if (match(Cond, m_Sub(m_ConstantInt(SubLHS), m_Value(Op0)))) {3760// Change 'switch (1-X) case 1:' into 'switch (X) case 0'.3761for (auto Case : SI.cases()) {3762Constant *NewCase = ConstantExpr::getSub(SubLHS, Case.getCaseValue());3763assert(isa<ConstantInt>(NewCase) &&3764"Result of expression should be constant");3765Case.setValue(cast<ConstantInt>(NewCase));3766}3767return replaceOperand(SI, 0, Op0);3768}37693770uint64_t ShiftAmt;3771if (match(Cond, m_Shl(m_Value(Op0), m_ConstantInt(ShiftAmt))) &&3772ShiftAmt < Op0->getType()->getScalarSizeInBits() &&3773all_of(SI.cases(), [&](const auto &Case) {3774return Case.getCaseValue()->getValue().countr_zero() >= ShiftAmt;3775})) {3776// Change 'switch (X << 2) case 4:' into 'switch (X) case 1:'.3777OverflowingBinaryOperator *Shl = cast<OverflowingBinaryOperator>(Cond);3778if (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap() ||3779Shl->hasOneUse()) {3780Value *NewCond = Op0;3781if (!Shl->hasNoUnsignedWrap() && !Shl->hasNoSignedWrap()) {3782// If the shift may wrap, we need to mask off the shifted bits.3783unsigned BitWidth = Op0->getType()->getScalarSizeInBits();3784NewCond = Builder.CreateAnd(3785Op0, APInt::getLowBitsSet(BitWidth, BitWidth - ShiftAmt));3786}3787for (auto Case : SI.cases()) {3788const APInt &CaseVal = Case.getCaseValue()->getValue();3789APInt ShiftedCase = Shl->hasNoSignedWrap() ? CaseVal.ashr(ShiftAmt)3790: CaseVal.lshr(ShiftAmt);3791Case.setValue(ConstantInt::get(SI.getContext(), ShiftedCase));3792}3793return replaceOperand(SI, 0, NewCond);3794}3795}37963797// Fold switch(zext/sext(X)) into switch(X) if possible.3798if (match(Cond, m_ZExtOrSExt(m_Value(Op0)))) {3799bool IsZExt = isa<ZExtInst>(Cond);3800Type *SrcTy = Op0->getType();3801unsigned NewWidth = SrcTy->getScalarSizeInBits();38023803if (all_of(SI.cases(), [&](const auto &Case) {3804const APInt &CaseVal = Case.getCaseValue()->getValue();3805return IsZExt ? CaseVal.isIntN(NewWidth)3806: CaseVal.isSignedIntN(NewWidth);3807})) {3808for (auto &Case : SI.cases()) {3809APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);3810Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));3811}3812return replaceOperand(SI, 0, Op0);3813}3814}38153816// Fold switch(select cond, X, Y) into switch(X/Y) if possible3817if (auto *Select = dyn_cast<SelectInst>(Cond)) {3818if (Value *V =3819simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/true))3820return replaceOperand(SI, 0, V);3821if (Value *V =3822simplifySwitchOnSelectUsingRanges(SI, Select, /*IsTrueArm=*/false))3823return replaceOperand(SI, 0, V);3824}38253826KnownBits Known = computeKnownBits(Cond, 0, &SI);3827unsigned LeadingKnownZeros = Known.countMinLeadingZeros();3828unsigned LeadingKnownOnes = Known.countMinLeadingOnes();38293830// Compute the number of leading bits we can ignore.3831// TODO: A better way to determine this would use ComputeNumSignBits().3832for (const auto &C : SI.cases()) {3833LeadingKnownZeros =3834std::min(LeadingKnownZeros, C.getCaseValue()->getValue().countl_zero());3835LeadingKnownOnes =3836std::min(LeadingKnownOnes, C.getCaseValue()->getValue().countl_one());3837}38383839unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);38403841// Shrink the condition operand if the new type is smaller than the old type.3842// But do not shrink to a non-standard type, because backend can't generate3843// good code for that yet.3844// TODO: We can make it aggressive again after fixing PR39569.3845if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&3846shouldChangeType(Known.getBitWidth(), NewWidth)) {3847IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);3848Builder.SetInsertPoint(&SI);3849Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");38503851for (auto Case : SI.cases()) {3852APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);3853Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));3854}3855return replaceOperand(SI, 0, NewCond);3856}38573858if (isa<UndefValue>(Cond)) {3859handlePotentiallyDeadSuccessors(SI.getParent(), /*LiveSucc*/ nullptr);3860return nullptr;3861}3862if (auto *CI = dyn_cast<ConstantInt>(Cond)) {3863handlePotentiallyDeadSuccessors(SI.getParent(),3864SI.findCaseValue(CI)->getCaseSuccessor());3865return nullptr;3866}38673868return nullptr;3869}38703871Instruction *3872InstCombinerImpl::foldExtractOfOverflowIntrinsic(ExtractValueInst &EV) {3873auto *WO = dyn_cast<WithOverflowInst>(EV.getAggregateOperand());3874if (!WO)3875return nullptr;38763877Intrinsic::ID OvID = WO->getIntrinsicID();3878const APInt *C = nullptr;3879if (match(WO->getRHS(), m_APIntAllowPoison(C))) {3880if (*EV.idx_begin() == 0 && (OvID == Intrinsic::smul_with_overflow ||3881OvID == Intrinsic::umul_with_overflow)) {3882// extractvalue (any_mul_with_overflow X, -1), 0 --> -X3883if (C->isAllOnes())3884return BinaryOperator::CreateNeg(WO->getLHS());3885// extractvalue (any_mul_with_overflow X, 2^n), 0 --> X << n3886if (C->isPowerOf2()) {3887return BinaryOperator::CreateShl(3888WO->getLHS(),3889ConstantInt::get(WO->getLHS()->getType(), C->logBase2()));3890}3891}3892}38933894// We're extracting from an overflow intrinsic. See if we're the only user.3895// That allows us to simplify multiple result intrinsics to simpler things3896// that just get one value.3897if (!WO->hasOneUse())3898return nullptr;38993900// Check if we're grabbing only the result of a 'with overflow' intrinsic3901// and replace it with a traditional binary instruction.3902if (*EV.idx_begin() == 0) {3903Instruction::BinaryOps BinOp = WO->getBinaryOp();3904Value *LHS = WO->getLHS(), *RHS = WO->getRHS();3905// Replace the old instruction's uses with poison.3906replaceInstUsesWith(*WO, PoisonValue::get(WO->getType()));3907eraseInstFromFunction(*WO);3908return BinaryOperator::Create(BinOp, LHS, RHS);3909}39103911assert(*EV.idx_begin() == 1 && "Unexpected extract index for overflow inst");39123913// (usub LHS, RHS) overflows when LHS is unsigned-less-than RHS.3914if (OvID == Intrinsic::usub_with_overflow)3915return new ICmpInst(ICmpInst::ICMP_ULT, WO->getLHS(), WO->getRHS());39163917// smul with i1 types overflows when both sides are set: -1 * -1 == +1, but3918// +1 is not possible because we assume signed values.3919if (OvID == Intrinsic::smul_with_overflow &&3920WO->getLHS()->getType()->isIntOrIntVectorTy(1))3921return BinaryOperator::CreateAnd(WO->getLHS(), WO->getRHS());39223923// extractvalue (umul_with_overflow X, X), 1 -> X u> 2^(N/2)-13924if (OvID == Intrinsic::umul_with_overflow && WO->getLHS() == WO->getRHS()) {3925unsigned BitWidth = WO->getLHS()->getType()->getScalarSizeInBits();3926// Only handle even bitwidths for performance reasons.3927if (BitWidth % 2 == 0)3928return new ICmpInst(3929ICmpInst::ICMP_UGT, WO->getLHS(),3930ConstantInt::get(WO->getLHS()->getType(),3931APInt::getLowBitsSet(BitWidth, BitWidth / 2)));3932}39333934// If only the overflow result is used, and the right hand side is a3935// constant (or constant splat), we can remove the intrinsic by directly3936// checking for overflow.3937if (C) {3938// Compute the no-wrap range for LHS given RHS=C, then construct an3939// equivalent icmp, potentially using an offset.3940ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(3941WO->getBinaryOp(), *C, WO->getNoWrapKind());39423943CmpInst::Predicate Pred;3944APInt NewRHSC, Offset;3945NWR.getEquivalentICmp(Pred, NewRHSC, Offset);3946auto *OpTy = WO->getRHS()->getType();3947auto *NewLHS = WO->getLHS();3948if (Offset != 0)3949NewLHS = Builder.CreateAdd(NewLHS, ConstantInt::get(OpTy, Offset));3950return new ICmpInst(ICmpInst::getInversePredicate(Pred), NewLHS,3951ConstantInt::get(OpTy, NewRHSC));3952}39533954return nullptr;3955}39563957Instruction *InstCombinerImpl::visitExtractValueInst(ExtractValueInst &EV) {3958Value *Agg = EV.getAggregateOperand();39593960if (!EV.hasIndices())3961return replaceInstUsesWith(EV, Agg);39623963if (Value *V = simplifyExtractValueInst(Agg, EV.getIndices(),3964SQ.getWithInstruction(&EV)))3965return replaceInstUsesWith(EV, V);39663967if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {3968// We're extracting from an insertvalue instruction, compare the indices3969const unsigned *exti, *exte, *insi, *inse;3970for (exti = EV.idx_begin(), insi = IV->idx_begin(),3971exte = EV.idx_end(), inse = IV->idx_end();3972exti != exte && insi != inse;3973++exti, ++insi) {3974if (*insi != *exti)3975// The insert and extract both reference distinctly different elements.3976// This means the extract is not influenced by the insert, and we can3977// replace the aggregate operand of the extract with the aggregate3978// operand of the insert. i.e., replace3979// %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 13980// %E = extractvalue { i32, { i32 } } %I, 03981// with3982// %E = extractvalue { i32, { i32 } } %A, 03983return ExtractValueInst::Create(IV->getAggregateOperand(),3984EV.getIndices());3985}3986if (exti == exte && insi == inse)3987// Both iterators are at the end: Index lists are identical. Replace3988// %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 03989// %C = extractvalue { i32, { i32 } } %B, 1, 03990// with "i32 42"3991return replaceInstUsesWith(EV, IV->getInsertedValueOperand());3992if (exti == exte) {3993// The extract list is a prefix of the insert list. i.e. replace3994// %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 03995// %E = extractvalue { i32, { i32 } } %I, 13996// with3997// %X = extractvalue { i32, { i32 } } %A, 13998// %E = insertvalue { i32 } %X, i32 42, 03999// by switching the order of the insert and extract (though the4000// insertvalue should be left in, since it may have other uses).4001Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),4002EV.getIndices());4003return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),4004ArrayRef(insi, inse));4005}4006if (insi == inse)4007// The insert list is a prefix of the extract list4008// We can simply remove the common indices from the extract and make it4009// operate on the inserted value instead of the insertvalue result.4010// i.e., replace4011// %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 14012// %E = extractvalue { i32, { i32 } } %I, 1, 04013// with4014// %E extractvalue { i32 } { i32 42 }, 04015return ExtractValueInst::Create(IV->getInsertedValueOperand(),4016ArrayRef(exti, exte));4017}40184019if (Instruction *R = foldExtractOfOverflowIntrinsic(EV))4020return R;40214022if (LoadInst *L = dyn_cast<LoadInst>(Agg)) {4023// Bail out if the aggregate contains scalable vector type4024if (auto *STy = dyn_cast<StructType>(Agg->getType());4025STy && STy->containsScalableVectorType())4026return nullptr;40274028// If the (non-volatile) load only has one use, we can rewrite this to a4029// load from a GEP. This reduces the size of the load. If a load is used4030// only by extractvalue instructions then this either must have been4031// optimized before, or it is a struct with padding, in which case we4032// don't want to do the transformation as it loses padding knowledge.4033if (L->isSimple() && L->hasOneUse()) {4034// extractvalue has integer indices, getelementptr has Value*s. Convert.4035SmallVector<Value*, 4> Indices;4036// Prefix an i32 0 since we need the first element.4037Indices.push_back(Builder.getInt32(0));4038for (unsigned Idx : EV.indices())4039Indices.push_back(Builder.getInt32(Idx));40404041// We need to insert these at the location of the old load, not at that of4042// the extractvalue.4043Builder.SetInsertPoint(L);4044Value *GEP = Builder.CreateInBoundsGEP(L->getType(),4045L->getPointerOperand(), Indices);4046Instruction *NL = Builder.CreateLoad(EV.getType(), GEP);4047// Whatever aliasing information we had for the orignal load must also4048// hold for the smaller load, so propagate the annotations.4049NL->setAAMetadata(L->getAAMetadata());4050// Returning the load directly will cause the main loop to insert it in4051// the wrong spot, so use replaceInstUsesWith().4052return replaceInstUsesWith(EV, NL);4053}4054}40554056if (auto *PN = dyn_cast<PHINode>(Agg))4057if (Instruction *Res = foldOpIntoPhi(EV, PN))4058return Res;40594060// Canonicalize extract (select Cond, TV, FV)4061// -> select cond, (extract TV), (extract FV)4062if (auto *SI = dyn_cast<SelectInst>(Agg))4063if (Instruction *R = FoldOpIntoSelect(EV, SI, /*FoldWithMultiUse=*/true))4064return R;40654066// We could simplify extracts from other values. Note that nested extracts may4067// already be simplified implicitly by the above: extract (extract (insert) )4068// will be translated into extract ( insert ( extract ) ) first and then just4069// the value inserted, if appropriate. Similarly for extracts from single-use4070// loads: extract (extract (load)) will be translated to extract (load (gep))4071// and if again single-use then via load (gep (gep)) to load (gep).4072// However, double extracts from e.g. function arguments or return values4073// aren't handled yet.4074return nullptr;4075}40764077/// Return 'true' if the given typeinfo will match anything.4078static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {4079switch (Personality) {4080case EHPersonality::GNU_C:4081case EHPersonality::GNU_C_SjLj:4082case EHPersonality::Rust:4083// The GCC C EH and Rust personality only exists to support cleanups, so4084// it's not clear what the semantics of catch clauses are.4085return false;4086case EHPersonality::Unknown:4087return false;4088case EHPersonality::GNU_Ada:4089// While __gnat_all_others_value will match any Ada exception, it doesn't4090// match foreign exceptions (or didn't, before gcc-4.7).4091return false;4092case EHPersonality::GNU_CXX:4093case EHPersonality::GNU_CXX_SjLj:4094case EHPersonality::GNU_ObjC:4095case EHPersonality::MSVC_X86SEH:4096case EHPersonality::MSVC_TableSEH:4097case EHPersonality::MSVC_CXX:4098case EHPersonality::CoreCLR:4099case EHPersonality::Wasm_CXX:4100case EHPersonality::XL_CXX:4101case EHPersonality::ZOS_CXX:4102return TypeInfo->isNullValue();4103}4104llvm_unreachable("invalid enum");4105}41064107static bool shorter_filter(const Value *LHS, const Value *RHS) {4108return4109cast<ArrayType>(LHS->getType())->getNumElements()4110<4111cast<ArrayType>(RHS->getType())->getNumElements();4112}41134114Instruction *InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) {4115// The logic here should be correct for any real-world personality function.4116// However if that turns out not to be true, the offending logic can always4117// be conditioned on the personality function, like the catch-all logic is.4118EHPersonality Personality =4119classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());41204121// Simplify the list of clauses, eg by removing repeated catch clauses4122// (these are often created by inlining).4123bool MakeNewInstruction = false; // If true, recreate using the following:4124SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;4125bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.41264127SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.4128for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {4129bool isLastClause = i + 1 == e;4130if (LI.isCatch(i)) {4131// A catch clause.4132Constant *CatchClause = LI.getClause(i);4133Constant *TypeInfo = CatchClause->stripPointerCasts();41344135// If we already saw this clause, there is no point in having a second4136// copy of it.4137if (AlreadyCaught.insert(TypeInfo).second) {4138// This catch clause was not already seen.4139NewClauses.push_back(CatchClause);4140} else {4141// Repeated catch clause - drop the redundant copy.4142MakeNewInstruction = true;4143}41444145// If this is a catch-all then there is no point in keeping any following4146// clauses or marking the landingpad as having a cleanup.4147if (isCatchAll(Personality, TypeInfo)) {4148if (!isLastClause)4149MakeNewInstruction = true;4150CleanupFlag = false;4151break;4152}4153} else {4154// A filter clause. If any of the filter elements were already caught4155// then they can be dropped from the filter. It is tempting to try to4156// exploit the filter further by saying that any typeinfo that does not4157// occur in the filter can't be caught later (and thus can be dropped).4158// However this would be wrong, since typeinfos can match without being4159// equal (for example if one represents a C++ class, and the other some4160// class derived from it).4161assert(LI.isFilter(i) && "Unsupported landingpad clause!");4162Constant *FilterClause = LI.getClause(i);4163ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());4164unsigned NumTypeInfos = FilterType->getNumElements();41654166// An empty filter catches everything, so there is no point in keeping any4167// following clauses or marking the landingpad as having a cleanup. By4168// dealing with this case here the following code is made a bit simpler.4169if (!NumTypeInfos) {4170NewClauses.push_back(FilterClause);4171if (!isLastClause)4172MakeNewInstruction = true;4173CleanupFlag = false;4174break;4175}41764177bool MakeNewFilter = false; // If true, make a new filter.4178SmallVector<Constant *, 16> NewFilterElts; // New elements.4179if (isa<ConstantAggregateZero>(FilterClause)) {4180// Not an empty filter - it contains at least one null typeinfo.4181assert(NumTypeInfos > 0 && "Should have handled empty filter already!");4182Constant *TypeInfo =4183Constant::getNullValue(FilterType->getElementType());4184// If this typeinfo is a catch-all then the filter can never match.4185if (isCatchAll(Personality, TypeInfo)) {4186// Throw the filter away.4187MakeNewInstruction = true;4188continue;4189}41904191// There is no point in having multiple copies of this typeinfo, so4192// discard all but the first copy if there is more than one.4193NewFilterElts.push_back(TypeInfo);4194if (NumTypeInfos > 1)4195MakeNewFilter = true;4196} else {4197ConstantArray *Filter = cast<ConstantArray>(FilterClause);4198SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.4199NewFilterElts.reserve(NumTypeInfos);42004201// Remove any filter elements that were already caught or that already4202// occurred in the filter. While there, see if any of the elements are4203// catch-alls. If so, the filter can be discarded.4204bool SawCatchAll = false;4205for (unsigned j = 0; j != NumTypeInfos; ++j) {4206Constant *Elt = Filter->getOperand(j);4207Constant *TypeInfo = Elt->stripPointerCasts();4208if (isCatchAll(Personality, TypeInfo)) {4209// This element is a catch-all. Bail out, noting this fact.4210SawCatchAll = true;4211break;4212}42134214// Even if we've seen a type in a catch clause, we don't want to4215// remove it from the filter. An unexpected type handler may be4216// set up for a call site which throws an exception of the same4217// type caught. In order for the exception thrown by the unexpected4218// handler to propagate correctly, the filter must be correctly4219// described for the call site.4220//4221// Example:4222//4223// void unexpected() { throw 1;}4224// void foo() throw (int) {4225// std::set_unexpected(unexpected);4226// try {4227// throw 2.0;4228// } catch (int i) {}4229// }42304231// There is no point in having multiple copies of the same typeinfo in4232// a filter, so only add it if we didn't already.4233if (SeenInFilter.insert(TypeInfo).second)4234NewFilterElts.push_back(cast<Constant>(Elt));4235}4236// A filter containing a catch-all cannot match anything by definition.4237if (SawCatchAll) {4238// Throw the filter away.4239MakeNewInstruction = true;4240continue;4241}42424243// If we dropped something from the filter, make a new one.4244if (NewFilterElts.size() < NumTypeInfos)4245MakeNewFilter = true;4246}4247if (MakeNewFilter) {4248FilterType = ArrayType::get(FilterType->getElementType(),4249NewFilterElts.size());4250FilterClause = ConstantArray::get(FilterType, NewFilterElts);4251MakeNewInstruction = true;4252}42534254NewClauses.push_back(FilterClause);42554256// If the new filter is empty then it will catch everything so there is4257// no point in keeping any following clauses or marking the landingpad4258// as having a cleanup. The case of the original filter being empty was4259// already handled above.4260if (MakeNewFilter && !NewFilterElts.size()) {4261assert(MakeNewInstruction && "New filter but not a new instruction!");4262CleanupFlag = false;4263break;4264}4265}4266}42674268// If several filters occur in a row then reorder them so that the shortest4269// filters come first (those with the smallest number of elements). This is4270// advantageous because shorter filters are more likely to match, speeding up4271// unwinding, but mostly because it increases the effectiveness of the other4272// filter optimizations below.4273for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {4274unsigned j;4275// Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.4276for (j = i; j != e; ++j)4277if (!isa<ArrayType>(NewClauses[j]->getType()))4278break;42794280// Check whether the filters are already sorted by length. We need to know4281// if sorting them is actually going to do anything so that we only make a4282// new landingpad instruction if it does.4283for (unsigned k = i; k + 1 < j; ++k)4284if (shorter_filter(NewClauses[k+1], NewClauses[k])) {4285// Not sorted, so sort the filters now. Doing an unstable sort would be4286// correct too but reordering filters pointlessly might confuse users.4287std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,4288shorter_filter);4289MakeNewInstruction = true;4290break;4291}42924293// Look for the next batch of filters.4294i = j + 1;4295}42964297// If typeinfos matched if and only if equal, then the elements of a filter L4298// that occurs later than a filter F could be replaced by the intersection of4299// the elements of F and L. In reality two typeinfos can match without being4300// equal (for example if one represents a C++ class, and the other some class4301// derived from it) so it would be wrong to perform this transform in general.4302// However the transform is correct and useful if F is a subset of L. In that4303// case L can be replaced by F, and thus removed altogether since repeating a4304// filter is pointless. So here we look at all pairs of filters F and L where4305// L follows F in the list of clauses, and remove L if every element of F is4306// an element of L. This can occur when inlining C++ functions with exception4307// specifications.4308for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {4309// Examine each filter in turn.4310Value *Filter = NewClauses[i];4311ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());4312if (!FTy)4313// Not a filter - skip it.4314continue;4315unsigned FElts = FTy->getNumElements();4316// Examine each filter following this one. Doing this backwards means that4317// we don't have to worry about filters disappearing under us when removed.4318for (unsigned j = NewClauses.size() - 1; j != i; --j) {4319Value *LFilter = NewClauses[j];4320ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());4321if (!LTy)4322// Not a filter - skip it.4323continue;4324// If Filter is a subset of LFilter, i.e. every element of Filter is also4325// an element of LFilter, then discard LFilter.4326SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;4327// If Filter is empty then it is a subset of LFilter.4328if (!FElts) {4329// Discard LFilter.4330NewClauses.erase(J);4331MakeNewInstruction = true;4332// Move on to the next filter.4333continue;4334}4335unsigned LElts = LTy->getNumElements();4336// If Filter is longer than LFilter then it cannot be a subset of it.4337if (FElts > LElts)4338// Move on to the next filter.4339continue;4340// At this point we know that LFilter has at least one element.4341if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.4342// Filter is a subset of LFilter iff Filter contains only zeros (as we4343// already know that Filter is not longer than LFilter).4344if (isa<ConstantAggregateZero>(Filter)) {4345assert(FElts <= LElts && "Should have handled this case earlier!");4346// Discard LFilter.4347NewClauses.erase(J);4348MakeNewInstruction = true;4349}4350// Move on to the next filter.4351continue;4352}4353ConstantArray *LArray = cast<ConstantArray>(LFilter);4354if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.4355// Since Filter is non-empty and contains only zeros, it is a subset of4356// LFilter iff LFilter contains a zero.4357assert(FElts > 0 && "Should have eliminated the empty filter earlier!");4358for (unsigned l = 0; l != LElts; ++l)4359if (LArray->getOperand(l)->isNullValue()) {4360// LFilter contains a zero - discard it.4361NewClauses.erase(J);4362MakeNewInstruction = true;4363break;4364}4365// Move on to the next filter.4366continue;4367}4368// At this point we know that both filters are ConstantArrays. Loop over4369// operands to see whether every element of Filter is also an element of4370// LFilter. Since filters tend to be short this is probably faster than4371// using a method that scales nicely.4372ConstantArray *FArray = cast<ConstantArray>(Filter);4373bool AllFound = true;4374for (unsigned f = 0; f != FElts; ++f) {4375Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();4376AllFound = false;4377for (unsigned l = 0; l != LElts; ++l) {4378Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();4379if (LTypeInfo == FTypeInfo) {4380AllFound = true;4381break;4382}4383}4384if (!AllFound)4385break;4386}4387if (AllFound) {4388// Discard LFilter.4389NewClauses.erase(J);4390MakeNewInstruction = true;4391}4392// Move on to the next filter.4393}4394}43954396// If we changed any of the clauses, replace the old landingpad instruction4397// with a new one.4398if (MakeNewInstruction) {4399LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),4400NewClauses.size());4401for (Constant *C : NewClauses)4402NLI->addClause(C);4403// A landing pad with no clauses must have the cleanup flag set. It is4404// theoretically possible, though highly unlikely, that we eliminated all4405// clauses. If so, force the cleanup flag to true.4406if (NewClauses.empty())4407CleanupFlag = true;4408NLI->setCleanup(CleanupFlag);4409return NLI;4410}44114412// Even if none of the clauses changed, we may nonetheless have understood4413// that the cleanup flag is pointless. Clear it if so.4414if (LI.isCleanup() != CleanupFlag) {4415assert(!CleanupFlag && "Adding a cleanup, not removing one?!");4416LI.setCleanup(CleanupFlag);4417return &LI;4418}44194420return nullptr;4421}44224423Value *4424InstCombinerImpl::pushFreezeToPreventPoisonFromPropagating(FreezeInst &OrigFI) {4425// Try to push freeze through instructions that propagate but don't produce4426// poison as far as possible. If an operand of freeze follows three4427// conditions 1) one-use, 2) does not produce poison, and 3) has all but one4428// guaranteed-non-poison operands then push the freeze through to the one4429// operand that is not guaranteed non-poison. The actual transform is as4430// follows.4431// Op1 = ... ; Op1 can be posion4432// Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have4433// ; single guaranteed-non-poison operands4434// ... = Freeze(Op0)4435// =>4436// Op1 = ...4437// Op1.fr = Freeze(Op1)4438// ... = Inst(Op1.fr, NonPoisonOps...)4439auto *OrigOp = OrigFI.getOperand(0);4440auto *OrigOpInst = dyn_cast<Instruction>(OrigOp);44414442// While we could change the other users of OrigOp to use freeze(OrigOp), that4443// potentially reduces their optimization potential, so let's only do this iff4444// the OrigOp is only used by the freeze.4445if (!OrigOpInst || !OrigOpInst->hasOneUse() || isa<PHINode>(OrigOp))4446return nullptr;44474448// We can't push the freeze through an instruction which can itself create4449// poison. If the only source of new poison is flags, we can simply4450// strip them (since we know the only use is the freeze and nothing can4451// benefit from them.)4452if (canCreateUndefOrPoison(cast<Operator>(OrigOp),4453/*ConsiderFlagsAndMetadata*/ false))4454return nullptr;44554456// If operand is guaranteed not to be poison, there is no need to add freeze4457// to the operand. So we first find the operand that is not guaranteed to be4458// poison.4459Use *MaybePoisonOperand = nullptr;4460for (Use &U : OrigOpInst->operands()) {4461if (isa<MetadataAsValue>(U.get()) ||4462isGuaranteedNotToBeUndefOrPoison(U.get()))4463continue;4464if (!MaybePoisonOperand)4465MaybePoisonOperand = &U;4466else4467return nullptr;4468}44694470OrigOpInst->dropPoisonGeneratingAnnotations();44714472// If all operands are guaranteed to be non-poison, we can drop freeze.4473if (!MaybePoisonOperand)4474return OrigOp;44754476Builder.SetInsertPoint(OrigOpInst);4477auto *FrozenMaybePoisonOperand = Builder.CreateFreeze(4478MaybePoisonOperand->get(), MaybePoisonOperand->get()->getName() + ".fr");44794480replaceUse(*MaybePoisonOperand, FrozenMaybePoisonOperand);4481return OrigOp;4482}44834484Instruction *InstCombinerImpl::foldFreezeIntoRecurrence(FreezeInst &FI,4485PHINode *PN) {4486// Detect whether this is a recurrence with a start value and some number of4487// backedge values. We'll check whether we can push the freeze through the4488// backedge values (possibly dropping poison flags along the way) until we4489// reach the phi again. In that case, we can move the freeze to the start4490// value.4491Use *StartU = nullptr;4492SmallVector<Value *> Worklist;4493for (Use &U : PN->incoming_values()) {4494if (DT.dominates(PN->getParent(), PN->getIncomingBlock(U))) {4495// Add backedge value to worklist.4496Worklist.push_back(U.get());4497continue;4498}44994500// Don't bother handling multiple start values.4501if (StartU)4502return nullptr;4503StartU = &U;4504}45054506if (!StartU || Worklist.empty())4507return nullptr; // Not a recurrence.45084509Value *StartV = StartU->get();4510BasicBlock *StartBB = PN->getIncomingBlock(*StartU);4511bool StartNeedsFreeze = !isGuaranteedNotToBeUndefOrPoison(StartV);4512// We can't insert freeze if the start value is the result of the4513// terminator (e.g. an invoke).4514if (StartNeedsFreeze && StartBB->getTerminator() == StartV)4515return nullptr;45164517SmallPtrSet<Value *, 32> Visited;4518SmallVector<Instruction *> DropFlags;4519while (!Worklist.empty()) {4520Value *V = Worklist.pop_back_val();4521if (!Visited.insert(V).second)4522continue;45234524if (Visited.size() > 32)4525return nullptr; // Limit the total number of values we inspect.45264527// Assume that PN is non-poison, because it will be after the transform.4528if (V == PN || isGuaranteedNotToBeUndefOrPoison(V))4529continue;45304531Instruction *I = dyn_cast<Instruction>(V);4532if (!I || canCreateUndefOrPoison(cast<Operator>(I),4533/*ConsiderFlagsAndMetadata*/ false))4534return nullptr;45354536DropFlags.push_back(I);4537append_range(Worklist, I->operands());4538}45394540for (Instruction *I : DropFlags)4541I->dropPoisonGeneratingAnnotations();45424543if (StartNeedsFreeze) {4544Builder.SetInsertPoint(StartBB->getTerminator());4545Value *FrozenStartV = Builder.CreateFreeze(StartV,4546StartV->getName() + ".fr");4547replaceUse(*StartU, FrozenStartV);4548}4549return replaceInstUsesWith(FI, PN);4550}45514552bool InstCombinerImpl::freezeOtherUses(FreezeInst &FI) {4553Value *Op = FI.getOperand(0);45544555if (isa<Constant>(Op) || Op->hasOneUse())4556return false;45574558// Move the freeze directly after the definition of its operand, so that4559// it dominates the maximum number of uses. Note that it may not dominate4560// *all* uses if the operand is an invoke/callbr and the use is in a phi on4561// the normal/default destination. This is why the domination check in the4562// replacement below is still necessary.4563BasicBlock::iterator MoveBefore;4564if (isa<Argument>(Op)) {4565MoveBefore =4566FI.getFunction()->getEntryBlock().getFirstNonPHIOrDbgOrAlloca();4567} else {4568auto MoveBeforeOpt = cast<Instruction>(Op)->getInsertionPointAfterDef();4569if (!MoveBeforeOpt)4570return false;4571MoveBefore = *MoveBeforeOpt;4572}45734574// Don't move to the position of a debug intrinsic.4575if (isa<DbgInfoIntrinsic>(MoveBefore))4576MoveBefore = MoveBefore->getNextNonDebugInstruction()->getIterator();4577// Re-point iterator to come after any debug-info records, if we're4578// running in "RemoveDIs" mode4579MoveBefore.setHeadBit(false);45804581bool Changed = false;4582if (&FI != &*MoveBefore) {4583FI.moveBefore(*MoveBefore->getParent(), MoveBefore);4584Changed = true;4585}45864587Op->replaceUsesWithIf(&FI, [&](Use &U) -> bool {4588bool Dominates = DT.dominates(&FI, U);4589Changed |= Dominates;4590return Dominates;4591});45924593return Changed;4594}45954596// Check if any direct or bitcast user of this value is a shuffle instruction.4597static bool isUsedWithinShuffleVector(Value *V) {4598for (auto *U : V->users()) {4599if (isa<ShuffleVectorInst>(U))4600return true;4601else if (match(U, m_BitCast(m_Specific(V))) && isUsedWithinShuffleVector(U))4602return true;4603}4604return false;4605}46064607Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) {4608Value *Op0 = I.getOperand(0);46094610if (Value *V = simplifyFreezeInst(Op0, SQ.getWithInstruction(&I)))4611return replaceInstUsesWith(I, V);46124613// freeze (phi const, x) --> phi const, (freeze x)4614if (auto *PN = dyn_cast<PHINode>(Op0)) {4615if (Instruction *NV = foldOpIntoPhi(I, PN))4616return NV;4617if (Instruction *NV = foldFreezeIntoRecurrence(I, PN))4618return NV;4619}46204621if (Value *NI = pushFreezeToPreventPoisonFromPropagating(I))4622return replaceInstUsesWith(I, NI);46234624// If I is freeze(undef), check its uses and fold it to a fixed constant.4625// - or: pick -14626// - select's condition: if the true value is constant, choose it by making4627// the condition true.4628// - default: pick 04629//4630// Note that this transform is intentionally done here rather than4631// via an analysis in InstSimplify or at individual user sites. That is4632// because we must produce the same value for all uses of the freeze -4633// it's the reason "freeze" exists!4634//4635// TODO: This could use getBinopAbsorber() / getBinopIdentity() to avoid4636// duplicating logic for binops at least.4637auto getUndefReplacement = [&I](Type *Ty) {4638Constant *BestValue = nullptr;4639Constant *NullValue = Constant::getNullValue(Ty);4640for (const auto *U : I.users()) {4641Constant *C = NullValue;4642if (match(U, m_Or(m_Value(), m_Value())))4643C = ConstantInt::getAllOnesValue(Ty);4644else if (match(U, m_Select(m_Specific(&I), m_Constant(), m_Value())))4645C = ConstantInt::getTrue(Ty);46464647if (!BestValue)4648BestValue = C;4649else if (BestValue != C)4650BestValue = NullValue;4651}4652assert(BestValue && "Must have at least one use");4653return BestValue;4654};46554656if (match(Op0, m_Undef())) {4657// Don't fold freeze(undef/poison) if it's used as a vector operand in4658// a shuffle. This may improve codegen for shuffles that allow4659// unspecified inputs.4660if (isUsedWithinShuffleVector(&I))4661return nullptr;4662return replaceInstUsesWith(I, getUndefReplacement(I.getType()));4663}46644665Constant *C;4666if (match(Op0, m_Constant(C)) && C->containsUndefOrPoisonElement()) {4667Constant *ReplaceC = getUndefReplacement(I.getType()->getScalarType());4668return replaceInstUsesWith(I, Constant::replaceUndefsWith(C, ReplaceC));4669}46704671// Replace uses of Op with freeze(Op).4672if (freezeOtherUses(I))4673return &I;46744675return nullptr;4676}46774678/// Check for case where the call writes to an otherwise dead alloca. This4679/// shows up for unused out-params in idiomatic C/C++ code. Note that this4680/// helper *only* analyzes the write; doesn't check any other legality aspect.4681static bool SoleWriteToDeadLocal(Instruction *I, TargetLibraryInfo &TLI) {4682auto *CB = dyn_cast<CallBase>(I);4683if (!CB)4684// TODO: handle e.g. store to alloca here - only worth doing if we extend4685// to allow reload along used path as described below. Otherwise, this4686// is simply a store to a dead allocation which will be removed.4687return false;4688std::optional<MemoryLocation> Dest = MemoryLocation::getForDest(CB, TLI);4689if (!Dest)4690return false;4691auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(Dest->Ptr));4692if (!AI)4693// TODO: allow malloc?4694return false;4695// TODO: allow memory access dominated by move point? Note that since AI4696// could have a reference to itself captured by the call, we would need to4697// account for cycles in doing so.4698SmallVector<const User *> AllocaUsers;4699SmallPtrSet<const User *, 4> Visited;4700auto pushUsers = [&](const Instruction &I) {4701for (const User *U : I.users()) {4702if (Visited.insert(U).second)4703AllocaUsers.push_back(U);4704}4705};4706pushUsers(*AI);4707while (!AllocaUsers.empty()) {4708auto *UserI = cast<Instruction>(AllocaUsers.pop_back_val());4709if (isa<BitCastInst>(UserI) || isa<GetElementPtrInst>(UserI) ||4710isa<AddrSpaceCastInst>(UserI)) {4711pushUsers(*UserI);4712continue;4713}4714if (UserI == CB)4715continue;4716// TODO: support lifetime.start/end here4717return false;4718}4719return true;4720}47214722/// Try to move the specified instruction from its current block into the4723/// beginning of DestBlock, which can only happen if it's safe to move the4724/// instruction past all of the instructions between it and the end of its4725/// block.4726bool InstCombinerImpl::tryToSinkInstruction(Instruction *I,4727BasicBlock *DestBlock) {4728BasicBlock *SrcBlock = I->getParent();47294730// Cannot move control-flow-involving, volatile loads, vaarg, etc.4731if (isa<PHINode>(I) || I->isEHPad() || I->mayThrow() || !I->willReturn() ||4732I->isTerminator())4733return false;47344735// Do not sink static or dynamic alloca instructions. Static allocas must4736// remain in the entry block, and dynamic allocas must not be sunk in between4737// a stacksave / stackrestore pair, which would incorrectly shorten its4738// lifetime.4739if (isa<AllocaInst>(I))4740return false;47414742// Do not sink into catchswitch blocks.4743if (isa<CatchSwitchInst>(DestBlock->getTerminator()))4744return false;47454746// Do not sink convergent call instructions.4747if (auto *CI = dyn_cast<CallInst>(I)) {4748if (CI->isConvergent())4749return false;4750}47514752// Unless we can prove that the memory write isn't visibile except on the4753// path we're sinking to, we must bail.4754if (I->mayWriteToMemory()) {4755if (!SoleWriteToDeadLocal(I, TLI))4756return false;4757}47584759// We can only sink load instructions if there is nothing between the load and4760// the end of block that could change the value.4761if (I->mayReadFromMemory()) {4762// We don't want to do any sophisticated alias analysis, so we only check4763// the instructions after I in I's parent block if we try to sink to its4764// successor block.4765if (DestBlock->getUniquePredecessor() != I->getParent())4766return false;4767for (BasicBlock::iterator Scan = std::next(I->getIterator()),4768E = I->getParent()->end();4769Scan != E; ++Scan)4770if (Scan->mayWriteToMemory())4771return false;4772}47734774I->dropDroppableUses([&](const Use *U) {4775auto *I = dyn_cast<Instruction>(U->getUser());4776if (I && I->getParent() != DestBlock) {4777Worklist.add(I);4778return true;4779}4780return false;4781});4782/// FIXME: We could remove droppable uses that are not dominated by4783/// the new position.47844785BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();4786I->moveBefore(*DestBlock, InsertPos);4787++NumSunkInst;47884789// Also sink all related debug uses from the source basic block. Otherwise we4790// get debug use before the def. Attempt to salvage debug uses first, to4791// maximise the range variables have location for. If we cannot salvage, then4792// mark the location undef: we know it was supposed to receive a new location4793// here, but that computation has been sunk.4794SmallVector<DbgVariableIntrinsic *, 2> DbgUsers;4795SmallVector<DbgVariableRecord *, 2> DbgVariableRecords;4796findDbgUsers(DbgUsers, I, &DbgVariableRecords);4797if (!DbgUsers.empty())4798tryToSinkInstructionDbgValues(I, InsertPos, SrcBlock, DestBlock, DbgUsers);4799if (!DbgVariableRecords.empty())4800tryToSinkInstructionDbgVariableRecords(I, InsertPos, SrcBlock, DestBlock,4801DbgVariableRecords);48024803// PS: there are numerous flaws with this behaviour, not least that right now4804// assignments can be re-ordered past other assignments to the same variable4805// if they use different Values. Creating more undef assignements can never be4806// undone. And salvaging all users outside of this block can un-necessarily4807// alter the lifetime of the live-value that the variable refers to.4808// Some of these things can be resolved by tolerating debug use-before-defs in4809// LLVM-IR, however it depends on the instruction-referencing CodeGen backend4810// being used for more architectures.48114812return true;4813}48144815void InstCombinerImpl::tryToSinkInstructionDbgValues(4816Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,4817BasicBlock *DestBlock, SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers) {4818// For all debug values in the destination block, the sunk instruction4819// will still be available, so they do not need to be dropped.4820SmallVector<DbgVariableIntrinsic *, 2> DbgUsersToSalvage;4821for (auto &DbgUser : DbgUsers)4822if (DbgUser->getParent() != DestBlock)4823DbgUsersToSalvage.push_back(DbgUser);48244825// Process the sinking DbgUsersToSalvage in reverse order, as we only want4826// to clone the last appearing debug intrinsic for each given variable.4827SmallVector<DbgVariableIntrinsic *, 2> DbgUsersToSink;4828for (DbgVariableIntrinsic *DVI : DbgUsersToSalvage)4829if (DVI->getParent() == SrcBlock)4830DbgUsersToSink.push_back(DVI);4831llvm::sort(DbgUsersToSink,4832[](auto *A, auto *B) { return B->comesBefore(A); });48334834SmallVector<DbgVariableIntrinsic *, 2> DIIClones;4835SmallSet<DebugVariable, 4> SunkVariables;4836for (auto *User : DbgUsersToSink) {4837// A dbg.declare instruction should not be cloned, since there can only be4838// one per variable fragment. It should be left in the original place4839// because the sunk instruction is not an alloca (otherwise we could not be4840// here).4841if (isa<DbgDeclareInst>(User))4842continue;48434844DebugVariable DbgUserVariable =4845DebugVariable(User->getVariable(), User->getExpression(),4846User->getDebugLoc()->getInlinedAt());48474848if (!SunkVariables.insert(DbgUserVariable).second)4849continue;48504851// Leave dbg.assign intrinsics in their original positions and there should4852// be no need to insert a clone.4853if (isa<DbgAssignIntrinsic>(User))4854continue;48554856DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone()));4857if (isa<DbgDeclareInst>(User) && isa<CastInst>(I))4858DIIClones.back()->replaceVariableLocationOp(I, I->getOperand(0));4859LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n');4860}48614862// Perform salvaging without the clones, then sink the clones.4863if (!DIIClones.empty()) {4864salvageDebugInfoForDbgValues(*I, DbgUsersToSalvage, {});4865// The clones are in reverse order of original appearance, reverse again to4866// maintain the original order.4867for (auto &DIIClone : llvm::reverse(DIIClones)) {4868DIIClone->insertBefore(&*InsertPos);4869LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n');4870}4871}4872}48734874void InstCombinerImpl::tryToSinkInstructionDbgVariableRecords(4875Instruction *I, BasicBlock::iterator InsertPos, BasicBlock *SrcBlock,4876BasicBlock *DestBlock,4877SmallVectorImpl<DbgVariableRecord *> &DbgVariableRecords) {4878// Implementation of tryToSinkInstructionDbgValues, but for the4879// DbgVariableRecord of variable assignments rather than dbg.values.48804881// Fetch all DbgVariableRecords not already in the destination.4882SmallVector<DbgVariableRecord *, 2> DbgVariableRecordsToSalvage;4883for (auto &DVR : DbgVariableRecords)4884if (DVR->getParent() != DestBlock)4885DbgVariableRecordsToSalvage.push_back(DVR);48864887// Fetch a second collection, of DbgVariableRecords in the source block that4888// we're going to sink.4889SmallVector<DbgVariableRecord *> DbgVariableRecordsToSink;4890for (DbgVariableRecord *DVR : DbgVariableRecordsToSalvage)4891if (DVR->getParent() == SrcBlock)4892DbgVariableRecordsToSink.push_back(DVR);48934894// Sort DbgVariableRecords according to their position in the block. This is a4895// partial order: DbgVariableRecords attached to different instructions will4896// be ordered by the instruction order, but DbgVariableRecords attached to the4897// same instruction won't have an order.4898auto Order = [](DbgVariableRecord *A, DbgVariableRecord *B) -> bool {4899return B->getInstruction()->comesBefore(A->getInstruction());4900};4901llvm::stable_sort(DbgVariableRecordsToSink, Order);49024903// If there are two assignments to the same variable attached to the same4904// instruction, the ordering between the two assignments is important. Scan4905// for this (rare) case and establish which is the last assignment.4906using InstVarPair = std::pair<const Instruction *, DebugVariable>;4907SmallDenseMap<InstVarPair, DbgVariableRecord *> FilterOutMap;4908if (DbgVariableRecordsToSink.size() > 1) {4909SmallDenseMap<InstVarPair, unsigned> CountMap;4910// Count how many assignments to each variable there is per instruction.4911for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {4912DebugVariable DbgUserVariable =4913DebugVariable(DVR->getVariable(), DVR->getExpression(),4914DVR->getDebugLoc()->getInlinedAt());4915CountMap[std::make_pair(DVR->getInstruction(), DbgUserVariable)] += 1;4916}49174918// If there are any instructions with two assignments, add them to the4919// FilterOutMap to record that they need extra filtering.4920SmallPtrSet<const Instruction *, 4> DupSet;4921for (auto It : CountMap) {4922if (It.second > 1) {4923FilterOutMap[It.first] = nullptr;4924DupSet.insert(It.first.first);4925}4926}49274928// For all instruction/variable pairs needing extra filtering, find the4929// latest assignment.4930for (const Instruction *Inst : DupSet) {4931for (DbgVariableRecord &DVR :4932llvm::reverse(filterDbgVars(Inst->getDbgRecordRange()))) {4933DebugVariable DbgUserVariable =4934DebugVariable(DVR.getVariable(), DVR.getExpression(),4935DVR.getDebugLoc()->getInlinedAt());4936auto FilterIt =4937FilterOutMap.find(std::make_pair(Inst, DbgUserVariable));4938if (FilterIt == FilterOutMap.end())4939continue;4940if (FilterIt->second != nullptr)4941continue;4942FilterIt->second = &DVR;4943}4944}4945}49464947// Perform cloning of the DbgVariableRecords that we plan on sinking, filter4948// out any duplicate assignments identified above.4949SmallVector<DbgVariableRecord *, 2> DVRClones;4950SmallSet<DebugVariable, 4> SunkVariables;4951for (DbgVariableRecord *DVR : DbgVariableRecordsToSink) {4952if (DVR->Type == DbgVariableRecord::LocationType::Declare)4953continue;49544955DebugVariable DbgUserVariable =4956DebugVariable(DVR->getVariable(), DVR->getExpression(),4957DVR->getDebugLoc()->getInlinedAt());49584959// For any variable where there were multiple assignments in the same place,4960// ignore all but the last assignment.4961if (!FilterOutMap.empty()) {4962InstVarPair IVP = std::make_pair(DVR->getInstruction(), DbgUserVariable);4963auto It = FilterOutMap.find(IVP);49644965// Filter out.4966if (It != FilterOutMap.end() && It->second != DVR)4967continue;4968}49694970if (!SunkVariables.insert(DbgUserVariable).second)4971continue;49724973if (DVR->isDbgAssign())4974continue;49754976DVRClones.emplace_back(DVR->clone());4977LLVM_DEBUG(dbgs() << "CLONE: " << *DVRClones.back() << '\n');4978}49794980// Perform salvaging without the clones, then sink the clones.4981if (DVRClones.empty())4982return;49834984salvageDebugInfoForDbgValues(*I, {}, DbgVariableRecordsToSalvage);49854986// The clones are in reverse order of original appearance. Assert that the4987// head bit is set on the iterator as we _should_ have received it via4988// getFirstInsertionPt. Inserting like this will reverse the clone order as4989// we'll repeatedly insert at the head, such as:4990// DVR-3 (third insertion goes here)4991// DVR-2 (second insertion goes here)4992// DVR-1 (first insertion goes here)4993// Any-Prior-DVRs4994// InsertPtInst4995assert(InsertPos.getHeadBit());4996for (DbgVariableRecord *DVRClone : DVRClones) {4997InsertPos->getParent()->insertDbgRecordBefore(DVRClone, InsertPos);4998LLVM_DEBUG(dbgs() << "SINK: " << *DVRClone << '\n');4999}5000}50015002bool InstCombinerImpl::run() {5003while (!Worklist.isEmpty()) {5004// Walk deferred instructions in reverse order, and push them to the5005// worklist, which means they'll end up popped from the worklist in-order.5006while (Instruction *I = Worklist.popDeferred()) {5007// Check to see if we can DCE the instruction. We do this already here to5008// reduce the number of uses and thus allow other folds to trigger.5009// Note that eraseInstFromFunction() may push additional instructions on5010// the deferred worklist, so this will DCE whole instruction chains.5011if (isInstructionTriviallyDead(I, &TLI)) {5012eraseInstFromFunction(*I);5013++NumDeadInst;5014continue;5015}50165017Worklist.push(I);5018}50195020Instruction *I = Worklist.removeOne();5021if (I == nullptr) continue; // skip null values.50225023// Check to see if we can DCE the instruction.5024if (isInstructionTriviallyDead(I, &TLI)) {5025eraseInstFromFunction(*I);5026++NumDeadInst;5027continue;5028}50295030if (!DebugCounter::shouldExecute(VisitCounter))5031continue;50325033// See if we can trivially sink this instruction to its user if we can5034// prove that the successor is not executed more frequently than our block.5035// Return the UserBlock if successful.5036auto getOptionalSinkBlockForInst =5037[this](Instruction *I) -> std::optional<BasicBlock *> {5038if (!EnableCodeSinking)5039return std::nullopt;50405041BasicBlock *BB = I->getParent();5042BasicBlock *UserParent = nullptr;5043unsigned NumUsers = 0;50445045for (Use &U : I->uses()) {5046User *User = U.getUser();5047if (User->isDroppable())5048continue;5049if (NumUsers > MaxSinkNumUsers)5050return std::nullopt;50515052Instruction *UserInst = cast<Instruction>(User);5053// Special handling for Phi nodes - get the block the use occurs in.5054BasicBlock *UserBB = UserInst->getParent();5055if (PHINode *PN = dyn_cast<PHINode>(UserInst))5056UserBB = PN->getIncomingBlock(U);5057// Bail out if we have uses in different blocks. We don't do any5058// sophisticated analysis (i.e finding NearestCommonDominator of these5059// use blocks).5060if (UserParent && UserParent != UserBB)5061return std::nullopt;5062UserParent = UserBB;50635064// Make sure these checks are done only once, naturally we do the checks5065// the first time we get the userparent, this will save compile time.5066if (NumUsers == 0) {5067// Try sinking to another block. If that block is unreachable, then do5068// not bother. SimplifyCFG should handle it.5069if (UserParent == BB || !DT.isReachableFromEntry(UserParent))5070return std::nullopt;50715072auto *Term = UserParent->getTerminator();5073// See if the user is one of our successors that has only one5074// predecessor, so that we don't have to split the critical edge.5075// Another option where we can sink is a block that ends with a5076// terminator that does not pass control to other block (such as5077// return or unreachable or resume). In this case:5078// - I dominates the User (by SSA form);5079// - the User will be executed at most once.5080// So sinking I down to User is always profitable or neutral.5081if (UserParent->getUniquePredecessor() != BB && !succ_empty(Term))5082return std::nullopt;50835084assert(DT.dominates(BB, UserParent) && "Dominance relation broken?");5085}50865087NumUsers++;5088}50895090// No user or only has droppable users.5091if (!UserParent)5092return std::nullopt;50935094return UserParent;5095};50965097auto OptBB = getOptionalSinkBlockForInst(I);5098if (OptBB) {5099auto *UserParent = *OptBB;5100// Okay, the CFG is simple enough, try to sink this instruction.5101if (tryToSinkInstruction(I, UserParent)) {5102LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n');5103MadeIRChange = true;5104// We'll add uses of the sunk instruction below, but since5105// sinking can expose opportunities for it's *operands* add5106// them to the worklist5107for (Use &U : I->operands())5108if (Instruction *OpI = dyn_cast<Instruction>(U.get()))5109Worklist.push(OpI);5110}5111}51125113// Now that we have an instruction, try combining it to simplify it.5114Builder.SetInsertPoint(I);5115Builder.CollectMetadataToCopy(5116I, {LLVMContext::MD_dbg, LLVMContext::MD_annotation});51175118#ifndef NDEBUG5119std::string OrigI;5120#endif5121LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS););5122LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');51235124if (Instruction *Result = visit(*I)) {5125++NumCombined;5126// Should we replace the old instruction with a new one?5127if (Result != I) {5128LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'5129<< " New = " << *Result << '\n');51305131Result->copyMetadata(*I,5132{LLVMContext::MD_dbg, LLVMContext::MD_annotation});5133// Everything uses the new instruction now.5134I->replaceAllUsesWith(Result);51355136// Move the name to the new instruction first.5137Result->takeName(I);51385139// Insert the new instruction into the basic block...5140BasicBlock *InstParent = I->getParent();5141BasicBlock::iterator InsertPos = I->getIterator();51425143// Are we replace a PHI with something that isn't a PHI, or vice versa?5144if (isa<PHINode>(Result) != isa<PHINode>(I)) {5145// We need to fix up the insertion point.5146if (isa<PHINode>(I)) // PHI -> Non-PHI5147InsertPos = InstParent->getFirstInsertionPt();5148else // Non-PHI -> PHI5149InsertPos = InstParent->getFirstNonPHIIt();5150}51515152Result->insertInto(InstParent, InsertPos);51535154// Push the new instruction and any users onto the worklist.5155Worklist.pushUsersToWorkList(*Result);5156Worklist.push(Result);51575158eraseInstFromFunction(*I);5159} else {5160LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'5161<< " New = " << *I << '\n');51625163// If the instruction was modified, it's possible that it is now dead.5164// if so, remove it.5165if (isInstructionTriviallyDead(I, &TLI)) {5166eraseInstFromFunction(*I);5167} else {5168Worklist.pushUsersToWorkList(*I);5169Worklist.push(I);5170}5171}5172MadeIRChange = true;5173}5174}51755176Worklist.zap();5177return MadeIRChange;5178}51795180// Track the scopes used by !alias.scope and !noalias. In a function, a5181// @llvm.experimental.noalias.scope.decl is only useful if that scope is used5182// by both sets. If not, the declaration of the scope can be safely omitted.5183// The MDNode of the scope can be omitted as well for the instructions that are5184// part of this function. We do not do that at this point, as this might become5185// too time consuming to do.5186class AliasScopeTracker {5187SmallPtrSet<const MDNode *, 8> UsedAliasScopesAndLists;5188SmallPtrSet<const MDNode *, 8> UsedNoAliasScopesAndLists;51895190public:5191void analyse(Instruction *I) {5192// This seems to be faster than checking 'mayReadOrWriteMemory()'.5193if (!I->hasMetadataOtherThanDebugLoc())5194return;51955196auto Track = [](Metadata *ScopeList, auto &Container) {5197const auto *MDScopeList = dyn_cast_or_null<MDNode>(ScopeList);5198if (!MDScopeList || !Container.insert(MDScopeList).second)5199return;5200for (const auto &MDOperand : MDScopeList->operands())5201if (auto *MDScope = dyn_cast<MDNode>(MDOperand))5202Container.insert(MDScope);5203};52045205Track(I->getMetadata(LLVMContext::MD_alias_scope), UsedAliasScopesAndLists);5206Track(I->getMetadata(LLVMContext::MD_noalias), UsedNoAliasScopesAndLists);5207}52085209bool isNoAliasScopeDeclDead(Instruction *Inst) {5210NoAliasScopeDeclInst *Decl = dyn_cast<NoAliasScopeDeclInst>(Inst);5211if (!Decl)5212return false;52135214assert(Decl->use_empty() &&5215"llvm.experimental.noalias.scope.decl in use ?");5216const MDNode *MDSL = Decl->getScopeList();5217assert(MDSL->getNumOperands() == 1 &&5218"llvm.experimental.noalias.scope should refer to a single scope");5219auto &MDOperand = MDSL->getOperand(0);5220if (auto *MD = dyn_cast<MDNode>(MDOperand))5221return !UsedAliasScopesAndLists.contains(MD) ||5222!UsedNoAliasScopesAndLists.contains(MD);52235224// Not an MDNode ? throw away.5225return true;5226}5227};52285229/// Populate the IC worklist from a function, by walking it in reverse5230/// post-order and adding all reachable code to the worklist.5231///5232/// This has a couple of tricks to make the code faster and more powerful. In5233/// particular, we constant fold and DCE instructions as we go, to avoid adding5234/// them to the worklist (this significantly speeds up instcombine on code where5235/// many instructions are dead or constant). Additionally, if we find a branch5236/// whose condition is a known constant, we only visit the reachable successors.5237bool InstCombinerImpl::prepareWorklist(5238Function &F, ReversePostOrderTraversal<BasicBlock *> &RPOT) {5239bool MadeIRChange = false;5240SmallPtrSet<BasicBlock *, 32> LiveBlocks;5241SmallVector<Instruction *, 128> InstrsForInstructionWorklist;5242DenseMap<Constant *, Constant *> FoldedConstants;5243AliasScopeTracker SeenAliasScopes;52445245auto HandleOnlyLiveSuccessor = [&](BasicBlock *BB, BasicBlock *LiveSucc) {5246for (BasicBlock *Succ : successors(BB))5247if (Succ != LiveSucc && DeadEdges.insert({BB, Succ}).second)5248for (PHINode &PN : Succ->phis())5249for (Use &U : PN.incoming_values())5250if (PN.getIncomingBlock(U) == BB && !isa<PoisonValue>(U)) {5251U.set(PoisonValue::get(PN.getType()));5252MadeIRChange = true;5253}5254};52555256for (BasicBlock *BB : RPOT) {5257if (!BB->isEntryBlock() && all_of(predecessors(BB), [&](BasicBlock *Pred) {5258return DeadEdges.contains({Pred, BB}) || DT.dominates(BB, Pred);5259})) {5260HandleOnlyLiveSuccessor(BB, nullptr);5261continue;5262}5263LiveBlocks.insert(BB);52645265for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {5266// ConstantProp instruction if trivially constant.5267if (!Inst.use_empty() &&5268(Inst.getNumOperands() == 0 || isa<Constant>(Inst.getOperand(0))))5269if (Constant *C = ConstantFoldInstruction(&Inst, DL, &TLI)) {5270LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << Inst5271<< '\n');5272Inst.replaceAllUsesWith(C);5273++NumConstProp;5274if (isInstructionTriviallyDead(&Inst, &TLI))5275Inst.eraseFromParent();5276MadeIRChange = true;5277continue;5278}52795280// See if we can constant fold its operands.5281for (Use &U : Inst.operands()) {5282if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))5283continue;52845285auto *C = cast<Constant>(U);5286Constant *&FoldRes = FoldedConstants[C];5287if (!FoldRes)5288FoldRes = ConstantFoldConstant(C, DL, &TLI);52895290if (FoldRes != C) {5291LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << Inst5292<< "\n Old = " << *C5293<< "\n New = " << *FoldRes << '\n');5294U = FoldRes;5295MadeIRChange = true;5296}5297}52985299// Skip processing debug and pseudo intrinsics in InstCombine. Processing5300// these call instructions consumes non-trivial amount of time and5301// provides no value for the optimization.5302if (!Inst.isDebugOrPseudoInst()) {5303InstrsForInstructionWorklist.push_back(&Inst);5304SeenAliasScopes.analyse(&Inst);5305}5306}53075308// If this is a branch or switch on a constant, mark only the single5309// live successor. Otherwise assume all successors are live.5310Instruction *TI = BB->getTerminator();5311if (BranchInst *BI = dyn_cast<BranchInst>(TI); BI && BI->isConditional()) {5312if (isa<UndefValue>(BI->getCondition())) {5313// Branch on undef is UB.5314HandleOnlyLiveSuccessor(BB, nullptr);5315continue;5316}5317if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {5318bool CondVal = Cond->getZExtValue();5319HandleOnlyLiveSuccessor(BB, BI->getSuccessor(!CondVal));5320continue;5321}5322} else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {5323if (isa<UndefValue>(SI->getCondition())) {5324// Switch on undef is UB.5325HandleOnlyLiveSuccessor(BB, nullptr);5326continue;5327}5328if (auto *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {5329HandleOnlyLiveSuccessor(BB,5330SI->findCaseValue(Cond)->getCaseSuccessor());5331continue;5332}5333}5334}53355336// Remove instructions inside unreachable blocks. This prevents the5337// instcombine code from having to deal with some bad special cases, and5338// reduces use counts of instructions.5339for (BasicBlock &BB : F) {5340if (LiveBlocks.count(&BB))5341continue;53425343unsigned NumDeadInstInBB;5344unsigned NumDeadDbgInstInBB;5345std::tie(NumDeadInstInBB, NumDeadDbgInstInBB) =5346removeAllNonTerminatorAndEHPadInstructions(&BB);53475348MadeIRChange |= NumDeadInstInBB + NumDeadDbgInstInBB > 0;5349NumDeadInst += NumDeadInstInBB;5350}53515352// Once we've found all of the instructions to add to instcombine's worklist,5353// add them in reverse order. This way instcombine will visit from the top5354// of the function down. This jives well with the way that it adds all uses5355// of instructions to the worklist after doing a transformation, thus avoiding5356// some N^2 behavior in pathological cases.5357Worklist.reserve(InstrsForInstructionWorklist.size());5358for (Instruction *Inst : reverse(InstrsForInstructionWorklist)) {5359// DCE instruction if trivially dead. As we iterate in reverse program5360// order here, we will clean up whole chains of dead instructions.5361if (isInstructionTriviallyDead(Inst, &TLI) ||5362SeenAliasScopes.isNoAliasScopeDeclDead(Inst)) {5363++NumDeadInst;5364LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');5365salvageDebugInfo(*Inst);5366Inst->eraseFromParent();5367MadeIRChange = true;5368continue;5369}53705371Worklist.push(Inst);5372}53735374return MadeIRChange;5375}53765377static bool combineInstructionsOverFunction(5378Function &F, InstructionWorklist &Worklist, AliasAnalysis *AA,5379AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI,5380DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,5381BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI, LoopInfo *LI,5382const InstCombineOptions &Opts) {5383auto &DL = F.getDataLayout();53845385/// Builder - This is an IRBuilder that automatically inserts new5386/// instructions into the worklist when they are created.5387IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(5388F.getContext(), TargetFolder(DL),5389IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {5390Worklist.add(I);5391if (auto *Assume = dyn_cast<AssumeInst>(I))5392AC.registerAssumption(Assume);5393}));53945395ReversePostOrderTraversal<BasicBlock *> RPOT(&F.front());53965397// Lower dbg.declare intrinsics otherwise their value may be clobbered5398// by instcombiner.5399bool MadeIRChange = false;5400if (ShouldLowerDbgDeclare)5401MadeIRChange = LowerDbgDeclare(F);54025403// Iterate while there is work to do.5404unsigned Iteration = 0;5405while (true) {5406++Iteration;54075408if (Iteration > Opts.MaxIterations && !Opts.VerifyFixpoint) {5409LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << Opts.MaxIterations5410<< " on " << F.getName()5411<< " reached; stopping without verifying fixpoint\n");5412break;5413}54145415++NumWorklistIterations;5416LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "5417<< F.getName() << "\n");54185419InstCombinerImpl IC(Worklist, Builder, F.hasMinSize(), AA, AC, TLI, TTI, DT,5420ORE, BFI, BPI, PSI, DL, LI);5421IC.MaxArraySizeForCombine = MaxArraySize;5422bool MadeChangeInThisIteration = IC.prepareWorklist(F, RPOT);5423MadeChangeInThisIteration |= IC.run();5424if (!MadeChangeInThisIteration)5425break;54265427MadeIRChange = true;5428if (Iteration > Opts.MaxIterations) {5429report_fatal_error(5430"Instruction Combining did not reach a fixpoint after " +5431Twine(Opts.MaxIterations) + " iterations",5432/*GenCrashDiag=*/false);5433}5434}54355436if (Iteration == 1)5437++NumOneIteration;5438else if (Iteration == 2)5439++NumTwoIterations;5440else if (Iteration == 3)5441++NumThreeIterations;5442else5443++NumFourOrMoreIterations;54445445return MadeIRChange;5446}54475448InstCombinePass::InstCombinePass(InstCombineOptions Opts) : Options(Opts) {}54495450void InstCombinePass::printPipeline(5451raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {5452static_cast<PassInfoMixin<InstCombinePass> *>(this)->printPipeline(5453OS, MapClassName2PassName);5454OS << '<';5455OS << "max-iterations=" << Options.MaxIterations << ";";5456OS << (Options.UseLoopInfo ? "" : "no-") << "use-loop-info;";5457OS << (Options.VerifyFixpoint ? "" : "no-") << "verify-fixpoint";5458OS << '>';5459}54605461PreservedAnalyses InstCombinePass::run(Function &F,5462FunctionAnalysisManager &AM) {5463auto &AC = AM.getResult<AssumptionAnalysis>(F);5464auto &DT = AM.getResult<DominatorTreeAnalysis>(F);5465auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);5466auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);5467auto &TTI = AM.getResult<TargetIRAnalysis>(F);54685469// TODO: Only use LoopInfo when the option is set. This requires that the5470// callers in the pass pipeline explicitly set the option.5471auto *LI = AM.getCachedResult<LoopAnalysis>(F);5472if (!LI && Options.UseLoopInfo)5473LI = &AM.getResult<LoopAnalysis>(F);54745475auto *AA = &AM.getResult<AAManager>(F);5476auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);5477ProfileSummaryInfo *PSI =5478MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());5479auto *BFI = (PSI && PSI->hasProfileSummary()) ?5480&AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;5481auto *BPI = AM.getCachedResult<BranchProbabilityAnalysis>(F);54825483if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,5484BFI, BPI, PSI, LI, Options))5485// No changes, all analyses are preserved.5486return PreservedAnalyses::all();54875488// Mark all the analyses that instcombine updates as preserved.5489PreservedAnalyses PA;5490PA.preserveSet<CFGAnalyses>();5491return PA;5492}54935494void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {5495AU.setPreservesCFG();5496AU.addRequired<AAResultsWrapperPass>();5497AU.addRequired<AssumptionCacheTracker>();5498AU.addRequired<TargetLibraryInfoWrapperPass>();5499AU.addRequired<TargetTransformInfoWrapperPass>();5500AU.addRequired<DominatorTreeWrapperPass>();5501AU.addRequired<OptimizationRemarkEmitterWrapperPass>();5502AU.addPreserved<DominatorTreeWrapperPass>();5503AU.addPreserved<AAResultsWrapperPass>();5504AU.addPreserved<BasicAAWrapperPass>();5505AU.addPreserved<GlobalsAAWrapperPass>();5506AU.addRequired<ProfileSummaryInfoWrapperPass>();5507LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);5508}55095510bool InstructionCombiningPass::runOnFunction(Function &F) {5511if (skipFunction(F))5512return false;55135514// Required analyses.5515auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();5516auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);5517auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);5518auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);5519auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();5520auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();55215522// Optional analyses.5523auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();5524auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;5525ProfileSummaryInfo *PSI =5526&getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();5527BlockFrequencyInfo *BFI =5528(PSI && PSI->hasProfileSummary()) ?5529&getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :5530nullptr;5531BranchProbabilityInfo *BPI = nullptr;5532if (auto *WrapperPass =5533getAnalysisIfAvailable<BranchProbabilityInfoWrapperPass>())5534BPI = &WrapperPass->getBPI();55355536return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,5537BFI, BPI, PSI, LI,5538InstCombineOptions());5539}55405541char InstructionCombiningPass::ID = 0;55425543InstructionCombiningPass::InstructionCombiningPass() : FunctionPass(ID) {5544initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());5545}55465547INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",5548"Combine redundant instructions", false, false)5549INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)5550INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)5551INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)5552INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)5553INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)5554INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)5555INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)5556INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)5557INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)5558INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",5559"Combine redundant instructions", false, false)55605561// Initialization Routines5562void llvm::initializeInstCombine(PassRegistry &Registry) {5563initializeInstructionCombiningPassPass(Registry);5564}55655566FunctionPass *llvm::createInstructionCombiningPass() {5567return new InstructionCombiningPass();5568}556955705571