InstCombineNegator.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. default:
  198. break; // Other instructions require recursive reasoning.
  199. }
  200. if (I->getOpcode() == Instruction::Sub &&
  201. (I->hasOneUse() || match(I->getOperand(0), m_ImmConstant()))) {
  202. // `sub` is always negatible.
  203. // However, only do this either if the old `sub` doesn't stick around, or
  204. // it was subtracting from a constant. Otherwise, this isn't profitable.
  205. return Builder.CreateSub(I->getOperand(1), I->getOperand(0),
  206. I->getName() + ".neg");
  207. }
  208. // Some other cases, while still don't require recursion,
  209. // are restricted to the one-use case.
  210. if (!V->hasOneUse())
  211. return nullptr;
  212. switch (I->getOpcode()) {
  213. case Instruction::SDiv:
  214. // `sdiv` is negatible if divisor is not undef/INT_MIN/1.
  215. // While this is normally not behind a use-check,
  216. // let's consider division to be special since it's costly.
  217. if (auto *Op1C = dyn_cast<Constant>(I->getOperand(1))) {
  218. if (!Op1C->containsUndefOrPoisonElement() &&
  219. Op1C->isNotMinSignedValue() && Op1C->isNotOneValue()) {
  220. Value *BO =
  221. Builder.CreateSDiv(I->getOperand(0), ConstantExpr::getNeg(Op1C),
  222. I->getName() + ".neg");
  223. if (auto *NewInstr = dyn_cast<Instruction>(BO))
  224. NewInstr->setIsExact(I->isExact());
  225. return BO;
  226. }
  227. }
  228. break;
  229. }
  230. // Rest of the logic is recursive, so if it's time to give up then it's time.
  231. if (Depth > NegatorMaxDepth) {
  232. LLVM_DEBUG(dbgs() << "Negator: reached maximal allowed traversal depth in "
  233. << *V << ". Giving up.\n");
  234. ++NegatorTimesDepthLimitReached;
  235. return nullptr;
  236. }
  237. switch (I->getOpcode()) {
  238. case Instruction::Freeze: {
  239. // `freeze` is negatible if its operand is negatible.
  240. Value *NegOp = negate(I->getOperand(0), Depth + 1);
  241. if (!NegOp) // Early return.
  242. return nullptr;
  243. return Builder.CreateFreeze(NegOp, I->getName() + ".neg");
  244. }
  245. case Instruction::PHI: {
  246. // `phi` is negatible if all the incoming values are negatible.
  247. auto *PHI = cast<PHINode>(I);
  248. SmallVector<Value *, 4> NegatedIncomingValues(PHI->getNumOperands());
  249. for (auto I : zip(PHI->incoming_values(), NegatedIncomingValues)) {
  250. if (!(std::get<1>(I) =
  251. negate(std::get<0>(I), Depth + 1))) // Early return.
  252. return nullptr;
  253. }
  254. // All incoming values are indeed negatible. Create negated PHI node.
  255. PHINode *NegatedPHI = Builder.CreatePHI(
  256. PHI->getType(), PHI->getNumOperands(), PHI->getName() + ".neg");
  257. for (auto I : zip(NegatedIncomingValues, PHI->blocks()))
  258. NegatedPHI->addIncoming(std::get<0>(I), std::get<1>(I));
  259. return NegatedPHI;
  260. }
  261. case Instruction::Select: {
  262. if (isKnownNegation(I->getOperand(1), I->getOperand(2))) {
  263. // Of one hand of select is known to be negation of another hand,
  264. // just swap the hands around.
  265. auto *NewSelect = cast<SelectInst>(I->clone());
  266. // Just swap the operands of the select.
  267. NewSelect->swapValues();
  268. // Don't swap prof metadata, we didn't change the branch behavior.
  269. NewSelect->setName(I->getName() + ".neg");
  270. Builder.Insert(NewSelect);
  271. return NewSelect;
  272. }
  273. // `select` is negatible if both hands of `select` are negatible.
  274. Value *NegOp1 = negate(I->getOperand(1), Depth + 1);
  275. if (!NegOp1) // Early return.
  276. return nullptr;
  277. Value *NegOp2 = negate(I->getOperand(2), Depth + 1);
  278. if (!NegOp2)
  279. return nullptr;
  280. // Do preserve the metadata!
  281. return Builder.CreateSelect(I->getOperand(0), NegOp1, NegOp2,
  282. I->getName() + ".neg", /*MDFrom=*/I);
  283. }
  284. case Instruction::ShuffleVector: {
  285. // `shufflevector` is negatible if both operands are negatible.
  286. auto *Shuf = cast<ShuffleVectorInst>(I);
  287. Value *NegOp0 = negate(I->getOperand(0), Depth + 1);
  288. if (!NegOp0) // Early return.
  289. return nullptr;
  290. Value *NegOp1 = negate(I->getOperand(1), Depth + 1);
  291. if (!NegOp1)
  292. return nullptr;
  293. return Builder.CreateShuffleVector(NegOp0, NegOp1, Shuf->getShuffleMask(),
  294. I->getName() + ".neg");
  295. }
  296. case Instruction::ExtractElement: {
  297. // `extractelement` is negatible if source operand is negatible.
  298. auto *EEI = cast<ExtractElementInst>(I);
  299. Value *NegVector = negate(EEI->getVectorOperand(), Depth + 1);
  300. if (!NegVector) // Early return.
  301. return nullptr;
  302. return Builder.CreateExtractElement(NegVector, EEI->getIndexOperand(),
  303. I->getName() + ".neg");
  304. }
  305. case Instruction::InsertElement: {
  306. // `insertelement` is negatible if both the source vector and
  307. // element-to-be-inserted are negatible.
  308. auto *IEI = cast<InsertElementInst>(I);
  309. Value *NegVector = negate(IEI->getOperand(0), Depth + 1);
  310. if (!NegVector) // Early return.
  311. return nullptr;
  312. Value *NegNewElt = negate(IEI->getOperand(1), Depth + 1);
  313. if (!NegNewElt) // Early return.
  314. return nullptr;
  315. return Builder.CreateInsertElement(NegVector, NegNewElt, IEI->getOperand(2),
  316. I->getName() + ".neg");
  317. }
  318. case Instruction::Trunc: {
  319. // `trunc` is negatible if its operand is negatible.
  320. Value *NegOp = negate(I->getOperand(0), Depth + 1);
  321. if (!NegOp) // Early return.
  322. return nullptr;
  323. return Builder.CreateTrunc(NegOp, I->getType(), I->getName() + ".neg");
  324. }
  325. case Instruction::Shl: {
  326. // `shl` is negatible if the first operand is negatible.
  327. if (Value *NegOp0 = negate(I->getOperand(0), Depth + 1))
  328. return Builder.CreateShl(NegOp0, I->getOperand(1), I->getName() + ".neg");
  329. // Otherwise, `shl %x, C` can be interpreted as `mul %x, 1<<C`.
  330. auto *Op1C = dyn_cast<Constant>(I->getOperand(1));
  331. if (!Op1C) // Early return.
  332. return nullptr;
  333. return Builder.CreateMul(
  334. I->getOperand(0),
  335. ConstantExpr::getShl(Constant::getAllOnesValue(Op1C->getType()), Op1C),
  336. I->getName() + ".neg");
  337. }
  338. case Instruction::Or: {
  339. if (!haveNoCommonBitsSet(I->getOperand(0), I->getOperand(1), DL, &AC, I,
  340. &DT))
  341. return nullptr; // Don't know how to handle `or` in general.
  342. std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
  343. // `or`/`add` are interchangeable when operands have no common bits set.
  344. // `inc` is always negatible.
  345. if (match(Ops[1], m_One()))
  346. return Builder.CreateNot(Ops[0], I->getName() + ".neg");
  347. // Else, just defer to Instruction::Add handling.
  348. LLVM_FALLTHROUGH;
  349. }
  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. std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
  381. // `xor` is negatible if one of its operands is invertible.
  382. // FIXME: InstCombineInverter? But how to connect Inverter and Negator?
  383. if (auto *C = dyn_cast<Constant>(Ops[1])) {
  384. Value *Xor = Builder.CreateXor(Ops[0], ConstantExpr::getNot(C));
  385. return Builder.CreateAdd(Xor, ConstantInt::get(Xor->getType(), 1),
  386. I->getName() + ".neg");
  387. }
  388. return nullptr;
  389. }
  390. case Instruction::Mul: {
  391. std::array<Value *, 2> Ops = getSortedOperandsOfBinOp(I);
  392. // `mul` is negatible if one of its operands is negatible.
  393. Value *NegatedOp, *OtherOp;
  394. // First try the second operand, in case it's a constant it will be best to
  395. // just invert it instead of sinking the `neg` deeper.
  396. if (Value *NegOp1 = negate(Ops[1], Depth + 1)) {
  397. NegatedOp = NegOp1;
  398. OtherOp = Ops[0];
  399. } else if (Value *NegOp0 = negate(Ops[0], Depth + 1)) {
  400. NegatedOp = NegOp0;
  401. OtherOp = Ops[1];
  402. } else
  403. // Can't negate either of them.
  404. return nullptr;
  405. return Builder.CreateMul(NegatedOp, OtherOp, I->getName() + ".neg");
  406. }
  407. default:
  408. return nullptr; // Don't know, likely not negatible for free.
  409. }
  410. llvm_unreachable("Can't get here. We always return from switch.");
  411. }
  412. LLVM_NODISCARD Value *Negator::negate(Value *V, unsigned Depth) {
  413. NegatorMaxDepthVisited.updateMax(Depth);
  414. ++NegatorNumValuesVisited;
  415. #if LLVM_ENABLE_STATS
  416. ++NumValuesVisitedInThisNegator;
  417. #endif
  418. #ifndef NDEBUG
  419. // We can't ever have a Value with such an address.
  420. Value *Placeholder = reinterpret_cast<Value *>(static_cast<uintptr_t>(-1));
  421. #endif
  422. // Did we already try to negate this value?
  423. auto NegationsCacheIterator = NegationsCache.find(V);
  424. if (NegationsCacheIterator != NegationsCache.end()) {
  425. ++NegatorNumNegationsFoundInCache;
  426. Value *NegatedV = NegationsCacheIterator->second;
  427. assert(NegatedV != Placeholder && "Encountered a cycle during negation.");
  428. return NegatedV;
  429. }
  430. #ifndef NDEBUG
  431. // We did not find a cached result for negation of V. While there,
  432. // let's temporairly cache a placeholder value, with the idea that if later
  433. // during negation we fetch it from cache, we'll know we're in a cycle.
  434. NegationsCache[V] = Placeholder;
  435. #endif
  436. // No luck. Try negating it for real.
  437. Value *NegatedV = visitImpl(V, Depth);
  438. // And cache the (real) result for the future.
  439. NegationsCache[V] = NegatedV;
  440. return NegatedV;
  441. }
  442. LLVM_NODISCARD Optional<Negator::Result> Negator::run(Value *Root) {
  443. Value *Negated = negate(Root, /*Depth=*/0);
  444. if (!Negated) {
  445. // We must cleanup newly-inserted instructions, to avoid any potential
  446. // endless combine looping.
  447. llvm::for_each(llvm::reverse(NewInstructions),
  448. [&](Instruction *I) { I->eraseFromParent(); });
  449. return llvm::None;
  450. }
  451. return std::make_pair(ArrayRef<Instruction *>(NewInstructions), Negated);
  452. }
  453. LLVM_NODISCARD Value *Negator::Negate(bool LHSIsZero, Value *Root,
  454. InstCombinerImpl &IC) {
  455. ++NegatorTotalNegationsAttempted;
  456. LLVM_DEBUG(dbgs() << "Negator: attempting to sink negation into " << *Root
  457. << "\n");
  458. if (!NegatorEnabled || !DebugCounter::shouldExecute(NegatorCounter))
  459. return nullptr;
  460. Negator N(Root->getContext(), IC.getDataLayout(), IC.getAssumptionCache(),
  461. IC.getDominatorTree(), LHSIsZero);
  462. Optional<Result> Res = N.run(Root);
  463. if (!Res) { // Negation failed.
  464. LLVM_DEBUG(dbgs() << "Negator: failed to sink negation into " << *Root
  465. << "\n");
  466. return nullptr;
  467. }
  468. LLVM_DEBUG(dbgs() << "Negator: successfully sunk negation into " << *Root
  469. << "\n NEW: " << *Res->second << "\n");
  470. ++NegatorNumTreesNegated;
  471. // We must temporarily unset the 'current' insertion point and DebugLoc of the
  472. // InstCombine's IRBuilder so that it won't interfere with the ones we have
  473. // already specified when producing negated instructions.
  474. InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
  475. IC.Builder.ClearInsertionPoint();
  476. IC.Builder.SetCurrentDebugLocation(DebugLoc());
  477. // And finally, we must add newly-created instructions into the InstCombine's
  478. // worklist (in a proper order!) so it can attempt to combine them.
  479. LLVM_DEBUG(dbgs() << "Negator: Propagating " << Res->first.size()
  480. << " instrs to InstCombine\n");
  481. NegatorMaxInstructionsCreated.updateMax(Res->first.size());
  482. NegatorNumInstructionsNegatedSuccess += Res->first.size();
  483. // They are in def-use order, so nothing fancy, just insert them in order.
  484. llvm::for_each(Res->first,
  485. [&](Instruction *I) { IC.Builder.Insert(I, I->getName()); });
  486. // And return the new root.
  487. return Res->second;
  488. }