InstCombineNegator.cpp 21 KB

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