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