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