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