15ffd83dbSDimitry Andric //===- InstCombineNegator.cpp -----------------------------------*- C++ -*-===// 25ffd83dbSDimitry Andric // 35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 65ffd83dbSDimitry Andric // 75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===// 85ffd83dbSDimitry Andric // 95ffd83dbSDimitry Andric // This file implements sinking of negation into expression trees, 105ffd83dbSDimitry Andric // as long as that can be done without increasing instruction count. 115ffd83dbSDimitry Andric // 125ffd83dbSDimitry Andric //===----------------------------------------------------------------------===// 135ffd83dbSDimitry Andric 145ffd83dbSDimitry Andric #include "InstCombineInternal.h" 155ffd83dbSDimitry Andric #include "llvm/ADT/APInt.h" 165ffd83dbSDimitry Andric #include "llvm/ADT/ArrayRef.h" 175ffd83dbSDimitry Andric #include "llvm/ADT/DenseMap.h" 185ffd83dbSDimitry Andric #include "llvm/ADT/STLExtras.h" 195ffd83dbSDimitry Andric #include "llvm/ADT/SmallVector.h" 205ffd83dbSDimitry Andric #include "llvm/ADT/Statistic.h" 215ffd83dbSDimitry Andric #include "llvm/ADT/StringRef.h" 225ffd83dbSDimitry Andric #include "llvm/ADT/Twine.h" 235ffd83dbSDimitry Andric #include "llvm/Analysis/TargetFolder.h" 245ffd83dbSDimitry Andric #include "llvm/Analysis/ValueTracking.h" 255ffd83dbSDimitry Andric #include "llvm/IR/Constant.h" 265ffd83dbSDimitry Andric #include "llvm/IR/Constants.h" 275ffd83dbSDimitry Andric #include "llvm/IR/DebugLoc.h" 285ffd83dbSDimitry Andric #include "llvm/IR/IRBuilder.h" 295ffd83dbSDimitry Andric #include "llvm/IR/Instruction.h" 305ffd83dbSDimitry Andric #include "llvm/IR/Instructions.h" 315ffd83dbSDimitry Andric #include "llvm/IR/PatternMatch.h" 325ffd83dbSDimitry Andric #include "llvm/IR/Type.h" 335ffd83dbSDimitry Andric #include "llvm/IR/Use.h" 345ffd83dbSDimitry Andric #include "llvm/IR/User.h" 355ffd83dbSDimitry Andric #include "llvm/IR/Value.h" 365ffd83dbSDimitry Andric #include "llvm/Support/Casting.h" 375ffd83dbSDimitry Andric #include "llvm/Support/CommandLine.h" 385ffd83dbSDimitry Andric #include "llvm/Support/Compiler.h" 395ffd83dbSDimitry Andric #include "llvm/Support/DebugCounter.h" 405ffd83dbSDimitry Andric #include "llvm/Support/ErrorHandling.h" 415ffd83dbSDimitry Andric #include "llvm/Support/raw_ostream.h" 42e8d8bef9SDimitry Andric #include "llvm/Transforms/InstCombine/InstCombiner.h" 43e8d8bef9SDimitry Andric #include <cassert> 44e8d8bef9SDimitry Andric #include <cstdint> 455ffd83dbSDimitry Andric #include <functional> 465ffd83dbSDimitry Andric #include <type_traits> 475ffd83dbSDimitry Andric #include <utility> 485ffd83dbSDimitry Andric 495ffd83dbSDimitry Andric namespace llvm { 505ffd83dbSDimitry Andric class DataLayout; 515ffd83dbSDimitry Andric class LLVMContext; 525ffd83dbSDimitry Andric } // namespace llvm 535ffd83dbSDimitry Andric 545ffd83dbSDimitry Andric using namespace llvm; 555ffd83dbSDimitry Andric 565ffd83dbSDimitry Andric #define DEBUG_TYPE "instcombine" 575ffd83dbSDimitry Andric 585ffd83dbSDimitry Andric STATISTIC(NegatorTotalNegationsAttempted, 595ffd83dbSDimitry Andric "Negator: Number of negations attempted to be sinked"); 605ffd83dbSDimitry Andric STATISTIC(NegatorNumTreesNegated, 615ffd83dbSDimitry Andric "Negator: Number of negations successfully sinked"); 625ffd83dbSDimitry Andric STATISTIC(NegatorMaxDepthVisited, "Negator: Maximal traversal depth ever " 635ffd83dbSDimitry Andric "reached while attempting to sink negation"); 645ffd83dbSDimitry Andric STATISTIC(NegatorTimesDepthLimitReached, 655ffd83dbSDimitry Andric "Negator: How many times did the traversal depth limit was reached " 665ffd83dbSDimitry Andric "during sinking"); 675ffd83dbSDimitry Andric STATISTIC( 685ffd83dbSDimitry Andric NegatorNumValuesVisited, 695ffd83dbSDimitry Andric "Negator: Total number of values visited during attempts to sink negation"); 705ffd83dbSDimitry Andric STATISTIC(NegatorNumNegationsFoundInCache, 715ffd83dbSDimitry Andric "Negator: How many negations did we retrieve/reuse from cache"); 725ffd83dbSDimitry Andric STATISTIC(NegatorMaxTotalValuesVisited, 735ffd83dbSDimitry Andric "Negator: Maximal number of values ever visited while attempting to " 745ffd83dbSDimitry Andric "sink negation"); 755ffd83dbSDimitry Andric STATISTIC(NegatorNumInstructionsCreatedTotal, 765ffd83dbSDimitry Andric "Negator: Number of new negated instructions created, total"); 775ffd83dbSDimitry Andric STATISTIC(NegatorMaxInstructionsCreated, 785ffd83dbSDimitry Andric "Negator: Maximal number of new instructions created during negation " 795ffd83dbSDimitry Andric "attempt"); 805ffd83dbSDimitry Andric STATISTIC(NegatorNumInstructionsNegatedSuccess, 815ffd83dbSDimitry Andric "Negator: Number of new negated instructions created in successful " 825ffd83dbSDimitry Andric "negation sinking attempts"); 835ffd83dbSDimitry Andric 845ffd83dbSDimitry Andric DEBUG_COUNTER(NegatorCounter, "instcombine-negator", 855ffd83dbSDimitry Andric "Controls Negator transformations in InstCombine pass"); 865ffd83dbSDimitry Andric 875ffd83dbSDimitry Andric static cl::opt<bool> 885ffd83dbSDimitry Andric NegatorEnabled("instcombine-negator-enabled", cl::init(true), 895ffd83dbSDimitry Andric cl::desc("Should we attempt to sink negations?")); 905ffd83dbSDimitry Andric 915ffd83dbSDimitry Andric static cl::opt<unsigned> 925ffd83dbSDimitry Andric NegatorMaxDepth("instcombine-negator-max-depth", 935ffd83dbSDimitry Andric cl::init(NegatorDefaultMaxDepth), 945ffd83dbSDimitry Andric cl::desc("What is the maximal lookup depth when trying to " 955ffd83dbSDimitry Andric "check for viability of negation sinking.")); 965ffd83dbSDimitry Andric 975f757f3fSDimitry Andric Negator::Negator(LLVMContext &C, const DataLayout &DL, bool IsTrulyNegation_) 985f757f3fSDimitry Andric : Builder(C, TargetFolder(DL), 995ffd83dbSDimitry Andric IRBuilderCallbackInserter([&](Instruction *I) { 1005ffd83dbSDimitry Andric ++NegatorNumInstructionsCreatedTotal; 1015ffd83dbSDimitry Andric NewInstructions.push_back(I); 1025ffd83dbSDimitry Andric })), 1035f757f3fSDimitry Andric IsTrulyNegation(IsTrulyNegation_) {} 1045ffd83dbSDimitry Andric 1055ffd83dbSDimitry Andric #if LLVM_ENABLE_STATS 1065ffd83dbSDimitry Andric Negator::~Negator() { 1075ffd83dbSDimitry Andric NegatorMaxTotalValuesVisited.updateMax(NumValuesVisitedInThisNegator); 1085ffd83dbSDimitry Andric } 1095ffd83dbSDimitry Andric #endif 1105ffd83dbSDimitry Andric 111e8d8bef9SDimitry Andric // Due to the InstCombine's worklist management, there are no guarantees that 112e8d8bef9SDimitry Andric // each instruction we'll encounter has been visited by InstCombine already. 113e8d8bef9SDimitry Andric // In particular, most importantly for us, that means we have to canonicalize 114e8d8bef9SDimitry Andric // constants to RHS ourselves, since that is helpful sometimes. 115e8d8bef9SDimitry Andric std::array<Value *, 2> Negator::getSortedOperandsOfBinOp(Instruction *I) { 116e8d8bef9SDimitry Andric assert(I->getNumOperands() == 2 && "Only for binops!"); 117e8d8bef9SDimitry Andric std::array<Value *, 2> Ops{I->getOperand(0), I->getOperand(1)}; 118e8d8bef9SDimitry Andric if (I->isCommutative() && InstCombiner::getComplexity(I->getOperand(0)) < 119e8d8bef9SDimitry Andric InstCombiner::getComplexity(I->getOperand(1))) 120e8d8bef9SDimitry Andric std::swap(Ops[0], Ops[1]); 121e8d8bef9SDimitry Andric return Ops; 122e8d8bef9SDimitry Andric } 123e8d8bef9SDimitry Andric 1245ffd83dbSDimitry Andric // FIXME: can this be reworked into a worklist-based algorithm while preserving 1255ffd83dbSDimitry Andric // the depth-first, early bailout traversal? 1265f757f3fSDimitry Andric [[nodiscard]] Value *Negator::visitImpl(Value *V, bool IsNSW, unsigned Depth) { 1275ffd83dbSDimitry Andric // -(undef) -> undef. 1285ffd83dbSDimitry Andric if (match(V, m_Undef())) 1295ffd83dbSDimitry Andric return V; 1305ffd83dbSDimitry Andric 1315ffd83dbSDimitry Andric // In i1, negation can simply be ignored. 1325ffd83dbSDimitry Andric if (V->getType()->isIntOrIntVectorTy(1)) 1335ffd83dbSDimitry Andric return V; 1345ffd83dbSDimitry Andric 1355ffd83dbSDimitry Andric Value *X; 1365ffd83dbSDimitry Andric 1375ffd83dbSDimitry Andric // -(-(X)) -> X. 1385ffd83dbSDimitry Andric if (match(V, m_Neg(m_Value(X)))) 1395ffd83dbSDimitry Andric return X; 1405ffd83dbSDimitry Andric 1415ffd83dbSDimitry Andric // Integral constants can be freely negated. 1425ffd83dbSDimitry Andric if (match(V, m_AnyIntegralConstant())) 1430fca6ea1SDimitry Andric return ConstantExpr::getNeg(cast<Constant>(V), 1445ffd83dbSDimitry Andric /*HasNSW=*/false); 1455ffd83dbSDimitry Andric 1465ffd83dbSDimitry Andric // If we have a non-instruction, then give up. 1475ffd83dbSDimitry Andric if (!isa<Instruction>(V)) 1485ffd83dbSDimitry Andric return nullptr; 1495ffd83dbSDimitry Andric 1505ffd83dbSDimitry Andric // If we have started with a true negation (i.e. `sub 0, %y`), then if we've 1515ffd83dbSDimitry Andric // got instruction that does not require recursive reasoning, we can still 1525ffd83dbSDimitry Andric // negate it even if it has other uses, without increasing instruction count. 1535ffd83dbSDimitry Andric if (!V->hasOneUse() && !IsTrulyNegation) 1545ffd83dbSDimitry Andric return nullptr; 1555ffd83dbSDimitry Andric 1565ffd83dbSDimitry Andric auto *I = cast<Instruction>(V); 1575ffd83dbSDimitry Andric unsigned BitWidth = I->getType()->getScalarSizeInBits(); 1585ffd83dbSDimitry Andric 1595ffd83dbSDimitry Andric // We must preserve the insertion point and debug info that is set in the 1605ffd83dbSDimitry Andric // builder at the time this function is called. 1615ffd83dbSDimitry Andric InstCombiner::BuilderTy::InsertPointGuard Guard(Builder); 1625ffd83dbSDimitry Andric // And since we are trying to negate instruction I, that tells us about the 1635ffd83dbSDimitry Andric // insertion point and the debug info that we need to keep. 1645ffd83dbSDimitry Andric Builder.SetInsertPoint(I); 1655ffd83dbSDimitry Andric 1665ffd83dbSDimitry Andric // In some cases we can give the answer without further recursion. 1675ffd83dbSDimitry Andric switch (I->getOpcode()) { 168e8d8bef9SDimitry Andric case Instruction::Add: { 169e8d8bef9SDimitry Andric std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I); 1705ffd83dbSDimitry Andric // `inc` is always negatible. 171e8d8bef9SDimitry Andric if (match(Ops[1], m_One())) 172e8d8bef9SDimitry Andric return Builder.CreateNot(Ops[0], I->getName() + ".neg"); 1735ffd83dbSDimitry Andric break; 174e8d8bef9SDimitry Andric } 1755ffd83dbSDimitry Andric case Instruction::Xor: 1765ffd83dbSDimitry Andric // `not` is always negatible. 1775ffd83dbSDimitry Andric if (match(I, m_Not(m_Value(X)))) 1785ffd83dbSDimitry Andric return Builder.CreateAdd(X, ConstantInt::get(X->getType(), 1), 1795ffd83dbSDimitry Andric I->getName() + ".neg"); 1805ffd83dbSDimitry Andric break; 1815ffd83dbSDimitry Andric case Instruction::AShr: 1825ffd83dbSDimitry Andric case Instruction::LShr: { 1835ffd83dbSDimitry Andric // Right-shift sign bit smear is negatible. 1845ffd83dbSDimitry Andric const APInt *Op1Val; 1855ffd83dbSDimitry Andric if (match(I->getOperand(1), m_APInt(Op1Val)) && *Op1Val == BitWidth - 1) { 1865ffd83dbSDimitry Andric Value *BO = I->getOpcode() == Instruction::AShr 1875ffd83dbSDimitry Andric ? Builder.CreateLShr(I->getOperand(0), I->getOperand(1)) 1885ffd83dbSDimitry Andric : Builder.CreateAShr(I->getOperand(0), I->getOperand(1)); 1895ffd83dbSDimitry Andric if (auto *NewInstr = dyn_cast<Instruction>(BO)) { 1905ffd83dbSDimitry Andric NewInstr->copyIRFlags(I); 1915ffd83dbSDimitry Andric NewInstr->setName(I->getName() + ".neg"); 1925ffd83dbSDimitry Andric } 1935ffd83dbSDimitry Andric return BO; 1945ffd83dbSDimitry Andric } 195e8d8bef9SDimitry Andric // While we could negate exact arithmetic shift: 196e8d8bef9SDimitry Andric // ashr exact %x, C --> sdiv exact i8 %x, -1<<C 197e8d8bef9SDimitry Andric // iff C != 0 and C u< bitwidth(%x), we don't want to, 198e8d8bef9SDimitry Andric // because division is *THAT* much worse than a shift. 1995ffd83dbSDimitry Andric break; 2005ffd83dbSDimitry Andric } 2015ffd83dbSDimitry Andric case Instruction::SExt: 2025ffd83dbSDimitry Andric case Instruction::ZExt: 2035ffd83dbSDimitry Andric // `*ext` of i1 is always negatible 2045ffd83dbSDimitry Andric if (I->getOperand(0)->getType()->isIntOrIntVectorTy(1)) 2055ffd83dbSDimitry Andric return I->getOpcode() == Instruction::SExt 2065ffd83dbSDimitry Andric ? Builder.CreateZExt(I->getOperand(0), I->getType(), 2075ffd83dbSDimitry Andric I->getName() + ".neg") 2085ffd83dbSDimitry Andric : Builder.CreateSExt(I->getOperand(0), I->getType(), 2095ffd83dbSDimitry Andric I->getName() + ".neg"); 2105ffd83dbSDimitry Andric break; 211349cc55cSDimitry Andric case Instruction::Select: { 212349cc55cSDimitry Andric // If both arms of the select are constants, we don't need to recurse. 213349cc55cSDimitry Andric // Therefore, this transform is not limited by uses. 214349cc55cSDimitry Andric auto *Sel = cast<SelectInst>(I); 215349cc55cSDimitry Andric Constant *TrueC, *FalseC; 216349cc55cSDimitry Andric if (match(Sel->getTrueValue(), m_ImmConstant(TrueC)) && 217349cc55cSDimitry Andric match(Sel->getFalseValue(), m_ImmConstant(FalseC))) { 218349cc55cSDimitry Andric Constant *NegTrueC = ConstantExpr::getNeg(TrueC); 219349cc55cSDimitry Andric Constant *NegFalseC = ConstantExpr::getNeg(FalseC); 220349cc55cSDimitry Andric return Builder.CreateSelect(Sel->getCondition(), NegTrueC, NegFalseC, 221349cc55cSDimitry Andric I->getName() + ".neg", /*MDFrom=*/I); 222349cc55cSDimitry Andric } 223349cc55cSDimitry Andric break; 224349cc55cSDimitry Andric } 2250fca6ea1SDimitry Andric case Instruction::Call: 2260fca6ea1SDimitry Andric if (auto *CI = dyn_cast<CmpIntrinsic>(I); CI && CI->hasOneUse()) 2270fca6ea1SDimitry Andric return Builder.CreateIntrinsic(CI->getType(), CI->getIntrinsicID(), 2280fca6ea1SDimitry Andric {CI->getRHS(), CI->getLHS()}); 2290fca6ea1SDimitry Andric break; 2305ffd83dbSDimitry Andric default: 2315ffd83dbSDimitry Andric break; // Other instructions require recursive reasoning. 2325ffd83dbSDimitry Andric } 2335ffd83dbSDimitry Andric 234e8d8bef9SDimitry Andric if (I->getOpcode() == Instruction::Sub && 235e8d8bef9SDimitry Andric (I->hasOneUse() || match(I->getOperand(0), m_ImmConstant()))) { 236e8d8bef9SDimitry Andric // `sub` is always negatible. 237e8d8bef9SDimitry Andric // However, only do this either if the old `sub` doesn't stick around, or 238e8d8bef9SDimitry Andric // it was subtracting from a constant. Otherwise, this isn't profitable. 239e8d8bef9SDimitry Andric return Builder.CreateSub(I->getOperand(1), I->getOperand(0), 2405f757f3fSDimitry Andric I->getName() + ".neg", /* HasNUW */ false, 2415f757f3fSDimitry Andric IsNSW && I->hasNoSignedWrap()); 242e8d8bef9SDimitry Andric } 243e8d8bef9SDimitry Andric 2445ffd83dbSDimitry Andric // Some other cases, while still don't require recursion, 2455ffd83dbSDimitry Andric // are restricted to the one-use case. 2465ffd83dbSDimitry Andric if (!V->hasOneUse()) 2475ffd83dbSDimitry Andric return nullptr; 2485ffd83dbSDimitry Andric 2495ffd83dbSDimitry Andric switch (I->getOpcode()) { 250bdd1243dSDimitry Andric case Instruction::ZExt: { 251bdd1243dSDimitry Andric // Negation of zext of signbit is signbit splat: 252bdd1243dSDimitry Andric // 0 - (zext (i8 X u>> 7) to iN) --> sext (i8 X s>> 7) to iN 253bdd1243dSDimitry Andric Value *SrcOp = I->getOperand(0); 254bdd1243dSDimitry Andric unsigned SrcWidth = SrcOp->getType()->getScalarSizeInBits(); 255bdd1243dSDimitry Andric const APInt &FullShift = APInt(SrcWidth, SrcWidth - 1); 256bdd1243dSDimitry Andric if (IsTrulyNegation && 2570fca6ea1SDimitry Andric match(SrcOp, m_LShr(m_Value(X), m_SpecificIntAllowPoison(FullShift)))) { 258bdd1243dSDimitry Andric Value *Ashr = Builder.CreateAShr(X, FullShift); 259bdd1243dSDimitry Andric return Builder.CreateSExt(Ashr, I->getType()); 260bdd1243dSDimitry Andric } 261bdd1243dSDimitry Andric break; 262bdd1243dSDimitry Andric } 26381ad6265SDimitry Andric case Instruction::And: { 26481ad6265SDimitry Andric Constant *ShAmt; 26581ad6265SDimitry Andric // sub(y,and(lshr(x,C),1)) --> add(ashr(shl(x,(BW-1)-C),BW-1),y) 2660fca6ea1SDimitry Andric if (match(I, m_And(m_OneUse(m_TruncOrSelf( 26781ad6265SDimitry Andric m_LShr(m_Value(X), m_ImmConstant(ShAmt)))), 26881ad6265SDimitry Andric m_One()))) { 26981ad6265SDimitry Andric unsigned BW = X->getType()->getScalarSizeInBits(); 27081ad6265SDimitry Andric Constant *BWMinusOne = ConstantInt::get(X->getType(), BW - 1); 27181ad6265SDimitry Andric Value *R = Builder.CreateShl(X, Builder.CreateSub(BWMinusOne, ShAmt)); 27281ad6265SDimitry Andric R = Builder.CreateAShr(R, BWMinusOne); 27381ad6265SDimitry Andric return Builder.CreateTruncOrBitCast(R, I->getType()); 27481ad6265SDimitry Andric } 27581ad6265SDimitry Andric break; 27681ad6265SDimitry Andric } 2775ffd83dbSDimitry Andric case Instruction::SDiv: 2785ffd83dbSDimitry Andric // `sdiv` is negatible if divisor is not undef/INT_MIN/1. 2795ffd83dbSDimitry Andric // While this is normally not behind a use-check, 2805ffd83dbSDimitry Andric // let's consider division to be special since it's costly. 2815ffd83dbSDimitry Andric if (auto *Op1C = dyn_cast<Constant>(I->getOperand(1))) { 282e8d8bef9SDimitry Andric if (!Op1C->containsUndefOrPoisonElement() && 283e8d8bef9SDimitry Andric Op1C->isNotMinSignedValue() && Op1C->isNotOneValue()) { 2845ffd83dbSDimitry Andric Value *BO = 2855ffd83dbSDimitry Andric Builder.CreateSDiv(I->getOperand(0), ConstantExpr::getNeg(Op1C), 2865ffd83dbSDimitry Andric I->getName() + ".neg"); 2875ffd83dbSDimitry Andric if (auto *NewInstr = dyn_cast<Instruction>(BO)) 2885ffd83dbSDimitry Andric NewInstr->setIsExact(I->isExact()); 2895ffd83dbSDimitry Andric return BO; 2905ffd83dbSDimitry Andric } 2915ffd83dbSDimitry Andric } 2925ffd83dbSDimitry Andric break; 2935ffd83dbSDimitry Andric } 2945ffd83dbSDimitry Andric 2955ffd83dbSDimitry Andric // Rest of the logic is recursive, so if it's time to give up then it's time. 2965ffd83dbSDimitry Andric if (Depth > NegatorMaxDepth) { 2975ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Negator: reached maximal allowed traversal depth in " 2985ffd83dbSDimitry Andric << *V << ". Giving up.\n"); 2995ffd83dbSDimitry Andric ++NegatorTimesDepthLimitReached; 3005ffd83dbSDimitry Andric return nullptr; 3015ffd83dbSDimitry Andric } 3025ffd83dbSDimitry Andric 3035ffd83dbSDimitry Andric switch (I->getOpcode()) { 304e8d8bef9SDimitry Andric case Instruction::Freeze: { 305e8d8bef9SDimitry Andric // `freeze` is negatible if its operand is negatible. 3065f757f3fSDimitry Andric Value *NegOp = negate(I->getOperand(0), IsNSW, Depth + 1); 307e8d8bef9SDimitry Andric if (!NegOp) // Early return. 308e8d8bef9SDimitry Andric return nullptr; 309e8d8bef9SDimitry Andric return Builder.CreateFreeze(NegOp, I->getName() + ".neg"); 310e8d8bef9SDimitry Andric } 3115ffd83dbSDimitry Andric case Instruction::PHI: { 3125ffd83dbSDimitry Andric // `phi` is negatible if all the incoming values are negatible. 3135ffd83dbSDimitry Andric auto *PHI = cast<PHINode>(I); 3145ffd83dbSDimitry Andric SmallVector<Value *, 4> NegatedIncomingValues(PHI->getNumOperands()); 3155ffd83dbSDimitry Andric for (auto I : zip(PHI->incoming_values(), NegatedIncomingValues)) { 3165ffd83dbSDimitry Andric if (!(std::get<1>(I) = 3175f757f3fSDimitry Andric negate(std::get<0>(I), IsNSW, Depth + 1))) // Early return. 3185ffd83dbSDimitry Andric return nullptr; 3195ffd83dbSDimitry Andric } 3205ffd83dbSDimitry Andric // All incoming values are indeed negatible. Create negated PHI node. 3215ffd83dbSDimitry Andric PHINode *NegatedPHI = Builder.CreatePHI( 3225ffd83dbSDimitry Andric PHI->getType(), PHI->getNumOperands(), PHI->getName() + ".neg"); 3235ffd83dbSDimitry Andric for (auto I : zip(NegatedIncomingValues, PHI->blocks())) 3245ffd83dbSDimitry Andric NegatedPHI->addIncoming(std::get<0>(I), std::get<1>(I)); 3255ffd83dbSDimitry Andric return NegatedPHI; 3265ffd83dbSDimitry Andric } 3275ffd83dbSDimitry Andric case Instruction::Select: { 3280fca6ea1SDimitry Andric if (isKnownNegation(I->getOperand(1), I->getOperand(2), /*NeedNSW=*/false, 3290fca6ea1SDimitry Andric /*AllowPoison=*/false)) { 330e8d8bef9SDimitry Andric // Of one hand of select is known to be negation of another hand, 331e8d8bef9SDimitry Andric // just swap the hands around. 3325ffd83dbSDimitry Andric auto *NewSelect = cast<SelectInst>(I->clone()); 3335ffd83dbSDimitry Andric // Just swap the operands of the select. 3345ffd83dbSDimitry Andric NewSelect->swapValues(); 3355ffd83dbSDimitry Andric // Don't swap prof metadata, we didn't change the branch behavior. 3365ffd83dbSDimitry Andric NewSelect->setName(I->getName() + ".neg"); 337*415efcecSDimitry Andric // Poison-generating flags should be dropped 338*415efcecSDimitry Andric Value *TV = NewSelect->getTrueValue(); 339*415efcecSDimitry Andric Value *FV = NewSelect->getFalseValue(); 340*415efcecSDimitry Andric if (match(TV, m_Neg(m_Specific(FV)))) 341*415efcecSDimitry Andric cast<Instruction>(TV)->dropPoisonGeneratingFlags(); 342*415efcecSDimitry Andric else if (match(FV, m_Neg(m_Specific(TV)))) 343*415efcecSDimitry Andric cast<Instruction>(FV)->dropPoisonGeneratingFlags(); 344*415efcecSDimitry Andric else { 345*415efcecSDimitry Andric cast<Instruction>(TV)->dropPoisonGeneratingFlags(); 346*415efcecSDimitry Andric cast<Instruction>(FV)->dropPoisonGeneratingFlags(); 347*415efcecSDimitry Andric } 3485ffd83dbSDimitry Andric Builder.Insert(NewSelect); 3495ffd83dbSDimitry Andric return NewSelect; 3505ffd83dbSDimitry Andric } 3515ffd83dbSDimitry Andric // `select` is negatible if both hands of `select` are negatible. 3525f757f3fSDimitry Andric Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1); 3535ffd83dbSDimitry Andric if (!NegOp1) // Early return. 3545ffd83dbSDimitry Andric return nullptr; 3555f757f3fSDimitry Andric Value *NegOp2 = negate(I->getOperand(2), IsNSW, Depth + 1); 3565ffd83dbSDimitry Andric if (!NegOp2) 3575ffd83dbSDimitry Andric return nullptr; 3585ffd83dbSDimitry Andric // Do preserve the metadata! 3595ffd83dbSDimitry Andric return Builder.CreateSelect(I->getOperand(0), NegOp1, NegOp2, 3605ffd83dbSDimitry Andric I->getName() + ".neg", /*MDFrom=*/I); 3615ffd83dbSDimitry Andric } 3625ffd83dbSDimitry Andric case Instruction::ShuffleVector: { 3635ffd83dbSDimitry Andric // `shufflevector` is negatible if both operands are negatible. 3645ffd83dbSDimitry Andric auto *Shuf = cast<ShuffleVectorInst>(I); 3655f757f3fSDimitry Andric Value *NegOp0 = negate(I->getOperand(0), IsNSW, Depth + 1); 3665ffd83dbSDimitry Andric if (!NegOp0) // Early return. 3675ffd83dbSDimitry Andric return nullptr; 3685f757f3fSDimitry Andric Value *NegOp1 = negate(I->getOperand(1), IsNSW, Depth + 1); 3695ffd83dbSDimitry Andric if (!NegOp1) 3705ffd83dbSDimitry Andric return nullptr; 3715ffd83dbSDimitry Andric return Builder.CreateShuffleVector(NegOp0, NegOp1, Shuf->getShuffleMask(), 3725ffd83dbSDimitry Andric I->getName() + ".neg"); 3735ffd83dbSDimitry Andric } 3745ffd83dbSDimitry Andric case Instruction::ExtractElement: { 3755ffd83dbSDimitry Andric // `extractelement` is negatible if source operand is negatible. 3765ffd83dbSDimitry Andric auto *EEI = cast<ExtractElementInst>(I); 3775f757f3fSDimitry Andric Value *NegVector = negate(EEI->getVectorOperand(), IsNSW, Depth + 1); 3785ffd83dbSDimitry Andric if (!NegVector) // Early return. 3795ffd83dbSDimitry Andric return nullptr; 3805ffd83dbSDimitry Andric return Builder.CreateExtractElement(NegVector, EEI->getIndexOperand(), 3815ffd83dbSDimitry Andric I->getName() + ".neg"); 3825ffd83dbSDimitry Andric } 3835ffd83dbSDimitry Andric case Instruction::InsertElement: { 3845ffd83dbSDimitry Andric // `insertelement` is negatible if both the source vector and 3855ffd83dbSDimitry Andric // element-to-be-inserted are negatible. 3865ffd83dbSDimitry Andric auto *IEI = cast<InsertElementInst>(I); 3875f757f3fSDimitry Andric Value *NegVector = negate(IEI->getOperand(0), IsNSW, Depth + 1); 3885ffd83dbSDimitry Andric if (!NegVector) // Early return. 3895ffd83dbSDimitry Andric return nullptr; 3905f757f3fSDimitry Andric Value *NegNewElt = negate(IEI->getOperand(1), IsNSW, Depth + 1); 3915ffd83dbSDimitry Andric if (!NegNewElt) // Early return. 3925ffd83dbSDimitry Andric return nullptr; 3935ffd83dbSDimitry Andric return Builder.CreateInsertElement(NegVector, NegNewElt, IEI->getOperand(2), 3945ffd83dbSDimitry Andric I->getName() + ".neg"); 3955ffd83dbSDimitry Andric } 3965ffd83dbSDimitry Andric case Instruction::Trunc: { 3975ffd83dbSDimitry Andric // `trunc` is negatible if its operand is negatible. 3985f757f3fSDimitry Andric Value *NegOp = negate(I->getOperand(0), /* IsNSW */ false, Depth + 1); 3995ffd83dbSDimitry Andric if (!NegOp) // Early return. 4005ffd83dbSDimitry Andric return nullptr; 4015ffd83dbSDimitry Andric return Builder.CreateTrunc(NegOp, I->getType(), I->getName() + ".neg"); 4025ffd83dbSDimitry Andric } 4035ffd83dbSDimitry Andric case Instruction::Shl: { 4045ffd83dbSDimitry Andric // `shl` is negatible if the first operand is negatible. 4055f757f3fSDimitry Andric IsNSW &= I->hasNoSignedWrap(); 4065f757f3fSDimitry Andric if (Value *NegOp0 = negate(I->getOperand(0), IsNSW, Depth + 1)) 4075f757f3fSDimitry Andric return Builder.CreateShl(NegOp0, I->getOperand(1), I->getName() + ".neg", 4085f757f3fSDimitry Andric /* HasNUW */ false, IsNSW); 409e8d8bef9SDimitry Andric // Otherwise, `shl %x, C` can be interpreted as `mul %x, 1<<C`. 4100fca6ea1SDimitry Andric Constant *Op1C; 4110fca6ea1SDimitry Andric if (!match(I->getOperand(1), m_ImmConstant(Op1C)) || !IsTrulyNegation) 412e8d8bef9SDimitry Andric return nullptr; 413e8d8bef9SDimitry Andric return Builder.CreateMul( 414e8d8bef9SDimitry Andric I->getOperand(0), 4150fca6ea1SDimitry Andric Builder.CreateShl(Constant::getAllOnesValue(Op1C->getType()), Op1C), 4165f757f3fSDimitry Andric I->getName() + ".neg", /* HasNUW */ false, IsNSW); 4175ffd83dbSDimitry Andric } 418e8d8bef9SDimitry Andric case Instruction::Or: { 4195f757f3fSDimitry Andric if (!cast<PossiblyDisjointInst>(I)->isDisjoint()) 4205ffd83dbSDimitry Andric return nullptr; // Don't know how to handle `or` in general. 421e8d8bef9SDimitry Andric std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I); 4225ffd83dbSDimitry Andric // `or`/`add` are interchangeable when operands have no common bits set. 4235ffd83dbSDimitry Andric // `inc` is always negatible. 424e8d8bef9SDimitry Andric if (match(Ops[1], m_One())) 425e8d8bef9SDimitry Andric return Builder.CreateNot(Ops[0], I->getName() + ".neg"); 4265ffd83dbSDimitry Andric // Else, just defer to Instruction::Add handling. 427bdd1243dSDimitry Andric [[fallthrough]]; 428e8d8bef9SDimitry Andric } 4295ffd83dbSDimitry Andric case Instruction::Add: { 4305ffd83dbSDimitry Andric // `add` is negatible if both of its operands are negatible. 431e8d8bef9SDimitry Andric SmallVector<Value *, 2> NegatedOps, NonNegatedOps; 432e8d8bef9SDimitry Andric for (Value *Op : I->operands()) { 433e8d8bef9SDimitry Andric // Can we sink the negation into this operand? 4345f757f3fSDimitry Andric if (Value *NegOp = negate(Op, /* IsNSW */ false, Depth + 1)) { 435e8d8bef9SDimitry Andric NegatedOps.emplace_back(NegOp); // Successfully negated operand! 436e8d8bef9SDimitry Andric continue; 4375ffd83dbSDimitry Andric } 438e8d8bef9SDimitry Andric // Failed to sink negation into this operand. IFF we started from negation 439e8d8bef9SDimitry Andric // and we manage to sink negation into one operand, we can still do this. 440e8d8bef9SDimitry Andric if (!IsTrulyNegation) 441e8d8bef9SDimitry Andric return nullptr; 442e8d8bef9SDimitry Andric NonNegatedOps.emplace_back(Op); // Just record which operand that was. 443e8d8bef9SDimitry Andric } 444e8d8bef9SDimitry Andric assert((NegatedOps.size() + NonNegatedOps.size()) == 2 && 4454824e7fdSDimitry Andric "Internal consistency check failed."); 446e8d8bef9SDimitry Andric // Did we manage to sink negation into both of the operands? 447e8d8bef9SDimitry Andric if (NegatedOps.size() == 2) // Then we get to keep the `add`! 448e8d8bef9SDimitry Andric return Builder.CreateAdd(NegatedOps[0], NegatedOps[1], 449e8d8bef9SDimitry Andric I->getName() + ".neg"); 450e8d8bef9SDimitry Andric assert(IsTrulyNegation && "We should have early-exited then."); 451e8d8bef9SDimitry Andric // Completely failed to sink negation? 452e8d8bef9SDimitry Andric if (NonNegatedOps.size() == 2) 453e8d8bef9SDimitry Andric return nullptr; 454e8d8bef9SDimitry Andric // 0-(a+b) --> (-a)-b 455e8d8bef9SDimitry Andric return Builder.CreateSub(NegatedOps[0], NonNegatedOps[0], 456e8d8bef9SDimitry Andric I->getName() + ".neg"); 457e8d8bef9SDimitry Andric } 458e8d8bef9SDimitry Andric case Instruction::Xor: { 459e8d8bef9SDimitry Andric std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I); 4605ffd83dbSDimitry Andric // `xor` is negatible if one of its operands is invertible. 4615ffd83dbSDimitry Andric // FIXME: InstCombineInverter? But how to connect Inverter and Negator? 462e8d8bef9SDimitry Andric if (auto *C = dyn_cast<Constant>(Ops[1])) { 4635f757f3fSDimitry Andric if (IsTrulyNegation) { 464e8d8bef9SDimitry Andric Value *Xor = Builder.CreateXor(Ops[0], ConstantExpr::getNot(C)); 4655ffd83dbSDimitry Andric return Builder.CreateAdd(Xor, ConstantInt::get(Xor->getType(), 1), 4665ffd83dbSDimitry Andric I->getName() + ".neg"); 4675ffd83dbSDimitry Andric } 4685f757f3fSDimitry Andric } 4695ffd83dbSDimitry Andric return nullptr; 470e8d8bef9SDimitry Andric } 4715ffd83dbSDimitry Andric case Instruction::Mul: { 472e8d8bef9SDimitry Andric std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I); 4735ffd83dbSDimitry Andric // `mul` is negatible if one of its operands is negatible. 4745ffd83dbSDimitry Andric Value *NegatedOp, *OtherOp; 4755ffd83dbSDimitry Andric // First try the second operand, in case it's a constant it will be best to 4765ffd83dbSDimitry Andric // just invert it instead of sinking the `neg` deeper. 4775f757f3fSDimitry Andric if (Value *NegOp1 = negate(Ops[1], /* IsNSW */ false, Depth + 1)) { 4785ffd83dbSDimitry Andric NegatedOp = NegOp1; 479e8d8bef9SDimitry Andric OtherOp = Ops[0]; 4805f757f3fSDimitry Andric } else if (Value *NegOp0 = negate(Ops[0], /* IsNSW */ false, Depth + 1)) { 4815ffd83dbSDimitry Andric NegatedOp = NegOp0; 482e8d8bef9SDimitry Andric OtherOp = Ops[1]; 4835ffd83dbSDimitry Andric } else 4845ffd83dbSDimitry Andric // Can't negate either of them. 4855ffd83dbSDimitry Andric return nullptr; 4865f757f3fSDimitry Andric return Builder.CreateMul(NegatedOp, OtherOp, I->getName() + ".neg", 4875f757f3fSDimitry Andric /* HasNUW */ false, IsNSW && I->hasNoSignedWrap()); 4885ffd83dbSDimitry Andric } 4895ffd83dbSDimitry Andric default: 4905ffd83dbSDimitry Andric return nullptr; // Don't know, likely not negatible for free. 4915ffd83dbSDimitry Andric } 4925ffd83dbSDimitry Andric 4935ffd83dbSDimitry Andric llvm_unreachable("Can't get here. We always return from switch."); 4945ffd83dbSDimitry Andric } 4955ffd83dbSDimitry Andric 4965f757f3fSDimitry Andric [[nodiscard]] Value *Negator::negate(Value *V, bool IsNSW, unsigned Depth) { 4975ffd83dbSDimitry Andric NegatorMaxDepthVisited.updateMax(Depth); 4985ffd83dbSDimitry Andric ++NegatorNumValuesVisited; 4995ffd83dbSDimitry Andric 5005ffd83dbSDimitry Andric #if LLVM_ENABLE_STATS 5015ffd83dbSDimitry Andric ++NumValuesVisitedInThisNegator; 5025ffd83dbSDimitry Andric #endif 5035ffd83dbSDimitry Andric 5045ffd83dbSDimitry Andric #ifndef NDEBUG 5055ffd83dbSDimitry Andric // We can't ever have a Value with such an address. 5065ffd83dbSDimitry Andric Value *Placeholder = reinterpret_cast<Value *>(static_cast<uintptr_t>(-1)); 5075ffd83dbSDimitry Andric #endif 5085ffd83dbSDimitry Andric 5095ffd83dbSDimitry Andric // Did we already try to negate this value? 5105ffd83dbSDimitry Andric auto NegationsCacheIterator = NegationsCache.find(V); 5115ffd83dbSDimitry Andric if (NegationsCacheIterator != NegationsCache.end()) { 5125ffd83dbSDimitry Andric ++NegatorNumNegationsFoundInCache; 5135ffd83dbSDimitry Andric Value *NegatedV = NegationsCacheIterator->second; 5145ffd83dbSDimitry Andric assert(NegatedV != Placeholder && "Encountered a cycle during negation."); 5155ffd83dbSDimitry Andric return NegatedV; 5165ffd83dbSDimitry Andric } 5175ffd83dbSDimitry Andric 5185ffd83dbSDimitry Andric #ifndef NDEBUG 5195ffd83dbSDimitry Andric // We did not find a cached result for negation of V. While there, 5205ffd83dbSDimitry Andric // let's temporairly cache a placeholder value, with the idea that if later 5215ffd83dbSDimitry Andric // during negation we fetch it from cache, we'll know we're in a cycle. 5225ffd83dbSDimitry Andric NegationsCache[V] = Placeholder; 5235ffd83dbSDimitry Andric #endif 5245ffd83dbSDimitry Andric 5255ffd83dbSDimitry Andric // No luck. Try negating it for real. 5265f757f3fSDimitry Andric Value *NegatedV = visitImpl(V, IsNSW, Depth); 5275ffd83dbSDimitry Andric // And cache the (real) result for the future. 5285ffd83dbSDimitry Andric NegationsCache[V] = NegatedV; 5295ffd83dbSDimitry Andric 5305ffd83dbSDimitry Andric return NegatedV; 5315ffd83dbSDimitry Andric } 5325ffd83dbSDimitry Andric 5335f757f3fSDimitry Andric [[nodiscard]] std::optional<Negator::Result> Negator::run(Value *Root, 5345f757f3fSDimitry Andric bool IsNSW) { 5355f757f3fSDimitry Andric Value *Negated = negate(Root, IsNSW, /*Depth=*/0); 5365ffd83dbSDimitry Andric if (!Negated) { 5375ffd83dbSDimitry Andric // We must cleanup newly-inserted instructions, to avoid any potential 5385ffd83dbSDimitry Andric // endless combine looping. 539fe6060f1SDimitry Andric for (Instruction *I : llvm::reverse(NewInstructions)) 540fe6060f1SDimitry Andric I->eraseFromParent(); 541bdd1243dSDimitry Andric return std::nullopt; 5425ffd83dbSDimitry Andric } 5435ffd83dbSDimitry Andric return std::make_pair(ArrayRef<Instruction *>(NewInstructions), Negated); 5445ffd83dbSDimitry Andric } 5455ffd83dbSDimitry Andric 5465f757f3fSDimitry Andric [[nodiscard]] Value *Negator::Negate(bool LHSIsZero, bool IsNSW, Value *Root, 547e8d8bef9SDimitry Andric InstCombinerImpl &IC) { 5485ffd83dbSDimitry Andric ++NegatorTotalNegationsAttempted; 5495ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Negator: attempting to sink negation into " << *Root 5505ffd83dbSDimitry Andric << "\n"); 5515ffd83dbSDimitry Andric 5525ffd83dbSDimitry Andric if (!NegatorEnabled || !DebugCounter::shouldExecute(NegatorCounter)) 5535ffd83dbSDimitry Andric return nullptr; 5545ffd83dbSDimitry Andric 5555f757f3fSDimitry Andric Negator N(Root->getContext(), IC.getDataLayout(), LHSIsZero); 5565f757f3fSDimitry Andric std::optional<Result> Res = N.run(Root, IsNSW); 5575ffd83dbSDimitry Andric if (!Res) { // Negation failed. 5585ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root 5595ffd83dbSDimitry Andric << "\n"); 5605ffd83dbSDimitry Andric return nullptr; 5615ffd83dbSDimitry Andric } 5625ffd83dbSDimitry Andric 5635ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Negator: successfully sunk negation into " << *Root 5645ffd83dbSDimitry Andric << "\n NEW: " << *Res->second << "\n"); 5655ffd83dbSDimitry Andric ++NegatorNumTreesNegated; 5665ffd83dbSDimitry Andric 5675ffd83dbSDimitry Andric // We must temporarily unset the 'current' insertion point and DebugLoc of the 5685ffd83dbSDimitry Andric // InstCombine's IRBuilder so that it won't interfere with the ones we have 5695ffd83dbSDimitry Andric // already specified when producing negated instructions. 5705ffd83dbSDimitry Andric InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder); 5715ffd83dbSDimitry Andric IC.Builder.ClearInsertionPoint(); 5725ffd83dbSDimitry Andric IC.Builder.SetCurrentDebugLocation(DebugLoc()); 5735ffd83dbSDimitry Andric 5745ffd83dbSDimitry Andric // And finally, we must add newly-created instructions into the InstCombine's 5755ffd83dbSDimitry Andric // worklist (in a proper order!) so it can attempt to combine them. 5765ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Negator: Propagating " << Res->first.size() 5775ffd83dbSDimitry Andric << " instrs to InstCombine\n"); 5785ffd83dbSDimitry Andric NegatorMaxInstructionsCreated.updateMax(Res->first.size()); 5795ffd83dbSDimitry Andric NegatorNumInstructionsNegatedSuccess += Res->first.size(); 5805ffd83dbSDimitry Andric 5815ffd83dbSDimitry Andric // They are in def-use order, so nothing fancy, just insert them in order. 582fe6060f1SDimitry Andric for (Instruction *I : Res->first) 583fe6060f1SDimitry Andric IC.Builder.Insert(I, I->getName()); 5845ffd83dbSDimitry Andric 5855ffd83dbSDimitry Andric // And return the new root. 5865ffd83dbSDimitry Andric return Res->second; 5875ffd83dbSDimitry Andric } 588