LLVM 17.0.0git
InstCombineCompares.cpp
Go to the documentation of this file.
1//===- InstCombineCompares.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 implements the visitICmp and visitFCmp functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/Statistic.h"
23#include "llvm/IR/DataLayout.h"
29
30using namespace llvm;
31using namespace PatternMatch;
32
33#define DEBUG_TYPE "instcombine"
34
35// How many times is a select replaced by one of its operands?
36STATISTIC(NumSel, "Number of select opts");
37
38
39/// Compute Result = In1+In2, returning true if the result overflowed for this
40/// type.
41static bool addWithOverflow(APInt &Result, const APInt &In1,
42 const APInt &In2, bool IsSigned = false) {
43 bool Overflow;
44 if (IsSigned)
45 Result = In1.sadd_ov(In2, Overflow);
46 else
47 Result = In1.uadd_ov(In2, Overflow);
48
49 return Overflow;
50}
51
52/// Compute Result = In1-In2, returning true if the result overflowed for this
53/// type.
54static bool subWithOverflow(APInt &Result, const APInt &In1,
55 const APInt &In2, bool IsSigned = false) {
56 bool Overflow;
57 if (IsSigned)
58 Result = In1.ssub_ov(In2, Overflow);
59 else
60 Result = In1.usub_ov(In2, Overflow);
61
62 return Overflow;
63}
64
65/// Given an icmp instruction, return true if any use of this comparison is a
66/// branch on sign bit comparison.
67static bool hasBranchUse(ICmpInst &I) {
68 for (auto *U : I.users())
69 if (isa<BranchInst>(U))
70 return true;
71 return false;
72}
73
74/// Returns true if the exploded icmp can be expressed as a signed comparison
75/// to zero and updates the predicate accordingly.
76/// The signedness of the comparison is preserved.
77/// TODO: Refactor with decomposeBitTestICmp()?
78static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
79 if (!ICmpInst::isSigned(Pred))
80 return false;
81
82 if (C.isZero())
83 return ICmpInst::isRelational(Pred);
84
85 if (C.isOne()) {
86 if (Pred == ICmpInst::ICMP_SLT) {
87 Pred = ICmpInst::ICMP_SLE;
88 return true;
89 }
90 } else if (C.isAllOnes()) {
91 if (Pred == ICmpInst::ICMP_SGT) {
92 Pred = ICmpInst::ICMP_SGE;
93 return true;
94 }
95 }
96
97 return false;
98}
99
100/// This is called when we see this pattern:
101/// cmp pred (load (gep GV, ...)), cmpcst
102/// where GV is a global variable with a constant initializer. Try to simplify
103/// this into some simple computation that does not need the load. For example
104/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
105///
106/// If AndCst is non-null, then the loaded value is masked with that constant
107/// before doing the comparison. This handles cases like "A[i]&4 == 0".
110 ConstantInt *AndCst) {
111 if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||
112 GV->getValueType() != GEP->getSourceElementType() ||
113 !GV->isConstant() || !GV->hasDefinitiveInitializer())
114 return nullptr;
115
117 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
118 return nullptr;
119
120 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
121 // Don't blow up on huge arrays.
122 if (ArrayElementCount > MaxArraySizeForCombine)
123 return nullptr;
124
125 // There are many forms of this optimization we can handle, for now, just do
126 // the simple index into a single-dimensional array.
127 //
128 // Require: GEP GV, 0, i {{, constant indices}}
129 if (GEP->getNumOperands() < 3 ||
130 !isa<ConstantInt>(GEP->getOperand(1)) ||
131 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
132 isa<Constant>(GEP->getOperand(2)))
133 return nullptr;
134
135 // Check that indices after the variable are constants and in-range for the
136 // type they index. Collect the indices. This is typically for arrays of
137 // structs.
138 SmallVector<unsigned, 4> LaterIndices;
139
140 Type *EltTy = Init->getType()->getArrayElementType();
141 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
142 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
143 if (!Idx) return nullptr; // Variable index.
144
145 uint64_t IdxVal = Idx->getZExtValue();
146 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
147
148 if (StructType *STy = dyn_cast<StructType>(EltTy))
149 EltTy = STy->getElementType(IdxVal);
150 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
151 if (IdxVal >= ATy->getNumElements()) return nullptr;
152 EltTy = ATy->getElementType();
153 } else {
154 return nullptr; // Unknown type.
155 }
156
157 LaterIndices.push_back(IdxVal);
158 }
159
160 enum { Overdefined = -3, Undefined = -2 };
161
162 // Variables for our state machines.
163
164 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
165 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
166 // and 87 is the second (and last) index. FirstTrueElement is -2 when
167 // undefined, otherwise set to the first true element. SecondTrueElement is
168 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
169 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
170
171 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
172 // form "i != 47 & i != 87". Same state transitions as for true elements.
173 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
174
175 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
176 /// define a state machine that triggers for ranges of values that the index
177 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
178 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
179 /// index in the range (inclusive). We use -2 for undefined here because we
180 /// use relative comparisons and don't want 0-1 to match -1.
181 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
182
183 // MagicBitvector - This is a magic bitvector where we set a bit if the
184 // comparison is true for element 'i'. If there are 64 elements or less in
185 // the array, this will fully represent all the comparison results.
186 uint64_t MagicBitvector = 0;
187
188 // Scan the array and see if one of our patterns matches.
189 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
190 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
191 Constant *Elt = Init->getAggregateElement(i);
192 if (!Elt) return nullptr;
193
194 // If this is indexing an array of structures, get the structure element.
195 if (!LaterIndices.empty()) {
196 Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices);
197 if (!Elt)
198 return nullptr;
199 }
200
201 // If the element is masked, handle it.
202 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
203
204 // Find out if the comparison would be true or false for the i'th element.
206 CompareRHS, DL, &TLI);
207 // If the result is undef for this element, ignore it.
208 if (isa<UndefValue>(C)) {
209 // Extend range state machines to cover this element in case there is an
210 // undef in the middle of the range.
211 if (TrueRangeEnd == (int)i-1)
212 TrueRangeEnd = i;
213 if (FalseRangeEnd == (int)i-1)
214 FalseRangeEnd = i;
215 continue;
216 }
217
218 // If we can't compute the result for any of the elements, we have to give
219 // up evaluating the entire conditional.
220 if (!isa<ConstantInt>(C)) return nullptr;
221
222 // Otherwise, we know if the comparison is true or false for this element,
223 // update our state machines.
224 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
225
226 // State machine for single/double/range index comparison.
227 if (IsTrueForElt) {
228 // Update the TrueElement state machine.
229 if (FirstTrueElement == Undefined)
230 FirstTrueElement = TrueRangeEnd = i; // First true element.
231 else {
232 // Update double-compare state machine.
233 if (SecondTrueElement == Undefined)
234 SecondTrueElement = i;
235 else
236 SecondTrueElement = Overdefined;
237
238 // Update range state machine.
239 if (TrueRangeEnd == (int)i-1)
240 TrueRangeEnd = i;
241 else
242 TrueRangeEnd = Overdefined;
243 }
244 } else {
245 // Update the FalseElement state machine.
246 if (FirstFalseElement == Undefined)
247 FirstFalseElement = FalseRangeEnd = i; // First false element.
248 else {
249 // Update double-compare state machine.
250 if (SecondFalseElement == Undefined)
251 SecondFalseElement = i;
252 else
253 SecondFalseElement = Overdefined;
254
255 // Update range state machine.
256 if (FalseRangeEnd == (int)i-1)
257 FalseRangeEnd = i;
258 else
259 FalseRangeEnd = Overdefined;
260 }
261 }
262
263 // If this element is in range, update our magic bitvector.
264 if (i < 64 && IsTrueForElt)
265 MagicBitvector |= 1ULL << i;
266
267 // If all of our states become overdefined, bail out early. Since the
268 // predicate is expensive, only check it every 8 elements. This is only
269 // really useful for really huge arrays.
270 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
271 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
272 FalseRangeEnd == Overdefined)
273 return nullptr;
274 }
275
276 // Now that we've scanned the entire array, emit our new comparison(s). We
277 // order the state machines in complexity of the generated code.
278 Value *Idx = GEP->getOperand(2);
279
280 // If the index is larger than the pointer offset size of the target, truncate
281 // the index down like the GEP would do implicitly. We don't have to do this
282 // for an inbounds GEP because the index can't be out of range.
283 if (!GEP->isInBounds()) {
284 Type *PtrIdxTy = DL.getIndexType(GEP->getType());
285 unsigned OffsetSize = PtrIdxTy->getIntegerBitWidth();
286 if (Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > OffsetSize)
287 Idx = Builder.CreateTrunc(Idx, PtrIdxTy);
288 }
289
290 // If inbounds keyword is not present, Idx * ElementSize can overflow.
291 // Let's assume that ElementSize is 2 and the wanted value is at offset 0.
292 // Then, there are two possible values for Idx to match offset 0:
293 // 0x00..00, 0x80..00.
294 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
295 // comparison is false if Idx was 0x80..00.
296 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
297 unsigned ElementSize =
298 DL.getTypeAllocSize(Init->getType()->getArrayElementType());
299 auto MaskIdx = [&](Value *Idx) {
300 if (!GEP->isInBounds() && llvm::countr_zero(ElementSize) != 0) {
301 Value *Mask = ConstantInt::get(Idx->getType(), -1);
302 Mask = Builder.CreateLShr(Mask, llvm::countr_zero(ElementSize));
303 Idx = Builder.CreateAnd(Idx, Mask);
304 }
305 return Idx;
306 };
307
308 // If the comparison is only true for one or two elements, emit direct
309 // comparisons.
310 if (SecondTrueElement != Overdefined) {
311 Idx = MaskIdx(Idx);
312 // None true -> false.
313 if (FirstTrueElement == Undefined)
314 return replaceInstUsesWith(ICI, Builder.getFalse());
315
316 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
317
318 // True for one element -> 'i == 47'.
319 if (SecondTrueElement == Undefined)
320 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
321
322 // True for two elements -> 'i == 47 | i == 72'.
323 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
324 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
325 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
326 return BinaryOperator::CreateOr(C1, C2);
327 }
328
329 // If the comparison is only false for one or two elements, emit direct
330 // comparisons.
331 if (SecondFalseElement != Overdefined) {
332 Idx = MaskIdx(Idx);
333 // None false -> true.
334 if (FirstFalseElement == Undefined)
335 return replaceInstUsesWith(ICI, Builder.getTrue());
336
337 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
338
339 // False for one element -> 'i != 47'.
340 if (SecondFalseElement == Undefined)
341 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
342
343 // False for two elements -> 'i != 47 & i != 72'.
344 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
345 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
346 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
347 return BinaryOperator::CreateAnd(C1, C2);
348 }
349
350 // If the comparison can be replaced with a range comparison for the elements
351 // where it is true, emit the range check.
352 if (TrueRangeEnd != Overdefined) {
353 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
354 Idx = MaskIdx(Idx);
355
356 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
357 if (FirstTrueElement) {
358 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
359 Idx = Builder.CreateAdd(Idx, Offs);
360 }
361
362 Value *End = ConstantInt::get(Idx->getType(),
363 TrueRangeEnd-FirstTrueElement+1);
364 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
365 }
366
367 // False range check.
368 if (FalseRangeEnd != Overdefined) {
369 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
370 Idx = MaskIdx(Idx);
371 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
372 if (FirstFalseElement) {
373 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
374 Idx = Builder.CreateAdd(Idx, Offs);
375 }
376
377 Value *End = ConstantInt::get(Idx->getType(),
378 FalseRangeEnd-FirstFalseElement);
379 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
380 }
381
382 // If a magic bitvector captures the entire comparison state
383 // of this load, replace it with computation that does:
384 // ((magic_cst >> i) & 1) != 0
385 {
386 Type *Ty = nullptr;
387
388 // Look for an appropriate type:
389 // - The type of Idx if the magic fits
390 // - The smallest fitting legal type
391 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
392 Ty = Idx->getType();
393 else
394 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
395
396 if (Ty) {
397 Idx = MaskIdx(Idx);
398 Value *V = Builder.CreateIntCast(Idx, Ty, false);
399 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
400 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
401 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
402 }
403 }
404
405 return nullptr;
406}
407
408/// Returns true if we can rewrite Start as a GEP with pointer Base
409/// and some integer offset. The nodes that need to be re-written
410/// for this transformation will be added to Explored.
411static bool canRewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
412 const DataLayout &DL,
413 SetVector<Value *> &Explored) {
414 SmallVector<Value *, 16> WorkList(1, Start);
415 Explored.insert(Base);
416
417 // The following traversal gives us an order which can be used
418 // when doing the final transformation. Since in the final
419 // transformation we create the PHI replacement instructions first,
420 // we don't have to get them in any particular order.
421 //
422 // However, for other instructions we will have to traverse the
423 // operands of an instruction first, which means that we have to
424 // do a post-order traversal.
425 while (!WorkList.empty()) {
427
428 while (!WorkList.empty()) {
429 if (Explored.size() >= 100)
430 return false;
431
432 Value *V = WorkList.back();
433
434 if (Explored.contains(V)) {
435 WorkList.pop_back();
436 continue;
437 }
438
439 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
440 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
441 // We've found some value that we can't explore which is different from
442 // the base. Therefore we can't do this transformation.
443 return false;
444
445 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
446 auto *CI = cast<CastInst>(V);
447 if (!CI->isNoopCast(DL))
448 return false;
449
450 if (!Explored.contains(CI->getOperand(0)))
451 WorkList.push_back(CI->getOperand(0));
452 }
453
454 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
455 // We're limiting the GEP to having one index. This will preserve
456 // the original pointer type. We could handle more cases in the
457 // future.
458 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
459 GEP->getSourceElementType() != ElemTy)
460 return false;
461
462 if (!Explored.contains(GEP->getOperand(0)))
463 WorkList.push_back(GEP->getOperand(0));
464 }
465
466 if (WorkList.back() == V) {
467 WorkList.pop_back();
468 // We've finished visiting this node, mark it as such.
469 Explored.insert(V);
470 }
471
472 if (auto *PN = dyn_cast<PHINode>(V)) {
473 // We cannot transform PHIs on unsplittable basic blocks.
474 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
475 return false;
476 Explored.insert(PN);
477 PHIs.insert(PN);
478 }
479 }
480
481 // Explore the PHI nodes further.
482 for (auto *PN : PHIs)
483 for (Value *Op : PN->incoming_values())
484 if (!Explored.contains(Op))
485 WorkList.push_back(Op);
486 }
487
488 // Make sure that we can do this. Since we can't insert GEPs in a basic
489 // block before a PHI node, we can't easily do this transformation if
490 // we have PHI node users of transformed instructions.
491 for (Value *Val : Explored) {
492 for (Value *Use : Val->uses()) {
493
494 auto *PHI = dyn_cast<PHINode>(Use);
495 auto *Inst = dyn_cast<Instruction>(Val);
496
497 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
498 !Explored.contains(PHI))
499 continue;
500
501 if (PHI->getParent() == Inst->getParent())
502 return false;
503 }
504 }
505 return true;
506}
507
508// Sets the appropriate insert point on Builder where we can add
509// a replacement Instruction for V (if that is possible).
510static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
511 bool Before = true) {
512 if (auto *PHI = dyn_cast<PHINode>(V)) {
513 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
514 return;
515 }
516 if (auto *I = dyn_cast<Instruction>(V)) {
517 if (!Before)
518 I = &*std::next(I->getIterator());
519 Builder.SetInsertPoint(I);
520 return;
521 }
522 if (auto *A = dyn_cast<Argument>(V)) {
523 // Set the insertion point in the entry block.
524 BasicBlock &Entry = A->getParent()->getEntryBlock();
525 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
526 return;
527 }
528 // Otherwise, this is a constant and we don't need to set a new
529 // insertion point.
530 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
531}
532
533/// Returns a re-written value of Start as an indexed GEP using Base as a
534/// pointer.
535static Value *rewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
536 const DataLayout &DL,
537 SetVector<Value *> &Explored,
538 InstCombiner &IC) {
539 // Perform all the substitutions. This is a bit tricky because we can
540 // have cycles in our use-def chains.
541 // 1. Create the PHI nodes without any incoming values.
542 // 2. Create all the other values.
543 // 3. Add the edges for the PHI nodes.
544 // 4. Emit GEPs to get the original pointers.
545 // 5. Remove the original instructions.
546 Type *IndexType = IntegerType::get(
547 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
548
550 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
551
552 // Create the new PHI nodes, without adding any incoming values.
553 for (Value *Val : Explored) {
554 if (Val == Base)
555 continue;
556 // Create empty phi nodes. This avoids cyclic dependencies when creating
557 // the remaining instructions.
558 if (auto *PHI = dyn_cast<PHINode>(Val))
559 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
560 PHI->getName() + ".idx", PHI);
561 }
562 IRBuilder<> Builder(Base->getContext());
563
564 // Create all the other instructions.
565 for (Value *Val : Explored) {
566
567 if (NewInsts.contains(Val))
568 continue;
569
570 if (auto *CI = dyn_cast<CastInst>(Val)) {
571 // Don't get rid of the intermediate variable here; the store can grow
572 // the map which will invalidate the reference to the input value.
573 Value *V = NewInsts[CI->getOperand(0)];
574 NewInsts[CI] = V;
575 continue;
576 }
577 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
578 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
579 : GEP->getOperand(1);
581 // Indices might need to be sign extended. GEPs will magically do
582 // this, but we need to do it ourselves here.
583 if (Index->getType()->getScalarSizeInBits() !=
584 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
585 Index = Builder.CreateSExtOrTrunc(
586 Index, NewInsts[GEP->getOperand(0)]->getType(),
587 GEP->getOperand(0)->getName() + ".sext");
588 }
589
590 auto *Op = NewInsts[GEP->getOperand(0)];
591 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
592 NewInsts[GEP] = Index;
593 else
594 NewInsts[GEP] = Builder.CreateNSWAdd(
595 Op, Index, GEP->getOperand(0)->getName() + ".add");
596 continue;
597 }
598 if (isa<PHINode>(Val))
599 continue;
600
601 llvm_unreachable("Unexpected instruction type");
602 }
603
604 // Add the incoming values to the PHI nodes.
605 for (Value *Val : Explored) {
606 if (Val == Base)
607 continue;
608 // All the instructions have been created, we can now add edges to the
609 // phi nodes.
610 if (auto *PHI = dyn_cast<PHINode>(Val)) {
611 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
612 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
613 Value *NewIncoming = PHI->getIncomingValue(I);
614
615 if (NewInsts.contains(NewIncoming))
616 NewIncoming = NewInsts[NewIncoming];
617
618 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
619 }
620 }
621 }
622
623 PointerType *PtrTy =
624 ElemTy->getPointerTo(Start->getType()->getPointerAddressSpace());
625 for (Value *Val : Explored) {
626 if (Val == Base)
627 continue;
628
629 // Depending on the type, for external users we have to emit
630 // a GEP or a GEP + ptrtoint.
631 setInsertionPoint(Builder, Val, false);
632
633 // Cast base to the expected type.
634 Value *NewVal = Builder.CreateBitOrPointerCast(
635 Base, PtrTy, Start->getName() + "to.ptr");
636 NewVal = Builder.CreateInBoundsGEP(ElemTy, NewVal, ArrayRef(NewInsts[Val]),
637 Val->getName() + ".ptr");
638 NewVal = Builder.CreateBitOrPointerCast(
639 NewVal, Val->getType(), Val->getName() + ".conv");
640 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
641 // Add old instruction to worklist for DCE. We don't directly remove it
642 // here because the original compare is one of the users.
643 IC.addToWorklist(cast<Instruction>(Val));
644 }
645
646 return NewInsts[Start];
647}
648
649/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
650/// the input Value as a constant indexed GEP. Returns a pair containing
651/// the GEPs Pointer and Index.
652static std::pair<Value *, Value *>
654 Type *IndexType = IntegerType::get(V->getContext(),
655 DL.getIndexTypeSizeInBits(V->getType()));
656
658 while (true) {
659 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
660 // We accept only inbouds GEPs here to exclude the possibility of
661 // overflow.
662 if (!GEP->isInBounds())
663 break;
664 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
665 GEP->getSourceElementType() == ElemTy) {
666 V = GEP->getOperand(0);
667 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
669 Index, ConstantExpr::getSExtOrTrunc(GEPIndex, IndexType));
670 continue;
671 }
672 break;
673 }
674 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
675 if (!CI->isNoopCast(DL))
676 break;
677 V = CI->getOperand(0);
678 continue;
679 }
680 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
681 if (!CI->isNoopCast(DL))
682 break;
683 V = CI->getOperand(0);
684 continue;
685 }
686 break;
687 }
688 return {V, Index};
689}
690
691/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
692/// We can look through PHIs, GEPs and casts in order to determine a common base
693/// between GEPLHS and RHS.
696 const DataLayout &DL,
697 InstCombiner &IC) {
698 // FIXME: Support vector of pointers.
699 if (GEPLHS->getType()->isVectorTy())
700 return nullptr;
701
702 if (!GEPLHS->hasAllConstantIndices())
703 return nullptr;
704
705 Type *ElemTy = GEPLHS->getSourceElementType();
706 Value *PtrBase, *Index;
707 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(ElemTy, GEPLHS, DL);
708
709 // The set of nodes that will take part in this transformation.
710 SetVector<Value *> Nodes;
711
712 if (!canRewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes))
713 return nullptr;
714
715 // We know we can re-write this as
716 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
717 // Since we've only looked through inbouds GEPs we know that we
718 // can't have overflow on either side. We can therefore re-write
719 // this as:
720 // OFFSET1 cmp OFFSET2
721 Value *NewRHS = rewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes, IC);
722
723 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
724 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
725 // offset. Since Index is the offset of LHS to the base pointer, we will now
726 // compare the offsets instead of comparing the pointers.
727 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
728}
729
730/// Fold comparisons between a GEP instruction and something else. At this point
731/// we know that the GEP is on the LHS of the comparison.
734 Instruction &I) {
735 // Don't transform signed compares of GEPs into index compares. Even if the
736 // GEP is inbounds, the final add of the base pointer can have signed overflow
737 // and would change the result of the icmp.
738 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
739 // the maximum signed value for the pointer type.
741 return nullptr;
742
743 // Look through bitcasts and addrspacecasts. We do not however want to remove
744 // 0 GEPs.
745 if (!isa<GetElementPtrInst>(RHS))
747
748 Value *PtrBase = GEPLHS->getOperand(0);
749 if (PtrBase == RHS && (GEPLHS->isInBounds() || ICmpInst::isEquality(Cond))) {
750 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
751 Value *Offset = EmitGEPOffset(GEPLHS);
753 Constant::getNullValue(Offset->getType()));
754 }
755
756 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
757 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
758 !NullPointerIsDefined(I.getFunction(),
760 // For most address spaces, an allocation can't be placed at null, but null
761 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
762 // the only valid inbounds address derived from null, is null itself.
763 // Thus, we have four cases to consider:
764 // 1) Base == nullptr, Offset == 0 -> inbounds, null
765 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
766 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
767 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
768 //
769 // (Note if we're indexing a type of size 0, that simply collapses into one
770 // of the buckets above.)
771 //
772 // In general, we're allowed to make values less poison (i.e. remove
773 // sources of full UB), so in this case, we just select between the two
774 // non-poison cases (1 and 4 above).
775 //
776 // For vectors, we apply the same reasoning on a per-lane basis.
777 auto *Base = GEPLHS->getPointerOperand();
778 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
779 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
781 }
782 return new ICmpInst(Cond, Base,
784 cast<Constant>(RHS), Base->getType()));
785 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
786 // If the base pointers are different, but the indices are the same, just
787 // compare the base pointer.
788 if (PtrBase != GEPRHS->getOperand(0)) {
789 bool IndicesTheSame =
790 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
791 GEPLHS->getPointerOperand()->getType() ==
792 GEPRHS->getPointerOperand()->getType() &&
793 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
794 if (IndicesTheSame)
795 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
796 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
797 IndicesTheSame = false;
798 break;
799 }
800
801 // If all indices are the same, just compare the base pointers.
802 Type *BaseType = GEPLHS->getOperand(0)->getType();
803 if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
804 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
805
806 // If we're comparing GEPs with two base pointers that only differ in type
807 // and both GEPs have only constant indices or just one use, then fold
808 // the compare with the adjusted indices.
809 // FIXME: Support vector of pointers.
810 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
811 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
812 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
813 PtrBase->stripPointerCasts() ==
814 GEPRHS->getOperand(0)->stripPointerCasts() &&
815 !GEPLHS->getType()->isVectorTy()) {
816 Value *LOffset = EmitGEPOffset(GEPLHS);
817 Value *ROffset = EmitGEPOffset(GEPRHS);
818
819 // If we looked through an addrspacecast between different sized address
820 // spaces, the LHS and RHS pointers are different sized
821 // integers. Truncate to the smaller one.
822 Type *LHSIndexTy = LOffset->getType();
823 Type *RHSIndexTy = ROffset->getType();
824 if (LHSIndexTy != RHSIndexTy) {
825 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
826 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
827 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
828 } else
829 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
830 }
831
833 LOffset, ROffset);
834 return replaceInstUsesWith(I, Cmp);
835 }
836
837 // Otherwise, the base pointers are different and the indices are
838 // different. Try convert this to an indexed compare by looking through
839 // PHIs/casts.
840 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
841 }
842
843 // If one of the GEPs has all zero indices, recurse.
844 // FIXME: Handle vector of pointers.
845 if (!GEPLHS->getType()->isVectorTy() && GEPLHS->hasAllZeroIndices())
846 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
848
849 // If the other GEP has all zero indices, recurse.
850 // FIXME: Handle vector of pointers.
851 if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices())
852 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
853
854 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
855 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
856 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
857 // If the GEPs only differ by one index, compare it.
858 unsigned NumDifferences = 0; // Keep track of # differences.
859 unsigned DiffOperand = 0; // The operand that differs.
860 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
861 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
862 Type *LHSType = GEPLHS->getOperand(i)->getType();
863 Type *RHSType = GEPRHS->getOperand(i)->getType();
864 // FIXME: Better support for vector of pointers.
865 if (LHSType->getPrimitiveSizeInBits() !=
866 RHSType->getPrimitiveSizeInBits() ||
867 (GEPLHS->getType()->isVectorTy() &&
868 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
869 // Irreconcilable differences.
870 NumDifferences = 2;
871 break;
872 }
873
874 if (NumDifferences++) break;
875 DiffOperand = i;
876 }
877
878 if (NumDifferences == 0) // SAME GEP?
879 return replaceInstUsesWith(I, // No comparison is needed here.
881
882 else if (NumDifferences == 1 && GEPsInBounds) {
883 Value *LHSV = GEPLHS->getOperand(DiffOperand);
884 Value *RHSV = GEPRHS->getOperand(DiffOperand);
885 // Make sure we do a signed comparison here.
886 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
887 }
888 }
889
890 // Only lower this if the icmp is the only user of the GEP or if we expect
891 // the result to fold to a constant!
892 if ((GEPsInBounds || CmpInst::isEquality(Cond)) &&
893 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
894 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
895 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
896 Value *L = EmitGEPOffset(GEPLHS);
897 Value *R = EmitGEPOffset(GEPRHS);
898 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
899 }
900 }
901
902 // Try convert this to an indexed compare by looking through PHIs/casts as a
903 // last resort.
904 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
905}
906
908 // It would be tempting to fold away comparisons between allocas and any
909 // pointer not based on that alloca (e.g. an argument). However, even
910 // though such pointers cannot alias, they can still compare equal.
911 //
912 // But LLVM doesn't specify where allocas get their memory, so if the alloca
913 // doesn't escape we can argue that it's impossible to guess its value, and we
914 // can therefore act as if any such guesses are wrong.
915 //
916 // However, we need to ensure that this folding is consistent: We can't fold
917 // one comparison to false, and then leave a different comparison against the
918 // same value alone (as it might evaluate to true at runtime, leading to a
919 // contradiction). As such, this code ensures that all comparisons are folded
920 // at the same time, and there are no other escapes.
921
922 struct CmpCaptureTracker : public CaptureTracker {
923 AllocaInst *Alloca;
924 bool Captured = false;
925 /// The value of the map is a bit mask of which icmp operands the alloca is
926 /// used in.
928
929 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
930
931 void tooManyUses() override { Captured = true; }
932
933 bool captured(const Use *U) override {
934 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
935 // We need to check that U is based *only* on the alloca, and doesn't
936 // have other contributions from a select/phi operand.
937 // TODO: We could check whether getUnderlyingObjects() reduces to one
938 // object, which would allow looking through phi nodes.
939 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
940 // Collect equality icmps of the alloca, and don't treat them as
941 // captures.
942 auto Res = ICmps.insert({ICmp, 0});
943 Res.first->second |= 1u << U->getOperandNo();
944 return false;
945 }
946
947 Captured = true;
948 return true;
949 }
950 };
951
952 CmpCaptureTracker Tracker(Alloca);
953 PointerMayBeCaptured(Alloca, &Tracker);
954 if (Tracker.Captured)
955 return false;
956
957 bool Changed = false;
958 for (auto [ICmp, Operands] : Tracker.ICmps) {
959 switch (Operands) {
960 case 1:
961 case 2: {
962 // The alloca is only used in one icmp operand. Assume that the
963 // equality is false.
964 auto *Res = ConstantInt::get(
965 ICmp->getType(), ICmp->getPredicate() == ICmpInst::ICMP_NE);
966 replaceInstUsesWith(*ICmp, Res);
968 Changed = true;
969 break;
970 }
971 case 3:
972 // Both icmp operands are based on the alloca, so this is comparing
973 // pointer offsets, without leaking any information about the address
974 // of the alloca. Ignore such comparisons.
975 break;
976 default:
977 llvm_unreachable("Cannot happen");
978 }
979 }
980
981 return Changed;
982}
983
984/// Fold "icmp pred (X+C), X".
986 ICmpInst::Predicate Pred) {
987 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
988 // so the values can never be equal. Similarly for all other "or equals"
989 // operators.
990 assert(!!C && "C should not be zero!");
991
992 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
993 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
994 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
995 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
996 Constant *R = ConstantInt::get(X->getType(),
997 APInt::getMaxValue(C.getBitWidth()) - C);
998 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
999 }
1000
1001 // (X+1) >u X --> X <u (0-1) --> X != 255
1002 // (X+2) >u X --> X <u (0-2) --> X <u 254
1003 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
1004 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
1005 return new ICmpInst(ICmpInst::ICMP_ULT, X,
1006 ConstantInt::get(X->getType(), -C));
1007
1008 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
1009
1010 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1011 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1012 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1013 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1014 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1015 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
1016 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1017 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1018 ConstantInt::get(X->getType(), SMax - C));
1019
1020 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1021 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1022 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1023 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1024 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1025 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
1026
1027 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
1028 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1029 ConstantInt::get(X->getType(), SMax - (C - 1)));
1030}
1031
1032/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1033/// (icmp eq/ne A, Log2(AP2/AP1)) ->
1034/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
1036 const APInt &AP1,
1037 const APInt &AP2) {
1038 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1039
1040 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1041 if (I.getPredicate() == I.ICMP_NE)
1042 Pred = CmpInst::getInversePredicate(Pred);
1043 return new ICmpInst(Pred, LHS, RHS);
1044 };
1045
1046 // Don't bother doing any work for cases which InstSimplify handles.
1047 if (AP2.isZero())
1048 return nullptr;
1049
1050 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1051 if (IsAShr) {
1052 if (AP2.isAllOnes())
1053 return nullptr;
1054 if (AP2.isNegative() != AP1.isNegative())
1055 return nullptr;
1056 if (AP2.sgt(AP1))
1057 return nullptr;
1058 }
1059
1060 if (!AP1)
1061 // 'A' must be large enough to shift out the highest set bit.
1062 return getICmp(I.ICMP_UGT, A,
1063 ConstantInt::get(A->getType(), AP2.logBase2()));
1064
1065 if (AP1 == AP2)
1066 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1067
1068 int Shift;
1069 if (IsAShr && AP1.isNegative())
1070 Shift = AP1.countl_one() - AP2.countl_one();
1071 else
1072 Shift = AP1.countl_zero() - AP2.countl_zero();
1073
1074 if (Shift > 0) {
1075 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1076 // There are multiple solutions if we are comparing against -1 and the LHS
1077 // of the ashr is not a power of two.
1078 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1079 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1080 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1081 } else if (AP1 == AP2.lshr(Shift)) {
1082 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1083 }
1084 }
1085
1086 // Shifting const2 will never be equal to const1.
1087 // FIXME: This should always be handled by InstSimplify?
1088 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1089 return replaceInstUsesWith(I, TorF);
1090}
1091
1092/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1093/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1095 const APInt &AP1,
1096 const APInt &AP2) {
1097 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1098
1099 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1100 if (I.getPredicate() == I.ICMP_NE)
1101 Pred = CmpInst::getInversePredicate(Pred);
1102 return new ICmpInst(Pred, LHS, RHS);
1103 };
1104
1105 // Don't bother doing any work for cases which InstSimplify handles.
1106 if (AP2.isZero())
1107 return nullptr;
1108
1109 unsigned AP2TrailingZeros = AP2.countr_zero();
1110
1111 if (!AP1 && AP2TrailingZeros != 0)
1112 return getICmp(
1113 I.ICMP_UGE, A,
1114 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1115
1116 if (AP1 == AP2)
1117 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1118
1119 // Get the distance between the lowest bits that are set.
1120 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1121
1122 if (Shift > 0 && AP2.shl(Shift) == AP1)
1123 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1124
1125 // Shifting const2 will never be equal to const1.
1126 // FIXME: This should always be handled by InstSimplify?
1127 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1128 return replaceInstUsesWith(I, TorF);
1129}
1130
1131/// The caller has matched a pattern of the form:
1132/// I = icmp ugt (add (add A, B), CI2), CI1
1133/// If this is of the form:
1134/// sum = a + b
1135/// if (sum+128 >u 255)
1136/// Then replace it with llvm.sadd.with.overflow.i8.
1137///
1139 ConstantInt *CI2, ConstantInt *CI1,
1140 InstCombinerImpl &IC) {
1141 // The transformation we're trying to do here is to transform this into an
1142 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1143 // with a narrower add, and discard the add-with-constant that is part of the
1144 // range check (if we can't eliminate it, this isn't profitable).
1145
1146 // In order to eliminate the add-with-constant, the compare can be its only
1147 // use.
1148 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1149 if (!AddWithCst->hasOneUse())
1150 return nullptr;
1151
1152 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1153 if (!CI2->getValue().isPowerOf2())
1154 return nullptr;
1155 unsigned NewWidth = CI2->getValue().countr_zero();
1156 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1157 return nullptr;
1158
1159 // The width of the new add formed is 1 more than the bias.
1160 ++NewWidth;
1161
1162 // Check to see that CI1 is an all-ones value with NewWidth bits.
1163 if (CI1->getBitWidth() == NewWidth ||
1164 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1165 return nullptr;
1166
1167 // This is only really a signed overflow check if the inputs have been
1168 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1169 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1170 if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth ||
1171 IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth)
1172 return nullptr;
1173
1174 // In order to replace the original add with a narrower
1175 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1176 // and truncates that discard the high bits of the add. Verify that this is
1177 // the case.
1178 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1179 for (User *U : OrigAdd->users()) {
1180 if (U == AddWithCst)
1181 continue;
1182
1183 // Only accept truncates for now. We would really like a nice recursive
1184 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1185 // chain to see which bits of a value are actually demanded. If the
1186 // original add had another add which was then immediately truncated, we
1187 // could still do the transformation.
1188 TruncInst *TI = dyn_cast<TruncInst>(U);
1189 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1190 return nullptr;
1191 }
1192
1193 // If the pattern matches, truncate the inputs to the narrower type and
1194 // use the sadd_with_overflow intrinsic to efficiently compute both the
1195 // result and the overflow bit.
1196 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1198 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1199
1201
1202 // Put the new code above the original add, in case there are any uses of the
1203 // add between the add and the compare.
1204 Builder.SetInsertPoint(OrigAdd);
1205
1206 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1207 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1208 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1209 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1210 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1211
1212 // The inner add was the result of the narrow add, zero extended to the
1213 // wider type. Replace it with the result computed by the intrinsic.
1214 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1215 IC.eraseInstFromFunction(*OrigAdd);
1216
1217 // The original icmp gets replaced with the overflow value.
1218 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1219}
1220
1221/// If we have:
1222/// icmp eq/ne (urem/srem %x, %y), 0
1223/// iff %y is a power-of-two, we can replace this with a bit test:
1224/// icmp eq/ne (and %x, (add %y, -1)), 0
1226 // This fold is only valid for equality predicates.
1227 if (!I.isEquality())
1228 return nullptr;
1230 Value *X, *Y, *Zero;
1231 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1232 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1233 return nullptr;
1234 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
1235 return nullptr;
1236 // This may increase instruction count, we don't enforce that Y is a constant.
1237 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1238 Value *Masked = Builder.CreateAnd(X, Mask);
1239 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1240}
1241
1242/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1243/// by one-less-than-bitwidth into a sign test on the original value.
1245 Instruction *Val;
1247 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1248 return nullptr;
1249
1250 Value *X;
1251 Type *XTy;
1252
1253 Constant *C;
1254 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1255 XTy = X->getType();
1256 unsigned XBitWidth = XTy->getScalarSizeInBits();
1258 APInt(XBitWidth, XBitWidth - 1))))
1259 return nullptr;
1260 } else if (isa<BinaryOperator>(Val) &&
1262 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1263 /*AnalyzeForSignBitExtraction=*/true))) {
1264 XTy = X->getType();
1265 } else
1266 return nullptr;
1267
1268 return ICmpInst::Create(Instruction::ICmp,
1272}
1273
1274// Handle icmp pred X, 0
1276 CmpInst::Predicate Pred = Cmp.getPredicate();
1277 if (!match(Cmp.getOperand(1), m_Zero()))
1278 return nullptr;
1279
1280 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1281 if (Pred == ICmpInst::ICMP_SGT) {
1282 Value *A, *B;
1283 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1284 if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT))
1285 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1286 if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT))
1287 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1288 }
1289 }
1290
1292 return New;
1293
1294 // Given:
1295 // icmp eq/ne (urem %x, %y), 0
1296 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1297 // icmp eq/ne %x, 0
1298 Value *X, *Y;
1299 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1300 ICmpInst::isEquality(Pred)) {
1301 KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1302 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1303 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1304 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1305 }
1306
1307 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1308 // odd/non-zero/there is no overflow.
1309 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1310 ICmpInst::isEquality(Pred)) {
1311
1312 KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1313 // if X % 2 != 0
1314 // (icmp eq/ne Y)
1315 if (XKnown.countMaxTrailingZeros() == 0)
1316 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1317
1318 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1319 // if Y % 2 != 0
1320 // (icmp eq/ne X)
1321 if (YKnown.countMaxTrailingZeros() == 0)
1322 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1323
1324 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1325 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1326 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1327 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1328 // but to avoid unnecessary work, first just if this is an obvious case.
1329
1330 // if X non-zero and NoOverflow(X * Y)
1331 // (icmp eq/ne Y)
1332 if (!XKnown.One.isZero() || isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
1333 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1334
1335 // if Y non-zero and NoOverflow(X * Y)
1336 // (icmp eq/ne X)
1337 if (!YKnown.One.isZero() || isKnownNonZero(Y, DL, 0, Q.AC, Q.CxtI, Q.DT))
1338 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1339 }
1340 // Note, we are skipping cases:
1341 // if Y % 2 != 0 AND X % 2 != 0
1342 // (false/true)
1343 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1344 // (false/true)
1345 // Those can be simplified later as we would have already replaced the (icmp
1346 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1347 // will fold to a constant elsewhere.
1348 }
1349 return nullptr;
1350}
1351
1352/// Fold icmp Pred X, C.
1353/// TODO: This code structure does not make sense. The saturating add fold
1354/// should be moved to some other helper and extended as noted below (it is also
1355/// possible that code has been made unnecessary - do we canonicalize IR to
1356/// overflow/saturating intrinsics or not?).
1358 // Match the following pattern, which is a common idiom when writing
1359 // overflow-safe integer arithmetic functions. The source performs an addition
1360 // in wider type and explicitly checks for overflow using comparisons against
1361 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1362 //
1363 // TODO: This could probably be generalized to handle other overflow-safe
1364 // operations if we worked out the formulas to compute the appropriate magic
1365 // constants.
1366 //
1367 // sum = a + b
1368 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1369 CmpInst::Predicate Pred = Cmp.getPredicate();
1370 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1371 Value *A, *B;
1372 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1373 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1374 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1375 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1376 return Res;
1377
1378 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1379 Constant *C = dyn_cast<Constant>(Op1);
1380 if (!C)
1381 return nullptr;
1382
1383 if (auto *Phi = dyn_cast<PHINode>(Op0))
1384 if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) {
1386 for (Value *V : Phi->incoming_values()) {
1387 Constant *Res =
1388 ConstantFoldCompareInstOperands(Pred, cast<Constant>(V), C, DL);
1389 if (!Res)
1390 return nullptr;
1391 Ops.push_back(Res);
1392 }
1394 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1395 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1396 NewPhi->addIncoming(V, Pred);
1397 return replaceInstUsesWith(Cmp, NewPhi);
1398 }
1399
1400 return nullptr;
1401}
1402
1403/// Canonicalize icmp instructions based on dominating conditions.
1405 // This is a cheap/incomplete check for dominance - just match a single
1406 // predecessor with a conditional branch.
1407 BasicBlock *CmpBB = Cmp.getParent();
1408 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1409 if (!DomBB)
1410 return nullptr;
1411
1412 Value *DomCond;
1413 BasicBlock *TrueBB, *FalseBB;
1414 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1415 return nullptr;
1416
1417 assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
1418 "Predecessor block does not point to successor?");
1419
1420 // The branch should get simplified. Don't bother simplifying this condition.
1421 if (TrueBB == FalseBB)
1422 return nullptr;
1423
1424 // We already checked simple implication in InstSimplify, only handle complex
1425 // cases here.
1426
1427 CmpInst::Predicate Pred = Cmp.getPredicate();
1428 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1429 ICmpInst::Predicate DomPred;
1430 const APInt *C, *DomC;
1431 if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) &&
1432 match(Y, m_APInt(C))) {
1433 // We have 2 compares of a variable with constants. Calculate the constant
1434 // ranges of those compares to see if we can transform the 2nd compare:
1435 // DomBB:
1436 // DomCond = icmp DomPred X, DomC
1437 // br DomCond, CmpBB, FalseBB
1438 // CmpBB:
1439 // Cmp = icmp Pred X, C
1441 ConstantRange DominatingCR =
1442 (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC)
1444 CmpInst::getInversePredicate(DomPred), *DomC);
1445 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1446 ConstantRange Difference = DominatingCR.difference(CR);
1447 if (Intersection.isEmptySet())
1448 return replaceInstUsesWith(Cmp, Builder.getFalse());
1449 if (Difference.isEmptySet())
1450 return replaceInstUsesWith(Cmp, Builder.getTrue());
1451
1452 // Canonicalizing a sign bit comparison that gets used in a branch,
1453 // pessimizes codegen by generating branch on zero instruction instead
1454 // of a test and branch. So we avoid canonicalizing in such situations
1455 // because test and branch instruction has better branch displacement
1456 // than compare and branch instruction.
1457 bool UnusedBit;
1458 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1459 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1460 return nullptr;
1461
1462 // Avoid an infinite loop with min/max canonicalization.
1463 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1464 if (Cmp.hasOneUse() &&
1465 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1466 return nullptr;
1467
1468 if (const APInt *EqC = Intersection.getSingleElement())
1469 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1470 if (const APInt *NeC = Difference.getSingleElement())
1471 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1472 }
1473
1474 return nullptr;
1475}
1476
1477/// Fold icmp (trunc X), C.
1479 TruncInst *Trunc,
1480 const APInt &C) {
1481 ICmpInst::Predicate Pred = Cmp.getPredicate();
1482 Value *X = Trunc->getOperand(0);
1483 if (C.isOne() && C.getBitWidth() > 1) {
1484 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1485 Value *V = nullptr;
1486 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1487 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1488 ConstantInt::get(V->getType(), 1));
1489 }
1490
1491 Type *SrcTy = X->getType();
1492 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1493 SrcBits = SrcTy->getScalarSizeInBits();
1494
1495 // TODO: Handle any shifted constant by subtracting trailing zeros.
1496 // TODO: Handle non-equality predicates.
1497 Value *Y;
1498 if (Cmp.isEquality() && match(X, m_Shl(m_One(), m_Value(Y)))) {
1499 // (trunc (1 << Y) to iN) == 0 --> Y u>= N
1500 // (trunc (1 << Y) to iN) != 0 --> Y u< N
1501 if (C.isZero()) {
1502 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1503 return new ICmpInst(NewPred, Y, ConstantInt::get(SrcTy, DstBits));
1504 }
1505 // (trunc (1 << Y) to iN) == 2**C --> Y == C
1506 // (trunc (1 << Y) to iN) != 2**C --> Y != C
1507 if (C.isPowerOf2())
1508 return new ICmpInst(Pred, Y, ConstantInt::get(SrcTy, C.logBase2()));
1509 }
1510
1511 if (Cmp.isEquality() && Trunc->hasOneUse()) {
1512 // Canonicalize to a mask and wider compare if the wide type is suitable:
1513 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1514 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1515 Constant *Mask =
1516 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1517 Value *And = Builder.CreateAnd(X, Mask);
1518 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1519 return new ICmpInst(Pred, And, WideC);
1520 }
1521
1522 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1523 // of the high bits truncated out of x are known.
1524 KnownBits Known = computeKnownBits(X, 0, &Cmp);
1525
1526 // If all the high bits are known, we can do this xform.
1527 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1528 // Pull in the high bits from known-ones set.
1529 APInt NewRHS = C.zext(SrcBits);
1530 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1531 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1532 }
1533 }
1534
1535 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1536 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1537 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1538 Value *ShOp;
1539 const APInt *ShAmtC;
1540 bool TrueIfSigned;
1541 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1542 match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) &&
1543 DstBits == SrcBits - ShAmtC->getZExtValue()) {
1544 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1546 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1548 }
1549
1550 return nullptr;
1551}
1552
1553/// Fold icmp (xor X, Y), C.
1556 const APInt &C) {
1557 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1558 return I;
1559
1560 Value *X = Xor->getOperand(0);
1561 Value *Y = Xor->getOperand(1);
1562 const APInt *XorC;
1563 if (!match(Y, m_APInt(XorC)))
1564 return nullptr;
1565
1566 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1567 // fold the xor.
1568 ICmpInst::Predicate Pred = Cmp.getPredicate();
1569 bool TrueIfSigned = false;
1570 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1571
1572 // If the sign bit of the XorCst is not set, there is no change to
1573 // the operation, just stop using the Xor.
1574 if (!XorC->isNegative())
1575 return replaceOperand(Cmp, 0, X);
1576
1577 // Emit the opposite comparison.
1578 if (TrueIfSigned)
1579 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1580 ConstantInt::getAllOnesValue(X->getType()));
1581 else
1582 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1583 ConstantInt::getNullValue(X->getType()));
1584 }
1585
1586 if (Xor->hasOneUse()) {
1587 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1588 if (!Cmp.isEquality() && XorC->isSignMask()) {
1589 Pred = Cmp.getFlippedSignednessPredicate();
1590 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1591 }
1592
1593 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1594 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1595 Pred = Cmp.getFlippedSignednessPredicate();
1596 Pred = Cmp.getSwappedPredicate(Pred);
1597 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1598 }
1599 }
1600
1601 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1602 if (Pred == ICmpInst::ICMP_UGT) {
1603 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1604 if (*XorC == ~C && (C + 1).isPowerOf2())
1605 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1606 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1607 if (*XorC == C && (C + 1).isPowerOf2())
1608 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1609 }
1610 if (Pred == ICmpInst::ICMP_ULT) {
1611 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1612 if (*XorC == -C && C.isPowerOf2())
1613 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1614 ConstantInt::get(X->getType(), ~C));
1615 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1616 if (*XorC == C && (-C).isPowerOf2())
1617 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1618 ConstantInt::get(X->getType(), ~C));
1619 }
1620 return nullptr;
1621}
1622
1623/// For power-of-2 C:
1624/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1625/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1628 const APInt &C) {
1629 CmpInst::Predicate Pred = Cmp.getPredicate();
1630 APInt PowerOf2;
1631 if (Pred == ICmpInst::ICMP_ULT)
1632 PowerOf2 = C;
1633 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1634 PowerOf2 = C + 1;
1635 else
1636 return nullptr;
1637 if (!PowerOf2.isPowerOf2())
1638 return nullptr;
1639 Value *X;
1640 const APInt *ShiftC;
1642 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1643 return nullptr;
1644 uint64_t Shift = ShiftC->getLimitedValue();
1645 Type *XType = X->getType();
1646 if (Shift == 0 || PowerOf2.isMinSignedValue())
1647 return nullptr;
1648 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1649 APInt Bound =
1650 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1651 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1652}
1653
1654/// Fold icmp (and (sh X, Y), C2), C1.
1657 const APInt &C1,
1658 const APInt &C2) {
1659 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1660 if (!Shift || !Shift->isShift())
1661 return nullptr;
1662
1663 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1664 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1665 // code produced by the clang front-end, for bitfield access.
1666 // This seemingly simple opportunity to fold away a shift turns out to be
1667 // rather complicated. See PR17827 for details.
1668 unsigned ShiftOpcode = Shift->getOpcode();
1669 bool IsShl = ShiftOpcode == Instruction::Shl;
1670 const APInt *C3;
1671 if (match(Shift->getOperand(1), m_APInt(C3))) {
1672 APInt NewAndCst, NewCmpCst;
1673 bool AnyCmpCstBitsShiftedOut;
1674 if (ShiftOpcode == Instruction::Shl) {
1675 // For a left shift, we can fold if the comparison is not signed. We can
1676 // also fold a signed comparison if the mask value and comparison value
1677 // are not negative. These constraints may not be obvious, but we can
1678 // prove that they are correct using an SMT solver.
1679 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1680 return nullptr;
1681
1682 NewCmpCst = C1.lshr(*C3);
1683 NewAndCst = C2.lshr(*C3);
1684 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1685 } else if (ShiftOpcode == Instruction::LShr) {
1686 // For a logical right shift, we can fold if the comparison is not signed.
1687 // We can also fold a signed comparison if the shifted mask value and the
1688 // shifted comparison value are not negative. These constraints may not be
1689 // obvious, but we can prove that they are correct using an SMT solver.
1690 NewCmpCst = C1.shl(*C3);
1691 NewAndCst = C2.shl(*C3);
1692 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1693 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1694 return nullptr;
1695 } else {
1696 // For an arithmetic shift, check that both constants don't use (in a
1697 // signed sense) the top bits being shifted out.
1698 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1699 NewCmpCst = C1.shl(*C3);
1700 NewAndCst = C2.shl(*C3);
1701 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1702 if (NewAndCst.ashr(*C3) != C2)
1703 return nullptr;
1704 }
1705
1706 if (AnyCmpCstBitsShiftedOut) {
1707 // If we shifted bits out, the fold is not going to work out. As a
1708 // special case, check to see if this means that the result is always
1709 // true or false now.
1710 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1711 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1712 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1713 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1714 } else {
1715 Value *NewAnd = Builder.CreateAnd(
1716 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1717 return new ICmpInst(Cmp.getPredicate(),
1718 NewAnd, ConstantInt::get(And->getType(), NewCmpCst));
1719 }
1720 }
1721
1722 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1723 // preferable because it allows the C2 << Y expression to be hoisted out of a
1724 // loop if Y is invariant and X is not.
1725 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1726 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1727 // Compute C2 << Y.
1728 Value *NewShift =
1729 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1730 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1731
1732 // Compute X & (C2 << Y).
1733 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1734 return replaceOperand(Cmp, 0, NewAnd);
1735 }
1736
1737 return nullptr;
1738}
1739
1740/// Fold icmp (and X, C2), C1.
1743 const APInt &C1) {
1744 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1745
1746 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1747 // TODO: We canonicalize to the longer form for scalars because we have
1748 // better analysis/folds for icmp, and codegen may be better with icmp.
1749 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&
1750 match(And->getOperand(1), m_One()))
1751 return new TruncInst(And->getOperand(0), Cmp.getType());
1752
1753 const APInt *C2;
1754 Value *X;
1755 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1756 return nullptr;
1757
1758 // Don't perform the following transforms if the AND has multiple uses
1759 if (!And->hasOneUse())
1760 return nullptr;
1761
1762 if (Cmp.isEquality() && C1.isZero()) {
1763 // Restrict this fold to single-use 'and' (PR10267).
1764 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1765 if (C2->isSignMask()) {
1766 Constant *Zero = Constant::getNullValue(X->getType());
1767 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1768 return new ICmpInst(NewPred, X, Zero);
1769 }
1770
1771 APInt NewC2 = *C2;
1772 KnownBits Know = computeKnownBits(And->getOperand(0), 0, And);
1773 // Set high zeros of C2 to allow matching negated power-of-2.
1774 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1775 Know.countMinLeadingZeros());
1776
1777 // Restrict this fold only for single-use 'and' (PR10267).
1778 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1779 if (NewC2.isNegatedPowerOf2()) {
1780 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1781 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1782 return new ICmpInst(NewPred, X, NegBOC);
1783 }
1784 }
1785
1786 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1787 // the input width without changing the value produced, eliminate the cast:
1788 //
1789 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1790 //
1791 // We can do this transformation if the constants do not have their sign bits
1792 // set or if it is an equality comparison. Extending a relational comparison
1793 // when we're checking the sign bit would not work.
1794 Value *W;
1795 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1796 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1797 // TODO: Is this a good transform for vectors? Wider types may reduce
1798 // throughput. Should this transform be limited (even for scalars) by using
1799 // shouldChangeType()?
1800 if (!Cmp.getType()->isVectorTy()) {
1801 Type *WideType = W->getType();
1802 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1803 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1804 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1805 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1806 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1807 }
1808 }
1809
1810 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1811 return I;
1812
1813 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1814 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1815 //
1816 // iff pred isn't signed
1817 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1818 match(And->getOperand(1), m_One())) {
1819 Constant *One = cast<Constant>(And->getOperand(1));
1820 Value *Or = And->getOperand(0);
1821 Value *A, *B, *LShr;
1822 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1823 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1824 unsigned UsesRemoved = 0;
1825 if (And->hasOneUse())
1826 ++UsesRemoved;
1827 if (Or->hasOneUse())
1828 ++UsesRemoved;
1829 if (LShr->hasOneUse())
1830 ++UsesRemoved;
1831
1832 // Compute A & ((1 << B) | 1)
1833 Value *NewOr = nullptr;
1834 if (auto *C = dyn_cast<Constant>(B)) {
1835 if (UsesRemoved >= 1)
1836 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1837 } else {
1838 if (UsesRemoved >= 3)
1839 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1840 /*HasNUW=*/true),
1841 One, Or->getName());
1842 }
1843 if (NewOr) {
1844 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1845 return replaceOperand(Cmp, 0, NewAnd);
1846 }
1847 }
1848 }
1849
1850 return nullptr;
1851}
1852
1853/// Fold icmp (and X, Y), C.
1856 const APInt &C) {
1857 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1858 return I;
1859
1860 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1861 bool TrueIfNeg;
1862 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1863 // ((X - 1) & ~X) < 0 --> X == 0
1864 // ((X - 1) & ~X) >= 0 --> X != 0
1865 Value *X;
1866 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1867 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1868 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1869 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1870 }
1871 // (X & X) < 0 --> X == MinSignedC
1872 // (X & X) > -1 --> X != MinSignedC
1873 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1874 Constant *MinSignedC = ConstantInt::get(
1875 X->getType(),
1876 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1877 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1878 return new ICmpInst(NewPred, X, MinSignedC);
1879 }
1880 }
1881
1882 // TODO: These all require that Y is constant too, so refactor with the above.
1883
1884 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1885 Value *X = And->getOperand(0);
1886 Value *Y = And->getOperand(1);
1887 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1888 if (auto *LI = dyn_cast<LoadInst>(X))
1889 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1890 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1891 if (Instruction *Res =
1892 foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2))
1893 return Res;
1894
1895 if (!Cmp.isEquality())
1896 return nullptr;
1897
1898 // X & -C == -C -> X > u ~C
1899 // X & -C != -C -> X <= u ~C
1900 // iff C is a power of 2
1901 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1902 auto NewPred =
1904 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1905 }
1906
1907 // If we are testing the intersection of 2 select-of-nonzero-constants with no
1908 // common bits set, it's the same as checking if exactly one select condition
1909 // is set:
1910 // ((A ? TC : FC) & (B ? TC : FC)) == 0 --> xor A, B
1911 // ((A ? TC : FC) & (B ? TC : FC)) != 0 --> not(xor A, B)
1912 // TODO: Generalize for non-constant values.
1913 // TODO: Handle signed/unsigned predicates.
1914 // TODO: Handle other bitwise logic connectors.
1915 // TODO: Extend to handle a non-zero compare constant.
1916 if (C.isZero() && (Pred == CmpInst::ICMP_EQ || And->hasOneUse())) {
1917 assert(Cmp.isEquality() && "Not expecting non-equality predicates");
1918 Value *A, *B;
1919 const APInt *TC, *FC;
1920 if (match(X, m_Select(m_Value(A), m_APInt(TC), m_APInt(FC))) &&
1921 match(Y,
1922 m_Select(m_Value(B), m_SpecificInt(*TC), m_SpecificInt(*FC))) &&
1923 !TC->isZero() && !FC->isZero() && !TC->intersects(*FC)) {
1924 Value *R = Builder.CreateXor(A, B);
1925 if (Pred == CmpInst::ICMP_NE)
1926 R = Builder.CreateNot(R);
1927 return replaceInstUsesWith(Cmp, R);
1928 }
1929 }
1930
1931 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1932 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
1933 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
1934 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1936 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
1937 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
1938 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1939 Value *And = Builder.CreateAnd(TruncY, X);
1941 }
1942 return BinaryOperator::CreateAnd(TruncY, X);
1943 }
1944
1945 return nullptr;
1946}
1947
1948/// Fold icmp (or X, Y), C.
1951 const APInt &C) {
1952 ICmpInst::Predicate Pred = Cmp.getPredicate();
1953 if (C.isOne()) {
1954 // icmp slt signum(V) 1 --> icmp slt V, 1
1955 Value *V = nullptr;
1956 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
1957 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1958 ConstantInt::get(V->getType(), 1));
1959 }
1960
1961 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
1962 const APInt *MaskC;
1963 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
1964 if (*MaskC == C && (C + 1).isPowerOf2()) {
1965 // X | C == C --> X <=u C
1966 // X | C != C --> X >u C
1967 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
1969 return new ICmpInst(Pred, OrOp0, OrOp1);
1970 }
1971
1972 // More general: canonicalize 'equality with set bits mask' to
1973 // 'equality with clear bits mask'.
1974 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
1975 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
1976 if (Or->hasOneUse()) {
1977 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
1978 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
1979 return new ICmpInst(Pred, And, NewC);
1980 }
1981 }
1982
1983 // (X | (X-1)) s< 0 --> X s< 1
1984 // (X | (X-1)) s> -1 --> X s> 0
1985 Value *X;
1986 bool TrueIfSigned;
1987 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1989 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
1990 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
1991 return new ICmpInst(NewPred, X, NewC);
1992 }
1993
1994 const APInt *OrC;
1995 // icmp(X | OrC, C) --> icmp(X, 0)
1996 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
1997 switch (Pred) {
1998 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
1999 case ICmpInst::ICMP_SLT:
2000 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2001 case ICmpInst::ICMP_SGE:
2002 if (OrC->sge(C))
2003 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2004 break;
2005 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2006 case ICmpInst::ICMP_SLE:
2007 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2008 case ICmpInst::ICMP_SGT:
2009 if (OrC->sgt(C))
2011 ConstantInt::getNullValue(X->getType()));
2012 break;
2013 default:
2014 break;
2015 }
2016 }
2017
2018 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2019 return nullptr;
2020
2021 Value *P, *Q;
2023 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2024 // -> and (icmp eq P, null), (icmp eq Q, null).
2025 Value *CmpP =
2026 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2027 Value *CmpQ =
2029 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2030 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2031 }
2032
2033 // Are we using xors to bitwise check for a pair of (in)equalities? Convert to
2034 // a shorter form that has more potential to be folded even further.
2035 Value *X1, *X2, *X3, *X4;
2036 if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) &&
2037 match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) {
2038 // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4)
2039 // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4)
2040 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
2041 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
2042 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2043 return BinaryOperator::Create(BOpc, Cmp12, Cmp34);
2044 }
2045
2046 return nullptr;
2047}
2048
2049/// Fold icmp (mul X, Y), C.
2052 const APInt &C) {
2053 ICmpInst::Predicate Pred = Cmp.getPredicate();
2054 Type *MulTy = Mul->getType();
2055 Value *X = Mul->getOperand(0);
2056
2057 // If there's no overflow:
2058 // X * X == 0 --> X == 0
2059 // X * X != 0 --> X != 0
2060 if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
2061 (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
2062 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2063
2064 const APInt *MulC;
2065 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2066 return nullptr;
2067
2068 // If this is a test of the sign bit and the multiply is sign-preserving with
2069 // a constant operand, use the multiply LHS operand instead:
2070 // (X * +MulC) < 0 --> X < 0
2071 // (X * -MulC) < 0 --> X > 0
2072 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2073 if (MulC->isNegative())
2074 Pred = ICmpInst::getSwappedPredicate(Pred);
2075 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2076 }
2077
2078 if (MulC->isZero())
2079 return nullptr;
2080
2081 // If the multiply does not wrap or the constant is odd, try to divide the
2082 // compare constant by the multiplication factor.
2083 if (Cmp.isEquality()) {
2084 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2085 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2086 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2087 return new ICmpInst(Pred, X, NewC);
2088 }
2089
2090 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2091 // correct to transform if MulC * N == C including overflow. I.e with i8
2092 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2093 // miss that case.
2094 if (C.urem(*MulC).isZero()) {
2095 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2096 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2097 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2098 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2099 return new ICmpInst(Pred, X, NewC);
2100 }
2101 }
2102 }
2103
2104 // With a matching no-overflow guarantee, fold the constants:
2105 // (X * MulC) < C --> X < (C / MulC)
2106 // (X * MulC) > C --> X > (C / MulC)
2107 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2108 Constant *NewC = nullptr;
2109 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2110 // MININT / -1 --> overflow.
2111 if (C.isMinSignedValue() && MulC->isAllOnes())
2112 return nullptr;
2113 if (MulC->isNegative())
2114 Pred = ICmpInst::getSwappedPredicate(Pred);
2115
2116 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2117 NewC = ConstantInt::get(
2119 } else {
2120 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2121 "Unexpected predicate");
2122 NewC = ConstantInt::get(
2124 }
2125 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2126 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2127 NewC = ConstantInt::get(
2129 } else {
2130 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2131 "Unexpected predicate");
2132 NewC = ConstantInt::get(
2134 }
2135 }
2136
2137 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2138}
2139
2140/// Fold icmp (shl 1, Y), C.
2142 const APInt &C) {
2143 Value *Y;
2144 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
2145 return nullptr;
2146
2147 Type *ShiftType = Shl->getType();
2148 unsigned TypeBits = C.getBitWidth();
2149 bool CIsPowerOf2 = C.isPowerOf2();
2150 ICmpInst::Predicate Pred = Cmp.getPredicate();
2151 if (Cmp.isUnsigned()) {
2152 // (1 << Y) pred C -> Y pred Log2(C)
2153 if (!CIsPowerOf2) {
2154 // (1 << Y) < 30 -> Y <= 4
2155 // (1 << Y) <= 30 -> Y <= 4
2156 // (1 << Y) >= 30 -> Y > 4
2157 // (1 << Y) > 30 -> Y > 4
2158 if (Pred == ICmpInst::ICMP_ULT)
2159 Pred = ICmpInst::ICMP_ULE;
2160 else if (Pred == ICmpInst::ICMP_UGE)
2161 Pred = ICmpInst::ICMP_UGT;
2162 }
2163
2164 unsigned CLog2 = C.logBase2();
2165 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2166 } else if (Cmp.isSigned()) {
2167 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2168 // (1 << Y) > 0 -> Y != 31
2169 // (1 << Y) > C -> Y != 31 if C is negative.
2170 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2171 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2172
2173 // (1 << Y) < 0 -> Y == 31
2174 // (1 << Y) < 1 -> Y == 31
2175 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2176 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2177 if (Pred == ICmpInst::ICMP_SLT && (C-1).sle(0))
2178 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2179 }
2180
2181 return nullptr;
2182}
2183
2184/// Fold icmp (shl X, Y), C.
2186 BinaryOperator *Shl,
2187 const APInt &C) {
2188 const APInt *ShiftVal;
2189 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2190 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2191
2192 const APInt *ShiftAmt;
2193 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2194 return foldICmpShlOne(Cmp, Shl, C);
2195
2196 // Check that the shift amount is in range. If not, don't perform undefined
2197 // shifts. When the shift is visited, it will be simplified.
2198 unsigned TypeBits = C.getBitWidth();
2199 if (ShiftAmt->uge(TypeBits))
2200 return nullptr;
2201
2202 ICmpInst::Predicate Pred = Cmp.getPredicate();
2203 Value *X = Shl->getOperand(0);
2204 Type *ShType = Shl->getType();
2205
2206 // NSW guarantees that we are only shifting out sign bits from the high bits,
2207 // so we can ASHR the compare constant without needing a mask and eliminate
2208 // the shift.
2209 if (Shl->hasNoSignedWrap()) {
2210 if (Pred == ICmpInst::ICMP_SGT) {
2211 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2212 APInt ShiftedC = C.ashr(*ShiftAmt);
2213 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2214 }
2215 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2216 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2217 APInt ShiftedC = C.ashr(*ShiftAmt);
2218 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2219 }
2220 if (Pred == ICmpInst::ICMP_SLT) {
2221 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2222 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2223 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2224 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2225 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2226 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2227 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2228 }
2229 // If this is a signed comparison to 0 and the shift is sign preserving,
2230 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
2231 // do that if we're sure to not continue on in this function.
2232 if (isSignTest(Pred, C))
2233 return new ICmpInst(Pred, X, Constant::getNullValue(ShType));
2234 }
2235
2236 // NUW guarantees that we are only shifting out zero bits from the high bits,
2237 // so we can LSHR the compare constant without needing a mask and eliminate
2238 // the shift.
2239 if (Shl->hasNoUnsignedWrap()) {
2240 if (Pred == ICmpInst::ICMP_UGT) {
2241 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2242 APInt ShiftedC = C.lshr(*ShiftAmt);
2243 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2244 }
2245 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2246 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2247 APInt ShiftedC = C.lshr(*ShiftAmt);
2248 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2249 }
2250 if (Pred == ICmpInst::ICMP_ULT) {
2251 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2252 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2253 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2254 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2255 assert(C.ugt(0) && "ult 0 should have been eliminated");
2256 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2257 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2258 }
2259 }
2260
2261 if (Cmp.isEquality() && Shl->hasOneUse()) {
2262 // Strength-reduce the shift into an 'and'.
2263 Constant *Mask = ConstantInt::get(
2264 ShType,
2265 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2266 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2267 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2268 return new ICmpInst(Pred, And, LShrC);
2269 }
2270
2271 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2272 bool TrueIfSigned = false;
2273 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2274 // (X << 31) <s 0 --> (X & 1) != 0
2275 Constant *Mask = ConstantInt::get(
2276 ShType,
2277 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2278 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2279 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2280 And, Constant::getNullValue(ShType));
2281 }
2282
2283 // Simplify 'shl' inequality test into 'and' equality test.
2284 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2285 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2286 if ((C + 1).isPowerOf2() &&
2287 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2288 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2289 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2291 And, Constant::getNullValue(ShType));
2292 }
2293 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2294 if (C.isPowerOf2() &&
2295 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2296 Value *And =
2297 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2298 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2300 And, Constant::getNullValue(ShType));
2301 }
2302 }
2303
2304 // Transform (icmp pred iM (shl iM %v, N), C)
2305 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2306 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2307 // This enables us to get rid of the shift in favor of a trunc that may be
2308 // free on the target. It has the additional benefit of comparing to a
2309 // smaller constant that may be more target-friendly.
2310 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2311 if (Shl->hasOneUse() && Amt != 0 && C.countr_zero() >= Amt &&
2312 DL.isLegalInteger(TypeBits - Amt)) {
2313 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2314 if (auto *ShVTy = dyn_cast<VectorType>(ShType))
2315 TruncTy = VectorType::get(TruncTy, ShVTy->getElementCount());
2316 Constant *NewC =
2317 ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2318 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2319 }
2320
2321 return nullptr;
2322}
2323
2324/// Fold icmp ({al}shr X, Y), C.
2326 BinaryOperator *Shr,
2327 const APInt &C) {
2328 // An exact shr only shifts out zero bits, so:
2329 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2330 Value *X = Shr->getOperand(0);
2331 CmpInst::Predicate Pred = Cmp.getPredicate();
2332 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2333 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2334
2335 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2336 const APInt *ShiftValC;
2337 if (match(X, m_APInt(ShiftValC))) {
2338 if (Cmp.isEquality())
2339 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2340
2341 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2342 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2343 bool TrueIfSigned;
2344 if (!IsAShr && ShiftValC->isNegative() &&
2345 isSignBitCheck(Pred, C, TrueIfSigned))
2346 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2347 Shr->getOperand(1),
2348 ConstantInt::getNullValue(X->getType()));
2349
2350 // If the shifted constant is a power-of-2, test the shift amount directly:
2351 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2352 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2353 if (!IsAShr && ShiftValC->isPowerOf2() &&
2354 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2355 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2356 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2357 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2358
2359 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2360 unsigned ShiftLZ = ShiftValC->countl_zero();
2361 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2362 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2363 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2364 }
2365 }
2366
2367 const APInt *ShiftAmtC;
2368 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2369 return nullptr;
2370
2371 // Check that the shift amount is in range. If not, don't perform undefined
2372 // shifts. When the shift is visited it will be simplified.
2373 unsigned TypeBits = C.getBitWidth();
2374 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2375 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2376 return nullptr;
2377
2378 bool IsExact = Shr->isExact();
2379 Type *ShrTy = Shr->getType();
2380 // TODO: If we could guarantee that InstSimplify would handle all of the
2381 // constant-value-based preconditions in the folds below, then we could assert
2382 // those conditions rather than checking them. This is difficult because of
2383 // undef/poison (PR34838).
2384 if (IsAShr) {
2385 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2386 // When ShAmtC can be shifted losslessly:
2387 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2388 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2389 APInt ShiftedC = C.shl(ShAmtVal);
2390 if (ShiftedC.ashr(ShAmtVal) == C)
2391 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2392 }
2393 if (Pred == CmpInst::ICMP_SGT) {
2394 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2395 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2396 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2397 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2398 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2399 }
2400 if (Pred == CmpInst::ICMP_UGT) {
2401 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2402 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2403 // clause accounts for that pattern.
2404 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2405 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2406 (C + 1).shl(ShAmtVal).isMinSignedValue())
2407 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2408 }
2409
2410 // If the compare constant has significant bits above the lowest sign-bit,
2411 // then convert an unsigned cmp to a test of the sign-bit:
2412 // (ashr X, ShiftC) u> C --> X s< 0
2413 // (ashr X, ShiftC) u< C --> X s> -1
2414 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2415 if (Pred == CmpInst::ICMP_UGT) {
2416 return new ICmpInst(CmpInst::ICMP_SLT, X,
2418 }
2419 if (Pred == CmpInst::ICMP_ULT) {
2420 return new ICmpInst(CmpInst::ICMP_SGT, X,
2422 }
2423 }
2424 } else {
2425 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2426 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2427 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2428 APInt ShiftedC = C.shl(ShAmtVal);
2429 if (ShiftedC.lshr(ShAmtVal) == C)
2430 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2431 }
2432 if (Pred == CmpInst::ICMP_UGT) {
2433 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2434 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2435 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2436 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2437 }
2438 }
2439
2440 if (!Cmp.isEquality())
2441 return nullptr;
2442
2443 // Handle equality comparisons of shift-by-constant.
2444
2445 // If the comparison constant changes with the shift, the comparison cannot
2446 // succeed (bits of the comparison constant cannot match the shifted value).
2447 // This should be known by InstSimplify and already be folded to true/false.
2448 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2449 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2450 "Expected icmp+shr simplify did not occur.");
2451
2452 // If the bits shifted out are known zero, compare the unshifted value:
2453 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2454 if (Shr->isExact())
2455 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2456
2457 if (C.isZero()) {
2458 // == 0 is u< 1.
2459 if (Pred == CmpInst::ICMP_EQ)
2460 return new ICmpInst(CmpInst::ICMP_ULT, X,
2461 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal)));
2462 else
2463 return new ICmpInst(CmpInst::ICMP_UGT, X,
2464 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1));
2465 }
2466
2467 if (Shr->hasOneUse()) {
2468 // Canonicalize the shift into an 'and':
2469 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2470 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2471 Constant *Mask = ConstantInt::get(ShrTy, Val);
2472 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2473 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2474 }
2475
2476 return nullptr;
2477}
2478
2480 BinaryOperator *SRem,
2481 const APInt &C) {
2482 // Match an 'is positive' or 'is negative' comparison of remainder by a
2483 // constant power-of-2 value:
2484 // (X % pow2C) sgt/slt 0
2485 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2486 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2487 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2488 return nullptr;
2489
2490 // TODO: The one-use check is standard because we do not typically want to
2491 // create longer instruction sequences, but this might be a special-case
2492 // because srem is not good for analysis or codegen.
2493 if (!SRem->hasOneUse())
2494 return nullptr;
2495
2496 const APInt *DivisorC;
2497 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2498 return nullptr;
2499
2500 // For cmp_sgt/cmp_slt only zero valued C is handled.
2501 // For cmp_eq/cmp_ne only positive valued C is handled.
2502 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2503 !C.isZero()) ||
2504 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2505 !C.isStrictlyPositive()))
2506 return nullptr;
2507
2508 // Mask off the sign bit and the modulo bits (low-bits).
2509 Type *Ty = SRem->getType();
2511 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2512 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2513
2514 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2515 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2516
2517 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2518 // bit is set. Example:
2519 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2520 if (Pred == ICmpInst::ICMP_SGT)
2522
2523 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2524 // bit is set. Example:
2525 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2526 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2527}
2528
2529/// Fold icmp (udiv X, Y), C.
2531 BinaryOperator *UDiv,
2532 const APInt &C) {
2533 ICmpInst::Predicate Pred = Cmp.getPredicate();
2534 Value *X = UDiv->getOperand(0);
2535 Value *Y = UDiv->getOperand(1);
2536 Type *Ty = UDiv->getType();
2537
2538 const APInt *C2;
2539 if (!match(X, m_APInt(C2)))
2540 return nullptr;
2541
2542 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2543
2544 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2545 if (Pred == ICmpInst::ICMP_UGT) {
2546 assert(!C.isMaxValue() &&
2547 "icmp ugt X, UINT_MAX should have been simplified already.");
2548 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2549 ConstantInt::get(Ty, C2->udiv(C + 1)));
2550 }
2551
2552 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2553 if (Pred == ICmpInst::ICMP_ULT) {
2554 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2555 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2556 ConstantInt::get(Ty, C2->udiv(C)));
2557 }
2558
2559 return nullptr;
2560}
2561
2562/// Fold icmp ({su}div X, Y), C.
2564 BinaryOperator *Div,
2565 const APInt &C) {
2566 ICmpInst::Predicate Pred = Cmp.getPredicate();
2567 Value *X = Div->getOperand(0);
2568 Value *Y = Div->getOperand(1);
2569 Type *Ty = Div->getType();
2570 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2571
2572 // If unsigned division and the compare constant is bigger than
2573 // UMAX/2 (negative), there's only one pair of values that satisfies an
2574 // equality check, so eliminate the division:
2575 // (X u/ Y) == C --> (X == C) && (Y == 1)
2576 // (X u/ Y) != C --> (X != C) || (Y != 1)
2577 // Similarly, if signed division and the compare constant is exactly SMIN:
2578 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2579 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2580 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2581 (!DivIsSigned || C.isMinSignedValue())) {
2582 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2583 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2584 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2585 return BinaryOperator::Create(Logic, XBig, YOne);
2586 }
2587
2588 // Fold: icmp pred ([us]div X, C2), C -> range test
2589 // Fold this div into the comparison, producing a range check.
2590 // Determine, based on the divide type, what the range is being
2591 // checked. If there is an overflow on the low or high side, remember
2592 // it, otherwise compute the range [low, hi) bounding the new value.
2593 // See: InsertRangeTest above for the kinds of replacements possible.
2594 const APInt *C2;
2595 if (!match(Y, m_APInt(C2)))
2596 return nullptr;
2597
2598 // FIXME: If the operand types don't match the type of the divide
2599 // then don't attempt this transform. The code below doesn't have the
2600 // logic to deal with a signed divide and an unsigned compare (and
2601 // vice versa). This is because (x /s C2) <s C produces different
2602 // results than (x /s C2) <u C or (x /u C2) <s C or even
2603 // (x /u C2) <u C. Simply casting the operands and result won't
2604 // work. :( The if statement below tests that condition and bails
2605 // if it finds it.
2606 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2607 return nullptr;
2608
2609 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2610 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2611 // division-by-constant cases should be present, we can not assert that they
2612 // have happened before we reach this icmp instruction.
2613 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2614 return nullptr;
2615
2616 // Compute Prod = C * C2. We are essentially solving an equation of
2617 // form X / C2 = C. We solve for X by multiplying C2 and C.
2618 // By solving for X, we can turn this into a range check instead of computing
2619 // a divide.
2620 APInt Prod = C * *C2;
2621
2622 // Determine if the product overflows by seeing if the product is not equal to
2623 // the divide. Make sure we do the same kind of divide as in the LHS
2624 // instruction that we're folding.
2625 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2626
2627 // If the division is known to be exact, then there is no remainder from the
2628 // divide, so the covered range size is unit, otherwise it is the divisor.
2629 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2630
2631 // Figure out the interval that is being checked. For example, a comparison
2632 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2633 // Compute this interval based on the constants involved and the signedness of
2634 // the compare/divide. This computes a half-open interval, keeping track of
2635 // whether either value in the interval overflows. After analysis each
2636 // overflow variable is set to 0 if it's corresponding bound variable is valid
2637 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2638 int LoOverflow = 0, HiOverflow = 0;
2639 APInt LoBound, HiBound;
2640
2641 if (!DivIsSigned) { // udiv
2642 // e.g. X/5 op 3 --> [15, 20)
2643 LoBound = Prod;
2644 HiOverflow = LoOverflow = ProdOV;
2645 if (!HiOverflow) {
2646 // If this is not an exact divide, then many values in the range collapse
2647 // to the same result value.
2648 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2649 }
2650 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2651 if (C.isZero()) { // (X / pos) op 0
2652 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2653 LoBound = -(RangeSize - 1);
2654 HiBound = RangeSize;
2655 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2656 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2657 HiOverflow = LoOverflow = ProdOV;
2658 if (!HiOverflow)
2659 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2660 } else { // (X / pos) op neg
2661 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2662 HiBound = Prod + 1;
2663 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2664 if (!LoOverflow) {
2665 APInt DivNeg = -RangeSize;
2666 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2667 }
2668 }
2669 } else if (C2->isNegative()) { // Divisor is < 0.
2670 if (Div->isExact())
2671 RangeSize.negate();
2672 if (C.isZero()) { // (X / neg) op 0
2673 // e.g. X/-5 op 0 --> [-4, 5)
2674 LoBound = RangeSize + 1;
2675 HiBound = -RangeSize;
2676 if (HiBound == *C2) { // -INTMIN = INTMIN
2677 HiOverflow = 1; // [INTMIN+1, overflow)
2678 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2679 }
2680 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2681 // e.g. X/-5 op 3 --> [-19, -14)
2682 HiBound = Prod + 1;
2683 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2684 if (!LoOverflow)
2685 LoOverflow =
2686 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2687 } else { // (X / neg) op neg
2688 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2689 LoOverflow = HiOverflow = ProdOV;
2690 if (!HiOverflow)
2691 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2692 }
2693
2694 // Dividing by a negative swaps the condition. LT <-> GT
2695 Pred = ICmpInst::getSwappedPredicate(Pred);
2696 }
2697
2698 switch (Pred) {
2699 default:
2700 llvm_unreachable("Unhandled icmp predicate!");
2701 case ICmpInst::ICMP_EQ:
2702 if (LoOverflow && HiOverflow)
2703 return replaceInstUsesWith(Cmp, Builder.getFalse());
2704 if (HiOverflow)
2705 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2706 X, ConstantInt::get(Ty, LoBound));
2707 if (LoOverflow)
2708 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2709 X, ConstantInt::get(Ty, HiBound));
2710 return replaceInstUsesWith(
2711 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2712 case ICmpInst::ICMP_NE:
2713 if (LoOverflow && HiOverflow)
2714 return replaceInstUsesWith(Cmp, Builder.getTrue());
2715 if (HiOverflow)
2716 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2717 X, ConstantInt::get(Ty, LoBound));
2718 if (LoOverflow)
2719 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2720 X, ConstantInt::get(Ty, HiBound));
2721 return replaceInstUsesWith(
2722 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2723 case ICmpInst::ICMP_ULT:
2724 case ICmpInst::ICMP_SLT:
2725 if (LoOverflow == +1) // Low bound is greater than input range.
2726 return replaceInstUsesWith(Cmp, Builder.getTrue());
2727 if (LoOverflow == -1) // Low bound is less than input range.
2728 return replaceInstUsesWith(Cmp, Builder.getFalse());
2729 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
2730 case ICmpInst::ICMP_UGT:
2731 case ICmpInst::ICMP_SGT:
2732 if (HiOverflow == +1) // High bound greater than input range.
2733 return replaceInstUsesWith(Cmp, Builder.getFalse());
2734 if (HiOverflow == -1) // High bound less than input range.
2735 return replaceInstUsesWith(Cmp, Builder.getTrue());
2736 if (Pred == ICmpInst::ICMP_UGT)
2737 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
2738 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
2739 }
2740
2741 return nullptr;
2742}
2743
2744/// Fold icmp (sub X, Y), C.
2746 BinaryOperator *Sub,
2747 const APInt &C) {
2748 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2749 ICmpInst::Predicate Pred = Cmp.getPredicate();
2750 Type *Ty = Sub->getType();
2751
2752 // (SubC - Y) == C) --> Y == (SubC - C)
2753 // (SubC - Y) != C) --> Y != (SubC - C)
2754 Constant *SubC;
2755 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
2756 return new ICmpInst(Pred, Y,
2758 }
2759
2760 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2761 const APInt *C2;
2762 APInt SubResult;
2763 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2764 bool HasNSW = Sub->hasNoSignedWrap();
2765 bool HasNUW = Sub->hasNoUnsignedWrap();
2766 if (match(X, m_APInt(C2)) &&
2767 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2768 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2769 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
2770
2771 // X - Y == 0 --> X == Y.
2772 // X - Y != 0 --> X != Y.
2773 // TODO: We allow this with multiple uses as long as the other uses are not
2774 // in phis. The phi use check is guarding against a codegen regression
2775 // for a loop test. If the backend could undo this (and possibly
2776 // subsequent transforms), we would not need this hack.
2777 if (Cmp.isEquality() && C.isZero() &&
2778 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
2779 return new ICmpInst(Pred, X, Y);
2780
2781 // The following transforms are only worth it if the only user of the subtract
2782 // is the icmp.
2783 // TODO: This is an artificial restriction for all of the transforms below
2784 // that only need a single replacement icmp. Can these use the phi test
2785 // like the transform above here?
2786 if (!Sub->hasOneUse())
2787 return nullptr;
2788
2789 if (Sub->hasNoSignedWrap()) {
2790 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2791 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
2792 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
2793
2794 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2795 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
2796 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2797
2798 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2799 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
2800 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2801
2802 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2803 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
2804 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2805 }
2806
2807 if (!match(X, m_APInt(C2)))
2808 return nullptr;
2809
2810 // C2 - Y <u C -> (Y | (C - 1)) == C2
2811 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2812 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
2813 (*C2 & (C - 1)) == (C - 1))
2814 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
2815
2816 // C2 - Y >u C -> (Y | C) != C2
2817 // iff C2 & C == C and C + 1 is a power of 2
2818 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
2819 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
2820
2821 // We have handled special cases that reduce.
2822 // Canonicalize any remaining sub to add as:
2823 // (C2 - Y) > C --> (Y + ~C2) < ~C
2824 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
2825 HasNUW, HasNSW);
2826 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
2827}
2828
2829/// Fold icmp (add X, Y), C.
2832 const APInt &C) {
2833 Value *Y = Add->getOperand(1);
2834 const APInt *C2;
2835 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
2836 return nullptr;
2837
2838 // Fold icmp pred (add X, C2), C.
2839 Value *X = Add->getOperand(0);
2840 Type *Ty = Add->getType();
2841 const CmpInst::Predicate Pred = Cmp.getPredicate();
2842
2843 // If the add does not wrap, we can always adjust the compare by subtracting
2844 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
2845 // are canonicalized to SGT/SLT/UGT/ULT.
2846 if ((Add->hasNoSignedWrap() &&
2847 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
2848 (Add->hasNoUnsignedWrap() &&
2849 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
2850 bool Overflow;
2851 APInt NewC =
2852 Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
2853 // If there is overflow, the result must be true or false.
2854 // TODO: Can we assert there is no overflow because InstSimplify always
2855 // handles those cases?
2856 if (!Overflow)
2857 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2858 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2859 }
2860
2861 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
2862 const APInt &Upper = CR.getUpper();
2863 const APInt &Lower = CR.getLower();
2864 if (Cmp.isSigned()) {
2865 if (Lower.isSignMask())
2867 if (Upper.isSignMask())
2869 } else {
2870 if (Lower.isMinValue())
2872 if (Upper.isMinValue())
2874 }
2875
2876 // This set of folds is intentionally placed after folds that use no-wrapping
2877 // flags because those folds are likely better for later analysis/codegen.
2880
2881 // Fold compare with offset to opposite sign compare if it eliminates offset:
2882 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
2883 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
2884 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
2885
2886 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
2887 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
2888 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
2889
2890 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
2891 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
2892 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
2893
2894 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
2895 if (Pred == CmpInst::ICMP_SLT && C == *C2)
2896 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
2897
2898 // (X + -1) <u C --> X <=u C (if X is never null)
2899 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
2900 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
2901 if (llvm::isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
2902 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
2903 }
2904
2905 if (!Add->hasOneUse())
2906 return nullptr;
2907
2908 // X+C <u C2 -> (X & -C2) == C
2909 // iff C & (C2-1) == 0
2910 // C2 is a power of 2
2911 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
2913 ConstantExpr::getNeg(cast<Constant>(Y)));
2914
2915 // X+C >u C2 -> (X & ~C2) != C
2916 // iff C & C2 == 0
2917 // C2+1 is a power of 2
2918 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
2920 ConstantExpr::getNeg(cast<Constant>(Y)));
2921
2922 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
2923 // to the ult form.
2924 // X+C2 >u C -> X+(C2-C-1) <u ~C
2925 if (Pred == ICmpInst::ICMP_UGT)
2926 return new ICmpInst(ICmpInst::ICMP_ULT,
2927 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
2928 ConstantInt::get(Ty, ~C));
2929
2930 return nullptr;
2931}
2932
2934 Value *&RHS, ConstantInt *&Less,
2935 ConstantInt *&Equal,
2936 ConstantInt *&Greater) {
2937 // TODO: Generalize this to work with other comparison idioms or ensure
2938 // they get canonicalized into this form.
2939
2940 // select i1 (a == b),
2941 // i32 Equal,
2942 // i32 (select i1 (a < b), i32 Less, i32 Greater)
2943 // where Equal, Less and Greater are placeholders for any three constants.
2944 ICmpInst::Predicate PredA;
2945 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
2946 !ICmpInst::isEquality(PredA))
2947 return false;
2948 Value *EqualVal = SI->getTrueValue();
2949 Value *UnequalVal = SI->getFalseValue();
2950 // We still can get non-canonical predicate here, so canonicalize.
2951 if (PredA == ICmpInst::ICMP_NE)
2952 std::swap(EqualVal, UnequalVal);
2953 if (!match(EqualVal, m_ConstantInt(Equal)))
2954 return false;
2955 ICmpInst::Predicate PredB;
2956 Value *LHS2, *RHS2;
2957 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
2958 m_ConstantInt(Less), m_ConstantInt(Greater))))
2959 return false;
2960 // We can get predicate mismatch here, so canonicalize if possible:
2961 // First, ensure that 'LHS' match.
2962 if (LHS2 != LHS) {
2963 // x sgt y <--> y slt x
2964 std::swap(LHS2, RHS2);
2965 PredB = ICmpInst::getSwappedPredicate(PredB);
2966 }
2967 if (LHS2 != LHS)
2968 return false;
2969 // We also need to canonicalize 'RHS'.
2970 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
2971 // x sgt C-1 <--> x sge C <--> not(x slt C)
2972 auto FlippedStrictness =
2974 PredB, cast<Constant>(RHS2));
2975 if (!FlippedStrictness)
2976 return false;
2977 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
2978 "basic correctness failure");
2979 RHS2 = FlippedStrictness->second;
2980 // And kind-of perform the result swap.
2981 std::swap(Less, Greater);
2982 PredB = ICmpInst::ICMP_SLT;
2983 }
2984 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
2985}
2986
2989 ConstantInt *C) {
2990
2991 assert(C && "Cmp RHS should be a constant int!");
2992 // If we're testing a constant value against the result of a three way
2993 // comparison, the result can be expressed directly in terms of the
2994 // original values being compared. Note: We could possibly be more
2995 // aggressive here and remove the hasOneUse test. The original select is
2996 // really likely to simplify or sink when we remove a test of the result.
2997 Value *OrigLHS, *OrigRHS;
2998 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2999 if (Cmp.hasOneUse() &&
3000 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3001 C3GreaterThan)) {
3002 assert(C1LessThan && C2Equal && C3GreaterThan);
3003
3004 bool TrueWhenLessThan =
3005 ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
3006 ->isAllOnesValue();
3007 bool TrueWhenEqual =
3008 ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
3009 ->isAllOnesValue();
3010 bool TrueWhenGreaterThan =
3011 ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
3012 ->isAllOnesValue();
3013
3014 // This generates the new instruction that will replace the original Cmp
3015 // Instruction. Instead of enumerating the various combinations when
3016 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3017 // false, we rely on chaining of ORs and future passes of InstCombine to
3018 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3019
3020 // When none of the three constants satisfy the predicate for the RHS (C),
3021 // the entire original Cmp can be simplified to a false.
3023 if (TrueWhenLessThan)
3025 OrigLHS, OrigRHS));
3026 if (TrueWhenEqual)
3028 OrigLHS, OrigRHS));
3029 if (TrueWhenGreaterThan)
3031 OrigLHS, OrigRHS));
3032
3033 return replaceInstUsesWith(Cmp, Cond);
3034 }
3035 return nullptr;
3036}
3037
3039 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3040 if (!Bitcast)
3041 return nullptr;
3042
3043 ICmpInst::Predicate Pred = Cmp.getPredicate();
3044 Value *Op1 = Cmp.getOperand(1);
3045 Value *BCSrcOp = Bitcast->getOperand(0);
3046 Type *SrcType = Bitcast->getSrcTy();
3047 Type *DstType = Bitcast->getType();
3048
3049 // Make sure the bitcast doesn't change between scalar and vector and
3050 // doesn't change the number of vector elements.
3051 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3052 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3053 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3054 Value *X;
3055 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3056 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3057 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3058 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3059 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3060 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3061 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3062 match(Op1, m_Zero()))
3063 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3064
3065 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3066 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3067 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3068
3069 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3070 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3071 return new ICmpInst(Pred, X,
3072 ConstantInt::getAllOnesValue(X->getType()));
3073 }
3074
3075 // Zero-equality checks are preserved through unsigned floating-point casts:
3076 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3077 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3078 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3079 if (Cmp.isEquality() && match(Op1, m_Zero()))
3080 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3081
3082 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3083 // the FP extend/truncate because that cast does not change the sign-bit.
3084 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3085 // The sign-bit is always the most significant bit in those types.
3086 const APInt *C;
3087 bool TrueIfSigned;
3088 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse() &&
3089 isSignBitCheck(Pred, *C, TrueIfSigned)) {
3090 if (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3091 match(BCSrcOp, m_FPTrunc(m_Value(X)))) {
3092 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3093 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3094 Type *XType = X->getType();
3095
3096 // We can't currently handle Power style floating point operations here.
3097 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3098 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3099 if (auto *XVTy = dyn_cast<VectorType>(XType))
3100 NewType = VectorType::get(NewType, XVTy->getElementCount());
3101 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3102 if (TrueIfSigned)
3103 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3104 ConstantInt::getNullValue(NewType));
3105 else
3106 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3108 }
3109 }
3110 }
3111 }
3112
3113 // Test to see if the operands of the icmp are casted versions of other
3114 // values. If the ptr->ptr cast can be stripped off both arguments, do so.
3115 if (DstType->isPointerTy() && (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
3116 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3117 // so eliminate it as well.
3118 if (auto *BC2 = dyn_cast<BitCastInst>(Op1))
3119 Op1 = BC2->getOperand(0);
3120
3121 Op1 = Builder.CreateBitCast(Op1, SrcType);
3122 return new ICmpInst(Pred, BCSrcOp, Op1);
3123 }
3124
3125 const APInt *C;
3126 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3127 !SrcType->isIntOrIntVectorTy())
3128 return nullptr;
3129
3130 // If this is checking if all elements of a vector compare are set or not,
3131 // invert the casted vector equality compare and test if all compare
3132 // elements are clear or not. Compare against zero is generally easier for
3133 // analysis and codegen.
3134 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3135 // Example: are all elements equal? --> are zero elements not equal?
3136 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3137 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse() &&
3138 isFreeToInvert(BCSrcOp, BCSrcOp->hasOneUse())) {
3139 Value *Cast = Builder.CreateBitCast(Builder.CreateNot(BCSrcOp), DstType);
3140 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3141 }
3142
3143 // If this is checking if all elements of an extended vector are clear or not,
3144 // compare in a narrow type to eliminate the extend:
3145 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3146 Value *X;
3147 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3148 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3149 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3150 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3151 Value *NewCast = Builder.CreateBitCast(X, NewType);
3152 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3153 }
3154 }
3155
3156 // Folding: icmp <pred> iN X, C
3157 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3158 // and C is a splat of a K-bit pattern
3159 // and SC is a constant vector = <C', C', C', ..., C'>
3160 // Into:
3161 // %E = extractelement <M x iK> %vec, i32 C'
3162 // icmp <pred> iK %E, trunc(C)
3163 Value *Vec;
3164 ArrayRef<int> Mask;
3165 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3166 // Check whether every element of Mask is the same constant
3167 if (all_equal(Mask)) {
3168 auto *VecTy = cast<VectorType>(SrcType);
3169 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3170 if (C->isSplat(EltTy->getBitWidth())) {
3171 // Fold the icmp based on the value of C
3172 // If C is M copies of an iK sized bit pattern,
3173 // then:
3174 // => %E = extractelement <N x iK> %vec, i32 Elem
3175 // icmp <pred> iK %SplatVal, <pattern>
3176 Value *Elem = Builder.getInt32(Mask[0]);
3177 Value *Extract = Builder.CreateExtractElement(Vec, Elem);
3178 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3179 return new ICmpInst(Pred, Extract, NewC);
3180 }
3181 }
3182 }
3183 return nullptr;
3184}
3185
3186/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3187/// where X is some kind of instruction.
3189 const APInt *C;
3190
3191 if (match(Cmp.getOperand(1), m_APInt(C))) {
3192 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3193 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3194 return I;
3195
3196 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3197 // For now, we only support constant integers while folding the
3198 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3199 // similar to the cases handled by binary ops above.
3200 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3201 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3202 return I;
3203
3204 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3205 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3206 return I;
3207
3208 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3209 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
3210 return I;
3211
3212 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3213 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3214 // TODO: This checks one-use, but that is not strictly necessary.
3215 Value *Cmp0 = Cmp.getOperand(0);
3216 Value *X, *Y;
3217 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3218 (match(Cmp0,
3219 m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
3220 m_Value(X), m_Value(Y)))) ||
3221 match(Cmp0,
3222 m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
3223 m_Value(X), m_Value(Y))))))
3224 return new ICmpInst(Cmp.getPredicate(), X, Y);
3225 }
3226
3227 if (match(Cmp.getOperand(1), m_APIntAllowUndef(C)))
3229
3230 return nullptr;
3231}
3232
3233/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3234/// icmp eq/ne BO, C.
3236 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3237 // TODO: Some of these folds could work with arbitrary constants, but this
3238 // function is limited to scalar and vector splat constants.
3239 if (!Cmp.isEquality())
3240 return nullptr;
3241
3242 ICmpInst::Predicate Pred = Cmp.getPredicate();
3243 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3244 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3245 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3246
3247 switch (BO->getOpcode()) {
3248 case Instruction::SRem:
3249 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3250 if (C.isZero() && BO->hasOneUse()) {
3251 const APInt *BOC;
3252 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3253 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3254 return new ICmpInst(Pred, NewRem,
3256 }
3257 }
3258 break;
3259 case Instruction::Add: {
3260 // (A + C2) == C --> A == (C - C2)
3261 // (A + C2) != C --> A != (C - C2)
3262 // TODO: Remove the one-use limitation? See discussion in D58633.
3263 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3264 if (BO->hasOneUse())
3265 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3266 } else if (C.isZero()) {
3267 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3268 // efficiently invertible, or if the add has just this one use.
3269 if (Value *NegVal = dyn_castNegVal(BOp1))
3270 return new ICmpInst(Pred, BOp0, NegVal);
3271 if (Value *NegVal = dyn_castNegVal(BOp0))
3272 return new ICmpInst(Pred, NegVal, BOp1);
3273 if (BO->hasOneUse()) {
3274 Value *Neg = Builder.CreateNeg(BOp1);
3275 Neg->takeName(BO);
3276 return new ICmpInst(Pred, BOp0, Neg);
3277 }
3278 }
3279 break;
3280 }
3281 case Instruction::Xor:
3282 if (BO->hasOneUse()) {
3283 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3284 // For the xor case, we can xor two constants together, eliminating
3285 // the explicit xor.
3286 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3287 } else if (C.isZero()) {
3288 // Replace ((xor A, B) != 0) with (A != B)
3289 return new ICmpInst(Pred, BOp0, BOp1);
3290 }
3291 }
3292 break;
3293 case Instruction::Or: {
3294 const APInt *BOC;
3295 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3296 // Comparing if all bits outside of a constant mask are set?
3297 // Replace (X | C) == -1 with (X & ~C) == ~C.
3298 // This removes the -1 constant.
3299 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
3300 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3301 return new ICmpInst(Pred, And, NotBOC);
3302 }
3303 break;
3304 }
3305 case Instruction::UDiv:
3306 if (C.isZero()) {
3307 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3308 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3309 return new ICmpInst(NewPred, BOp1, BOp0);
3310 }
3311 break;
3312 default:
3313 break;
3314 }
3315 return nullptr;
3316}
3317
3318/// Fold an equality icmp with LLVM intrinsic and constant operand.
3320 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3321 Type *Ty = II->getType();
3322 unsigned BitWidth = C.getBitWidth();
3323 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3324
3325 switch (II->getIntrinsicID()) {
3326 case Intrinsic::abs:
3327 // abs(A) == 0 -> A == 0
3328 // abs(A) == INT_MIN -> A == INT_MIN
3329 if (C.isZero() || C.isMinSignedValue())
3330 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3331 break;
3332
3333 case Intrinsic::bswap:
3334 // bswap(A) == C -> A == bswap(C)
3335 return new ICmpInst(Pred, II->getArgOperand(0),
3336 ConstantInt::get(Ty, C.byteSwap()));
3337
3338 case Intrinsic::bitreverse:
3339 // bitreverse(A) == C -> A == bitreverse(C)
3340 return new ICmpInst(Pred, II->getArgOperand(0),
3341 ConstantInt::get(Ty, C.reverseBits()));
3342
3343 case Intrinsic::ctlz:
3344 case Intrinsic::cttz: {
3345 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3346 if (C == BitWidth)
3347 return new ICmpInst(Pred, II->getArgOperand(0),
3349
3350 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3351 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3352 // Limit to one use to ensure we don't increase instruction count.
3353 unsigned Num = C.getLimitedValue(BitWidth);
3354 if (Num != BitWidth && II->hasOneUse()) {
3355 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3356 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3357 : APInt::getHighBitsSet(BitWidth, Num + 1);
3358 APInt Mask2 = IsTrailing
3361 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3362 ConstantInt::get(Ty, Mask2));
3363 }
3364 break;
3365 }
3366
3367 case Intrinsic::ctpop: {
3368 // popcount(A) == 0 -> A == 0 and likewise for !=
3369 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3370 bool IsZero = C.isZero();
3371 if (IsZero || C == BitWidth)
3372 return new ICmpInst(Pred, II->getArgOperand(0),
3373 IsZero ? Constant::getNullValue(Ty)
3375
3376 break;
3377 }
3378
3379 case Intrinsic::fshl:
3380 case Intrinsic::fshr:
3381 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3382 const APInt *RotAmtC;
3383 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3384 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3385 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3386 return new ICmpInst(Pred, II->getArgOperand(0),
3387 II->getIntrinsicID() == Intrinsic::fshl
3388 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3389 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3390 }
3391 break;
3392
3393 case Intrinsic::umax:
3394 case Intrinsic::uadd_sat: {
3395 // uadd.sat(a, b) == 0 -> (a | b) == 0
3396 // umax(a, b) == 0 -> (a | b) == 0
3397 if (C.isZero() && II->hasOneUse()) {
3399 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3400 }
3401 break;
3402 }
3403
3404 case Intrinsic::ssub_sat:
3405 // ssub.sat(a, b) == 0 -> a == b
3406 if (C.isZero())
3407 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
3408 break;
3409 case Intrinsic::usub_sat: {
3410 // usub.sat(a, b) == 0 -> a <= b
3411 if (C.isZero()) {
3412 ICmpInst::Predicate NewPred =
3414 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
3415 }
3416 break;
3417 }
3418 default:
3419 break;
3420 }
3421
3422 return nullptr;
3423}
3424
3425/// Fold an icmp with LLVM intrinsics
3427 assert(Cmp.isEquality());
3428
3429 ICmpInst::Predicate Pred = Cmp.getPredicate();
3430 Value *Op0 = Cmp.getOperand(0);
3431 Value *Op1 = Cmp.getOperand(1);
3432 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3433 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3434 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3435 return nullptr;
3436
3437 switch (IIOp0->getIntrinsicID()) {
3438 case Intrinsic::bswap:
3439 case Intrinsic::bitreverse:
3440 // If both operands are byte-swapped or bit-reversed, just compare the
3441 // original values.
3442 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3443 case Intrinsic::fshl:
3444 case Intrinsic::fshr:
3445 // If both operands are rotated by same amount, just compare the
3446 // original values.
3447 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3448 break;
3449 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3450 break;
3451 if (IIOp0->getOperand(2) != IIOp1->getOperand(2))
3452 break;
3453 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3454 default:
3455 break;
3456 }
3457
3458 return nullptr;
3459}
3460
3461/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3462/// where X is some kind of instruction and C is AllowUndef.
3463/// TODO: Move more folds which allow undef to this function.
3466 const APInt &C) {
3467 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3468 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3469 switch (II->getIntrinsicID()) {
3470 default:
3471 break;
3472 case Intrinsic::fshl:
3473 case Intrinsic::fshr:
3474 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
3475 // (rot X, ?) == 0/-1 --> X == 0/-1
3476 if (C.isZero() || C.isAllOnes())
3477 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
3478 }
3479 break;
3480 }
3481 }
3482
3483 return nullptr;
3484}
3485
3486/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
3488 BinaryOperator *BO,
3489 const APInt &C) {
3490 switch (BO->getOpcode()) {
3491 case Instruction::Xor:
3492 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
3493 return I;
3494 break;
3495 case Instruction::And:
3496 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
3497 return I;
3498 break;
3499 case Instruction::Or:
3500 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
3501 return I;
3502 break;
3503 case Instruction::Mul:
3504 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
3505 return I;
3506 break;
3507 case Instruction::Shl:
3508 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
3509 return I;
3510 break;
3511 case Instruction::LShr:
3512 case Instruction::AShr:
3513 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
3514 return I;
3515 break;
3516 case Instruction::SRem:
3517 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
3518 return I;
3519 break;
3520 case Instruction::UDiv:
3521 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
3522 return I;
3523 [[fallthrough]];
3524 case Instruction::SDiv:
3525 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
3526 return I;
3527 break;
3528 case Instruction::Sub:
3529 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
3530 return I;
3531 break;
3532 case Instruction::Add:
3533 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
3534 return I;
3535 break;
3536 default:
3537 break;
3538 }
3539
3540 // TODO: These folds could be refactored to be part of the above calls.
3541 return foldICmpBinOpEqualityWithConstant(Cmp, BO, C);
3542}
3543
3544/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
3546 IntrinsicInst *II,
3547 const APInt &C) {
3548 if (Cmp.isEquality())
3549 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
3550
3551 Type *Ty = II->getType();
3552 unsigned BitWidth = C.getBitWidth();
3553 ICmpInst::Predicate Pred = Cmp.getPredicate();
3554 switch (II->getIntrinsicID()) {
3555 case Intrinsic::ctpop: {
3556 // (ctpop X > BitWidth - 1) --> X == -1
3557 Value *X = II->getArgOperand(0);
3558 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
3559 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
3561 // (ctpop X < BitWidth) --> X != -1
3562 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
3563 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
3565 break;
3566 }
3567 case Intrinsic::ctlz: {
3568 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
3569 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3570 unsigned Num = C.getLimitedValue();
3571 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3572 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
3573 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3574 }
3575
3576 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
3577 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3578 unsigned Num = C.getLimitedValue();
3580 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
3581 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3582 }
3583 break;
3584 }
3585 case Intrinsic::cttz: {
3586 // Limit to one use to ensure we don't increase instruction count.
3587 if (!II->hasOneUse())
3588 return nullptr;
3589
3590 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
3591 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3592 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
3593 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
3594 Builder.CreateAnd(II->getArgOperand(0), Mask),
3596 }
3597
3598 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
3599 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3600 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
3601 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
3602 Builder.CreateAnd(II->getArgOperand(0), Mask),
3604 }
3605 break;
3606 }
3607 case Intrinsic::ssub_sat:
3608 // ssub.sat(a, b) spred 0 -> a spred b
3609 if (ICmpInst::isSigned(Pred)) {
3610 if (C.isZero())
3611 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
3612 // X s<= 0 is cannonicalized to X s< 1
3613 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3614 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
3615 II->getArgOperand(1));
3616 // X s>= 0 is cannonicalized to X s> -1
3617 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3618 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
3619 II->getArgOperand(1));
3620 }
3621 break;
3622 default:
3623 break;
3624 }
3625
3626 return nullptr;
3627}
3628
3629/// Handle icmp with constant (but not simple integer constant) RHS.
3631 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3632 Constant *RHSC = dyn_cast<Constant>(Op1);
3633 Instruction *LHSI = dyn_cast<Instruction>(Op0);
3634 if (!RHSC || !LHSI)
3635 return nullptr;
3636
3637 switch (LHSI->getOpcode()) {
3638 case Instruction::GetElementPtr:
3639 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3640 if (RHSC->isNullValue() &&
3641 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3642 return new ICmpInst(
3643 I.getPredicate(), LHSI->getOperand(0),
3645 break;
3646 case Instruction::PHI:
3647 // Only fold icmp into the PHI if the phi and icmp are in the same
3648 // block. If in the same block, we're encouraging jump threading. If
3649 // not, we are just pessimizing the code by making an i1 phi.
3650 if (LHSI->getParent() == I.getParent())
3651 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3652 return NV;
3653 break;
3654 case Instruction::IntToPtr:
3655 // icmp pred inttoptr(X), null -> icmp pred X, 0
3656 if (RHSC->isNullValue() &&
3657 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3658 return new ICmpInst(
3659 I.getPredicate(), LHSI->getOperand(0),
3661 break;
3662
3663 case Instruction::Load:
3664 // Try to optimize things like "A[i] > 4" to index computations.
3665 if (GetElementPtrInst *GEP =
3666 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
3667 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3668 if (Instruction *Res =
3669 foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I))
3670 return Res;
3671 break;
3672 }
3673
3674 return nullptr;
3675}
3676
3678 SelectInst *SI, Value *RHS,
3679 const ICmpInst &I) {
3680 // Try to fold the comparison into the select arms, which will cause the
3681 // select to be converted into a logical and/or.
3682 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
3683 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
3684 return Res;
3685 if (std::optional<bool> Impl = isImpliedCondition(
3686 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
3687 return ConstantInt::get(I.getType(), *Impl);
3688 return nullptr;
3689 };
3690
3691 ConstantInt *CI = nullptr;
3692 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
3693 if (Op1)
3694 CI = dyn_cast<ConstantInt>(Op1);
3695
3696 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
3697 if (Op2)
3698 CI = dyn_cast<ConstantInt>(Op2);
3699
3700 // We only want to perform this transformation if it will not lead to
3701 // additional code. This is true if either both sides of the select
3702 // fold to a constant (in which case the icmp is replaced with a select
3703 // which will usually simplify) or this is the only user of the
3704 // select (in which case we are trading a select+icmp for a simpler
3705 // select+icmp) or all uses of the select can be replaced based on
3706 // dominance information ("Global cases").
3707 bool Transform = false;
3708 if (Op1 && Op2)
3709 Transform = true;
3710 else if (Op1 || Op2) {
3711 // Local case
3712 if (SI->hasOneUse())
3713 Transform = true;
3714 // Global cases
3715 else if (CI && !CI->isZero())
3716 // When Op1 is constant try replacing select with second operand.
3717 // Otherwise Op2 is constant and try replacing select with first
3718 // operand.
3719 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
3720 }
3721 if (Transform) {
3722 if (!Op1)
3723 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
3724 if (!Op2)
3725 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
3726 return SelectInst::Create(SI->getOperand(0), Op1, Op2);
3727 }
3728
3729 return nullptr;
3730}
3731
3732/// Some comparisons can be simplified.
3733/// In this case, we are looking for comparisons that look like
3734/// a check for a lossy truncation.
3735/// Folds:
3736/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
3737/// Where Mask is some pattern that produces all-ones in low bits:
3738/// (-1 >> y)
3739/// ((-1 << y) >> y) <- non-canonical, has extra uses
3740/// ~(-1 << y)
3741/// ((1 << y) + (-1)) <- non-canonical, has extra uses
3742/// The Mask can be a constant, too.
3743/// For some predicates, the operands are commutative.
3744/// For others, x can only be on a specific side.
3746 InstCombiner::BuilderTy &Builder) {
3747 ICmpInst::Predicate SrcPred;
3748 Value *X, *M, *Y;
3749 auto m_VariableMask = m_CombineOr(
3751 m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
3754 auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
3755 if (!match(&I, m_c_ICmp(SrcPred,
3757 m_Deferred(X))))
3758 return nullptr;
3759
3760 ICmpInst::Predicate DstPred;
3761 switch (SrcPred) {
3763 // x & (-1 >> y) == x -> x u<= (-1 >> y)
3765 break;
3767 // x & (-1 >> y) != x -> x u> (-1 >> y)
3769 break;
3771 // x & (-1 >> y) u< x -> x u> (-1 >> y)
3772 // x u> x & (-1 >> y) -> x u> (-1 >> y)
3774 break;
3776 // x & (-1 >> y) u>= x -> x u<= (-1 >> y)
3777 // x u<= x & (-1 >> y) -> x u<= (-1 >> y)
3779 break;
3781 // x & (-1 >> y) s< x -> x s> (-1 >> y)
3782 // x s> x & (-1 >> y) -> x s> (-1 >> y)
3783 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3784 return nullptr;
3785 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3786 return nullptr;
3788 break;
3790 // x & (-1 >> y) s>= x -> x s<= (-1 >> y)
3791 // x s<= x & (-1 >> y) -> x s<= (-1 >> y)
3792 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3793 return nullptr;
3794 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3795 return nullptr;
3797 break;
3800 return nullptr;
3803 llvm_unreachable("Instsimplify took care of commut. variant");
3804 break;
3805 default:
3806 llvm_unreachable("All possible folds are handled.");
3807 }
3808
3809 // The mask value may be a vector constant that has undefined elements. But it
3810 // may not be safe to propagate those undefs into the new compare, so replace
3811 // those elements by copying an existing, defined, and safe scalar constant.
3812 Type *OpTy = M->getType();
3813 auto *VecC = dyn_cast<Constant>(M);
3814 auto *OpVTy = dyn_cast<FixedVectorType>(OpTy);
3815 if (OpVTy && VecC && VecC->containsUndefOrPoisonElement()) {
3816 Constant *SafeReplacementConstant = nullptr;
3817 for (unsigned i = 0, e = OpVTy->getNumElements(); i != e; ++i) {
3818 if (!isa<UndefValue>(VecC->getAggregateElement(i))) {
3819 SafeReplacementConstant = VecC->getAggregateElement(i);
3820 break;
3821 }
3822 }
3823 assert(SafeReplacementConstant && "Failed to find undef replacement");
3824 M = Constant::replaceUndefsWith(VecC, SafeReplacementConstant);
3825 }
3826
3827 return Builder.CreateICmp(DstPred, X, M);
3828}
3829
3830/// Some comparisons can be simplified.
3831/// In this case, we are looking for comparisons that look like
3832/// a check for a lossy signed truncation.
3833/// Folds: (MaskedBits is a constant.)
3834/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
3835/// Into:
3836/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
3837/// Where KeptBits = bitwidth(%x) - MaskedBits
3838static Value *
3840 InstCombiner::BuilderTy &Builder) {
3841 ICmpInst::Predicate SrcPred;
3842 Value *X;
3843 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
3844 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
3845 if (!match(&I, m_c_ICmp(SrcPred,
3847 m_APInt(C1))),
3848 m_Deferred(X))))
3849 return nullptr;
3850
3851 // Potential handling of non-splats: for each element:
3852 // * if both are undef, replace with constant 0.
3853 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
3854 // * if both are not undef, and are different, bailout.
3855 // * else, only one is undef, then pick the non-undef one.
3856
3857 // The shift amount must be equal.
3858 if (*C0 != *C1)
3859 return nullptr;
3860 const APInt &MaskedBits = *C0;
3861 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
3862
3863 ICmpInst::Predicate DstPred;
3864 switch (SrcPred) {
3866 // ((%x << MaskedBits) a>> MaskedBits) == %x
3867 // =>
3868 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
3870 break;
3872 // ((%x << MaskedBits) a>> MaskedBits) != %x
3873 // =>
3874 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
3876 break;
3877 // FIXME: are more folds possible?
3878 default:
3879 return nullptr;
3880 }
3881
3882 auto *XType = X->getType();
3883 const unsigned XBitWidth = XType->getScalarSizeInBits();
3884 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
3885 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
3886
3887 // KeptBits = bitwidth(%x) - MaskedBits
3888 const APInt KeptBits = BitWidth - MaskedBits;
3889 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
3890 // ICmpCst = (1 << KeptBits)
3891 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
3892 assert(ICmpCst.isPowerOf2());
3893 // AddCst = (1 << (KeptBits-1))
3894 const APInt AddCst = ICmpCst.lshr(1);
3895 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
3896
3897 // T0 = add %x, AddCst
3898 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
3899 // T1 = T0 DstPred ICmpCst
3900 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
3901
3902 return T1;
3903}
3904
3905// Given pattern:
3906// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3907// we should move shifts to the same hand of 'and', i.e. rewrite as
3908// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3909// We are only interested in opposite logical shifts here.
3910// One of the shifts can be truncated.
3911// If we can, we want to end up creating 'lshr' shift.
3912static Value *
3914 InstCombiner::BuilderTy &Builder) {
3915 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
3916 !I.getOperand(0)->hasOneUse())
3917 return nullptr;
3918
3919 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
3920
3921 // Look for an 'and' of two logical shifts, one of which may be truncated.
3922 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
3923 Instruction *XShift, *MaybeTruncation, *YShift;
3924 if (!match(
3925 I.getOperand(0),
3926 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
3928 m_AnyLogicalShift, m_Instruction(YShift))),
3929 m_Instruction(MaybeTruncation)))))
3930 return nullptr;
3931
3932 // We potentially looked past 'trunc', but only when matching YShift,
3933 // therefore YShift must have the widest type.
3934 Instruction *WidestShift = YShift;
3935 // Therefore XShift must have the shallowest type.
3936 // Or they both have identical types if there was no truncation.
3937 Instruction *NarrowestShift = XShift;
3938
3939 Type *WidestTy = WidestShift->getType();
3940 Type *NarrowestTy = NarrowestShift->getType();
3941 assert(NarrowestTy == I.getOperand(0)->getType() &&
3942 "We did not look past any shifts while matching XShift though.");
3943 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
3944
3945 // If YShift is a 'lshr', swap the shifts around.
3946 if (match(YShift, m_LShr(m_Value(), m_Value())))
3947 std::swap(XShift, YShift);
3948
3949 // The shifts must be in opposite directions.
3950 auto XShiftOpcode = XShift->getOpcode();
3951 if (XShiftOpcode == YShift->getOpcode())
3952 return nullptr; // Do not care about same-direction shifts here.
3953
3954 Value *X, *XShAmt, *Y, *YShAmt;
3955 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
3956 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
3957
3958 // If one of the values being shifted is a constant, then we will end with
3959 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
3960 // however, we will need to ensure that we won't increase instruction count.
3961 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
3962 // At least one of the hands of the 'and' should be one-use shift.
3963 if (!match(I.getOperand(0),
3964 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
3965 return nullptr;
3966 if (HadTrunc) {
3967 // Due to the 'trunc', we will need to widen X. For that either the old
3968 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
3969 if (!MaybeTruncation->hasOneUse() &&
3970 !NarrowestShift->getOperand(1)->hasOneUse())
3971 return nullptr;
3972 }
3973 }
3974
3975 // We have two shift amounts from two different shifts. The types of those
3976 // shift amounts may not match. If that's the case let's bailout now.
3977 if (XShAmt->getType() != YShAmt->getType())
3978 return nullptr;
3979
3980 // As input, we have the following pattern:
3981 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3982 // We want to rewrite that as:
3983 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3984 // While we know that originally (Q+K) would not overflow
3985 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
3986 // shift amounts. so it may now overflow in smaller bitwidth.
3987 // To ensure that does not happen, we need to ensure that the total maximal
3988 // shift amount is still representable in that smaller bit width.
3989 unsigned MaximalPossibleTotalShiftAmount =
3990 (WidestTy->getScalarSizeInBits() - 1) +
3991 (NarrowestTy->getScalarSizeInBits() - 1);
3992 APInt MaximalRepresentableShiftAmount =
3994 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
3995 return nullptr;
3996
3997 // Can we fold (XShAmt+YShAmt) ?
3998 auto *NewShAmt = dyn_cast_or_null<Constant>(
3999 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
4000 /*isNUW=*/false, SQ.getWithInstruction(&I)));
4001 if (!NewShAmt)
4002 return nullptr;
4003 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy);
4004 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4005
4006 // Is the new shift amount smaller than the bit width?
4007 // FIXME: could also rely on ConstantRange.
4008 if (!match(NewShAmt,
4010 APInt(WidestBitWidth, WidestBitWidth))))
4011 return nullptr;
4012
4013 // An extra legality check is needed if we had trunc-of-lshr.
4014 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
4015 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4016 WidestShift]() {
4017 // It isn't obvious whether it's worth it to analyze non-constants here.
4018 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4019 // If *any* of these preconditions matches we can perform the fold.
4020 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4021 ? NewShAmt->getSplatValue()
4022 : NewShAmt;
4023 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4024 if (NewShAmtSplat &&
4025 (NewShAmtSplat->isNullValue() ||
4026 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4027 return true;
4028 // We consider *min* leading zeros so a single outlier
4029 // blocks the transform as opposed to allowing it.
4030 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
4031 KnownBits Known = computeKnownBits(C, SQ.DL);
4032 unsigned MinLeadZero = Known.countMinLeadingZeros();
4033 // If the value being shifted has at most lowest bit set we can fold.
4034 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4035 if (MaxActiveBits <= 1)
4036 return true;
4037 // Precondition: NewShAmt u<= countLeadingZeros(C)
4038 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
4039 return true;
4040 }
4041 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
4042 KnownBits Known = computeKnownBits(C, SQ.DL);
4043 unsigned MinLeadZero = Known.countMinLeadingZeros();
4044 // If the value being shifted has at most lowest bit set we can fold.
4045 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4046 if (MaxActiveBits <= 1)
4047 return true;
4048 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
4049 if (NewShAmtSplat) {
4050 APInt AdjNewShAmt =
4051 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
4052 if (AdjNewShAmt.ule(MinLeadZero))
4053 return true;
4054 }
4055 }
4056 return false; // Can't tell if it's ok.
4057 };
4058 if (!CanFold())
4059 return nullptr;
4060 }
4061
4062 // All good, we can do this fold.
4063 X = Builder.CreateZExt(X, WidestTy);
4064 Y = Builder.CreateZExt(Y, WidestTy);
4065 // The shift is the same that was for X.
4066 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4067 ? Builder.CreateLShr(X, NewShAmt)
4068 : Builder.CreateShl(X, NewShAmt);
4069 Value *T1 = Builder.CreateAnd(T0, Y);
4070 return Builder.CreateICmp(I.getPredicate(), T1,
4071 Constant::getNullValue(WidestTy));
4072}
4073
4074/// Fold
4075/// (-1 u/ x) u< y
4076/// ((x * y) ?/ x) != y
4077/// to
4078/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4079/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4080/// will mean that we are looking for the opposite answer.
4083 Value *X, *Y;
4085 Instruction *Div;
4086 bool NeedNegation;
4087 // Look for: (-1 u/ x) u</u>= y
4088 if (!I.isEquality() &&
4089 match(&I, m_c_ICmp(Pred,
4091 m_Instruction(Div)),
4092 m_Value(Y)))) {
4093 Mul = nullptr;
4094
4095 // Are we checking that overflow does not happen, or does happen?
4096 switch (Pred) {
4098 NeedNegation = false;
4099 break; // OK
4101 NeedNegation = true;
4102 break; // OK
4103 default:
4104 return nullptr; // Wrong predicate.
4105 }
4106 } else // Look for: ((x * y) / x) !=/== y
4107 if (I.isEquality() &&
4108 match(&I,
4109 m_c_ICmp(Pred, m_Value(Y),
4112 m_Value(X)),
4114 m_Deferred(X))),
4115 m_Instruction(Div))))) {
4116 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4117 } else
4118 return nullptr;
4119
4121 // If the pattern included (x * y), we'll want to insert new instructions
4122 // right before that original multiplication so that we can replace it.
4123 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
4124 if (MulHadOtherUses)
4126
4127 Function *F = Intrinsic::getDeclaration(I.getModule(),
4128 Div->getOpcode() == Instruction::UDiv
4129 ? Intrinsic::umul_with_overflow
4130 : Intrinsic::smul_with_overflow,
4131 X->getType());
4132 CallInst *Call = Builder.CreateCall(F, {X, Y}, "mul");
4133
4134 // If the multiplication was used elsewhere, to ensure that we don't leave
4135 // "duplicate" instructions, replace uses of that original multiplication
4136 // with the multiplication result from the with.overflow intrinsic.
4137 if (MulHadOtherUses)
4138 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
4139
4140 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
4141 if (NeedNegation) // This technically increases instruction count.
4142 Res = Builder.CreateNot(Res, "mul.not.ov");
4143
4144 // If we replaced the mul, erase it. Do this after all uses of Builder,
4145 // as the mul is used as insertion point.
4146 if (MulHadOtherUses)
4148
4149 return Res;
4150}
4151
4153 InstCombiner::BuilderTy &Builder) {
4154 CmpInst::Predicate Pred;
4155 Value *X;
4156 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
4157
4158 if (ICmpInst::isSigned(Pred))
4159 Pred = ICmpInst::getSwappedPredicate(Pred);
4160 else if (ICmpInst::isUnsigned(Pred))
4161 Pred = ICmpInst::getSignedPredicate(Pred);
4162 // else for equality-comparisons just keep the predicate.
4163
4164 return ICmpInst::Create(Instruction::ICmp, Pred, X,
4165 Constant::getNullValue(X->getType()), I.getName());
4166 }
4167
4168 // A value is not equal to its negation unless that value is 0 or
4169 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
4170 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
4171 ICmpInst::isEquality(Pred)) {
4172 Type *Ty = X->getType();
4174 Constant *MaxSignedVal =
4176 Value *And = Builder.CreateAnd(X, MaxSignedVal);
4177 Constant *Zero = Constant::getNullValue(Ty);
4178 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
4179 }
4180
4181 return nullptr;
4182}
4183
4185 InstCombinerImpl &IC) {
4186 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
4187 // Normalize xor operand as operand 0.
4188 CmpInst::Predicate Pred = I.getPredicate();
4189 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
4190 std::swap(Op0, Op1);
4191 Pred = ICmpInst::getSwappedPredicate(Pred);
4192 }
4193 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
4194 return nullptr;
4195
4196 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
4197 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
4198 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
4199 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
4201 if (PredOut != Pred &&
4202 isKnownNonZero(A, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4203 return new ICmpInst(PredOut, Op0, Op1);
4204
4205 return nullptr;
4206}
4207
4208/// Try to fold icmp (binop), X or icmp X, (binop).
4209/// TODO: A large part of this logic is duplicated in InstSimplify's
4210/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
4211/// duplication.