LLVM 24.0.0git
CorrelatedValuePropagation.cpp
Go to the documentation of this file.
1//===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===//
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 Correlated Value Propagation pass.
10//
11//===----------------------------------------------------------------------===//
12
16#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/Loads.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/Constant.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DebugInfo.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
37#include "llvm/IR/MDBuilder.h"
38#include "llvm/IR/Operator.h"
39#include "llvm/IR/PassManager.h"
41#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
45#include <cassert>
46#include <optional>
47#include <utility>
48
49using namespace llvm;
50
51#define DEBUG_TYPE "correlated-value-propagation"
52
53STATISTIC(NumPhis, "Number of phis propagated");
54STATISTIC(NumPhiCommon, "Number of phis deleted via common incoming value");
55STATISTIC(NumSelects, "Number of selects propagated");
56STATISTIC(NumCmps, "Number of comparisons propagated");
57STATISTIC(NumReturns, "Number of return values propagated");
58STATISTIC(NumDeadCases, "Number of switch cases removed");
59STATISTIC(NumSDivSRemsNarrowed,
60 "Number of sdivs/srems whose width was decreased");
61STATISTIC(NumSDivs, "Number of sdiv converted to udiv");
62STATISTIC(NumUDivURemsNarrowed,
63 "Number of udivs/urems whose width was decreased");
64STATISTIC(NumAShrsConverted, "Number of ashr converted to lshr");
65STATISTIC(NumAShrsRemoved, "Number of ashr removed");
66STATISTIC(NumSRems, "Number of srem converted to urem");
67STATISTIC(NumSExt, "Number of sext converted to zext");
68STATISTIC(NumSIToFP, "Number of sitofp converted to uitofp");
69STATISTIC(NumSICmps, "Number of signed icmp preds simplified to unsigned");
70STATISTIC(NumAnd, "Number of ands removed");
71STATISTIC(NumNW, "Number of no-wrap deductions");
72STATISTIC(NumNSW, "Number of no-signed-wrap deductions");
73STATISTIC(NumNUW, "Number of no-unsigned-wrap deductions");
74STATISTIC(NumAddNW, "Number of no-wrap deductions for add");
75STATISTIC(NumAddNSW, "Number of no-signed-wrap deductions for add");
76STATISTIC(NumAddNUW, "Number of no-unsigned-wrap deductions for add");
77STATISTIC(NumSubNW, "Number of no-wrap deductions for sub");
78STATISTIC(NumSubNSW, "Number of no-signed-wrap deductions for sub");
79STATISTIC(NumSubNUW, "Number of no-unsigned-wrap deductions for sub");
80STATISTIC(NumMulNW, "Number of no-wrap deductions for mul");
81STATISTIC(NumMulNSW, "Number of no-signed-wrap deductions for mul");
82STATISTIC(NumMulNUW, "Number of no-unsigned-wrap deductions for mul");
83STATISTIC(NumShlNW, "Number of no-wrap deductions for shl");
84STATISTIC(NumShlNSW, "Number of no-signed-wrap deductions for shl");
85STATISTIC(NumShlNUW, "Number of no-unsigned-wrap deductions for shl");
86STATISTIC(NumAbs, "Number of llvm.abs intrinsics removed");
87STATISTIC(NumOverflows, "Number of overflow checks removed");
88STATISTIC(NumSaturating,
89 "Number of saturating arithmetics converted to normal arithmetics");
90STATISTIC(NumNonNull, "Number of function pointer arguments marked non-null");
91STATISTIC(NumCmpIntr, "Number of llvm.[us]cmp intrinsics removed");
92STATISTIC(NumMinMax, "Number of llvm.[us]{min,max} intrinsics removed");
93STATISTIC(NumSMinMax,
94 "Number of llvm.s{min,max} intrinsics simplified to unsigned");
95STATISTIC(NumUDivURemsNarrowedExpanded,
96 "Number of bound udiv's/urem's expanded");
97STATISTIC(NumNNeg, "Number of zext/uitofp non-negative deductions");
98
99namespace {
100struct NoWrapFlags;
101
102class CVPImpl {
103 Function &F;
104 LazyValueInfo *LVI;
105 DominatorTree *DT;
106 const SimplifyQuery SQ;
107 std::optional<ConstantRange> RetRange;
108
109public:
110 CVPImpl(Function &F, LazyValueInfo *LVI, DominatorTree *DT,
111 const SimplifyQuery &SQ)
112 : F(F), LVI(LVI), DT(DT), SQ(SQ) {}
113
114 bool run();
115
116private:
117 // Driver methods.
118 bool processInstruction(Instruction &I);
119 bool inferReturnRangeAttr();
120
121 // Process instructions.
122 bool processSelect(SelectInst *S);
123 bool processPHI(PHINode *P);
124 bool processICmp(ICmpInst *Cmp);
125 bool processCmp(CmpInst *Cmp);
126 bool processSwitch(SwitchInst *I);
127 bool processBinOp(BinaryOperator *BinOp);
128 bool processAbsIntrinsic(IntrinsicInst *II);
129 bool processCmpIntrinsic(CmpIntrinsic *CI);
130 bool processMinMaxIntrinsic(MinMaxIntrinsic *MM);
131 bool processOverflowIntrinsic(WithOverflowInst *WO);
132 bool processSaturatingInst(SaturatingInst *SI);
133 bool processCallSite(CallBase &CB);
134 bool processUDivOrURem(BinaryOperator *Instr);
135 bool processSRem(BinaryOperator *SDI, const ConstantRange &LCR,
136 const ConstantRange &RCR);
137 bool processSDiv(BinaryOperator *SDI, const ConstantRange &LCR,
138 const ConstantRange &RCR);
139 bool processSDivOrSRem(BinaryOperator *Instr);
140 bool processAShr(BinaryOperator *SDI);
141 bool processSExt(SExtInst *SDI);
142 bool processPossibleNonNeg(PossiblyNonNegInst *I);
143 bool processSIToFP(SIToFPInst *SIToFP);
144 bool processAnd(BinaryOperator *BinOp);
145 bool processTrunc(TruncInst *TI);
146 bool processReturn(ReturnInst *RI);
147
148 // Helpers.
149 Constant *getConstantAt(Value *V, Instruction *At, const Use *U = nullptr);
150 bool simplifyCommonValuePhi(PHINode *P);
151 bool constantFoldCmp(CmpInst *Cmp);
152 bool willNotOverflow(BinaryOpIntrinsic *BO);
153 Value *getValueOnEdge(const Use &IncomingUse, BasicBlock *From,
154 BasicBlock *To, Instruction *CtxI);
155 NoWrapFlags inferNoWrapFromUses(BinaryOperator *BinOp, bool WantNSW,
156 bool WantNUW);
157};
158} // end anonymous namespace
159
160Constant *CVPImpl::getConstantAt(Value *V, Instruction *At, const Use *U) {
161 if (Constant *C = LVI->getConstant(V, At, U))
162 return C;
163
164 // TODO: The following really should be sunk inside LVI's core algorithm, or
165 // at least the outer shims around such.
166 auto *C = dyn_cast<CmpInst>(V);
167 if (!C)
168 return nullptr;
169
170 Value *Op0 = C->getOperand(0);
171 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
172 if (!Op1)
173 return nullptr;
174
175 return LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At,
176 /*UseBlockValue=*/false);
177}
178
179bool CVPImpl::processSelect(SelectInst *S) {
180 if (S->getType()->isVectorTy() || isa<Constant>(S->getCondition()))
181 return false;
182
183 bool Changed = false;
184 for (Use &U : make_early_inc_range(S->uses())) {
185 auto *I = cast<Instruction>(U.getUser());
186 Constant *C;
187 if (auto *PN = dyn_cast<PHINode>(I))
188 C = LVI->getConstantOnEdge(S->getCondition(), PN->getIncomingBlock(U),
189 I->getParent(), I);
190 else
191 C = getConstantAt(S->getCondition(), I);
192
194 if (!CI)
195 continue;
196
197 U.set(CI->isOne() ? S->getTrueValue() : S->getFalseValue());
198 Changed = true;
199 ++NumSelects;
200 }
201
202 if (Changed && S->use_empty())
203 S->eraseFromParent();
204
205 return Changed;
206}
207
208/// Try to simplify a phi with constant incoming values that match the edge
209/// values of a non-constant value on all other edges:
210/// bb0:
211/// %isnull = icmp eq i8* %x, null
212/// br i1 %isnull, label %bb2, label %bb1
213/// bb1:
214/// br label %bb2
215/// bb2:
216/// %r = phi i8* [ %x, %bb1 ], [ null, %bb0 ]
217/// -->
218/// %r = %x
219bool CVPImpl::simplifyCommonValuePhi(PHINode *P) {
220 // Collect incoming constants and initialize possible common value.
222 Value *CommonValue = nullptr;
223 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; ++I) {
224 Value *Incoming = P->getIncomingValue(I);
225 if (auto *IncomingConstant = dyn_cast<Constant>(Incoming)) {
226 IncomingConstants.push_back(std::make_pair(IncomingConstant, I));
227 } else if (!CommonValue) {
228 // The potential common value is initialized to the first non-constant.
229 CommonValue = Incoming;
230 } else if (Incoming != CommonValue) {
231 // There can be only one non-constant common value.
232 return false;
233 }
234 }
235
236 if (!CommonValue || IncomingConstants.empty())
237 return false;
238
239 // The common value must be valid in all incoming blocks.
240 BasicBlock *ToBB = P->getParent();
241 if (auto *CommonInst = dyn_cast<Instruction>(CommonValue))
242 if (!DT->dominates(CommonInst, ToBB))
243 return false;
244
245 // We have a phi with exactly 1 variable incoming value and 1 or more constant
246 // incoming values. See if all constant incoming values can be mapped back to
247 // the same incoming variable value.
248 const DataLayout &DL = P->getDataLayout();
249 for (auto &IncomingConstant : IncomingConstants) {
250 Constant *C = IncomingConstant.first;
251 unsigned Idx = IncomingConstant.second;
252 BasicBlock *IncomingBB = P->getIncomingBlock(Idx);
253 // Is CommonValue equal to the incoming constant on this edge?
254 Constant *Res = LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, CommonValue, C,
255 IncomingBB, ToBB, P);
256 if (!Res || !Res->isOneValue())
257 return false;
258
259 // The constant incoming pointer may not be freely substituted with
260 // CommonValue if their provenance differs.
261 if (!canReplacePointersInUseIfEqual(P->getOperandUse(Idx), CommonValue, DL))
262 return false;
263 }
264
265 // LVI only guarantees that the value matches a certain constant if the value
266 // is not poison. Make sure we don't replace a well-defined value with poison.
267 // This is usually satisfied due to a prior branch on the value.
268 if (!isGuaranteedNotToBePoison(CommonValue, nullptr, P, DT))
269 return false;
270
271 // All constant incoming values map to the same variable along the incoming
272 // edges of the phi. The phi is unnecessary.
273 P->replaceAllUsesWith(CommonValue);
275 ++NumPhiCommon;
276 return true;
277}
278
279Value *CVPImpl::getValueOnEdge(const Use &IncomingUse, BasicBlock *From,
280 BasicBlock *To, Instruction *CtxI) {
281 Value *Incoming = IncomingUse.get();
282 if (Constant *C =
283 LVI->getConstantOnEdge(Incoming, From, To, CtxI, &IncomingUse))
284 return C;
285
286 // Look if the incoming value is a select with a scalar condition for which
287 // LVI can tells us the value. In that case replace the incoming value with
288 // the appropriate value of the select. This often allows us to remove the
289 // select later.
290 auto *SI = dyn_cast<SelectInst>(Incoming);
291 if (!SI)
292 return nullptr;
293
294 // Once LVI learns to handle vector types, we could also add support
295 // for vector type constants that are not all zeroes or all ones.
296 Value *Condition = SI->getCondition();
297 if (!Condition->getType()->isVectorTy()) {
298 if (Constant *C = LVI->getConstantOnEdge(Condition, From, To, CtxI)) {
299 if (C->isOneValue())
300 return SI->getTrueValue();
301 if (C->isNullValue())
302 return SI->getFalseValue();
303 }
304 }
305
306 // Look if the select has a constant but LVI tells us that the incoming
307 // value can never be that constant. In that case replace the incoming
308 // value with the other value of the select. This often allows us to
309 // remove the select later.
310
311 // The "false" case
312 if (auto *C = dyn_cast<Constant>(SI->getFalseValue()))
313 if (auto *Res = dyn_cast_or_null<ConstantInt>(
314 LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C, From, To, CtxI));
315 Res && Res->isZero())
316 return SI->getTrueValue();
317
318 // The "true" case,
319 // similar to the select "false" case, but try the select "true" value
320 if (auto *C = dyn_cast<Constant>(SI->getTrueValue()))
321 if (auto *Res = dyn_cast_or_null<ConstantInt>(
322 LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C, From, To, CtxI));
323 Res && Res->isZero())
324 return SI->getFalseValue();
325
326 return nullptr;
327}
328
329bool CVPImpl::processPHI(PHINode *P) {
330 bool Changed = false;
331
332 BasicBlock *BB = P->getParent();
333 for (unsigned I = 0, E = P->getNumIncomingValues(); I < E; ++I) {
334 const Use &IncomingUse = P->getOperandUse(I);
335 if (isa<Constant>(IncomingUse.get()))
336 continue;
337
338 Value *V = getValueOnEdge(IncomingUse, P->getIncomingBlock(I), BB, P);
339 if (V) {
340 P->setIncomingValue(I, V);
341 Changed = true;
342 }
343 }
344
345 if (Value *V = simplifyInstruction(P, SQ)) {
346 P->replaceAllUsesWith(V);
347 P->eraseFromParent();
348 Changed = true;
349 }
350
351 if (!Changed)
352 Changed = simplifyCommonValuePhi(P);
353
354 if (Changed)
355 ++NumPhis;
356
357 return Changed;
358}
359
360bool CVPImpl::processICmp(ICmpInst *Cmp) {
361 // Only for signed relational comparisons of integers.
362 if (!Cmp->getOperand(0)->getType()->isIntOrIntVectorTy())
363 return false;
364
365 if (!Cmp->isSigned() && (!Cmp->isUnsigned() || Cmp->hasSameSign()))
366 return false;
367
368 bool Changed = false;
370 ConstantRange CR1 = LVI->getConstantRangeAtUse(Cmp->getOperandUse(0),
371 /*UndefAllowed=*/false,
372 &DebugUsers),
373 CR2 = LVI->getConstantRangeAtUse(Cmp->getOperandUse(1),
374 /*UndefAllowed=*/false,
375 &DebugUsers);
376 if (Cmp->isSigned()) {
377 ICmpInst::Predicate UnsignedPred =
379 Cmp->getPredicate(), CR1, CR2);
380
381 if (UnsignedPred == ICmpInst::Predicate::BAD_ICMP_PREDICATE)
382 return false;
383
384 // Since the instruction changed, all debug users of
385 // this value must be poisoned
386 for (auto *Record : DebugUsers)
387 Record->setKillLocation();
388
389 ++NumSICmps;
390 Cmp->setPredicate(UnsignedPred);
391 Changed = true;
392 }
393
395 Cmp->setSameSign();
396 Changed = true;
397 }
398
399 return Changed;
400}
401
402/// See if LazyValueInfo's ability to exploit edge conditions or range
403/// information is sufficient to prove this comparison. Even for local
404/// conditions, this can sometimes prove conditions instcombine can't by
405/// exploiting range information.
406bool CVPImpl::constantFoldCmp(CmpInst *Cmp) {
407 Value *Op0 = Cmp->getOperand(0);
408 Value *Op1 = Cmp->getOperand(1);
409 Constant *Res = LVI->getPredicateAt(Cmp->getPredicate(), Op0, Op1, Cmp,
410 /*UseBlockValue=*/true);
411 if (!Res)
412 return false;
413
414 bool Changed = Cmp->replaceUsesWithIf(
415 Res, [](Use &U) { return !isa<AssumeInst>(U.getUser()); });
416 if (Cmp->use_empty()) {
417 Cmp->eraseFromParent();
418 Changed = true;
419 }
420
421 if (Changed)
422 ++NumCmps;
423
424 return Changed;
425}
426
427bool CVPImpl::processCmp(CmpInst *Cmp) {
428 if (constantFoldCmp(Cmp))
429 return true;
430
431 if (auto *ICmp = dyn_cast<ICmpInst>(Cmp))
432 if (processICmp(ICmp))
433 return true;
434
435 return false;
436}
437
438/// Simplify a switch instruction by removing cases which can never fire. If the
439/// uselessness of a case could be determined locally then constant propagation
440/// would already have figured it out. Instead, walk the predecessors and
441/// statically evaluate cases based on information available on that edge. Cases
442/// that cannot fire no matter what the incoming edge can safely be removed. If
443/// a case fires on every incoming edge then the entire switch can be removed
444/// and replaced with a branch to the case destination.
445bool CVPImpl::processSwitch(SwitchInst *I) {
446 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
447 Value *Cond = I->getCondition();
448 BasicBlock *BB = I->getParent();
449
450 // Analyse each switch case in turn.
451 bool Changed = false;
452 DenseMap<BasicBlock*, int> SuccessorsCount;
453 for (auto *Succ : successors(BB))
454 SuccessorsCount[Succ]++;
455
456 { // Scope for SwitchInstProfUpdateWrapper. It must not live during
457 // ConstantFoldTerminator() as the underlying SwitchInst can be changed.
458 SwitchInstProfUpdateWrapper SI(*I);
459 ConstantRange CR =
460 LVI->getConstantRangeAtUse(I->getOperandUse(0), /*UndefAllowed=*/false);
461 unsigned ReachableCaseCount = 0;
462
463 for (auto CI = SI->case_begin(), CE = SI->case_end(); CI != CE;) {
464 ConstantInt *Case = CI->getCaseValue();
465 std::optional<bool> Predicate = std::nullopt;
466 if (!CR.contains(Case->getValue()))
467 Predicate = false;
468 else if (CR.isSingleElement() &&
469 *CR.getSingleElement() == Case->getValue())
470 Predicate = true;
471 if (!Predicate) {
472 // Handle missing cases, e.g., the range has a hole.
475 /* UseBlockValue=*/true));
476 if (Res && Res->isZero())
477 Predicate = false;
478 else if (Res && Res->isOne())
479 Predicate = true;
480 }
481
482 if (Predicate && !*Predicate) {
483 // This case never fires - remove it.
484 BasicBlock *Succ = CI->getCaseSuccessor();
485 Succ->removePredecessor(BB);
486 CI = SI.removeCase(CI);
487 CE = SI->case_end();
488
489 // The condition can be modified by removePredecessor's PHI simplification
490 // logic.
491 Cond = SI->getCondition();
492
493 ++NumDeadCases;
494 Changed = true;
495 if (--SuccessorsCount[Succ] == 0)
496 DTU.applyUpdatesPermissive({{DominatorTree::Delete, BB, Succ}});
497 continue;
498 }
499 if (Predicate && *Predicate) {
500 // This case always fires. Arrange for the switch to be turned into an
501 // unconditional branch by replacing the switch condition with the case
502 // value.
503 SI->setCondition(Case);
504 NumDeadCases += SI->getNumCases();
505 Changed = true;
506 break;
507 }
508
509 // Increment the case iterator since we didn't delete it.
510 ++CI;
511 ++ReachableCaseCount;
512 }
513
514 // The default dest is unreachable if all cases are covered.
515 if (!SI->defaultDestUnreachable() &&
516 !CR.isSizeLargerThan(ReachableCaseCount)) {
517 BasicBlock *DefaultDest = SI->getDefaultDest();
518 BasicBlock *NewUnreachableBB =
519 BasicBlock::Create(BB->getContext(), "default.unreachable",
520 BB->getParent(), DefaultDest);
521 auto *UI = new UnreachableInst(BB->getContext(), NewUnreachableBB);
522 UI->setDebugLoc(DebugLoc::getTemporary());
523
524 DefaultDest->removePredecessor(BB);
525 SI->setDefaultDest(NewUnreachableBB);
526
527 if (SuccessorsCount[DefaultDest] == 1)
528 DTU.applyUpdates({{DominatorTree::Delete, BB, DefaultDest}});
529 DTU.applyUpdates({{DominatorTree::Insert, BB, NewUnreachableBB}});
530
531 ++NumDeadCases;
532 Changed = true;
533 }
534 }
535
536 if (Changed)
537 // If the switch has been simplified to the point where it can be replaced
538 // by a branch then do so now.
539 ConstantFoldTerminator(BB, /*DeleteDeadConditions = */ false,
540 /*TLI = */ nullptr, &DTU);
541 return Changed;
542}
543
544// See if we can prove that the given binary op intrinsic will not overflow.
545bool CVPImpl::willNotOverflow(BinaryOpIntrinsic *BO) {
546 ConstantRange LRange =
547 LVI->getConstantRangeAtUse(BO->getOperandUse(0), /*UndefAllowed*/ false);
548 ConstantRange RRange =
549 LVI->getConstantRangeAtUse(BO->getOperandUse(1), /*UndefAllowed*/ false);
550 ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
551 BO->getBinaryOp(), RRange, BO->getNoWrapKind());
552 return NWRegion.contains(LRange);
553}
554
556 bool NewNSW, bool NewNUW) {
557 Statistic *OpcNW, *OpcNSW, *OpcNUW;
558 switch (Opcode) {
559 case Instruction::Add:
560 OpcNW = &NumAddNW;
561 OpcNSW = &NumAddNSW;
562 OpcNUW = &NumAddNUW;
563 break;
564 case Instruction::Sub:
565 OpcNW = &NumSubNW;
566 OpcNSW = &NumSubNSW;
567 OpcNUW = &NumSubNUW;
568 break;
569 case Instruction::Mul:
570 OpcNW = &NumMulNW;
571 OpcNSW = &NumMulNSW;
572 OpcNUW = &NumMulNUW;
573 break;
574 case Instruction::Shl:
575 OpcNW = &NumShlNW;
576 OpcNSW = &NumShlNSW;
577 OpcNUW = &NumShlNUW;
578 break;
579 default:
580 llvm_unreachable("Will not be called with other binops");
581 }
582
583 auto *Inst = dyn_cast<Instruction>(V);
584 if (NewNSW) {
585 ++NumNW;
586 ++*OpcNW;
587 ++NumNSW;
588 ++*OpcNSW;
589 if (Inst)
590 Inst->setHasNoSignedWrap();
591 }
592 if (NewNUW) {
593 ++NumNW;
594 ++*OpcNW;
595 ++NumNUW;
596 ++*OpcNUW;
597 if (Inst)
598 Inst->setHasNoUnsignedWrap();
599 }
600}
601
602// See if @llvm.abs argument is alays positive/negative, and simplify.
603// Notably, INT_MIN can belong to either range, regardless of the NSW,
604// because it is negation-invariant.
605bool CVPImpl::processAbsIntrinsic(IntrinsicInst *II) {
606 Value *X = II->getArgOperand(0);
607 bool IsIntMinPoison = cast<ConstantInt>(II->getArgOperand(1))->isOne();
608 APInt IntMin = APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
609 ConstantRange Range = LVI->getConstantRangeAtUse(
610 II->getOperandUse(0), /*UndefAllowed*/ IsIntMinPoison);
611
612 // Is X in [0, IntMin]? NOTE: INT_MIN is fine!
613 if (Range.icmp(CmpInst::ICMP_ULE, IntMin)) {
614 ++NumAbs;
615 II->replaceAllUsesWith(X);
616 II->eraseFromParent();
617 return true;
618 }
619
620 // Is X in [IntMin, 0]? NOTE: INT_MIN is fine!
623 Value *NegX = B.CreateNeg(X, II->getName(),
624 /*HasNSW=*/IsIntMinPoison);
625 ++NumAbs;
626 II->replaceAllUsesWith(NegX);
627 II->eraseFromParent();
628
629 // See if we can infer some no-wrap flags.
630 if (auto *BO = dyn_cast<BinaryOperator>(NegX))
631 processBinOp(BO);
632
633 return true;
634 }
635
636 // Argument's range crosses zero.
637 // Can we at least tell that the argument is never INT_MIN?
638 if (!IsIntMinPoison && !Range.contains(IntMin)) {
639 ++NumNSW;
640 ++NumSubNSW;
641 II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
642 return true;
643 }
644 return false;
645}
646
647bool CVPImpl::processCmpIntrinsic(CmpIntrinsic *CI) {
648 ConstantRange LRange =
649 LVI->getConstantRangeAtUse(CI->getOperandUse(0), /*UndefAllowed*/ false);
650 ConstantRange RRange =
651 LVI->getConstantRangeAtUse(CI->getOperandUse(1), /*UndefAllowed*/ false);
652
653 if (LRange.icmp(CI->getGTPredicate(), RRange)) {
654 ++NumCmpIntr;
655 CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
656 CI->eraseFromParent();
657 return true;
658 }
659 if (LRange.icmp(CI->getLTPredicate(), RRange)) {
660 ++NumCmpIntr;
662 CI->eraseFromParent();
663 return true;
664 }
665 if (LRange.icmp(ICmpInst::ICMP_EQ, RRange)) {
666 ++NumCmpIntr;
667 CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 0));
668 CI->eraseFromParent();
669 return true;
670 }
671
672 return false;
673}
674
675// See if this min/max intrinsic always picks it's one specific operand.
676// If not, check whether we can canonicalize signed minmax into unsigned version
677bool CVPImpl::processMinMaxIntrinsic(MinMaxIntrinsic *MM) {
679 ConstantRange LRange = LVI->getConstantRangeAtUse(MM->getOperandUse(0),
680 /*UndefAllowed*/ false);
681 ConstantRange RRange = LVI->getConstantRangeAtUse(MM->getOperandUse(1),
682 /*UndefAllowed*/ false);
683 if (LRange.icmp(Pred, RRange)) {
684 ++NumMinMax;
685 MM->replaceAllUsesWith(MM->getLHS());
686 MM->eraseFromParent();
687 return true;
688 }
689 if (RRange.icmp(Pred, LRange)) {
690 ++NumMinMax;
691 MM->replaceAllUsesWith(MM->getRHS());
692 MM->eraseFromParent();
693 return true;
694 }
695
696 // A select condition that may be undef still constrains an operand if the
697 // operand is frozen, so that the condition and the min/max observe the same
698 // value:
699 // select (m < 0), (shl x, (sub 0, smin(m, 0))), 0
700 // --> m.fr = freeze m
701 // select (m.fr < 0), (shl x, (sub 0, m.fr)), 0
702 auto TryFoldWithFreeze = [&](unsigned OpIdx,
703 const ConstantRange &OtherRange) {
704 ConstantRange FrozenRange = LVI->getConstantRangeAtUse(
705 MM->getOperandUse(OpIdx),
706 /*UndefAllowed*/ false, /*DebugUsers*/ nullptr, /*AssumeFrozen*/ true);
707 if (!FrozenRange.icmp(Pred, OtherRange))
708 return false;
709 Value *Op = MM->getOperand(OpIdx);
710 auto *FI = new FreezeInst(Op, Op->getName() + ".fr", MM->getIterator());
711 if (!freezeUsesAfterDef(*FI, *DT)) {
712 FI->eraseFromParent();
713 return false;
714 }
715 ++NumMinMax;
716 MM->replaceAllUsesWith(FI);
717 MM->eraseFromParent();
718 return true;
719 };
720 if (TryFoldWithFreeze(0, RRange) || TryFoldWithFreeze(1, LRange))
721 return true;
722
723 if (MM->isSigned() &&
725 RRange)) {
726 ++NumSMinMax;
727 IRBuilder<> B(MM);
728 salvageDebugInfo(*MM);
729 MM->replaceAllUsesWith(B.CreateBinaryIntrinsic(
730 MM->getIntrinsicID() == Intrinsic::smin ? Intrinsic::umin
731 : Intrinsic::umax,
732 MM->getLHS(), MM->getRHS()));
733 MM->eraseFromParent();
734 return true;
735 }
736
737 return false;
738}
739
740// Rewrite this with.overflow intrinsic as non-overflowing.
741bool CVPImpl::processOverflowIntrinsic(WithOverflowInst *WO) {
742 IRBuilder<> B(WO);
743 Instruction::BinaryOps Opcode = WO->getBinaryOp();
744 bool NSW = WO->isSigned();
745 bool NUW = !WO->isSigned();
746
747 Value *NewOp =
748 B.CreateBinOp(Opcode, WO->getLHS(), WO->getRHS(), WO->getName());
749 setDeducedOverflowingFlags(NewOp, Opcode, NSW, NUW);
750
751 StructType *ST = cast<StructType>(WO->getType());
753 { PoisonValue::get(ST->getElementType(0)),
754 ConstantInt::getFalse(ST->getElementType(1)) });
755 Value *NewI = B.CreateInsertValue(Struct, NewOp, 0);
756 WO->replaceAllUsesWith(NewI);
757 WO->eraseFromParent();
758 ++NumOverflows;
759
760 // See if we can infer the other no-wrap too.
761 if (auto *BO = dyn_cast<BinaryOperator>(NewOp))
762 processBinOp(BO);
763
764 return true;
765}
766
767bool CVPImpl::processSaturatingInst(SaturatingInst *SI) {
768 Instruction::BinaryOps Opcode = SI->getBinaryOp();
769 bool NSW = SI->isSigned();
770 bool NUW = !SI->isSigned();
771 BinaryOperator *BinOp = BinaryOperator::Create(
772 Opcode, SI->getLHS(), SI->getRHS(), SI->getName(), SI->getIterator());
773 BinOp->setDebugLoc(SI->getDebugLoc());
774 setDeducedOverflowingFlags(BinOp, Opcode, NSW, NUW);
775
776 salvageDebugInfo(*SI);
777 SI->replaceAllUsesWith(BinOp);
778 SI->eraseFromParent();
779 ++NumSaturating;
780
781 // See if we can infer the other no-wrap too.
782 processBinOp(BinOp);
783
784 return true;
785}
786
787/// Infer nonnull attributes for the arguments at the specified callsite.
788bool CVPImpl::processCallSite(CallBase &CB) {
789
790 if (CB.getIntrinsicID() == Intrinsic::abs) {
791 return processAbsIntrinsic(&cast<IntrinsicInst>(CB));
792 }
793
794 if (auto *CI = dyn_cast<CmpIntrinsic>(&CB)) {
795 return processCmpIntrinsic(CI);
796 }
797
798 if (auto *MM = dyn_cast<MinMaxIntrinsic>(&CB)) {
799 return processMinMaxIntrinsic(MM);
800 }
801
802 if (auto *WO = dyn_cast<WithOverflowInst>(&CB)) {
803 if (willNotOverflow(WO))
804 return processOverflowIntrinsic(WO);
805 }
806
807 if (auto *SI = dyn_cast<SaturatingInst>(&CB)) {
808 if (willNotOverflow(SI))
809 return processSaturatingInst(SI);
810 }
811
812 bool Changed = false;
813
814 // Deopt bundle operands are intended to capture state with minimal
815 // perturbance of the code otherwise. If we can find a constant value for
816 // any such operand and remove a use of the original value, that's
817 // desireable since it may allow further optimization of that value (e.g. via
818 // single use rules in instcombine). Since deopt uses tend to,
819 // idiomatically, appear along rare conditional paths, it's reasonable likely
820 // we may have a conditional fact with which LVI can fold.
821 if (auto DeoptBundle = CB.getOperandBundle(LLVMContext::OB_deopt)) {
822 for (const Use &ConstU : DeoptBundle->Inputs) {
823 Use &U = const_cast<Use&>(ConstU);
824 Value *V = U.get();
825 if (V->getType()->isVectorTy()) continue;
826 if (isa<Constant>(V)) continue;
827
828 Constant *C = LVI->getConstant(V, &CB, &U);
829 if (!C) continue;
830 U.set(C);
831 Changed = true;
832 }
833 }
834
835 SmallVector<unsigned, 4> ArgNos;
836 unsigned ArgNo = 0;
837
838 for (Value *V : CB.args()) {
840 // Try to mark pointer typed parameters as non-null. We skip the
841 // relatively expensive analysis for constants which are obviously either
842 // null or non-null to start with.
843 if (Type && !CB.paramHasAttr(ArgNo, Attribute::NonNull) &&
846 ICmpInst::ICMP_EQ, V, ConstantPointerNull::get(Type), &CB,
847 /*UseBlockValue=*/false));
848 Res && Res->isZero())
849 ArgNos.push_back(ArgNo);
850 ArgNo++;
851 }
852
853 assert(ArgNo == CB.arg_size() && "Call arguments not processed correctly.");
854
855 if (ArgNos.empty())
856 return Changed;
857
858 NumNonNull += ArgNos.size();
859 AttributeList AS = CB.getAttributes();
860 LLVMContext &Ctx = CB.getContext();
861 AS = AS.addParamAttribute(Ctx, ArgNos,
862 Attribute::get(Ctx, Attribute::NonNull));
863 CB.setAttributes(AS);
864
865 return true;
866}
867
869
870static Domain getDomain(const ConstantRange &CR) {
871 if (CR.isAllNonNegative())
872 return Domain::NonNegative;
874 return Domain::NonPositive;
875 return Domain::Unknown;
876}
877
878/// Try to shrink a sdiv/srem's width down to the smallest power of two that's
879/// sufficient to contain its operands.
880static bool narrowSDivOrSRem(BinaryOperator *Instr, const ConstantRange &LCR,
881 const ConstantRange &RCR) {
882 assert(Instr->getOpcode() == Instruction::SDiv ||
883 Instr->getOpcode() == Instruction::SRem);
884
885 // Find the smallest power of two bitwidth that's sufficient to hold Instr's
886 // operands.
887 unsigned OrigWidth = Instr->getType()->getScalarSizeInBits();
888
889 // What is the smallest bit width that can accommodate the entire value ranges
890 // of both of the operands?
891 unsigned MinSignedBits =
892 std::max(LCR.getMinSignedBits(), RCR.getMinSignedBits());
893
894 // sdiv/srem is UB if divisor is -1 and divident is INT_MIN, so unless we can
895 // prove that such a combination is impossible, we need to bump the bitwidth.
896 if (RCR.contains(APInt::getAllOnes(OrigWidth)) &&
897 LCR.contains(APInt::getSignedMinValue(MinSignedBits).sext(OrigWidth)))
898 ++MinSignedBits;
899
900 // Don't shrink below 8 bits wide.
901 unsigned NewWidth = std::max<unsigned>(PowerOf2Ceil(MinSignedBits), 8);
902
903 // NewWidth might be greater than OrigWidth if OrigWidth is not a power of
904 // two.
905 if (NewWidth >= OrigWidth)
906 return false;
907
908 ++NumSDivSRemsNarrowed;
909 IRBuilder<> B{Instr};
910 auto *TruncTy = Instr->getType()->getWithNewBitWidth(NewWidth);
911 auto *LHS = B.CreateTruncOrBitCast(Instr->getOperand(0), TruncTy,
912 Instr->getName() + ".lhs.trunc");
913 auto *RHS = B.CreateTruncOrBitCast(Instr->getOperand(1), TruncTy,
914 Instr->getName() + ".rhs.trunc");
915 auto *BO = B.CreateBinOp(Instr->getOpcode(), LHS, RHS, Instr->getName());
916 auto *Sext = B.CreateSExt(BO, Instr->getType(), Instr->getName() + ".sext");
917 if (auto *BinOp = dyn_cast<BinaryOperator>(BO))
918 if (BinOp->getOpcode() == Instruction::SDiv)
919 BinOp->setIsExact(Instr->isExact());
920
921 Instr->replaceAllUsesWith(Sext);
922 Instr->eraseFromParent();
923 return true;
924}
925
926static bool expandUDivOrURem(BinaryOperator *Instr, const ConstantRange &XCR,
927 const ConstantRange &YCR) {
928 Type *Ty = Instr->getType();
929 assert(Instr->getOpcode() == Instruction::UDiv ||
930 Instr->getOpcode() == Instruction::URem);
931 bool IsRem = Instr->getOpcode() == Instruction::URem;
932
933 Value *X = Instr->getOperand(0);
934 Value *Y = Instr->getOperand(1);
935
936 // X u/ Y -> 0 iff X u< Y
937 // X u% Y -> X iff X u< Y
938 if (XCR.icmp(ICmpInst::ICMP_ULT, YCR)) {
939 salvageDebugInfo(*Instr);
940 Instr->replaceAllUsesWith(IsRem ? X : Constant::getNullValue(Ty));
941 Instr->eraseFromParent();
942 ++NumUDivURemsNarrowedExpanded;
943 return true;
944 }
945
946 // Given
947 // R = X u% Y
948 // We can represent the modulo operation as a loop/self-recursion:
949 // urem_rec(X, Y):
950 // Z = X - Y
951 // if X u< Y
952 // ret X
953 // else
954 // ret urem_rec(Z, Y)
955 // which isn't better, but if we only need a single iteration
956 // to compute the answer, this becomes quite good:
957 // R = X < Y ? X : X - Y iff X u< 2*Y (w/ unsigned saturation)
958 // Now, we do not care about all full multiples of Y in X, they do not change
959 // the answer, thus we could rewrite the expression as:
960 // X* = X - (Y * |_ X / Y _|)
961 // R = X* % Y
962 // so we don't need the *first* iteration to return, we just need to
963 // know *which* iteration will always return, so we could also rewrite it as:
964 // X* = X - (Y * |_ X / Y _|)
965 // R = X* % Y iff X* u< 2*Y (w/ unsigned saturation)
966 // but that does not seem profitable here.
967
968 // Even if we don't know X's range, the divisor may be so large, X can't ever
969 // be 2x larger than that. I.e. if divisor is always negative.
970 if (!XCR.icmp(ICmpInst::ICMP_ULT, YCR.uadd_sat(YCR)) && !YCR.isAllNegative())
971 return false;
972
973 IRBuilder<> B(Instr);
974 Value *ExpandedOp;
975 if (XCR.icmp(ICmpInst::ICMP_UGE, YCR)) {
976 // If X is between Y and 2*Y the result is known.
977 if (IsRem)
978 ExpandedOp = B.CreateNUWSub(X, Y);
979 else
980 ExpandedOp = ConstantInt::get(Instr->getType(), 1);
981 } else if (IsRem) {
982 // NOTE: this transformation introduces two uses of X,
983 // but it may be undef so we must freeze it first.
984 Value *FrozenX = X;
986 FrozenX = B.CreateFreeze(X, X->getName() + ".frozen");
987 Value *FrozenY = Y;
989 FrozenY = B.CreateFreeze(Y, Y->getName() + ".frozen");
990 auto *AdjX = B.CreateNUWSub(FrozenX, FrozenY, Instr->getName() + ".urem");
991 auto *Cmp = B.CreateICmp(ICmpInst::ICMP_ULT, FrozenX, FrozenY,
992 Instr->getName() + ".cmp");
993 ExpandedOp =
994 B.CreateSelectWithUnknownProfile(Cmp, FrozenX, AdjX, DEBUG_TYPE);
995 } else {
996 auto *Cmp =
997 B.CreateICmp(ICmpInst::ICMP_UGE, X, Y, Instr->getName() + ".cmp");
998 ExpandedOp = B.CreateZExt(Cmp, Ty, Instr->getName() + ".udiv");
999 }
1000 ExpandedOp->takeName(Instr);
1001 Instr->replaceAllUsesWith(ExpandedOp);
1002 Instr->eraseFromParent();
1003 ++NumUDivURemsNarrowedExpanded;
1004 return true;
1005}
1006
1007/// Try to shrink a udiv/urem's width down to the smallest power of two that's
1008/// sufficient to contain its operands.
1009static bool narrowUDivOrURem(BinaryOperator *Instr, const ConstantRange &XCR,
1010 const ConstantRange &YCR) {
1011 assert(Instr->getOpcode() == Instruction::UDiv ||
1012 Instr->getOpcode() == Instruction::URem);
1013
1014 // Find the smallest power of two bitwidth that's sufficient to hold Instr's
1015 // operands.
1016
1017 // What is the smallest bit width that can accommodate the entire value ranges
1018 // of both of the operands?
1019 unsigned MaxActiveBits = std::max(XCR.getActiveBits(), YCR.getActiveBits());
1020 // Don't shrink below 8 bits wide.
1021 unsigned NewWidth = std::max<unsigned>(PowerOf2Ceil(MaxActiveBits), 8);
1022
1023 // NewWidth might be greater than OrigWidth if OrigWidth is not a power of
1024 // two.
1025 if (NewWidth >= Instr->getType()->getScalarSizeInBits())
1026 return false;
1027
1028 ++NumUDivURemsNarrowed;
1029 IRBuilder<> B{Instr};
1030 auto *TruncTy = Instr->getType()->getWithNewBitWidth(NewWidth);
1031 auto *LHS = B.CreateTruncOrBitCast(Instr->getOperand(0), TruncTy,
1032 Instr->getName() + ".lhs.trunc");
1033 auto *RHS = B.CreateTruncOrBitCast(Instr->getOperand(1), TruncTy,
1034 Instr->getName() + ".rhs.trunc");
1035 auto *BO = B.CreateBinOp(Instr->getOpcode(), LHS, RHS, Instr->getName());
1036 auto *Zext = B.CreateZExt(BO, Instr->getType(), Instr->getName() + ".zext");
1037 if (auto *BinOp = dyn_cast<BinaryOperator>(BO))
1038 if (BinOp->getOpcode() == Instruction::UDiv)
1039 BinOp->setIsExact(Instr->isExact());
1040
1041 Instr->replaceAllUsesWith(Zext);
1042 Instr->eraseFromParent();
1043 return true;
1044}
1045
1046bool CVPImpl::processUDivOrURem(BinaryOperator *Instr) {
1047 assert(Instr->getOpcode() == Instruction::UDiv ||
1048 Instr->getOpcode() == Instruction::URem);
1049 ConstantRange XCR = LVI->getConstantRangeAtUse(Instr->getOperandUse(0),
1050 /*UndefAllowed*/ false);
1051 // Allow undef for RHS, as we can assume it is division by zero UB.
1052 ConstantRange YCR = LVI->getConstantRangeAtUse(Instr->getOperandUse(1),
1053 /*UndefAllowed*/ true);
1054 if (expandUDivOrURem(Instr, XCR, YCR))
1055 return true;
1056
1057 return narrowUDivOrURem(Instr, XCR, YCR);
1058}
1059
1060bool CVPImpl::processSRem(BinaryOperator *SDI, const ConstantRange &LCR,
1061 const ConstantRange &RCR) {
1062 assert(SDI->getOpcode() == Instruction::SRem);
1063
1064 if (LCR.abs().icmp(CmpInst::ICMP_ULT, RCR.abs())) {
1065 salvageDebugInfo(*SDI);
1066 SDI->replaceAllUsesWith(SDI->getOperand(0));
1067 SDI->eraseFromParent();
1068 return true;
1069 }
1070
1071 struct Operand {
1072 Value *V;
1073 Domain D;
1074 };
1075 std::array<Operand, 2> Ops = {{{SDI->getOperand(0), getDomain(LCR)},
1076 {SDI->getOperand(1), getDomain(RCR)}}};
1077 if (Ops[0].D == Domain::Unknown || Ops[1].D == Domain::Unknown)
1078 return false;
1079
1080 // We know domains of both of the operands!
1081 ++NumSRems;
1082
1083 // We need operands to be non-negative, so negate each one that isn't.
1084 for (Operand &Op : Ops) {
1085 if (Op.D == Domain::NonNegative)
1086 continue;
1087 auto *BO = BinaryOperator::CreateNeg(Op.V, Op.V->getName() + ".nonneg",
1088 SDI->getIterator());
1089 BO->setDebugLoc(SDI->getDebugLoc());
1090 Op.V = BO;
1091 }
1092
1093 auto *URem = BinaryOperator::CreateURem(Ops[0].V, Ops[1].V, SDI->getName(),
1094 SDI->getIterator());
1095 URem->setDebugLoc(SDI->getDebugLoc());
1096
1097 auto *Res = URem;
1098
1099 // If the divident was non-positive, we need to negate the result.
1100 if (Ops[0].D == Domain::NonPositive) {
1101 Res = BinaryOperator::CreateNeg(Res, Res->getName() + ".neg",
1102 SDI->getIterator());
1103 Res->setDebugLoc(SDI->getDebugLoc());
1104 }
1105
1106 salvageDebugInfo(*SDI);
1107 SDI->replaceAllUsesWith(Res);
1108 SDI->eraseFromParent();
1109
1110 // Try to simplify our new urem.
1111 processUDivOrURem(URem);
1112
1113 return true;
1114}
1115
1116/// See if LazyValueInfo's ability to exploit edge conditions or range
1117/// information is sufficient to prove the signs of both operands of this SDiv.
1118/// If this is the case, replace the SDiv with a UDiv. Even for local
1119/// conditions, this can sometimes prove conditions instcombine can't by
1120/// exploiting range information.
1121bool CVPImpl::processSDiv(BinaryOperator *SDI, const ConstantRange &LCR,
1122 const ConstantRange &RCR) {
1123 assert(SDI->getOpcode() == Instruction::SDiv);
1124
1125 // Check whether the division folds to a constant.
1126 ConstantRange DivCR = LCR.sdiv(RCR);
1127 if (const APInt *Elem = DivCR.getSingleElement()) {
1128 salvageDebugInfo(*SDI);
1129 SDI->replaceAllUsesWith(ConstantInt::get(SDI->getType(), *Elem));
1130 SDI->eraseFromParent();
1131 return true;
1132 }
1133
1134 struct Operand {
1135 Value *V;
1136 Domain D;
1137 };
1138 std::array<Operand, 2> Ops = {{{SDI->getOperand(0), getDomain(LCR)},
1139 {SDI->getOperand(1), getDomain(RCR)}}};
1140 if (Ops[0].D == Domain::Unknown || Ops[1].D == Domain::Unknown)
1141 return false;
1142
1143 // We know domains of both of the operands!
1144 ++NumSDivs;
1145
1146 // We need operands to be non-negative, so negate each one that isn't.
1147 for (Operand &Op : Ops) {
1148 if (Op.D == Domain::NonNegative)
1149 continue;
1150 auto *BO = BinaryOperator::CreateNeg(Op.V, Op.V->getName() + ".nonneg",
1151 SDI->getIterator());
1152 BO->setDebugLoc(SDI->getDebugLoc());
1153 Op.V = BO;
1154 }
1155
1156 auto *UDiv = BinaryOperator::CreateUDiv(Ops[0].V, Ops[1].V, SDI->getName(),
1157 SDI->getIterator());
1158 UDiv->setDebugLoc(SDI->getDebugLoc());
1159 UDiv->setIsExact(SDI->isExact());
1160
1161 auto *Res = UDiv;
1162
1163 // If the operands had two different domains, we need to negate the result.
1164 if (Ops[0].D != Ops[1].D) {
1165 Res = BinaryOperator::CreateNeg(Res, Res->getName() + ".neg",
1166 SDI->getIterator());
1167 Res->setDebugLoc(SDI->getDebugLoc());
1168 }
1169
1170 salvageDebugInfo(*SDI);
1171 SDI->replaceAllUsesWith(Res);
1172 SDI->eraseFromParent();
1173
1174 // Try to simplify our new udiv.
1175 processUDivOrURem(UDiv);
1176
1177 return true;
1178}
1179
1180bool CVPImpl::processSDivOrSRem(BinaryOperator *Instr) {
1181 assert(Instr->getOpcode() == Instruction::SDiv ||
1182 Instr->getOpcode() == Instruction::SRem);
1183 ConstantRange LCR =
1184 LVI->getConstantRangeAtUse(Instr->getOperandUse(0), /*AllowUndef*/ false);
1185 // Allow undef for RHS, as we can assume it is division by zero UB.
1186 ConstantRange RCR =
1187 LVI->getConstantRangeAtUse(Instr->getOperandUse(1), /*AlloweUndef*/ true);
1188 if (Instr->getOpcode() == Instruction::SDiv)
1189 if (processSDiv(Instr, LCR, RCR))
1190 return true;
1191
1192 if (Instr->getOpcode() == Instruction::SRem) {
1193 if (processSRem(Instr, LCR, RCR))
1194 return true;
1195 }
1196
1197 return narrowSDivOrSRem(Instr, LCR, RCR);
1198}
1199
1200bool CVPImpl::processAShr(BinaryOperator *SDI) {
1201 ConstantRange LRange =
1202 LVI->getConstantRangeAtUse(SDI->getOperandUse(0), /*UndefAllowed*/ false);
1203 unsigned OrigWidth = SDI->getType()->getScalarSizeInBits();
1204 ConstantRange NegOneOrZero =
1205 ConstantRange(APInt(OrigWidth, (uint64_t)-1, true), APInt(OrigWidth, 1));
1206 if (NegOneOrZero.contains(LRange)) {
1207 // ashr of -1 or 0 never changes the value, so drop the whole instruction
1208 ++NumAShrsRemoved;
1209 salvageDebugInfo(*SDI);
1210 SDI->replaceAllUsesWith(SDI->getOperand(0));
1211 SDI->eraseFromParent();
1212 return true;
1213 }
1214
1215 if (!LRange.isAllNonNegative())
1216 return false;
1217
1218 ++NumAShrsConverted;
1219 auto *BO = BinaryOperator::CreateLShr(SDI->getOperand(0), SDI->getOperand(1),
1220 "", SDI->getIterator());
1221 BO->takeName(SDI);
1222 BO->setDebugLoc(SDI->getDebugLoc());
1223 BO->setIsExact(SDI->isExact());
1224 salvageDebugInfo(*SDI);
1225 SDI->replaceAllUsesWith(BO);
1226 SDI->eraseFromParent();
1227
1228 return true;
1229}
1230
1231bool CVPImpl::processSExt(SExtInst *SDI) {
1232 const Use &Base = SDI->getOperandUse(0);
1233 if (!LVI->getConstantRangeAtUse(Base, /*UndefAllowed*/ false)
1235 return false;
1236
1237 ++NumSExt;
1238 auto *ZExt = CastInst::CreateZExtOrBitCast(Base, SDI->getType(), "",
1239 SDI->getIterator());
1240 ZExt->takeName(SDI);
1241 ZExt->setDebugLoc(SDI->getDebugLoc());
1242 ZExt->setNonNeg();
1243 salvageDebugInfo(*SDI);
1244 SDI->replaceAllUsesWith(ZExt);
1245 SDI->eraseFromParent();
1246
1247 return true;
1248}
1249
1250bool CVPImpl::processPossibleNonNeg(PossiblyNonNegInst *I) {
1251 if (I->hasNonNeg())
1252 return false;
1253
1254 const Use &Base = I->getOperandUse(0);
1255 if (!LVI->getConstantRangeAtUse(Base, /*UndefAllowed*/ false)
1257 return false;
1258
1259 ++NumNNeg;
1260 I->setNonNeg();
1261
1262 return true;
1263}
1264
1265bool CVPImpl::processSIToFP(SIToFPInst *SIToFP) {
1266 const Use &Base = SIToFP->getOperandUse(0);
1267 if (!LVI->getConstantRangeAtUse(Base, /*UndefAllowed*/ false)
1269 return false;
1270
1271 ++NumSIToFP;
1272 auto *UIToFP = CastInst::Create(Instruction::UIToFP, Base, SIToFP->getType(),
1273 "", SIToFP->getIterator());
1274 UIToFP->takeName(SIToFP);
1275 UIToFP->setDebugLoc(SIToFP->getDebugLoc());
1276 UIToFP->setNonNeg();
1277 salvageDebugInfo(*SIToFP);
1278 SIToFP->replaceAllUsesWith(UIToFP);
1279 SIToFP->eraseFromParent();
1280
1281 return true;
1282}
1283
1284namespace {
1285struct NoWrapFlags {
1286 bool NSW = false;
1287 bool NUW = false;
1288};
1289} // namespace
1290
1291// Check if the requested no-wrap flags are valid for \p Opcode on \p LRange and
1292// \p RRange.
1294 const ConstantRange &LRange,
1295 const ConstantRange &RRange,
1296 bool CheckNSW, bool CheckNUW) {
1297 using OBO = OverflowingBinaryOperator;
1298 NoWrapFlags Flags;
1299 if (CheckNUW)
1300 Flags.NUW = ConstantRange::makeGuaranteedNoWrapRegion(Opcode, RRange,
1301 OBO::NoUnsignedWrap)
1302 .contains(LRange);
1303 if (CheckNSW)
1304 Flags.NSW = ConstantRange::makeGuaranteedNoWrapRegion(Opcode, RRange,
1305 OBO::NoSignedWrap)
1306 .contains(LRange);
1307 return Flags;
1308}
1309
1310// Try to prove that \p BinOp does not wrap by looking at the operand ranges
1311// constrained at each of its use sites, rather than at the definition. This
1312// improves results, e.g. when all uses are constrained by a runtime check.
1313NoWrapFlags CVPImpl::inferNoWrapFromUses(BinaryOperator *BinOp, bool WantNSW,
1314 bool WantNUW) {
1315 // Skip analysis, when there are too many uses to check or any use is in the
1316 // same block.
1317 const unsigned MaxUsesToInspect = 4;
1318 BasicBlock *DefBB = BinOp->getParent();
1319 unsigned NumUses = 0;
1320 for (Use &U : BinOp->uses()) {
1321 if (++NumUses > MaxUsesToInspect)
1322 return {};
1323 auto *UserI = cast<Instruction>(U.getUser());
1324 if (isa<PHINode>(UserI) || UserI->getParent() == DefBB)
1325 return {};
1326 }
1327 if (NumUses == 0)
1328 return {};
1329
1330 Instruction::BinaryOps Opcode = BinOp->getOpcode();
1331 NoWrapFlags Flags;
1332 Flags.NSW = WantNSW;
1333 Flags.NUW = WantNUW;
1334 for (Use &U : BinOp->uses()) {
1335 auto *UserI = cast<Instruction>(U.getUser());
1336 // Constrain both operands at this use site and see which flags still hold.
1337 ConstantRange LRange = LVI->getConstantRange(BinOp->getOperand(0), UserI,
1338 /*UndefAllowed=*/false);
1339 ConstantRange RRange = LVI->getConstantRange(BinOp->getOperand(1), UserI,
1340 /*UndefAllowed=*/false);
1341 Flags = computeNoWrapFlags(Opcode, LRange, RRange, Flags.NSW, Flags.NUW);
1342 if (!Flags.NSW && !Flags.NUW)
1343 return {};
1344 }
1345
1346 return Flags;
1347}
1348
1349bool CVPImpl::processBinOp(BinaryOperator *BinOp) {
1350 bool NSW = BinOp->hasNoSignedWrap();
1351 bool NUW = BinOp->hasNoUnsignedWrap();
1352 if (NSW && NUW)
1353 return false;
1354
1355 Instruction::BinaryOps Opcode = BinOp->getOpcode();
1356 ConstantRange LRange = LVI->getConstantRangeAtUse(BinOp->getOperandUse(0),
1357 /*UndefAllowed=*/false);
1358 ConstantRange RRange = LVI->getConstantRangeAtUse(BinOp->getOperandUse(1),
1359 /*UndefAllowed=*/false);
1360
1361 NoWrapFlags New =
1362 computeNoWrapFlags(Opcode, LRange, RRange, /*CheckNSW=*/!NSW,
1363 /*CheckNUW=*/!NUW);
1364
1365 // If a still-wanted flag could not be proven at the definition, retry using
1366 // the operand ranges constrained at the use sites. This is the more
1367 // expensive path, so it only runs when the cheap query above came up short.
1368 bool WantNSW = !NSW && !New.NSW;
1369 bool WantNUW = !NUW && !New.NUW;
1370 if (WantNSW || WantNUW) {
1371 NoWrapFlags FromUses = inferNoWrapFromUses(BinOp, WantNSW, WantNUW);
1372 New.NSW |= FromUses.NSW;
1373 New.NUW |= FromUses.NUW;
1374 }
1375
1376 setDeducedOverflowingFlags(BinOp, Opcode, New.NSW, New.NUW);
1377
1378 return New.NSW || New.NUW;
1379}
1380
1381bool CVPImpl::processAnd(BinaryOperator *BinOp) {
1382 using namespace llvm::PatternMatch;
1383
1384 // Pattern match (and lhs, C) where C includes a superset of bits which might
1385 // be set in lhs. This is a common truncation idiom created by instcombine.
1386 const Use &LHS = BinOp->getOperandUse(0);
1387 const APInt *RHS;
1388 if (!match(BinOp->getOperand(1), m_LowBitMask(RHS)))
1389 return false;
1390
1391 // We can only replace the AND with LHS based on range info if the range does
1392 // not include undef.
1393 ConstantRange LRange =
1394 LVI->getConstantRangeAtUse(LHS, /*UndefAllowed=*/false);
1395 if (!LRange.getUnsignedMax().ule(*RHS))
1396 return false;
1397
1398 salvageDebugInfo(*BinOp);
1399 BinOp->replaceAllUsesWith(LHS);
1400 BinOp->eraseFromParent();
1401 NumAnd++;
1402 return true;
1403}
1404
1405bool CVPImpl::processTrunc(TruncInst *TI) {
1406 if (TI->hasNoSignedWrap() && TI->hasNoUnsignedWrap())
1407 return false;
1408
1409 ConstantRange Range =
1410 LVI->getConstantRangeAtUse(TI->getOperandUse(0), /*UndefAllowed=*/false);
1411 uint64_t DestWidth = TI->getDestTy()->getScalarSizeInBits();
1412 bool Changed = false;
1413
1414 if (!TI->hasNoUnsignedWrap()) {
1415 if (Range.getActiveBits() <= DestWidth) {
1416 TI->setHasNoUnsignedWrap(true);
1417 ++NumNUW;
1418 Changed = true;
1419 }
1420 }
1421
1422 if (!TI->hasNoSignedWrap()) {
1423 if (Range.getMinSignedBits() <= DestWidth) {
1424 TI->setHasNoSignedWrap(true);
1425 ++NumNSW;
1426 Changed = true;
1427 }
1428 }
1429
1430 return Changed;
1431}
1432
1433bool CVPImpl::processReturn(ReturnInst *RI) {
1434 // Try to determine the return value if we can. This is mainly here to
1435 // simplify the writing of unit tests, but also helps to enable IPO by
1436 // constant folding the return values of callees.
1437 Value *RetVal = RI->getReturnValue();
1438 if (!RetVal)
1439 return false; // handle "ret void"
1440 if (RetRange && !RetRange->isFullSet())
1441 RetRange = RetRange->unionWith(
1442 LVI->getConstantRange(RetVal, RI, /*UndefAllowed=*/false));
1443
1444 if (isa<Constant>(RetVal))
1445 return false; // nothing to do
1446 if (Constant *C = getConstantAt(RetVal, RI, &RI->getOperandUse(0))) {
1447 ++NumReturns;
1448 RI->replaceUsesOfWith(RetVal, C);
1449 return true;
1450 }
1451 return false;
1452}
1453
1454bool CVPImpl::processInstruction(Instruction &I) {
1455 switch (I.getOpcode()) {
1456 case Instruction::Select:
1457 return processSelect(cast<SelectInst>(&I));
1458 case Instruction::PHI:
1459 return processPHI(cast<PHINode>(&I));
1460 case Instruction::ICmp:
1461 case Instruction::FCmp:
1462 return processCmp(cast<CmpInst>(&I));
1463 case Instruction::Call:
1464 case Instruction::Invoke:
1465 return processCallSite(cast<CallBase>(I));
1466 case Instruction::SRem:
1467 case Instruction::SDiv:
1468 return processSDivOrSRem(cast<BinaryOperator>(&I));
1469 case Instruction::UDiv:
1470 case Instruction::URem:
1471 return processUDivOrURem(cast<BinaryOperator>(&I));
1472 case Instruction::AShr:
1473 return processAShr(cast<BinaryOperator>(&I));
1474 case Instruction::SExt:
1475 return processSExt(cast<SExtInst>(&I));
1476 case Instruction::ZExt:
1477 case Instruction::UIToFP:
1478 return processPossibleNonNeg(cast<PossiblyNonNegInst>(&I));
1479 case Instruction::SIToFP:
1480 return processSIToFP(cast<SIToFPInst>(&I));
1481 case Instruction::Add:
1482 case Instruction::Sub:
1483 case Instruction::Mul:
1484 case Instruction::Shl:
1485 return processBinOp(cast<BinaryOperator>(&I));
1486 case Instruction::And:
1487 return processAnd(cast<BinaryOperator>(&I));
1488 case Instruction::Trunc:
1489 return processTrunc(cast<TruncInst>(&I));
1490 case Instruction::Switch:
1491 return processSwitch(cast<SwitchInst>(&I));
1492 case Instruction::Ret:
1493 return processReturn(cast<ReturnInst>(&I));
1494 default:
1495 return false;
1496 }
1497}
1498
1499bool CVPImpl::inferReturnRangeAttr() {
1500 // Infer range attribute on return value.
1501 if (!RetRange || RetRange->isFullSet())
1502 return false;
1503 Attribute RangeAttr = F.getRetAttribute(Attribute::Range);
1504 if (RangeAttr.isValid())
1505 RetRange = RetRange->intersectWith(RangeAttr.getRange());
1506 // Don't add attribute for constant integer returns to reduce noise. These
1507 // are propagated across functions by IPSCCP.
1508 if (RetRange->isEmptySet() || RetRange->isSingleElement())
1509 return false;
1510 F.addRangeRetAttr(*RetRange);
1511 return true;
1512}
1513
1514bool CVPImpl::run() {
1515 if (F.hasExactDefinition() && F.getReturnType()->isIntOrIntVectorTy())
1516 RetRange =
1517 ConstantRange::getEmpty(F.getReturnType()->getScalarSizeInBits());
1518
1519 bool Changed = false;
1520 // Visiting in a pre-order depth-first traversal causes us to simplify early
1521 // blocks before querying later blocks (which require us to analyze early
1522 // blocks). Eagerly simplifying shallow blocks means there is strictly less
1523 // work to do for deep blocks. This also means we don't visit unreachable
1524 // blocks.
1525 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
1526 for (Instruction &I : llvm::make_early_inc_range(*BB))
1527 Changed |= processInstruction(I);
1528
1529 Changed |= inferReturnRangeAttr();
1530 return Changed;
1531}
1532
1533PreservedAnalyses
1537
1538 CVPImpl Impl(F, LVI, DT, getBestSimplifyQuery(AM, F));
1539 bool Changed = Impl.run();
1540
1542 if (!Changed) {
1544 } else {
1545#if defined(EXPENSIVE_CHECKS)
1546 assert(DT->verify(DominatorTree::VerificationLevel::Full));
1547#else
1548 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
1549#endif // EXPENSIVE_CHECKS
1550
1553 }
1554
1555 // Keeping LVI alive is expensive, both because it uses a lot of memory, and
1556 // because invalidating values in LVI is expensive. While CVP does preserve
1557 // LVI, we know that passes after JumpThreading+CVP will not need the result
1558 // of this analysis, so we forcefully discard it early.
1560 return PA;
1561}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool expandUDivOrURem(BinaryOperator *Instr, const ConstantRange &XCR, const ConstantRange &YCR)
static bool narrowUDivOrURem(BinaryOperator *Instr, const ConstantRange &XCR, const ConstantRange &YCR)
Try to shrink a udiv/urem's width down to the smallest power of two that's sufficient to contain its ...
static void setDeducedOverflowingFlags(Value *V, Instruction::BinaryOps Opcode, bool NewNSW, bool NewNUW)
static Domain getDomain(const ConstantRange &CR)
static bool narrowSDivOrSRem(BinaryOperator *Instr, const ConstantRange &LCR, const ConstantRange &RCR)
Try to shrink a sdiv/srem's width down to the smallest power of two that's sufficient to contain its ...
static NoWrapFlags computeNoWrapFlags(Instruction::BinaryOps Opcode, const ConstantRange &LRange, const ConstantRange &RRange, bool CheckNSW, bool CheckNUW)
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
SmallVector< MachineOperand, 4 > Cond
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:357
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_ABI const ConstantRange & getRange() const
Returns the value of the range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:263
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI bool isSigned() const
Whether the intrinsic is signed or unsigned.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
void setAttributes(AttributeList A)
Set the attributes for this call.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
static LLVM_ABI CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Type * getDestTy() const
Return the destination type, as a convenience.
Definition InstrTypes.h:681
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
static CmpInst::Predicate getGTPredicate(Intrinsic::ID ID)
static CmpInst::Predicate getLTPredicate(Intrinsic::ID ID)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents a range of values.
LLVM_ABI unsigned getActiveBits() const
Compute the maximal number of active bits needed to represent every value in this range.
static LLVM_ABI CmpInst::Predicate getEquivalentPredWithFlippedSignedness(CmpInst::Predicate Pred, const ConstantRange &CR1, const ConstantRange &CR2)
If the comparison between constant ranges this and Other is insensitive to the signedness of the comp...
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
LLVM_ABI ConstantRange abs(bool IntMinIsPoison=false) const
Calculate absolute value range.
LLVM_ABI ConstantRange uadd_sat(const ConstantRange &Other) const
Perform an unsigned saturating addition of two constant ranges.
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
LLVM_ABI ConstantRange sdiv(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed division of a value in th...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
static LLVM_ABI bool areInsensitiveToSignednessOfICmpPredicate(const ConstantRange &CR1, const ConstantRange &CR2)
Return true iff CR1 ult CR2 is equivalent to CR1 slt CR2.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:83
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static DebugLoc getTemporary()
Definition DebugLoc.h:153
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Analysis to compute lazy value information.
This pass computes, caches, and vends lazy value constraint information.
LLVM_ABI ConstantRange getConstantRangeAtUse(const Use &U, bool UndefAllowed, SmallVectorImpl< DbgVariableRecord * > *DebugUsers=nullptr, bool AssumeFrozen=false)
Return the ConstantRange constraint that is known to hold for the value at a specific use-site.
LLVM_ABI Constant * getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=nullptr, const Use *U=nullptr)
Determine whether the specified value is known to be a constant on the specified edge.
LLVM_ABI Constant * getConstant(Value *V, Instruction *CtxI, const Use *U=nullptr)
Determine whether the specified value is known to be a constant at the specified instruction.
LLVM_ABI Constant * getPredicateAt(CmpInst::Predicate Pred, Value *V, Constant *C, Instruction *CtxI, bool UseBlockValue)
Determine whether the specified value comparison with a constant is known to be true or false at the ...
LLVM_ABI ConstantRange getConstantRange(Value *V, Instruction *CtxI, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the specified value at the specified in...
LLVM_ABI Constant * getPredicateOnEdge(CmpInst::Predicate Pred, Value *V, Constant *C, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=nullptr)
Determine whether the specified value comparison with a constant is known to be true or false on the ...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
Value * getLHS() const
Value * getRHS() const
static ICmpInst::Predicate getPredicate(Intrinsic::ID ID)
Returns the comparison predicate underlying the intrinsic.
static bool isSigned(Intrinsic::ID ID)
Whether the intrinsic is signed or unsigned.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & abandon()
Mark an analysis as abandoned.
Definition Analysis.h:172
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:133
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
void push_back(const T &Elt)
void setHasNoSignedWrap(bool B)
void setHasNoUnsignedWrap(bool B)
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * get() const
Definition Use.h:55
const Use & getOperandUse(unsigned i) const
Definition User.h:220
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
bool match(Val *V, const Pattern &P)
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
@ Unknown
Not known to have no common set bits.
LLVM_ABI bool freezeUsesAfterDef(FreezeInst &FI, DominatorTree &DT, SmallVectorImpl< User * > *Users=nullptr)
Move FI right after the definition of its operand, and replace the uses of the operand that it domina...
Definition Local.cpp:4096
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1837
auto successors(const MachineBasicBlock *BB)
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
NoopStatistic Statistic
Definition Statistic.h:162
LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To, const DataLayout &DL)
Definition Loads.cpp:926
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI const SimplifyQuery getBestSimplifyQuery(Pass &, Function &)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)