LLVM 23.0.0git
SCCPSolver.cpp
Go to the documentation of this file.
1//===- SCCPSolver.cpp - SCCP Utility --------------------------- *- C++ -*-===//
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// \file
10// This file implements the Sparse Conditional Constant Propagation (SCCP)
11// utility.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/SetVector.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/InstVisitor.h"
27#include "llvm/IR/NoFolder.h"
30#include "llvm/Support/Debug.h"
34#include <cassert>
35#include <utility>
36#include <vector>
37
38using namespace llvm;
39using namespace PatternMatch;
40
41#define DEBUG_TYPE "sccp"
42
43// The maximum number of range extensions allowed for operations requiring
44// widening.
45static const unsigned MaxNumRangeExtensions = 10;
46
47/// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
52
53namespace llvm {
54
56 return LV.isConstant() ||
58}
59
63
65 Constant *Const = getConstantOrNull(V);
66 if (!Const)
67 return false;
68 // Replacing `musttail` instructions with constant breaks `musttail` invariant
69 // unless the call itself can be removed.
70 // Calls with "clang.arc.attachedcall" implicitly use the return value and
71 // those uses cannot be updated with a constant.
73 if (CB && ((CB->isMustTailCall() && !wouldInstructionBeTriviallyDead(CB)) ||
76
77 // Don't zap returns of the callee
78 if (F)
80
81 LLVM_DEBUG(dbgs() << " Can\'t treat the result of call " << *CB
82 << " as a constant\n");
83 return false;
84 }
85
86 LLVM_DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
87
88 // Replaces all of the uses of a variable with uses of the constant.
89 V->replaceAllUsesWith(Const);
90 return true;
91}
92
93/// Helper for propagting !implicit.ref metadata from callee to caller before
94/// erasing a call instruction. This ensures that references to global objects
95/// (e.g., copyright strings) are preserved even when calls are optimized away.
97 Function *Callee = CB->getCalledFunction();
98 if (!Callee)
99 return;
100
101 if (!Callee->hasMetadata(LLVMContext::MD_implicit_ref))
102 return;
103
104 Function *Caller = CB->getParent()->getParent();
105 if (!Caller)
106 return;
107
109 Callee->getMetadata(LLVMContext::MD_implicit_ref, MDs);
110 for (MDNode *MD : MDs)
111 Caller->addMetadata(LLVMContext::MD_implicit_ref, *MD);
112}
113
114/// Helper for getting ranges from \p Solver. Instructions inserted during
115/// simplification are unavailable in the solver, so we return a full range for
116/// them.
118 const SmallPtrSetImpl<Value *> &InsertedValues) {
119 if (auto *Const = dyn_cast<Constant>(Op))
120 return Const->toConstantRange();
121 if (InsertedValues.contains(Op)) {
122 unsigned Bitwidth = Op->getType()->getScalarSizeInBits();
123 return ConstantRange::getFull(Bitwidth);
124 }
125 return Solver.getLatticeValueFor(Op).asConstantRange(Op->getType(),
126 /*UndefAllowed=*/false);
127}
128
129/// Try to use \p Inst's value range from \p Solver to infer the NUW flag.
130static bool refineInstruction(SCCPSolver &Solver,
131 const SmallPtrSetImpl<Value *> &InsertedValues,
132 Instruction &Inst) {
133 bool Changed = false;
134 auto GetRange = [&Solver, &InsertedValues](Value *Op) {
135 return getRange(Op, Solver, InsertedValues);
136 };
137
139 if (Inst.hasNoSignedWrap() && Inst.hasNoUnsignedWrap())
140 return false;
141
142 auto RangeA = GetRange(Inst.getOperand(0));
143 auto RangeB = GetRange(Inst.getOperand(1));
144 if (!Inst.hasNoUnsignedWrap()) {
146 Instruction::BinaryOps(Inst.getOpcode()), RangeB,
148 if (NUWRange.contains(RangeA)) {
150 Changed = true;
151 }
152 }
153 if (!Inst.hasNoSignedWrap()) {
155 Instruction::BinaryOps(Inst.getOpcode()), RangeB,
157 if (NSWRange.contains(RangeA)) {
158 Inst.setHasNoSignedWrap();
159 Changed = true;
160 }
161 }
162 } else if (isa<PossiblyNonNegInst>(Inst) && !Inst.hasNonNeg()) {
163 auto Range = GetRange(Inst.getOperand(0));
164 if (Range.isAllNonNegative()) {
165 Inst.setNonNeg();
166 Changed = true;
167 }
168 } else if (TruncInst *TI = dyn_cast<TruncInst>(&Inst)) {
169 if (TI->hasNoSignedWrap() && TI->hasNoUnsignedWrap())
170 return false;
171
172 auto Range = GetRange(Inst.getOperand(0));
173 uint64_t DestWidth = TI->getDestTy()->getScalarSizeInBits();
174 if (!TI->hasNoUnsignedWrap()) {
175 if (Range.getActiveBits() <= DestWidth) {
176 TI->setHasNoUnsignedWrap(true);
177 Changed = true;
178 }
179 }
180 if (!TI->hasNoSignedWrap()) {
181 if (Range.getMinSignedBits() <= DestWidth) {
182 TI->setHasNoSignedWrap(true);
183 Changed = true;
184 }
185 }
186 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst)) {
187 if (GEP->hasNoUnsignedWrap() || !GEP->hasNoUnsignedSignedWrap())
188 return false;
189
190 if (all_of(GEP->indices(),
191 [&](Value *V) { return GetRange(V).isAllNonNegative(); })) {
192 GEP->setNoWrapFlags(GEP->getNoWrapFlags() |
194 Changed = true;
195 }
196 }
197
198 return Changed;
199}
200
201/// Try to replace signed instructions with their unsigned equivalent.
202static bool replaceSignedInst(SCCPSolver &Solver,
203 SmallPtrSetImpl<Value *> &InsertedValues,
204 Instruction &Inst) {
205 // Determine if a signed value is known to be >= 0.
206 auto isNonNegative = [&Solver, &InsertedValues](Value *V) {
207 return getRange(V, Solver, InsertedValues).isAllNonNegative();
208 };
209
210 Instruction *NewInst = nullptr;
211 switch (Inst.getOpcode()) {
212 case Instruction::SIToFP:
213 case Instruction::SExt: {
214 // If the source value is not negative, this is a zext/uitofp.
215 Value *Op0 = Inst.getOperand(0);
216 if (!isNonNegative(Op0))
217 return false;
218 NewInst = CastInst::Create(Inst.getOpcode() == Instruction::SExt
219 ? Instruction::ZExt
220 : Instruction::UIToFP,
221 Op0, Inst.getType(), "", Inst.getIterator());
222 NewInst->setNonNeg();
223 break;
224 }
225 case Instruction::AShr: {
226 // If the shifted value is not negative, this is a logical shift right.
227 Value *Op0 = Inst.getOperand(0);
228 if (!isNonNegative(Op0))
229 return false;
230 NewInst = BinaryOperator::CreateLShr(Op0, Inst.getOperand(1), "", Inst.getIterator());
231 NewInst->setIsExact(Inst.isExact());
232 break;
233 }
234 case Instruction::SDiv:
235 case Instruction::SRem: {
236 // If both operands are not negative, this is the same as udiv/urem.
237 Value *Op0 = Inst.getOperand(0), *Op1 = Inst.getOperand(1);
238 if (!isNonNegative(Op0) || !isNonNegative(Op1))
239 return false;
240 auto NewOpcode = Inst.getOpcode() == Instruction::SDiv ? Instruction::UDiv
241 : Instruction::URem;
242 NewInst = BinaryOperator::Create(NewOpcode, Op0, Op1, "", Inst.getIterator());
243 if (Inst.getOpcode() == Instruction::SDiv)
244 NewInst->setIsExact(Inst.isExact());
245 break;
246 }
247 default:
248 return false;
249 }
250
251 // Wire up the new instruction and update state.
252 assert(NewInst && "Expected replacement instruction");
253 NewInst->takeName(&Inst);
254 InsertedValues.insert(NewInst);
255 Inst.replaceAllUsesWith(NewInst);
256 NewInst->setDebugLoc(Inst.getDebugLoc());
257 Solver.removeLatticeValueFor(&Inst);
258 Inst.eraseFromParent();
259 return true;
260}
261
262/// Try to use \p Inst's value range from \p Solver to simplify it.
264 SmallPtrSetImpl<Value *> &InsertedValues,
265 Instruction &Inst) {
266 auto GetRange = [&Solver, &InsertedValues](Value *Op) {
267 return getRange(Op, Solver, InsertedValues);
268 };
269
270 Value *X;
271 const APInt *RHSC;
272 // Remove masking operations.
273 if (match(&Inst, m_And(m_Value(X), m_LowBitMask(RHSC)))) {
274 ConstantRange LRange = GetRange(X);
275 if (LRange.getUnsignedMax().ule(*RHSC))
276 return X;
277 }
278
279 // Check if we can simplify [us]cmp(X, Y) to X - Y.
280 if (auto *Cmp = dyn_cast<CmpIntrinsic>(&Inst)) {
281 Value *LHS = Cmp->getOperand(0);
282 Value *RHS = Cmp->getOperand(1);
283 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
284 // Bail out on 1-bit comparisons.
285 if (BitWidth == 1)
286 return nullptr;
287 ConstantRange LRange = GetRange(LHS);
288 if (LRange.isSizeLargerThan(3))
289 return nullptr;
290 ConstantRange RRange = GetRange(RHS);
291 if (RRange.isSizeLargerThan(3))
292 return nullptr;
293 ConstantRange RHSLower = RRange.sub(APInt(BitWidth, 1));
294 ConstantRange RHSUpper = RRange.add(APInt(BitWidth, 1));
296 Cmp->isSigned() ? CmpInst::ICMP_SLE : CmpInst::ICMP_ULE;
297 if (!RHSLower.icmp(Pred, LRange) || !LRange.icmp(Pred, RHSUpper))
298 return nullptr;
299
300 IRBuilder<NoFolder> Builder(&Inst);
301 Value *Sub = Builder.CreateSub(LHS, RHS, Inst.getName(), /*HasNUW=*/false,
302 /*HasNSW=*/Cmp->isSigned());
303 InsertedValues.insert(Sub);
304 if (Sub->getType() != Inst.getType()) {
305 Sub = Builder.CreateSExtOrTrunc(Sub, Inst.getType());
306 InsertedValues.insert(Sub);
307 }
308 return Sub;
309 }
310
311 // Relax range checks.
312 if (auto *ICmp = dyn_cast<ICmpInst>(&Inst)) {
313 Value *X;
314 auto MatchTwoInstructionExactRangeCheck =
315 [&]() -> std::optional<ConstantRange> {
316 const APInt *RHSC;
317 if (!match(ICmp->getOperand(1), m_APInt(RHSC)))
318 return std::nullopt;
319
320 Value *LHS = ICmp->getOperand(0);
321 ICmpInst::Predicate Pred = ICmp->getPredicate();
322 const APInt *Offset;
324 return ConstantRange::makeExactICmpRegion(Pred, *RHSC).sub(*Offset);
325 // Match icmp eq/ne X & NegPow2, C
326 if (ICmp->isEquality()) {
327 const APInt *Mask;
328 if (match(LHS, m_OneUse(m_And(m_Value(X), m_NegatedPower2(Mask)))) &&
329 RHSC->countr_zero() >= Mask->countr_zero()) {
330 ConstantRange CR(*RHSC, *RHSC - *Mask);
331 return Pred == ICmpInst::ICMP_EQ ? CR : CR.inverse();
332 }
333 }
334 return std::nullopt;
335 };
336
337 if (auto CR = MatchTwoInstructionExactRangeCheck()) {
338 ConstantRange LRange = GetRange(X);
339 // Early exit if we know nothing about X.
340 if (LRange.isFullSet())
341 return nullptr;
342 auto ConvertCRToICmp =
343 [&](const std::optional<ConstantRange> &NewCR) -> Value * {
345 APInt RHS;
346 // Check if we can represent NewCR as an icmp predicate.
347 if (NewCR && NewCR->getEquivalentICmp(Pred, RHS)) {
348 IRBuilder<NoFolder> Builder(&Inst);
349 Value *NewICmp =
350 Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), RHS));
351 InsertedValues.insert(NewICmp);
352 return NewICmp;
353 }
354 return nullptr;
355 };
356 // We are allowed to refine the comparison to either true or false for out
357 // of range inputs.
358 // Here we refine the comparison to false, and check if we can narrow the
359 // range check to a simpler test.
360 if (auto *V = ConvertCRToICmp(CR->exactIntersectWith(LRange)))
361 return V;
362 // Here we refine the comparison to true, i.e. we relax the range check.
363 if (auto *V = ConvertCRToICmp(CR->exactUnionWith(LRange.inverse())))
364 return V;
365 }
366 }
367
368 return nullptr;
369}
370
372 SmallPtrSetImpl<Value *> &InsertedValues,
373 Statistic &InstRemovedStat,
374 Statistic &InstReplacedStat) {
375 bool MadeChanges = false;
376 for (Instruction &Inst : make_early_inc_range(BB)) {
377 if (Inst.getType()->isVoidTy())
378 continue;
379 if (tryToReplaceWithConstant(&Inst)) {
381 // Propagate !implicit.ref before erasing the call.
382 if (auto *CB = dyn_cast<CallBase>(&Inst))
384
385 Inst.eraseFromParent();
386 }
387
388 MadeChanges = true;
389 ++InstRemovedStat;
390 } else if (replaceSignedInst(*this, InsertedValues, Inst)) {
391 MadeChanges = true;
392 ++InstReplacedStat;
393 } else if (refineInstruction(*this, InsertedValues, Inst)) {
394 MadeChanges = true;
395 } else if (auto *V = simplifyInstruction(*this, InsertedValues, Inst)) {
396 Inst.replaceAllUsesWith(V);
397 Inst.eraseFromParent();
398 ++InstRemovedStat;
399 MadeChanges = true;
400 }
401 }
402 return MadeChanges;
403}
404
406 BasicBlock *&NewUnreachableBB) const {
407 SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors;
408 bool HasNonFeasibleEdges = false;
409 for (BasicBlock *Succ : successors(BB)) {
410 if (isEdgeFeasible(BB, Succ))
411 FeasibleSuccessors.insert(Succ);
412 else
413 HasNonFeasibleEdges = true;
414 }
415
416 // All edges feasible, nothing to do.
417 if (!HasNonFeasibleEdges)
418 return false;
419
420 // SCCP can only determine non-feasible edges for br, switch and indirectbr.
421 Instruction *TI = BB->getTerminator();
423 "Terminator must be a br, switch or indirectbr");
424
425 if (FeasibleSuccessors.size() == 0) {
426 // Branch on undef/poison, replace with unreachable.
429 for (BasicBlock *Succ : successors(BB)) {
430 Succ->removePredecessor(BB);
431 if (SeenSuccs.insert(Succ).second)
432 Updates.push_back({DominatorTree::Delete, BB, Succ});
433 }
434 TI->eraseFromParent();
435 new UnreachableInst(BB->getContext(), BB);
436 DTU.applyUpdatesPermissive(Updates);
437 } else if (FeasibleSuccessors.size() == 1) {
438 // Replace with an unconditional branch to the only feasible successor.
439 BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin();
441 bool HaveSeenOnlyFeasibleSuccessor = false;
442 for (BasicBlock *Succ : successors(BB)) {
443 if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) {
444 // Don't remove the edge to the only feasible successor the first time
445 // we see it. We still do need to remove any multi-edges to it though.
446 HaveSeenOnlyFeasibleSuccessor = true;
447 continue;
448 }
449
450 Succ->removePredecessor(BB);
451 Updates.push_back({DominatorTree::Delete, BB, Succ});
452 }
453
454 Instruction *BI = UncondBrInst::Create(OnlyFeasibleSuccessor, BB);
455 BI->setDebugLoc(TI->getDebugLoc());
456 TI->eraseFromParent();
457 DTU.applyUpdatesPermissive(Updates);
458 } else if (FeasibleSuccessors.size() > 1) {
461
462 // If the default destination is unfeasible it will never be taken. Replace
463 // it with a new block with a single Unreachable instruction.
464 BasicBlock *DefaultDest = SI->getDefaultDest();
465 if (!FeasibleSuccessors.contains(DefaultDest)) {
466 if (!NewUnreachableBB) {
467 NewUnreachableBB =
468 BasicBlock::Create(DefaultDest->getContext(), "default.unreachable",
469 DefaultDest->getParent(), DefaultDest);
470 auto *UI =
471 new UnreachableInst(DefaultDest->getContext(), NewUnreachableBB);
472 UI->setDebugLoc(DebugLoc::getTemporary());
473 }
474
475 DefaultDest->removePredecessor(BB);
476 SI->setDefaultDest(NewUnreachableBB);
477 Updates.push_back({DominatorTree::Delete, BB, DefaultDest});
478 Updates.push_back({DominatorTree::Insert, BB, NewUnreachableBB});
479 }
480
481 for (auto CI = SI->case_begin(); CI != SI->case_end();) {
482 if (FeasibleSuccessors.contains(CI->getCaseSuccessor())) {
483 ++CI;
484 continue;
485 }
486
487 BasicBlock *Succ = CI->getCaseSuccessor();
488 Succ->removePredecessor(BB);
489 Updates.push_back({DominatorTree::Delete, BB, Succ});
490 SI.removeCase(CI);
491 // Don't increment CI, as we removed a case.
492 }
493
494 DTU.applyUpdatesPermissive(Updates);
495 } else {
496 llvm_unreachable("Must have at least one feasible successor");
497 }
498 return true;
499}
500
501static void inferAttribute(Function *F, unsigned AttrIndex,
502 const ValueLatticeElement &Val) {
503 // If there is a known constant range for the value, add range attribute.
504 if (Val.isConstantRange() && !Val.getConstantRange().isSingleElement()) {
505 // Do not add range attribute if the value may include undef.
507 return;
508
509 // Take the intersection of the existing attribute and the inferred range.
510 Attribute OldAttr = F->getAttributeAtIndex(AttrIndex, Attribute::Range);
512 if (OldAttr.isValid())
513 CR = CR.intersectWith(OldAttr.getRange());
514 F->addAttributeAtIndex(
515 AttrIndex, Attribute::get(F->getContext(), Attribute::Range, CR));
516 return;
517 }
518 // Infer nonnull attribute.
519 if (Val.isNotConstant() && Val.getNotConstant()->getType()->isPointerTy() &&
520 Val.getNotConstant()->isNullValue() &&
521 !F->hasAttributeAtIndex(AttrIndex, Attribute::NonNull)) {
522 F->addAttributeAtIndex(AttrIndex,
523 Attribute::get(F->getContext(), Attribute::NonNull));
524 }
525}
526
528 for (const auto &[F, ReturnValue] : getTrackedRetVals())
529 inferAttribute(F, AttributeList::ReturnIndex, ReturnValue);
530}
531
534 if (!isBlockExecutable(&F->front()))
535 continue;
536 for (Argument &A : F->args())
537 if (!A.getType()->isStructTy())
538 inferAttribute(F, AttributeList::FirstArgIndex + A.getArgNo(),
540 }
541}
542
543/// Helper class for SCCPSolver. This implements the instruction visitor and
544/// holds all the state.
545class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> {
546 const DataLayout &DL;
547 std::function<const TargetLibraryInfo &(Function &)> GetTLI;
548 /// Basic blocks that are executable (but may not have been visited yet).
549 SmallPtrSet<BasicBlock *, 8> BBExecutable;
550 /// Basic blocks that are executable and have been visited at least once.
553 ValueState; // The state each value is in.
554
555 /// StructValueState - This maintains ValueState for values that have
556 /// StructType, for example for formal arguments, calls, insertelement, etc.
558
559 /// GlobalValue - If we are tracking any values for the contents of a global
560 /// variable, we keep a mapping from the constant accessor to the element of
561 /// the global, to the currently known value. If the value becomes
562 /// overdefined, it's entry is simply removed from this map.
564
565 /// TrackedRetVals - If we are tracking arguments into and the return
566 /// value out of a function, it will have an entry in this map, indicating
567 /// what the known return value for the function is.
569
570 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
571 /// that return multiple values.
573 TrackedMultipleRetVals;
574
575 /// The set of values whose lattice has been invalidated.
576 /// Populated by resetLatticeValueFor(), cleared after resolving undefs.
577 DenseSet<Value *> Invalidated;
578
579 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
580 /// represented here for efficient lookup.
581 SmallPtrSet<Function *, 16> MRVFunctionsTracked;
582
583 /// A list of functions whose return cannot be modified.
584 SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions;
585
586 /// TrackingIncomingArguments - This is the set of functions for whose
587 /// arguments we make optimistic assumptions about and try to prove as
588 /// constants.
589 SmallPtrSet<Function *, 16> TrackingIncomingArguments;
590
591 /// Worklist of instructions to re-visit. This only includes instructions
592 /// in blocks that have already been visited at least once.
594
595 /// Current instruction while visiting a block for the first time, used to
596 /// avoid unnecessary instruction worklist insertions. Null if an instruction
597 /// is visited outside a whole-block visitation.
598 Instruction *CurI = nullptr;
599
600 // The BasicBlock work list
602
603 /// KnownFeasibleEdges - Entries in this set are edges which have already had
604 /// PHI nodes retriggered.
605 using Edge = std::pair<BasicBlock *, BasicBlock *>;
606 DenseSet<Edge> KnownFeasibleEdges;
607
609
611
612 LLVMContext &Ctx;
613
614 BumpPtrAllocator PredicateInfoAllocator;
615
616private:
617 ConstantInt *getConstantInt(const ValueLatticeElement &IV, Type *Ty) const {
619 }
620
621 /// Push instruction \p I to the worklist.
622 void pushToWorkList(Instruction *I);
623
624 /// Push users of value \p V to the worklist.
625 void pushUsersToWorkList(Value *V);
626
627 /// Like pushUsersToWorkList(), but also prints a debug message with the
628 /// updated value.
629 void pushUsersToWorkListMsg(ValueLatticeElement &IV, Value *V);
630
631 // markConstant - Make a value be marked as "constant". If the value
632 // is not already a constant, add it to the instruction work list so that
633 // the users of the instruction are updated later.
634 bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C,
635 bool MayIncludeUndef = false);
636
637 bool markConstant(Value *V, Constant *C) {
638 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
639 return markConstant(ValueState[V], V, C);
640 }
641
642 bool markNotConstant(ValueLatticeElement &IV, Value *V, Constant *C);
643
644 bool markNotNull(ValueLatticeElement &IV, Value *V) {
645 return markNotConstant(IV, V, Constant::getNullValue(V->getType()));
646 }
647
648 /// markConstantRange - Mark the object as constant range with \p CR. If the
649 /// object is not a constant range with the range \p CR, add it to the
650 /// instruction work list so that the users of the instruction are updated
651 /// later.
652 bool markConstantRange(ValueLatticeElement &IV, Value *V,
653 const ConstantRange &CR);
654
655 // markOverdefined - Make a value be marked as "overdefined". If the
656 // value is not already overdefined, add it to the overdefined instruction
657 // work list so that the users of the instruction are updated later.
658 bool markOverdefined(ValueLatticeElement &IV, Value *V);
659
660 /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV
661 /// changes.
662 bool mergeInValue(ValueLatticeElement &IV, Value *V,
663 const ValueLatticeElement &MergeWithV,
665 /*MayIncludeUndef=*/false, /*CheckWiden=*/false});
666
667 /// getValueState - Return the ValueLatticeElement object that corresponds to
668 /// the value. This function handles the case when the value hasn't been seen
669 /// yet by properly seeding constants etc.
670 ValueLatticeElement &getValueState(Value *V) {
671 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
672
673 auto I = ValueState.try_emplace(V);
674 ValueLatticeElement &LV = I.first->second;
675
676 if (!I.second)
677 return LV; // Common case, already in the map.
678
679 if (auto *C = dyn_cast<Constant>(V))
680 LV.markConstant(C); // Constants are constant
681
682 // All others are unknown by default.
683 return LV;
684 }
685
686 /// getStructValueState - Return the ValueLatticeElement object that
687 /// corresponds to the value/field pair. This function handles the case when
688 /// the value hasn't been seen yet by properly seeding constants etc.
689 ValueLatticeElement &getStructValueState(Value *V, unsigned i) {
690 assert(V->getType()->isStructTy() && "Should use getValueState");
691 assert(i < cast<StructType>(V->getType())->getNumElements() &&
692 "Invalid element #");
693
694 auto I = StructValueState.insert(
695 std::make_pair(std::make_pair(V, i), ValueLatticeElement()));
696 ValueLatticeElement &LV = I.first->second;
697
698 if (!I.second)
699 return LV; // Common case, already in the map.
700
701 if (auto *C = dyn_cast<Constant>(V)) {
702 Constant *Elt = C->getAggregateElement(i);
703
704 if (!Elt)
705 LV.markOverdefined(); // Unknown sort of constant.
706 else
707 LV.markConstant(Elt); // Constants are constant.
708 }
709
710 // All others are underdefined by default.
711 return LV;
712 }
713
714 /// Traverse the use-def chain of \p Call, marking itself and its users as
715 /// "unknown" on the way.
716 void invalidate(CallBase *Call) {
718 ToInvalidate.push_back(Call);
719
720 while (!ToInvalidate.empty()) {
721 Instruction *Inst = ToInvalidate.pop_back_val();
722
723 if (!Invalidated.insert(Inst).second)
724 continue;
725
726 if (!BBExecutable.count(Inst->getParent()))
727 continue;
728
729 Value *V = nullptr;
730 // For return instructions we need to invalidate the tracked returns map.
731 // Anything else has its lattice in the value map.
732 if (auto *RetInst = dyn_cast<ReturnInst>(Inst)) {
733 Function *F = RetInst->getParent()->getParent();
734 if (auto It = TrackedRetVals.find(F); It != TrackedRetVals.end()) {
735 It->second = ValueLatticeElement();
736 V = F;
737 } else if (MRVFunctionsTracked.count(F)) {
738 auto *STy = cast<StructType>(F->getReturnType());
739 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
740 TrackedMultipleRetVals[{F, I}] = ValueLatticeElement();
741 V = F;
742 }
743 } else if (auto *STy = dyn_cast<StructType>(Inst->getType())) {
744 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
745 if (auto It = StructValueState.find({Inst, I});
746 It != StructValueState.end()) {
747 It->second = ValueLatticeElement();
748 V = Inst;
749 }
750 }
751 } else if (auto It = ValueState.find(Inst); It != ValueState.end()) {
752 It->second = ValueLatticeElement();
753 V = Inst;
754 }
755
756 if (V) {
757 LLVM_DEBUG(dbgs() << "Invalidated lattice for " << *V << "\n");
758
759 for (User *U : V->users())
760 if (auto *UI = dyn_cast<Instruction>(U))
761 ToInvalidate.push_back(UI);
762
763 auto It = AdditionalUsers.find(V);
764 if (It != AdditionalUsers.end())
765 for (User *U : It->second)
766 if (auto *UI = dyn_cast<Instruction>(U))
767 ToInvalidate.push_back(UI);
768 }
769 }
770 }
771
772 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
773 /// work list if it is not already executable.
774 bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest);
775
776 // getFeasibleSuccessors - Return a vector of booleans to indicate which
777 // successors are reachable from a given terminator instruction.
778 void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
779
780 // Add U as additional user of V.
781 void addAdditionalUser(Value *V, User *U) { AdditionalUsers[V].insert(U); }
782
783 void handlePredicate(Instruction *I, Value *CopyOf, const PredicateBase *PI);
784 void handleCallOverdefined(CallBase &CB);
785 void handleCallResult(CallBase &CB);
786 void handleCallArguments(CallBase &CB);
787 void handleExtractOfWithOverflow(ExtractValueInst &EVI,
788 const WithOverflowInst *WO, unsigned Idx);
789 bool isInstFullyOverDefined(Instruction &Inst);
790
791private:
792 friend class InstVisitor<SCCPInstVisitor>;
793
794 // visit implementations - Something changed in this instruction. Either an
795 // operand made a transition, or the instruction is newly executable. Change
796 // the value type of I to reflect these changes if appropriate.
797 void visitPHINode(PHINode &I);
798
799 // Terminators
800
801 void visitReturnInst(ReturnInst &I);
802 void visitTerminator(Instruction &TI);
803
804 void visitCastInst(CastInst &I);
805 void visitSelectInst(SelectInst &I);
806 void visitUnaryOperator(Instruction &I);
807 void visitFreezeInst(FreezeInst &I);
808 void visitBinaryOperator(Instruction &I);
809 void visitCmpInst(CmpInst &I);
810 void visitExtractValueInst(ExtractValueInst &EVI);
811 void visitInsertValueInst(InsertValueInst &IVI);
812
813 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
814 markOverdefined(&CPI);
815 visitTerminator(CPI);
816 }
817
818 // Instructions that cannot be folded away.
819
820 void visitStoreInst(StoreInst &I);
821 void visitLoadInst(LoadInst &I);
822 void visitGetElementPtrInst(GetElementPtrInst &I);
823 void visitAllocaInst(AllocaInst &AI);
824
825 void visitInvokeInst(InvokeInst &II) {
826 visitCallBase(II);
827 visitTerminator(II);
828 }
829
830 void visitCallBrInst(CallBrInst &CBI) {
831 visitCallBase(CBI);
832 visitTerminator(CBI);
833 }
834
835 void visitCallBase(CallBase &CB);
836 void visitResumeInst(ResumeInst &I) { /*returns void*/
837 }
838 void visitUnreachableInst(UnreachableInst &I) { /*returns void*/
839 }
840 void visitFenceInst(FenceInst &I) { /*returns void*/
841 }
842
843 void visitInstruction(Instruction &I);
844
845public:
847 FnPredicateInfo.insert({&F, std::make_unique<PredicateInfo>(
848 F, DT, AC, PredicateInfoAllocator)});
849 }
850
852 auto It = FnPredicateInfo.find(&F);
853 if (It == FnPredicateInfo.end())
854 return;
855
856 for (BasicBlock &BB : F) {
857 for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
858 if (auto *BC = dyn_cast<BitCastInst>(&Inst)) {
859 if (BC->getType() == BC->getOperand(0)->getType()) {
860 if (It->second->getPredicateInfoFor(&Inst)) {
861 Value *Op = BC->getOperand(0);
862 Inst.replaceAllUsesWith(Op);
863 Inst.eraseFromParent();
864 }
865 }
866 }
867 }
868 }
869 }
870
871 void visitCallInst(CallInst &I) { visitCallBase(I); }
872
874
876 auto It = FnPredicateInfo.find(I->getParent()->getParent());
877 if (It == FnPredicateInfo.end())
878 return nullptr;
879 return It->second->getPredicateInfoFor(I);
880 }
881
883 std::function<const TargetLibraryInfo &(Function &)> GetTLI,
884 LLVMContext &Ctx)
885 : DL(DL), GetTLI(GetTLI), Ctx(Ctx) {}
886
888 // We only track the contents of scalar globals.
889 if (GV->getValueType()->isSingleValueType()) {
890 ValueLatticeElement &IV = TrackedGlobals[GV];
891 IV.markConstant(GV->getInitializer());
892 }
893 }
894
896 // Add an entry, F -> undef.
897 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
898 MRVFunctionsTracked.insert(F);
899 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
900 TrackedMultipleRetVals.try_emplace(std::make_pair(F, i));
901 } else if (!F->getReturnType()->isVoidTy())
902 TrackedRetVals.try_emplace(F);
903 }
904
906 MustPreserveReturnsInFunctions.insert(F);
907 }
908
910 return MustPreserveReturnsInFunctions.count(F);
911 }
912
914 TrackingIncomingArguments.insert(F);
915 }
916
918 return TrackingIncomingArguments.count(F);
919 }
920
922 return TrackingIncomingArguments;
923 }
924
925 void solve();
926
928
930
932 return BBExecutable.count(BB);
933 }
934
935 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const;
936
937 std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const {
938 std::vector<ValueLatticeElement> StructValues;
939 auto *STy = dyn_cast<StructType>(V->getType());
940 assert(STy && "getStructLatticeValueFor() can be called only on structs");
941 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
942 auto I = StructValueState.find(std::make_pair(V, i));
943 assert(I != StructValueState.end() && "Value not in valuemap!");
944 StructValues.push_back(I->second);
945 }
946 return StructValues;
947 }
948
949 void removeLatticeValueFor(Value *V) { ValueState.erase(V); }
950
951 /// Invalidate the Lattice Value of \p Call and its users after specializing
952 /// the call. Then recompute it.
954 // Calls to void returning functions do not need invalidation.
955 Function *F = Call->getCalledFunction();
956 (void)F;
957 assert(!F->getReturnType()->isVoidTy() &&
958 (TrackedRetVals.count(F) || MRVFunctionsTracked.count(F)) &&
959 "All non void specializations should be tracked");
960 invalidate(Call);
961 handleCallResult(*Call);
962 }
963
965 assert(!V->getType()->isStructTy() &&
966 "Should use getStructLatticeValueFor");
967 auto I = ValueState.find(V);
968 assert(I != ValueState.end() &&
969 "V not found in ValueState nor Paramstate map!");
970 return I->second;
971 }
972
974 return TrackedRetVals;
975 }
976
979 return TrackedGlobals;
980 }
981
983 return MRVFunctionsTracked;
984 }
985
987 if (auto *STy = dyn_cast<StructType>(V->getType()))
988 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
989 markOverdefined(getStructValueState(V, i), V);
990 else
991 markOverdefined(ValueState[V], V);
992 }
993
995 if (A->getType()->isIntOrIntVectorTy()) {
996 if (std::optional<ConstantRange> Range = A->getRange())
998 }
999 if (A->hasNonNullAttr())
1001 // Assume nothing about the incoming arguments without attributes.
1003 }
1004
1006 if (A->getType()->isStructTy())
1007 return (void)markOverdefined(A);
1008 mergeInValue(ValueState[A], A, getArgAttributeVL(A));
1009 }
1010
1012
1013 Constant *getConstant(const ValueLatticeElement &LV, Type *Ty) const;
1014
1015 Constant *getConstantOrNull(Value *V) const;
1016
1018 const SmallVectorImpl<ArgInfo> &Args);
1019
1021 for (auto &BB : *F)
1022 BBExecutable.erase(&BB);
1023 }
1024
1026 bool ResolvedUndefs = true;
1027 while (ResolvedUndefs) {
1028 solve();
1029 ResolvedUndefs = false;
1030 for (Function &F : M)
1031 ResolvedUndefs |= resolvedUndefsIn(F);
1032 }
1033 }
1034
1036 bool ResolvedUndefs = true;
1037 while (ResolvedUndefs) {
1038 solve();
1039 ResolvedUndefs = false;
1040 for (Function *F : WorkList)
1041 ResolvedUndefs |= resolvedUndefsIn(*F);
1042 }
1043 }
1044
1046 bool ResolvedUndefs = true;
1047 while (ResolvedUndefs) {
1048 solve();
1049 ResolvedUndefs = false;
1050 for (Value *V : Invalidated)
1051 if (auto *I = dyn_cast<Instruction>(V))
1052 ResolvedUndefs |= resolvedUndef(*I);
1053 }
1054 Invalidated.clear();
1055 }
1056};
1057
1058} // namespace llvm
1059
1061 if (!BBExecutable.insert(BB).second)
1062 return false;
1063 LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
1064 BBWorkList.push_back(BB); // Add the block to the work list!
1065 return true;
1066}
1067
1068void SCCPInstVisitor::pushToWorkList(Instruction *I) {
1069 // If we're currently visiting a block, do not push any instructions in the
1070 // same blocks that are after the current one, as they will be visited
1071 // anyway. We do have to push updates to earlier instructions (e.g. phi
1072 // nodes or loads of tracked globals).
1073 if (CurI && I->getParent() == CurI->getParent() && !I->comesBefore(CurI))
1074 return;
1075 // Only push instructions in already visited blocks. Otherwise we'll handle
1076 // it when we visit the block for the first time.
1077 if (BBVisited.contains(I->getParent()))
1078 InstWorkList.insert(I);
1079}
1080
1081void SCCPInstVisitor::pushUsersToWorkList(Value *V) {
1082 for (User *U : V->users())
1083 if (auto *UI = dyn_cast<Instruction>(U))
1084 pushToWorkList(UI);
1085
1086 auto Iter = AdditionalUsers.find(V);
1087 if (Iter != AdditionalUsers.end()) {
1088 // Copy additional users before notifying them of changes, because new
1089 // users may be added, potentially invalidating the iterator.
1091 for (User *U : Iter->second)
1092 if (auto *UI = dyn_cast<Instruction>(U))
1093 ToNotify.push_back(UI);
1094 for (Instruction *UI : ToNotify)
1095 pushToWorkList(UI);
1096 }
1097}
1098
1099void SCCPInstVisitor::pushUsersToWorkListMsg(ValueLatticeElement &IV,
1100 Value *V) {
1101 LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n');
1102 pushUsersToWorkList(V);
1103}
1104
1105bool SCCPInstVisitor::markConstant(ValueLatticeElement &IV, Value *V,
1106 Constant *C, bool MayIncludeUndef) {
1107 if (!IV.markConstant(C, MayIncludeUndef))
1108 return false;
1109 LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
1110 pushUsersToWorkList(V);
1111 return true;
1112}
1113
1114bool SCCPInstVisitor::markNotConstant(ValueLatticeElement &IV, Value *V,
1115 Constant *C) {
1116 if (!IV.markNotConstant(C))
1117 return false;
1118 LLVM_DEBUG(dbgs() << "markNotConstant: " << *C << ": " << *V << '\n');
1119 pushUsersToWorkList(V);
1120 return true;
1121}
1122
1123bool SCCPInstVisitor::markConstantRange(ValueLatticeElement &IV, Value *V,
1124 const ConstantRange &CR) {
1125 if (!IV.markConstantRange(CR))
1126 return false;
1127 LLVM_DEBUG(dbgs() << "markConstantRange: " << CR << ": " << *V << '\n');
1128 pushUsersToWorkList(V);
1129 return true;
1130}
1131
1132bool SCCPInstVisitor::markOverdefined(ValueLatticeElement &IV, Value *V) {
1133 if (!IV.markOverdefined())
1134 return false;
1135
1136 LLVM_DEBUG(dbgs() << "markOverdefined: ";
1137 if (auto *F = dyn_cast<Function>(V)) dbgs()
1138 << "Function '" << F->getName() << "'\n";
1139 else dbgs() << *V << '\n');
1140 // Only instructions go on the work list
1141 pushUsersToWorkList(V);
1142 return true;
1143}
1144
1146 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1147 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
1148 assert(It != TrackedMultipleRetVals.end());
1149 if (!SCCPSolver::isConstant(It->second))
1150 return false;
1151 }
1152 return true;
1153}
1154
1156 Type *Ty) const {
1157 if (LV.isConstant()) {
1158 Constant *C = LV.getConstant();
1159 assert(C->getType() == Ty && "Type mismatch");
1160 return C;
1161 }
1162
1163 if (LV.isConstantRange()) {
1164 const auto &CR = LV.getConstantRange();
1165 if (CR.getSingleElement())
1166 return ConstantInt::get(Ty, *CR.getSingleElement());
1167 }
1168 return nullptr;
1169}
1170
1172 Constant *Const = nullptr;
1173 if (V->getType()->isStructTy()) {
1174 std::vector<ValueLatticeElement> LVs = getStructLatticeValueFor(V);
1176 return nullptr;
1177 std::vector<Constant *> ConstVals;
1178 auto *ST = cast<StructType>(V->getType());
1179 for (unsigned I = 0, E = ST->getNumElements(); I != E; ++I) {
1180 const ValueLatticeElement &LV = LVs[I];
1181 ConstVals.push_back(SCCPSolver::isConstant(LV)
1182 ? getConstant(LV, ST->getElementType(I))
1183 : UndefValue::get(ST->getElementType(I)));
1184 }
1185 Const = ConstantStruct::get(ST, ConstVals);
1186 } else {
1189 return nullptr;
1190 Const = SCCPSolver::isConstant(LV) ? getConstant(LV, V->getType())
1191 : UndefValue::get(V->getType());
1192 }
1193 assert(Const && "Constant is nullptr here!");
1194 return Const;
1195}
1196
1198 const SmallVectorImpl<ArgInfo> &Args) {
1199 assert(!Args.empty() && "Specialization without arguments");
1200 assert(F->arg_size() == Args[0].Formal->getParent()->arg_size() &&
1201 "Functions should have the same number of arguments");
1202
1203 auto Iter = Args.begin();
1204 Function::arg_iterator NewArg = F->arg_begin();
1205 Function::arg_iterator OldArg = Args[0].Formal->getParent()->arg_begin();
1206 for (auto End = F->arg_end(); NewArg != End; ++NewArg, ++OldArg) {
1207
1208 LLVM_DEBUG(dbgs() << "SCCP: Marking argument "
1209 << NewArg->getNameOrAsOperand() << "\n");
1210
1211 // Mark the argument constants in the new function
1212 // or copy the lattice state over from the old function.
1213 if (Iter != Args.end() && Iter->Formal == &*OldArg) {
1214 if (auto *STy = dyn_cast<StructType>(NewArg->getType())) {
1215 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
1216 ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}];
1217 NewValue.markConstant(Iter->Actual->getAggregateElement(I));
1218 }
1219 } else {
1220 ValueState[&*NewArg].markConstant(Iter->Actual);
1221 }
1222 ++Iter;
1223 } else {
1224 if (auto *STy = dyn_cast<StructType>(NewArg->getType())) {
1225 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
1226 ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}];
1227 NewValue = StructValueState[{&*OldArg, I}];
1228 }
1229 } else {
1230 ValueLatticeElement &NewValue = ValueState[&*NewArg];
1231 NewValue = ValueState[&*OldArg];
1232 }
1233 }
1234 }
1235}
1236
1237void SCCPInstVisitor::visitInstruction(Instruction &I) {
1238 // All the instructions we don't do any special handling for just
1239 // go to overdefined.
1240 LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
1241 markOverdefined(&I);
1242}
1243
1244bool SCCPInstVisitor::mergeInValue(ValueLatticeElement &IV, Value *V,
1245 const ValueLatticeElement &MergeWithV,
1247 if (IV.mergeIn(MergeWithV, Opts)) {
1248 pushUsersToWorkList(V);
1249 LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : "
1250 << IV << "\n");
1251 return true;
1252 }
1253 return false;
1254}
1255
1256bool SCCPInstVisitor::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
1257 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
1258 return false; // This edge is already known to be executable!
1259
1260 if (!markBlockExecutable(Dest)) {
1261 // If the destination is already executable, we just made an *edge*
1262 // feasible that wasn't before. Revisit the PHI nodes in the block
1263 // because they have potentially new operands.
1264 LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
1265 << " -> " << Dest->getName() << '\n');
1266
1267 for (PHINode &PN : Dest->phis())
1268 pushToWorkList(&PN);
1269 }
1270 return true;
1271}
1272
1273// getFeasibleSuccessors - Return a vector of booleans to indicate which
1274// successors are reachable from a given terminator instruction.
1275void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI,
1276 SmallVectorImpl<bool> &Succs) {
1277 Succs.resize(TI.getNumSuccessors());
1278 if (isa<UncondBrInst>(TI)) {
1279 Succs[0] = true;
1280 return;
1281 }
1282
1283 if (auto *BI = dyn_cast<CondBrInst>(&TI)) {
1284 const ValueLatticeElement &BCValue = getValueState(BI->getCondition());
1285 ConstantInt *CI = getConstantInt(BCValue, BI->getCondition()->getType());
1286 if (!CI) {
1287 // Overdefined condition variables, and branches on unfoldable constant
1288 // conditions, mean the branch could go either way.
1289 if (!BCValue.isUnknownOrUndef())
1290 Succs[0] = Succs[1] = true;
1291 return;
1292 }
1293
1294 // Constant condition variables mean the branch can only go a single way.
1295 Succs[CI->isZero()] = true;
1296 return;
1297 }
1298
1299 // We cannot analyze special terminators, so consider all successors
1300 // executable.
1301 if (TI.isSpecialTerminator()) {
1302 Succs.assign(TI.getNumSuccessors(), true);
1303 return;
1304 }
1305
1306 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
1307 if (!SI->getNumCases()) {
1308 Succs[0] = true;
1309 return;
1310 }
1311 const ValueLatticeElement &SCValue = getValueState(SI->getCondition());
1312 if (ConstantInt *CI =
1313 getConstantInt(SCValue, SI->getCondition()->getType())) {
1314 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
1315 return;
1316 }
1317
1318 // TODO: Switch on undef is UB. Stop passing false once the rest of LLVM
1319 // is ready.
1320 if (SCValue.isConstantRange(/*UndefAllowed=*/false)) {
1321 const ConstantRange &Range = SCValue.getConstantRange();
1322 unsigned ReachableCaseCount = 0;
1323 for (const auto &Case : SI->cases()) {
1324 const APInt &CaseValue = Case.getCaseValue()->getValue();
1325 if (Range.contains(CaseValue)) {
1326 Succs[Case.getSuccessorIndex()] = true;
1327 ++ReachableCaseCount;
1328 }
1329 }
1330
1331 Succs[SI->case_default()->getSuccessorIndex()] =
1332 Range.isSizeLargerThan(ReachableCaseCount);
1333 return;
1334 }
1335
1336 // Overdefined or unknown condition? All destinations are executable!
1337 if (!SCValue.isUnknownOrUndef())
1338 Succs.assign(TI.getNumSuccessors(), true);
1339 return;
1340 }
1341
1342 // In case of indirect branch and its address is a blockaddress, we mark
1343 // the target as executable.
1344 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
1345 // Casts are folded by visitCastInst.
1346 const ValueLatticeElement &IBRValue = getValueState(IBR->getAddress());
1348 getConstant(IBRValue, IBR->getAddress()->getType()));
1349 if (!Addr) { // Overdefined or unknown condition?
1350 // All destinations are executable!
1351 if (!IBRValue.isUnknownOrUndef())
1352 Succs.assign(TI.getNumSuccessors(), true);
1353 return;
1354 }
1355
1356 BasicBlock *T = Addr->getBasicBlock();
1357 assert(Addr->getFunction() == T->getParent() &&
1358 "Block address of a different function ?");
1359 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
1360 // This is the target.
1361 if (IBR->getDestination(i) == T) {
1362 Succs[i] = true;
1363 return;
1364 }
1365 }
1366
1367 // If we didn't find our destination in the IBR successor list, then we
1368 // have undefined behavior. Its ok to assume no successor is executable.
1369 return;
1370 }
1371
1372 LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
1373 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
1374}
1375
1376// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
1377// block to the 'To' basic block is currently feasible.
1379 // Check if we've called markEdgeExecutable on the edge yet. (We could
1380 // be more aggressive and try to consider edges which haven't been marked
1381 // yet, but there isn't any need.)
1382 return KnownFeasibleEdges.count(Edge(From, To));
1383}
1384
1385// visit Implementations - Something changed in this instruction, either an
1386// operand made a transition, or the instruction is newly executable. Change
1387// the value type of I to reflect these changes if appropriate. This method
1388// makes sure to do the following actions:
1389//
1390// 1. If a phi node merges two constants in, and has conflicting value coming
1391// from different branches, or if the PHI node merges in an overdefined
1392// value, then the PHI node becomes overdefined.
1393// 2. If a phi node merges only constants in, and they all agree on value, the
1394// PHI node becomes a constant value equal to that.
1395// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
1396// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
1397// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
1398// 6. If a conditional branch has a value that is constant, make the selected
1399// destination executable
1400// 7. If a conditional branch has a value that is overdefined, make all
1401// successors executable.
1402void SCCPInstVisitor::visitPHINode(PHINode &PN) {
1403 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
1404 // and slow us down a lot. Just mark them overdefined.
1405 if (PN.getNumIncomingValues() > 64)
1406 return (void)markOverdefined(&PN);
1407
1408 if (isInstFullyOverDefined(PN))
1409 return;
1410 SmallVector<unsigned> FeasibleIncomingIndices;
1411 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1412 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
1413 continue;
1414 FeasibleIncomingIndices.push_back(i);
1415 }
1416
1417 // Look at all of the executable operands of the PHI node. If any of them
1418 // are overdefined, the PHI becomes overdefined as well. If they are all
1419 // constant, and they agree with each other, the PHI becomes the identical
1420 // constant. If they are constant and don't agree, the PHI is a constant
1421 // range. If there are no executable operands, the PHI remains unknown.
1422 if (StructType *STy = dyn_cast<StructType>(PN.getType())) {
1423 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1424 ValueLatticeElement PhiState = getStructValueState(&PN, i);
1425 if (PhiState.isOverdefined())
1426 continue;
1427 for (unsigned j : FeasibleIncomingIndices) {
1428 const ValueLatticeElement &IV =
1429 getStructValueState(PN.getIncomingValue(j), i);
1430 PhiState.mergeIn(IV);
1431 if (PhiState.isOverdefined())
1432 break;
1433 }
1434 ValueLatticeElement &PhiStateRef = getStructValueState(&PN, i);
1435 mergeInValue(PhiStateRef, &PN, PhiState,
1436 ValueLatticeElement::MergeOptions().setMaxWidenSteps(
1437 FeasibleIncomingIndices.size() + 1));
1438 PhiStateRef.setNumRangeExtensions(
1439 std::max((unsigned)FeasibleIncomingIndices.size(),
1440 PhiStateRef.getNumRangeExtensions()));
1441 }
1442 } else {
1443 ValueLatticeElement PhiState = getValueState(&PN);
1444 for (unsigned i : FeasibleIncomingIndices) {
1445 const ValueLatticeElement &IV = getValueState(PN.getIncomingValue(i));
1446 PhiState.mergeIn(IV);
1447 if (PhiState.isOverdefined())
1448 break;
1449 }
1450 // We allow up to 1 range extension per active incoming value and one
1451 // additional extension. Note that we manually adjust the number of range
1452 // extensions to match the number of active incoming values. This helps to
1453 // limit multiple extensions caused by the same incoming value, if other
1454 // incoming values are equal.
1455 ValueLatticeElement &PhiStateRef = ValueState[&PN];
1456 mergeInValue(PhiStateRef, &PN, PhiState,
1457 ValueLatticeElement::MergeOptions().setMaxWidenSteps(
1458 FeasibleIncomingIndices.size() + 1));
1459 PhiStateRef.setNumRangeExtensions(
1460 std::max((unsigned)FeasibleIncomingIndices.size(),
1461 PhiStateRef.getNumRangeExtensions()));
1462 }
1463}
1464
1465void SCCPInstVisitor::visitReturnInst(ReturnInst &I) {
1466 if (I.getNumOperands() == 0)
1467 return; // ret void
1468
1469 Function *F = I.getParent()->getParent();
1470 Value *ResultOp = I.getOperand(0);
1471
1472 // If we are tracking the return value of this function, merge it in.
1473 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
1474 auto TFRVI = TrackedRetVals.find(F);
1475 if (TFRVI != TrackedRetVals.end()) {
1476 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
1477 return;
1478 }
1479 }
1480
1481 // Handle functions that return multiple values.
1482 if (!TrackedMultipleRetVals.empty()) {
1483 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
1484 if (MRVFunctionsTracked.count(F))
1485 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1486 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
1487 getStructValueState(ResultOp, i));
1488 }
1489}
1490
1491void SCCPInstVisitor::visitTerminator(Instruction &TI) {
1492 SmallVector<bool, 16> SuccFeasible;
1493 getFeasibleSuccessors(TI, SuccFeasible);
1494
1495 BasicBlock *BB = TI.getParent();
1496
1497 // Mark all feasible successors executable.
1498 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
1499 if (SuccFeasible[i])
1500 markEdgeExecutable(BB, TI.getSuccessor(i));
1501}
1502
1503void SCCPInstVisitor::visitCastInst(CastInst &I) {
1504 // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1505 // discover a concrete value later.
1506 if (ValueState[&I].isOverdefined())
1507 return;
1508
1509 if (auto *BC = dyn_cast<BitCastInst>(&I)) {
1510 if (BC->getType() == BC->getOperand(0)->getType()) {
1511 if (const PredicateBase *PI = getPredicateInfoFor(&I)) {
1512 handlePredicate(&I, I.getOperand(0), PI);
1513 return;
1514 }
1515 }
1516 }
1517
1518 const ValueLatticeElement &OpSt = getValueState(I.getOperand(0));
1519 if (OpSt.isUnknownOrUndef())
1520 return;
1521
1522 if (Constant *OpC = getConstant(OpSt, I.getOperand(0)->getType())) {
1523 // Fold the constant as we build.
1524 if (Constant *C =
1525 ConstantFoldCastOperand(I.getOpcode(), OpC, I.getType(), DL)) {
1526 auto &LV = ValueState[&I];
1527 mergeInValue(LV, &I, ValueLatticeElement::get(C));
1528 return;
1529 }
1530 }
1531
1532 // Ignore bitcasts, as they may change the number of vector elements.
1533 if (I.getDestTy()->isIntOrIntVectorTy() &&
1534 I.getSrcTy()->isIntOrIntVectorTy() &&
1535 I.getOpcode() != Instruction::BitCast) {
1536 ConstantRange OpRange =
1537 OpSt.asConstantRange(I.getSrcTy(), /*UndefAllowed=*/false);
1538 auto &LV = getValueState(&I);
1539
1540 Type *DestTy = I.getDestTy();
1541 ConstantRange Res = ConstantRange::getEmpty(DestTy->getScalarSizeInBits());
1542 if (auto *Trunc = dyn_cast<TruncInst>(&I))
1543 Res = OpRange.truncate(DestTy->getScalarSizeInBits(),
1544 Trunc->getNoWrapKind());
1545 else
1546 Res = OpRange.castOp(I.getOpcode(), DestTy->getScalarSizeInBits());
1547 mergeInValue(LV, &I, ValueLatticeElement::getRange(Res));
1548 } else
1549 markOverdefined(&I);
1550}
1551
1552void SCCPInstVisitor::handleExtractOfWithOverflow(ExtractValueInst &EVI,
1553 const WithOverflowInst *WO,
1554 unsigned Idx) {
1555 Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
1556 Type *Ty = LHS->getType();
1557
1558 addAdditionalUser(LHS, &EVI);
1559 addAdditionalUser(RHS, &EVI);
1560
1561 const ValueLatticeElement &L = getValueState(LHS);
1562 if (L.isUnknownOrUndef())
1563 return; // Wait to resolve.
1564 ConstantRange LR = L.asConstantRange(Ty, /*UndefAllowed=*/false);
1565
1566 const ValueLatticeElement &R = getValueState(RHS);
1567 if (R.isUnknownOrUndef())
1568 return; // Wait to resolve.
1569
1570 ConstantRange RR = R.asConstantRange(Ty, /*UndefAllowed=*/false);
1571 if (Idx == 0) {
1572 ConstantRange Res = LR.binaryOp(WO->getBinaryOp(), RR);
1573 mergeInValue(ValueState[&EVI], &EVI, ValueLatticeElement::getRange(Res));
1574 } else {
1575 assert(Idx == 1 && "Index can only be 0 or 1");
1576 ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1577 WO->getBinaryOp(), RR, WO->getNoWrapKind());
1578 if (NWRegion.contains(LR))
1579 return (void)markConstant(&EVI, ConstantInt::getFalse(EVI.getType()));
1580 markOverdefined(&EVI);
1581 }
1582}
1583
1584void SCCPInstVisitor::visitExtractValueInst(ExtractValueInst &EVI) {
1585 // If this returns a struct, mark all elements over defined, we don't track
1586 // structs in structs.
1587 if (EVI.getType()->isStructTy())
1588 return (void)markOverdefined(&EVI);
1589
1590 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1591 // discover a concrete value later.
1592 if (ValueState[&EVI].isOverdefined())
1593 return (void)markOverdefined(&EVI);
1594
1595 // If this is extracting from more than one level of struct, we don't know.
1596 if (EVI.getNumIndices() != 1)
1597 return (void)markOverdefined(&EVI);
1598
1599 Value *AggVal = EVI.getAggregateOperand();
1600 if (AggVal->getType()->isStructTy()) {
1601 unsigned i = *EVI.idx_begin();
1602 if (auto *WO = dyn_cast<WithOverflowInst>(AggVal))
1603 return handleExtractOfWithOverflow(EVI, WO, i);
1604 ValueLatticeElement EltVal = getStructValueState(AggVal, i);
1605 mergeInValue(ValueState[&EVI], &EVI, EltVal);
1606 } else {
1607 // Otherwise, must be extracting from an array.
1608 return (void)markOverdefined(&EVI);
1609 }
1610}
1611
1612void SCCPInstVisitor::visitInsertValueInst(InsertValueInst &IVI) {
1613 auto *STy = dyn_cast<StructType>(IVI.getType());
1614 if (!STy)
1615 return (void)markOverdefined(&IVI);
1616
1617 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1618 // discover a concrete value later.
1619 if (ValueState[&IVI].isOverdefined())
1620 return (void)markOverdefined(&IVI);
1621
1622 // If this has more than one index, we can't handle it, drive all results to
1623 // undef.
1624 if (IVI.getNumIndices() != 1)
1625 return (void)markOverdefined(&IVI);
1626
1627 Value *Aggr = IVI.getAggregateOperand();
1628 unsigned Idx = *IVI.idx_begin();
1629
1630 // Compute the result based on what we're inserting.
1631 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1632 // This passes through all values that aren't the inserted element.
1633 if (i != Idx) {
1634 ValueLatticeElement EltVal = getStructValueState(Aggr, i);
1635 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
1636 continue;
1637 }
1638
1639 Value *Val = IVI.getInsertedValueOperand();
1640 if (Val->getType()->isStructTy())
1641 // We don't track structs in structs.
1642 markOverdefined(getStructValueState(&IVI, i), &IVI);
1643 else {
1644 ValueLatticeElement InVal = getValueState(Val);
1645 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
1646 }
1647 }
1648}
1649
1650void SCCPInstVisitor::visitSelectInst(SelectInst &I) {
1651 // If this select returns a struct, just mark the result overdefined.
1652 // TODO: We could do a lot better than this if code actually uses this.
1653 if (I.getType()->isStructTy())
1654 return (void)markOverdefined(&I);
1655
1656 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1657 // discover a concrete value later.
1658 if (ValueState[&I].isOverdefined())
1659 return (void)markOverdefined(&I);
1660
1661 const ValueLatticeElement &CondValue = getValueState(I.getCondition());
1662 if (CondValue.isUnknownOrUndef())
1663 return;
1664
1665 if (ConstantInt *CondCB =
1666 getConstantInt(CondValue, I.getCondition()->getType())) {
1667 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
1668 const ValueLatticeElement &OpValState = getValueState(OpVal);
1669 // Safety: ValueState[&I] doesn't invalidate OpValState since it is already
1670 // in the map.
1671 assert(ValueState.contains(&I) && "&I is not in ValueState map.");
1672 mergeInValue(ValueState[&I], &I, OpValState);
1673 return;
1674 }
1675
1676 // Otherwise, the condition is overdefined or a constant we can't evaluate.
1677 // See if we can produce something better than overdefined based on the T/F
1678 // value.
1679 ValueLatticeElement TVal = getValueState(I.getTrueValue());
1680 ValueLatticeElement FVal = getValueState(I.getFalseValue());
1681
1682 ValueLatticeElement &State = ValueState[&I];
1683 bool Changed = State.mergeIn(TVal);
1684 Changed |= State.mergeIn(FVal);
1685 if (Changed)
1686 pushUsersToWorkListMsg(State, &I);
1687}
1688
1689// Handle Unary Operators.
1690void SCCPInstVisitor::visitUnaryOperator(Instruction &I) {
1691 ValueLatticeElement V0State = getValueState(I.getOperand(0));
1692
1693 ValueLatticeElement &IV = ValueState[&I];
1694 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1695 // discover a concrete value later.
1696 if (IV.isOverdefined())
1697 return (void)markOverdefined(&I);
1698
1699 // If something is unknown/undef, wait for it to resolve.
1700 if (V0State.isUnknownOrUndef())
1701 return;
1702
1703 if (SCCPSolver::isConstant(V0State))
1704 if (Constant *C = ConstantFoldUnaryOpOperand(
1705 I.getOpcode(), getConstant(V0State, I.getType()), DL))
1706 return (void)markConstant(IV, &I, C);
1707
1708 markOverdefined(&I);
1709}
1710
1711void SCCPInstVisitor::visitFreezeInst(FreezeInst &I) {
1712 // If this freeze returns a struct, just mark the result overdefined.
1713 // TODO: We could do a lot better than this.
1714 if (I.getType()->isStructTy())
1715 return (void)markOverdefined(&I);
1716
1717 ValueLatticeElement V0State = getValueState(I.getOperand(0));
1718 ValueLatticeElement &IV = ValueState[&I];
1719 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1720 // discover a concrete value later.
1721 if (IV.isOverdefined())
1722 return (void)markOverdefined(&I);
1723
1724 // If something is unknown/undef, wait for it to resolve.
1725 if (V0State.isUnknownOrUndef())
1726 return;
1727
1728 if (SCCPSolver::isConstant(V0State) &&
1729 isGuaranteedNotToBeUndefOrPoison(getConstant(V0State, I.getType())))
1730 return (void)markConstant(IV, &I, getConstant(V0State, I.getType()));
1731
1732 markOverdefined(&I);
1733}
1734
1735// Handle Binary Operators.
1736void SCCPInstVisitor::visitBinaryOperator(Instruction &I) {
1737 ValueLatticeElement V1State = getValueState(I.getOperand(0));
1738 ValueLatticeElement V2State = getValueState(I.getOperand(1));
1739
1740 ValueLatticeElement &IV = ValueState[&I];
1741 if (IV.isOverdefined())
1742 return;
1743
1744 // If something is undef, wait for it to resolve.
1745 if (V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef())
1746 return;
1747
1748 if (V1State.isOverdefined() && V2State.isOverdefined())
1749 return (void)markOverdefined(&I);
1750
1751 // If either of the operands is a constant, try to fold it to a constant.
1752 // TODO: Use information from notconstant better.
1753 if ((V1State.isConstant() || V2State.isConstant())) {
1754 Value *V1 = SCCPSolver::isConstant(V1State)
1755 ? getConstant(V1State, I.getOperand(0)->getType())
1756 : I.getOperand(0);
1757 Value *V2 = SCCPSolver::isConstant(V2State)
1758 ? getConstant(V2State, I.getOperand(1)->getType())
1759 : I.getOperand(1);
1760 Value *R = simplifyBinOp(I.getOpcode(), V1, V2, SimplifyQuery(DL, &I));
1761 auto *C = dyn_cast_or_null<Constant>(R);
1762 if (C) {
1763 // Conservatively assume that the result may be based on operands that may
1764 // be undef. Note that we use mergeInValue to combine the constant with
1765 // the existing lattice value for I, as different constants might be found
1766 // after one of the operands go to overdefined, e.g. due to one operand
1767 // being a special floating value.
1768 ValueLatticeElement NewV;
1769 NewV.markConstant(C, /*MayIncludeUndef=*/true);
1770 return (void)mergeInValue(ValueState[&I], &I, NewV);
1771 }
1772 }
1773
1774 // Only use ranges for binary operators on integers.
1775 if (!I.getType()->isIntOrIntVectorTy())
1776 return markOverdefined(&I);
1777
1778 // Try to simplify to a constant range.
1779 ConstantRange A =
1780 V1State.asConstantRange(I.getType(), /*UndefAllowed=*/false);
1781 ConstantRange B =
1782 V2State.asConstantRange(I.getType(), /*UndefAllowed=*/false);
1783
1784 auto *BO = cast<BinaryOperator>(&I);
1785 ConstantRange R = ConstantRange::getEmpty(I.getType()->getScalarSizeInBits());
1786 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO))
1787 R = A.overflowingBinaryOp(BO->getOpcode(), B, OBO->getNoWrapKind());
1788 else
1789 R = A.binaryOp(BO->getOpcode(), B);
1790 mergeInValue(ValueState[&I], &I, ValueLatticeElement::getRange(R));
1791
1792 // TODO: Currently we do not exploit special values that produce something
1793 // better than overdefined with an overdefined operand for vector or floating
1794 // point types, like and <4 x i32> overdefined, zeroinitializer.
1795}
1796
1797// Handle ICmpInst instruction.
1798void SCCPInstVisitor::visitCmpInst(CmpInst &I) {
1799 // Do not cache this lookup, getValueState calls later in the function might
1800 // invalidate the reference.
1801 if (ValueState[&I].isOverdefined())
1802 return (void)markOverdefined(&I);
1803
1804 Value *Op1 = I.getOperand(0);
1805 Value *Op2 = I.getOperand(1);
1806
1807 // For parameters, use ParamState which includes constant range info if
1808 // available.
1809 auto V1State = getValueState(Op1);
1810 auto V2State = getValueState(Op2);
1811
1812 Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State, DL);
1813 if (C) {
1814 ValueLatticeElement CV;
1815 CV.markConstant(C);
1816 mergeInValue(ValueState[&I], &I, CV);
1817 return;
1818 }
1819
1820 // If operands are still unknown, wait for it to resolve.
1821 if ((V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) &&
1822 !SCCPSolver::isConstant(ValueState[&I]))
1823 return;
1824
1825 markOverdefined(&I);
1826}
1827
1828// Handle getelementptr instructions. If all operands are constants then we
1829// can turn this into a getelementptr ConstantExpr.
1830void SCCPInstVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
1831 if (ValueState[&I].isOverdefined())
1832 return (void)markOverdefined(&I);
1833
1834 const ValueLatticeElement &PtrState = getValueState(I.getPointerOperand());
1835 if (PtrState.isUnknownOrUndef())
1836 return;
1837
1838 // gep inbounds/nuw of non-null is non-null.
1839 if (PtrState.isNotConstant() && PtrState.getNotConstant()->isNullValue()) {
1840 if (I.hasNoUnsignedWrap() ||
1841 (I.isInBounds() &&
1842 !NullPointerIsDefined(I.getFunction(), I.getAddressSpace())))
1843 return (void)markNotNull(ValueState[&I], &I);
1844 return (void)markOverdefined(&I);
1845 }
1846
1848 Operands.reserve(I.getNumOperands());
1849
1850 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1851 const ValueLatticeElement &State = getValueState(I.getOperand(i));
1852 if (State.isUnknownOrUndef())
1853 return; // Operands are not resolved yet.
1854
1855 if (Constant *C = getConstant(State, I.getOperand(i)->getType())) {
1856 Operands.push_back(C);
1857 continue;
1858 }
1859
1860 return (void)markOverdefined(&I);
1861 }
1862
1863 if (Constant *C = ConstantFoldInstOperands(&I, Operands, DL))
1864 markConstant(&I, C);
1865 else
1866 markOverdefined(&I);
1867}
1868
1869void SCCPInstVisitor::visitAllocaInst(AllocaInst &I) {
1870 if (!NullPointerIsDefined(I.getFunction(), I.getAddressSpace()))
1871 return (void)markNotNull(ValueState[&I], &I);
1872
1873 markOverdefined(&I);
1874}
1875
1876void SCCPInstVisitor::visitStoreInst(StoreInst &SI) {
1877 // If this store is of a struct, ignore it.
1878 if (SI.getOperand(0)->getType()->isStructTy())
1879 return;
1880
1881 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1882 return;
1883
1884 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1885 auto I = TrackedGlobals.find(GV);
1886 if (I == TrackedGlobals.end())
1887 return;
1888
1889 // Get the value we are storing into the global, then merge it.
1890 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)),
1891 ValueLatticeElement::MergeOptions().setCheckWiden(false));
1892 if (I->second.isOverdefined())
1893 TrackedGlobals.erase(I); // No need to keep tracking this!
1894}
1895
1897 if (const auto *CB = dyn_cast<CallBase>(I)) {
1898 if (CB->getType()->isIntOrIntVectorTy())
1899 if (std::optional<ConstantRange> Range = CB->getRange())
1901 if (CB->getType()->isPointerTy() && CB->isReturnNonNull())
1904 }
1905
1906 if (I->getType()->isIntOrIntVectorTy())
1907 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range))
1910 if (I->hasMetadata(LLVMContext::MD_nonnull))
1913
1915}
1916
1917// Handle load instructions. If the operand is a constant pointer to a constant
1918// global, we can replace the load with the loaded constant value!
1919void SCCPInstVisitor::visitLoadInst(LoadInst &I) {
1920 // If this load is of a struct or the load is volatile, just mark the result
1921 // as overdefined.
1922 if (I.getType()->isStructTy() || I.isVolatile())
1923 return (void)markOverdefined(&I);
1924
1925 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1926 // discover a concrete value later.
1927 if (ValueState[&I].isOverdefined())
1928 return (void)markOverdefined(&I);
1929
1930 const ValueLatticeElement &PtrVal = getValueState(I.getOperand(0));
1931 if (PtrVal.isUnknownOrUndef())
1932 return; // The pointer is not resolved yet!
1933
1934 if (SCCPSolver::isConstant(PtrVal)) {
1935 Constant *Ptr = getConstant(PtrVal, I.getOperand(0)->getType());
1936 ValueLatticeElement &IV = ValueState[&I];
1937
1938 // load null is undefined.
1939 if (isa<ConstantPointerNull>(Ptr)) {
1940 if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1941 return (void)markOverdefined(IV, &I);
1942 else
1943 return;
1944 }
1945
1946 // Transform load (constant global) into the value loaded.
1947 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1948 if (!TrackedGlobals.empty()) {
1949 // If we are tracking this global, merge in the known value for it.
1950 auto It = TrackedGlobals.find(GV);
1951 if (It != TrackedGlobals.end()) {
1952 mergeInValue(IV, &I, It->second, getMaxWidenStepsOpts());
1953 return;
1954 }
1955 }
1956 }
1957
1958 // Transform load from a constant into a constant if possible.
1959 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL))
1960 return (void)markConstant(IV, &I, C);
1961 }
1962
1963 // Fall back to metadata.
1964 mergeInValue(ValueState[&I], &I, getValueFromMetadata(&I));
1965}
1966
1967void SCCPInstVisitor::visitCallBase(CallBase &CB) {
1968 handleCallResult(CB);
1969 handleCallArguments(CB);
1970}
1971
1972void SCCPInstVisitor::handleCallOverdefined(CallBase &CB) {
1974
1975 // Void return and not tracking callee, just bail.
1976 if (CB.getType()->isVoidTy())
1977 return;
1978
1979 // Always mark struct return as overdefined.
1980 if (CB.getType()->isStructTy())
1981 return (void)markOverdefined(&CB);
1982
1983 // Otherwise, if we have a single return value case, and if the function is
1984 // a declaration, maybe we can constant fold it.
1985 if (F && F->isDeclaration() && canConstantFoldCallTo(&CB, F)) {
1987 for (const Use &A : CB.args()) {
1988 if (A.get()->getType()->isStructTy())
1989 return markOverdefined(&CB); // Can't handle struct args.
1990 if (A.get()->getType()->isMetadataTy())
1991 continue; // Carried in CB, not allowed in Operands.
1992 const ValueLatticeElement &State = getValueState(A);
1993
1994 if (State.isUnknownOrUndef())
1995 return; // Operands are not resolved yet.
1996 if (SCCPSolver::isOverdefined(State))
1997 return (void)markOverdefined(&CB);
1998 assert(SCCPSolver::isConstant(State) && "Unknown state!");
1999 Operands.push_back(getConstant(State, A->getType()));
2000 }
2001
2002 if (SCCPSolver::isOverdefined(getValueState(&CB)))
2003 return (void)markOverdefined(&CB);
2004
2005 // If we can constant fold this, mark the result of the call as a
2006 // constant.
2007 if (Constant *C = ConstantFoldCall(&CB, F, Operands, &GetTLI(*F)))
2008 return (void)markConstant(&CB, C);
2009 }
2010
2011 // Fall back to metadata.
2012 mergeInValue(ValueState[&CB], &CB, getValueFromMetadata(&CB));
2013}
2014
2015void SCCPInstVisitor::handleCallArguments(CallBase &CB) {
2017 // If this is a local function that doesn't have its address taken, mark its
2018 // entry block executable and merge in the actual arguments to the call into
2019 // the formal arguments of the function.
2020 if (TrackingIncomingArguments.count(F)) {
2021 markBlockExecutable(&F->front());
2022
2023 // Propagate information from this call site into the callee.
2024 auto CAI = CB.arg_begin();
2025 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2026 ++AI, ++CAI) {
2027 // If this argument is byval, and if the function is not readonly, there
2028 // will be an implicit copy formed of the input aggregate.
2029 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
2030 markOverdefined(&*AI);
2031 continue;
2032 }
2033
2034 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
2035 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2036 ValueLatticeElement CallArg = getStructValueState(*CAI, i);
2037 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg,
2039 }
2040 } else {
2041 ValueLatticeElement CallArg =
2042 getValueState(*CAI).intersect(getArgAttributeVL(&*AI));
2043 mergeInValue(ValueState[&*AI], &*AI, CallArg, getMaxWidenStepsOpts());
2044 }
2045 }
2046 }
2047}
2048
2049void SCCPInstVisitor::handlePredicate(Instruction *I, Value *CopyOf,
2050 const PredicateBase *PI) {
2051 ValueLatticeElement CopyOfVal = getValueState(CopyOf);
2052 const std::optional<PredicateConstraint> &Constraint = PI->getConstraint();
2053 if (!Constraint) {
2054 mergeInValue(ValueState[I], I, CopyOfVal);
2055 return;
2056 }
2057
2058 CmpInst::Predicate Pred = Constraint->Predicate;
2059 Value *OtherOp = Constraint->OtherOp;
2060
2061 // Wait until OtherOp is resolved.
2062 if (getValueState(OtherOp).isUnknown()) {
2063 addAdditionalUser(OtherOp, I);
2064 return;
2065 }
2066
2067 ValueLatticeElement CondVal = getValueState(OtherOp);
2068 ValueLatticeElement &IV = ValueState[I];
2069 if (CondVal.isConstantRange() || CopyOfVal.isConstantRange()) {
2070 auto ImposedCR =
2071 ConstantRange::getFull(DL.getTypeSizeInBits(CopyOf->getType()));
2072
2073 // Get the range imposed by the condition.
2074 if (CondVal.isConstantRange())
2076 Pred, CondVal.getConstantRange());
2077
2078 // Combine range info for the original value with the new range from the
2079 // condition.
2080 auto CopyOfCR = CopyOfVal.asConstantRange(CopyOf->getType(),
2081 /*UndefAllowed=*/true);
2082 // Treat an unresolved input like a full range.
2083 if (CopyOfCR.isEmptySet())
2084 CopyOfCR = ConstantRange::getFull(CopyOfCR.getBitWidth());
2085 auto NewCR = ImposedCR.intersectWith(CopyOfCR);
2086 // If the existing information is != x, do not use the information from
2087 // a chained predicate, as the != x information is more likely to be
2088 // helpful in practice.
2089 if (!CopyOfCR.contains(NewCR) && CopyOfCR.getSingleMissingElement())
2090 NewCR = std::move(CopyOfCR);
2091
2092 // The new range is based on a branch condition. That guarantees that
2093 // neither of the compare operands can be undef in the branch targets,
2094 // unless we have conditions that are always true/false (e.g. icmp ule
2095 // i32, %a, i32_max). For the latter overdefined/empty range will be
2096 // inferred, but the branch will get folded accordingly anyways.
2097 addAdditionalUser(OtherOp, I);
2098 mergeInValue(
2099 IV, I, ValueLatticeElement::getRange(NewCR, /*MayIncludeUndef*/ false));
2100 return;
2101 } else if (Pred == CmpInst::ICMP_EQ &&
2102 (CondVal.isConstant() || CondVal.isNotConstant())) {
2103 // For non-integer values or integer constant expressions, only
2104 // propagate equal constants or not-constants.
2105 addAdditionalUser(OtherOp, I);
2106 mergeInValue(IV, I, CondVal);
2107 return;
2108 } else if (Pred == CmpInst::ICMP_NE && CondVal.isConstant()) {
2109 // Propagate inequalities.
2110 addAdditionalUser(OtherOp, I);
2111 mergeInValue(IV, I, ValueLatticeElement::getNot(CondVal.getConstant()));
2112 return;
2113 }
2114
2115 return (void)mergeInValue(IV, I, CopyOfVal);
2116}
2117
2118void SCCPInstVisitor::handleCallResult(CallBase &CB) {
2120
2121 if (auto *II = dyn_cast<IntrinsicInst>(&CB)) {
2122 if (II->getIntrinsicID() == Intrinsic::vscale) {
2123 unsigned BitWidth = CB.getType()->getScalarSizeInBits();
2124 const ConstantRange Result = getVScaleRange(II->getFunction(), BitWidth);
2125 return (void)mergeInValue(ValueState[II], II,
2127 }
2128 if (II->getIntrinsicID() == Intrinsic::experimental_get_vector_length) {
2129 Value *CountArg = II->getArgOperand(0);
2130 Value *VF = II->getArgOperand(1);
2131 bool Scalable = cast<ConstantInt>(II->getArgOperand(2))->isOne();
2132
2133 // Computation happens in the larger type.
2134 unsigned BitWidth = std::max(CountArg->getType()->getScalarSizeInBits(),
2135 VF->getType()->getScalarSizeInBits());
2136
2137 ConstantRange Count = getValueState(CountArg)
2138 .asConstantRange(CountArg->getType(), false)
2139 .zeroExtend(BitWidth);
2140 ConstantRange MaxLanes = getValueState(VF)
2141 .asConstantRange(VF->getType(), false)
2142 .zeroExtend(BitWidth);
2143 if (Scalable)
2144 MaxLanes =
2145 MaxLanes.multiply(getVScaleRange(II->getFunction(), BitWidth));
2146
2147 // The result is always less than both Count and MaxLanes.
2148 ConstantRange Result = ConstantRange::getNonEmpty(
2150 APIntOps::umin(Count.getUnsignedMax(), MaxLanes.getUnsignedMax()) +
2151 1);
2152
2153 // If Count <= MaxLanes, getvectorlength(Count, MaxLanes) = Count
2154 if (Count.icmp(CmpInst::ICMP_ULE, MaxLanes))
2155 Result = std::move(Count);
2156
2157 Result = Result.truncate(II->getType()->getScalarSizeInBits());
2158 return (void)mergeInValue(ValueState[II], II,
2160 }
2161
2162 if (ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
2163 // Compute result range for intrinsics supported by ConstantRange.
2164 // Do this even if we don't know a range for all operands, as we may
2165 // still know something about the result range, e.g. of abs(x).
2167 for (Value *Op : II->args()) {
2168 const ValueLatticeElement &State = getValueState(Op);
2169 if (State.isUnknownOrUndef())
2170 return;
2171 OpRanges.push_back(
2172 State.asConstantRange(Op->getType(), /*UndefAllowed=*/false));
2173 }
2174
2175 ConstantRange Result =
2176 ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges);
2177 return (void)mergeInValue(ValueState[II], II,
2179 }
2180 }
2181
2182 // The common case is that we aren't tracking the callee, either because we
2183 // are not doing interprocedural analysis or the callee is indirect, or is
2184 // external. Handle these cases first.
2185 if (!F || F->isDeclaration())
2186 return handleCallOverdefined(CB);
2187
2188 // If this is a single/zero retval case, see if we're tracking the function.
2189 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
2190 if (!MRVFunctionsTracked.count(F))
2191 return handleCallOverdefined(CB); // Not tracking this callee.
2192
2193 // If we are tracking this callee, propagate the result of the function
2194 // into this call site.
2195 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2196 mergeInValue(getStructValueState(&CB, i), &CB,
2197 TrackedMultipleRetVals[std::make_pair(F, i)],
2199 } else {
2200 auto TFRVI = TrackedRetVals.find(F);
2201 if (TFRVI == TrackedRetVals.end())
2202 return handleCallOverdefined(CB); // Not tracking this callee.
2203
2204 // If so, propagate the return value of the callee into this call result.
2205 mergeInValue(ValueState[&CB], &CB, TFRVI->second, getMaxWidenStepsOpts());
2206 }
2207}
2208
2209bool SCCPInstVisitor::isInstFullyOverDefined(Instruction &Inst) {
2210 // For structure Type, we handle each member separately.
2211 // A structure object won't be considered as overdefined when
2212 // there is at least one member that is not overdefined.
2213 if (StructType *STy = dyn_cast<StructType>(Inst.getType())) {
2214 for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i) {
2215 if (!getStructValueState(&Inst, i).isOverdefined())
2216 return false;
2217 }
2218 return true;
2219 }
2220
2221 return getValueState(&Inst).isOverdefined();
2222}
2223
2225 // Process the work lists until they are empty!
2226 while (!BBWorkList.empty() || !InstWorkList.empty()) {
2227 // Process the instruction work list.
2228 while (!InstWorkList.empty()) {
2229 Instruction *I = InstWorkList.pop_back_val();
2230 Invalidated.erase(I);
2231
2232 LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
2233
2234 visit(I);
2235 }
2236
2237 // Process the basic block work list.
2238 while (!BBWorkList.empty()) {
2239 BasicBlock *BB = BBWorkList.pop_back_val();
2240 BBVisited.insert(BB);
2241
2242 LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
2243 for (Instruction &I : *BB) {
2244 CurI = &I;
2245 visit(I);
2246 }
2247 CurI = nullptr;
2248 }
2249 }
2250}
2251
2253 // Look for instructions which produce undef values.
2254 if (I.getType()->isVoidTy())
2255 return false;
2256
2257 if (auto *STy = dyn_cast<StructType>(I.getType())) {
2258 // Only a few things that can be structs matter for undef.
2259
2260 // Tracked calls must never be marked overdefined in resolvedUndefsIn.
2261 if (auto *CB = dyn_cast<CallBase>(&I))
2262 if (Function *F = CB->getCalledFunction())
2263 if (MRVFunctionsTracked.count(F))
2264 return false;
2265
2266 // extractvalue and insertvalue don't need to be marked; they are
2267 // tracked as precisely as their operands.
2269 return false;
2270 // Send the results of everything else to overdefined. We could be
2271 // more precise than this but it isn't worth bothering.
2272 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2273 ValueLatticeElement &LV = getStructValueState(&I, i);
2274 if (LV.isUnknown()) {
2275 markOverdefined(LV, &I);
2276 return true;
2277 }
2278 }
2279 return false;
2280 }
2281
2282 ValueLatticeElement &LV = getValueState(&I);
2283 if (!LV.isUnknown())
2284 return false;
2285
2286 // There are two reasons a call can have an undef result
2287 // 1. It could be tracked.
2288 // 2. It could be constant-foldable.
2289 // Because of the way we solve return values, tracked calls must
2290 // never be marked overdefined in resolvedUndefsIn.
2291 if (auto *CB = dyn_cast<CallBase>(&I))
2292 if (Function *F = CB->getCalledFunction())
2293 if (TrackedRetVals.count(F))
2294 return false;
2295
2296 if (isa<LoadInst>(I)) {
2297 // A load here means one of two things: a load of undef from a global,
2298 // a load from an unknown pointer. Either way, having it return undef
2299 // is okay.
2300 return false;
2301 }
2302
2303 markOverdefined(&I);
2304 return true;
2305}
2306
2307/// While solving the dataflow for a function, we don't compute a result for
2308/// operations with an undef operand, to allow undef to be lowered to a
2309/// constant later. For example, constant folding of "zext i8 undef to i16"
2310/// would result in "i16 0", and if undef is later lowered to "i8 1", then the
2311/// zext result would become "i16 1" and would result into an overdefined
2312/// lattice value once merged with the previous result. Not computing the
2313/// result of the zext (treating undef the same as unknown) allows us to handle
2314/// a later undef->constant lowering more optimally.
2315///
2316/// However, if the operand remains undef when the solver returns, we do need
2317/// to assign some result to the instruction (otherwise we would treat it as
2318/// unreachable). For simplicity, we mark any instructions that are still
2319/// unknown as overdefined.
2321 bool MadeChange = false;
2322 for (BasicBlock &BB : F) {
2323 if (!BBExecutable.count(&BB))
2324 continue;
2325
2326 for (Instruction &I : BB)
2327 MadeChange |= resolvedUndef(I);
2328 }
2329
2330 LLVM_DEBUG(if (MadeChange) dbgs()
2331 << "\nResolved undefs in " << F.getName() << '\n');
2332
2333 return MadeChange;
2334}
2335
2336//===----------------------------------------------------------------------===//
2337//
2338// SCCPSolver implementations
2339//
2341 const DataLayout &DL,
2342 std::function<const TargetLibraryInfo &(Function &)> GetTLI,
2343 LLVMContext &Ctx)
2344 : Visitor(new SCCPInstVisitor(DL, std::move(GetTLI), Ctx)) {}
2345
2346SCCPSolver::~SCCPSolver() = default;
2347
2349 AssumptionCache &AC) {
2350 Visitor->addPredicateInfo(F, DT, AC);
2351}
2352
2354 Visitor->removeSSACopies(F);
2355}
2356
2358 return Visitor->markBlockExecutable(BB);
2359}
2360
2362 return Visitor->getPredicateInfoFor(I);
2363}
2364
2366 Visitor->trackValueOfGlobalVariable(GV);
2367}
2368
2370 Visitor->addTrackedFunction(F);
2371}
2372
2374 Visitor->addToMustPreserveReturnsInFunctions(F);
2375}
2376
2378 return Visitor->mustPreserveReturn(F);
2379}
2380
2382 Visitor->addArgumentTrackedFunction(F);
2383}
2384
2386 return Visitor->isArgumentTrackedFunction(F);
2387}
2388
2391 return Visitor->getArgumentTrackedFunctions();
2392}
2393
2394void SCCPSolver::solve() { Visitor->solve(); }
2395
2397 return Visitor->resolvedUndefsIn(F);
2398}
2399
2401 Visitor->solveWhileResolvedUndefsIn(M);
2402}
2403
2404void
2406 Visitor->solveWhileResolvedUndefsIn(WorkList);
2407}
2408
2410 Visitor->solveWhileResolvedUndefs();
2411}
2412
2414 return Visitor->isBlockExecutable(BB);
2415}
2416
2418 return Visitor->isEdgeFeasible(From, To);
2419}
2420
2421std::vector<ValueLatticeElement>
2423 return Visitor->getStructLatticeValueFor(V);
2424}
2425
2427 return Visitor->removeLatticeValueFor(V);
2428}
2429
2431 Visitor->resetLatticeValueFor(Call);
2432}
2433
2435 return Visitor->getLatticeValueFor(V);
2436}
2437
2440 return Visitor->getTrackedRetVals();
2441}
2442
2445 return Visitor->getTrackedGlobals();
2446}
2447
2449 return Visitor->getMRVFunctionsTracked();
2450}
2451
2452void SCCPSolver::markOverdefined(Value *V) { Visitor->markOverdefined(V); }
2453
2455 Visitor->trackValueOfArgument(V);
2456}
2457
2459 return Visitor->isStructLatticeConstant(F, STy);
2460}
2461
2463 Type *Ty) const {
2464 return Visitor->getConstant(LV, Ty);
2465}
2466
2468 return Visitor->getConstantOrNull(V);
2469}
2470
2472 const SmallVectorImpl<ArgInfo> &Args) {
2473 Visitor->setLatticeValueForSpecializationArguments(F, Args);
2474}
2475
2477 Visitor->markFunctionUnreachable(F);
2478}
2479
2480void SCCPSolver::visit(Instruction *I) { Visitor->visit(I); }
2481
2482void SCCPSolver::visitCall(CallInst &I) { Visitor->visitCall(I); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:853
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts()
Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
static const unsigned MaxNumRangeExtensions
static ValueLatticeElement getValueFromMetadata(const Instruction *I)
std::pair< BasicBlock *, BasicBlock * > Edge
This file implements a set that has insertion order iteration characteristics.
static ConstantInt * getConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1662
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1157
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
A cache of @llvm.assume calls within a function.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI const ConstantRange & getRange() const
Returns the value of the range attribute.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:530
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.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
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 Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
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.
Function * getFunction() const
Definition Constants.h:1126
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
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 ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
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_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
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 ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI ConstantRange castOp(Instruction::CastOps CastOp, uint32_t BitWidth) const
Return a new range representing the possible values resulting from an application of the specified ca...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
static LLVM_ABI ConstantRange intrinsic(Intrinsic::ID IntrinsicID, ArrayRef< ConstantRange > Ops)
Compute range of intrinsic result for the given operand ranges.
LLVM_ABI bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
static LLVM_ABI bool isIntrinsicSupported(Intrinsic::ID IntrinsicID)
Returns true if ConstantRange calculations are supported for intrinsic with IntrinsicID.
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
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 ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
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 ConstantRange binaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other) const
Return a new range representing the possible values resulting from an application of the specified bi...
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static DebugLoc getTemporary()
Definition DebugLoc.h:150
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
This instruction extracts a struct member or array element value from an aggregate value.
unsigned getNumIndices() const
idx_iterator idx_begin() const
This class represents a freeze function that returns random concrete value if an operand is either a ...
Argument * arg_iterator
Definition Function.h:73
static GEPNoWrapFlags noUnsignedWrap()
void applyUpdatesPermissive(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Module * getParent()
Get the module that this global value is contained inside of...
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2848
This instruction inserts a struct field of array element value into an aggregate value.
Value * getInsertedValueOperand()
unsigned getNumIndices() const
idx_iterator idx_begin() const
Base class for instruction visitors.
Definition InstVisitor.h:78
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
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 BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
LLVM_ABI bool hasNonNeg() const LLVM_READONLY
Determine whether the the nneg flag is set.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
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.
bool isSpecialTerminator() const
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1069
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
LLVM_ABI std::optional< PredicateConstraint > getConstraint() const
Fetch condition in the form of PredicateConstraint, if possible.
Return a value (possibly void), from a function.
Helper class for SCCPSolver.
const MapVector< Function *, ValueLatticeElement > & getTrackedRetVals() const
const PredicateBase * getPredicateInfoFor(Instruction *I)
std::vector< ValueLatticeElement > getStructLatticeValueFor(Value *V) const
bool resolvedUndef(Instruction &I)
void markFunctionUnreachable(Function *F)
bool markBlockExecutable(BasicBlock *BB)
bool resolvedUndefsIn(Function &F)
While solving the dataflow for a function, we don't compute a result for operations with an undef ope...
Constant * getConstant(const ValueLatticeElement &LV, Type *Ty) const
SCCPInstVisitor(const DataLayout &DL, std::function< const TargetLibraryInfo &(Function &)> GetTLI, LLVMContext &Ctx)
const DenseMap< GlobalVariable *, ValueLatticeElement > & getTrackedGlobals() const
const ValueLatticeElement & getLatticeValueFor(Value *V) const
void removeLatticeValueFor(Value *V)
void trackValueOfArgument(Argument *A)
void visitCallInst(CallInst &I)
void markOverdefined(Value *V)
bool isArgumentTrackedFunction(Function *F)
void addTrackedFunction(Function *F)
void solveWhileResolvedUndefsIn(Module &M)
void trackValueOfGlobalVariable(GlobalVariable *GV)
Constant * getConstantOrNull(Value *V) const
void removeSSACopies(Function &F)
const SmallPtrSet< Function *, 16 > & getMRVFunctionsTracked() const
const SmallPtrSetImpl< Function * > & getArgumentTrackedFunctions() const
void resetLatticeValueFor(CallBase *Call)
Invalidate the Lattice Value of Call and its users after specializing the call.
ValueLatticeElement getArgAttributeVL(Argument *A)
void addPredicateInfo(Function &F, DominatorTree &DT, AssumptionCache &AC)
void addToMustPreserveReturnsInFunctions(Function *F)
void addArgumentTrackedFunction(Function *F)
bool isStructLatticeConstant(Function *F, StructType *STy)
void solveWhileResolvedUndefsIn(SmallVectorImpl< Function * > &WorkList)
bool isBlockExecutable(BasicBlock *BB) const
bool mustPreserveReturn(Function *F)
void setLatticeValueForSpecializationArguments(Function *F, const SmallVectorImpl< ArgInfo > &Args)
bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const
SCCPSolver - This interface class is a general purpose solver for Sparse Conditional Constant Propaga...
Definition SCCPSolver.h:66
LLVM_ABI void visitCall(CallInst &I)
LLVM_ABI ~SCCPSolver()
LLVM_ABI void resetLatticeValueFor(CallBase *Call)
Invalidate the Lattice Value of Call and its users after specializing the call.
LLVM_ABI void trackValueOfGlobalVariable(GlobalVariable *GV)
trackValueOfGlobalVariable - Clients can use this method to inform the SCCPSolver that it should trac...
LLVM_ABI bool tryToReplaceWithConstant(Value *V)
LLVM_ABI void inferArgAttributes() const
LLVM_ABI bool isStructLatticeConstant(Function *F, StructType *STy)
LLVM_ABI void addPredicateInfo(Function &F, DominatorTree &DT, AssumptionCache &AC)
LLVM_ABI void solve()
Solve - Solve for constants and executable blocks.
LLVM_ABI void visit(Instruction *I)
LLVM_ABI void trackValueOfArgument(Argument *V)
trackValueOfArgument - Mark the specified argument overdefined unless it have range attribute.
LLVM_ABI const DenseMap< GlobalVariable *, ValueLatticeElement > & getTrackedGlobals() const
getTrackedGlobals - Get and return the set of inferred initializers for global variables.
LLVM_ABI void addTrackedFunction(Function *F)
addTrackedFunction - If the SCCP solver is supposed to track calls into and out of the specified func...
LLVM_ABI void solveWhileResolvedUndefsIn(Module &M)
LLVM_ABI const PredicateBase * getPredicateInfoFor(Instruction *I)
LLVM_ABI const SmallPtrSetImpl< Function * > & getArgumentTrackedFunctions() const
LLVM_ABI const SmallPtrSet< Function *, 16 > & getMRVFunctionsTracked() const
getMRVFunctionsTracked - Get the set of functions which return multiple values tracked by the pass.
LLVM_ABI bool resolvedUndefsIn(Function &F)
resolvedUndefsIn - While solving the dataflow for a function, we assume that branches on undef values...
LLVM_ABI void addArgumentTrackedFunction(Function *F)
LLVM_ABI void solveWhileResolvedUndefs()
LLVM_ABI void removeLatticeValueFor(Value *V)
LLVM_ABI std::vector< ValueLatticeElement > getStructLatticeValueFor(Value *V) const
LLVM_ABI Constant * getConstantOrNull(Value *V) const
Return either a Constant or nullptr for a given Value.
LLVM_ABI bool simplifyInstsInBlock(BasicBlock &BB, SmallPtrSetImpl< Value * > &InsertedValues, Statistic &InstRemovedStat, Statistic &InstReplacedStat)
LLVM_ABI Constant * getConstant(const ValueLatticeElement &LV, Type *Ty) const
Helper to return a Constant if LV is either a constant or a constant range with a single element.
LLVM_ABI const ValueLatticeElement & getLatticeValueFor(Value *V) const
LLVM_ABI void addToMustPreserveReturnsInFunctions(Function *F)
Add function to the list of functions whose return cannot be modified.
LLVM_ABI bool removeNonFeasibleEdges(BasicBlock *BB, DomTreeUpdater &DTU, BasicBlock *&NewUnreachableBB) const
LLVM_ABI bool isBlockExecutable(BasicBlock *BB) const
LLVM_ABI void inferReturnAttributes() const
LLVM_ABI bool markBlockExecutable(BasicBlock *BB)
markBlockExecutable - This method can be used by clients to mark all of the blocks that are known to ...
LLVM_ABI void setLatticeValueForSpecializationArguments(Function *F, const SmallVectorImpl< ArgInfo > &Args)
Set the Lattice Value for the arguments of a specialization F.
static LLVM_ABI bool isConstant(const ValueLatticeElement &LV)
LLVM_ABI const MapVector< Function *, ValueLatticeElement > & getTrackedRetVals() const
getTrackedRetVals - Get the inferred return value map.
LLVM_ABI bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const
LLVM_ABI bool mustPreserveReturn(Function *F)
Returns true if the return of the given function cannot be modified.
static LLVM_ABI bool isOverdefined(const ValueLatticeElement &LV)
LLVM_ABI void markFunctionUnreachable(Function *F)
Mark all of the blocks in function F non-executable.
LLVM_ABI bool isArgumentTrackedFunction(Function *F)
Returns true if the given function is in the solver's set of argument-tracked functions.
LLVM_ABI SCCPSolver(const DataLayout &DL, std::function< const TargetLibraryInfo &(Function &)> GetTLI, LLVMContext &Ctx)
LLVM_ABI void markOverdefined(Value *V)
markOverdefined - Mark the specified value overdefined.
LLVM_ABI void removeSSACopies(Function &F)
This class represents the LLVM 'select' instruction.
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
Provides information about what library functions are available for the current target.
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:311
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:276
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
Value * getOperand(unsigned i) const
Definition User.h:207
This class represents lattice values for constants.
static ValueLatticeElement getRange(ConstantRange CR, bool MayIncludeUndef=false)
LLVM_ABI Constant * getCompare(CmpInst::Predicate Pred, Type *Ty, const ValueLatticeElement &Other, const DataLayout &DL) const
true, false or undef constants, or nullptr if the comparison cannot be evaluated.
bool isConstantRangeIncludingUndef() const
static ValueLatticeElement getNot(Constant *C)
ConstantRange asConstantRange(unsigned BW, bool UndefAllowed=false) const
void setNumRangeExtensions(unsigned N)
const ConstantRange & getConstantRange(bool UndefAllowed=true) const
Returns the constant range for this value.
bool isConstantRange(bool UndefAllowed=true) const
Returns true if this value is a constant range.
static ValueLatticeElement get(Constant *C)
unsigned getNumRangeExtensions() const
Constant * getNotConstant() const
LLVM_ABI ValueLatticeElement intersect(const ValueLatticeElement &Other) const
Combine two sets of facts about the same value into a single set of facts.
Constant * getConstant() const
bool mergeIn(const ValueLatticeElement &RHS, MergeOptions Opts=MergeOptions())
Updates this object to approximate both this object and RHS.
bool markConstant(Constant *V, bool MayIncludeUndef=false)
static ValueLatticeElement getOverdefined()
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI std::string getNameOrAsOperand() const
Definition Value.cpp:461
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
Represents an op.with.overflow intrinsic.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2287
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
static bool replaceSignedInst(SCCPSolver &Solver, SmallPtrSetImpl< Value * > &InsertedValues, Instruction &Inst)
Try to replace signed instructions with their unsigned equivalent.
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
static ConstantRange getRange(Value *Op, SCCPSolver &Solver, const SmallPtrSetImpl< Value * > &InsertedValues)
Helper for getting ranges from Solver.
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:633
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
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
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
NoopStatistic Statistic
Definition Statistic.h:162
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:422
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
static void propagateImplicitRefFromCall(CallBase *CB)
Helper for propagting !implicit.ref metadata from callee to caller before erasing a call instruction.
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
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
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ Sub
Subtraction of integers.
DWARFExpression::Operation Op
LLVM_ABI 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.
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:395
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
static bool refineInstruction(SCCPSolver &Solver, const SmallPtrSetImpl< Value * > &InsertedValues, Instruction &Inst)
Try to use Inst's value range from Solver to infer the NUW flag.
static void inferAttribute(Function *F, unsigned AttrIndex, const ValueLatticeElement &Val)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:860
Struct to control some aspects related to merging constant ranges.
MergeOptions & setMaxWidenSteps(unsigned Steps=1)