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