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