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