LLVM 23.0.0git
InstCombineSimplifyDemanded.cpp
Go to the documentation of this file.
1//===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
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 contains logic for simplifying instructions based on information
10// about how they are used.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
23
24using namespace llvm;
25using namespace llvm::PatternMatch;
26
27#define DEBUG_TYPE "instcombine"
28
29static cl::opt<bool>
30 VerifyKnownBits("instcombine-verify-known-bits",
31 cl::desc("Verify that computeKnownBits() and "
32 "SimplifyDemandedBits() are consistent"),
33 cl::Hidden, cl::init(false));
34
36 "instcombine-simplify-vector-elts-depth",
38 "Depth limit when simplifying vector instructions and their operands"),
39 cl::Hidden, cl::init(10));
40
41/// Check to see if the specified operand of the specified instruction is a
42/// constant integer. If so, check to see if there are any bits set in the
43/// constant that are not demanded. If so, shrink the constant and return true.
44static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
45 const APInt &Demanded) {
46 assert(I && "No instruction?");
47 assert(OpNo < I->getNumOperands() && "Operand index too large");
48
49 // The operand must be a constant integer or splat integer.
50 Value *Op = I->getOperand(OpNo);
51 const APInt *C;
52 if (!match(Op, m_APInt(C)))
53 return false;
54
55 // If there are no bits set that aren't demanded, nothing to do.
56 if (C->isSubsetOf(Demanded))
57 return false;
58
59 // This instruction is producing bits that are not demanded. Shrink the RHS.
60 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
61
62 return true;
63}
64
65/// Let N = 2 * M.
66/// Given an N-bit integer representing a pack of two M-bit integers,
67/// we can select one of the packed integers by right-shifting by either
68/// zero or M (which is the most straightforward to check if M is a power
69/// of 2), and then isolating the lower M bits. In this case, we can
70/// represent the shift as a select on whether the shr amount is nonzero.
72 const APInt &DemandedMask,
74 unsigned Depth) {
75 assert(I->getOpcode() == Instruction::LShr &&
76 "Only lshr instruction supported");
77
78 uint64_t ShlAmt;
79 Value *Upper, *Lower;
80 if (!match(I->getOperand(0),
83 m_Value(Lower)))))
84 return nullptr;
85
86 if (!isPowerOf2_64(ShlAmt))
87 return nullptr;
88
89 const uint64_t DemandedBitWidth = DemandedMask.getActiveBits();
90 if (DemandedBitWidth > ShlAmt)
91 return nullptr;
92
93 // Check that upper demanded bits are not lost from lshift.
94 if (Upper->getType()->getScalarSizeInBits() < ShlAmt + DemandedBitWidth)
95 return nullptr;
96
97 KnownBits KnownLowerBits = IC.computeKnownBits(Lower, I, Depth);
98 if (!KnownLowerBits.getMaxValue().isIntN(ShlAmt))
99 return nullptr;
100
101 Value *ShrAmt = I->getOperand(1);
102 KnownBits KnownShrBits = IC.computeKnownBits(ShrAmt, I, Depth);
103
104 // Verify that ShrAmt is either exactly ShlAmt (which is a power of 2) or
105 // zero.
106 if (~KnownShrBits.Zero != ShlAmt)
107 return nullptr;
108
111 Value *ShrAmtZ =
113 ShrAmt->getName() + ".z");
114 // There is no existing !prof metadata we can derive the !prof metadata for
115 // this select.
118 Select->takeName(I);
119 return Select;
120}
121
122/// Returns the bitwidth of the given scalar or pointer type. For vector types,
123/// returns the element type's bitwidth.
124static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
125 if (unsigned BitWidth = Ty->getScalarSizeInBits())
126 return BitWidth;
127
128 return DL.getPointerTypeSizeInBits(Ty);
129}
130
131/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
132/// the instruction has any properties that allow us to simplify its operands.
134 KnownBits &Known) {
135 APInt DemandedMask(APInt::getAllOnes(Known.getBitWidth()));
136 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
137 SQ.getWithInstruction(&Inst));
138 if (!V) return false;
139 if (V == &Inst) return true;
140 replaceInstUsesWith(Inst, V);
141 return true;
142}
143
144/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
145/// the instruction has any properties that allow us to simplify its operands.
150
153
155 SQ.getWithInstruction(&Inst));
156 if (!V)
157 return false;
158 if (V == &Inst)
159 return true;
160 replaceInstUsesWith(Inst, V);
161 return true;
162}
163
164/// This form of SimplifyDemandedBits simplifies the specified instruction
165/// operand if possible, updating it in place. It returns true if it made any
166/// change and false otherwise.
168 const APInt &DemandedMask,
170 const SimplifyQuery &Q,
171 unsigned Depth) {
172 Use &U = I->getOperandUse(OpNo);
173 Value *V = U.get();
174 if (isa<Constant>(V)) {
176 return false;
177 }
178
179 Known.resetAll();
180 if (DemandedMask.isZero()) {
181 // Not demanding any bits from V.
182 replaceUse(U, UndefValue::get(V->getType()));
183 return true;
184 }
185
187 if (!VInst) {
189 return false;
190 }
191
193 return false;
194
195 Value *NewVal;
196 if (VInst->hasOneUse()) {
197 // If the instruction has one use, we can directly simplify it.
198 NewVal = SimplifyDemandedUseBits(VInst, DemandedMask, Known, Q, Depth);
199 } else {
200 // If there are multiple uses of this instruction, then we can simplify
201 // VInst to some other value, but not modify the instruction.
202 NewVal =
203 SimplifyMultipleUseDemandedBits(VInst, DemandedMask, Known, Q, Depth);
204 }
205 if (!NewVal) return false;
206 if (Instruction* OpInst = dyn_cast<Instruction>(U))
207 salvageDebugInfo(*OpInst);
208
209 replaceUse(U, NewVal);
210 return true;
211}
212
213/// This function attempts to replace V with a simpler value based on the
214/// demanded bits. When this function is called, it is known that only the bits
215/// set in DemandedMask of the result of V are ever used downstream.
216/// Consequently, depending on the mask and V, it may be possible to replace V
217/// with a constant or one of its operands. In such cases, this function does
218/// the replacement and returns true. In all other cases, it returns false after
219/// analyzing the expression and setting KnownOne and known to be one in the
220/// expression. Known.Zero contains all the bits that are known to be zero in
221/// the expression. These are provided to potentially allow the caller (which
222/// might recursively be SimplifyDemandedBits itself) to simplify the
223/// expression.
224/// Known.One and Known.Zero always follow the invariant that:
225/// Known.One & Known.Zero == 0.
226/// That is, a bit can't be both 1 and 0. The bits in Known.One and Known.Zero
227/// are accurate even for bits not in DemandedMask. Note
228/// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
229/// be the same.
230///
231/// This returns null if it did not change anything and it permits no
232/// simplification. This returns V itself if it did some simplification of V's
233/// operands based on the information about what bits are demanded. This returns
234/// some other non-null value if it found out that V is equal to another value
235/// in the context where the specified bits are demanded, but not for all users.
237 const APInt &DemandedMask,
239 const SimplifyQuery &Q,
240 unsigned Depth) {
241 assert(I != nullptr && "Null pointer of Value???");
242 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
243 uint32_t BitWidth = DemandedMask.getBitWidth();
244 Type *VTy = I->getType();
245 assert(
246 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
247 Known.getBitWidth() == BitWidth &&
248 "Value *V, DemandedMask and Known must have same BitWidth");
249
250 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
251
252 // Update flags after simplifying an operand based on the fact that some high
253 // order bits are not demanded.
254 auto disableWrapFlagsBasedOnUnusedHighBits = [](Instruction *I,
255 unsigned NLZ) {
256 if (NLZ > 0) {
257 // Disable the nsw and nuw flags here: We can no longer guarantee that
258 // we won't wrap after simplification. Removing the nsw/nuw flags is
259 // legal here because the top bit is not demanded.
260 I->setHasNoSignedWrap(false);
261 I->setHasNoUnsignedWrap(false);
262 }
263 return I;
264 };
265
266 // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
267 // about the high bits of the operands.
268 auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
269 unsigned NLZ = DemandedMask.countl_zero();
270 // Right fill the mask of bits for the operands to demand the most
271 // significant bit and all those below it.
272 DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
273 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
274 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Q, Depth + 1) ||
275 ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
276 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1)) {
277 disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
278 return true;
279 }
280 return false;
281 };
282
283 switch (I->getOpcode()) {
284 default:
286 break;
287 case Instruction::And: {
288 // If either the LHS or the RHS are Zero, the result is zero.
289 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
290 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown, Q,
291 Depth + 1))
292 return I;
293
294 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
295 Q, Depth);
296
297 // If the client is only demanding bits that we know, return the known
298 // constant.
299 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
300 return Constant::getIntegerValue(VTy, Known.One);
301
302 // If all of the demanded bits are known 1 on one side, return the other.
303 // These bits cannot contribute to the result of the 'and'.
304 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
305 return I->getOperand(0);
306 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
307 return I->getOperand(1);
308
309 // If the RHS is a constant, see if we can simplify it.
310 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
311 return I;
312
313 break;
314 }
315 case Instruction::Or: {
316 // If either the LHS or the RHS are One, the result is One.
317 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
318 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown, Q,
319 Depth + 1)) {
320 // Disjoint flag may not longer hold.
321 I->dropPoisonGeneratingFlags();
322 return I;
323 }
324
325 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
326 Q, Depth);
327
328 // If the client is only demanding bits that we know, return the known
329 // constant.
330 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
331 return Constant::getIntegerValue(VTy, Known.One);
332
333 // If all of the demanded bits are known zero on one side, return the other.
334 // These bits cannot contribute to the result of the 'or'.
335 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
336 return I->getOperand(0);
337 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
338 return I->getOperand(1);
339
340 // If the RHS is a constant, see if we can simplify it.
341 if (ShrinkDemandedConstant(I, 1, DemandedMask))
342 return I;
343
344 // Infer disjoint flag if no common bits are set.
345 if (!cast<PossiblyDisjointInst>(I)->isDisjoint()) {
346 WithCache<const Value *> LHSCache(I->getOperand(0), LHSKnown),
347 RHSCache(I->getOperand(1), RHSKnown);
348 if (haveNoCommonBitsSet(LHSCache, RHSCache, Q)) {
349 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
350 return I;
351 }
352 }
353
354 break;
355 }
356 case Instruction::Xor: {
357 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
358 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Q, Depth + 1))
359 return I;
360 Value *LHS, *RHS;
361 if (DemandedMask == 1 && match(I->getOperand(0), m_Ctpop(m_Value(LHS))) &&
362 match(I->getOperand(1), m_Ctpop(m_Value(RHS)))) {
363 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
365 Builder.SetInsertPoint(I);
366 auto *Xor = Builder.CreateXor(LHS, RHS);
367 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
368 }
369
370 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
371 Q, Depth);
372
373 // If the client is only demanding bits that we know, return the known
374 // constant.
375 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
376 return Constant::getIntegerValue(VTy, Known.One);
377
378 // If all of the demanded bits are known zero on one side, return the other.
379 // These bits cannot contribute to the result of the 'xor'.
380 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
381 return I->getOperand(0);
382 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
383 return I->getOperand(1);
384
385 // If all of the demanded bits are known to be zero on one side or the
386 // other, turn this into an *inclusive* or.
387 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
388 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
389 Instruction *Or =
390 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1));
391 if (DemandedMask.isAllOnes())
392 cast<PossiblyDisjointInst>(Or)->setIsDisjoint(true);
393 Or->takeName(I);
394 return InsertNewInstWith(Or, I->getIterator());
395 }
396
397 // If all of the demanded bits on one side are known, and all of the set
398 // bits on that side are also known to be set on the other side, turn this
399 // into an AND, as we know the bits will be cleared.
400 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
401 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
402 RHSKnown.One.isSubsetOf(LHSKnown.One)) {
404 ~RHSKnown.One & DemandedMask);
405 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
406 return InsertNewInstWith(And, I->getIterator());
407 }
408
409 // If the RHS is a constant, see if we can change it. Don't alter a -1
410 // constant because that's a canonical 'not' op, and that is better for
411 // combining, SCEV, and codegen.
412 const APInt *C;
413 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
414 if ((*C | ~DemandedMask).isAllOnes()) {
415 // Force bits to 1 to create a 'not' op.
416 I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
417 return I;
418 }
419 // If we can't turn this into a 'not', try to shrink the constant.
420 if (ShrinkDemandedConstant(I, 1, DemandedMask))
421 return I;
422 }
423
424 // If our LHS is an 'and' and if it has one use, and if any of the bits we
425 // are flipping are known to be set, then the xor is just resetting those
426 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
427 // simplifying both of them.
428 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
429 ConstantInt *AndRHS, *XorRHS;
430 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
431 match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
432 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
433 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
434 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
435
436 Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue());
437 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
438 InsertNewInstWith(NewAnd, I->getIterator());
439
440 Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue());
441 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
442 return InsertNewInstWith(NewXor, I->getIterator());
443 }
444 }
445 break;
446 }
447 case Instruction::Select: {
448 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Q, Depth + 1) ||
449 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Q, Depth + 1))
450 return I;
451
452 // If the operands are constants, see if we can simplify them.
453 // This is similar to ShrinkDemandedConstant, but for a select we want to
454 // try to keep the selected constants the same as icmp value constants, if
455 // we can. This helps not break apart (or helps put back together)
456 // canonical patterns like min and max.
457 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
458 const APInt &DemandedMask) {
459 const APInt *SelC;
460 if (!match(I->getOperand(OpNo), m_APInt(SelC)))
461 return false;
462
463 // Get the constant out of the ICmp, if there is one.
464 // Only try this when exactly 1 operand is a constant (if both operands
465 // are constant, the icmp should eventually simplify). Otherwise, we may
466 // invert the transform that reduces set bits and infinite-loop.
467 Value *X;
468 const APInt *CmpC;
469 if (!match(I->getOperand(0), m_ICmp(m_Value(X), m_APInt(CmpC))) ||
470 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
471 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
472
473 // If the constant is already the same as the ICmp, leave it as-is.
474 if (*CmpC == *SelC)
475 return false;
476 // If the constants are not already the same, but can be with the demand
477 // mask, use the constant value from the ICmp.
478 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
479 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
480 return true;
481 }
482 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
483 };
484 if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
485 CanonicalizeSelectConstant(I, 2, DemandedMask))
486 return I;
487
488 // Only known if known in both the LHS and RHS.
489 adjustKnownBitsForSelectArm(LHSKnown, I->getOperand(0), I->getOperand(1),
490 /*Invert=*/false, Q, Depth);
491 adjustKnownBitsForSelectArm(RHSKnown, I->getOperand(0), I->getOperand(2),
492 /*Invert=*/true, Q, Depth);
493 Known = LHSKnown.intersectWith(RHSKnown);
494 break;
495 }
496 case Instruction::Trunc: {
497 // If we do not demand the high bits of a right-shifted and truncated value,
498 // then we may be able to truncate it before the shift.
499 Value *X;
500 const APInt *C;
501 if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
502 // The shift amount must be valid (not poison) in the narrow type, and
503 // it must not be greater than the high bits demanded of the result.
504 if (C->ult(VTy->getScalarSizeInBits()) &&
505 C->ule(DemandedMask.countl_zero())) {
506 // trunc (lshr X, C) --> lshr (trunc X), C
508 Builder.SetInsertPoint(I);
509 Value *Trunc = Builder.CreateTrunc(X, VTy);
510 return Builder.CreateLShr(Trunc, C->getZExtValue());
511 }
512 }
513 }
514 [[fallthrough]];
515 case Instruction::ZExt: {
516 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
517
518 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
519 KnownBits InputKnown(SrcBitWidth);
520 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Q,
521 Depth + 1)) {
522 // For zext nneg, we may have dropped the instruction which made the
523 // input non-negative.
524 I->dropPoisonGeneratingFlags();
525 return I;
526 }
527 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
528 if (I->getOpcode() == Instruction::ZExt && I->hasNonNeg() &&
529 !InputKnown.isNegative())
530 InputKnown.makeNonNegative();
531 Known = InputKnown.zextOrTrunc(BitWidth);
532
533 break;
534 }
535 case Instruction::SExt: {
536 // Compute the bits in the result that are not present in the input.
537 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
538
539 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
540
541 // If any of the sign extended bits are demanded, we know that the sign
542 // bit is demanded.
543 if (DemandedMask.getActiveBits() > SrcBitWidth)
544 InputDemandedBits.setBit(SrcBitWidth-1);
545
546 KnownBits InputKnown(SrcBitWidth);
547 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Q, Depth + 1))
548 return I;
549
550 // If the input sign bit is known zero, or if the NewBits are not demanded
551 // convert this into a zero extension.
552 if (InputKnown.isNonNegative() ||
553 DemandedMask.getActiveBits() <= SrcBitWidth) {
554 // Convert to ZExt cast.
555 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy);
556 NewCast->takeName(I);
557 return InsertNewInstWith(NewCast, I->getIterator());
558 }
559
560 // If the sign bit of the input is known set or clear, then we know the
561 // top bits of the result.
562 Known = InputKnown.sext(BitWidth);
563 break;
564 }
565 case Instruction::Add: {
566 if ((DemandedMask & 1) == 0) {
567 // If we do not need the low bit, try to convert bool math to logic:
568 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
569 Value *X, *Y;
571 m_OneUse(m_SExt(m_Value(Y))))) &&
572 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
573 // Truth table for inputs and output signbits:
574 // X:0 | X:1
575 // ----------
576 // Y:0 | 0 | 0 |
577 // Y:1 | -1 | 0 |
578 // ----------
580 Builder.SetInsertPoint(I);
581 Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
582 return Builder.CreateSExt(AndNot, VTy);
583 }
584
585 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
586 if (match(I, m_Add(m_SExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
587 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
588 (I->getOperand(0)->hasOneUse() || I->getOperand(1)->hasOneUse())) {
589
590 // Truth table for inputs and output signbits:
591 // X:0 | X:1
592 // -----------
593 // Y:0 | 0 | -1 |
594 // Y:1 | -1 | -1 |
595 // -----------
597 Builder.SetInsertPoint(I);
598 Value *Or = Builder.CreateOr(X, Y);
599 return Builder.CreateSExt(Or, VTy);
600 }
601 }
602
603 // Right fill the mask of bits for the operands to demand the most
604 // significant bit and all those below it.
605 unsigned NLZ = DemandedMask.countl_zero();
606 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
607 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
608 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1))
609 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
610
611 // If low order bits are not demanded and known to be zero in one operand,
612 // then we don't need to demand them from the other operand, since they
613 // can't cause overflow into any bits that are demanded in the result.
614 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
615 APInt DemandedFromLHS = DemandedFromOps;
616 DemandedFromLHS.clearLowBits(NTZ);
617 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
618 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Q, Depth + 1))
619 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
620
621 unsigned NtzLHS = (~DemandedMask & LHSKnown.Zero).countr_one();
622 APInt DemandedFromRHS = DemandedFromOps;
623 DemandedFromRHS.clearLowBits(NtzLHS);
624 if (ShrinkDemandedConstant(I, 1, DemandedFromRHS))
625 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
626
627 // If we are known to be adding zeros to every bit below
628 // the highest demanded bit, we just return the other side.
629 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
630 return I->getOperand(0);
631 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
632 return I->getOperand(1);
633
634 // (add X, C) --> (xor X, C) IFF C is equal to the top bit of the DemandMask
635 {
636 const APInt *C;
637 if (match(I->getOperand(1), m_APInt(C)) &&
638 C->isOneBitSet(DemandedMask.getActiveBits() - 1)) {
640 Builder.SetInsertPoint(I);
641 return Builder.CreateXor(I->getOperand(0), ConstantInt::get(VTy, *C));
642 }
643 }
644
645 // Otherwise just compute the known bits of the result.
646 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
647 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
648 Known = KnownBits::add(LHSKnown, RHSKnown, NSW, NUW);
649 break;
650 }
651 case Instruction::Sub: {
652 // Right fill the mask of bits for the operands to demand the most
653 // significant bit and all those below it.
654 unsigned NLZ = DemandedMask.countl_zero();
655 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
656 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
657 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1))
658 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
659
660 // If low order bits are not demanded and are known to be zero in RHS,
661 // then we don't need to demand them from LHS, since they can't cause a
662 // borrow from any bits that are demanded in the result.
663 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
664 APInt DemandedFromLHS = DemandedFromOps;
665 DemandedFromLHS.clearLowBits(NTZ);
666 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
667 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Q, Depth + 1))
668 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
669
670 // If we are known to be subtracting zeros from every bit below
671 // the highest demanded bit, we just return the other side.
672 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
673 return I->getOperand(0);
674 // We can't do this with the LHS for subtraction, unless we are only
675 // demanding the LSB.
676 if (DemandedFromOps.isOne() && DemandedFromOps.isSubsetOf(LHSKnown.Zero))
677 return I->getOperand(1);
678
679 // Canonicalize sub mask, X -> ~X
680 const APInt *LHSC;
681 if (match(I->getOperand(0), m_LowBitMask(LHSC)) &&
682 DemandedFromOps.isSubsetOf(*LHSC)) {
684 Builder.SetInsertPoint(I);
685 return Builder.CreateNot(I->getOperand(1));
686 }
687
688 // Otherwise just compute the known bits of the result.
689 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
690 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
691 Known = KnownBits::sub(LHSKnown, RHSKnown, NSW, NUW);
692 break;
693 }
694 case Instruction::Mul: {
695 APInt DemandedFromOps;
696 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
697 return I;
698
699 if (DemandedMask.isPowerOf2()) {
700 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
701 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
702 // odd (has LSB set), then the left-shifted low bit of X is the answer.
703 unsigned CTZ = DemandedMask.countr_zero();
704 const APInt *C;
705 if (match(I->getOperand(1), m_APInt(C)) && C->countr_zero() == CTZ) {
706 Constant *ShiftC = ConstantInt::get(VTy, CTZ);
707 Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
708 return InsertNewInstWith(Shl, I->getIterator());
709 }
710 }
711 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
712 // X * X is odd iff X is odd.
713 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
714 if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
715 Constant *One = ConstantInt::get(VTy, 1);
716 Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
717 return InsertNewInstWith(And1, I->getIterator());
718 }
719
721 break;
722 }
723 case Instruction::Shl: {
724 const APInt *SA;
725 if (match(I->getOperand(1), m_APInt(SA))) {
726 const APInt *ShrAmt;
727 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
728 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
729 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
730 DemandedMask, Known))
731 return R;
732
733 // Do not simplify if shl is part of funnel-shift pattern
734 if (I->hasOneUse()) {
735 Instruction *Inst = I->user_back();
736 if (Inst->getOpcode() == BinaryOperator::Or) {
737 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
738 auto [IID, FShiftArgs] = *Opt;
739 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
740 FShiftArgs[0] == FShiftArgs[1]) {
742 break;
743 }
744 }
745 }
746 }
747
748 // We only want bits that already match the signbit then we don't
749 // need to shift.
750 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth - 1);
751 if (DemandedMask.countr_zero() >= ShiftAmt) {
752 if (I->hasNoSignedWrap()) {
753 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
754 unsigned SignBits =
755 ComputeNumSignBits(I->getOperand(0), Q.CxtI, Depth + 1);
756 if (SignBits > ShiftAmt && SignBits - ShiftAmt >= NumHiDemandedBits)
757 return I->getOperand(0);
758 }
759
760 // If we can pre-shift a right-shifted constant to the left without
761 // losing any high bits and we don't demand the low bits, then eliminate
762 // the left-shift:
763 // (C >> X) << LeftShiftAmtC --> (C << LeftShiftAmtC) >> X
764 Value *X;
765 Constant *C;
766 if (match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) {
767 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
768 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::Shl, C,
769 LeftShiftAmtC, DL);
770 if (ConstantFoldBinaryOpOperands(Instruction::LShr, NewC,
771 LeftShiftAmtC, DL) == C) {
772 Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X);
773 return InsertNewInstWith(Lshr, I->getIterator());
774 }
775 }
776 }
777
778 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
779
780 // If the shift is NUW/NSW, then it does demand the high bits.
782 if (IOp->hasNoSignedWrap())
783 DemandedMaskIn.setHighBits(ShiftAmt+1);
784 else if (IOp->hasNoUnsignedWrap())
785 DemandedMaskIn.setHighBits(ShiftAmt);
786
787 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1))
788 return I;
789
792 /* NUW */ IOp->hasNoUnsignedWrap(),
793 /* NSW */ IOp->hasNoSignedWrap());
794 } else {
795 // This is a variable shift, so we can't shift the demand mask by a known
796 // amount. But if we are not demanding high bits, then we are not
797 // demanding those bits from the pre-shifted operand either.
798 if (unsigned CTLZ = DemandedMask.countl_zero()) {
799 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
800 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Q, Depth + 1)) {
801 // We can't guarantee that nsw/nuw hold after simplifying the operand.
802 I->dropPoisonGeneratingFlags();
803 return I;
804 }
805 }
807 }
808 break;
809 }
810 case Instruction::LShr: {
811 const APInt *SA;
812 if (match(I->getOperand(1), m_APInt(SA))) {
813 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
814
815 // Do not simplify if lshr is part of funnel-shift pattern
816 if (I->hasOneUse()) {
817 Instruction *Inst = I->user_back();
818 if (Inst->getOpcode() == BinaryOperator::Or) {
819 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
820 auto [IID, FShiftArgs] = *Opt;
821 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
822 FShiftArgs[0] == FShiftArgs[1]) {
824 break;
825 }
826 }
827 }
828 }
829
830 // If we are just demanding the shifted sign bit and below, then this can
831 // be treated as an ASHR in disguise.
832 if (DemandedMask.countl_zero() >= ShiftAmt) {
833 // If we only want bits that already match the signbit then we don't
834 // need to shift.
835 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
836 unsigned SignBits =
837 ComputeNumSignBits(I->getOperand(0), Q.CxtI, Depth + 1);
838 if (SignBits >= NumHiDemandedBits)
839 return I->getOperand(0);
840
841 // If we can pre-shift a left-shifted constant to the right without
842 // losing any low bits (we already know we don't demand the high bits),
843 // then eliminate the right-shift:
844 // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
845 Value *X;
846 Constant *C;
847 if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
848 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
849 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::LShr, C,
850 RightShiftAmtC, DL);
851 if (ConstantFoldBinaryOpOperands(Instruction::Shl, NewC,
852 RightShiftAmtC, DL) == C) {
853 Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
854 return InsertNewInstWith(Shl, I->getIterator());
855 }
856 }
857
858 const APInt *Factor;
859 if (match(I->getOperand(0),
860 m_OneUse(m_Mul(m_Value(X), m_APInt(Factor)))) &&
861 Factor->countr_zero() >= ShiftAmt) {
862 BinaryOperator *Mul = BinaryOperator::CreateMul(
863 X, ConstantInt::get(X->getType(), Factor->lshr(ShiftAmt)));
864 return InsertNewInstWith(Mul, I->getIterator());
865 }
866 }
867
868 // Unsigned shift right.
869 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
870 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1)) {
871 // exact flag may not longer hold.
872 I->dropPoisonGeneratingFlags();
873 return I;
874 }
875 Known >>= ShiftAmt;
876 if (ShiftAmt)
877 Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
878 break;
879 }
880 if (Value *V =
881 simplifyShiftSelectingPackedElement(I, DemandedMask, *this, Depth))
882 return V;
883
885 break;
886 }
887 case Instruction::AShr: {
888 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Q.CxtI, Depth + 1);
889
890 // If we only want bits that already match the signbit then we don't need
891 // to shift.
892 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
893 if (SignBits >= NumHiDemandedBits)
894 return I->getOperand(0);
895
896 // If this is an arithmetic shift right and only the low-bit is set, we can
897 // always convert this into a logical shr, even if the shift amount is
898 // variable. The low bit of the shift cannot be an input sign bit unless
899 // the shift amount is >= the size of the datatype, which is undefined.
900 if (DemandedMask.isOne()) {
901 // Perform the logical shift right.
902 Instruction *NewVal = BinaryOperator::CreateLShr(
903 I->getOperand(0), I->getOperand(1), I->getName());
904 return InsertNewInstWith(NewVal, I->getIterator());
905 }
906
907 const APInt *SA;
908 if (match(I->getOperand(1), m_APInt(SA))) {
909 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
910
911 // Signed shift right.
912 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
913 // If any of the bits being shifted in are demanded, then we should set
914 // the sign bit as demanded.
915 bool ShiftedInBitsDemanded = DemandedMask.countl_zero() < ShiftAmt;
916 if (ShiftedInBitsDemanded)
917 DemandedMaskIn.setSignBit();
918 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1)) {
919 // exact flag may not longer hold.
920 I->dropPoisonGeneratingFlags();
921 return I;
922 }
923
924 // If the input sign bit is known to be zero, or if none of the shifted in
925 // bits are demanded, turn this into an unsigned shift right.
926 if (Known.Zero[BitWidth - 1] || !ShiftedInBitsDemanded) {
927 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
928 I->getOperand(1));
929 LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
930 LShr->takeName(I);
931 return InsertNewInstWith(LShr, I->getIterator());
932 }
933
936 ShiftAmt != 0, I->isExact());
937 } else {
939 }
940 break;
941 }
942 case Instruction::UDiv: {
943 // UDiv doesn't demand low bits that are zero in the divisor.
944 const APInt *SA;
945 if (match(I->getOperand(1), m_APInt(SA))) {
946 // TODO: Take the demanded mask of the result into account.
947 unsigned RHSTrailingZeros = SA->countr_zero();
948 APInt DemandedMaskIn =
949 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
950 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Q, Depth + 1)) {
951 // We can't guarantee that "exact" is still true after changing the
952 // the dividend.
953 I->dropPoisonGeneratingFlags();
954 return I;
955 }
956
958 cast<BinaryOperator>(I)->isExact());
959 } else {
961 }
962 break;
963 }
964 case Instruction::SRem: {
965 const APInt *Rem;
966 if (match(I->getOperand(1), m_APInt(Rem)) && Rem->isPowerOf2()) {
967 if (DemandedMask.ult(*Rem)) // srem won't affect demanded bits
968 return I->getOperand(0);
969
970 APInt LowBits = *Rem - 1;
971 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
972 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Q, Depth + 1))
973 return I;
975 break;
976 }
977
979 break;
980 }
981 case Instruction::Call: {
982 bool KnownBitsComputed = false;
984 switch (II->getIntrinsicID()) {
985 case Intrinsic::abs: {
986 if (DemandedMask == 1)
987 return II->getArgOperand(0);
988 break;
989 }
990 case Intrinsic::ctpop: {
991 // Checking if the number of clear bits is odd (parity)? If the type has
992 // an even number of bits, that's the same as checking if the number of
993 // set bits is odd, so we can eliminate the 'not' op.
994 Value *X;
995 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
996 match(II->getArgOperand(0), m_Not(m_Value(X)))) {
998 II->getModule(), Intrinsic::ctpop, VTy);
999 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), I->getIterator());
1000 }
1001 break;
1002 }
1003 case Intrinsic::bswap: {
1004 // If the only bits demanded come from one byte of the bswap result,
1005 // just shift the input byte into position to eliminate the bswap.
1006 unsigned NLZ = DemandedMask.countl_zero();
1007 unsigned NTZ = DemandedMask.countr_zero();
1008
1009 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1010 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1011 // have 14 leading zeros, round to 8.
1012 NLZ = alignDown(NLZ, 8);
1013 NTZ = alignDown(NTZ, 8);
1014 // If we need exactly one byte, we can do this transformation.
1015 if (BitWidth - NLZ - NTZ == 8) {
1016 // Replace this with either a left or right shift to get the byte into
1017 // the right place.
1018 Instruction *NewVal;
1019 if (NLZ > NTZ)
1020 NewVal = BinaryOperator::CreateLShr(
1021 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
1022 else
1023 NewVal = BinaryOperator::CreateShl(
1024 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
1025 NewVal->takeName(I);
1026 return InsertNewInstWith(NewVal, I->getIterator());
1027 }
1028 break;
1029 }
1030 case Intrinsic::ptrmask: {
1031 unsigned MaskWidth = I->getOperand(1)->getType()->getScalarSizeInBits();
1032 RHSKnown = KnownBits(MaskWidth);
1033 // If either the LHS or the RHS are Zero, the result is zero.
1034 if (SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Q, Depth + 1) ||
1036 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth),
1037 RHSKnown, Q, Depth + 1))
1038 return I;
1039
1040 // TODO: Should be 1-extend
1041 RHSKnown = RHSKnown.anyextOrTrunc(BitWidth);
1042
1043 Known = LHSKnown & RHSKnown;
1044 KnownBitsComputed = true;
1045
1046 // If the client is only demanding bits we know to be zero, return
1047 // `llvm.ptrmask(p, 0)`. We can't return `null` here due to pointer
1048 // provenance, but making the mask zero will be easily optimizable in
1049 // the backend.
1050 if (DemandedMask.isSubsetOf(Known.Zero) &&
1051 !match(I->getOperand(1), m_Zero()))
1052 return replaceOperand(
1053 *I, 1, Constant::getNullValue(I->getOperand(1)->getType()));
1054
1055 // Mask in demanded space does nothing.
1056 // NOTE: We may have attributes associated with the return value of the
1057 // llvm.ptrmask intrinsic that will be lost when we just return the
1058 // operand. We should try to preserve them.
1059 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1060 return I->getOperand(0);
1061
1062 // If the RHS is a constant, see if we can simplify it.
1064 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth)))
1065 return I;
1066
1067 // Combine:
1068 // (ptrmask (getelementptr i8, ptr p, imm i), imm mask)
1069 // -> (ptrmask (getelementptr i8, ptr p, imm (i & mask)), imm mask)
1070 // where only the low bits known to be zero in the pointer are changed
1071 Value *InnerPtr;
1072 uint64_t GEPIndex;
1073 uint64_t PtrMaskImmediate;
1075 m_PtrAdd(m_Value(InnerPtr), m_ConstantInt(GEPIndex)),
1076 m_ConstantInt(PtrMaskImmediate)))) {
1077
1078 LHSKnown = computeKnownBits(InnerPtr, I, Depth + 1);
1079 if (!LHSKnown.isZero()) {
1080 const unsigned trailingZeros = LHSKnown.countMinTrailingZeros();
1081 uint64_t PointerAlignBits = (uint64_t(1) << trailingZeros) - 1;
1082
1083 uint64_t HighBitsGEPIndex = GEPIndex & ~PointerAlignBits;
1084 uint64_t MaskedLowBitsGEPIndex =
1085 GEPIndex & PointerAlignBits & PtrMaskImmediate;
1086
1087 uint64_t MaskedGEPIndex = HighBitsGEPIndex | MaskedLowBitsGEPIndex;
1088
1089 if (MaskedGEPIndex != GEPIndex) {
1090 auto *GEP = cast<GEPOperator>(II->getArgOperand(0));
1091 Builder.SetInsertPoint(I);
1092 Type *GEPIndexType =
1093 DL.getIndexType(GEP->getPointerOperand()->getType());
1094 Value *MaskedGEP = Builder.CreateGEP(
1095 GEP->getSourceElementType(), InnerPtr,
1096 ConstantInt::get(GEPIndexType, MaskedGEPIndex),
1097 GEP->getName(), GEP->isInBounds());
1098
1099 replaceOperand(*I, 0, MaskedGEP);
1100 return I;
1101 }
1102 }
1103 }
1104
1105 break;
1106 }
1107
1108 case Intrinsic::fshr:
1109 case Intrinsic::fshl: {
1110 const APInt *SA;
1111 if (!match(I->getOperand(2), m_APInt(SA)))
1112 break;
1113
1114 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
1115 // defined, so no need to special-case zero shifts here.
1116 uint64_t ShiftAmt = SA->urem(BitWidth);
1117 if (II->getIntrinsicID() == Intrinsic::fshr)
1118 ShiftAmt = BitWidth - ShiftAmt;
1119
1120 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
1121 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
1122 if (I->getOperand(0) != I->getOperand(1)) {
1123 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Q,
1124 Depth + 1) ||
1125 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Q,
1126 Depth + 1)) {
1127 // Range attribute or metadata may no longer hold.
1128 I->dropPoisonGeneratingAnnotations();
1129 return I;
1130 }
1131 } else { // fshl is a rotate
1132 // Avoid converting rotate into funnel shift.
1133 // Only simplify if one operand is constant.
1134 LHSKnown = computeKnownBits(I->getOperand(0), I, Depth + 1);
1135 if (DemandedMaskLHS.isSubsetOf(LHSKnown.Zero | LHSKnown.One) &&
1136 !match(I->getOperand(0), m_SpecificInt(LHSKnown.One))) {
1137 replaceOperand(*I, 0, Constant::getIntegerValue(VTy, LHSKnown.One));
1138 return I;
1139 }
1140
1141 RHSKnown = computeKnownBits(I->getOperand(1), I, Depth + 1);
1142 if (DemandedMaskRHS.isSubsetOf(RHSKnown.Zero | RHSKnown.One) &&
1143 !match(I->getOperand(1), m_SpecificInt(RHSKnown.One))) {
1144 replaceOperand(*I, 1, Constant::getIntegerValue(VTy, RHSKnown.One));
1145 return I;
1146 }
1147 }
1148
1149 LHSKnown <<= ShiftAmt;
1150 RHSKnown >>= BitWidth - ShiftAmt;
1151 Known = LHSKnown.unionWith(RHSKnown);
1152 KnownBitsComputed = true;
1153 break;
1154 }
1155 case Intrinsic::umax: {
1156 // UMax(A, C) == A if ...
1157 // The lowest non-zero bit of DemandMask is higher than the highest
1158 // non-zero bit of C.
1159 const APInt *C;
1160 unsigned CTZ = DemandedMask.countr_zero();
1161 if (match(II->getArgOperand(1), m_APInt(C)) &&
1162 CTZ >= C->getActiveBits())
1163 return II->getArgOperand(0);
1164 break;
1165 }
1166 case Intrinsic::umin: {
1167 // UMin(A, C) == A if ...
1168 // The lowest non-zero bit of DemandMask is higher than the highest
1169 // non-one bit of C.
1170 // This comes from using DeMorgans on the above umax example.
1171 const APInt *C;
1172 unsigned CTZ = DemandedMask.countr_zero();
1173 if (match(II->getArgOperand(1), m_APInt(C)) &&
1174 CTZ >= C->getBitWidth() - C->countl_one())
1175 return II->getArgOperand(0);
1176 break;
1177 }
1178 default: {
1179 // Handle target specific intrinsics
1180 std::optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
1181 *II, DemandedMask, Known, KnownBitsComputed);
1182 if (V)
1183 return *V;
1184 break;
1185 }
1186 }
1187 }
1188
1189 if (!KnownBitsComputed)
1191 break;
1192 }
1193 }
1194
1195 if (I->getType()->isPointerTy()) {
1196 Align Alignment = I->getPointerAlignment(DL);
1197 Known.Zero.setLowBits(Log2(Alignment));
1198 }
1199
1200 // If the client is only demanding bits that we know, return the known
1201 // constant. We can't directly simplify pointers as a constant because of
1202 // pointer provenance.
1203 // TODO: We could return `(inttoptr const)` for pointers.
1204 if (!I->getType()->isPointerTy() &&
1205 DemandedMask.isSubsetOf(Known.Zero | Known.One))
1206 return Constant::getIntegerValue(VTy, Known.One);
1207
1208 if (VerifyKnownBits) {
1209 KnownBits ReferenceKnown = llvm::computeKnownBits(I, Q, Depth);
1210 if (Known != ReferenceKnown) {
1211 errs() << "Mismatched known bits for " << *I << " in "
1212 << I->getFunction()->getName() << "\n";
1213 errs() << "computeKnownBits(): " << ReferenceKnown << "\n";
1214 errs() << "SimplifyDemandedBits(): " << Known << "\n";
1215 std::abort();
1216 }
1217 }
1218
1219 return nullptr;
1220}
1221
1222/// Helper routine of SimplifyDemandedUseBits. It computes Known
1223/// bits. It also tries to handle simplifications that can be done based on
1224/// DemandedMask, but without modifying the Instruction.
1226 Instruction *I, const APInt &DemandedMask, KnownBits &Known,
1227 const SimplifyQuery &Q, unsigned Depth) {
1228 unsigned BitWidth = DemandedMask.getBitWidth();
1229 Type *ITy = I->getType();
1230
1231 KnownBits LHSKnown(BitWidth);
1232 KnownBits RHSKnown(BitWidth);
1233
1234 // Despite the fact that we can't simplify this instruction in all User's
1235 // context, we can at least compute the known bits, and we can
1236 // do simplifications that apply to *just* the one user if we know that
1237 // this instruction has a simpler value in that context.
1238 switch (I->getOpcode()) {
1239 case Instruction::And: {
1240 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1241 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1242 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1243 Q, Depth);
1245
1246 // If the client is only demanding bits that we know, return the known
1247 // constant.
1248 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1249 return Constant::getIntegerValue(ITy, Known.One);
1250
1251 // If all of the demanded bits are known 1 on one side, return the other.
1252 // These bits cannot contribute to the result of the 'and' in this context.
1253 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
1254 return I->getOperand(0);
1255 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
1256 return I->getOperand(1);
1257
1258 break;
1259 }
1260 case Instruction::Or: {
1261 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1262 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1263 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1264 Q, Depth);
1266
1267 // If the client is only demanding bits that we know, return the known
1268 // constant.
1269 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1270 return Constant::getIntegerValue(ITy, Known.One);
1271
1272 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1273 // only bits from X or Y are demanded.
1274 // If all of the demanded bits are known zero on one side, return the other.
1275 // These bits cannot contribute to the result of the 'or' in this context.
1276 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
1277 return I->getOperand(0);
1278 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1279 return I->getOperand(1);
1280
1281 break;
1282 }
1283 case Instruction::Xor: {
1284 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1285 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1286 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1287 Q, Depth);
1289
1290 // If the client is only demanding bits that we know, return the known
1291 // constant.
1292 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1293 return Constant::getIntegerValue(ITy, Known.One);
1294
1295 // We can simplify (X^Y) -> X or Y in the user's context if we know that
1296 // only bits from X or Y are demanded.
1297 // If all of the demanded bits are known zero on one side, return the other.
1298 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1299 return I->getOperand(0);
1300 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1301 return I->getOperand(1);
1302
1303 break;
1304 }
1305 case Instruction::Add: {
1306 unsigned NLZ = DemandedMask.countl_zero();
1307 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1308
1309 // If an operand adds zeros to every bit below the highest demanded bit,
1310 // that operand doesn't change the result. Return the other side.
1311 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1312 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1313 return I->getOperand(0);
1314
1315 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1316 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
1317 return I->getOperand(1);
1318
1319 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1320 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1321 Known = KnownBits::add(LHSKnown, RHSKnown, NSW, NUW);
1323 break;
1324 }
1325 case Instruction::Sub: {
1326 unsigned NLZ = DemandedMask.countl_zero();
1327 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1328
1329 // If an operand subtracts zeros from every bit below the highest demanded
1330 // bit, that operand doesn't change the result. Return the other side.
1331 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1332 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1333 return I->getOperand(0);
1334
1335 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1336 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1337 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1338 Known = KnownBits::sub(LHSKnown, RHSKnown, NSW, NUW);
1340 break;
1341 }
1342 case Instruction::AShr: {
1343 // Compute the Known bits to simplify things downstream.
1345
1346 // If this user is only demanding bits that we know, return the known
1347 // constant.
1348 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1349 return Constant::getIntegerValue(ITy, Known.One);
1350
1351 // If the right shift operand 0 is a result of a left shift by the same
1352 // amount, this is probably a zero/sign extension, which may be unnecessary,
1353 // if we do not demand any of the new sign bits. So, return the original
1354 // operand instead.
1355 const APInt *ShiftRC;
1356 const APInt *ShiftLC;
1357 Value *X;
1358 unsigned BitWidth = DemandedMask.getBitWidth();
1359 if (match(I,
1360 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1361 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1362 DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1363 BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1364 return X;
1365 }
1366
1367 break;
1368 }
1369 default:
1370 // Compute the Known bits to simplify things downstream.
1372
1373 // If this user is only demanding bits that we know, return the known
1374 // constant.
1375 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1376 return Constant::getIntegerValue(ITy, Known.One);
1377
1378 break;
1379 }
1380
1381 return nullptr;
1382}
1383
1384/// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1385/// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1386/// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1387/// of "C2-C1".
1388///
1389/// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1390/// ..., bn}, without considering the specific value X is holding.
1391/// This transformation is legal iff one of following conditions is hold:
1392/// 1) All the bit in S are 0, in this case E1 == E2.
1393/// 2) We don't care those bits in S, per the input DemandedMask.
1394/// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1395/// rest bits.
1396///
1397/// Currently we only test condition 2).
1398///
1399/// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1400/// not successful.
1402 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1403 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1404 if (!ShlOp1 || !ShrOp1)
1405 return nullptr; // No-op.
1406
1407 Value *VarX = Shr->getOperand(0);
1408 Type *Ty = VarX->getType();
1409 unsigned BitWidth = Ty->getScalarSizeInBits();
1410 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1411 return nullptr; // Undef.
1412
1413 unsigned ShlAmt = ShlOp1.getZExtValue();
1414 unsigned ShrAmt = ShrOp1.getZExtValue();
1415
1416 Known.One.clearAllBits();
1417 Known.Zero.setLowBits(ShlAmt - 1);
1418 Known.Zero &= DemandedMask;
1419
1420 APInt BitMask1(APInt::getAllOnes(BitWidth));
1421 APInt BitMask2(APInt::getAllOnes(BitWidth));
1422
1423 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1424 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1425 (BitMask1.ashr(ShrAmt) << ShlAmt);
1426
1427 if (ShrAmt <= ShlAmt) {
1428 BitMask2 <<= (ShlAmt - ShrAmt);
1429 } else {
1430 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1431 BitMask2.ashr(ShrAmt - ShlAmt);
1432 }
1433
1434 // Check if condition-2 (see the comment to this function) is satified.
1435 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1436 if (ShrAmt == ShlAmt)
1437 return VarX;
1438
1439 if (!Shr->hasOneUse())
1440 return nullptr;
1441
1442 BinaryOperator *New;
1443 if (ShrAmt < ShlAmt) {
1444 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1445 New = BinaryOperator::CreateShl(VarX, Amt);
1447 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1448 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1449 } else {
1450 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1451 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1452 BinaryOperator::CreateAShr(VarX, Amt);
1453 if (cast<BinaryOperator>(Shr)->isExact())
1454 New->setIsExact(true);
1455 }
1456
1457 return InsertNewInstWith(New, Shl->getIterator());
1458 }
1459
1460 return nullptr;
1461}
1462
1463/// Return true if the top-level all-lanes demanded-elements query can be
1464/// skipped for an intermediate insertelement chain node. This is limited to a
1465/// bounded one-use chain with distinct in-range constant indices, where SDVE
1466/// cannot remove a dead insert before hitting its depth limit.
1468 unsigned VWidth,
1469 unsigned DepthLimit) {
1470 // Only skip chain nodes that feed another insertelement; the final chain root
1471 // still runs the full query.
1472 if (!IE.hasOneUse())
1473 return false;
1474 auto *UserIE = dyn_cast<InsertElementInst>(IE.user_back());
1475 if (!UserIE || UserIE->getOperand(0) != &IE)
1476 return false;
1477
1478 SmallBitVector SeenIndices(VWidth);
1479 auto HasNewIndexInRange = [&](InsertElementInst &Insert) {
1480 auto *Idx = dyn_cast<ConstantInt>(Insert.getOperand(2));
1481 // Let the normal SDVE path handle variable or out-of-range indices. The
1482 // latter may simplify the chain and must not be passed to getZExtValue().
1483 if (!Idx || Idx->getValue().uge(VWidth))
1484 return false;
1485
1486 unsigned Index = Idx->getZExtValue();
1487 if (SeenIndices.test(Index))
1488 return false;
1489
1490 SeenIndices.set(Index);
1491 return true;
1492 };
1493
1494 auto *Cur = &IE;
1495 for (unsigned I = 0; I != DepthLimit; ++I) {
1496 // This loop scans the same base-chain window that the SDVE query would
1497 // inspect before hitting its depth limit. With distinct insert indices in
1498 // that window, the all-lanes query cannot remove a dead insert; with
1499 // VWidth > DepthLimit, it also cannot narrow demand to a single lane.
1500 if (!HasNewIndexInRange(*Cur))
1501 return false;
1502
1503 Value *Base = Cur->getOperand(0);
1504 if (match(Base, m_Poison()))
1505 return true;
1506
1508 if (!Cur || !Cur->hasOneUse())
1509 return false;
1510 }
1511
1512 return true;
1513}
1514
1515/// The specified value produces a vector with any number of elements.
1516/// This method analyzes which elements of the operand are poison and
1517/// returns that information in PoisonElts.
1518///
1519/// DemandedElts contains the set of elements that are actually used by the
1520/// caller, and by default (AllowMultipleUsers equals false) the value is
1521/// simplified only if it has a single caller. If AllowMultipleUsers is set
1522/// to true, DemandedElts refers to the union of sets of elements that are
1523/// used by all callers.
1524///
1525/// If the information about demanded elements can be used to simplify the
1526/// operation, the operation is simplified, then the resultant value is
1527/// returned. This returns null if no change was made.
1529 APInt DemandedElts,
1530 APInt &PoisonElts,
1531 unsigned Depth,
1532 bool AllowMultipleUsers) {
1533 // Cannot analyze scalable type. The number of vector elements is not a
1534 // compile-time constant.
1535 if (isa<ScalableVectorType>(V->getType()))
1536 return nullptr;
1537
1538 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1539 APInt EltMask(APInt::getAllOnes(VWidth));
1540 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1541
1542 if (match(V, m_Poison())) {
1543 // If the entire vector is poison, just return this info.
1544 PoisonElts = EltMask;
1545 return nullptr;
1546 }
1547
1548 if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1549 PoisonElts = EltMask;
1550 return PoisonValue::get(V->getType());
1551 }
1552
1553 PoisonElts = 0;
1554
1555 if (auto *C = dyn_cast<Constant>(V)) {
1556 // Check if this is identity. If so, return 0 since we are not simplifying
1557 // anything.
1558 if (DemandedElts.isAllOnes())
1559 return nullptr;
1560
1561 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1564 for (unsigned i = 0; i != VWidth; ++i) {
1565 if (!DemandedElts[i]) { // If not demanded, set to poison.
1566 Elts.push_back(Poison);
1567 PoisonElts.setBit(i);
1568 continue;
1569 }
1570
1571 Constant *Elt = C->getAggregateElement(i);
1572 if (!Elt) return nullptr;
1573
1574 Elts.push_back(Elt);
1575 if (isa<PoisonValue>(Elt)) // Already poison.
1576 PoisonElts.setBit(i);
1577 }
1578
1579 // If we changed the constant, return it.
1580 Constant *NewCV = ConstantVector::get(Elts);
1581 return NewCV != C ? NewCV : nullptr;
1582 }
1583
1584 // Limit search depth.
1586 return nullptr;
1587
1588 if (!AllowMultipleUsers) {
1589 // If multiple users are using the root value, proceed with
1590 // simplification conservatively assuming that all elements
1591 // are needed.
1592 if (!V->hasOneUse()) {
1593 // Quit if we find multiple users of a non-root value though.
1594 // They'll be handled when it's their turn to be visited by
1595 // the main instcombine process.
1596 if (Depth != 0)
1597 // TODO: Just compute the PoisonElts information recursively.
1598 return nullptr;
1599
1600 // Conservatively assume that all elements are needed.
1601 DemandedElts = EltMask;
1602 }
1603 }
1604
1606 if (!I) return nullptr; // Only analyze instructions.
1607
1608 bool MadeChange = false;
1609 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1610 APInt Demanded, APInt &Undef) {
1611 auto *II = dyn_cast<IntrinsicInst>(Inst);
1612 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1613 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1614 replaceOperand(*Inst, OpNum, V);
1615 MadeChange = true;
1616 }
1617 };
1618
1619 APInt PoisonElts2(VWidth, 0);
1620 APInt PoisonElts3(VWidth, 0);
1621 switch (I->getOpcode()) {
1622 default: break;
1623
1624 case Instruction::GetElementPtr: {
1625 // The LangRef requires that struct geps have all constant indices. As
1626 // such, we can't convert any operand to partial undef.
1627 auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1628 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1629 I != E; I++)
1630 if (I.isStruct())
1631 return true;
1632 return false;
1633 };
1634 if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1635 break;
1636
1637 // Conservatively track the demanded elements back through any vector
1638 // operands we may have. We know there must be at least one, or we
1639 // wouldn't have a vector result to get here. Note that we intentionally
1640 // merge the undef bits here since gepping with either an poison base or
1641 // index results in poison.
1642 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1643 if (i == 0 ? match(I->getOperand(i), m_Undef())
1644 : match(I->getOperand(i), m_Poison())) {
1645 // If the entire vector is undefined, just return this info.
1646 PoisonElts = EltMask;
1647 return nullptr;
1648 }
1649 if (I->getOperand(i)->getType()->isVectorTy()) {
1650 APInt PoisonEltsOp(VWidth, 0);
1651 simplifyAndSetOp(I, i, DemandedElts, PoisonEltsOp);
1652 // gep(x, undef) is not undef, so skip considering idx ops here
1653 // Note that we could propagate poison, but we can't distinguish between
1654 // undef & poison bits ATM
1655 if (i == 0)
1656 PoisonElts |= PoisonEltsOp;
1657 }
1658 }
1659
1660 break;
1661 }
1662 case Instruction::InsertElement: {
1663 unsigned DepthLimit = SimplifyDemandedVectorEltsDepthLimit;
1664 auto *IE = cast<InsertElementInst>(I);
1665 // Skip only when SDVE cannot simplify this insert chain before the limit.
1666 if (Depth == 0 && DemandedElts.isAllOnes() && VWidth > DepthLimit &&
1667 canSkipDemandedEltsInInsertChain(*IE, VWidth, DepthLimit))
1668 return nullptr;
1669
1670 // If this is a variable index, we don't know which element it overwrites.
1671 // demand exactly the same input as we produce.
1672 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1673 if (!Idx) {
1674 // Note that we can't propagate undef elt info, because we don't know
1675 // which elt is getting updated.
1676 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts2);
1677 break;
1678 }
1679
1680 // The element inserted overwrites whatever was there, so the input demanded
1681 // set is simpler than the output set.
1682 unsigned IdxNo = Idx->getZExtValue();
1683 APInt PreInsertDemandedElts = DemandedElts;
1684 if (IdxNo < VWidth)
1685 PreInsertDemandedElts.clearBit(IdxNo);
1686
1687 // If we only demand the element that is being inserted and that element
1688 // was extracted from the same index in another vector with the same type,
1689 // replace this insert with that other vector.
1690 // Note: This is attempted before the call to simplifyAndSetOp because that
1691 // may change PoisonElts to a value that does not match with Vec.
1692 Value *Vec;
1693 if (PreInsertDemandedElts == 0 &&
1694 match(I->getOperand(1),
1695 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1696 Vec->getType() == I->getType()) {
1697 return Vec;
1698 }
1699
1700 simplifyAndSetOp(I, 0, PreInsertDemandedElts, PoisonElts);
1701
1702 // If this is inserting an element that isn't demanded, remove this
1703 // insertelement.
1704 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1705 Worklist.push(I);
1706 return I->getOperand(0);
1707 }
1708
1709 // The inserted element is defined.
1710 PoisonElts.clearBit(IdxNo);
1711 break;
1712 }
1713 case Instruction::ShuffleVector: {
1714 auto *Shuffle = cast<ShuffleVectorInst>(I);
1715 assert(Shuffle->getOperand(0)->getType() ==
1716 Shuffle->getOperand(1)->getType() &&
1717 "Expected shuffle operands to have same type");
1718 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1719 ->getNumElements();
1720 // Handle trivial case of a splat. Only check the first element of LHS
1721 // operand.
1722 if (all_of(Shuffle->getShuffleMask(), equal_to(0)) &&
1723 DemandedElts.isAllOnes()) {
1724 if (!isa<PoisonValue>(I->getOperand(1))) {
1725 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1726 MadeChange = true;
1727 }
1728 APInt LeftDemanded(OpWidth, 1);
1729 APInt LHSPoisonElts(OpWidth, 0);
1730 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1731 if (LHSPoisonElts[0])
1732 PoisonElts = EltMask;
1733 else
1734 PoisonElts.clearAllBits();
1735 break;
1736 }
1737
1738 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1739 for (unsigned i = 0; i < VWidth; i++) {
1740 if (DemandedElts[i]) {
1741 unsigned MaskVal = Shuffle->getMaskValue(i);
1742 if (MaskVal != -1u) {
1743 assert(MaskVal < OpWidth * 2 &&
1744 "shufflevector mask index out of range!");
1745 if (MaskVal < OpWidth)
1746 LeftDemanded.setBit(MaskVal);
1747 else
1748 RightDemanded.setBit(MaskVal - OpWidth);
1749 }
1750 }
1751 }
1752
1753 APInt LHSPoisonElts(OpWidth, 0);
1754 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1755
1756 APInt RHSPoisonElts(OpWidth, 0);
1757 simplifyAndSetOp(I, 1, RightDemanded, RHSPoisonElts);
1758
1759 // If this shuffle does not change the vector length and the elements
1760 // demanded by this shuffle are an identity mask, then this shuffle is
1761 // unnecessary.
1762 //
1763 // We are assuming canonical form for the mask, so the source vector is
1764 // operand 0 and operand 1 is not used.
1765 //
1766 // Note that if an element is demanded and this shuffle mask is undefined
1767 // for that element, then the shuffle is not considered an identity
1768 // operation. The shuffle prevents poison from the operand vector from
1769 // leaking to the result by replacing poison with an undefined value.
1770 if (VWidth == OpWidth) {
1771 bool IsIdentityShuffle = true;
1772 for (unsigned i = 0; i < VWidth; i++) {
1773 unsigned MaskVal = Shuffle->getMaskValue(i);
1774 if (DemandedElts[i] && i != MaskVal) {
1775 IsIdentityShuffle = false;
1776 break;
1777 }
1778 }
1779 if (IsIdentityShuffle)
1780 return Shuffle->getOperand(0);
1781 }
1782
1783 bool NewPoisonElts = false;
1784 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1785 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1786 bool LHSUniform = true;
1787 bool RHSUniform = true;
1788 for (unsigned i = 0; i < VWidth; i++) {
1789 unsigned MaskVal = Shuffle->getMaskValue(i);
1790 if (MaskVal == -1u) {
1791 PoisonElts.setBit(i);
1792 } else if (!DemandedElts[i]) {
1793 NewPoisonElts = true;
1794 PoisonElts.setBit(i);
1795 } else if (MaskVal < OpWidth) {
1796 if (LHSPoisonElts[MaskVal]) {
1797 NewPoisonElts = true;
1798 PoisonElts.setBit(i);
1799 } else {
1800 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1801 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1802 LHSUniform = LHSUniform && (MaskVal == i);
1803 }
1804 } else {
1805 if (RHSPoisonElts[MaskVal - OpWidth]) {
1806 NewPoisonElts = true;
1807 PoisonElts.setBit(i);
1808 } else {
1809 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1810 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1811 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1812 }
1813 }
1814 }
1815
1816 // Try to transform shuffle with constant vector and single element from
1817 // this constant vector to single insertelement instruction.
1818 // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1819 // insertelement V, C[ci], ci-n
1820 if (OpWidth ==
1821 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1822 Value *Op = nullptr;
1823 Constant *Value = nullptr;
1824 unsigned Idx = -1u;
1825
1826 // Find constant vector with the single element in shuffle (LHS or RHS).
1827 if (LHSIdx < OpWidth && RHSUniform) {
1828 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1829 Op = Shuffle->getOperand(1);
1830 Value = CV->getOperand(LHSValIdx);
1831 Idx = LHSIdx;
1832 }
1833 }
1834 if (RHSIdx < OpWidth && LHSUniform) {
1835 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1836 Op = Shuffle->getOperand(0);
1837 Value = CV->getOperand(RHSValIdx);
1838 Idx = RHSIdx;
1839 }
1840 }
1841 // Found constant vector with single element - convert to insertelement.
1842 if (Op && Value) {
1844 Op, Value, ConstantInt::get(Type::getInt64Ty(I->getContext()), Idx),
1845 Shuffle->getName());
1846 InsertNewInstWith(New, Shuffle->getIterator());
1847 return New;
1848 }
1849 }
1850 if (NewPoisonElts) {
1851 // Add additional discovered undefs.
1853 for (unsigned i = 0; i < VWidth; ++i) {
1854 if (PoisonElts[i])
1856 else
1857 Elts.push_back(Shuffle->getMaskValue(i));
1858 }
1859 Shuffle->setShuffleMask(Elts);
1860 MadeChange = true;
1861 }
1862 break;
1863 }
1864 case Instruction::Select: {
1865 // If this is a vector select, try to transform the select condition based
1866 // on the current demanded elements.
1868 if (Sel->getCondition()->getType()->isVectorTy()) {
1869 // TODO: We are not doing anything with PoisonElts based on this call.
1870 // It is overwritten below based on the other select operands. If an
1871 // element of the select condition is known undef, then we are free to
1872 // choose the output value from either arm of the select. If we know that
1873 // one of those values is undef, then the output can be undef.
1874 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1875 }
1876
1877 // Next, see if we can transform the arms of the select.
1878 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1879 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1880 for (unsigned i = 0; i < VWidth; i++) {
1881 Constant *CElt = CV->getAggregateElement(i);
1882
1883 // isNullValue() always returns false when called on a ConstantExpr.
1884 if (CElt->isNullValue())
1885 DemandedLHS.clearBit(i);
1886 else if (CElt->isOneValue())
1887 DemandedRHS.clearBit(i);
1888 }
1889 }
1890
1891 simplifyAndSetOp(I, 1, DemandedLHS, PoisonElts2);
1892 simplifyAndSetOp(I, 2, DemandedRHS, PoisonElts3);
1893
1894 // Output elements are undefined if the element from each arm is undefined.
1895 // TODO: This can be improved. See comment in select condition handling.
1896 PoisonElts = PoisonElts2 & PoisonElts3;
1897 break;
1898 }
1899 case Instruction::BitCast: {
1900 // Vector->vector casts only.
1901 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1902 if (!VTy) break;
1903 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1904 APInt InputDemandedElts(InVWidth, 0);
1905 PoisonElts2 = APInt(InVWidth, 0);
1906 unsigned Ratio;
1907
1908 if (VWidth == InVWidth) {
1909 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1910 // elements as are demanded of us.
1911 Ratio = 1;
1912 InputDemandedElts = DemandedElts;
1913 } else if ((VWidth % InVWidth) == 0) {
1914 // If the number of elements in the output is a multiple of the number of
1915 // elements in the input then an input element is live if any of the
1916 // corresponding output elements are live.
1917 Ratio = VWidth / InVWidth;
1918 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1919 if (DemandedElts[OutIdx])
1920 InputDemandedElts.setBit(OutIdx / Ratio);
1921 } else if ((InVWidth % VWidth) == 0) {
1922 // If the number of elements in the input is a multiple of the number of
1923 // elements in the output then an input element is live if the
1924 // corresponding output element is live.
1925 Ratio = InVWidth / VWidth;
1926 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1927 if (DemandedElts[InIdx / Ratio])
1928 InputDemandedElts.setBit(InIdx);
1929 } else {
1930 // Unsupported so far.
1931 break;
1932 }
1933
1934 simplifyAndSetOp(I, 0, InputDemandedElts, PoisonElts2);
1935
1936 if (VWidth == InVWidth) {
1937 PoisonElts = PoisonElts2;
1938 } else if ((VWidth % InVWidth) == 0) {
1939 // If the number of elements in the output is a multiple of the number of
1940 // elements in the input then an output element is undef if the
1941 // corresponding input element is undef.
1942 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1943 if (PoisonElts2[OutIdx / Ratio])
1944 PoisonElts.setBit(OutIdx);
1945 } else if ((InVWidth % VWidth) == 0) {
1946 // If the number of elements in the input is a multiple of the number of
1947 // elements in the output then an output element is undef if all of the
1948 // corresponding input elements are undef.
1949 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1950 APInt SubUndef = PoisonElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1951 if (SubUndef.popcount() == Ratio)
1952 PoisonElts.setBit(OutIdx);
1953 }
1954 } else {
1955 llvm_unreachable("Unimp");
1956 }
1957 break;
1958 }
1959 case Instruction::FPTrunc:
1960 case Instruction::FPExt:
1961 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1962 break;
1963
1964 case Instruction::Call: {
1966 if (!II) break;
1967 switch (II->getIntrinsicID()) {
1968 case Intrinsic::masked_gather: // fallthrough
1969 case Intrinsic::masked_load: {
1970 // Subtlety: If we load from a pointer, the pointer must be valid
1971 // regardless of whether the element is demanded. Doing otherwise risks
1972 // segfaults which didn't exist in the original program.
1973 APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1974 DemandedPassThrough(DemandedElts);
1975 if (auto *CMask = dyn_cast<Constant>(II->getOperand(1))) {
1976 for (unsigned i = 0; i < VWidth; i++) {
1977 if (Constant *CElt = CMask->getAggregateElement(i)) {
1978 if (CElt->isNullValue())
1979 DemandedPtrs.clearBit(i);
1980 else if (CElt->isAllOnesValue())
1981 DemandedPassThrough.clearBit(i);
1982 }
1983 }
1984 }
1985
1986 if (II->getIntrinsicID() == Intrinsic::masked_gather)
1987 simplifyAndSetOp(II, 0, DemandedPtrs, PoisonElts2);
1988 simplifyAndSetOp(II, 2, DemandedPassThrough, PoisonElts3);
1989
1990 // Output elements are undefined if the element from both sources are.
1991 // TODO: can strengthen via mask as well.
1992 PoisonElts = PoisonElts2 & PoisonElts3;
1993 break;
1994 }
1995 default: {
1996 // Handle target specific intrinsics
1997 std::optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1998 *II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
1999 simplifyAndSetOp);
2000 if (V)
2001 return *V;
2002 break;
2003 }
2004 } // switch on IntrinsicID
2005 break;
2006 } // case Call
2007 } // switch on Opcode
2008
2009 // TODO: We bail completely on integer div/rem and shifts because they have
2010 // UB/poison potential, but that should be refined.
2011 BinaryOperator *BO;
2012 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
2013 Value *X = BO->getOperand(0);
2014 Value *Y = BO->getOperand(1);
2015
2016 // Look for an equivalent binop except that one operand has been shuffled.
2017 // If the demand for this binop only includes elements that are the same as
2018 // the other binop, then we may be able to replace this binop with a use of
2019 // the earlier one.
2020 //
2021 // Example:
2022 // %other_bo = bo (shuf X, {0}), Y
2023 // %this_extracted_bo = extelt (bo X, Y), 0
2024 // -->
2025 // %other_bo = bo (shuf X, {0}), Y
2026 // %this_extracted_bo = extelt %other_bo, 0
2027 //
2028 // TODO: Handle demand of an arbitrary single element or more than one
2029 // element instead of just element 0.
2030 // TODO: Unlike general demanded elements transforms, this should be safe
2031 // for any (div/rem/shift) opcode too.
2032 if (DemandedElts == 1 && !X->hasOneUse() && !Y->hasOneUse() &&
2033 BO->hasOneUse() ) {
2034
2035 auto findShufBO = [&](bool MatchShufAsOp0) -> User * {
2036 // Try to use shuffle-of-operand in place of an operand:
2037 // bo X, Y --> bo (shuf X), Y
2038 // bo X, Y --> bo X, (shuf Y)
2039
2040 Value *OtherOp = MatchShufAsOp0 ? Y : X;
2041 if (!OtherOp->hasUseList())
2042 return nullptr;
2043
2044 BinaryOperator::BinaryOps Opcode = BO->getOpcode();
2045 Value *ShufOp = MatchShufAsOp0 ? X : Y;
2046
2047 for (User *U : OtherOp->users()) {
2048 ArrayRef<int> Mask;
2049 auto Shuf = m_Shuffle(m_Specific(ShufOp), m_Value(), m_Mask(Mask));
2050 if (BO->isCommutative()
2051 ? match(U, m_c_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
2052 : MatchShufAsOp0
2053 ? match(U, m_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
2054 : match(U, m_BinOp(Opcode, m_Specific(OtherOp), Shuf)))
2055 if (match(Mask, m_ZeroMask()) && Mask[0] != PoisonMaskElem)
2056 if (DT.dominates(U, I))
2057 return U;
2058 }
2059 return nullptr;
2060 };
2061
2062 User *ShufBO = findShufBO(/* MatchShufAsOp0 */ true);
2063 if (!ShufBO)
2064 ShufBO = findShufBO(/* MatchShufAsOp0 */ false);
2065 if (ShufBO) {
2066 auto *ShufBOI = cast<Instruction>(ShufBO);
2067 ShufBOI->andIRFlags(BO);
2068 Worklist.add(ShufBOI);
2069 return ShufBO;
2070 }
2071 }
2072
2073 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
2074 simplifyAndSetOp(I, 1, DemandedElts, PoisonElts2);
2075
2076 // Output elements are undefined if both are undefined. Consider things
2077 // like undef & 0. The result is known zero, not undef.
2078 PoisonElts &= PoisonElts2;
2079 }
2080
2081 // If we've proven all of the lanes poison, return a poison value.
2082 // TODO: Intersect w/demanded lanes
2083 if (PoisonElts.isAllOnes())
2084 return PoisonValue::get(I->getType());
2085
2086 return MadeChange ? I : nullptr;
2087}
2088
2089/// For floating-point classes that resolve to a single bit pattern, return that
2090/// value.
2092 bool IsCanonicalizing = false) {
2093 if (Mask == fcNone)
2094 return PoisonValue::get(Ty);
2095
2096 if (Mask == fcPosZero)
2097 return Constant::getNullValue(Ty);
2098
2099 // TODO: Support aggregate types that are allowed by FPMathOperator.
2100 if (Ty->isAggregateType())
2101 return nullptr;
2102
2103 // Turn any possible snans into quiet if we can.
2104 if (Mask == fcNan && IsCanonicalizing)
2105 return ConstantFP::getQNaN(Ty);
2106
2107 switch (Mask) {
2108 case fcNegZero:
2109 return ConstantFP::getZero(Ty, true);
2110 case fcPosInf:
2111 return ConstantFP::getInfinity(Ty);
2112 case fcNegInf:
2113 return ConstantFP::getInfinity(Ty, true);
2114 case fcQNan:
2115 // Payload bits cannot be dropped for pure signbit operations.
2116 return IsCanonicalizing ? ConstantFP::getQNaN(Ty) : nullptr;
2117 default:
2118 return nullptr;
2119 }
2120}
2121
2122/// Perform multiple-use aware simplfications for fabs(\p Src). Returns a
2123/// replacement value if it's simplified, otherwise nullptr. Updates \p Known
2124/// with the known fpclass if not simplified.
2126 FPClassTest DemandedMask,
2127 KnownFPClass KnownSrc, bool NSZ) {
2128 if ((DemandedMask & fcNan) == fcNone)
2129 KnownSrc.knownNot(fcNan);
2130 if ((DemandedMask & fcInf) == fcNone)
2131 KnownSrc.knownNot(fcInf);
2132
2133 if (KnownSrc.SignBit == false ||
2134 ((DemandedMask & fcNan) == fcNone && KnownSrc.isKnownNever(fcNegative)))
2135 return Src;
2136
2137 // If the only sign bit difference is due to -0, ignore it with nsz
2138 if (NSZ &&
2140 return Src;
2141
2142 Known = KnownFPClass::fabs(KnownSrc);
2143 Known.knownNot(~DemandedMask);
2144 return nullptr;
2145}
2146
2147/// Try to set an inferred no-nans or no-infs in \p FMF. \p ValidResults is a
2148/// mask of known valid results for the operator (already computed from the
2149/// result, and the known operand inputs in \p Known)
2151 FPClassTest ValidResults,
2153 if (!FMF.noNaNs() && (ValidResults & fcNan) == fcNone) {
2154 if (all_of(Known, [](const KnownFPClass KnownSrc) {
2155 return KnownSrc.isKnownNeverNaN();
2156 }))
2157 FMF.setNoNaNs();
2158 }
2159
2160 if (!FMF.noInfs() && (ValidResults & fcInf) == fcNone) {
2161 if (all_of(Known, [](const KnownFPClass KnownSrc) {
2162 return KnownSrc.isKnownNeverInfinity();
2163 }))
2164 FMF.setNoInfs();
2165 }
2166
2167 return FMF;
2168}
2169
2171 FastMathFlags FMF) {
2172 if (FMF.noNaNs())
2173 DemandedMask &= ~fcNan;
2174
2175 if (FMF.noInfs())
2176 DemandedMask &= ~fcInf;
2177 return DemandedMask;
2178}
2179
2180/// Apply epilog fixups to a floating-point intrinsic. See if the result can
2181/// fold to a constant, or apply fast math flags.
2183 FastMathFlags FMF,
2184 FPClassTest DemandedMask,
2186 ArrayRef<KnownFPClass> KnownSrcs) {
2187 FPClassTest ValidResults = DemandedMask & Known.KnownFPClasses;
2188 Constant *SingleVal = getFPClassConstant(FPOp->getType(), ValidResults,
2189 /*IsCanonicalizing=*/true);
2190 if (SingleVal)
2191 return SingleVal;
2192
2193 FastMathFlags InferredFMF =
2194 inferFastMathValueFlags(FMF, ValidResults, KnownSrcs);
2195 if (InferredFMF != FMF) {
2197 FPOp->setFastMathFlags(InferredFMF);
2198 return FPOp;
2199 }
2200
2201 return nullptr;
2202}
2203
2204/// Perform multiple-use aware simplfications for fneg(fabs(\p Src)). Returns a
2205/// replacement value if it's simplified, otherwise nullptr. Updates \p Known
2206/// with the known fpclass if not simplified.
2208 FPClassTest DemandedMask,
2209 KnownFPClass KnownSrc, bool NSZ) {
2210 if ((DemandedMask & fcNan) == fcNone)
2211 KnownSrc.knownNot(fcNan);
2212 if ((DemandedMask & fcInf) == fcNone)
2213 KnownSrc.knownNot(fcInf);
2214
2215 // If the source value is known negative, we can directly fold to it.
2216 if (KnownSrc.SignBit == true)
2217 return Src;
2218
2219 // If the only sign bit difference is for 0, ignore it with nsz.
2220 if (NSZ &&
2222 return Src;
2223
2225 Known.knownNot(~DemandedMask);
2226 return nullptr;
2227}
2228
2230 FPClassTest DemandedMask,
2231 KnownFPClass KnownSrc,
2232 bool NSZ) {
2233 if (NSZ) {
2234 constexpr FPClassTest NegOrZero = fcNegative | fcPosZero;
2235 constexpr FPClassTest PosOrZero = fcPositive | fcNegZero;
2236
2237 if ((DemandedMask & ~NegOrZero) == fcNone &&
2238 KnownSrc.isKnownAlways(NegOrZero))
2239 return MagSrc;
2240
2241 if ((DemandedMask & ~PosOrZero) == fcNone &&
2242 KnownSrc.isKnownAlways(PosOrZero))
2243 return MagSrc;
2244 } else {
2245 if ((DemandedMask & ~fcNegative) == fcNone && KnownSrc.SignBit == true)
2246 return MagSrc;
2247
2248 if ((DemandedMask & ~fcPositive) == fcNone && KnownSrc.SignBit == false)
2249 return MagSrc;
2250 }
2251
2252 return nullptr;
2253}
2254
2255static Value *
2257 const CallInst *CI, FPClassTest DemandedMask,
2258 KnownFPClass KnownLHS, KnownFPClass KnownRHS,
2259 const Function &F, bool NSZ) {
2260 bool OrderedZeroSign = !NSZ;
2261
2263 switch (IID) {
2264 case Intrinsic::maximum: {
2266
2267 // If one operand is known greater than the other, it must be that
2268 // operand unless the other is a nan.
2270 KnownRHS.KnownFPClasses, OrderedZeroSign) &&
2271 KnownRHS.isKnownNever(fcNan))
2272 return CI->getArgOperand(0);
2273
2275 KnownRHS.KnownFPClasses, OrderedZeroSign) &&
2276 KnownLHS.isKnownNever(fcNan))
2277 return CI->getArgOperand(1);
2278
2279 break;
2280 }
2281 case Intrinsic::minimum: {
2283
2284 // If one operand is known less than the other, it must be that operand
2285 // unless the other is a nan.
2287 KnownRHS.KnownFPClasses, OrderedZeroSign) &&
2288 KnownRHS.isKnownNever(fcNan))
2289 return CI->getArgOperand(0);
2290
2292 KnownRHS.KnownFPClasses, OrderedZeroSign) &&
2293 KnownLHS.isKnownNever(fcNan))
2294 return CI->getArgOperand(1);
2295
2296 break;
2297 }
2298 case Intrinsic::maxnum:
2299 case Intrinsic::maximumnum: {
2300 OpKind = IID == Intrinsic::maxnum ? KnownFPClass::MinMaxKind::maxnum
2302
2304 KnownRHS.KnownFPClasses, OrderedZeroSign) &&
2305 KnownLHS.isKnownNever(fcNan))
2306 return CI->getArgOperand(0);
2307
2309 KnownRHS.KnownFPClasses, OrderedZeroSign) &&
2310 KnownRHS.isKnownNever(fcNan))
2311 return CI->getArgOperand(1);
2312
2313 break;
2314 }
2315 case Intrinsic::minnum:
2316 case Intrinsic::minimumnum: {
2317 OpKind = IID == Intrinsic::minnum ? KnownFPClass::MinMaxKind::minnum
2319
2321 KnownRHS.KnownFPClasses, OrderedZeroSign) &&
2322 KnownLHS.isKnownNever(fcNan))
2323 return CI->getArgOperand(0);
2324
2326 KnownRHS.KnownFPClasses, OrderedZeroSign) &&
2327 KnownRHS.isKnownNever(fcNan))
2328 return CI->getArgOperand(1);
2329
2330 break;
2331 }
2332 default:
2333 llvm_unreachable("not a min/max intrinsic");
2334 }
2335
2336 Type *EltTy = CI->getType()->getScalarType();
2337 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2338 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, OpKind, Mode);
2339 Known.knownNot(~DemandedMask);
2340
2341 return getFPClassConstant(CI->getType(), Known.KnownFPClasses,
2342 /*IsCanonicalizing=*/true);
2343}
2344
2345static Value *
2347 FastMathFlags FMF, FPClassTest DemandedMask,
2348 KnownFPClass &Known, const SimplifyQuery &SQ,
2349 unsigned Depth) {
2350
2351 FPClassTest SrcDemandedMask = DemandedMask;
2352 if (DemandedMask & fcNan)
2353 SrcDemandedMask |= fcNan;
2354
2355 // Zero results may have been rounded from subnormal or normal sources.
2356 if (DemandedMask & fcNegZero)
2357 SrcDemandedMask |= fcNegSubnormal | fcNegNormal;
2358 if (DemandedMask & fcPosZero)
2359 SrcDemandedMask |= fcPosSubnormal | fcPosNormal;
2360
2361 // Subnormal results may have been normal in the source type
2362 if (DemandedMask & fcNegSubnormal)
2363 SrcDemandedMask |= fcNegNormal;
2364 if (DemandedMask & fcPosSubnormal)
2365 SrcDemandedMask |= fcPosNormal;
2366
2367 if (DemandedMask & fcPosInf)
2368 SrcDemandedMask |= fcPosNormal;
2369 if (DemandedMask & fcNegInf)
2370 SrcDemandedMask |= fcNegNormal;
2371
2372 KnownFPClass KnownSrc;
2373 if (IC.SimplifyDemandedFPClass(&I, 0, SrcDemandedMask, KnownSrc, SQ,
2374 Depth + 1))
2375 return &I;
2376
2377 Known = KnownFPClass::fptrunc(KnownSrc);
2378 Known.knownNot(~DemandedMask);
2379
2380 return simplifyDemandedFPClassResult(&I, FMF, DemandedMask, Known,
2381 {KnownSrc});
2382}
2383
2385 FPClassTest DemandedMask,
2387 const SimplifyQuery &SQ,
2388 unsigned Depth) {
2389 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2390 assert(Known == KnownFPClass() && "expected uninitialized state");
2391
2392 Type *VTy = I->getType();
2393
2394 FastMathFlags FMF;
2395 if (auto *FPOp = dyn_cast<FPMathOperator>(I)) {
2396 FMF = FPOp->getFastMathFlags();
2397 DemandedMask = adjustDemandedMaskFromFlags(DemandedMask, FMF);
2398 }
2399
2400 switch (I->getOpcode()) {
2401 case Instruction::FNeg: {
2402 // Special case fneg(fabs(x))
2403
2404 Value *FNegSrc = I->getOperand(0);
2405 Value *FNegFAbsSrc;
2406 if (match(FNegSrc, m_OneUse(m_FAbs(m_Value(FNegFAbsSrc))))) {
2407 KnownFPClass KnownSrc;
2409 llvm::unknown_sign(DemandedMask), KnownSrc,
2410 SQ, Depth + 1))
2411 return I;
2412
2413 FastMathFlags FabsFMF = cast<FPMathOperator>(FNegSrc)->getFastMathFlags();
2414 FPClassTest ThisDemandedMask =
2415 adjustDemandedMaskFromFlags(DemandedMask, FabsFMF);
2416
2417 bool IsNSZ = FMF.noSignedZeros() || FabsFMF.noSignedZeros();
2418 if (Value *Simplified = simplifyDemandedFPClassFnegFabs(
2419 Known, FNegFAbsSrc, ThisDemandedMask, KnownSrc, IsNSZ))
2420 return Simplified;
2421
2422 if ((ThisDemandedMask & fcNan) == fcNone)
2423 KnownSrc.knownNot(fcNan);
2424 if ((ThisDemandedMask & fcInf) == fcNone)
2425 KnownSrc.knownNot(fcInf);
2426
2427 // fneg(fabs(x)) => fneg(x)
2428 if (KnownSrc.SignBit == false)
2429 return replaceOperand(*I, 0, FNegFAbsSrc);
2430
2431 // fneg(fabs(x)) => fneg(x), ignoring -0 if nsz.
2432 if (IsNSZ &&
2434 return replaceOperand(*I, 0, FNegFAbsSrc);
2435
2436 break;
2437 }
2438
2439 if (SimplifyDemandedFPClass(I, 0, llvm::fneg(DemandedMask), Known, SQ,
2440 Depth + 1))
2441 return I;
2442 Known.fneg();
2443 Known.knownNot(~DemandedMask);
2444 break;
2445 }
2446 case Instruction::FAdd:
2447 case Instruction::FSub: {
2448 KnownFPClass KnownLHS, KnownRHS;
2449
2450 // fadd x, x can be handled more aggressively.
2451 if (I->getOperand(0) == I->getOperand(1) &&
2452 I->getOpcode() == Instruction::FAdd &&
2453 isGuaranteedNotToBeUndef(I->getOperand(0), SQ.AC, SQ.CxtI, SQ.DT,
2454 Depth + 1)) {
2455 Type *EltTy = VTy->getScalarType();
2456 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2457
2458 FPClassTest SrcDemandedMask = DemandedMask;
2459 if (DemandedMask & fcNan)
2460 SrcDemandedMask |= fcNan;
2461
2462 // Doubling a subnormal could have resulted in a normal value.
2463 if (DemandedMask & fcPosNormal)
2464 SrcDemandedMask |= fcPosSubnormal;
2465 if (DemandedMask & fcNegNormal)
2466 SrcDemandedMask |= fcNegSubnormal;
2467
2468 // Doubling a subnormal may produce 0 if FTZ/DAZ.
2469 if (Mode != DenormalMode::getIEEE()) {
2470 if (DemandedMask & fcPosZero) {
2471 SrcDemandedMask |= fcPosSubnormal;
2472
2473 if (Mode.inputsMayBePositiveZero() || Mode.outputsMayBePositiveZero())
2474 SrcDemandedMask |= fcNegSubnormal;
2475 }
2476
2477 if (DemandedMask & fcNegZero)
2478 SrcDemandedMask |= fcNegSubnormal;
2479 }
2480
2481 // Doubling a normal could have resulted in an infinity.
2482 if (DemandedMask & fcPosInf)
2483 SrcDemandedMask |= fcPosNormal;
2484 if (DemandedMask & fcNegInf)
2485 SrcDemandedMask |= fcNegNormal;
2486
2487 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownLHS, SQ,
2488 Depth + 1))
2489 return I;
2490
2491 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
2492 KnownRHS = KnownLHS;
2493 } else {
2494 FPClassTest SrcDemandedMask = fcFinite;
2495
2496 // inf + (-inf) = nan
2497 if (DemandedMask & fcNan)
2498 SrcDemandedMask |= fcNan | fcInf;
2499
2500 if (DemandedMask & fcInf)
2501 SrcDemandedMask |= fcInf;
2502
2503 if (SimplifyDemandedFPClass(I, 1, SrcDemandedMask, KnownRHS, SQ,
2504 Depth + 1) ||
2505 SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownLHS, SQ,
2506 Depth + 1))
2507 return I;
2508
2509 Type *EltTy = VTy->getScalarType();
2510 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2511
2512 Known = I->getOpcode() == Instruction::FAdd
2513 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
2514 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
2515 }
2516
2517 Known.knownNot(~DemandedMask);
2518
2519 if (Constant *SingleVal = getFPClassConstant(VTy, Known.KnownFPClasses,
2520 /*IsCanonicalizing=*/true))
2521 return SingleVal;
2522
2523 // Propagate known result to simplify edge case checks.
2524 bool ResultNotNan = (DemandedMask & fcNan) == fcNone;
2525
2526 // With nnan: X + {+/-}Inf --> {+/-}Inf
2527 if (ResultNotNan && I->getOpcode() == Instruction::FAdd &&
2528 KnownRHS.isKnownAlways(fcInf | fcNan) && KnownLHS.isKnownNever(fcNan))
2529 return I->getOperand(1);
2530
2531 // With nnan: {+/-}Inf + X --> {+/-}Inf
2532 // With nnan: {+/-}Inf - X --> {+/-}Inf
2533 if (ResultNotNan && KnownLHS.isKnownAlways(fcInf | fcNan) &&
2534 KnownRHS.isKnownNever(fcNan))
2535 return I->getOperand(0);
2536
2538 FMF, Known.KnownFPClasses, {KnownLHS, KnownRHS});
2539 if (InferredFMF != FMF) {
2540 I->setFastMathFlags(InferredFMF);
2541 return I;
2542 }
2543
2544 return nullptr;
2545 }
2546 case Instruction::FMul: {
2547 KnownFPClass KnownLHS, KnownRHS;
2548
2549 Value *X = I->getOperand(0);
2550 Value *Y = I->getOperand(1);
2551
2552 FPClassTest SrcDemandedMask =
2553 DemandedMask & (fcNan | fcZero | fcSubnormal | fcNormal);
2554
2555 if (DemandedMask & fcInf) {
2556 // mul x, inf = inf
2557 // mul large_x, large_y = inf
2558 SrcDemandedMask |= fcSubnormal | fcNormal | fcInf;
2559 }
2560
2561 if (DemandedMask & fcNan) {
2562 // mul +/-inf, 0 => nan
2563 SrcDemandedMask |= fcZero | fcInf | fcNan;
2564
2565 // TODO: Mode check
2566 // mul +/-inf, sub => nan if daz
2567 SrcDemandedMask |= fcSubnormal;
2568 }
2569
2570 // mul normal, subnormal = normal
2571 // Normal inputs may result in underflow.
2572 if (DemandedMask & (fcNormal | fcSubnormal))
2573 SrcDemandedMask |= fcNormal | fcSubnormal;
2574
2575 if (DemandedMask & fcZero)
2576 SrcDemandedMask |= fcNormal | fcSubnormal;
2577
2578 if (X == Y &&
2579 isGuaranteedNotToBeUndef(X, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1)) {
2580 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownLHS, SQ,
2581 Depth + 1))
2582 return I;
2583 Type *EltTy = VTy->getScalarType();
2584
2585 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2586 Known = KnownFPClass::square(KnownLHS, Mode);
2587 Known.knownNot(~DemandedMask);
2588
2589 if (Constant *Folded = getFPClassConstant(VTy, Known.KnownFPClasses,
2590 /*IsCanonicalizing=*/true))
2591 return Folded;
2592
2593 if (Known.isKnownAlways(fcPosZero | fcPosInf | fcNan) &&
2594 KnownLHS.isKnownNever(fcSubnormal | fcNormal)) {
2595 // We can skip the fabs if the source was already known positive.
2596 if (KnownLHS.isKnownAlways(fcPositive))
2597 return X;
2598
2599 // => fabs(x), in case this was a -inf or -0.
2600 // Note: Dropping canonicalize.
2602 Builder.SetInsertPoint(I);
2603 Value *Fabs = Builder.CreateFAbs(X, FMF);
2604 Fabs->takeName(I);
2605 return Fabs;
2606 }
2607
2608 return nullptr;
2609 }
2610
2611 if (SimplifyDemandedFPClass(I, 1, SrcDemandedMask, KnownRHS, SQ,
2612 Depth + 1) ||
2613 SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownLHS, SQ, Depth + 1))
2614 return I;
2615
2616 if (FMF.noInfs()) {
2617 // Flag implies inputs cannot be infinity.
2618 KnownLHS.knownNot(fcInf);
2619 KnownRHS.knownNot(fcInf);
2620 }
2621
2622 bool NonNanResult = (DemandedMask & fcNan) == fcNone;
2623
2624 // With no-nans/no-infs:
2625 // X * 0.0 --> copysign(0.0, X)
2626 // X * -0.0 --> copysign(0.0, -X)
2627 if ((NonNanResult || KnownLHS.isKnownNeverInfOrNaN()) &&
2628 KnownRHS.isKnownAlways(fcPosZero | fcNan)) {
2630 Builder.SetInsertPoint(I);
2631
2632 // => copysign(+0, lhs)
2633 // Note: Dropping canonicalize
2634 Value *Copysign = Builder.CreateCopySign(Y, X, FMF);
2635 Copysign->takeName(I);
2636 return Copysign;
2637 }
2638
2639 if (KnownLHS.isKnownAlways(fcPosZero | fcNan) &&
2640 (NonNanResult || KnownRHS.isKnownNeverInfOrNaN())) {
2642 Builder.SetInsertPoint(I);
2643
2644 // => copysign(+0, rhs)
2645 // Note: Dropping canonicalize
2646 Value *Copysign = Builder.CreateCopySign(X, Y, FMF);
2647 Copysign->takeName(I);
2648 return Copysign;
2649 }
2650
2651 if ((NonNanResult || KnownLHS.isKnownNeverInfOrNaN()) &&
2652 KnownRHS.isKnownAlways(fcNegZero | fcNan)) {
2654 Builder.SetInsertPoint(I);
2655
2656 // => copysign(0, fneg(lhs))
2657 // Note: Dropping canonicalize
2658 Value *Copysign =
2659 Builder.CreateCopySign(Y, Builder.CreateFNegFMF(X, FMF), FMF);
2660 Copysign->takeName(I);
2661 return Copysign;
2662 }
2663
2664 if (KnownLHS.isKnownAlways(fcNegZero | fcNan) &&
2665 (NonNanResult || KnownRHS.isKnownNeverInfOrNaN())) {
2667 Builder.SetInsertPoint(I);
2668
2669 // => copysign(+0, fneg(rhs))
2670 // Note: Dropping canonicalize
2671 Value *Copysign =
2672 Builder.CreateCopySign(X, Builder.CreateFNegFMF(Y, FMF), FMF);
2673 Copysign->takeName(I);
2674 return Copysign;
2675 }
2676
2677 Type *EltTy = VTy->getScalarType();
2678 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2679
2680 if (KnownLHS.isKnownAlways(fcInf | fcNan) &&
2681 (KnownRHS.isKnownNeverNaN() &&
2682 KnownRHS.cannotBeOrderedGreaterEqZero(Mode))) {
2684 Builder.SetInsertPoint(I);
2685
2686 // Note: Dropping canonicalize
2687 Value *Neg = Builder.CreateFNegFMF(X, FMF);
2688 Neg->takeName(I);
2689 return Neg;
2690 }
2691
2692 if (KnownRHS.isKnownAlways(fcInf | fcNan) &&
2693 (KnownLHS.isKnownNeverNaN() &&
2694 KnownLHS.cannotBeOrderedGreaterEqZero(Mode))) {
2696 Builder.SetInsertPoint(I);
2697
2698 // Note: Dropping canonicalize
2699 Value *Neg = Builder.CreateFNegFMF(Y, FMF);
2700 Neg->takeName(I);
2701 return Neg;
2702 }
2703
2704 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
2705 Known.knownNot(~DemandedMask);
2706
2707 if (Constant *SingleVal = getFPClassConstant(VTy, Known.KnownFPClasses,
2708 /*IsCanonicalizing=*/true))
2709 return SingleVal;
2710
2712 FMF, Known.KnownFPClasses, {KnownLHS, KnownRHS});
2713 if (InferredFMF != FMF) {
2714 I->setFastMathFlags(InferredFMF);
2715 return I;
2716 }
2717
2718 return nullptr;
2719 }
2720 case Instruction::FDiv: {
2721 Value *X = I->getOperand(0);
2722 Value *Y = I->getOperand(1);
2723 if (X == Y &&
2724 isGuaranteedNotToBeUndef(X, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1)) {
2725 // If the source is 0, inf or nan, the result is a nan
2727 Builder.SetInsertPoint(I);
2728
2729 Value *IsZeroOrNan = Builder.CreateFCmpFMF(
2730 FCmpInst::FCMP_UEQ, I->getOperand(0), ConstantFP::getZero(VTy), FMF);
2731
2732 Value *Fabs = Builder.CreateFAbs(I->getOperand(0), FMF);
2733 Value *IsInfOrNan = Builder.CreateFCmpFMF(
2735
2736 Value *IsInfOrZeroOrNan = Builder.CreateOr(IsInfOrNan, IsZeroOrNan);
2737
2738 return Builder.CreateSelectFMFWithUnknownProfile(
2739 IsInfOrZeroOrNan, ConstantFP::getQNaN(VTy),
2740 ConstantFP::get(
2742 FMF, DEBUG_TYPE);
2743 }
2744
2745 Type *EltTy = VTy->getScalarType();
2746 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2747
2748 // Every output class could require denormal inputs (except for the
2749 // degenerate case of only-nan results, without DAZ).
2750 FPClassTest SrcDemandedMask = (DemandedMask & fcNan) | fcSubnormal;
2751
2752 // Normal inputs may result in underflow.
2753 // x / x = 1.0 for non0/inf/nan
2754 // -x = +y / -z
2755 // -x = -y / +z
2756 if (DemandedMask & (fcSubnormal | fcNormal))
2757 SrcDemandedMask |= fcNormal;
2758
2759 if (DemandedMask & fcNan) {
2760 // 0 / 0 = nan
2761 // inf / inf = nan
2762
2763 // Subnormal is added in case of DAZ, but this isn't strictly
2764 // necessary. Every other input class implies a possible subnormal source,
2765 // so this only could matter in the degenerate case of only-nan results.
2766 SrcDemandedMask |= fcZero | fcInf | fcNan;
2767 }
2768
2769 // Zero outputs may be the result of underflow.
2770 if (DemandedMask & fcZero)
2771 SrcDemandedMask |= fcNormal | fcSubnormal;
2772
2773 FPClassTest LHSDemandedMask = SrcDemandedMask;
2774 FPClassTest RHSDemandedMask = SrcDemandedMask;
2775
2776 // 0 / inf = 0
2777 if (DemandedMask & fcZero) {
2778 assert((LHSDemandedMask & fcSubnormal) &&
2779 "should not have to worry about daz here");
2780 LHSDemandedMask |= fcZero;
2781 RHSDemandedMask |= fcInf;
2782 }
2783
2784 // x / 0 = inf
2785 // large_normal / small_normal = inf
2786 // inf / 1 = inf
2787 // large_normal / subnormal = inf
2788 if (DemandedMask & fcInf) {
2789 LHSDemandedMask |= fcInf | fcNormal | fcSubnormal;
2790 RHSDemandedMask |= fcZero | fcSubnormal | fcNormal;
2791 }
2792
2793 KnownFPClass KnownLHS, KnownRHS;
2794 if (SimplifyDemandedFPClass(I, 0, LHSDemandedMask, KnownLHS, SQ,
2795 Depth + 1) ||
2796 SimplifyDemandedFPClass(I, 1, RHSDemandedMask, KnownRHS, SQ, Depth + 1))
2797 return I;
2798
2799 // nsz [+-]0 / x -> 0
2800 if (FMF.noSignedZeros() && KnownLHS.isKnownAlways(fcZero) &&
2801 KnownRHS.isKnownNeverNaN())
2802 return ConstantFP::getZero(VTy);
2803
2804 if (KnownLHS.isKnownAlways(fcPosZero) && KnownRHS.isKnownNeverNaN()) {
2806 Builder.SetInsertPoint(I);
2807
2808 // nnan +0 / x -> copysign(0, rhs)
2809 // TODO: -0 / x => copysign(0, fneg(rhs))
2810 Value *Copysign = Builder.CreateCopySign(X, Y, FMF);
2811 Copysign->takeName(I);
2812 return Copysign;
2813 }
2814
2815 bool ResultNotNan = (DemandedMask & fcNan) == fcNone;
2816 bool ResultNotInf = (DemandedMask & fcInf) == fcNone;
2817
2818 if (!ResultNotInf &&
2819 ((ResultNotNan || (KnownLHS.isKnownNeverNaN() &&
2820 KnownLHS.isKnownNeverLogicalZero(Mode))) &&
2821 (KnownRHS.isKnownAlways(fcPosZero) ||
2822 (FMF.noSignedZeros() && KnownRHS.isKnownAlways(fcZero))))) {
2824 Builder.SetInsertPoint(I);
2825
2826 // nnan x / 0 => copysign(inf, x);
2827 // nnan nsz x / -0 => copysign(inf, x);
2828 Value *Copysign =
2829 Builder.CreateCopySign(ConstantFP::getInfinity(VTy), X, FMF);
2830 Copysign->takeName(I);
2831 return Copysign;
2832 }
2833
2834 // nnan ninf X / [-]0.0 -> poison
2835 if (ResultNotNan && ResultNotInf && KnownRHS.isKnownAlways(fcZero))
2836 return PoisonValue::get(VTy);
2837
2838 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
2839 Known.knownNot(~DemandedMask);
2840
2841 if (Constant *SingleVal = getFPClassConstant(VTy, Known.KnownFPClasses,
2842 /*IsCanonicalizing=*/true))
2843 return SingleVal;
2844
2846 FMF, Known.KnownFPClasses, {KnownLHS, KnownRHS});
2847 if (InferredFMF != FMF) {
2848 I->setFastMathFlags(InferredFMF);
2849 return I;
2850 }
2851
2852 return nullptr;
2853 }
2854 case Instruction::FPTrunc:
2855 return simplifyDemandedUseFPClassFPTrunc(*this, *I, FMF, DemandedMask,
2856 Known, SQ, Depth);
2857 case Instruction::FPExt: {
2858 FPClassTest SrcDemandedMask = DemandedMask;
2859 if (DemandedMask & fcNan)
2860 SrcDemandedMask |= fcNan;
2861
2862 // No subnormal result does not imply not-subnormal in the source type.
2863 if ((DemandedMask & fcNegNormal) != fcNone)
2864 SrcDemandedMask |= fcNegSubnormal;
2865 if ((DemandedMask & fcPosNormal) != fcNone)
2866 SrcDemandedMask |= fcPosSubnormal;
2867
2868 KnownFPClass KnownSrc;
2869 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownSrc, SQ, Depth + 1))
2870 return I;
2871
2872 const fltSemantics &DstTy = VTy->getScalarType()->getFltSemantics();
2873 const fltSemantics &SrcTy =
2874 I->getOperand(0)->getType()->getScalarType()->getFltSemantics();
2875
2876 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
2877 Known.knownNot(~DemandedMask);
2878
2879 return simplifyDemandedFPClassResult(I, FMF, DemandedMask, Known,
2880 {KnownSrc});
2881 }
2882 case Instruction::Call: {
2883 CallInst *CI = cast<CallInst>(I);
2884 const Intrinsic::ID IID = CI->getIntrinsicID();
2885 switch (IID) {
2886 case Intrinsic::fabs: {
2887 KnownFPClass KnownSrc;
2888 if (SimplifyDemandedFPClass(I, 0, llvm::inverse_fabs(DemandedMask),
2889 KnownSrc, SQ, Depth + 1))
2890 return I;
2891
2892 if (Value *Simplified = simplifyDemandedFPClassFabs(
2893 Known, CI->getArgOperand(0), DemandedMask, KnownSrc,
2894 FMF.noSignedZeros()))
2895 return Simplified;
2896 break;
2897 }
2898 case Intrinsic::arithmetic_fence:
2899 if (SimplifyDemandedFPClass(I, 0, DemandedMask, Known, SQ, Depth + 1))
2900 return I;
2901 break;
2902 case Intrinsic::copysign: {
2903 // Flip on more potentially demanded classes
2904 const FPClassTest DemandedMaskAnySign = llvm::unknown_sign(DemandedMask);
2905 KnownFPClass KnownMag;
2906 if (SimplifyDemandedFPClass(CI, 0, DemandedMaskAnySign, KnownMag, SQ,
2907 Depth + 1))
2908 return I;
2909
2910 if ((DemandedMask & fcNegative) == DemandedMask) {
2911 // Roundabout way of replacing with fneg(fabs)
2912 CI->setOperand(1, ConstantFP::get(VTy, -1.0));
2913 return I;
2914 }
2915
2916 if ((DemandedMask & fcPositive) == DemandedMask) {
2917 // Roundabout way of replacing with fabs
2918 CI->setOperand(1, ConstantFP::getZero(VTy));
2919 return I;
2920 }
2921
2922 if (Value *Simplified = simplifyDemandedFPClassCopysignMag(
2923 CI->getArgOperand(0), DemandedMask, KnownMag,
2924 FMF.noSignedZeros()))
2925 return Simplified;
2926
2927 KnownFPClass KnownSign =
2929 if (KnownMag.SignBit && KnownSign.SignBit &&
2930 *KnownMag.SignBit == *KnownSign.SignBit)
2931 return CI->getOperand(0);
2932
2933 // TODO: Call argument attribute not considered
2934 // Input implied not-nan from flag.
2935 if (FMF.noNaNs())
2936 KnownSign.knownNot(fcNan);
2937
2938 if (KnownSign.SignBit == false) {
2940 CI->setOperand(1, ConstantFP::getZero(VTy));
2941 return I;
2942 }
2943
2944 if (KnownSign.SignBit == true) {
2946 CI->setOperand(1, ConstantFP::get(VTy, -1.0));
2947 return I;
2948 }
2949
2950 Known = KnownFPClass::copysign(KnownMag, KnownSign);
2951 Known.knownNot(~DemandedMask);
2952 break;
2953 }
2954 case Intrinsic::fma:
2955 case Intrinsic::fmuladd: {
2956 // We can't do any simplification on the source besides stripping out
2957 // unneeded nans.
2958 FPClassTest SrcDemandedMask = DemandedMask | ~fcNan;
2959 if (DemandedMask & fcNan)
2960 SrcDemandedMask |= fcNan;
2961
2962 KnownFPClass KnownSrc[3];
2963
2964 Type *EltTy = VTy->getScalarType();
2965 if (CI->getArgOperand(0) == CI->getArgOperand(1) &&
2966 isGuaranteedNotToBeUndef(CI->getArgOperand(0), SQ.AC, SQ.CxtI, SQ.DT,
2967 Depth + 1)) {
2968 if (SimplifyDemandedFPClass(CI, 0, SrcDemandedMask, KnownSrc[0], SQ,
2969 Depth + 1) ||
2970 SimplifyDemandedFPClass(CI, 2, SrcDemandedMask, KnownSrc[2], SQ,
2971 Depth + 1))
2972 return I;
2973
2974 KnownSrc[1] = KnownSrc[0];
2975 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2976 Known = KnownFPClass::fma_square(KnownSrc[0], KnownSrc[2], Mode);
2977 } else {
2978 for (int OpIdx = 0; OpIdx != 3; ++OpIdx) {
2979 if (SimplifyDemandedFPClass(CI, OpIdx, SrcDemandedMask,
2980 KnownSrc[OpIdx], SQ, Depth + 1))
2981 return CI;
2982 }
2983
2984 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2985 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
2986 }
2987
2988 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
2989 {KnownSrc});
2990 }
2991 case Intrinsic::maximum:
2992 case Intrinsic::minimum:
2993 case Intrinsic::maximumnum:
2994 case Intrinsic::minimumnum:
2995 case Intrinsic::maxnum:
2996 case Intrinsic::minnum: {
2997 const bool PropagateNaN =
2998 IID == Intrinsic::maximum || IID == Intrinsic::minimum;
2999
3000 // We can't tell much based on the demanded result without inspecting the
3001 // operands (e.g., a known-positive result could have been clamped), but
3002 // we can still prune known-nan inputs.
3003 FPClassTest SrcDemandedMask =
3004 PropagateNaN && ((DemandedMask & fcNan) == fcNone)
3005 ? DemandedMask | ~fcNan
3006 : fcAllFlags;
3007
3008 KnownFPClass KnownLHS, KnownRHS;
3009 if (SimplifyDemandedFPClass(CI, 1, SrcDemandedMask, KnownRHS, SQ,
3010 Depth + 1) ||
3011 SimplifyDemandedFPClass(CI, 0, SrcDemandedMask, KnownLHS, SQ,
3012 Depth + 1))
3013 return I;
3014
3015 Value *Simplified =
3016 simplifyDemandedFPClassMinMax(Known, IID, CI, DemandedMask, KnownLHS,
3017 KnownRHS, F, FMF.noSignedZeros());
3018 if (Simplified)
3019 return Simplified;
3020
3021 auto *FPOp = cast<FPMathOperator>(CI);
3022
3023 FPClassTest ValidResults = DemandedMask & Known.KnownFPClasses;
3024 FastMathFlags InferredFMF = FMF;
3025
3026 if (!FMF.noSignedZeros()) {
3027 // Add NSZ flag if we know the result will not be sensitive to the sign
3028 // of 0.
3029 FPClassTest ZeroMask = fcZero;
3030
3031 Type *EltTy = VTy->getScalarType();
3032 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3033 if (Mode != DenormalMode::getIEEE())
3034 ZeroMask |= fcSubnormal;
3035
3036 bool ResultNotLogical0 = (ValidResults & ZeroMask) == fcNone;
3037 if (ResultNotLogical0 || ((KnownLHS.isKnownNeverLogicalNegZero(Mode) ||
3038 KnownRHS.isKnownNeverLogicalPosZero(Mode)) &&
3039 (KnownLHS.isKnownNeverLogicalPosZero(Mode) ||
3040 KnownRHS.isKnownNeverLogicalNegZero(Mode))))
3041 InferredFMF.setNoSignedZeros(true);
3042 }
3043
3044 if (!FMF.noNaNs() &&
3045 ((PropagateNaN && (ValidResults & fcNan) == fcNone) ||
3046 (KnownLHS.isKnownNeverNaN() && KnownRHS.isKnownNeverNaN()))) {
3048 InferredFMF.setNoNaNs(true);
3049 }
3050
3051 if (InferredFMF != FMF) {
3052 CI->setFastMathFlags(InferredFMF);
3053 return FPOp;
3054 }
3055
3056 return nullptr;
3057 }
3058 case Intrinsic::exp:
3059 case Intrinsic::exp2:
3060 case Intrinsic::exp10: {
3061 if ((DemandedMask & fcPositive) == fcNone) {
3062 // Only returns positive values or nans.
3063 if ((DemandedMask & fcNan) == fcNone)
3064 return PoisonValue::get(VTy);
3065
3066 // Only need nan propagation.
3067 if ((DemandedMask & ~fcNan) == fcNone)
3068 return ConstantFP::getQNaN(VTy);
3069
3070 return CI->getArgOperand(0);
3071 }
3072
3073 FPClassTest SrcDemandedMask = DemandedMask & fcNan;
3074 if (DemandedMask & fcNan)
3075 SrcDemandedMask |= fcNan;
3076
3077 if (DemandedMask & fcZero) {
3078 // exp(-infinity) = 0
3079 SrcDemandedMask |= fcNegInf;
3080
3081 // exp(-largest_normal) = 0
3082 //
3083 // Negative numbers of sufficiently large magnitude underflow to 0. No
3084 // subnormal input has a 0 result.
3085 SrcDemandedMask |= fcNegNormal;
3086 }
3087
3088 if (DemandedMask & fcPosSubnormal) {
3089 // Negative numbers of sufficiently large magnitude underflow to 0. No
3090 // subnormal input has a 0 result.
3091 SrcDemandedMask |= fcNegNormal;
3092 }
3093
3094 if (DemandedMask & fcPosNormal) {
3095 // exp(0) = 1
3096 // exp(+/- smallest_normal) = 1
3097 // exp(+/- largest_denormal) = 1
3098 // exp(+/- smallest_denormal) = 1
3099 // exp(-1) = pos normal
3100 SrcDemandedMask |= fcNormal | fcSubnormal | fcZero;
3101 }
3102
3103 // exp(inf), exp(largest_normal) = inf
3104 if (DemandedMask & fcPosInf)
3105 SrcDemandedMask |= fcPosInf | fcPosNormal;
3106
3107 KnownFPClass KnownSrc;
3108
3109 // TODO: This could really make use of KnownFPClass of specific value
3110 // range, (i.e., close enough to 1)
3111 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownSrc, SQ,
3112 Depth + 1))
3113 return I;
3114
3115 // exp(+/-0) = 1
3116 if (KnownSrc.isKnownAlways(fcZero))
3117 return ConstantFP::get(VTy, 1.0);
3118
3119 // Only perform nan propagation.
3120 // Note: Dropping canonicalize / quiet of signaling nan.
3121 if (KnownSrc.isKnownAlways(fcNan))
3122 return CI->getArgOperand(0);
3123
3124 // exp(0 | nan) => x == 0.0 ? 1.0 : x
3125 if (KnownSrc.isKnownAlways(fcZero | fcNan)) {
3127 Builder.SetInsertPoint(CI);
3128
3129 // fadd +/-0, 1.0 => 1.0
3130 // fadd nan, 1.0 => nan
3131 return Builder.CreateFAddFMF(CI->getArgOperand(0),
3132 ConstantFP::get(VTy, 1.0), FMF);
3133 }
3134
3135 if (KnownSrc.isKnownAlways(fcInf | fcNan)) {
3136 // exp(-inf) = 0
3137 // exp(+inf) = +inf
3139 Builder.SetInsertPoint(CI);
3140
3141 // Note: Dropping canonicalize / quiet of signaling nan.
3142 Value *X = CI->getArgOperand(0);
3143 Value *IsPosInfOrNan = Builder.CreateFCmpFMF(
3145 // We do not know whether an infinity or a NaN is more likely here,
3146 // so mark the branch weights as unkown.
3147 Value *ZeroOrInf = Builder.CreateSelectFMFWithUnknownProfile(
3148 IsPosInfOrNan, X, ConstantFP::getZero(VTy), FMF, DEBUG_TYPE);
3149 return ZeroOrInf;
3150 }
3151
3152 Known = KnownFPClass::exp(KnownSrc);
3153 Known.knownNot(~DemandedMask);
3154
3155 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
3156 KnownSrc);
3157 }
3158 case Intrinsic::log:
3159 case Intrinsic::log2:
3160 case Intrinsic::log10: {
3161 FPClassTest DemandedSrcMask = DemandedMask & (fcNan | fcPosInf);
3162 if (DemandedMask & fcNan)
3163 DemandedSrcMask |= fcNan;
3164
3165 Type *EltTy = VTy->getScalarType();
3166 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3167
3168 // log(x < 0) = nan
3169 if (DemandedMask & fcNan)
3170 DemandedSrcMask |= (fcNegative & ~fcNegZero);
3171
3172 // log(0) = -inf
3173 if (DemandedMask & fcNegInf) {
3174 DemandedSrcMask |= fcZero;
3175
3176 // No value produces subnormal result.
3177 if (Mode.inputsMayBeZero())
3178 DemandedSrcMask |= fcSubnormal;
3179 }
3180
3181 if (DemandedMask & fcNormal)
3182 DemandedSrcMask |= fcNormal | fcSubnormal;
3183
3184 // log(1) = 0
3185 if (DemandedMask & fcZero)
3186 DemandedSrcMask |= fcPosNormal;
3187
3188 KnownFPClass KnownSrc;
3189 if (SimplifyDemandedFPClass(I, 0, DemandedSrcMask, KnownSrc, SQ,
3190 Depth + 1))
3191 return I;
3192
3193 Known = KnownFPClass::log(KnownSrc, Mode);
3194 Known.knownNot(~DemandedMask);
3195
3196 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
3197 KnownSrc);
3198 }
3199 case Intrinsic::sqrt: {
3200 FPClassTest DemandedSrcMask =
3201 DemandedMask & (fcNegZero | fcPositive | fcNan);
3202
3203 if (DemandedMask & fcNan)
3204 DemandedSrcMask |= fcNan | (fcNegative & ~fcNegZero);
3205
3206 // sqrt(max_subnormal) is a normal value
3207 if (DemandedMask & fcPosNormal)
3208 DemandedSrcMask |= fcPosSubnormal;
3209
3210 KnownFPClass KnownSrc;
3211 if (SimplifyDemandedFPClass(I, 0, DemandedSrcMask, KnownSrc, SQ,
3212 Depth + 1))
3213 return I;
3214
3215 // Infer the source cannot be negative if the result cannot be nan.
3216 if ((DemandedMask & fcNan) == fcNone)
3217 KnownSrc.knownNot((fcNegative & ~fcNegZero) | fcNan);
3218
3219 // Infer the source cannot be +inf if the result is not +nf
3220 if ((DemandedMask & fcPosInf) == fcNone)
3221 KnownSrc.knownNot(fcPosInf);
3222
3223 Type *EltTy = VTy->getScalarType();
3224 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3225
3226 // sqrt(-x) = nan, but be careful of negative subnormals flushed to 0.
3227 if (KnownSrc.isKnownNever(fcPositive) &&
3228 KnownSrc.isKnownNeverLogicalZero(Mode))
3229 return ConstantFP::getQNaN(VTy);
3230
3231 Known = KnownFPClass::sqrt(KnownSrc, Mode);
3232 Known.knownNot(~DemandedMask);
3233
3234 if (Known.KnownFPClasses == fcZero) {
3235 if (FMF.noSignedZeros())
3236 return ConstantFP::getZero(VTy);
3238 Builder.SetInsertPoint(CI);
3239
3240 Value *Copysign = Builder.CreateCopySign(ConstantFP::getZero(VTy),
3241 CI->getArgOperand(0), FMF);
3242 Copysign->takeName(CI);
3243 return Copysign;
3244 }
3245
3246 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
3247 {KnownSrc});
3248 }
3249 case Intrinsic::ldexp: {
3250 FPClassTest SrcDemandedMask = DemandedMask & fcInf;
3251 if (DemandedMask & fcNan)
3252 SrcDemandedMask |= fcNan;
3253
3254 if (DemandedMask & fcPosInf)
3255 SrcDemandedMask |= fcPosNormal | fcPosSubnormal;
3256 if (DemandedMask & fcNegInf)
3257 SrcDemandedMask |= fcNegNormal | fcNegSubnormal;
3258
3259 if (DemandedMask & (fcPosNormal | fcPosSubnormal))
3260 SrcDemandedMask |= fcPosNormal | fcPosSubnormal;
3261 if (DemandedMask & (fcNegNormal | fcNegSubnormal))
3262 SrcDemandedMask |= fcNegNormal | fcNegSubnormal;
3263
3264 if (DemandedMask & fcPosZero)
3265 SrcDemandedMask |= fcPosFinite;
3266 if (DemandedMask & fcNegZero)
3267 SrcDemandedMask |= fcNegFinite;
3268
3269 KnownFPClass KnownSrc;
3270 if (SimplifyDemandedFPClass(CI, 0, SrcDemandedMask, KnownSrc, SQ,
3271 Depth + 1))
3272 return CI;
3273
3274 Type *EltTy = VTy->getScalarType();
3275 const fltSemantics &FltSem = EltTy->getFltSemantics();
3276 DenormalMode Mode = F.getDenormalMode(FltSem);
3277
3278 KnownBits KnownExpBits =
3280
3281 Known = KnownFPClass::ldexp(KnownSrc, KnownExpBits, FltSem, Mode);
3282 Known.knownNot(~DemandedMask);
3283
3284 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
3285 {KnownSrc});
3286 }
3287 case Intrinsic::trunc:
3288 case Intrinsic::floor:
3289 case Intrinsic::ceil:
3290 case Intrinsic::rint:
3291 case Intrinsic::nearbyint:
3292 case Intrinsic::round:
3293 case Intrinsic::roundeven: {
3294 FPClassTest DemandedSrcMask = DemandedMask;
3295 if (DemandedMask & fcNan)
3296 DemandedSrcMask |= fcNan;
3297
3298 // Zero results imply valid subnormal sources.
3299 if (DemandedMask & fcNegZero)
3300 DemandedSrcMask |= fcNegSubnormal | fcNegNormal;
3301
3302 if (DemandedMask & fcPosZero)
3303 DemandedSrcMask |= fcPosSubnormal | fcPosNormal;
3304
3305 KnownFPClass KnownSrc;
3306 if (SimplifyDemandedFPClass(CI, 0, DemandedSrcMask, KnownSrc, SQ,
3307 Depth + 1))
3308 return I;
3309
3310 // Note: Possibly dropping snan quiet.
3311 if (KnownSrc.isKnownAlways(fcInf | fcNan | fcZero))
3312 return CI->getArgOperand(0);
3313
3314 bool IsRoundNearestOrTrunc =
3315 IID == Intrinsic::round || IID == Intrinsic::roundeven ||
3316 IID == Intrinsic::nearbyint || IID == Intrinsic::rint ||
3317 IID == Intrinsic::trunc;
3318
3319 // Ignore denormals-as-zero, as canonicalization is not mandated.
3320 if ((IID == Intrinsic::floor || IsRoundNearestOrTrunc) &&
3322 return ConstantFP::getZero(VTy);
3323
3324 if ((IID == Intrinsic::ceil || IsRoundNearestOrTrunc) &&
3326 return ConstantFP::getZero(VTy, true);
3327
3328 if (IID == Intrinsic::floor && KnownSrc.isKnownAlways(fcNegSubnormal))
3329 return ConstantFP::get(VTy, -1.0);
3330
3331 if (IID == Intrinsic::ceil && KnownSrc.isKnownAlways(fcPosSubnormal))
3332 return ConstantFP::get(VTy, 1.0);
3333
3335 KnownSrc, IID == Intrinsic::trunc,
3337
3338 Known.knownNot(~DemandedMask);
3339
3340 if (Constant *SingleVal = getFPClassConstant(VTy, Known.KnownFPClasses,
3341 /*IsCanonicalizing=*/true))
3342 return SingleVal;
3343
3344 if ((IID == Intrinsic::trunc || IsRoundNearestOrTrunc) &&
3345 KnownSrc.isKnownAlways(fcZero | fcSubnormal)) {
3347 Builder.SetInsertPoint(CI);
3348
3349 Value *Copysign = Builder.CreateCopySign(ConstantFP::getZero(VTy),
3350 CI->getArgOperand(0));
3351 Copysign->takeName(CI);
3352 return Copysign;
3353 }
3354
3355 FastMathFlags InferredFMF =
3356 inferFastMathValueFlags(FMF, Known.KnownFPClasses, KnownSrc);
3357 if (InferredFMF != FMF) {
3359 CI->setFastMathFlags(InferredFMF);
3360 return CI;
3361 }
3362
3363 return nullptr;
3364 }
3365 case Intrinsic::fptrunc_round:
3366 return simplifyDemandedUseFPClassFPTrunc(*this, *CI, FMF, DemandedMask,
3367 Known, SQ, Depth);
3368 case Intrinsic::canonicalize: {
3369 Type *EltTy = VTy->getScalarType();
3370
3371 // TODO: This could have more refined support for PositiveZero denormal
3372 // mode.
3373 if (EltTy->isIEEELikeFPTy()) {
3374 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3375
3376 FPClassTest SrcDemandedMask = DemandedMask;
3377
3378 // A demanded quiet nan result may have come from a signaling nan, so we
3379 // need to expand the demanded mask.
3380 if ((DemandedMask & fcQNan) != fcNone)
3381 SrcDemandedMask |= fcSNan;
3382
3383 if (Mode != DenormalMode::getIEEE()) {
3384 // Any zero results may have come from flushed denormals.
3385 if (DemandedMask & fcPosZero)
3386 SrcDemandedMask |= fcPosSubnormal;
3387 if (DemandedMask & fcNegZero)
3388 SrcDemandedMask |= fcNegSubnormal;
3389 }
3390
3391 if (Mode == DenormalMode::getPreserveSign()) {
3392 // If a denormal input will be flushed, and we don't need zeros, we
3393 // don't need denormals either.
3394 if ((DemandedMask & fcPosZero) == fcNone)
3395 SrcDemandedMask &= ~fcPosSubnormal;
3396
3397 if ((DemandedMask & fcNegZero) == fcNone)
3398 SrcDemandedMask &= ~fcNegSubnormal;
3399 }
3400
3401 KnownFPClass KnownSrc;
3402
3403 // Simplify upstream operations before trying to simplify this call.
3404 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownSrc, SQ,
3405 Depth + 1))
3406 return I;
3407
3408 // Perform the canonicalization to see if this folded to a constant.
3409 Known = KnownFPClass::canonicalize(KnownSrc, Mode);
3410 Known.knownNot(~DemandedMask);
3411
3412 if (Constant *SingleVal = getFPClassConstant(VTy, Known.KnownFPClasses))
3413 return SingleVal;
3414
3415 // For IEEE handling, there is only a bit change for nan inputs, so we
3416 // can drop it if we do not demand nan results or we know the input
3417 // isn't a nan.
3418 // Otherwise, we also need to avoid denormal inputs to drop the
3419 // canonicalize.
3420 if (KnownSrc.isKnownNeverNaN() && (Mode == DenormalMode::getIEEE() ||
3421 KnownSrc.isKnownNeverSubnormal()))
3422 return CI->getArgOperand(0);
3423
3424 FastMathFlags InferredFMF =
3425 inferFastMathValueFlags(FMF, Known.KnownFPClasses, KnownSrc);
3426 if (InferredFMF != FMF) {
3428 CI->setFastMathFlags(InferredFMF);
3429 return CI;
3430 }
3431
3432 return nullptr;
3433 }
3434
3435 [[fallthrough]];
3436 }
3437 default:
3438 Known = computeKnownFPClass(I, DemandedMask, SQ, Depth + 1);
3439 Known.knownNot(~DemandedMask);
3440 break;
3441 }
3442
3443 break;
3444 }
3445 case Instruction::Select: {
3446 KnownFPClass KnownLHS, KnownRHS;
3447 if (SimplifyDemandedFPClass(I, 2, DemandedMask, KnownRHS, SQ, Depth + 1) ||
3448 SimplifyDemandedFPClass(I, 1, DemandedMask, KnownLHS, SQ, Depth + 1))
3449 return I;
3450
3451 if (KnownLHS.isKnownNever(DemandedMask))
3452 return I->getOperand(2);
3453 if (KnownRHS.isKnownNever(DemandedMask))
3454 return I->getOperand(1);
3455
3456 adjustKnownFPClassForSelectArm(KnownLHS, I->getOperand(0), I->getOperand(1),
3457 /*Invert=*/false, SQ, Depth);
3458 adjustKnownFPClassForSelectArm(KnownRHS, I->getOperand(0), I->getOperand(2),
3459 /*Invert=*/true, SQ, Depth);
3460 Known = KnownLHS.intersectWith(KnownRHS);
3461 Known.knownNot(~DemandedMask);
3462 break;
3463 }
3464 case Instruction::ExtractElement: {
3465 // TODO: Handle demanded element mask
3466 if (SimplifyDemandedFPClass(I, 0, DemandedMask, Known, SQ, Depth + 1))
3467 return I;
3468 Known.knownNot(~DemandedMask);
3469 break;
3470 }
3471 case Instruction::InsertElement: {
3472 KnownFPClass KnownInserted, KnownVec;
3473 if (SimplifyDemandedFPClass(I, 1, DemandedMask, KnownInserted, SQ,
3474 Depth + 1) ||
3475 SimplifyDemandedFPClass(I, 0, DemandedMask, KnownVec, SQ, Depth + 1))
3476 return I;
3477
3478 // TODO: Use demanded elements logic from computeKnownFPClass
3479 Known = KnownVec | KnownInserted;
3480 Known.knownNot(~DemandedMask);
3481 break;
3482 }
3483 case Instruction::ShuffleVector: {
3484 KnownFPClass KnownLHS, KnownRHS;
3485 if (SimplifyDemandedFPClass(I, 1, DemandedMask, KnownRHS, SQ, Depth + 1) ||
3486 SimplifyDemandedFPClass(I, 0, DemandedMask, KnownLHS, SQ, Depth + 1))
3487 return I;
3488
3489 // TODO: This is overly conservative and should consider demanded elements,
3490 // and splats.
3491 Known = KnownLHS | KnownRHS;
3492 Known.knownNot(~DemandedMask);
3493 break;
3494 }
3495 case Instruction::InsertValue: {
3496 KnownFPClass KnownAgg, KnownElt;
3497 if (SimplifyDemandedFPClass(I, 0, DemandedMask, KnownAgg, SQ, Depth + 1) ||
3498 SimplifyDemandedFPClass(I, 1, DemandedMask, KnownElt, SQ, Depth + 1))
3499 return I;
3500
3501 Known = KnownAgg | KnownElt;
3502 break;
3503 }
3504 case Instruction::ExtractValue: {
3505 Value *ExtractSrc;
3506 if (match(I, m_ExtractValue<0>(m_OneUse(m_Value(ExtractSrc))))) {
3507 if (auto *II = dyn_cast<IntrinsicInst>(ExtractSrc)) {
3508 const Intrinsic::ID IID = II->getIntrinsicID();
3509 switch (IID) {
3510 case Intrinsic::frexp: {
3511 FPClassTest SrcDemandedMask = fcNone;
3512 if (DemandedMask & fcNan)
3513 SrcDemandedMask |= fcNan;
3514 if (DemandedMask & fcNegFinite)
3515 SrcDemandedMask |= fcNegFinite;
3516 if (DemandedMask & fcPosFinite)
3517 SrcDemandedMask |= fcPosFinite;
3518 if (DemandedMask & fcPosInf)
3519 SrcDemandedMask |= fcPosInf;
3520 if (DemandedMask & fcNegInf)
3521 SrcDemandedMask |= fcNegInf;
3522
3523 KnownFPClass KnownSrc;
3524 if (SimplifyDemandedFPClass(II, 0, SrcDemandedMask, KnownSrc, SQ,
3525 Depth + 1))
3526 return I;
3527
3528 Type *EltTy = VTy->getScalarType();
3529 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3530
3531 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
3532 Known.KnownFPClasses &= DemandedMask;
3533
3534 if (Constant *SingleVal =
3535 getFPClassConstant(VTy, Known.KnownFPClasses,
3536 /*IsCanonicalizing=*/true))
3537 return SingleVal;
3538
3539 if (Known.isKnownAlways(fcInf | fcNan))
3540 return II->getArgOperand(0);
3541
3542 return nullptr;
3543 }
3544 default:
3545 break;
3546 }
3547 }
3548 }
3549
3550 KnownFPClass KnownSrc;
3551 if (SimplifyDemandedFPClass(I, 0, DemandedMask, KnownSrc, SQ, Depth + 1))
3552 return I;
3553 Known = KnownSrc;
3554 break;
3555 }
3556 case Instruction::PHI: {
3557 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
3558 if (Depth >= PhiRecursionLimit)
3559 break;
3560
3562 SimplifyQuery ContextSQ = SQ.getWithoutCondContext();
3563
3564 bool First = true;
3565 bool Changed = false;
3566 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; ++I) {
3567 // TODO: Better support for self recursive phi
3568 BasicBlock *PredBB = P->getIncomingBlock(I);
3569 const Instruction *CtxI = PredBB->getTerminator();
3570
3571 // Attempt to simplify all incoming edges at a time. If we simplify one
3572 // incoming edge, the phi may fold away, losing information on a later
3573 // visit.
3574 KnownFPClass KnownSrc;
3576 P, P->getOperandNumForIncomingValue(I), DemandedMask, KnownSrc,
3577 ContextSQ.getWithInstruction(CtxI), Depth + 1)) {
3578 // Fixup the other block references to the simplified value.
3579 P->setIncomingValueForBlock(PredBB, P->getIncomingValue(I));
3580 Changed = true;
3581 }
3582
3583 if (First) {
3584 Known = KnownSrc;
3585 First = false;
3586 } else {
3587 Known |= KnownSrc;
3588 }
3589 }
3590
3591 if (Changed)
3592 return P;
3593
3594 Known.knownNot(~DemandedMask);
3595 break;
3596 }
3597 default:
3598 Known = computeKnownFPClass(I, DemandedMask, SQ, Depth + 1);
3599 Known.knownNot(~DemandedMask);
3600 break;
3601 }
3602
3603 return getFPClassConstant(VTy, Known.KnownFPClasses);
3604}
3605
3606/// Helper routine of SimplifyDemandedUseFPClass. It computes Known
3607/// floating-point classes. It also tries to handle simplifications that can be
3608/// done based on DemandedMask, but without modifying the Instruction.
3610 Instruction *I, FPClassTest DemandedMask, KnownFPClass &Known,
3611 const SimplifyQuery &SQ, unsigned Depth) {
3612 FastMathFlags FMF;
3613 if (auto *FPOp = dyn_cast<FPMathOperator>(I)) {
3614 FMF = FPOp->getFastMathFlags();
3615 DemandedMask = adjustDemandedMaskFromFlags(DemandedMask, FMF);
3616 }
3617
3618 switch (I->getOpcode()) {
3619 case Instruction::Select: {
3620 // TODO: Can we infer which side it came from based on adjusted result
3621 // class?
3622 KnownFPClass KnownRHS =
3623 computeKnownFPClass(I->getOperand(2), DemandedMask, SQ, Depth + 1);
3624 if (KnownRHS.isKnownNever(DemandedMask))
3625 return I->getOperand(1);
3626
3627 KnownFPClass KnownLHS =
3628 computeKnownFPClass(I->getOperand(1), DemandedMask, SQ, Depth + 1);
3629 if (KnownLHS.isKnownNever(DemandedMask))
3630 return I->getOperand(2);
3631
3632 adjustKnownFPClassForSelectArm(KnownLHS, I->getOperand(0), I->getOperand(1),
3633 /*Invert=*/false, SQ, Depth);
3634 adjustKnownFPClassForSelectArm(KnownRHS, I->getOperand(0), I->getOperand(2),
3635 /*Invert=*/true, SQ, Depth);
3636 Known = KnownLHS.intersectWith(KnownRHS);
3637 Known.knownNot(~DemandedMask);
3638 break;
3639 }
3640 case Instruction::FNeg: {
3641 // Special case fneg(fabs(x))
3642 Value *Src;
3643
3644 Value *FNegSrc = I->getOperand(0);
3645 if (!match(FNegSrc, m_FAbs(m_Value(Src)))) {
3646 Known = computeKnownFPClass(I, DemandedMask, SQ, Depth + 1);
3647 break;
3648 }
3649
3650 KnownFPClass KnownSrc = computeKnownFPClass(Src, fcAllFlags, SQ, Depth + 1);
3651
3652 FastMathFlags FabsFMF = cast<FPMathOperator>(FNegSrc)->getFastMathFlags();
3653 FPClassTest ThisDemandedMask =
3654 adjustDemandedMaskFromFlags(DemandedMask, FabsFMF);
3655
3656 // We cannot apply the NSZ logic with multiple uses. We can apply it if the
3657 // inner fabs has it and this is the only use.
3658 if (Value *Simplified = simplifyDemandedFPClassFnegFabs(
3659 Known, Src, ThisDemandedMask, KnownSrc, /*NSZ=*/false))
3660 return Simplified;
3661 break;
3662 }
3663 case Instruction::Call: {
3664 const CallInst *CI = cast<CallInst>(I);
3665 const Intrinsic::ID IID = CI->getIntrinsicID();
3666 switch (IID) {
3667 case Intrinsic::fabs: {
3668 Value *Src = CI->getArgOperand(0);
3669 KnownFPClass KnownSrc =
3671
3672 // NSZ cannot be applied in multiple use case (maybe it could if all uses
3673 // were known nsz)
3674 if (Value *Simplified = simplifyDemandedFPClassFabs(
3675 Known, CI->getArgOperand(0), DemandedMask, KnownSrc,
3676 /*NSZ=*/false))
3677 return Simplified;
3678 break;
3679 }
3680 case Intrinsic::copysign: {
3681 Value *Mag = CI->getArgOperand(0);
3682 Value *Sign = CI->getArgOperand(1);
3683 KnownFPClass KnownMag =
3685
3686 // Rule out some cases by magnitude, which may help prove the sign bit is
3687 // one direction or the other.
3688 KnownMag.knownNot(~llvm::unknown_sign(DemandedMask));
3689
3690 // Cannot use nsz in the multiple use case.
3691 if (Value *Simplified = simplifyDemandedFPClassCopysignMag(
3692 Mag, DemandedMask, KnownMag, /*NSZ=*/false))
3693 return Simplified;
3694
3695 KnownFPClass KnownSign =
3697
3698 if (FMF.noInfs())
3699 KnownSign.knownNot(fcInf);
3700 if (FMF.noNaNs())
3701 KnownSign.knownNot(fcNan);
3702
3703 if (KnownSign.SignBit && KnownMag.SignBit &&
3704 *KnownSign.SignBit == *KnownMag.SignBit)
3705 return Mag;
3706
3707 Known = KnownFPClass::copysign(KnownMag, KnownSign);
3708 break;
3709 }
3710 case Intrinsic::maxnum:
3711 case Intrinsic::minnum:
3712 case Intrinsic::maximum:
3713 case Intrinsic::minimum:
3714 case Intrinsic::maximumnum:
3715 case Intrinsic::minimumnum: {
3717 DemandedMask, SQ, Depth + 1);
3718 if (KnownRHS.isUnknown())
3719 return nullptr;
3720
3722 DemandedMask, SQ, Depth + 1);
3723
3724 // Cannot use NSZ in the multiple use case.
3725 return simplifyDemandedFPClassMinMax(Known, IID, CI, DemandedMask,
3726 KnownLHS, KnownRHS, F,
3727 /*NSZ=*/false);
3728 }
3729 default:
3730 break;
3731 }
3732
3733 [[fallthrough]];
3734 }
3735 default:
3736 Known = computeKnownFPClass(I, DemandedMask, SQ, Depth + 1);
3737 Known.knownNot(~DemandedMask);
3738 break;
3739 }
3740
3741 return getFPClassConstant(I->getType(), Known.KnownFPClasses);
3742}
3743
3745 FPClassTest DemandedMask,
3747 const SimplifyQuery &SQ,
3748 unsigned Depth) {
3749 Use &U = I->getOperandUse(OpNo);
3750 Value *V = U.get();
3751 Type *VTy = V->getType();
3752
3753 if (DemandedMask == fcNone) {
3754 if (isa<PoisonValue>(V))
3755 return false;
3757 return true;
3758 }
3759
3760 // Handle constant
3762 if (!VInst) {
3763 // Handle constants and arguments
3765 Known.knownNot(~DemandedMask);
3766
3767 if (Known.KnownFPClasses == fcNone) {
3768 if (isa<PoisonValue>(V))
3769 return false;
3771 return true;
3772 }
3773
3774 // Do not try to replace values which are already constants (unless we are
3775 // folding to poison). Doing so could promote poison elements to non-poison
3776 // constants.
3777 if (isa<Constant>(V))
3778 return false;
3779
3780 Value *FoldedToConst = getFPClassConstant(VTy, Known.KnownFPClasses);
3781 if (!FoldedToConst || FoldedToConst == V)
3782 return false;
3783
3784 replaceUse(U, FoldedToConst);
3785 return true;
3786 }
3787
3789 Known.knownNot(~DemandedMask);
3790 return false;
3791 }
3792
3793 Value *NewVal;
3794
3795 if (VInst->hasOneUse()) {
3796 // If the instruction has one use, we can directly simplify it.
3797 NewVal = SimplifyDemandedUseFPClass(VInst, DemandedMask, Known, SQ, Depth);
3798 } else {
3799 // If there are multiple uses of this instruction, then we can simplify
3800 // VInst to some other value, but not modify the instruction.
3801 NewVal = SimplifyMultipleUseDemandedFPClass(VInst, DemandedMask, Known, SQ,
3802 Depth);
3803 }
3804
3805 if (!NewVal)
3806 return false;
3807 if (Instruction *OpInst = dyn_cast<Instruction>(U))
3808 salvageDebugInfo(*OpInst);
3809
3810 replaceUse(U, NewVal);
3811 return true;
3812}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
#define DEBUG_TYPE
Hexagon Common GEP
This file provides internal interfaces used to implement the InstCombine.
static cl::opt< unsigned > SimplifyDemandedVectorEltsDepthLimit("instcombine-simplify-vector-elts-depth", cl::desc("Depth limit when simplifying vector instructions and their operands"), cl::Hidden, cl::init(10))
static Constant * getFPClassConstant(Type *Ty, FPClassTest Mask, bool IsCanonicalizing=false)
For floating-point classes that resolve to a single bit pattern, return that value.
static cl::opt< bool > VerifyKnownBits("instcombine-verify-known-bits", cl::desc("Verify that computeKnownBits() and " "SimplifyDemandedBits() are consistent"), cl::Hidden, cl::init(false))
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static Value * simplifyDemandedFPClassFabs(KnownFPClass &Known, Value *Src, FPClassTest DemandedMask, KnownFPClass KnownSrc, bool NSZ)
Perform multiple-use aware simplfications for fabs(Src).
static Value * simplifyDemandedUseFPClassFPTrunc(InstCombinerImpl &IC, Instruction &I, FastMathFlags FMF, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &SQ, unsigned Depth)
static Value * simplifyDemandedFPClassFnegFabs(KnownFPClass &Known, Value *Src, FPClassTest DemandedMask, KnownFPClass KnownSrc, bool NSZ)
Perform multiple-use aware simplfications for fneg(fabs(Src)).
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
static Value * simplifyShiftSelectingPackedElement(Instruction *I, const APInt &DemandedMask, InstCombinerImpl &IC, unsigned Depth)
Let N = 2 * M.
static Value * simplifyDemandedFPClassMinMax(KnownFPClass &Known, Intrinsic::ID IID, const CallInst *CI, FPClassTest DemandedMask, KnownFPClass KnownLHS, KnownFPClass KnownRHS, const Function &F, bool NSZ)
static bool canSkipDemandedEltsInInsertChain(InsertElementInst &IE, unsigned VWidth, unsigned DepthLimit)
Return true if the top-level all-lanes demanded-elements query can be skipped for an intermediate ins...
static Value * simplifyDemandedFPClassCopysignMag(Value *MagSrc, FPClassTest DemandedMask, KnownFPClass KnownSrc, bool NSZ)
static FPClassTest adjustDemandedMaskFromFlags(FPClassTest DemandedMask, FastMathFlags FMF)
static FastMathFlags inferFastMathValueFlags(FastMathFlags FMF, FPClassTest ValidResults, ArrayRef< KnownFPClass > Known)
Try to set an inferred no-nans or no-infs in FMF.
static Value * simplifyDemandedFPClassResult(Instruction *FPOp, FastMathFlags FMF, FPClassTest DemandedMask, KnownFPClass &Known, ArrayRef< KnownFPClass > KnownSrcs)
Apply epilog fixups to a floating-point intrinsic.
This file provides the interface for the instcombine pass implementation.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file implements the SmallBitVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1168
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1431
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1416
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1695
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1076
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1692
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1365
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1421
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1664
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1623
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1460
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:476
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1266
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:433
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:390
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:89
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
void setNoInfs(bool B=true)
Definition FMF.h:81
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2364
LLVM_ABI Value * CreateSelectWithUnknownProfile(Value *C, Value *True, Value *False, StringRef PassName, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
This instruction inserts a single (scalar) element into a VectorType value.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool SimplifyDemandedInstructionFPClass(Instruction &Inst)
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
Value * SimplifyDemandedUseFPClass(Instruction *I, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth=0)
Attempts to replace V with a simpler value based on the demanded floating-point classes.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
std::optional< std::pair< Intrinsic::ID, SmallVector< Value *, 3 > > > convertOrOfShiftsToFunnelShift(Instruction &Or)
Value * SimplifyMultipleUseDemandedFPClass(Instruction *I, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
Helper routine of SimplifyDemandedUseFPClass.
Value * simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1, Instruction *Shl, const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known)
Helper routine of SimplifyDemandedUseBits.
bool SimplifyDemandedFPClass(Instruction *I, unsigned Op, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth=0)
Value * SimplifyDemandedUseBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Attempts to replace I with a simpler value based on the demanded bits.
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Value * SimplifyMultipleUseDemandedBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Helper routine of SimplifyDemandedUseBits.
SimplifyQuery SQ
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
const DataLayout & DL
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
LLVM_ABI std::optional< Value * > targetSimplifyDemandedVectorEltsIntrinsic(IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
LLVM_ABI std::optional< Value * > targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
bool isShift() const
bool isIntDivRem() const
A wrapper class for inspecting calls to intrinsic functions.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
const Value * getCondition() const
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
bool test(unsigned Idx) const
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isMultiUnitFPType() const
Returns true if this is a floating-point type that is an unevaluated sum of multiple floating-point u...
Definition Type.h:195
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isIEEELikeFPTy() const
Return true if this is a well-behaved IEEE-like type, which has a IEEE compatible layout,...
Definition Type.h:172
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
iterator_range< user_iterator > users()
Definition Value.h:426
bool hasUseList() const
Check if this Value has a use-list.
Definition Value.h:344
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
Base class of all SIMD vector types.
This class represents zero extension of integer types.
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
DisjointOr_match< LHS, RHS, true > m_c_DisjointOr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_FAbs(const Opnd0 &Op0)
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1690
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
gep_type_iterator gep_type_end(const User *GEP)
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI bool cannotOrderStrictlyLess(FPClassTest LHS, FPClassTest RHS, bool OrderedZeroSign=false)
Returns true if all values in LHS must be greater than or equal to those in RHS.
LLVM_ABI bool cannotOrderStrictlyGreater(FPClassTest LHS, FPClassTest RHS, bool OrderedZeroSign=false)
Returns true if all values in LHS must be less than or equal to those in RHS.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI FPClassTest fneg(FPClassTest Mask)
Return the test mask which returns true if the value's sign bit is flipped.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI FPClassTest inverse_fabs(FPClassTest Mask)
Return the test mask which returns true after fabs is applied to the value.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
LLVM_ABI FPClassTest unknown_sign(FPClassTest Mask)
Return the test mask which returns true if the value could have the same set of classes,...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getPreserveSign()
static constexpr DenormalMode getIEEE()
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:184
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:200
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
bool isKnownNeverInfinity() const
Return true if it's known this can never be an infinity.
static constexpr FPClassTest OrderedGreaterThanZeroMask
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
void copysign(const KnownFPClass &Sign)
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
bool isKnownAlways(FPClassTest Mask) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
bool isUnknown() const
KnownFPClass intersectWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
std::optional< bool > SignBit
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
LLVM_ABI bool isKnownNeverLogicalPosZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a positive zero.
bool cannotBeOrderedGreaterEqZero(DenormalMode Mode) const
Return true if it's know this can never be a negative value or a logical 0.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
Matching combinators.
const Instruction * CxtI
SimplifyQuery getWithInstruction(const Instruction *I) const