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