LLVM 18.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/Operator.h"
36#include "llvm/IR/PassManager.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Value.h"
42#include <cassert>
43#include <optional>
44#include <utility>
45
46using namespace llvm;
47
48#define DEBUG_TYPE "correlated-value-propagation"
49
51 "canonicalize-icmp-predicates-to-unsigned", cl::init(true), cl::Hidden,
52 cl::desc("Enables canonicalization of signed relational predicates to "
53 "unsigned (e.g. sgt => ugt)"));
54
55STATISTIC(NumPhis, "Number of phis propagated");
56STATISTIC(NumPhiCommon, "Number of phis deleted via common incoming value");
57STATISTIC(NumSelects, "Number of selects propagated");
58STATISTIC(NumCmps, "Number of comparisons propagated");
59STATISTIC(NumReturns, "Number of return values propagated");
60STATISTIC(NumDeadCases, "Number of switch cases removed");
61STATISTIC(NumSDivSRemsNarrowed,
62 "Number of sdivs/srems whose width was decreased");
63STATISTIC(NumSDivs, "Number of sdiv converted to udiv");
64STATISTIC(NumUDivURemsNarrowed,
65 "Number of udivs/urems whose width was decreased");
66STATISTIC(NumAShrsConverted, "Number of ashr converted to lshr");
67STATISTIC(NumAShrsRemoved, "Number of ashr removed");
68STATISTIC(NumSRems, "Number of srem converted to urem");
69STATISTIC(NumSExt, "Number of sext converted to zext");
70STATISTIC(NumSICmps, "Number of signed icmp preds simplified to unsigned");
71STATISTIC(NumAnd, "Number of ands removed");
72STATISTIC(NumNW, "Number of no-wrap deductions");
73STATISTIC(NumNSW, "Number of no-signed-wrap deductions");
74STATISTIC(NumNUW, "Number of no-unsigned-wrap deductions");
75STATISTIC(NumAddNW, "Number of no-wrap deductions for add");
76STATISTIC(NumAddNSW, "Number of no-signed-wrap deductions for add");
77STATISTIC(NumAddNUW, "Number of no-unsigned-wrap deductions for add");
78STATISTIC(NumSubNW, "Number of no-wrap deductions for sub");
79STATISTIC(NumSubNSW, "Number of no-signed-wrap deductions for sub");
80STATISTIC(NumSubNUW, "Number of no-unsigned-wrap deductions for sub");
81STATISTIC(NumMulNW, "Number of no-wrap deductions for mul");
82STATISTIC(NumMulNSW, "Number of no-signed-wrap deductions for mul");
83STATISTIC(NumMulNUW, "Number of no-unsigned-wrap deductions for mul");
84STATISTIC(NumShlNW, "Number of no-wrap deductions for shl");
85STATISTIC(NumShlNSW, "Number of no-signed-wrap deductions for shl");
86STATISTIC(NumShlNUW, "Number of no-unsigned-wrap deductions for shl");
87STATISTIC(NumAbs, "Number of llvm.abs intrinsics removed");
88STATISTIC(NumOverflows, "Number of overflow checks removed");
89STATISTIC(NumSaturating,
90 "Number of saturating arithmetics converted to normal arithmetics");
91STATISTIC(NumNonNull, "Number of function pointer arguments marked non-null");
92STATISTIC(NumMinMax, "Number of llvm.[us]{min,max} intrinsics removed");
93STATISTIC(NumUDivURemsNarrowedExpanded,
94 "Number of bound udiv's/urem's expanded");
95STATISTIC(NumZExt, "Number of non-negative deductions");
96
97static bool processSelect(SelectInst *S, LazyValueInfo *LVI) {
98 if (S->getType()->isVectorTy() || isa<Constant>(S->getCondition()))
99 return false;
100
101 bool Changed = false;
102 for (Use &U : make_early_inc_range(S->uses())) {
103 auto *I = cast<Instruction>(U.getUser());
104 Constant *C;
105 if (auto *PN = dyn_cast<PHINode>(I))
106 C = LVI->getConstantOnEdge(S->getCondition(), PN->getIncomingBlock(U),
107 I->getParent(), I);
108 else
109 C = LVI->getConstant(S->getCondition(), I);
110
111 auto *CI = dyn_cast_or_null<ConstantInt>(C);
112 if (!CI)
113 continue;
114
115 U.set(CI->isOne() ? S->getTrueValue() : S->getFalseValue());
116 Changed = true;
117 ++NumSelects;
118 }
119
120 if (Changed && S->use_empty())
121 S->eraseFromParent();
122
123 return Changed;
124}
125
126/// Try to simplify a phi with constant incoming values that match the edge
127/// values of a non-constant value on all other edges:
128/// bb0:
129/// %isnull = icmp eq i8* %x, null
130/// br i1 %isnull, label %bb2, label %bb1
131/// bb1:
132/// br label %bb2
133/// bb2:
134/// %r = phi i8* [ %x, %bb1 ], [ null, %bb0 ]
135/// -->
136/// %r = %x
138 DominatorTree *DT) {
139 // Collect incoming constants and initialize possible common value.
141 Value *CommonValue = nullptr;
142 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
143 Value *Incoming = P->getIncomingValue(i);
144 if (auto *IncomingConstant = dyn_cast<Constant>(Incoming)) {
145 IncomingConstants.push_back(std::make_pair(IncomingConstant, i));
146 } else if (!CommonValue) {
147 // The potential common value is initialized to the first non-constant.
148 CommonValue = Incoming;
149 } else if (Incoming != CommonValue) {
150 // There can be only one non-constant common value.
151 return false;
152 }
153 }
154
155 if (!CommonValue || IncomingConstants.empty())
156 return false;
157
158 // The common value must be valid in all incoming blocks.
159 BasicBlock *ToBB = P->getParent();
160 if (auto *CommonInst = dyn_cast<Instruction>(CommonValue))
161 if (!DT->dominates(CommonInst, ToBB))
162 return false;
163
164 // We have a phi with exactly 1 variable incoming value and 1 or more constant
165 // incoming values. See if all constant incoming values can be mapped back to
166 // the same incoming variable value.
167 for (auto &IncomingConstant : IncomingConstants) {
168 Constant *C = IncomingConstant.first;
169 BasicBlock *IncomingBB = P->getIncomingBlock(IncomingConstant.second);
170 if (C != LVI->getConstantOnEdge(CommonValue, IncomingBB, ToBB, P))
171 return false;
172 }
173
174 // LVI only guarantees that the value matches a certain constant if the value
175 // is not poison. Make sure we don't replace a well-defined value with poison.
176 // This is usually satisfied due to a prior branch on the value.
177 if (!isGuaranteedNotToBePoison(CommonValue, nullptr, P, DT))
178 return false;
179
180 // All constant incoming values map to the same variable along the incoming
181 // edges of the phi. The phi is unnecessary.
182 P->replaceAllUsesWith(CommonValue);
183 P->eraseFromParent();
184 ++NumPhiCommon;
185 return true;
186}
187
188static Value *getValueOnEdge(LazyValueInfo *LVI, Value *Incoming,
190 Instruction *CxtI) {
191 if (Constant *C = LVI->getConstantOnEdge(Incoming, From, To, CxtI))
192 return C;
193
194 // Look if the incoming value is a select with a scalar condition for which
195 // LVI can tells us the value. In that case replace the incoming value with
196 // the appropriate value of the select. This often allows us to remove the
197 // select later.
198 auto *SI = dyn_cast<SelectInst>(Incoming);
199 if (!SI)
200 return nullptr;
201
202 // Once LVI learns to handle vector types, we could also add support
203 // for vector type constants that are not all zeroes or all ones.
204 Value *Condition = SI->getCondition();
205 if (!Condition->getType()->isVectorTy()) {
206 if (Constant *C = LVI->getConstantOnEdge(Condition, From, To, CxtI)) {
207 if (C->isOneValue())
208 return SI->getTrueValue();
209 if (C->isZeroValue())
210 return SI->getFalseValue();
211 }
212 }
213
214 // Look if the select has a constant but LVI tells us that the incoming
215 // value can never be that constant. In that case replace the incoming
216 // value with the other value of the select. This often allows us to
217 // remove the select later.
218
219 // The "false" case
220 if (auto *C = dyn_cast<Constant>(SI->getFalseValue()))
221 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C, From, To, CxtI) ==
223 return SI->getTrueValue();
224
225 // The "true" case,
226 // similar to the select "false" case, but try the select "true" value
227 if (auto *C = dyn_cast<Constant>(SI->getTrueValue()))
228 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C, From, To, CxtI) ==
230 return SI->getFalseValue();
231
232 return nullptr;
233}
234
236 const SimplifyQuery &SQ) {
237 bool Changed = false;
238
239 BasicBlock *BB = P->getParent();
240 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
241 Value *Incoming = P->getIncomingValue(i);
242 if (isa<Constant>(Incoming)) continue;
243
244 Value *V = getValueOnEdge(LVI, Incoming, P->getIncomingBlock(i), BB, P);
245 if (V) {
246 P->setIncomingValue(i, V);
247 Changed = true;
248 }
249 }
250
251 if (Value *V = simplifyInstruction(P, SQ)) {
252 P->replaceAllUsesWith(V);
253 P->eraseFromParent();
254 Changed = true;
255 }
256
257 if (!Changed)
258 Changed = simplifyCommonValuePhi(P, LVI, DT);
259
260 if (Changed)
261 ++NumPhis;
262
263 return Changed;
264}
265
266static bool processICmp(ICmpInst *Cmp, LazyValueInfo *LVI) {
268 return false;
269
270 // Only for signed relational comparisons of scalar integers.
271 if (Cmp->getType()->isVectorTy() ||
272 !Cmp->getOperand(0)->getType()->isIntegerTy())
273 return false;
274
275 if (!Cmp->isSigned())
276 return false;
277
278 ICmpInst::Predicate UnsignedPred =
280 Cmp->getPredicate(),
281 LVI->getConstantRangeAtUse(Cmp->getOperandUse(0)),
282 LVI->getConstantRangeAtUse(Cmp->getOperandUse(1)));
283
284 if (UnsignedPred == ICmpInst::Predicate::BAD_ICMP_PREDICATE)
285 return false;
286
287 ++NumSICmps;
288 Cmp->setPredicate(UnsignedPred);
289
290 return true;
291}
292
293/// See if LazyValueInfo's ability to exploit edge conditions or range
294/// information is sufficient to prove this comparison. Even for local
295/// conditions, this can sometimes prove conditions instcombine can't by
296/// exploiting range information.
297static bool constantFoldCmp(CmpInst *Cmp, LazyValueInfo *LVI) {
298 Value *Op0 = Cmp->getOperand(0);
299 Value *Op1 = Cmp->getOperand(1);
301 LVI->getPredicateAt(Cmp->getPredicate(), Op0, Op1, Cmp,
302 /*UseBlockValue=*/true);
303 if (Result == LazyValueInfo::Unknown)
304 return false;
305
306 ++NumCmps;
307 Constant *TorF =
309 Cmp->replaceAllUsesWith(TorF);
310 Cmp->eraseFromParent();
311 return true;
312}
313
314static bool processCmp(CmpInst *Cmp, LazyValueInfo *LVI) {
315 if (constantFoldCmp(Cmp, LVI))
316 return true;
317
318 if (auto *ICmp = dyn_cast<ICmpInst>(Cmp))
319 if (processICmp(ICmp, LVI))
320 return true;
321
322 return false;
323}
324
325/// Simplify a switch instruction by removing cases which can never fire. If the
326/// uselessness of a case could be determined locally then constant propagation
327/// would already have figured it out. Instead, walk the predecessors and
328/// statically evaluate cases based on information available on that edge. Cases
329/// that cannot fire no matter what the incoming edge can safely be removed. If
330/// a case fires on every incoming edge then the entire switch can be removed
331/// and replaced with a branch to the case destination.
333 DominatorTree *DT) {
334 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
335 Value *Cond = I->getCondition();
336 BasicBlock *BB = I->getParent();
337
338 // Analyse each switch case in turn.
339 bool Changed = false;
340 DenseMap<BasicBlock*, int> SuccessorsCount;
341 for (auto *Succ : successors(BB))
342 SuccessorsCount[Succ]++;
343
344 { // Scope for SwitchInstProfUpdateWrapper. It must not live during
345 // ConstantFoldTerminator() as the underlying SwitchInst can be changed.
347
348 for (auto CI = SI->case_begin(), CE = SI->case_end(); CI != CE;) {
349 ConstantInt *Case = CI->getCaseValue();
352 /* UseBlockValue */ true);
353
354 if (State == LazyValueInfo::False) {
355 // This case never fires - remove it.
356 BasicBlock *Succ = CI->getCaseSuccessor();
357 Succ->removePredecessor(BB);
358 CI = SI.removeCase(CI);
359 CE = SI->case_end();
360
361 // The condition can be modified by removePredecessor's PHI simplification
362 // logic.
363 Cond = SI->getCondition();
364
365 ++NumDeadCases;
366 Changed = true;
367 if (--SuccessorsCount[Succ] == 0)
368 DTU.applyUpdatesPermissive({{DominatorTree::Delete, BB, Succ}});
369 continue;
370 }
371 if (State == LazyValueInfo::True) {
372 // This case always fires. Arrange for the switch to be turned into an
373 // unconditional branch by replacing the switch condition with the case
374 // value.
375 SI->setCondition(Case);
376 NumDeadCases += SI->getNumCases();
377 Changed = true;
378 break;
379 }
380
381 // Increment the case iterator since we didn't delete it.
382 ++CI;
383 }
384 }
385
386 if (Changed)
387 // If the switch has been simplified to the point where it can be replaced
388 // by a branch then do so now.
389 ConstantFoldTerminator(BB, /*DeleteDeadConditions = */ false,
390 /*TLI = */ nullptr, &DTU);
391 return Changed;
392}
393
394// See if we can prove that the given binary op intrinsic will not overflow.
399 BO->getBinaryOp(), RRange, BO->getNoWrapKind());
400 return NWRegion.contains(LRange);
401}
402
404 bool NewNSW, bool NewNUW) {
405 Statistic *OpcNW, *OpcNSW, *OpcNUW;
406 switch (Opcode) {
407 case Instruction::Add:
408 OpcNW = &NumAddNW;
409 OpcNSW = &NumAddNSW;
410 OpcNUW = &NumAddNUW;
411 break;
412 case Instruction::Sub:
413 OpcNW = &NumSubNW;
414 OpcNSW = &NumSubNSW;
415 OpcNUW = &NumSubNUW;
416 break;
417 case Instruction::Mul:
418 OpcNW = &NumMulNW;
419 OpcNSW = &NumMulNSW;
420 OpcNUW = &NumMulNUW;
421 break;
422 case Instruction::Shl:
423 OpcNW = &NumShlNW;
424 OpcNSW = &NumShlNSW;
425 OpcNUW = &NumShlNUW;
426 break;
427 default:
428 llvm_unreachable("Will not be called with other binops");
429 }
430
431 auto *Inst = dyn_cast<Instruction>(V);
432 if (NewNSW) {
433 ++NumNW;
434 ++*OpcNW;
435 ++NumNSW;
436 ++*OpcNSW;
437 if (Inst)
438 Inst->setHasNoSignedWrap();
439 }
440 if (NewNUW) {
441 ++NumNW;
442 ++*OpcNW;
443 ++NumNUW;
444 ++*OpcNUW;
445 if (Inst)
446 Inst->setHasNoUnsignedWrap();
447 }
448}
449
450static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI);
451
452// See if @llvm.abs argument is alays positive/negative, and simplify.
453// Notably, INT_MIN can belong to either range, regardless of the NSW,
454// because it is negation-invariant.
456 Value *X = II->getArgOperand(0);
457 Type *Ty = X->getType();
458 if (!Ty->isIntegerTy())
459 return false;
460
461 bool IsIntMinPoison = cast<ConstantInt>(II->getArgOperand(1))->isOne();
464 II->getOperandUse(0), /*UndefAllowed*/ IsIntMinPoison);
465
466 // Is X in [0, IntMin]? NOTE: INT_MIN is fine!
467 if (Range.icmp(CmpInst::ICMP_ULE, IntMin)) {
468 ++NumAbs;
470 II->eraseFromParent();
471 return true;
472 }
473
474 // Is X in [IntMin, 0]? NOTE: INT_MIN is fine!
475 if (Range.getSignedMax().isNonPositive()) {
476 IRBuilder<> B(II);
477 Value *NegX = B.CreateNeg(X, II->getName(), /*HasNUW=*/false,
478 /*HasNSW=*/IsIntMinPoison);
479 ++NumAbs;
480 II->replaceAllUsesWith(NegX);
481 II->eraseFromParent();
482
483 // See if we can infer some no-wrap flags.
484 if (auto *BO = dyn_cast<BinaryOperator>(NegX))
485 processBinOp(BO, LVI);
486
487 return true;
488 }
489
490 // Argument's range crosses zero.
491 // Can we at least tell that the argument is never INT_MIN?
492 if (!IsIntMinPoison && !Range.contains(IntMin)) {
493 ++NumNSW;
494 ++NumSubNSW;
496 return true;
497 }
498 return false;
499}
500
501// See if this min/max intrinsic always picks it's one specific operand.
505 Pred, MM->getLHS(), MM->getRHS(), MM, /*UseBlockValue=*/true);
506 if (Result == LazyValueInfo::Unknown)
507 return false;
508
509 ++NumMinMax;
510 MM->replaceAllUsesWith(MM->getOperand(!Result));
511 MM->eraseFromParent();
512 return true;
513}
514
515// Rewrite this with.overflow intrinsic as non-overflowing.
517 IRBuilder<> B(WO);
519 bool NSW = WO->isSigned();
520 bool NUW = !WO->isSigned();
521
522 Value *NewOp =
523 B.CreateBinOp(Opcode, WO->getLHS(), WO->getRHS(), WO->getName());
524 setDeducedOverflowingFlags(NewOp, Opcode, NSW, NUW);
525
526 StructType *ST = cast<StructType>(WO->getType());
528 { PoisonValue::get(ST->getElementType(0)),
529 ConstantInt::getFalse(ST->getElementType(1)) });
530 Value *NewI = B.CreateInsertValue(Struct, NewOp, 0);
531 WO->replaceAllUsesWith(NewI);
532 WO->eraseFromParent();
533 ++NumOverflows;
534
535 // See if we can infer the other no-wrap too.
536 if (auto *BO = dyn_cast<BinaryOperator>(NewOp))
537 processBinOp(BO, LVI);
538
539 return true;
540}
541
543 Instruction::BinaryOps Opcode = SI->getBinaryOp();
544 bool NSW = SI->isSigned();
545 bool NUW = !SI->isSigned();
547 Opcode, SI->getLHS(), SI->getRHS(), SI->getName(), SI);
548 BinOp->setDebugLoc(SI->getDebugLoc());
549 setDeducedOverflowingFlags(BinOp, Opcode, NSW, NUW);
550
551 SI->replaceAllUsesWith(BinOp);
552 SI->eraseFromParent();
553 ++NumSaturating;
554
555 // See if we can infer the other no-wrap too.
556 if (auto *BO = dyn_cast<BinaryOperator>(BinOp))
557 processBinOp(BO, LVI);
558
559 return true;
560}
561
562/// Infer nonnull attributes for the arguments at the specified callsite.
563static bool processCallSite(CallBase &CB, LazyValueInfo *LVI) {
564
565 if (CB.getIntrinsicID() == Intrinsic::abs) {
566 return processAbsIntrinsic(&cast<IntrinsicInst>(CB), LVI);
567 }
568
569 if (auto *MM = dyn_cast<MinMaxIntrinsic>(&CB)) {
570 return processMinMaxIntrinsic(MM, LVI);
571 }
572
573 if (auto *WO = dyn_cast<WithOverflowInst>(&CB)) {
574 if (WO->getLHS()->getType()->isIntegerTy() && willNotOverflow(WO, LVI)) {
575 return processOverflowIntrinsic(WO, LVI);
576 }
577 }
578
579 if (auto *SI = dyn_cast<SaturatingInst>(&CB)) {
580 if (SI->getType()->isIntegerTy() && willNotOverflow(SI, LVI)) {
581 return processSaturatingInst(SI, LVI);
582 }
583 }
584
585 bool Changed = false;
586
587 // Deopt bundle operands are intended to capture state with minimal
588 // perturbance of the code otherwise. If we can find a constant value for
589 // any such operand and remove a use of the original value, that's
590 // desireable since it may allow further optimization of that value (e.g. via
591 // single use rules in instcombine). Since deopt uses tend to,
592 // idiomatically, appear along rare conditional paths, it's reasonable likely
593 // we may have a conditional fact with which LVI can fold.
594 if (auto DeoptBundle = CB.getOperandBundle(LLVMContext::OB_deopt)) {
595 for (const Use &ConstU : DeoptBundle->Inputs) {
596 Use &U = const_cast<Use&>(ConstU);
597 Value *V = U.get();
598 if (V->getType()->isVectorTy()) continue;
599 if (isa<Constant>(V)) continue;
600
601 Constant *C = LVI->getConstant(V, &CB);
602 if (!C) continue;
603 U.set(C);
604 Changed = true;
605 }
606 }
607
609 unsigned ArgNo = 0;
610
611 for (Value *V : CB.args()) {
612 PointerType *Type = dyn_cast<PointerType>(V->getType());
613 // Try to mark pointer typed parameters as non-null. We skip the
614 // relatively expensive analysis for constants which are obviously either
615 // null or non-null to start with.
616 if (Type && !CB.paramHasAttr(ArgNo, Attribute::NonNull) &&
617 !isa<Constant>(V) &&
618 LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
620 /*UseBlockValue=*/false) == LazyValueInfo::False)
621 ArgNos.push_back(ArgNo);
622 ArgNo++;
623 }
624
625 assert(ArgNo == CB.arg_size() && "Call arguments not processed correctly.");
626
627 if (ArgNos.empty())
628 return Changed;
629
630 NumNonNull += ArgNos.size();
632 LLVMContext &Ctx = CB.getContext();
633 AS = AS.addParamAttribute(Ctx, ArgNos,
634 Attribute::get(Ctx, Attribute::NonNull));
635 CB.setAttributes(AS);
636
637 return true;
638}
639
641
642static Domain getDomain(const ConstantRange &CR) {
643 if (CR.isAllNonNegative())
644 return Domain::NonNegative;
645 if (CR.icmp(ICmpInst::ICMP_SLE, APInt::getZero(CR.getBitWidth())))
646 return Domain::NonPositive;
647 return Domain::Unknown;
648}
649
650/// Try to shrink a sdiv/srem's width down to the smallest power of two that's
651/// sufficient to contain its operands.
652static bool narrowSDivOrSRem(BinaryOperator *Instr, const ConstantRange &LCR,
653 const ConstantRange &RCR) {
654 assert(Instr->getOpcode() == Instruction::SDiv ||
655 Instr->getOpcode() == Instruction::SRem);
656 assert(!Instr->getType()->isVectorTy());
657
658 // Find the smallest power of two bitwidth that's sufficient to hold Instr's
659 // operands.
660 unsigned OrigWidth = Instr->getType()->getIntegerBitWidth();
661
662 // What is the smallest bit width that can accommodate the entire value ranges
663 // of both of the operands?
664 unsigned MinSignedBits =
665 std::max(LCR.getMinSignedBits(), RCR.getMinSignedBits());
666
667 // sdiv/srem is UB if divisor is -1 and divident is INT_MIN, so unless we can
668 // prove that such a combination is impossible, we need to bump the bitwidth.
669 if (RCR.contains(APInt::getAllOnes(OrigWidth)) &&
670 LCR.contains(APInt::getSignedMinValue(MinSignedBits).sext(OrigWidth)))
671 ++MinSignedBits;
672
673 // Don't shrink below 8 bits wide.
674 unsigned NewWidth = std::max<unsigned>(PowerOf2Ceil(MinSignedBits), 8);
675
676 // NewWidth might be greater than OrigWidth if OrigWidth is not a power of
677 // two.
678 if (NewWidth >= OrigWidth)
679 return false;
680
681 ++NumSDivSRemsNarrowed;
682 IRBuilder<> B{Instr};
683 auto *TruncTy = Type::getIntNTy(Instr->getContext(), NewWidth);
684 auto *LHS = B.CreateTruncOrBitCast(Instr->getOperand(0), TruncTy,
685 Instr->getName() + ".lhs.trunc");
686 auto *RHS = B.CreateTruncOrBitCast(Instr->getOperand(1), TruncTy,
687 Instr->getName() + ".rhs.trunc");
688 auto *BO = B.CreateBinOp(Instr->getOpcode(), LHS, RHS, Instr->getName());
689 auto *Sext = B.CreateSExt(BO, Instr->getType(), Instr->getName() + ".sext");
690 if (auto *BinOp = dyn_cast<BinaryOperator>(BO))
691 if (BinOp->getOpcode() == Instruction::SDiv)
692 BinOp->setIsExact(Instr->isExact());
693
694 Instr->replaceAllUsesWith(Sext);
695 Instr->eraseFromParent();
696 return true;
697}
698
699static bool expandUDivOrURem(BinaryOperator *Instr, const ConstantRange &XCR,
700 const ConstantRange &YCR) {
701 Type *Ty = Instr->getType();
702 assert(Instr->getOpcode() == Instruction::UDiv ||
703 Instr->getOpcode() == Instruction::URem);
704 assert(!Ty->isVectorTy());
705 bool IsRem = Instr->getOpcode() == Instruction::URem;
706
707 Value *X = Instr->getOperand(0);
708 Value *Y = Instr->getOperand(1);
709
710 // X u/ Y -> 0 iff X u< Y
711 // X u% Y -> X iff X u< Y
712 if (XCR.icmp(ICmpInst::ICMP_ULT, YCR)) {
713 Instr->replaceAllUsesWith(IsRem ? X : Constant::getNullValue(Ty));
714 Instr->eraseFromParent();
715 ++NumUDivURemsNarrowedExpanded;
716 return true;
717 }
718
719 // Given
720 // R = X u% Y
721 // We can represent the modulo operation as a loop/self-recursion:
722 // urem_rec(X, Y):
723 // Z = X - Y
724 // if X u< Y
725 // ret X
726 // else
727 // ret urem_rec(Z, Y)
728 // which isn't better, but if we only need a single iteration
729 // to compute the answer, this becomes quite good:
730 // R = X < Y ? X : X - Y iff X u< 2*Y (w/ unsigned saturation)
731 // Now, we do not care about all full multiples of Y in X, they do not change
732 // the answer, thus we could rewrite the expression as:
733 // X* = X - (Y * |_ X / Y _|)
734 // R = X* % Y
735 // so we don't need the *first* iteration to return, we just need to
736 // know *which* iteration will always return, so we could also rewrite it as:
737 // X* = X - (Y * |_ X / Y _|)
738 // R = X* % Y iff X* u< 2*Y (w/ unsigned saturation)
739 // but that does not seem profitable here.
740
741 // Even if we don't know X's range, the divisor may be so large, X can't ever
742 // be 2x larger than that. I.e. if divisor is always negative.
743 if (!XCR.icmp(ICmpInst::ICMP_ULT,
744 YCR.umul_sat(APInt(YCR.getBitWidth(), 2))) &&
745 !YCR.isAllNegative())
746 return false;
747
748 IRBuilder<> B(Instr);
749 Value *ExpandedOp;
750 if (XCR.icmp(ICmpInst::ICMP_UGE, YCR)) {
751 // If X is between Y and 2*Y the result is known.
752 if (IsRem)
753 ExpandedOp = B.CreateNUWSub(X, Y);
754 else
755 ExpandedOp = ConstantInt::get(Instr->getType(), 1);
756 } else if (IsRem) {
757 // NOTE: this transformation introduces two uses of X,
758 // but it may be undef so we must freeze it first.
759 Value *FrozenX = X;
761 FrozenX = B.CreateFreeze(X, X->getName() + ".frozen");
762 auto *AdjX = B.CreateNUWSub(FrozenX, Y, Instr->getName() + ".urem");
763 auto *Cmp =
764 B.CreateICmp(ICmpInst::ICMP_ULT, FrozenX, Y, Instr->getName() + ".cmp");
765 ExpandedOp = B.CreateSelect(Cmp, FrozenX, AdjX);
766 } else {
767 auto *Cmp =
768 B.CreateICmp(ICmpInst::ICMP_UGE, X, Y, Instr->getName() + ".cmp");
769 ExpandedOp = B.CreateZExt(Cmp, Ty, Instr->getName() + ".udiv");
770 }
771 ExpandedOp->takeName(Instr);
772 Instr->replaceAllUsesWith(ExpandedOp);
773 Instr->eraseFromParent();
774 ++NumUDivURemsNarrowedExpanded;
775 return true;
776}
777
778/// Try to shrink a udiv/urem's width down to the smallest power of two that's
779/// sufficient to contain its operands.
780static bool narrowUDivOrURem(BinaryOperator *Instr, const ConstantRange &XCR,
781 const ConstantRange &YCR) {
782 assert(Instr->getOpcode() == Instruction::UDiv ||
783 Instr->getOpcode() == Instruction::URem);
784 assert(!Instr->getType()->isVectorTy());
785
786 // Find the smallest power of two bitwidth that's sufficient to hold Instr's
787 // operands.
788
789 // What is the smallest bit width that can accommodate the entire value ranges
790 // of both of the operands?
791 unsigned MaxActiveBits = std::max(XCR.getActiveBits(), YCR.getActiveBits());
792 // Don't shrink below 8 bits wide.
793 unsigned NewWidth = std::max<unsigned>(PowerOf2Ceil(MaxActiveBits), 8);
794
795 // NewWidth might be greater than OrigWidth if OrigWidth is not a power of
796 // two.
797 if (NewWidth >= Instr->getType()->getIntegerBitWidth())
798 return false;
799
800 ++NumUDivURemsNarrowed;
801 IRBuilder<> B{Instr};
802 auto *TruncTy = Type::getIntNTy(Instr->getContext(), NewWidth);
803 auto *LHS = B.CreateTruncOrBitCast(Instr->getOperand(0), TruncTy,
804 Instr->getName() + ".lhs.trunc");
805 auto *RHS = B.CreateTruncOrBitCast(Instr->getOperand(1), TruncTy,
806 Instr->getName() + ".rhs.trunc");
807 auto *BO = B.CreateBinOp(Instr->getOpcode(), LHS, RHS, Instr->getName());
808 auto *Zext = B.CreateZExt(BO, Instr->getType(), Instr->getName() + ".zext");
809 if (auto *BinOp = dyn_cast<BinaryOperator>(BO))
810 if (BinOp->getOpcode() == Instruction::UDiv)
811 BinOp->setIsExact(Instr->isExact());
812
813 Instr->replaceAllUsesWith(Zext);
814 Instr->eraseFromParent();
815 return true;
816}
817
819 assert(Instr->getOpcode() == Instruction::UDiv ||
820 Instr->getOpcode() == Instruction::URem);
821 if (Instr->getType()->isVectorTy())
822 return false;
823
824 ConstantRange XCR = LVI->getConstantRangeAtUse(Instr->getOperandUse(0));
825 ConstantRange YCR = LVI->getConstantRangeAtUse(Instr->getOperandUse(1));
826 if (expandUDivOrURem(Instr, XCR, YCR))
827 return true;
828
829 return narrowUDivOrURem(Instr, XCR, YCR);
830}
831
832static bool processSRem(BinaryOperator *SDI, const ConstantRange &LCR,
833 const ConstantRange &RCR, LazyValueInfo *LVI) {
834 assert(SDI->getOpcode() == Instruction::SRem);
835 assert(!SDI->getType()->isVectorTy());
836
837 if (LCR.abs().icmp(CmpInst::ICMP_ULT, RCR.abs())) {
838 SDI->replaceAllUsesWith(SDI->getOperand(0));
839 SDI->eraseFromParent();
840 return true;
841 }
842
843 struct Operand {
844 Value *V;
845 Domain D;
846 };
847 std::array<Operand, 2> Ops = {{{SDI->getOperand(0), getDomain(LCR)},
848 {SDI->getOperand(1), getDomain(RCR)}}};
849 if (Ops[0].D == Domain::Unknown || Ops[1].D == Domain::Unknown)
850 return false;
851
852 // We know domains of both of the operands!
853 ++NumSRems;
854
855 // We need operands to be non-negative, so negate each one that isn't.
856 for (Operand &Op : Ops) {
857 if (Op.D == Domain::NonNegative)
858 continue;
859 auto *BO =
860 BinaryOperator::CreateNeg(Op.V, Op.V->getName() + ".nonneg", SDI);
861 BO->setDebugLoc(SDI->getDebugLoc());
862 Op.V = BO;
863 }
864
865 auto *URem =
866 BinaryOperator::CreateURem(Ops[0].V, Ops[1].V, SDI->getName(), SDI);
867 URem->setDebugLoc(SDI->getDebugLoc());
868
869 auto *Res = URem;
870
871 // If the divident was non-positive, we need to negate the result.
872 if (Ops[0].D == Domain::NonPositive) {
873 Res = BinaryOperator::CreateNeg(Res, Res->getName() + ".neg", SDI);
874 Res->setDebugLoc(SDI->getDebugLoc());
875 }
876
877 SDI->replaceAllUsesWith(Res);
878 SDI->eraseFromParent();
879
880 // Try to simplify our new urem.
881 processUDivOrURem(URem, LVI);
882
883 return true;
884}
885
886/// See if LazyValueInfo's ability to exploit edge conditions or range
887/// information is sufficient to prove the signs of both operands of this SDiv.
888/// If this is the case, replace the SDiv with a UDiv. Even for local
889/// conditions, this can sometimes prove conditions instcombine can't by
890/// exploiting range information.
891static bool processSDiv(BinaryOperator *SDI, const ConstantRange &LCR,
892 const ConstantRange &RCR, LazyValueInfo *LVI) {
893 assert(SDI->getOpcode() == Instruction::SDiv);
894 assert(!SDI->getType()->isVectorTy());
895
896 // Check whether the division folds to a constant.
897 ConstantRange DivCR = LCR.sdiv(RCR);
898 if (const APInt *Elem = DivCR.getSingleElement()) {
899 SDI->replaceAllUsesWith(ConstantInt::get(SDI->getType(), *Elem));
900 SDI->eraseFromParent();
901 return true;
902 }
903
904 struct Operand {
905 Value *V;
906 Domain D;
907 };
908 std::array<Operand, 2> Ops = {{{SDI->getOperand(0), getDomain(LCR)},
909 {SDI->getOperand(1), getDomain(RCR)}}};
910 if (Ops[0].D == Domain::Unknown || Ops[1].D == Domain::Unknown)
911 return false;
912
913 // We know domains of both of the operands!
914 ++NumSDivs;
915
916 // We need operands to be non-negative, so negate each one that isn't.
917 for (Operand &Op : Ops) {
918 if (Op.D == Domain::NonNegative)
919 continue;
920 auto *BO =
921 BinaryOperator::CreateNeg(Op.V, Op.V->getName() + ".nonneg", SDI);
922 BO->setDebugLoc(SDI->getDebugLoc());
923 Op.V = BO;
924 }
925
926 auto *UDiv =
927 BinaryOperator::CreateUDiv(Ops[0].V, Ops[1].V, SDI->getName(), SDI);
928 UDiv->setDebugLoc(SDI->getDebugLoc());
929 UDiv->setIsExact(SDI->isExact());
930
931 Value *Res = UDiv;
932
933 // If the operands had two different domains, we need to negate the result.
934 if (Ops[0].D != Ops[1].D)
935 Res = BinaryOperator::CreateNeg(Res, Res->getName() + ".neg", SDI);
936
937 SDI->replaceAllUsesWith(Res);
938 SDI->eraseFromParent();
939
940 // Try to simplify our new udiv.
941 processUDivOrURem(UDiv, LVI);
942
943 return true;
944}
945
947 assert(Instr->getOpcode() == Instruction::SDiv ||
948 Instr->getOpcode() == Instruction::SRem);
949 if (Instr->getType()->isVectorTy())
950 return false;
951
952 ConstantRange LCR = LVI->getConstantRangeAtUse(Instr->getOperandUse(0));
953 ConstantRange RCR = LVI->getConstantRangeAtUse(Instr->getOperandUse(1));
954 if (Instr->getOpcode() == Instruction::SDiv)
955 if (processSDiv(Instr, LCR, RCR, LVI))
956 return true;
957
958 if (Instr->getOpcode() == Instruction::SRem) {
959 if (processSRem(Instr, LCR, RCR, LVI))
960 return true;
961 }
962
963 return narrowSDivOrSRem(Instr, LCR, RCR);
964}
965
966static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI) {
967 if (SDI->getType()->isVectorTy())
968 return false;
969
970 ConstantRange LRange =
971 LVI->getConstantRangeAtUse(SDI->getOperandUse(0), /*UndefAllowed*/ false);
972 unsigned OrigWidth = SDI->getType()->getIntegerBitWidth();
973 ConstantRange NegOneOrZero =
974 ConstantRange(APInt(OrigWidth, (uint64_t)-1, true), APInt(OrigWidth, 1));
975 if (NegOneOrZero.contains(LRange)) {
976 // ashr of -1 or 0 never changes the value, so drop the whole instruction
977 ++NumAShrsRemoved;
978 SDI->replaceAllUsesWith(SDI->getOperand(0));
979 SDI->eraseFromParent();
980 return true;
981 }
982
983 if (!LRange.isAllNonNegative())
984 return false;
985
986 ++NumAShrsConverted;
987 auto *BO = BinaryOperator::CreateLShr(SDI->getOperand(0), SDI->getOperand(1),
988 "", SDI);
989 BO->takeName(SDI);
990 BO->setDebugLoc(SDI->getDebugLoc());
991 BO->setIsExact(SDI->isExact());
992 SDI->replaceAllUsesWith(BO);
993 SDI->eraseFromParent();
994
995 return true;
996}
997
998static bool processSExt(SExtInst *SDI, LazyValueInfo *LVI) {
999 if (SDI->getType()->isVectorTy())
1000 return false;
1001
1002 const Use &Base = SDI->getOperandUse(0);
1003 if (!LVI->getConstantRangeAtUse(Base, /*UndefAllowed*/ false)
1005 return false;
1006
1007 ++NumSExt;
1008 auto *ZExt = CastInst::CreateZExtOrBitCast(Base, SDI->getType(), "", SDI);
1009 ZExt->takeName(SDI);
1010 ZExt->setDebugLoc(SDI->getDebugLoc());
1011 ZExt->setNonNeg();
1012 SDI->replaceAllUsesWith(ZExt);
1013 SDI->eraseFromParent();
1014
1015 return true;
1016}
1017
1018static bool processZExt(ZExtInst *ZExt, LazyValueInfo *LVI) {
1019 if (ZExt->getType()->isVectorTy())
1020 return false;
1021
1022 if (ZExt->hasNonNeg())
1023 return false;
1024
1025 const Use &Base = ZExt->getOperandUse(0);
1026 if (!LVI->getConstantRangeAtUse(Base, /*UndefAllowed*/ false)
1028 return false;
1029
1030 ++NumZExt;
1031 ZExt->setNonNeg();
1032
1033 return true;
1034}
1035
1036static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI) {
1037 using OBO = OverflowingBinaryOperator;
1038
1039 if (BinOp->getType()->isVectorTy())
1040 return false;
1041
1042 bool NSW = BinOp->hasNoSignedWrap();
1043 bool NUW = BinOp->hasNoUnsignedWrap();
1044 if (NSW && NUW)
1045 return false;
1046
1048 Value *LHS = BinOp->getOperand(0);
1049 Value *RHS = BinOp->getOperand(1);
1050
1051 ConstantRange LRange = LVI->getConstantRange(LHS, BinOp);
1052 ConstantRange RRange = LVI->getConstantRange(RHS, BinOp);
1053
1054 bool Changed = false;
1055 bool NewNUW = false, NewNSW = false;
1056 if (!NUW) {
1058 Opcode, RRange, OBO::NoUnsignedWrap);
1059 NewNUW = NUWRange.contains(LRange);
1060 Changed |= NewNUW;
1061 }
1062 if (!NSW) {
1064 Opcode, RRange, OBO::NoSignedWrap);
1065 NewNSW = NSWRange.contains(LRange);
1066 Changed |= NewNSW;
1067 }
1068
1069 setDeducedOverflowingFlags(BinOp, Opcode, NewNSW, NewNUW);
1070
1071 return Changed;
1072}
1073
1074static bool processAnd(BinaryOperator *BinOp, LazyValueInfo *LVI) {
1075 if (BinOp->getType()->isVectorTy())
1076 return false;
1077
1078 // Pattern match (and lhs, C) where C includes a superset of bits which might
1079 // be set in lhs. This is a common truncation idiom created by instcombine.
1080 const Use &LHS = BinOp->getOperandUse(0);
1081 ConstantInt *RHS = dyn_cast<ConstantInt>(BinOp->getOperand(1));
1082 if (!RHS || !RHS->getValue().isMask())
1083 return false;
1084
1085 // We can only replace the AND with LHS based on range info if the range does
1086 // not include undef.
1087 ConstantRange LRange =
1088 LVI->getConstantRangeAtUse(LHS, /*UndefAllowed=*/false);
1089 if (!LRange.getUnsignedMax().ule(RHS->getValue()))
1090 return false;
1091
1092 BinOp->replaceAllUsesWith(LHS);
1093 BinOp->eraseFromParent();
1094 NumAnd++;
1095 return true;
1096}
1097
1098
1100 if (Constant *C = LVI->getConstant(V, At))
1101 return C;
1102
1103 // TODO: The following really should be sunk inside LVI's core algorithm, or
1104 // at least the outer shims around such.
1105 auto *C = dyn_cast<CmpInst>(V);
1106 if (!C) return nullptr;
1107
1108 Value *Op0 = C->getOperand(0);
1109 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
1110 if (!Op1) return nullptr;
1111
1113 C->getPredicate(), Op0, Op1, At, /*UseBlockValue=*/false);
1114 if (Result == LazyValueInfo::Unknown)
1115 return nullptr;
1116
1117 return (Result == LazyValueInfo::True) ?
1118 ConstantInt::getTrue(C->getContext()) :
1119 ConstantInt::getFalse(C->getContext());
1120}
1121
1123 const SimplifyQuery &SQ) {
1124 bool FnChanged = false;
1125 // Visiting in a pre-order depth-first traversal causes us to simplify early
1126 // blocks before querying later blocks (which require us to analyze early
1127 // blocks). Eagerly simplifying shallow blocks means there is strictly less
1128 // work to do for deep blocks. This also means we don't visit unreachable
1129 // blocks.
1130 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
1131 bool BBChanged = false;
1132 for (Instruction &II : llvm::make_early_inc_range(*BB)) {
1133 switch (II.getOpcode()) {
1134 case Instruction::Select:
1135 BBChanged |= processSelect(cast<SelectInst>(&II), LVI);
1136 break;
1137 case Instruction::PHI:
1138 BBChanged |= processPHI(cast<PHINode>(&II), LVI, DT, SQ);
1139 break;
1140 case Instruction::ICmp:
1141 case Instruction::FCmp:
1142 BBChanged |= processCmp(cast<CmpInst>(&II), LVI);
1143 break;
1144 case Instruction::Call:
1145 case Instruction::Invoke:
1146 BBChanged |= processCallSite(cast<CallBase>(II), LVI);
1147 break;
1148 case Instruction::SRem:
1149 case Instruction::SDiv:
1150 BBChanged |= processSDivOrSRem(cast<BinaryOperator>(&II), LVI);
1151 break;
1152 case Instruction::UDiv:
1153 case Instruction::URem:
1154 BBChanged |= processUDivOrURem(cast<BinaryOperator>(&II), LVI);
1155 break;
1156 case Instruction::AShr:
1157 BBChanged |= processAShr(cast<BinaryOperator>(&II), LVI);
1158 break;
1159 case Instruction::SExt:
1160 BBChanged |= processSExt(cast<SExtInst>(&II), LVI);
1161 break;
1162 case Instruction::ZExt:
1163 BBChanged |= processZExt(cast<ZExtInst>(&II), LVI);
1164 break;
1165 case Instruction::Add:
1166 case Instruction::Sub:
1167 case Instruction::Mul:
1168 case Instruction::Shl:
1169 BBChanged |= processBinOp(cast<BinaryOperator>(&II), LVI);
1170 break;
1171 case Instruction::And:
1172 BBChanged |= processAnd(cast<BinaryOperator>(&II), LVI);
1173 break;
1174 }
1175 }
1176
1177 Instruction *Term = BB->getTerminator();
1178 switch (Term->getOpcode()) {
1179 case Instruction::Switch:
1180 BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI, DT);
1181 break;
1182 case Instruction::Ret: {
1183 auto *RI = cast<ReturnInst>(Term);
1184 // Try to determine the return value if we can. This is mainly here to
1185 // simplify the writing of unit tests, but also helps to enable IPO by
1186 // constant folding the return values of callees.
1187 auto *RetVal = RI->getReturnValue();
1188 if (!RetVal) break; // handle "ret void"
1189 if (isa<Constant>(RetVal)) break; // nothing to do
1190 if (auto *C = getConstantAt(RetVal, RI, LVI)) {
1191 ++NumReturns;
1192 RI->replaceUsesOfWith(RetVal, C);
1193 BBChanged = true;
1194 }
1195 }
1196 }
1197
1198 FnChanged |= BBChanged;
1199 }
1200
1201 return FnChanged;
1202}
1203
1208
1209 bool Changed = runImpl(F, LVI, DT, getBestSimplifyQuery(AM, F));
1210
1212 if (!Changed) {
1214 } else {
1217 }
1218
1219 // Keeping LVI alive is expensive, both because it uses a lot of memory, and
1220 // because invalidating values in LVI is expensive. While CVP does preserve
1221 // LVI, we know that passes after JumpThreading+CVP will not need the result
1222 // of this analysis, so we forcefully discard it early.
1224 return PA;
1225}
This file contains the simple types necessary to represent the attributes associated with functions a...
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool processICmp(ICmpInst *Cmp, LazyValueInfo *LVI)
static bool processAnd(BinaryOperator *BinOp, LazyValueInfo *LVI)
static bool processOverflowIntrinsic(WithOverflowInst *WO, LazyValueInfo *LVI)
static bool processSDivOrSRem(BinaryOperator *Instr, LazyValueInfo *LVI)
static bool expandUDivOrURem(BinaryOperator *Instr, const ConstantRange &XCR, const ConstantRange &YCR)
static bool constantFoldCmp(CmpInst *Cmp, LazyValueInfo *LVI)
See if LazyValueInfo's ability to exploit edge conditions or range information is sufficient to prove...
static bool processSaturatingInst(SaturatingInst *SI, LazyValueInfo *LVI)
static Value * getValueOnEdge(LazyValueInfo *LVI, Value *Incoming, BasicBlock *From, BasicBlock *To, Instruction *CxtI)
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 bool willNotOverflow(BinaryOpIntrinsic *BO, LazyValueInfo *LVI)
static bool processSelect(SelectInst *S, LazyValueInfo *LVI)
static bool runImpl(Function &F, LazyValueInfo *LVI, DominatorTree *DT, const SimplifyQuery &SQ)
static void setDeducedOverflowingFlags(Value *V, Instruction::BinaryOps Opcode, bool NewNSW, bool NewNUW)
static bool processMinMaxIntrinsic(MinMaxIntrinsic *MM, LazyValueInfo *LVI)
static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI)
static bool simplifyCommonValuePhi(PHINode *P, LazyValueInfo *LVI, DominatorTree *DT)
Try to simplify a phi with constant incoming values that match the edge values of a non-constant valu...
static bool processSRem(BinaryOperator *SDI, const ConstantRange &LCR, const ConstantRange &RCR, LazyValueInfo *LVI)
static Domain getDomain(const ConstantRange &CR)
static bool processPHI(PHINode *P, LazyValueInfo *LVI, DominatorTree *DT, const SimplifyQuery &SQ)
static bool processUDivOrURem(BinaryOperator *Instr, LazyValueInfo *LVI)
@ NonNegative
@ NonPositive
static bool processSDiv(BinaryOperator *SDI, const ConstantRange &LCR, const ConstantRange &RCR, LazyValueInfo *LVI)
See if LazyValueInfo's ability to exploit edge conditions or range information is sufficient to prove...
static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI)
static cl::opt< bool > CanonicalizeICmpPredicatesToUnsigned("canonicalize-icmp-predicates-to-unsigned", cl::init(true), cl::Hidden, cl::desc("Enables canonicalization of signed relational predicates to " "unsigned (e.g. sgt => ugt)"))
static bool processZExt(ZExtInst *ZExt, LazyValueInfo *LVI)
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 bool processSExt(SExtInst *SDI, LazyValueInfo *LVI)
static bool processSwitch(SwitchInst *I, LazyValueInfo *LVI, DominatorTree *DT)
Simplify a switch instruction by removing cases which can never fire.
static Constant * getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI)
static bool processCmp(CmpInst *Cmp, LazyValueInfo *LVI)
static bool processAbsIntrinsic(IntrinsicInst *II, LazyValueInfo *LVI)
static bool processCallSite(CallBase &CB, LazyValueInfo *LVI)
Infer nonnull attributes for the arguments at the specified callsite.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool runImpl(Function &F, const TargetLowering &TLI)
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...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
#define P(N)
This header defines various interfaces for pass management in LLVM.
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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:167
@ Struct
Value * RHS
Value * LHS
static constexpr uint32_t Opcode
Definition: aarch32.h:200
Class for arbitrary precision integers.
Definition: APInt.h:76
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:212
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:197
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1122
APInt sext(unsigned width) const
Sign extend to a new width.
Definition: APInt.cpp:954
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:178
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:649
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:803
AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:573
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Definition: Attributes.cpp:92
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:546
This class represents an intrinsic that is based on a binary operation.
Value * getRHS() const
unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
bool isSigned() const
Whether the intrinsic is signed or unsigned.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
Value * getLHS() const
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition: InstrTypes.h:391
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1227
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Definition: InstrTypes.h:2091
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1530
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1394
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1399
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.
Definition: InstrTypes.h:1385
unsigned arg_size() const
Definition: InstrTypes.h:1392
AttributeList getAttributes() const
Return the parameter attributes for this call.
Definition: InstrTypes.h:1526
static CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:738
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:1095
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:748
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:773
@ ICMP_EQ
equal
Definition: InstrTypes.h:769
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:774
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition: InstrTypes.h:944
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:833
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:840
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1691
This class represents a range of values.
Definition: ConstantRange.h:47
unsigned getActiveBits() const
Compute the maximal number of active bits needed to represent every value in this range.
ConstantRange umul_sat(const ConstantRange &Other) const
Perform an unsigned saturating multiplication of two constant ranges.
static 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.
bool isAllNegative() const
Return true if all values in this range are negative.
bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other? NOTE: false does not mean that inverse pr...
ConstantRange abs(bool IntMinIsPoison=false) const
Calculate absolute value range.
bool isAllNonNegative() const
Return true if all values in this range are non-negative.
ConstantRange sdiv(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed division of a value in th...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static 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)...
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 Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1300
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:356
This class represents an Operation in the Expression.
void applyUpdatesPermissive(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:278
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:165
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:123
This instruction compares its operands according to the predicate given to the constructor.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2636
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:433
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:93
bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool hasNonNeg() const LLVM_READONLY
Determine whether the the nneg flag is set.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:430
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Analysis to compute lazy value information.
This pass computes, caches, and vends lazy value constraint information.
Definition: LazyValueInfo.h:31
ConstantRange getConstantRangeAtUse(const Use &U, bool UndefAllowed=true)
Return the ConstantRange constraint that is known to hold for the value at a specific use-site.
Tristate
This is used to return true/false/dunno results.
Definition: LazyValueInfo.h:64
Constant * getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value is known to be a constant on the specified edge.
Tristate getPredicateOnEdge(unsigned Pred, Value *V, Constant *C, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value comparison with a constant is known to be true or false on the ...
Tristate getPredicateAt(unsigned Pred, Value *V, Constant *C, Instruction *CxtI, bool UseBlockValue)
Determine whether the specified value comparison with a constant is known to be true or false at the ...
Constant * getConstant(Value *V, Instruction *CxtI)
Determine whether the specified value is known to be a constant at the specified instruction.
ConstantRange getConstantRange(Value *V, Instruction *CxtI, bool UndefAllowed=true)
Return the ConstantRange constraint that is known to hold for the specified value at the specified in...
This class represents min/max intrinsics.
Value * getLHS() const
Value * getRHS() const
static ICmpInst::Predicate getPredicate(Intrinsic::ID ID)
Returns the comparison predicate underlying the intrinsic.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition: Operator.h:75
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1743
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:172
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:178
void abandon()
Mark an analysis as abandoned.
Definition: PassManager.h:226
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:193
This class represents a sign extension of integer types.
Represents a saturating add/sub intrinsic.
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Class to represent struct types.
Definition: DerivedTypes.h:216
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
Multiway switch.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
const Use & getOperandUse(unsigned i) const
Definition: User.h:182
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
bool use_empty() const
Definition: Value.h:344
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
iterator_range< use_iterator > uses()
Definition: Value.h:376
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
Represents an op.with.overflow intrinsic.
This class represents zero extension of integer types.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:129
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:665
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition: MathExtras.h:361
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
iterator_range< df_iterator< T > > depth_first(const T &G)
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
const SimplifyQuery getBestSimplifyQuery(Pass &, Function &)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)