LLVM 19.0.0git
InstCombineSimplifyDemanded.cpp
Go to the documentation of this file.
1//===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains logic for simplifying instructions based on information
10// about how they are used.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
21
22using namespace llvm;
23using namespace llvm::PatternMatch;
24
25#define DEBUG_TYPE "instcombine"
26
27static cl::opt<bool>
28 VerifyKnownBits("instcombine-verify-known-bits",
29 cl::desc("Verify that computeKnownBits() and "
30 "SimplifyDemandedBits() are consistent"),
31 cl::Hidden, cl::init(false));
32
33/// Check to see if the specified operand of the specified instruction is a
34/// constant integer. If so, check to see if there are any bits set in the
35/// constant that are not demanded. If so, shrink the constant and return true.
36static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
37 const APInt &Demanded) {
38 assert(I && "No instruction?");
39 assert(OpNo < I->getNumOperands() && "Operand index too large");
40
41 // The operand must be a constant integer or splat integer.
42 Value *Op = I->getOperand(OpNo);
43 const APInt *C;
44 if (!match(Op, m_APInt(C)))
45 return false;
46
47 // If there are no bits set that aren't demanded, nothing to do.
48 if (C->isSubsetOf(Demanded))
49 return false;
50
51 // This instruction is producing bits that are not demanded. Shrink the RHS.
52 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
53
54 return true;
55}
56
57/// Returns the bitwidth of the given scalar or pointer type. For vector types,
58/// returns the element type's bitwidth.
59static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
60 if (unsigned BitWidth = Ty->getScalarSizeInBits())
61 return BitWidth;
62
63 return DL.getPointerTypeSizeInBits(Ty);
64}
65
66/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
67/// the instruction has any properties that allow us to simplify its operands.
69 KnownBits &Known) {
70 APInt DemandedMask(APInt::getAllOnes(Known.getBitWidth()));
71 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
72 0, SQ.getWithInstruction(&Inst));
73 if (!V) return false;
74 if (V == &Inst) return true;
75 replaceInstUsesWith(Inst, V);
76 return true;
77}
78
79/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
80/// the instruction has any properties that allow us to simplify its operands.
82 KnownBits Known(getBitWidth(Inst.getType(), DL));
83 return SimplifyDemandedInstructionBits(Inst, Known);
84}
85
86/// This form of SimplifyDemandedBits simplifies the specified instruction
87/// operand if possible, updating it in place. It returns true if it made any
88/// change and false otherwise.
90 const APInt &DemandedMask,
91 KnownBits &Known, unsigned Depth,
92 const SimplifyQuery &Q) {
93 Use &U = I->getOperandUse(OpNo);
94 Value *V = U.get();
95 if (isa<Constant>(V)) {
96 llvm::computeKnownBits(V, Known, Depth, Q);
97 return false;
98 }
99
100 Known.resetAll();
101 if (DemandedMask.isZero()) {
102 // Not demanding any bits from V.
103 replaceUse(U, UndefValue::get(V->getType()));
104 return true;
105 }
106
108 return false;
109
110 Instruction *VInst = dyn_cast<Instruction>(V);
111 if (!VInst) {
112 llvm::computeKnownBits(V, Known, Depth, Q);
113 return false;
114 }
115
116 Value *NewVal;
117 if (VInst->hasOneUse()) {
118 // If the instruction has one use, we can directly simplify it.
119 NewVal = SimplifyDemandedUseBits(VInst, DemandedMask, Known, Depth, Q);
120 } else {
121 // If there are multiple uses of this instruction, then we can simplify
122 // VInst to some other value, but not modify the instruction.
123 NewVal =
124 SimplifyMultipleUseDemandedBits(VInst, DemandedMask, Known, Depth, Q);
125 }
126 if (!NewVal) return false;
127 if (Instruction* OpInst = dyn_cast<Instruction>(U))
128 salvageDebugInfo(*OpInst);
129
130 replaceUse(U, NewVal);
131 return true;
132}
133
134/// This function attempts to replace V with a simpler value based on the
135/// demanded bits. When this function is called, it is known that only the bits
136/// set in DemandedMask of the result of V are ever used downstream.
137/// Consequently, depending on the mask and V, it may be possible to replace V
138/// with a constant or one of its operands. In such cases, this function does
139/// the replacement and returns true. In all other cases, it returns false after
140/// analyzing the expression and setting KnownOne and known to be one in the
141/// expression. Known.Zero contains all the bits that are known to be zero in
142/// the expression. These are provided to potentially allow the caller (which
143/// might recursively be SimplifyDemandedBits itself) to simplify the
144/// expression.
145/// Known.One and Known.Zero always follow the invariant that:
146/// Known.One & Known.Zero == 0.
147/// That is, a bit can't be both 1 and 0. The bits in Known.One and Known.Zero
148/// are accurate even for bits not in DemandedMask. Note
149/// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
150/// be the same.
151///
152/// This returns null if it did not change anything and it permits no
153/// simplification. This returns V itself if it did some simplification of V's
154/// operands based on the information about what bits are demanded. This returns
155/// some other non-null value if it found out that V is equal to another value
156/// in the context where the specified bits are demanded, but not for all users.
158 const APInt &DemandedMask,
159 KnownBits &Known,
160 unsigned Depth,
161 const SimplifyQuery &Q) {
162 assert(I != nullptr && "Null pointer of Value???");
163 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
164 uint32_t BitWidth = DemandedMask.getBitWidth();
165 Type *VTy = I->getType();
166 assert(
167 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
168 Known.getBitWidth() == BitWidth &&
169 "Value *V, DemandedMask and Known must have same BitWidth");
170
171 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
172
173 // Update flags after simplifying an operand based on the fact that some high
174 // order bits are not demanded.
175 auto disableWrapFlagsBasedOnUnusedHighBits = [](Instruction *I,
176 unsigned NLZ) {
177 if (NLZ > 0) {
178 // Disable the nsw and nuw flags here: We can no longer guarantee that
179 // we won't wrap after simplification. Removing the nsw/nuw flags is
180 // legal here because the top bit is not demanded.
181 I->setHasNoSignedWrap(false);
182 I->setHasNoUnsignedWrap(false);
183 }
184 return I;
185 };
186
187 // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
188 // about the high bits of the operands.
189 auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
190 unsigned NLZ = DemandedMask.countl_zero();
191 // Right fill the mask of bits for the operands to demand the most
192 // significant bit and all those below it.
193 DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
194 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
195 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1, Q) ||
196 ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
197 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1, Q)) {
198 disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
199 return true;
200 }
201 return false;
202 };
203
204 switch (I->getOpcode()) {
205 default:
206 llvm::computeKnownBits(I, Known, Depth, Q);
207 break;
208 case Instruction::And: {
209 // If either the LHS or the RHS are Zero, the result is zero.
210 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1, Q) ||
211 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
212 Depth + 1, Q))
213 return I;
214
215 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
216 Depth, Q);
217
218 // If the client is only demanding bits that we know, return the known
219 // constant.
220 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
221 return Constant::getIntegerValue(VTy, Known.One);
222
223 // If all of the demanded bits are known 1 on one side, return the other.
224 // These bits cannot contribute to the result of the 'and'.
225 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
226 return I->getOperand(0);
227 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
228 return I->getOperand(1);
229
230 // If the RHS is a constant, see if we can simplify it.
231 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
232 return I;
233
234 break;
235 }
236 case Instruction::Or: {
237 // If either the LHS or the RHS are One, the result is One.
238 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1, Q) ||
239 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
240 Depth + 1, Q)) {
241 // Disjoint flag may not longer hold.
242 I->dropPoisonGeneratingFlags();
243 return I;
244 }
245
246 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
247 Depth, Q);
248
249 // If the client is only demanding bits that we know, return the known
250 // constant.
251 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
252 return Constant::getIntegerValue(VTy, Known.One);
253
254 // If all of the demanded bits are known zero on one side, return the other.
255 // These bits cannot contribute to the result of the 'or'.
256 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
257 return I->getOperand(0);
258 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
259 return I->getOperand(1);
260
261 // If the RHS is a constant, see if we can simplify it.
262 if (ShrinkDemandedConstant(I, 1, DemandedMask))
263 return I;
264
265 // Infer disjoint flag if no common bits are set.
266 if (!cast<PossiblyDisjointInst>(I)->isDisjoint()) {
267 WithCache<const Value *> LHSCache(I->getOperand(0), LHSKnown),
268 RHSCache(I->getOperand(1), RHSKnown);
269 if (haveNoCommonBitsSet(LHSCache, RHSCache, Q)) {
270 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
271 return I;
272 }
273 }
274
275 break;
276 }
277 case Instruction::Xor: {
278 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1, Q) ||
279 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1, Q))
280 return I;
281 Value *LHS, *RHS;
282 if (DemandedMask == 1 &&
283 match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) &&
284 match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) {
285 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
288 auto *Xor = Builder.CreateXor(LHS, RHS);
289 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
290 }
291
292 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
293 Depth, Q);
294
295 // If the client is only demanding bits that we know, return the known
296 // constant.
297 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
298 return Constant::getIntegerValue(VTy, Known.One);
299
300 // If all of the demanded bits are known zero on one side, return the other.
301 // These bits cannot contribute to the result of the 'xor'.
302 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
303 return I->getOperand(0);
304 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
305 return I->getOperand(1);
306
307 // If all of the demanded bits are known to be zero on one side or the
308 // other, turn this into an *inclusive* or.
309 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
310 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
311 Instruction *Or =
312 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1));
313 if (DemandedMask.isAllOnes())
314 cast<PossiblyDisjointInst>(Or)->setIsDisjoint(true);
315 Or->takeName(I);
316 return InsertNewInstWith(Or, I->getIterator());
317 }
318
319 // If all of the demanded bits on one side are known, and all of the set
320 // bits on that side are also known to be set on the other side, turn this
321 // into an AND, as we know the bits will be cleared.
322 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
323 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
324 RHSKnown.One.isSubsetOf(LHSKnown.One)) {
326 ~RHSKnown.One & DemandedMask);
327 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
328 return InsertNewInstWith(And, I->getIterator());
329 }
330
331 // If the RHS is a constant, see if we can change it. Don't alter a -1
332 // constant because that's a canonical 'not' op, and that is better for
333 // combining, SCEV, and codegen.
334 const APInt *C;
335 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
336 if ((*C | ~DemandedMask).isAllOnes()) {
337 // Force bits to 1 to create a 'not' op.
338 I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
339 return I;
340 }
341 // If we can't turn this into a 'not', try to shrink the constant.
342 if (ShrinkDemandedConstant(I, 1, DemandedMask))
343 return I;
344 }
345
346 // If our LHS is an 'and' and if it has one use, and if any of the bits we
347 // are flipping are known to be set, then the xor is just resetting those
348 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
349 // simplifying both of them.
350 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
351 ConstantInt *AndRHS, *XorRHS;
352 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
353 match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
354 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
355 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
356 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
357
358 Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue());
359 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
360 InsertNewInstWith(NewAnd, I->getIterator());
361
362 Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue());
363 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
364 return InsertNewInstWith(NewXor, I->getIterator());
365 }
366 }
367 break;
368 }
369 case Instruction::Select: {
370 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1, Q) ||
371 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1, Q))
372 return I;
373
374 // If the operands are constants, see if we can simplify them.
375 // This is similar to ShrinkDemandedConstant, but for a select we want to
376 // try to keep the selected constants the same as icmp value constants, if
377 // we can. This helps not break apart (or helps put back together)
378 // canonical patterns like min and max.
379 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
380 const APInt &DemandedMask) {
381 const APInt *SelC;
382 if (!match(I->getOperand(OpNo), m_APInt(SelC)))
383 return false;
384
385 // Get the constant out of the ICmp, if there is one.
386 // Only try this when exactly 1 operand is a constant (if both operands
387 // are constant, the icmp should eventually simplify). Otherwise, we may
388 // invert the transform that reduces set bits and infinite-loop.
389 Value *X;
390 const APInt *CmpC;
392 if (!match(I->getOperand(0), m_ICmp(Pred, m_Value(X), m_APInt(CmpC))) ||
393 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
394 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
395
396 // If the constant is already the same as the ICmp, leave it as-is.
397 if (*CmpC == *SelC)
398 return false;
399 // If the constants are not already the same, but can be with the demand
400 // mask, use the constant value from the ICmp.
401 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
402 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
403 return true;
404 }
405 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
406 };
407 if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
408 CanonicalizeSelectConstant(I, 2, DemandedMask))
409 return I;
410
411 // Only known if known in both the LHS and RHS.
412 adjustKnownBitsForSelectArm(LHSKnown, I->getOperand(0), I->getOperand(1),
413 /*Invert=*/false, Depth, Q);
414 adjustKnownBitsForSelectArm(RHSKnown, I->getOperand(0), I->getOperand(2),
415 /*Invert=*/true, Depth, Q);
416 Known = LHSKnown.intersectWith(RHSKnown);
417 break;
418 }
419 case Instruction::Trunc: {
420 // If we do not demand the high bits of a right-shifted and truncated value,
421 // then we may be able to truncate it before the shift.
422 Value *X;
423 const APInt *C;
424 if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
425 // The shift amount must be valid (not poison) in the narrow type, and
426 // it must not be greater than the high bits demanded of the result.
427 if (C->ult(VTy->getScalarSizeInBits()) &&
428 C->ule(DemandedMask.countl_zero())) {
429 // trunc (lshr X, C) --> lshr (trunc X), C
432 Value *Trunc = Builder.CreateTrunc(X, VTy);
433 return Builder.CreateLShr(Trunc, C->getZExtValue());
434 }
435 }
436 }
437 [[fallthrough]];
438 case Instruction::ZExt: {
439 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
440
441 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
442 KnownBits InputKnown(SrcBitWidth);
443 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1,
444 Q)) {
445 // For zext nneg, we may have dropped the instruction which made the
446 // input non-negative.
447 I->dropPoisonGeneratingFlags();
448 return I;
449 }
450 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
451 if (I->getOpcode() == Instruction::ZExt && I->hasNonNeg() &&
452 !InputKnown.isNegative())
453 InputKnown.makeNonNegative();
454 Known = InputKnown.zextOrTrunc(BitWidth);
455
456 break;
457 }
458 case Instruction::SExt: {
459 // Compute the bits in the result that are not present in the input.
460 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
461
462 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
463
464 // If any of the sign extended bits are demanded, we know that the sign
465 // bit is demanded.
466 if (DemandedMask.getActiveBits() > SrcBitWidth)
467 InputDemandedBits.setBit(SrcBitWidth-1);
468
469 KnownBits InputKnown(SrcBitWidth);
470 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1, Q))
471 return I;
472
473 // If the input sign bit is known zero, or if the NewBits are not demanded
474 // convert this into a zero extension.
475 if (InputKnown.isNonNegative() ||
476 DemandedMask.getActiveBits() <= SrcBitWidth) {
477 // Convert to ZExt cast.
478 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy);
479 NewCast->takeName(I);
480 return InsertNewInstWith(NewCast, I->getIterator());
481 }
482
483 // If the sign bit of the input is known set or clear, then we know the
484 // top bits of the result.
485 Known = InputKnown.sext(BitWidth);
486 break;
487 }
488 case Instruction::Add: {
489 if ((DemandedMask & 1) == 0) {
490 // If we do not need the low bit, try to convert bool math to logic:
491 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
492 Value *X, *Y;
494 m_OneUse(m_SExt(m_Value(Y))))) &&
495 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
496 // Truth table for inputs and output signbits:
497 // X:0 | X:1
498 // ----------
499 // Y:0 | 0 | 0 |
500 // Y:1 | -1 | 0 |
501 // ----------
505 return Builder.CreateSExt(AndNot, VTy);
506 }
507
508 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
509 if (match(I, m_Add(m_SExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
510 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
511 (I->getOperand(0)->hasOneUse() || I->getOperand(1)->hasOneUse())) {
512
513 // Truth table for inputs and output signbits:
514 // X:0 | X:1
515 // -----------
516 // Y:0 | -1 | -1 |
517 // Y:1 | -1 | 0 |
518 // -----------
521 Value *Or = Builder.CreateOr(X, Y);
522 return Builder.CreateSExt(Or, VTy);
523 }
524 }
525
526 // Right fill the mask of bits for the operands to demand the most
527 // significant bit and all those below it.
528 unsigned NLZ = DemandedMask.countl_zero();
529 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
530 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
531 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1, Q))
532 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
533
534 // If low order bits are not demanded and known to be zero in one operand,
535 // then we don't need to demand them from the other operand, since they
536 // can't cause overflow into any bits that are demanded in the result.
537 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
538 APInt DemandedFromLHS = DemandedFromOps;
539 DemandedFromLHS.clearLowBits(NTZ);
540 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
541 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1, Q))
542 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
543
544 // If we are known to be adding zeros to every bit below
545 // the highest demanded bit, we just return the other side.
546 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
547 return I->getOperand(0);
548 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
549 return I->getOperand(1);
550
551 // (add X, C) --> (xor X, C) IFF C is equal to the top bit of the DemandMask
552 {
553 const APInt *C;
554 if (match(I->getOperand(1), m_APInt(C)) &&
555 C->isOneBitSet(DemandedMask.getActiveBits() - 1)) {
558 return Builder.CreateXor(I->getOperand(0), ConstantInt::get(VTy, *C));
559 }
560 }
561
562 // Otherwise just compute the known bits of the result.
563 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
564 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
565 Known = KnownBits::computeForAddSub(true, NSW, NUW, LHSKnown, RHSKnown);
566 break;
567 }
568 case Instruction::Sub: {
569 // Right fill the mask of bits for the operands to demand the most
570 // significant bit and all those below it.
571 unsigned NLZ = DemandedMask.countl_zero();
572 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
573 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
574 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1, Q))
575 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
576
577 // If low order bits are not demanded and are known to be zero in RHS,
578 // then we don't need to demand them from LHS, since they can't cause a
579 // borrow from any bits that are demanded in the result.
580 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
581 APInt DemandedFromLHS = DemandedFromOps;
582 DemandedFromLHS.clearLowBits(NTZ);
583 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
584 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1, Q))
585 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
586
587 // If we are known to be subtracting zeros from every bit below
588 // the highest demanded bit, we just return the other side.
589 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
590 return I->getOperand(0);
591 // We can't do this with the LHS for subtraction, unless we are only
592 // demanding the LSB.
593 if (DemandedFromOps.isOne() && DemandedFromOps.isSubsetOf(LHSKnown.Zero))
594 return I->getOperand(1);
595
596 // Otherwise just compute the known bits of the result.
597 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
598 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
599 Known = KnownBits::computeForAddSub(false, NSW, NUW, LHSKnown, RHSKnown);
600 break;
601 }
602 case Instruction::Mul: {
603 APInt DemandedFromOps;
604 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
605 return I;
606
607 if (DemandedMask.isPowerOf2()) {
608 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
609 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
610 // odd (has LSB set), then the left-shifted low bit of X is the answer.
611 unsigned CTZ = DemandedMask.countr_zero();
612 const APInt *C;
613 if (match(I->getOperand(1), m_APInt(C)) && C->countr_zero() == CTZ) {
614 Constant *ShiftC = ConstantInt::get(VTy, CTZ);
615 Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
616 return InsertNewInstWith(Shl, I->getIterator());
617 }
618 }
619 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
620 // X * X is odd iff X is odd.
621 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
622 if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
623 Constant *One = ConstantInt::get(VTy, 1);
624 Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
625 return InsertNewInstWith(And1, I->getIterator());
626 }
627
628 llvm::computeKnownBits(I, Known, Depth, Q);
629 break;
630 }
631 case Instruction::Shl: {
632 const APInt *SA;
633 if (match(I->getOperand(1), m_APInt(SA))) {
634 const APInt *ShrAmt;
635 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
636 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
637 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
638 DemandedMask, Known))
639 return R;
640
641 // Do not simplify if shl is part of funnel-shift pattern
642 if (I->hasOneUse()) {
643 auto *Inst = dyn_cast<Instruction>(I->user_back());
644 if (Inst && Inst->getOpcode() == BinaryOperator::Or) {
645 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
646 auto [IID, FShiftArgs] = *Opt;
647 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
648 FShiftArgs[0] == FShiftArgs[1]) {
649 llvm::computeKnownBits(I, Known, Depth, Q);
650 break;
651 }
652 }
653 }
654 }
655
656 // We only want bits that already match the signbit then we don't
657 // need to shift.
658 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth - 1);
659 if (DemandedMask.countr_zero() >= ShiftAmt) {
660 if (I->hasNoSignedWrap()) {
661 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
662 unsigned SignBits =
663 ComputeNumSignBits(I->getOperand(0), Depth + 1, Q.CxtI);
664 if (SignBits > ShiftAmt && SignBits - ShiftAmt >= NumHiDemandedBits)
665 return I->getOperand(0);
666 }
667
668 // If we can pre-shift a right-shifted constant to the left without
669 // losing any high bits and we don't demand the low bits, then eliminate
670 // the left-shift:
671 // (C >> X) << LeftShiftAmtC --> (C << LeftShiftAmtC) >> X
672 Value *X;
673 Constant *C;
674 if (match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) {
675 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
676 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::Shl, C,
677 LeftShiftAmtC, DL);
678 if (ConstantFoldBinaryOpOperands(Instruction::LShr, NewC,
679 LeftShiftAmtC, DL) == C) {
680 Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X);
681 return InsertNewInstWith(Lshr, I->getIterator());
682 }
683 }
684 }
685
686 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
687
688 // If the shift is NUW/NSW, then it does demand the high bits.
689 ShlOperator *IOp = cast<ShlOperator>(I);
690 if (IOp->hasNoSignedWrap())
691 DemandedMaskIn.setHighBits(ShiftAmt+1);
692 else if (IOp->hasNoUnsignedWrap())
693 DemandedMaskIn.setHighBits(ShiftAmt);
694
695 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1, Q))
696 return I;
697
698 Known = KnownBits::shl(Known,
700 /* NUW */ IOp->hasNoUnsignedWrap(),
701 /* NSW */ IOp->hasNoSignedWrap());
702 } else {
703 // This is a variable shift, so we can't shift the demand mask by a known
704 // amount. But if we are not demanding high bits, then we are not
705 // demanding those bits from the pre-shifted operand either.
706 if (unsigned CTLZ = DemandedMask.countl_zero()) {
707 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
708 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Depth + 1, Q)) {
709 // We can't guarantee that nsw/nuw hold after simplifying the operand.
710 I->dropPoisonGeneratingFlags();
711 return I;
712 }
713 }
714 llvm::computeKnownBits(I, Known, Depth, Q);
715 }
716 break;
717 }
718 case Instruction::LShr: {
719 const APInt *SA;
720 if (match(I->getOperand(1), m_APInt(SA))) {
721 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
722
723 // Do not simplify if lshr is part of funnel-shift pattern
724 if (I->hasOneUse()) {
725 auto *Inst = dyn_cast<Instruction>(I->user_back());
726 if (Inst && Inst->getOpcode() == BinaryOperator::Or) {
727 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
728 auto [IID, FShiftArgs] = *Opt;
729 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
730 FShiftArgs[0] == FShiftArgs[1]) {
731 llvm::computeKnownBits(I, Known, Depth, Q);
732 break;
733 }
734 }
735 }
736 }
737
738 // If we are just demanding the shifted sign bit and below, then this can
739 // be treated as an ASHR in disguise.
740 if (DemandedMask.countl_zero() >= ShiftAmt) {
741 // If we only want bits that already match the signbit then we don't
742 // need to shift.
743 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
744 unsigned SignBits =
745 ComputeNumSignBits(I->getOperand(0), Depth + 1, Q.CxtI);
746 if (SignBits >= NumHiDemandedBits)
747 return I->getOperand(0);
748
749 // If we can pre-shift a left-shifted constant to the right without
750 // losing any low bits (we already know we don't demand the high bits),
751 // then eliminate the right-shift:
752 // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
753 Value *X;
754 Constant *C;
755 if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
756 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
757 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::LShr, C,
758 RightShiftAmtC, DL);
759 if (ConstantFoldBinaryOpOperands(Instruction::Shl, NewC,
760 RightShiftAmtC, DL) == C) {
761 Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
762 return InsertNewInstWith(Shl, I->getIterator());
763 }
764 }
765 }
766
767 // Unsigned shift right.
768 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
769 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1, Q)) {
770 // exact flag may not longer hold.
771 I->dropPoisonGeneratingFlags();
772 return I;
773 }
774 Known.Zero.lshrInPlace(ShiftAmt);
775 Known.One.lshrInPlace(ShiftAmt);
776 if (ShiftAmt)
777 Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
778 } else {
779 llvm::computeKnownBits(I, Known, Depth, Q);
780 }
781 break;
782 }
783 case Instruction::AShr: {
784 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, Q.CxtI);
785
786 // If we only want bits that already match the signbit then we don't need
787 // to shift.
788 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
789 if (SignBits >= NumHiDemandedBits)
790 return I->getOperand(0);
791
792 // If this is an arithmetic shift right and only the low-bit is set, we can
793 // always convert this into a logical shr, even if the shift amount is
794 // variable. The low bit of the shift cannot be an input sign bit unless
795 // the shift amount is >= the size of the datatype, which is undefined.
796 if (DemandedMask.isOne()) {
797 // Perform the logical shift right.
798 Instruction *NewVal = BinaryOperator::CreateLShr(
799 I->getOperand(0), I->getOperand(1), I->getName());
800 return InsertNewInstWith(NewVal, I->getIterator());
801 }
802
803 const APInt *SA;
804 if (match(I->getOperand(1), m_APInt(SA))) {
805 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
806
807 // Signed shift right.
808 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
809 // If any of the high bits are demanded, we should set the sign bit as
810 // demanded.
811 if (DemandedMask.countl_zero() <= ShiftAmt)
812 DemandedMaskIn.setSignBit();
813
814 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1, Q)) {
815 // exact flag may not longer hold.
816 I->dropPoisonGeneratingFlags();
817 return I;
818 }
819
820 Known = KnownBits::ashr(
821 Known, KnownBits::makeConstant(APInt(BitWidth, ShiftAmt)),
822 ShiftAmt != 0, I->isExact());
823
824 // If the input sign bit is known to be zero, or if none of the top bits
825 // are demanded, turn this into an unsigned shift right.
826 assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
828 BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
829 if (Known.Zero[BitWidth-ShiftAmt-1] ||
830 !DemandedMask.intersects(HighBits)) {
831 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
832 I->getOperand(1));
833 LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
834 LShr->takeName(I);
835 return InsertNewInstWith(LShr, I->getIterator());
836 }
837 } else {
838 llvm::computeKnownBits(I, Known, Depth, Q);
839 }
840 break;
841 }
842 case Instruction::UDiv: {
843 // UDiv doesn't demand low bits that are zero in the divisor.
844 const APInt *SA;
845 if (match(I->getOperand(1), m_APInt(SA))) {
846 // TODO: Take the demanded mask of the result into account.
847 unsigned RHSTrailingZeros = SA->countr_zero();
848 APInt DemandedMaskIn =
849 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
850 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1, Q)) {
851 // We can't guarantee that "exact" is still true after changing the
852 // the dividend.
853 I->dropPoisonGeneratingFlags();
854 return I;
855 }
856
857 Known = KnownBits::udiv(LHSKnown, KnownBits::makeConstant(*SA),
858 cast<BinaryOperator>(I)->isExact());
859 } else {
860 llvm::computeKnownBits(I, Known, Depth, Q);
861 }
862 break;
863 }
864 case Instruction::SRem: {
865 const APInt *Rem;
866 if (match(I->getOperand(1), m_APInt(Rem))) {
867 // X % -1 demands all the bits because we don't want to introduce
868 // INT_MIN % -1 (== undef) by accident.
869 if (Rem->isAllOnes())
870 break;
871 APInt RA = Rem->abs();
872 if (RA.isPowerOf2()) {
873 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
874 return I->getOperand(0);
875
876 APInt LowBits = RA - 1;
877 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
878 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1, Q))
879 return I;
880
881 // The low bits of LHS are unchanged by the srem.
882 Known.Zero = LHSKnown.Zero & LowBits;
883 Known.One = LHSKnown.One & LowBits;
884
885 // If LHS is non-negative or has all low bits zero, then the upper bits
886 // are all zero.
887 if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
888 Known.Zero |= ~LowBits;
889
890 // If LHS is negative and not all low bits are zero, then the upper bits
891 // are all one.
892 if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
893 Known.One |= ~LowBits;
894
895 break;
896 }
897 }
898
899 llvm::computeKnownBits(I, Known, Depth, Q);
900 break;
901 }
902 case Instruction::Call: {
903 bool KnownBitsComputed = false;
904 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
905 switch (II->getIntrinsicID()) {
906 case Intrinsic::abs: {
907 if (DemandedMask == 1)
908 return II->getArgOperand(0);
909 break;
910 }
911 case Intrinsic::ctpop: {
912 // Checking if the number of clear bits is odd (parity)? If the type has
913 // an even number of bits, that's the same as checking if the number of
914 // set bits is odd, so we can eliminate the 'not' op.
915 Value *X;
916 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
917 match(II->getArgOperand(0), m_Not(m_Value(X)))) {
919 II->getModule(), Intrinsic::ctpop, VTy);
920 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), I->getIterator());
921 }
922 break;
923 }
924 case Intrinsic::bswap: {
925 // If the only bits demanded come from one byte of the bswap result,
926 // just shift the input byte into position to eliminate the bswap.
927 unsigned NLZ = DemandedMask.countl_zero();
928 unsigned NTZ = DemandedMask.countr_zero();
929
930 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
931 // we need all the bits down to bit 8. Likewise, round NLZ. If we
932 // have 14 leading zeros, round to 8.
933 NLZ = alignDown(NLZ, 8);
934 NTZ = alignDown(NTZ, 8);
935 // If we need exactly one byte, we can do this transformation.
936 if (BitWidth - NLZ - NTZ == 8) {
937 // Replace this with either a left or right shift to get the byte into
938 // the right place.
939 Instruction *NewVal;
940 if (NLZ > NTZ)
941 NewVal = BinaryOperator::CreateLShr(
942 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
943 else
944 NewVal = BinaryOperator::CreateShl(
945 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
946 NewVal->takeName(I);
947 return InsertNewInstWith(NewVal, I->getIterator());
948 }
949 break;
950 }
951 case Intrinsic::ptrmask: {
952 unsigned MaskWidth = I->getOperand(1)->getType()->getScalarSizeInBits();
953 RHSKnown = KnownBits(MaskWidth);
954 // If either the LHS or the RHS are Zero, the result is zero.
955 if (SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1, Q) ||
957 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth),
958 RHSKnown, Depth + 1, Q))
959 return I;
960
961 // TODO: Should be 1-extend
962 RHSKnown = RHSKnown.anyextOrTrunc(BitWidth);
963
964 Known = LHSKnown & RHSKnown;
965 KnownBitsComputed = true;
966
967 // If the client is only demanding bits we know to be zero, return
968 // `llvm.ptrmask(p, 0)`. We can't return `null` here due to pointer
969 // provenance, but making the mask zero will be easily optimizable in
970 // the backend.
971 if (DemandedMask.isSubsetOf(Known.Zero) &&
972 !match(I->getOperand(1), m_Zero()))
973 return replaceOperand(
974 *I, 1, Constant::getNullValue(I->getOperand(1)->getType()));
975
976 // Mask in demanded space does nothing.
977 // NOTE: We may have attributes associated with the return value of the
978 // llvm.ptrmask intrinsic that will be lost when we just return the
979 // operand. We should try to preserve them.
980 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
981 return I->getOperand(0);
982
983 // If the RHS is a constant, see if we can simplify it.
985 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth)))
986 return I;
987
988 // Combine:
989 // (ptrmask (getelementptr i8, ptr p, imm i), imm mask)
990 // -> (ptrmask (getelementptr i8, ptr p, imm (i & mask)), imm mask)
991 // where only the low bits known to be zero in the pointer are changed
992 Value *InnerPtr;
993 uint64_t GEPIndex;
994 uint64_t PtrMaskImmediate;
995 if (match(I, m_Intrinsic<Intrinsic::ptrmask>(
996 m_PtrAdd(m_Value(InnerPtr), m_ConstantInt(GEPIndex)),
997 m_ConstantInt(PtrMaskImmediate)))) {
998
999 LHSKnown = computeKnownBits(InnerPtr, Depth + 1, I);
1000 if (!LHSKnown.isZero()) {
1001 const unsigned trailingZeros = LHSKnown.countMinTrailingZeros();
1002 uint64_t PointerAlignBits = (uint64_t(1) << trailingZeros) - 1;
1003
1004 uint64_t HighBitsGEPIndex = GEPIndex & ~PointerAlignBits;
1005 uint64_t MaskedLowBitsGEPIndex =
1006 GEPIndex & PointerAlignBits & PtrMaskImmediate;
1007
1008 uint64_t MaskedGEPIndex = HighBitsGEPIndex | MaskedLowBitsGEPIndex;
1009
1010 if (MaskedGEPIndex != GEPIndex) {
1011 auto *GEP = cast<GetElementPtrInst>(II->getArgOperand(0));
1013 Type *GEPIndexType =
1014 DL.getIndexType(GEP->getPointerOperand()->getType());
1015 Value *MaskedGEP = Builder.CreateGEP(
1016 GEP->getSourceElementType(), InnerPtr,
1017 ConstantInt::get(GEPIndexType, MaskedGEPIndex),
1018 GEP->getName(), GEP->isInBounds());
1019
1020 replaceOperand(*I, 0, MaskedGEP);
1021 return I;
1022 }
1023 }
1024 }
1025
1026 break;
1027 }
1028
1029 case Intrinsic::fshr:
1030 case Intrinsic::fshl: {
1031 const APInt *SA;
1032 if (!match(I->getOperand(2), m_APInt(SA)))
1033 break;
1034
1035 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
1036 // defined, so no need to special-case zero shifts here.
1037 uint64_t ShiftAmt = SA->urem(BitWidth);
1038 if (II->getIntrinsicID() == Intrinsic::fshr)
1039 ShiftAmt = BitWidth - ShiftAmt;
1040
1041 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
1042 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
1043 if (I->getOperand(0) != I->getOperand(1)) {
1044 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown,
1045 Depth + 1, Q) ||
1046 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1,
1047 Q))
1048 return I;
1049 } else { // fshl is a rotate
1050 // Avoid converting rotate into funnel shift.
1051 // Only simplify if one operand is constant.
1052 LHSKnown = computeKnownBits(I->getOperand(0), Depth + 1, I);
1053 if (DemandedMaskLHS.isSubsetOf(LHSKnown.Zero | LHSKnown.One) &&
1054 !match(I->getOperand(0), m_SpecificInt(LHSKnown.One))) {
1055 replaceOperand(*I, 0, Constant::getIntegerValue(VTy, LHSKnown.One));
1056 return I;
1057 }
1058
1059 RHSKnown = computeKnownBits(I->getOperand(1), Depth + 1, I);
1060 if (DemandedMaskRHS.isSubsetOf(RHSKnown.Zero | RHSKnown.One) &&
1061 !match(I->getOperand(1), m_SpecificInt(RHSKnown.One))) {
1062 replaceOperand(*I, 1, Constant::getIntegerValue(VTy, RHSKnown.One));
1063 return I;
1064 }
1065 }
1066
1067 Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
1068 RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
1069 Known.One = LHSKnown.One.shl(ShiftAmt) |
1070 RHSKnown.One.lshr(BitWidth - ShiftAmt);
1071 KnownBitsComputed = true;
1072 break;
1073 }
1074 case Intrinsic::umax: {
1075 // UMax(A, C) == A if ...
1076 // The lowest non-zero bit of DemandMask is higher than the highest
1077 // non-zero bit of C.
1078 const APInt *C;
1079 unsigned CTZ = DemandedMask.countr_zero();
1080 if (match(II->getArgOperand(1), m_APInt(C)) &&
1081 CTZ >= C->getActiveBits())
1082 return II->getArgOperand(0);
1083 break;
1084 }
1085 case Intrinsic::umin: {
1086 // UMin(A, C) == A if ...
1087 // The lowest non-zero bit of DemandMask is higher than the highest
1088 // non-one bit of C.
1089 // This comes from using DeMorgans on the above umax example.
1090 const APInt *C;
1091 unsigned CTZ = DemandedMask.countr_zero();
1092 if (match(II->getArgOperand(1), m_APInt(C)) &&
1093 CTZ >= C->getBitWidth() - C->countl_one())
1094 return II->getArgOperand(0);
1095 break;
1096 }
1097 default: {
1098 // Handle target specific intrinsics
1099 std::optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
1100 *II, DemandedMask, Known, KnownBitsComputed);
1101 if (V)
1102 return *V;
1103 break;
1104 }
1105 }
1106 }
1107
1108 if (!KnownBitsComputed)
1109 llvm::computeKnownBits(I, Known, Depth, Q);
1110 break;
1111 }
1112 }
1113
1114 if (I->getType()->isPointerTy()) {
1115 Align Alignment = I->getPointerAlignment(DL);
1116 Known.Zero.setLowBits(Log2(Alignment));
1117 }
1118
1119 // If the client is only demanding bits that we know, return the known
1120 // constant. We can't directly simplify pointers as a constant because of
1121 // pointer provenance.
1122 // TODO: We could return `(inttoptr const)` for pointers.
1123 if (!I->getType()->isPointerTy() &&
1124 DemandedMask.isSubsetOf(Known.Zero | Known.One))
1125 return Constant::getIntegerValue(VTy, Known.One);
1126
1127 if (VerifyKnownBits) {
1128 KnownBits ReferenceKnown = llvm::computeKnownBits(I, Depth, Q);
1129 if (Known != ReferenceKnown) {
1130 errs() << "Mismatched known bits for " << *I << " in "
1131 << I->getFunction()->getName() << "\n";
1132 errs() << "computeKnownBits(): " << ReferenceKnown << "\n";
1133 errs() << "SimplifyDemandedBits(): " << Known << "\n";
1134 std::abort();
1135 }
1136 }
1137
1138 return nullptr;
1139}
1140
1141/// Helper routine of SimplifyDemandedUseBits. It computes Known
1142/// bits. It also tries to handle simplifications that can be done based on
1143/// DemandedMask, but without modifying the Instruction.
1145 Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth,
1146 const SimplifyQuery &Q) {
1147 unsigned BitWidth = DemandedMask.getBitWidth();
1148 Type *ITy = I->getType();
1149
1150 KnownBits LHSKnown(BitWidth);
1151 KnownBits RHSKnown(BitWidth);
1152
1153 // Despite the fact that we can't simplify this instruction in all User's
1154 // context, we can at least compute the known bits, and we can
1155 // do simplifications that apply to *just* the one user if we know that
1156 // this instruction has a simpler value in that context.
1157 switch (I->getOpcode()) {
1158 case Instruction::And: {
1159 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, Q);
1160 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, Q);
1161 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1162 Depth, Q);
1164
1165 // If the client is only demanding bits that we know, return the known
1166 // constant.
1167 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1168 return Constant::getIntegerValue(ITy, Known.One);
1169
1170 // If all of the demanded bits are known 1 on one side, return the other.
1171 // These bits cannot contribute to the result of the 'and' in this context.
1172 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
1173 return I->getOperand(0);
1174 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
1175 return I->getOperand(1);
1176
1177 break;
1178 }
1179 case Instruction::Or: {
1180 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, Q);
1181 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, Q);
1182 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1183 Depth, Q);
1185
1186 // If the client is only demanding bits that we know, return the known
1187 // constant.
1188 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1189 return Constant::getIntegerValue(ITy, Known.One);
1190
1191 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1192 // only bits from X or Y are demanded.
1193 // If all of the demanded bits are known zero on one side, return the other.
1194 // These bits cannot contribute to the result of the 'or' in this context.
1195 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
1196 return I->getOperand(0);
1197 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1198 return I->getOperand(1);
1199
1200 break;
1201 }
1202 case Instruction::Xor: {
1203 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, Q);
1204 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, Q);
1205 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1206 Depth, Q);
1208
1209 // If the client is only demanding bits that we know, return the known
1210 // constant.
1211 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1212 return Constant::getIntegerValue(ITy, Known.One);
1213
1214 // We can simplify (X^Y) -> X or Y in the user's context if we know that
1215 // only bits from X or Y are demanded.
1216 // If all of the demanded bits are known zero on one side, return the other.
1217 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1218 return I->getOperand(0);
1219 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1220 return I->getOperand(1);
1221
1222 break;
1223 }
1224 case Instruction::Add: {
1225 unsigned NLZ = DemandedMask.countl_zero();
1226 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1227
1228 // If an operand adds zeros to every bit below the highest demanded bit,
1229 // that operand doesn't change the result. Return the other side.
1230 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, Q);
1231 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1232 return I->getOperand(0);
1233
1234 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, Q);
1235 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
1236 return I->getOperand(1);
1237
1238 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1239 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1240 Known =
1241 KnownBits::computeForAddSub(/*Add=*/true, NSW, NUW, LHSKnown, RHSKnown);
1243 break;
1244 }
1245 case Instruction::Sub: {
1246 unsigned NLZ = DemandedMask.countl_zero();
1247 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1248
1249 // If an operand subtracts zeros from every bit below the highest demanded
1250 // bit, that operand doesn't change the result. Return the other side.
1251 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, Q);
1252 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1253 return I->getOperand(0);
1254
1255 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1256 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1257 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, Q);
1258 Known = KnownBits::computeForAddSub(/*Add=*/false, NSW, NUW, LHSKnown,
1259 RHSKnown);
1261 break;
1262 }
1263 case Instruction::AShr: {
1264 // Compute the Known bits to simplify things downstream.
1265 llvm::computeKnownBits(I, Known, Depth, Q);
1266
1267 // If this user is only demanding bits that we know, return the known
1268 // constant.
1269 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1270 return Constant::getIntegerValue(ITy, Known.One);
1271
1272 // If the right shift operand 0 is a result of a left shift by the same
1273 // amount, this is probably a zero/sign extension, which may be unnecessary,
1274 // if we do not demand any of the new sign bits. So, return the original
1275 // operand instead.
1276 const APInt *ShiftRC;
1277 const APInt *ShiftLC;
1278 Value *X;
1279 unsigned BitWidth = DemandedMask.getBitWidth();
1280 if (match(I,
1281 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1282 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1283 DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1284 BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1285 return X;
1286 }
1287
1288 break;
1289 }
1290 default:
1291 // Compute the Known bits to simplify things downstream.
1292 llvm::computeKnownBits(I, Known, Depth, Q);
1293
1294 // If this user is only demanding bits that we know, return the known
1295 // constant.
1296 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1297 return Constant::getIntegerValue(ITy, Known.One);
1298
1299 break;
1300 }
1301
1302 return nullptr;
1303}
1304
1305/// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1306/// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1307/// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1308/// of "C2-C1".
1309///
1310/// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1311/// ..., bn}, without considering the specific value X is holding.
1312/// This transformation is legal iff one of following conditions is hold:
1313/// 1) All the bit in S are 0, in this case E1 == E2.
1314/// 2) We don't care those bits in S, per the input DemandedMask.
1315/// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1316/// rest bits.
1317///
1318/// Currently we only test condition 2).
1319///
1320/// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1321/// not successful.
1323 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1324 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1325 if (!ShlOp1 || !ShrOp1)
1326 return nullptr; // No-op.
1327
1328 Value *VarX = Shr->getOperand(0);
1329 Type *Ty = VarX->getType();
1330 unsigned BitWidth = Ty->getScalarSizeInBits();
1331 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1332 return nullptr; // Undef.
1333
1334 unsigned ShlAmt = ShlOp1.getZExtValue();
1335 unsigned ShrAmt = ShrOp1.getZExtValue();
1336
1337 Known.One.clearAllBits();
1338 Known.Zero.setLowBits(ShlAmt - 1);
1339 Known.Zero &= DemandedMask;
1340
1341 APInt BitMask1(APInt::getAllOnes(BitWidth));
1342 APInt BitMask2(APInt::getAllOnes(BitWidth));
1343
1344 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1345 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1346 (BitMask1.ashr(ShrAmt) << ShlAmt);
1347
1348 if (ShrAmt <= ShlAmt) {
1349 BitMask2 <<= (ShlAmt - ShrAmt);
1350 } else {
1351 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1352 BitMask2.ashr(ShrAmt - ShlAmt);
1353 }
1354
1355 // Check if condition-2 (see the comment to this function) is satified.
1356 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1357 if (ShrAmt == ShlAmt)
1358 return VarX;
1359
1360 if (!Shr->hasOneUse())
1361 return nullptr;
1362
1363 BinaryOperator *New;
1364 if (ShrAmt < ShlAmt) {
1365 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1366 New = BinaryOperator::CreateShl(VarX, Amt);
1367 BinaryOperator *Orig = cast<BinaryOperator>(Shl);
1368 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1369 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1370 } else {
1371 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1372 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1373 BinaryOperator::CreateAShr(VarX, Amt);
1374 if (cast<BinaryOperator>(Shr)->isExact())
1375 New->setIsExact(true);
1376 }
1377
1378 return InsertNewInstWith(New, Shl->getIterator());
1379 }
1380
1381 return nullptr;
1382}
1383
1384/// The specified value produces a vector with any number of elements.
1385/// This method analyzes which elements of the operand are poison and
1386/// returns that information in PoisonElts.
1387///
1388/// DemandedElts contains the set of elements that are actually used by the
1389/// caller, and by default (AllowMultipleUsers equals false) the value is
1390/// simplified only if it has a single caller. If AllowMultipleUsers is set
1391/// to true, DemandedElts refers to the union of sets of elements that are
1392/// used by all callers.
1393///
1394/// If the information about demanded elements can be used to simplify the
1395/// operation, the operation is simplified, then the resultant value is
1396/// returned. This returns null if no change was made.
1398 APInt DemandedElts,
1399 APInt &PoisonElts,
1400 unsigned Depth,
1401 bool AllowMultipleUsers) {
1402 // Cannot analyze scalable type. The number of vector elements is not a
1403 // compile-time constant.
1404 if (isa<ScalableVectorType>(V->getType()))
1405 return nullptr;
1406
1407 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1408 APInt EltMask(APInt::getAllOnes(VWidth));
1409 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1410
1411 if (match(V, m_Poison())) {
1412 // If the entire vector is poison, just return this info.
1413 PoisonElts = EltMask;
1414 return nullptr;
1415 }
1416
1417 if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1418 PoisonElts = EltMask;
1419 return PoisonValue::get(V->getType());
1420 }
1421
1422 PoisonElts = 0;
1423
1424 if (auto *C = dyn_cast<Constant>(V)) {
1425 // Check if this is identity. If so, return 0 since we are not simplifying
1426 // anything.
1427 if (DemandedElts.isAllOnes())
1428 return nullptr;
1429
1430 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1431 Constant *Poison = PoisonValue::get(EltTy);
1433 for (unsigned i = 0; i != VWidth; ++i) {
1434 if (!DemandedElts[i]) { // If not demanded, set to poison.
1435 Elts.push_back(Poison);
1436 PoisonElts.setBit(i);
1437 continue;
1438 }
1439
1440 Constant *Elt = C->getAggregateElement(i);
1441 if (!Elt) return nullptr;
1442
1443 Elts.push_back(Elt);
1444 if (isa<PoisonValue>(Elt)) // Already poison.
1445 PoisonElts.setBit(i);
1446 }
1447
1448 // If we changed the constant, return it.
1449 Constant *NewCV = ConstantVector::get(Elts);
1450 return NewCV != C ? NewCV : nullptr;
1451 }
1452
1453 // Limit search depth.
1454 if (Depth == 10)
1455 return nullptr;
1456
1457 if (!AllowMultipleUsers) {
1458 // If multiple users are using the root value, proceed with
1459 // simplification conservatively assuming that all elements
1460 // are needed.
1461 if (!V->hasOneUse()) {
1462 // Quit if we find multiple users of a non-root value though.
1463 // They'll be handled when it's their turn to be visited by
1464 // the main instcombine process.
1465 if (Depth != 0)
1466 // TODO: Just compute the PoisonElts information recursively.
1467 return nullptr;
1468
1469 // Conservatively assume that all elements are needed.
1470 DemandedElts = EltMask;
1471 }
1472 }
1473
1474 Instruction *I = dyn_cast<Instruction>(V);
1475 if (!I) return nullptr; // Only analyze instructions.
1476
1477 bool MadeChange = false;
1478 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1479 APInt Demanded, APInt &Undef) {
1480 auto *II = dyn_cast<IntrinsicInst>(Inst);
1481 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1482 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1483 replaceOperand(*Inst, OpNum, V);
1484 MadeChange = true;
1485 }
1486 };
1487
1488 APInt PoisonElts2(VWidth, 0);
1489 APInt PoisonElts3(VWidth, 0);
1490 switch (I->getOpcode()) {
1491 default: break;
1492
1493 case Instruction::GetElementPtr: {
1494 // The LangRef requires that struct geps have all constant indices. As
1495 // such, we can't convert any operand to partial undef.
1496 auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1497 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1498 I != E; I++)
1499 if (I.isStruct())
1500 return true;
1501 return false;
1502 };
1503 if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1504 break;
1505
1506 // Conservatively track the demanded elements back through any vector
1507 // operands we may have. We know there must be at least one, or we
1508 // wouldn't have a vector result to get here. Note that we intentionally
1509 // merge the undef bits here since gepping with either an poison base or
1510 // index results in poison.
1511 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1512 if (i == 0 ? match(I->getOperand(i), m_Undef())
1513 : match(I->getOperand(i), m_Poison())) {
1514 // If the entire vector is undefined, just return this info.
1515 PoisonElts = EltMask;
1516 return nullptr;
1517 }
1518 if (I->getOperand(i)->getType()->isVectorTy()) {
1519 APInt PoisonEltsOp(VWidth, 0);
1520 simplifyAndSetOp(I, i, DemandedElts, PoisonEltsOp);
1521 // gep(x, undef) is not undef, so skip considering idx ops here
1522 // Note that we could propagate poison, but we can't distinguish between
1523 // undef & poison bits ATM
1524 if (i == 0)
1525 PoisonElts |= PoisonEltsOp;
1526 }
1527 }
1528
1529 break;
1530 }
1531 case Instruction::InsertElement: {
1532 // If this is a variable index, we don't know which element it overwrites.
1533 // demand exactly the same input as we produce.
1534 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1535 if (!Idx) {
1536 // Note that we can't propagate undef elt info, because we don't know
1537 // which elt is getting updated.
1538 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts2);
1539 break;
1540 }
1541
1542 // The element inserted overwrites whatever was there, so the input demanded
1543 // set is simpler than the output set.
1544 unsigned IdxNo = Idx->getZExtValue();
1545 APInt PreInsertDemandedElts = DemandedElts;
1546 if (IdxNo < VWidth)
1547 PreInsertDemandedElts.clearBit(IdxNo);
1548
1549 // If we only demand the element that is being inserted and that element
1550 // was extracted from the same index in another vector with the same type,
1551 // replace this insert with that other vector.
1552 // Note: This is attempted before the call to simplifyAndSetOp because that
1553 // may change PoisonElts to a value that does not match with Vec.
1554 Value *Vec;
1555 if (PreInsertDemandedElts == 0 &&
1556 match(I->getOperand(1),
1557 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1558 Vec->getType() == I->getType()) {
1559 return Vec;
1560 }
1561
1562 simplifyAndSetOp(I, 0, PreInsertDemandedElts, PoisonElts);
1563
1564 // If this is inserting an element that isn't demanded, remove this
1565 // insertelement.
1566 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1567 Worklist.push(I);
1568 return I->getOperand(0);
1569 }
1570
1571 // The inserted element is defined.
1572 PoisonElts.clearBit(IdxNo);
1573 break;
1574 }
1575 case Instruction::ShuffleVector: {
1576 auto *Shuffle = cast<ShuffleVectorInst>(I);
1577 assert(Shuffle->getOperand(0)->getType() ==
1578 Shuffle->getOperand(1)->getType() &&
1579 "Expected shuffle operands to have same type");
1580 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1581 ->getNumElements();
1582 // Handle trivial case of a splat. Only check the first element of LHS
1583 // operand.
1584 if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1585 DemandedElts.isAllOnes()) {
1586 if (!isa<PoisonValue>(I->getOperand(1))) {
1587 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1588 MadeChange = true;
1589 }
1590 APInt LeftDemanded(OpWidth, 1);
1591 APInt LHSPoisonElts(OpWidth, 0);
1592 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1593 if (LHSPoisonElts[0])
1594 PoisonElts = EltMask;
1595 else
1596 PoisonElts.clearAllBits();
1597 break;
1598 }
1599
1600 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1601 for (unsigned i = 0; i < VWidth; i++) {
1602 if (DemandedElts[i]) {
1603 unsigned MaskVal = Shuffle->getMaskValue(i);
1604 if (MaskVal != -1u) {
1605 assert(MaskVal < OpWidth * 2 &&
1606 "shufflevector mask index out of range!");
1607 if (MaskVal < OpWidth)
1608 LeftDemanded.setBit(MaskVal);
1609 else
1610 RightDemanded.setBit(MaskVal - OpWidth);
1611 }
1612 }
1613 }
1614
1615 APInt LHSPoisonElts(OpWidth, 0);
1616 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1617
1618 APInt RHSPoisonElts(OpWidth, 0);
1619 simplifyAndSetOp(I, 1, RightDemanded, RHSPoisonElts);
1620
1621 // If this shuffle does not change the vector length and the elements
1622 // demanded by this shuffle are an identity mask, then this shuffle is
1623 // unnecessary.
1624 //
1625 // We are assuming canonical form for the mask, so the source vector is
1626 // operand 0 and operand 1 is not used.
1627 //
1628 // Note that if an element is demanded and this shuffle mask is undefined
1629 // for that element, then the shuffle is not considered an identity
1630 // operation. The shuffle prevents poison from the operand vector from
1631 // leaking to the result by replacing poison with an undefined value.
1632 if (VWidth == OpWidth) {
1633 bool IsIdentityShuffle = true;
1634 for (unsigned i = 0; i < VWidth; i++) {
1635 unsigned MaskVal = Shuffle->getMaskValue(i);
1636 if (DemandedElts[i] && i != MaskVal) {
1637 IsIdentityShuffle = false;
1638 break;
1639 }
1640 }
1641 if (IsIdentityShuffle)
1642 return Shuffle->getOperand(0);
1643 }
1644
1645 bool NewPoisonElts = false;
1646 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1647 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1648 bool LHSUniform = true;
1649 bool RHSUniform = true;
1650 for (unsigned i = 0; i < VWidth; i++) {
1651 unsigned MaskVal = Shuffle->getMaskValue(i);
1652 if (MaskVal == -1u) {
1653 PoisonElts.setBit(i);
1654 } else if (!DemandedElts[i]) {
1655 NewPoisonElts = true;
1656 PoisonElts.setBit(i);
1657 } else if (MaskVal < OpWidth) {
1658 if (LHSPoisonElts[MaskVal]) {
1659 NewPoisonElts = true;
1660 PoisonElts.setBit(i);
1661 } else {
1662 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1663 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1664 LHSUniform = LHSUniform && (MaskVal == i);
1665 }
1666 } else {
1667 if (RHSPoisonElts[MaskVal - OpWidth]) {
1668 NewPoisonElts = true;
1669 PoisonElts.setBit(i);
1670 } else {
1671 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1672 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1673 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1674 }
1675 }
1676 }
1677
1678 // Try to transform shuffle with constant vector and single element from
1679 // this constant vector to single insertelement instruction.
1680 // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1681 // insertelement V, C[ci], ci-n
1682 if (OpWidth ==
1683 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1684 Value *Op = nullptr;
1685 Constant *Value = nullptr;
1686 unsigned Idx = -1u;
1687
1688 // Find constant vector with the single element in shuffle (LHS or RHS).
1689 if (LHSIdx < OpWidth && RHSUniform) {
1690 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1691 Op = Shuffle->getOperand(1);
1692 Value = CV->getOperand(LHSValIdx);
1693 Idx = LHSIdx;
1694 }
1695 }
1696 if (RHSIdx < OpWidth && LHSUniform) {
1697 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1698 Op = Shuffle->getOperand(0);
1699 Value = CV->getOperand(RHSValIdx);
1700 Idx = RHSIdx;
1701 }
1702 }
1703 // Found constant vector with single element - convert to insertelement.
1704 if (Op && Value) {
1706 Op, Value, ConstantInt::get(Type::getInt64Ty(I->getContext()), Idx),
1707 Shuffle->getName());
1708 InsertNewInstWith(New, Shuffle->getIterator());
1709 return New;
1710 }
1711 }
1712 if (NewPoisonElts) {
1713 // Add additional discovered undefs.
1715 for (unsigned i = 0; i < VWidth; ++i) {
1716 if (PoisonElts[i])
1718 else
1719 Elts.push_back(Shuffle->getMaskValue(i));
1720 }
1721 Shuffle->setShuffleMask(Elts);
1722 MadeChange = true;
1723 }
1724 break;
1725 }
1726 case Instruction::Select: {
1727 // If this is a vector select, try to transform the select condition based
1728 // on the current demanded elements.
1729 SelectInst *Sel = cast<SelectInst>(I);
1730 if (Sel->getCondition()->getType()->isVectorTy()) {
1731 // TODO: We are not doing anything with PoisonElts based on this call.
1732 // It is overwritten below based on the other select operands. If an
1733 // element of the select condition is known undef, then we are free to
1734 // choose the output value from either arm of the select. If we know that
1735 // one of those values is undef, then the output can be undef.
1736 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1737 }
1738
1739 // Next, see if we can transform the arms of the select.
1740 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1741 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1742 for (unsigned i = 0; i < VWidth; i++) {
1743 // isNullValue() always returns false when called on a ConstantExpr.
1744 // Skip constant expressions to avoid propagating incorrect information.
1745 Constant *CElt = CV->getAggregateElement(i);
1746 if (isa<ConstantExpr>(CElt))
1747 continue;
1748 // TODO: If a select condition element is undef, we can demand from
1749 // either side. If one side is known undef, choosing that side would
1750 // propagate undef.
1751 if (CElt->isNullValue())
1752 DemandedLHS.clearBit(i);
1753 else
1754 DemandedRHS.clearBit(i);
1755 }
1756 }
1757
1758 simplifyAndSetOp(I, 1, DemandedLHS, PoisonElts2);
1759 simplifyAndSetOp(I, 2, DemandedRHS, PoisonElts3);
1760
1761 // Output elements are undefined if the element from each arm is undefined.
1762 // TODO: This can be improved. See comment in select condition handling.
1763 PoisonElts = PoisonElts2 & PoisonElts3;
1764 break;
1765 }
1766 case Instruction::BitCast: {
1767 // Vector->vector casts only.
1768 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1769 if (!VTy) break;
1770 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1771 APInt InputDemandedElts(InVWidth, 0);
1772 PoisonElts2 = APInt(InVWidth, 0);
1773 unsigned Ratio;
1774
1775 if (VWidth == InVWidth) {
1776 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1777 // elements as are demanded of us.
1778 Ratio = 1;
1779 InputDemandedElts = DemandedElts;
1780 } else if ((VWidth % InVWidth) == 0) {
1781 // If the number of elements in the output is a multiple of the number of
1782 // elements in the input then an input element is live if any of the
1783 // corresponding output elements are live.
1784 Ratio = VWidth / InVWidth;
1785 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1786 if (DemandedElts[OutIdx])
1787 InputDemandedElts.setBit(OutIdx / Ratio);
1788 } else if ((InVWidth % VWidth) == 0) {
1789 // If the number of elements in the input is a multiple of the number of
1790 // elements in the output then an input element is live if the
1791 // corresponding output element is live.
1792 Ratio = InVWidth / VWidth;
1793 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1794 if (DemandedElts[InIdx / Ratio])
1795 InputDemandedElts.setBit(InIdx);
1796 } else {
1797 // Unsupported so far.
1798 break;
1799 }
1800
1801 simplifyAndSetOp(I, 0, InputDemandedElts, PoisonElts2);
1802
1803 if (VWidth == InVWidth) {
1804 PoisonElts = PoisonElts2;
1805 } else if ((VWidth % InVWidth) == 0) {
1806 // If the number of elements in the output is a multiple of the number of
1807 // elements in the input then an output element is undef if the
1808 // corresponding input element is undef.
1809 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1810 if (PoisonElts2[OutIdx / Ratio])
1811 PoisonElts.setBit(OutIdx);
1812 } else if ((InVWidth % VWidth) == 0) {
1813 // If the number of elements in the input is a multiple of the number of
1814 // elements in the output then an output element is undef if all of the
1815 // corresponding input elements are undef.
1816 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1817 APInt SubUndef = PoisonElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1818 if (SubUndef.popcount() == Ratio)
1819 PoisonElts.setBit(OutIdx);
1820 }
1821 } else {
1822 llvm_unreachable("Unimp");
1823 }
1824 break;
1825 }
1826 case Instruction::FPTrunc:
1827 case Instruction::FPExt:
1828 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1829 break;
1830
1831 case Instruction::Call: {
1832 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1833 if (!II) break;
1834 switch (II->getIntrinsicID()) {
1835 case Intrinsic::masked_gather: // fallthrough
1836 case Intrinsic::masked_load: {
1837 // Subtlety: If we load from a pointer, the pointer must be valid
1838 // regardless of whether the element is demanded. Doing otherwise risks
1839 // segfaults which didn't exist in the original program.
1840 APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1841 DemandedPassThrough(DemandedElts);
1842 if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
1843 for (unsigned i = 0; i < VWidth; i++) {
1844 Constant *CElt = CV->getAggregateElement(i);
1845 if (CElt->isNullValue())
1846 DemandedPtrs.clearBit(i);
1847 else if (CElt->isAllOnesValue())
1848 DemandedPassThrough.clearBit(i);
1849 }
1850 if (II->getIntrinsicID() == Intrinsic::masked_gather)
1851 simplifyAndSetOp(II, 0, DemandedPtrs, PoisonElts2);
1852 simplifyAndSetOp(II, 3, DemandedPassThrough, PoisonElts3);
1853
1854 // Output elements are undefined if the element from both sources are.
1855 // TODO: can strengthen via mask as well.
1856 PoisonElts = PoisonElts2 & PoisonElts3;
1857 break;
1858 }
1859 default: {
1860 // Handle target specific intrinsics
1861 std::optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1862 *II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
1863 simplifyAndSetOp);
1864 if (V)
1865 return *V;
1866 break;
1867 }
1868 } // switch on IntrinsicID
1869 break;
1870 } // case Call
1871 } // switch on Opcode
1872
1873 // TODO: We bail completely on integer div/rem and shifts because they have
1874 // UB/poison potential, but that should be refined.
1875 BinaryOperator *BO;
1876 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1877 Value *X = BO->getOperand(0);
1878 Value *Y = BO->getOperand(1);
1879
1880 // Look for an equivalent binop except that one operand has been shuffled.
1881 // If the demand for this binop only includes elements that are the same as
1882 // the other binop, then we may be able to replace this binop with a use of
1883 // the earlier one.
1884 //
1885 // Example:
1886 // %other_bo = bo (shuf X, {0}), Y
1887 // %this_extracted_bo = extelt (bo X, Y), 0
1888 // -->
1889 // %other_bo = bo (shuf X, {0}), Y
1890 // %this_extracted_bo = extelt %other_bo, 0
1891 //
1892 // TODO: Handle demand of an arbitrary single element or more than one
1893 // element instead of just element 0.
1894 // TODO: Unlike general demanded elements transforms, this should be safe
1895 // for any (div/rem/shift) opcode too.
1896 if (DemandedElts == 1 && !X->hasOneUse() && !Y->hasOneUse() &&
1897 BO->hasOneUse() ) {
1898
1899 auto findShufBO = [&](bool MatchShufAsOp0) -> User * {
1900 // Try to use shuffle-of-operand in place of an operand:
1901 // bo X, Y --> bo (shuf X), Y
1902 // bo X, Y --> bo X, (shuf Y)
1903 BinaryOperator::BinaryOps Opcode = BO->getOpcode();
1904 Value *ShufOp = MatchShufAsOp0 ? X : Y;
1905 Value *OtherOp = MatchShufAsOp0 ? Y : X;
1906 for (User *U : OtherOp->users()) {
1907 ArrayRef<int> Mask;
1908 auto Shuf = m_Shuffle(m_Specific(ShufOp), m_Value(), m_Mask(Mask));
1909 if (BO->isCommutative()
1910 ? match(U, m_c_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
1911 : MatchShufAsOp0
1912 ? match(U, m_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
1913 : match(U, m_BinOp(Opcode, m_Specific(OtherOp), Shuf)))
1914 if (match(Mask, m_ZeroMask()) && Mask[0] != PoisonMaskElem)
1915 if (DT.dominates(U, I))
1916 return U;
1917 }
1918 return nullptr;
1919 };
1920
1921 if (User *ShufBO = findShufBO(/* MatchShufAsOp0 */ true))
1922 return ShufBO;
1923 if (User *ShufBO = findShufBO(/* MatchShufAsOp0 */ false))
1924 return ShufBO;
1925 }
1926
1927 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1928 simplifyAndSetOp(I, 1, DemandedElts, PoisonElts2);
1929
1930 // Output elements are undefined if both are undefined. Consider things
1931 // like undef & 0. The result is known zero, not undef.
1932 PoisonElts &= PoisonElts2;
1933 }
1934
1935 // If we've proven all of the lanes poison, return a poison value.
1936 // TODO: Intersect w/demanded lanes
1937 if (PoisonElts.isAllOnes())
1938 return PoisonValue::get(I->getType());
1939
1940 return MadeChange ? I : nullptr;
1941}
1942
1943/// For floating-point classes that resolve to a single bit pattern, return that
1944/// value.
1946 switch (Mask) {
1947 case fcPosZero:
1948 return ConstantFP::getZero(Ty);
1949 case fcNegZero:
1950 return ConstantFP::getZero(Ty, true);
1951 case fcPosInf:
1952 return ConstantFP::getInfinity(Ty);
1953 case fcNegInf:
1954 return ConstantFP::getInfinity(Ty, true);
1955 case fcNone:
1956 return PoisonValue::get(Ty);
1957 default:
1958 return nullptr;
1959 }
1960}
1961
1963 Value *V, const FPClassTest DemandedMask, KnownFPClass &Known,
1964 unsigned Depth, Instruction *CxtI) {
1965 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1966 Type *VTy = V->getType();
1967
1968 assert(Known == KnownFPClass() && "expected uninitialized state");
1969
1970 if (DemandedMask == fcNone)
1971 return isa<UndefValue>(V) ? nullptr : PoisonValue::get(VTy);
1972
1974 return nullptr;
1975
1976 Instruction *I = dyn_cast<Instruction>(V);
1977 if (!I) {
1978 // Handle constants and arguments
1979 Known = computeKnownFPClass(V, fcAllFlags, CxtI, Depth + 1);
1980 Value *FoldedToConst =
1981 getFPClassConstant(VTy, DemandedMask & Known.KnownFPClasses);
1982 return FoldedToConst == V ? nullptr : FoldedToConst;
1983 }
1984
1985 if (!I->hasOneUse())
1986 return nullptr;
1987
1988 // TODO: Should account for nofpclass/FastMathFlags on current instruction
1989 switch (I->getOpcode()) {
1990 case Instruction::FNeg: {
1991 if (SimplifyDemandedFPClass(I, 0, llvm::fneg(DemandedMask), Known,
1992 Depth + 1))
1993 return I;
1994 Known.fneg();
1995 break;
1996 }
1997 case Instruction::Call: {
1998 CallInst *CI = cast<CallInst>(I);
1999 switch (CI->getIntrinsicID()) {
2000 case Intrinsic::fabs:
2001 if (SimplifyDemandedFPClass(I, 0, llvm::inverse_fabs(DemandedMask), Known,
2002 Depth + 1))
2003 return I;
2004 Known.fabs();
2005 break;
2006 case Intrinsic::arithmetic_fence:
2007 if (SimplifyDemandedFPClass(I, 0, DemandedMask, Known, Depth + 1))
2008 return I;
2009 break;
2010 case Intrinsic::copysign: {
2011 // Flip on more potentially demanded classes
2012 const FPClassTest DemandedMaskAnySign = llvm::unknown_sign(DemandedMask);
2013 if (SimplifyDemandedFPClass(I, 0, DemandedMaskAnySign, Known, Depth + 1))
2014 return I;
2015
2016 if ((DemandedMask & fcPositive) == fcNone) {
2017 // Roundabout way of replacing with fneg(fabs)
2018 I->setOperand(1, ConstantFP::get(VTy, -1.0));
2019 return I;
2020 }
2021
2022 if ((DemandedMask & fcNegative) == fcNone) {
2023 // Roundabout way of replacing with fabs
2024 I->setOperand(1, ConstantFP::getZero(VTy));
2025 return I;
2026 }
2027
2028 KnownFPClass KnownSign =
2029 computeKnownFPClass(I->getOperand(1), fcAllFlags, CxtI, Depth + 1);
2030 Known.copysign(KnownSign);
2031 break;
2032 }
2033 default:
2034 Known = computeKnownFPClass(I, ~DemandedMask, CxtI, Depth + 1);
2035 break;
2036 }
2037
2038 break;
2039 }
2040 case Instruction::Select: {
2041 KnownFPClass KnownLHS, KnownRHS;
2042 if (SimplifyDemandedFPClass(I, 2, DemandedMask, KnownRHS, Depth + 1) ||
2043 SimplifyDemandedFPClass(I, 1, DemandedMask, KnownLHS, Depth + 1))
2044 return I;
2045
2046 if (KnownLHS.isKnownNever(DemandedMask))
2047 return I->getOperand(2);
2048 if (KnownRHS.isKnownNever(DemandedMask))
2049 return I->getOperand(1);
2050
2051 // TODO: Recognize clamping patterns
2052 Known = KnownLHS | KnownRHS;
2053 break;
2054 }
2055 default:
2056 Known = computeKnownFPClass(I, ~DemandedMask, CxtI, Depth + 1);
2057 break;
2058 }
2059
2060 return getFPClassConstant(VTy, DemandedMask & Known.KnownFPClasses);
2061}
2062
2064 FPClassTest DemandedMask,
2065 KnownFPClass &Known,
2066 unsigned Depth) {
2067 Use &U = I->getOperandUse(OpNo);
2068 Value *NewVal =
2069 SimplifyDemandedUseFPClass(U.get(), DemandedMask, Known, Depth, I);
2070 if (!NewVal)
2071 return false;
2072 if (Instruction *OpInst = dyn_cast<Instruction>(U))
2073 salvageDebugInfo(*OpInst);
2074
2075 replaceUse(U, NewVal);
2076 return true;
2077}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
Hexagon Common GEP
This file provides internal interfaces used to implement the InstCombine.
static Constant * getFPClassConstant(Type *Ty, FPClassTest Mask)
For floating-point classes that resolve to a single bit pattern, return that value.
static cl::opt< bool > VerifyKnownBits("instcombine-verify-known-bits", cl::desc("Verify that computeKnownBits() and " "SimplifyDemandedBits() are consistent"), cl::Hidden, cl::init(false))
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
This file provides the interface for the instcombine pass implementation.
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SI optimize exec mask operations pre RA
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:214
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition: APInt.h:1387
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:209
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1500
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition: APInt.h:1372
unsigned popcount() const
Count the number of bits set.
Definition: APInt.h:1629
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:1002
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1472
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:906
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition: APInt.h:1310
APInt abs() const
Get the absolute value.
Definition: APInt.h:1753
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition: APInt.h:351
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:360
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition: APInt.cpp:1636
void setSignBit()
Set the sign bit to 1.
Definition: APInt.h:1320
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1448
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1091
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition: APInt.h:1229
void clearAllBits()
Set every bit to 0.
Definition: APInt.h:1377
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition: APInt.h:1598
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition: APInt.h:1557
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition: APInt.h:1397
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:455
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:807
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:853
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition: APInt.h:1237
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition: APInt.h:420
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:286
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition: APInt.h:276
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition: APInt.h:1369
bool isOne() const
Determine if this is a value of 1.
Definition: APInt.h:369
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:838
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:831
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1201
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
BinaryOps getOpcode() const
Definition: InstrTypes.h:442
Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:530
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:757
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1084
static Constant * getZero(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1038
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:146
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1399
This is an important base class in LLVM.
Definition: Constant.h:42
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:400
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition: Constants.cpp:107
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:432
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:90
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
Definition: DataLayout.cpp:905
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:915
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:914
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2038
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1442
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition: IRBuilder.h:1871
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1754
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1480
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2012
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1502
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1524
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
KnownFPClass computeKnownFPClass(Value *Val, FastMathFlags FMF, FPClassTest Interested=fcAllFlags, const Instruction *CtxI=nullptr, unsigned Depth=0) const
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
Value * SimplifyDemandedUseBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q)
Attempts to replace I with a simpler value based on the demanded bits.
std::optional< std::pair< Intrinsic::ID, SmallVector< Value *, 3 > > > convertOrOfShiftsToFunnelShift(Instruction &Or)
Value * SimplifyMultipleUseDemandedBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q)
Helper routine of SimplifyDemandedUseBits.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
Value * simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1, Instruction *Shl, const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known)
Helper routine of SimplifyDemandedUseBits.
Value * SimplifyDemandedUseFPClass(Value *V, FPClassTest DemandedMask, KnownFPClass &Known, unsigned Depth, Instruction *CxtI)
Attempts to replace V with a simpler value based on the demanded floating-point classes.
bool SimplifyDemandedFPClass(Instruction *I, unsigned Op, FPClassTest DemandedMask, KnownFPClass &Known, unsigned Depth=0)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
SimplifyQuery SQ
Definition: InstCombiner.h:76
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:386
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
Definition: InstCombiner.h:418
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Definition: InstCombiner.h:64
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
Definition: InstCombiner.h:375
const DataLayout & DL
Definition: InstCombiner.h:75
unsigned ComputeNumSignBits(const Value *Op, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:452
std::optional< Value * > targetSimplifyDemandedVectorEltsIntrinsic(IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:410
DominatorTree & DT
Definition: InstCombiner.h:74
std::optional< Value * > targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:431
BuilderTy & Builder
Definition: InstCombiner.h:60
void push(Instruction *I)
Push the instruction onto the worklist stack.
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
bool isShift() const
Definition: Instruction.h:281
bool isIntDivRem() const
Definition: Instruction.h:280
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition: Operator.h:110
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition: Operator.h:104
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1852
This class represents the LLVM 'select' instruction.
const Value * getCondition() const
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:234
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static IntegerType * getInt64Ty(LLVMContext &C)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1833
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
iterator_range< user_iterator > users()
Definition: Value.h:421
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
Base class of all SIMD vector types.
Definition: DerivedTypes.h:403
This class represents zero extension of integer types.
self_iterator getIterator()
Definition: ilist_node.h:132
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1513
class_match< PoisonValue > m_Poison()
Match an arbitrary poison constant.
Definition: PatternMatch.h:160
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:972
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:875
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:168
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
match_combine_and< class_match< Constant >, match_unless< constantexpr_match > > m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
Definition: PatternMatch.h:854
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:612
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition: bit.h:307
void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition: Utils.cpp:1671
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition: MathExtras.h:547
gep_type_iterator gep_type_end(const User *GEP)
void computeKnownBitsFromContext(const Value *V, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q)
Merge bits known from context-dependent facts into Known.
KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, unsigned Depth, const SimplifyQuery &SQ)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
constexpr unsigned MaxAnalysisRecursionDepth
Definition: ValueTracking.h:48
FPClassTest fneg(FPClassTest Mask)
Return the test mask which returns true if the value's sign bit is flipped.
void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, unsigned Depth, const SimplifyQuery &Q)
Adjust Known for the given select Arm to include information from the select Cond.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
FPClassTest inverse_fabs(FPClassTest Mask)
Return the test mask which returns true after fabs is applied to the value.
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
FPClassTest unknown_sign(FPClassTest Mask)
Return the test mask which returns true if the value could have the same set of classes,...
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
gep_type_iterator gep_type_begin(const User *GEP)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition: KnownBits.h:290
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition: KnownBits.h:175
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:97
void makeNonNegative()
Make this value non-negative.
Definition: KnownBits.h:113
static KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
Definition: KnownBits.cpp:428
unsigned getBitWidth() const
Get the bit width of this value.
Definition: KnownBits.h:40
void resetAll()
Resets the known state of all bits.
Definition: KnownBits.h:70
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition: KnownBits.h:300
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition: KnownBits.h:169
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition: KnownBits.h:185
static KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
Definition: KnownBits.cpp:1002
static KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition: KnownBits.cpp:51
bool isNegative() const
Returns true if this value is known to be negative.
Definition: KnownBits.h:94
static KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
Definition: KnownBits.cpp:285
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
void copysign(const KnownFPClass &Sign)
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
const Instruction * CxtI
Definition: SimplifyQuery.h:75
SimplifyQuery getWithInstruction(const Instruction *I) const