1 //===- InstCombineNegator.cpp -----------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements sinking of negation into expression trees, 10 // as long as that can be done without increasing instruction count. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "InstCombineInternal.h" 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Twine.h" 25 #include "llvm/ADT/iterator_range.h" 26 #include "llvm/Analysis/TargetFolder.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/Constant.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/DebugLoc.h" 31 #include "llvm/IR/IRBuilder.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/IR/Type.h" 36 #include "llvm/IR/Use.h" 37 #include "llvm/IR/User.h" 38 #include "llvm/IR/Value.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/Compiler.h" 42 #include "llvm/Support/DebugCounter.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/raw_ostream.h" 45 #include "llvm/Transforms/InstCombine/InstCombiner.h" 46 #include <cassert> 47 #include <cstdint> 48 #include <functional> 49 #include <tuple> 50 #include <type_traits> 51 #include <utility> 52 53 namespace llvm { 54 class AssumptionCache; 55 class DataLayout; 56 class DominatorTree; 57 class LLVMContext; 58 } // namespace llvm 59 60 using namespace llvm; 61 62 #define DEBUG_TYPE "instcombine" 63 64 STATISTIC(NegatorTotalNegationsAttempted, 65 "Negator: Number of negations attempted to be sinked"); 66 STATISTIC(NegatorNumTreesNegated, 67 "Negator: Number of negations successfully sinked"); 68 STATISTIC(NegatorMaxDepthVisited, "Negator: Maximal traversal depth ever " 69 "reached while attempting to sink negation"); 70 STATISTIC(NegatorTimesDepthLimitReached, 71 "Negator: How many times did the traversal depth limit was reached " 72 "during sinking"); 73 STATISTIC( 74 NegatorNumValuesVisited, 75 "Negator: Total number of values visited during attempts to sink negation"); 76 STATISTIC(NegatorNumNegationsFoundInCache, 77 "Negator: How many negations did we retrieve/reuse from cache"); 78 STATISTIC(NegatorMaxTotalValuesVisited, 79 "Negator: Maximal number of values ever visited while attempting to " 80 "sink negation"); 81 STATISTIC(NegatorNumInstructionsCreatedTotal, 82 "Negator: Number of new negated instructions created, total"); 83 STATISTIC(NegatorMaxInstructionsCreated, 84 "Negator: Maximal number of new instructions created during negation " 85 "attempt"); 86 STATISTIC(NegatorNumInstructionsNegatedSuccess, 87 "Negator: Number of new negated instructions created in successful " 88 "negation sinking attempts"); 89 90 DEBUG_COUNTER(NegatorCounter, "instcombine-negator", 91 "Controls Negator transformations in InstCombine pass"); 92 93 static cl::opt<bool> 94 NegatorEnabled("instcombine-negator-enabled", cl::init(true), 95 cl::desc("Should we attempt to sink negations?")); 96 97 static cl::opt<unsigned> 98 NegatorMaxDepth("instcombine-negator-max-depth", 99 cl::init(NegatorDefaultMaxDepth), 100 cl::desc("What is the maximal lookup depth when trying to " 101 "check for viability of negation sinking.")); 102 103 Negator::Negator(LLVMContext &C, const DataLayout &DL_, AssumptionCache &AC_, 104 const DominatorTree &DT_, bool IsTrulyNegation_) 105 : Builder(C, TargetFolder(DL_), 106 IRBuilderCallbackInserter([&](Instruction *I) { 107 ++NegatorNumInstructionsCreatedTotal; 108 NewInstructions.push_back(I); 109 })), 110 DL(DL_), AC(AC_), DT(DT_), IsTrulyNegation(IsTrulyNegation_) {} 111 112 #if LLVM_ENABLE_STATS 113 Negator::~Negator() { 114 NegatorMaxTotalValuesVisited.updateMax(NumValuesVisitedInThisNegator); 115 } 116 #endif 117 118 // FIXME: can this be reworked into a worklist-based algorithm while preserving 119 // the depth-first, early bailout traversal? 120 LLVM_NODISCARD Value *Negator::visitImpl(Value *V, unsigned Depth) { 121 // -(undef) -> undef. 122 if (match(V, m_Undef())) 123 return V; 124 125 // In i1, negation can simply be ignored. 126 if (V->getType()->isIntOrIntVectorTy(1)) 127 return V; 128 129 Value *X; 130 131 // -(-(X)) -> X. 132 if (match(V, m_Neg(m_Value(X)))) 133 return X; 134 135 // Integral constants can be freely negated. 136 if (match(V, m_AnyIntegralConstant())) 137 return ConstantExpr::getNeg(cast<Constant>(V), /*HasNUW=*/false, 138 /*HasNSW=*/false); 139 140 // If we have a non-instruction, then give up. 141 if (!isa<Instruction>(V)) 142 return nullptr; 143 144 // If we have started with a true negation (i.e. `sub 0, %y`), then if we've 145 // got instruction that does not require recursive reasoning, we can still 146 // negate it even if it has other uses, without increasing instruction count. 147 if (!V->hasOneUse() && !IsTrulyNegation) 148 return nullptr; 149 150 auto *I = cast<Instruction>(V); 151 unsigned BitWidth = I->getType()->getScalarSizeInBits(); 152 153 // We must preserve the insertion point and debug info that is set in the 154 // builder at the time this function is called. 155 InstCombiner::BuilderTy::InsertPointGuard Guard(Builder); 156 // And since we are trying to negate instruction I, that tells us about the 157 // insertion point and the debug info that we need to keep. 158 Builder.SetInsertPoint(I); 159 160 // In some cases we can give the answer without further recursion. 161 switch (I->getOpcode()) { 162 case Instruction::Add: 163 // `inc` is always negatible. 164 if (match(I->getOperand(1), m_One())) 165 return Builder.CreateNot(I->getOperand(0), I->getName() + ".neg"); 166 break; 167 case Instruction::Xor: 168 // `not` is always negatible. 169 if (match(I, m_Not(m_Value(X)))) 170 return Builder.CreateAdd(X, ConstantInt::get(X->getType(), 1), 171 I->getName() + ".neg"); 172 break; 173 case Instruction::AShr: 174 case Instruction::LShr: { 175 // Right-shift sign bit smear is negatible. 176 const APInt *Op1Val; 177 if (match(I->getOperand(1), m_APInt(Op1Val)) && *Op1Val == BitWidth - 1) { 178 Value *BO = I->getOpcode() == Instruction::AShr 179 ? Builder.CreateLShr(I->getOperand(0), I->getOperand(1)) 180 : Builder.CreateAShr(I->getOperand(0), I->getOperand(1)); 181 if (auto *NewInstr = dyn_cast<Instruction>(BO)) { 182 NewInstr->copyIRFlags(I); 183 NewInstr->setName(I->getName() + ".neg"); 184 } 185 return BO; 186 } 187 // While we could negate exact arithmetic shift: 188 // ashr exact %x, C --> sdiv exact i8 %x, -1<<C 189 // iff C != 0 and C u< bitwidth(%x), we don't want to, 190 // because division is *THAT* much worse than a shift. 191 break; 192 } 193 case Instruction::SExt: 194 case Instruction::ZExt: 195 // `*ext` of i1 is always negatible 196 if (I->getOperand(0)->getType()->isIntOrIntVectorTy(1)) 197 return I->getOpcode() == Instruction::SExt 198 ? Builder.CreateZExt(I->getOperand(0), I->getType(), 199 I->getName() + ".neg") 200 : Builder.CreateSExt(I->getOperand(0), I->getType(), 201 I->getName() + ".neg"); 202 break; 203 default: 204 break; // Other instructions require recursive reasoning. 205 } 206 207 // Some other cases, while still don't require recursion, 208 // are restricted to the one-use case. 209 if (!V->hasOneUse()) 210 return nullptr; 211 212 switch (I->getOpcode()) { 213 case Instruction::Sub: 214 // `sub` is always negatible. 215 // But if the old `sub` sticks around, even thought we don't increase 216 // instruction count, this is a likely regression since we increased 217 // live-range of *both* of the operands, which might lead to more spilling. 218 return Builder.CreateSub(I->getOperand(1), I->getOperand(0), 219 I->getName() + ".neg"); 220 case Instruction::SDiv: 221 // `sdiv` is negatible if divisor is not undef/INT_MIN/1. 222 // While this is normally not behind a use-check, 223 // let's consider division to be special since it's costly. 224 if (auto *Op1C = dyn_cast<Constant>(I->getOperand(1))) { 225 if (!Op1C->containsUndefElement() && Op1C->isNotMinSignedValue() && 226 Op1C->isNotOneValue()) { 227 Value *BO = 228 Builder.CreateSDiv(I->getOperand(0), ConstantExpr::getNeg(Op1C), 229 I->getName() + ".neg"); 230 if (auto *NewInstr = dyn_cast<Instruction>(BO)) 231 NewInstr->setIsExact(I->isExact()); 232 return BO; 233 } 234 } 235 break; 236 } 237 238 // Rest of the logic is recursive, so if it's time to give up then it's time. 239 if (Depth > NegatorMaxDepth) { 240 LLVM_DEBUG(dbgs() << "Negator: reached maximal allowed traversal depth in " 241 << *V << ". Giving up.\n"); 242 ++NegatorTimesDepthLimitReached; 243 return nullptr; 244 } 245 246 switch (I->getOpcode()) { 247 case Instruction::PHI: { 248 // `phi` is negatible if all the incoming values are negatible. 249 auto *PHI = cast<PHINode>(I); 250 SmallVector<Value *, 4> NegatedIncomingValues(PHI->getNumOperands()); 251 for (auto I : zip(PHI->incoming_values(), NegatedIncomingValues)) { 252 if (!(std::get<1>(I) = 253 negate(std::get<0>(I), Depth + 1))) // Early return. 254 return nullptr; 255 } 256 // All incoming values are indeed negatible. Create negated PHI node. 257 PHINode *NegatedPHI = Builder.CreatePHI( 258 PHI->getType(), PHI->getNumOperands(), PHI->getName() + ".neg"); 259 for (auto I : zip(NegatedIncomingValues, PHI->blocks())) 260 NegatedPHI->addIncoming(std::get<0>(I), std::get<1>(I)); 261 return NegatedPHI; 262 } 263 case Instruction::Select: { 264 if (isKnownNegation(I->getOperand(1), I->getOperand(2))) { 265 // Of one hand of select is known to be negation of another hand, 266 // just swap the hands around. 267 auto *NewSelect = cast<SelectInst>(I->clone()); 268 // Just swap the operands of the select. 269 NewSelect->swapValues(); 270 // Don't swap prof metadata, we didn't change the branch behavior. 271 NewSelect->setName(I->getName() + ".neg"); 272 Builder.Insert(NewSelect); 273 return NewSelect; 274 } 275 // `select` is negatible if both hands of `select` are negatible. 276 Value *NegOp1 = negate(I->getOperand(1), Depth + 1); 277 if (!NegOp1) // Early return. 278 return nullptr; 279 Value *NegOp2 = negate(I->getOperand(2), Depth + 1); 280 if (!NegOp2) 281 return nullptr; 282 // Do preserve the metadata! 283 return Builder.CreateSelect(I->getOperand(0), NegOp1, NegOp2, 284 I->getName() + ".neg", /*MDFrom=*/I); 285 } 286 case Instruction::ShuffleVector: { 287 // `shufflevector` is negatible if both operands are negatible. 288 auto *Shuf = cast<ShuffleVectorInst>(I); 289 Value *NegOp0 = negate(I->getOperand(0), Depth + 1); 290 if (!NegOp0) // Early return. 291 return nullptr; 292 Value *NegOp1 = negate(I->getOperand(1), Depth + 1); 293 if (!NegOp1) 294 return nullptr; 295 return Builder.CreateShuffleVector(NegOp0, NegOp1, Shuf->getShuffleMask(), 296 I->getName() + ".neg"); 297 } 298 case Instruction::ExtractElement: { 299 // `extractelement` is negatible if source operand is negatible. 300 auto *EEI = cast<ExtractElementInst>(I); 301 Value *NegVector = negate(EEI->getVectorOperand(), Depth + 1); 302 if (!NegVector) // Early return. 303 return nullptr; 304 return Builder.CreateExtractElement(NegVector, EEI->getIndexOperand(), 305 I->getName() + ".neg"); 306 } 307 case Instruction::InsertElement: { 308 // `insertelement` is negatible if both the source vector and 309 // element-to-be-inserted are negatible. 310 auto *IEI = cast<InsertElementInst>(I); 311 Value *NegVector = negate(IEI->getOperand(0), Depth + 1); 312 if (!NegVector) // Early return. 313 return nullptr; 314 Value *NegNewElt = negate(IEI->getOperand(1), Depth + 1); 315 if (!NegNewElt) // Early return. 316 return nullptr; 317 return Builder.CreateInsertElement(NegVector, NegNewElt, IEI->getOperand(2), 318 I->getName() + ".neg"); 319 } 320 case Instruction::Trunc: { 321 // `trunc` is negatible if its operand is negatible. 322 Value *NegOp = negate(I->getOperand(0), Depth + 1); 323 if (!NegOp) // Early return. 324 return nullptr; 325 return Builder.CreateTrunc(NegOp, I->getType(), I->getName() + ".neg"); 326 } 327 case Instruction::Shl: { 328 // `shl` is negatible if the first operand is negatible. 329 if (Value *NegOp0 = negate(I->getOperand(0), Depth + 1)) 330 return Builder.CreateShl(NegOp0, I->getOperand(1), I->getName() + ".neg"); 331 // Otherwise, `shl %x, C` can be interpreted as `mul %x, 1<<C`. 332 auto *Op1C = dyn_cast<Constant>(I->getOperand(1)); 333 if (!Op1C) // Early return. 334 return nullptr; 335 return Builder.CreateMul( 336 I->getOperand(0), 337 ConstantExpr::getShl(Constant::getAllOnesValue(Op1C->getType()), Op1C), 338 I->getName() + ".neg"); 339 } 340 case Instruction::Or: 341 if (!haveNoCommonBitsSet(I->getOperand(0), I->getOperand(1), DL, &AC, I, 342 &DT)) 343 return nullptr; // Don't know how to handle `or` in general. 344 // `or`/`add` are interchangeable when operands have no common bits set. 345 // `inc` is always negatible. 346 if (match(I->getOperand(1), m_One())) 347 return Builder.CreateNot(I->getOperand(0), I->getName() + ".neg"); 348 // Else, just defer to Instruction::Add handling. 349 LLVM_FALLTHROUGH; 350 case Instruction::Add: { 351 // `add` is negatible if both of its operands are negatible. 352 SmallVector<Value *, 2> NegatedOps, NonNegatedOps; 353 for (Value *Op : I->operands()) { 354 // Can we sink the negation into this operand? 355 if (Value *NegOp = negate(Op, Depth + 1)) { 356 NegatedOps.emplace_back(NegOp); // Successfully negated operand! 357 continue; 358 } 359 // Failed to sink negation into this operand. IFF we started from negation 360 // and we manage to sink negation into one operand, we can still do this. 361 if (!IsTrulyNegation) 362 return nullptr; 363 NonNegatedOps.emplace_back(Op); // Just record which operand that was. 364 } 365 assert((NegatedOps.size() + NonNegatedOps.size()) == 2 && 366 "Internal consistency sanity check."); 367 // Did we manage to sink negation into both of the operands? 368 if (NegatedOps.size() == 2) // Then we get to keep the `add`! 369 return Builder.CreateAdd(NegatedOps[0], NegatedOps[1], 370 I->getName() + ".neg"); 371 assert(IsTrulyNegation && "We should have early-exited then."); 372 // Completely failed to sink negation? 373 if (NonNegatedOps.size() == 2) 374 return nullptr; 375 // 0-(a+b) --> (-a)-b 376 return Builder.CreateSub(NegatedOps[0], NonNegatedOps[0], 377 I->getName() + ".neg"); 378 } 379 case Instruction::Xor: 380 // `xor` is negatible if one of its operands is invertible. 381 // FIXME: InstCombineInverter? But how to connect Inverter and Negator? 382 if (auto *C = dyn_cast<Constant>(I->getOperand(1))) { 383 Value *Xor = Builder.CreateXor(I->getOperand(0), ConstantExpr::getNot(C)); 384 return Builder.CreateAdd(Xor, ConstantInt::get(Xor->getType(), 1), 385 I->getName() + ".neg"); 386 } 387 return nullptr; 388 case Instruction::Mul: { 389 // `mul` is negatible if one of its operands is negatible. 390 Value *NegatedOp, *OtherOp; 391 // First try the second operand, in case it's a constant it will be best to 392 // just invert it instead of sinking the `neg` deeper. 393 if (Value *NegOp1 = negate(I->getOperand(1), Depth + 1)) { 394 NegatedOp = NegOp1; 395 OtherOp = I->getOperand(0); 396 } else if (Value *NegOp0 = negate(I->getOperand(0), Depth + 1)) { 397 NegatedOp = NegOp0; 398 OtherOp = I->getOperand(1); 399 } else 400 // Can't negate either of them. 401 return nullptr; 402 return Builder.CreateMul(NegatedOp, OtherOp, I->getName() + ".neg"); 403 } 404 default: 405 return nullptr; // Don't know, likely not negatible for free. 406 } 407 408 llvm_unreachable("Can't get here. We always return from switch."); 409 } 410 411 LLVM_NODISCARD Value *Negator::negate(Value *V, unsigned Depth) { 412 NegatorMaxDepthVisited.updateMax(Depth); 413 ++NegatorNumValuesVisited; 414 415 #if LLVM_ENABLE_STATS 416 ++NumValuesVisitedInThisNegator; 417 #endif 418 419 #ifndef NDEBUG 420 // We can't ever have a Value with such an address. 421 Value *Placeholder = reinterpret_cast<Value *>(static_cast<uintptr_t>(-1)); 422 #endif 423 424 // Did we already try to negate this value? 425 auto NegationsCacheIterator = NegationsCache.find(V); 426 if (NegationsCacheIterator != NegationsCache.end()) { 427 ++NegatorNumNegationsFoundInCache; 428 Value *NegatedV = NegationsCacheIterator->second; 429 assert(NegatedV != Placeholder && "Encountered a cycle during negation."); 430 return NegatedV; 431 } 432 433 #ifndef NDEBUG 434 // We did not find a cached result for negation of V. While there, 435 // let's temporairly cache a placeholder value, with the idea that if later 436 // during negation we fetch it from cache, we'll know we're in a cycle. 437 NegationsCache[V] = Placeholder; 438 #endif 439 440 // No luck. Try negating it for real. 441 Value *NegatedV = visitImpl(V, Depth); 442 // And cache the (real) result for the future. 443 NegationsCache[V] = NegatedV; 444 445 return NegatedV; 446 } 447 448 LLVM_NODISCARD Optional<Negator::Result> Negator::run(Value *Root) { 449 Value *Negated = negate(Root, /*Depth=*/0); 450 if (!Negated) { 451 // We must cleanup newly-inserted instructions, to avoid any potential 452 // endless combine looping. 453 llvm::for_each(llvm::reverse(NewInstructions), 454 [&](Instruction *I) { I->eraseFromParent(); }); 455 return llvm::None; 456 } 457 return std::make_pair(ArrayRef<Instruction *>(NewInstructions), Negated); 458 } 459 460 LLVM_NODISCARD Value *Negator::Negate(bool LHSIsZero, Value *Root, 461 InstCombinerImpl &IC) { 462 ++NegatorTotalNegationsAttempted; 463 LLVM_DEBUG(dbgs() << "Negator: attempting to sink negation into " << *Root 464 << "\n"); 465 466 if (!NegatorEnabled || !DebugCounter::shouldExecute(NegatorCounter)) 467 return nullptr; 468 469 Negator N(Root->getContext(), IC.getDataLayout(), IC.getAssumptionCache(), 470 IC.getDominatorTree(), LHSIsZero); 471 Optional<Result> Res = N.run(Root); 472 if (!Res) { // Negation failed. 473 LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root 474 << "\n"); 475 return nullptr; 476 } 477 478 LLVM_DEBUG(dbgs() << "Negator: successfully sunk negation into " << *Root 479 << "\n NEW: " << *Res->second << "\n"); 480 ++NegatorNumTreesNegated; 481 482 // We must temporarily unset the 'current' insertion point and DebugLoc of the 483 // InstCombine's IRBuilder so that it won't interfere with the ones we have 484 // already specified when producing negated instructions. 485 InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder); 486 IC.Builder.ClearInsertionPoint(); 487 IC.Builder.SetCurrentDebugLocation(DebugLoc()); 488 489 // And finally, we must add newly-created instructions into the InstCombine's 490 // worklist (in a proper order!) so it can attempt to combine them. 491 LLVM_DEBUG(dbgs() << "Negator: Propagating " << Res->first.size() 492 << " instrs to InstCombine\n"); 493 NegatorMaxInstructionsCreated.updateMax(Res->first.size()); 494 NegatorNumInstructionsNegatedSuccess += Res->first.size(); 495 496 // They are in def-use order, so nothing fancy, just insert them in order. 497 llvm::for_each(Res->first, 498 [&](Instruction *I) { IC.Builder.Insert(I, I->getName()); }); 499 500 // And return the new root. 501 return Res->second; 502 } 503